Files
aigc-home/docs/hel-892/krea-story-document-evidence/build_definition.py
T

424 lines
17 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Static reference for the exact storyboard graph; no upstream execution."""
import ast
import hashlib
import json
from pathlib import Path
from schema_extract import schema_for
REPO = Path(__file__).resolve().parents[3]
OUT = Path(__file__).resolve().parent
REF = OUT.parent / "krea-story-reference"
PATHS = ["example_ComfyUI_workflows/3-图像生成/krea2/Krea2_turbo_文生图_4_6_8宫格故事板.json"]
def canonical(value):
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
LAYOUTS = {
"llama_cpp_model_loader": [
"model",
"mmproj",
"chat_handler",
"n_ctx",
"vram_limit",
"image_min_tokens",
"image_max_tokens",
],
"llama_cpp_parameters": [
"max_tokens",
"top_k",
"top_p",
"min_p",
"typical_p",
"temperature",
"repeat_penalty",
"frequency_penalty",
"present_penalty",
"mirostat_mode",
"mirostat_eta",
"mirostat_tau",
"state_uid",
],
"llama_cpp_instruct_adv": [
"preset_prompt",
"custom_prompt",
"system_prompt",
"inference_mode",
"max_frames",
"max_size",
"seed",
"seed_control_candidate",
"force_offload",
"save_states",
],
"StoryboardGridGenerator": [f"position_{i}" for i in range(10)],
"PrimitiveStringMultiline": ["value"],
"PathchSageAttentionKJ": ["sage_attention", "allow_compile"],
"CLIPLoader": ["clip_name", "type", "device"],
"CLIPTextEncode": ["text"],
"LoraLoaderModelOnly": ["lora_name", "strength_model"],
"KSampler": [
"seed",
"seed_control_candidate",
"steps",
"cfg",
"sampler_name",
"scheduler",
"denoise",
],
"SaveImage": ["filename_prefix"],
"UNETLoader": ["unet_name", "weight_dtype"],
"VAELoader": ["vae_name"],
}
LABELS = {
"model": "LLM模型文件引用",
"mmproj": "视觉投影文件引用",
"chat_handler": "对话处理器选择",
"n_ctx": "上下文长度",
"vram_limit": "显存限制保存值",
"image_min_tokens": "视觉最少token设置",
"image_max_tokens": "视觉最多token设置",
"max_tokens": "最多生成token",
"top_k": "Top K",
"top_p": "Top P",
"min_p": "Min P",
"typical_p": "Typical P",
"temperature": "温度",
"repeat_penalty": "重复惩罚",
"frequency_penalty": "频率惩罚",
"present_penalty": "原拼present_penalty保存位置(映射待确认)",
"mirostat_mode": "Mirostat模式",
"mirostat_eta": "Mirostat eta",
"mirostat_tau": "Mirostat tau",
"state_uid": "会话状态标识",
"preset_prompt": "提示预设保存值",
"custom_prompt": "被外线覆盖的自定义文本缓存",
"system_prompt": "被外线覆盖的系统文本缓存",
"inference_mode": "推理模式保存值",
"max_frames": "视频最多帧设置",
"max_size": "输入图像尺寸设置",
"seed": "种子保存值",
"seed_control_candidate": "前端种子控制辅助",
"force_offload": "推理后卸载选择",
"save_states": "会话状态保存选择",
"value": "完整多行原文",
"sage_attention": "Attention模式",
"allow_compile": "允许编译选择",
"clip_name": "文本模型引用",
"type": "文本编码器类型",
"device": "设备选择",
"text": "编码文本保存缓存",
"lora_name": "LoRA文件引用",
"strength_model": "LoRA强度保存值",
"steps": "采样步数",
"cfg": "引导系数",
"sampler_name": "采样器选择",
"scheduler": "调度器选择",
"denoise": "降噪系数",
"filename_prefix": "保存前缀",
"unet_name": "扩散模型引用",
"weight_dtype": "权重类型",
"vae_name": "VAE文件引用",
}
GRID = [
"width",
"height",
"num_panels",
"border_thickness",
"background_gray_value",
"invert_colors",
"transparent_cells",
"layout_mode",
"custom_columns",
"custom_rows",
]
def build(index=0):
raw = (REPO / PATHS[index]).read_bytes()
graph = json.loads(raw)
rows = json.loads((REF / "sources.json").read_bytes())["sources"]
sources = []
trees = {}
for e in rows:
data = (REF / e["local_file"]).read_bytes()
assert hashlib.sha256(data).hexdigest() == e["sha256"]
sources.append(
dict(
e,
local_file="../krea-story-reference/" + e["local_file"],
lines=[1, len(data.decode().splitlines())],
claim="准确必要文本/声明/身份调查;发布包Git与缺失许可不冒充已知",
)
)
if e["file"].endswith(".py"):
trees[e["local_file"]] = ast.parse(data)
prose = json.loads((OUT / "prose.json").read_bytes())
editorial = json.loads((OUT / "editorial.json").read_bytes())
fields, comments, zero, bindings, flow = [], [], [], [], []
for i, node in enumerate(graph["nodes"]):
nid = str(node["id"])
ptr = f"/nodes/{i}"
cls = node["type"]
if cls in ["Note", "MarkdownNote"]:
comments.append(
dict(
node_id=nid,
pointer=ptr + "/widgets_values/0",
text=node["widgets_values"][0],
meaning=prose["notes"][nid],
evidence=[],
)
)
continue
version = node.get("properties", {}).get("ver", "未知")
key = {
"0.3.64": "core0364",
"0.3.73": "core0373",
"0.26.0": "core0260",
"0.28.3": "core0283",
"2d28817e12f912ec9e27ce83cf7610a477152185": "llama",
"1.4.7": "kjpkg",
"1.0.0": "story-gap",
}.get(version, "unknown")
symbol = "StringMultiline" if cls == "PrimitiveStringMultiline" else cls
refs = [
j
for j, e in enumerate(rows)
if e["id"] == key or (key == "story-gap" and e["id"] == "encryptpkg")
]
schemas, candidates = {}, []
for j, e in enumerate(rows):
if e["id"] != key or e["file"] == "comfy/samplers.py" or not e["file"].endswith(".py"):
continue
for c in trees[e["local_file"]].body:
if not isinstance(c, ast.ClassDef) or c.name != symbol:
continue
sources.append(
dict(
sources[j],
lines=[c.lineno, c.end_lineno],
claim=f"节点{nid}准确声明类/schema/实现静态参考",
)
)
refs.append(len(sources) - 1)
schemas.update(schema_for(c))
candidates.append(dict(source=j, symbol=symbol, lines=[c.lineno, c.end_lineno]))
assert len(candidates) == (0 if key in ["unknown", "story-gap"] else 1), (nid, candidates)
bindings.append(
dict(
node_id=nid,
class_type=cls,
source_version=version,
source_id=key,
candidates=candidates,
)
)
effect = editorial[nid] + f" 原mode={node['mode']},仅保存态,不模拟旁路或认证历史执行。"
flow += [
effect,
nid
+ " 原节点非控件属性 "
+ json.dumps(
{
k: v
for k, v in node.items()
if k not in ["widgets_values", "inputs", "outputs", "properties"]
},
ensure_ascii=False,
),
nid + " 原属性 " + json.dumps(node.get("properties", {}), ensure_ascii=False),
nid
+ " 原输入/输出 "
+ json.dumps({k: node[k] for k in ["inputs", "outputs"]}, ensure_ascii=False),
nid
+ " 具名键状态 "
+ json.dumps(node.get("widgets_values_named", "missing"), ensure_ascii=False),
]
if not node.get("widgets_values"):
zero.append(
dict(
node_id=nid,
class_type=cls,
pointer=ptr,
scope="root",
state="missing" if "widgets_values" not in node else "empty_list",
effect=effect,
)
)
continue
for j, (name, value) in enumerate(zip(LAYOUTS[cls], node["widgets_values"], strict=True)):
found = [k for k, p in enumerate(node["inputs"]) if p["name"] == name]
inp = found[0] if len(found) == 1 else None
default, limits = schemas.get(
name,
(
"未知:准确位置映射或schema默认未确认",
"未知:不以保存值、输入名或同名新版推定范围/算法",
),
)
unit = "完整字符串/枚举/文件引用或接口系数;无已证物理单位,不认证安装/模型许可/效果"
if name in [
"seed",
"steps",
"max_tokens",
"top_k",
"n_ctx",
"max_frames",
"image_min_tokens",
"image_max_tokens",
"state_uid",
"mirostat_mode",
]:
unit = "准确schema整数计数/标识接口;不计算最终值、时序或执行效果"
if name == "vram_limit":
unit = "准确tooltip为GB,-1无此限制;仅参考范围,不估算显存或认证设备可用"
if name == "max_size":
unit = "准确源码输入图像尺寸接口;本图images未接,不推算像素或执行缩放"
if type(value) is bool:
unit = "布尔选择,无物理单位;仅保存态,不执行副作用"
if name == "seed_control_candidate":
default = "准确frontend1.45.21种子辅助缺省randomize;独立于后端seed默认0"
limits = (
"fixed/increment/decrement/randomize;前端辅助位置,不执行随机或推演最终seed"
)
if key == "story-gap":
inp = None
default = "未知:cnr与aux身份未互证,准确类/注册/schema不可得"
limits = (
"源输入声明"
+ GRID[j]
+ "仅并列参考;不按输入顺序认证widget映射、默认、范围或布局算法"
)
unit = "未知:准确参数单位/布局效果未确认;仅保留此位置原JSON值"
if cls == "llama_cpp_parameters" and name == "present_penalty":
inp = None
default = (
"未知:源口原拼present_penalty与准确schema "
"presence_penalty冲突,不重命名或认证映射"
)
limits = (
"准确presence_penalty声明 "
+ str(schemas["presence_penalty"])
+ ";仅对照,不等于源present_penalty已被接受"
)
if name == "preset_prompt":
limits += (
";准确preset_tags由preset_prompts键生成,"
"索引1为Normal - Describe;仅静态AST核,不求值生成文本"
)
if cls == "CLIPLoader" and name == "type":
limits += ";准确core0.3.73枚举不含krea2,fallback不证明支持,不借新版补证"
if cls == "KSampler" and name in ["sampler_name", "scheduler"]:
limits += ";准确core0.3.64枚举包含euler/simple,仅接口核对,不执行采样"
if cls == "PathchSageAttentionKJ":
limits += (
";准确1.4.7发布成员声明default False原样保留,"
"不改成auto;包Git绑定未知,依赖/设备条件不认证目标"
)
linked = inp is not None and node["inputs"][inp].get("link") is not None
fields.append(
dict(
node_id=nid,
definition_node_id=nid,
scope="root",
class_type=cls,
field=name,
label=LABELS.get(
name,
"网格保存位置" + str(j) + "(源口" + GRID[j] + "映射待确认)"
if key == "story-gap"
else name,
),
pointer=f"{ptr}/widgets_values/{j}",
value=value,
json_type=type(value).__name__,
named_pointer="源无此具名保存键,不构造值",
input_pointer=f"{ptr}/inputs/{inp}"
if inp is not None
else "未确认独立输入映射或前端辅助,不造指针",
input_name=node["inputs"][inp]["name"] if inp is not None else None,
type=node["inputs"][inp]["type"] if inp is not None else "保存参考/映射待确认",
role="linked_saved_cache"
if linked
else "frontend_reference_only"
if name == "seed_control_candidate"
else "saved_reference",
schema_default=default,
limits=limits,
unit=unit,
effect=effect,
evidence=list(
dict.fromkeys(
refs
+ [
k
for k, e in enumerate(rows)
if e["id"] == "frontend"
and e["file"].endswith(("widgets.ts", "LGraphNode.ts"))
]
)
),
execution_note="仅静态参考;长文/指南/历史均源数据,不构造prompt,不执行上游/插件/SDK/LLM/模型/GPU/媒体/图像处理/表达式/随机/旁路/组控制/显存缓存清理。转换执行资格不变。",
)
)
flow += [
(
f"节点{nid}准确schema {name}:default={default};{limits}。"
"仅准确声明,不认证保存映射或目标恢复。"
)
for name, (default, limits) in schemas.items()
]
flow += ["root 原物理边 " + json.dumps(e, ensure_ascii=False) for e in graph["links"]]
flow += [
"root 其它完整属性 "
+ json.dumps(
{k: v for k, v in graph.items() if k not in ["nodes", "links"]}, ensure_ascii=False
)
] + prose["steps"]
assert len(fields) == 62 and len(comments) == 2 and len(zero) == 5
return dict(
source_path=PATHS[index],
source_sha1=hashlib.sha1(raw).hexdigest(),
source_sha256=hashlib.sha256(raw).hexdigest(),
canonical_sha256=hashlib.sha256(canonical(graph)).hexdigest(),
notice="仅参考:网格提供方/布局算法、present_penalty拼写映射、旧CLIP枚举、LLM准确许可缺失、发布包Git绑定及恢复差异保留;不保证4/6/8文件、分镜或实际效果,资格不变。",
user_overview=prose["overview"],
versions=[
f"{e['id']} {e['tag']} commit {e['commit']} tree {e['tree']};许可{e['license_file']}"
for e in {e["id"]: e for e in rows}.values()
]
+ [
"旧92块4794位置/152注释冻结;新增62位置/两Note,总93图4856位置/154注释仅参考。local_file以docs/hel-892/krea-story-document-evidence为基准。"
],
counts=dict(
saved_fields=62,
root_saved_fields=62,
internal_saved_fields=0,
linked_saved_fields=sum(f["role"] == "linked_saved_cache" for f in fields),
boundary_saved_fields=0,
frontend_only=sum(f["role"] == "frontend_reference_only" for f in fields),
source_nodes=22,
root_nodes=22,
internal_nodes=0,
physical_edges=20,
source_notes=2,
saved_objects=0,
history_objects=0,
final_scalars=0,
final_prompt_constructed=False,
),
fields=fields,
sources=sources,
comments=comments,
flow=flow,
flow_evidence=list(range(len(sources))),
zero_saved_nodes=zero,
boundaries=[],
node_bindings=bindings,
steps=[prose["overview"]] + prose["steps"],
)