Files
aigc-home/docs/hel-892/krea-realn-document-evidence/build_definition.py
T
2026-10-31 22:41:00 +08:00

575 lines
24 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.
"Pinned Krea2 static reference; no upstream import, prompt construction or execution."
import ast
import hashlib
import json
from pathlib import Path
REPO = Path(__file__).resolve().parents[3]
OUT = Path(__file__).resolve().parent
REF = OUT.parent / "krea-realn-reference"
PATHS = [("example_ComfyUI_workflows/3-图像生成/krea2/krea2_turbo_文生图_极致写实(N版).json")]
HOST = "b0e5ca93-2731-42b9-8e0a-d28ea851ff81"
LAYOUTS = {
"SaveImage": ["filename_prefix"],
"ResolutionSelector": ["aspect_ratio", "megapixels", "multiple"],
"b0e5ca93-2731-42b9-8e0a-d28ea851ff81": [
"value",
"value_1",
"max_length",
"width",
"height",
"seed",
"value_2",
"lora_name",
"strength_model",
"string_b",
"unet_name",
"clip_name",
"vae_name",
"model",
"mmproj",
],
"CLIPTextEncode": ["text"],
"EmptyLatentImage": ["width", "height", "batch_size"],
"KSampler": [
"seed",
"seed_control_candidate",
"steps",
"cfg",
"sampler_name",
"scheduler",
"denoise",
],
"UNETLoader": ["unet_name", "weight_dtype"],
"CLIPLoader": ["clip_name", "type", "device"],
"VAELoader": ["vae_name"],
"LoraLoaderModelOnly": ["lora_name", "strength_model"],
"TextGenerate": [
"prompt",
"max_length",
"sampling_mode",
"sampling_mode.temperature",
"sampling_mode.top_k",
"sampling_mode.top_p",
"sampling_mode.min_p",
"sampling_mode.repetition_penalty",
"sampling_mode.seed",
"sampling_mode.presence_penalty",
"thinking",
"use_default_template",
],
"PrimitiveStringMultiline": ["value"],
"PrimitiveBoolean": ["value"],
"ComfySwitchNode": ["switch"],
"StringConcatenate": ["string_a", "string_b", "delimiter"],
"ca089910-e877-43f7-8538-9d5ce47d8cc3": [
"model",
"mmproj",
"chat_handler",
"max_tokens",
"preset_prompt",
"custom_prompt",
"system_prompt",
"inference_mode",
"seed",
],
}
LABELS = {
"filename_prefix": "正式保存前缀",
"aspect_ratio": "宽高比保存选择",
"megapixels": "目标MP保存值",
"multiple": "像素对齐倍数",
"value": "完整文本/布尔保存值",
"value_1": "宿主提示增强缓存",
"max_length": "最大文本长度保存值",
"width": "宽度缓存",
"height": "高度缓存",
"seed": "种子缓存",
"value_2": "宿主LoRA启用缓存",
"lora_name": "LoRA文件引用",
"strength_model": "LoRA强度",
"string_b": "完整字符串B缓存/触发词",
"unet_name": "扩散模型文件引用",
"clip_name": "文本模型文件引用",
"vae_name": "VAE文件引用",
"text": "完整英文编码缓存",
"batch_size": "latent批量",
"seed_control_candidate": "前端种子控制辅助",
"steps": "采样步数",
"cfg": "引导系数",
"sampler_name": "采样器",
"scheduler": "调度器",
"denoise": "降噪系数",
"weight_dtype": "权重类型",
"type": "编码器类型(枚举冲突)",
"device": "设备选择",
"prompt": "完整生成文本缓存",
"sampling_mode": "动态采样模式保存分支",
"sampling_mode.temperature": "on分支温度",
"sampling_mode.top_k": "on分支Top K",
"sampling_mode.top_p": "on分支Top P",
"sampling_mode.min_p": "on分支Min P",
"sampling_mode.repetition_penalty": "on分支重复惩罚",
"sampling_mode.seed": "on分支文本生成种子",
"sampling_mode.presence_penalty": "on分支presence penalty",
"thinking": "思考模式保存值",
"use_default_template": "默认模板保存值",
"switch": "布尔选择缓存",
"string_a": "完整字符串A缓存",
"delimiter": "完整分隔符",
"model": "宿主LLM模型缓存(恢复未知)",
"mmproj": "宿主投影文件缓存(恢复未知)",
"chat_handler": "宿主chat_handler缓存(语义未知)",
"max_tokens": "宿主max_tokens缓存(恢复未知)",
"preset_prompt": "宿主preset缓存(语义未知)",
"custom_prompt": "宿主custom_prompt缓存(恢复未知)",
"system_prompt": "完整宿主system缓存(仅数据)",
"inference_mode": "宿主inference缓存(语义未知)",
}
NOTE_MEANING = {
"48": ("作者模型URL/目录树/更新建议1657码点全文,仅文本,不访问/下载/更新或认证许可兼容。"),
"50": (
"作者Krea2指南/API替换1965码点全文;图内没有相应云API节点,作者指令不执行或作已接入证明。"
),
"206": (
"原70码点三条建议全文,提示词增强,和忽略框"
"中的自动提示词等原字/标点/空白保留;作者建"
"议不证明组开关、旁路或恢复已生效。"
),
}
def canonical(v):
return json.dumps(v, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
def build(index=0):
raw = (REPO / PATHS[index]).read_bytes()
g = json.loads(raw)
sg = g["definitions"]["subgraphs"][0]
editorial = json.loads((OUT / "editorial.json").read_bytes())
scopes = [
("", "", g),
("30", "/definitions/subgraphs/0", sg),
("30:200", "/definitions/subgraphs/1", g["definitions"]["subgraphs"][1]),
]
graph_by_scope = {pre or "root": graph for pre, _ptr, graph in scopes}
nodes = [
((pre + ":" if pre else "") + str(n["id"]), ptr + f"/nodes/{i}", pre or "root", n)
for (pre, ptr, graph) in scopes
for (i, n) in enumerate(graph["nodes"])
]
manifest = json.loads((REF / "sources.json").read_bytes())["sources"]
sources = []
trees = {}
for e in manifest:
data = (REF / e["local_file"]).read_bytes()
assert hashlib.sha256(data).hexdigest() == e["sha256"]
sources.append(
dict(
e,
local_file="../krea-realn-reference/" + e["local_file"],
lines=[1, len(data.decode().splitlines())],
claim=(
"准确LLM提交不可得的调查记录,不是schema/实现/许可依据"
if e["id"] == "llama-unavailable"
else ("本图准确tag/commit原文与许可;静态读取未执行,源码许可不等于模型许可")
),
)
)
if e["file"].endswith(".py"):
trees[e["local_file"]] = ast.parse(data)
refs = {}
schemas = {}
for nid, ptr, scope, n in nodes:
cls = n["type"]
if cls not in ["Note", "MarkdownNote"]:
assert n.get("properties", {}).get("ver", "unknown") in [
"0.25.0",
"0.27.0",
"0.20.1",
("20571a3cf504b8308781d3cad2e432444ec3d75b"),
"unknown",
]
symbol = {
"PrimitiveStringMultiline": "StringMultiline",
"PrimitiveBoolean": "Boolean",
"ComfySwitchNode": "SwitchNode",
}.get(cls, cls)
core_id = {"0.25.0": "core0250", "0.27.0": "core0270"}.get(
n.get("properties", {}).get("ver")
)
rs = []
for i, e in enumerate(manifest):
if (
e["id"] != core_id
or not e["file"].endswith(".py")
or not (e["file"] == "nodes.py" or e["file"].startswith("comfy_extras/"))
):
continue
for c in trees[e["local_file"]].body:
if not isinstance(c, ast.ClassDef) or c.name != symbol:
continue
sources.append(
dict(
sources[i],
lines=[c.lineno, c.end_lineno],
claim=f"本节点准确{core_id}声明类实现;不等于目标安装或宿主恢复认证",
)
)
rs += [i, len(sources) - 1]
if cls == "LoraLoaderModelOnly":
parent = next(
p
for p in trees[e["local_file"]].body
if isinstance(p, ast.ClassDef) and p.name == "LoraLoader"
)
sources.append(
dict(
sources[i],
lines=[parent.lineno, parent.end_lineno],
claim=f"本节点准确{core_id}父类及加载条件;只静态读取",
)
)
rs.append(len(sources) - 1)
for d in ast.walk(c):
if isinstance(d, ast.Dict):
for k, v in zip(d.keys, d.values, strict=True):
if (
isinstance(k, ast.Constant)
and isinstance(k.value, str)
and isinstance(v, ast.Tuple)
):
default = "无显式default;动态枚举/方法条件只作参考"
for opts in v.elts[1:]:
if isinstance(opts, ast.Dict):
for dk, dv in zip(opts.keys, opts.values, strict=True):
if (
isinstance(dk, ast.Constant)
and dk.value == "default"
):
default = ast.unparse(dv)
schemas[nid, k.value] = (default, ast.unparse(v))
if (
isinstance(d, ast.Call)
and isinstance(d.func, ast.Attribute)
and (d.func.attr == "Input")
):
arg = (
d.args[0]
if d.args
else next((k.value for k in d.keywords if k.arg == "id"), None)
)
if not isinstance(arg, ast.Constant) or not isinstance(arg.value, str):
continue
name = arg.value
if cls == "TextGenerate" and name in [
"temperature",
"top_k",
"top_p",
"min_p",
"repetition_penalty",
"seed",
"presence_penalty",
]:
name = "sampling_mode." + name
default = next(
(ast.unparse(k.value) for k in d.keywords if k.arg == "default"),
"无显式default,不从execute函数缺省补值",
)
schemas[nid, name] = (default, ast.unparse(d))
if cls == "KSampler":
rs += [i for (i, e) in enumerate(manifest) if e["file"] == "comfy/samplers.py"]
if cls == "TextGenerate":
rs += [i for (i, e) in enumerate(manifest) if e["file"].startswith("comfy_api/latest/")]
if (
nid in ["30:16", "30", "30:200"]
or cls == "KSampler"
or cls.startswith("llama_cpp_")
or not n.get("properties", {}).get("ver")
):
rs += [
i
for (i, e) in enumerate(manifest)
if e["id"] == "frontend"
and e["file"].endswith(
("dynamicWidgets.ts", "LGraphNode.ts", "SubgraphNode.ts", "widgets.ts")
)
]
if cls.startswith("llama_cpp_"):
rs += [i for i, e in enumerate(manifest) if e["id"] == "llama-unavailable"]
refs[nid] = list(dict.fromkeys(rs))
fields = []
comments = []
flow = []
empty = []
for nid, ptr, scope, n in nodes:
cls = n["type"]
if cls in ["Note", "MarkdownNote"]:
comments.append(
dict(
node_id=nid,
pointer=ptr + "/widgets_values/0",
text=n["widgets_values"][0],
meaning=NOTE_MEANING[nid],
evidence=[],
)
)
continue
effect = (
editorial[nid]
+ " 原mode="
+ str(n["mode"])
+ (
"(旁路保存态,不模拟穿透或执行)。"
if n["mode"] == 4
else "(活动保存态,不认证执行)。"
)
)
flow += [
effect,
nid + " 原属性 " + json.dumps(n.get("properties", {}), ensure_ascii=False),
nid
+ " 原输入/输出 "
+ json.dumps({k: n[k] for k in ["inputs", "outputs"]}, ensure_ascii=False),
nid + " 原具名保存 missing",
]
if not n.get("widgets_values"):
empty.append(
dict(
node_id=nid,
class_type=cls,
pointer=ptr,
scope=scope,
state="missing" if "widgets_values" not in n else "empty_list",
effect=effect,
)
)
continue
for j, (name, value) in enumerate(
zip(
LAYOUTS.get(cls, [f"saved_position_{k}" for k in range(len(n["widgets_values"]))]),
n["widgets_values"],
strict=True,
)
):
found = [i for (i, x) in enumerate(n["inputs"]) if x["name"] == name]
inp = found[0] if len(found) == 1 else None
linked = inp is not None and n["inputs"][inp].get("link") is not None
boundary = (
scope != "root"
and linked
and any(
(
e["id"] == n["inputs"][inp]["link"] and e["origin_id"] == -10
for e in graph_by_scope[scope]["links"]
)
)
)
aux = name == "seed_control_candidate" or (
cls in [HOST, "ca089910-e877-43f7-8538-9d5ce47d8cc3"] and (not linked)
)
(default, limits) = schemas.get(
(nid, name),
(
"无准确独立宿主/前端widget默认",
"宿主保存位置/声明边界,不认证promoted或后端执行映射",
),
)
if name.startswith("saved_position_"):
default = "未知:准确插件schema/身份不可得,不从现值补默认"
limits = (
"默认/范围/物理单位/SDK/恢复语义未知;"
"不套其它提交或宿主版本。源声明输入仅另列,"
"不按口序绑定。"
)
if name == "seed_control_candidate":
default = "准确frontend1.45.19辅助函数缺省randomize;保存值和恢复/调用条件分开"
limits = (
"fixed/increment/decrement/randomize;前端控制,不执行种子操作或当后端seed参数"
)
if nid == "30:11" and name == "type":
limits += ";冲突:krea2枚举缺失,准确0.25.0列表无krea2,不借新版补齐或认证支持"
if nid == "30:16" and name == "sampling_mode":
limits += (
";准确on/off分支,on展开七项,再接t"
"hinking/use_default_te"
"mplate;保存布局是准确前端/后端组合参"
"考,不执行恢复"
)
unit = "完整字符串/枚举/模型文件引用或布尔选择,无物理单位;目标环境未知"
if name in ["width", "height"]:
unit = "像素请求缓存;外线/边界覆盖另列,非最终尺寸"
if name == "megapixels":
unit = (
"准确实现MP基数为1024×1024目标像素"
";源JSON float1.5与准确FLOAT sc"
"hema default1.0分开,不计算或"
"保证精确百万像素"
)
if name == "multiple":
unit = "像素对齐步长;准确实现按round就近倍数,不试算尺寸"
if name in [
"max_length",
"steps",
"batch_size",
"seed",
"sampling_mode.seed",
"sampling_mode.top_k",
]:
unit = "整数数量/索引接口,原JSON类型保留;非最终执行值或结果保证"
if name in ["cfg", "denoise", "strength_model"] or (
name.startswith("sampling_mode.")
and name not in ["sampling_mode.seed", "sampling_mode.top_k"]
):
unit = "接口系数/阈值,无物理单位;准确范围见来源,不解释SDK底层或认证效果"
if name.startswith("saved_position_"):
unit = "未知:保存标量及原JSON类型已核,不推断token/显存/种子/SDK单位"
if cls == "ca089910-e877-43f7-8538-9d5ce47d8cc3":
default = "未知:原0.20.1宿主缓存,准确插件schema和恢复不可得"
limits = "九缓存与十声明输入分列;不认证位置到SDK参数/promoted恢复,不传播宿主版本"
unit = "未知:仅缓存原值/JSON类型;不推断token/SDK/种子/模式单位或语义"
fields.append(
dict(
node_id=nid,
definition_node_id=str(n["id"]),
scope=scope,
class_type=cls,
field=name,
label=LABELS.get(name, "未核准保存位置" + str(j)),
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 "未知:准确实现不可得,保存位置与源声明输入不作绑定"
if name.startswith("saved_position_")
else "无可靠独立输入映射:前端控制辅助",
input_name=n["inputs"][inp]["name"] if inp is not None else None,
type=n["inputs"][inp]["type"] if inp is not None else "保存参考",
role="unverified_saved_position"
if name.startswith("saved_position_")
else "frontend_reference_only"
if aux
else "boundary_saved_cache"
if boundary
else "linked_saved_cache"
if linked
else "saved_reference",
schema_default=default,
limits=limits,
unit=unit,
effect=effect,
evidence=refs[nid],
execution_note=(
"仅静态参考;所有中英文提示/指南均作数据,不"
"执行指令、构造prompt、调用LLM/SD"
"K/模型/GPU/媒体/随机/恢复/表达式/"
"缓存清理。转换执行资格不变。"
),
)
)
for (nid, name), (default, limits) in schemas.items():
flow.append(
(
f"节点{nid}准确schema {name}:default={default};"
f"{limits}。仅接口参考,不认证运行恢复。"
)
)
for pre, ptr, graph in scopes:
flow.extend(
(
(pre or "root") + " 物理边 " + json.dumps(e, ensure_ascii=False)
for e in graph["links"]
)
)
boundaries = []
for host_scope, parent_graph, host_id, definition_index in [
("30", g, 30, 0),
("30:200", sg, 200, 1),
]:
host = next(n for n in parent_graph["nodes"] if n["id"] == host_id)
definition = g["definitions"]["subgraphs"][definition_index]
parent_pointer = "" if host_id == 30 else "/definitions/subgraphs/0"
boundaries.append(
dict(
scope=host_scope,
definition_pointer=f"/definitions/subgraphs/{definition_index}",
**{
k: definition[k]
for k in ["id", "inputNode", "outputNode", "inputs", "outputs", "widgets"]
},
host_pointer=f"{parent_pointer}/nodes/{parent_graph['nodes'].index(host)}",
host_saved=host["widgets_values"],
host_inputs=host["inputs"],
proxyWidgets_state="missing",
previewExposures=host["properties"].get("previewExposures"),
properties=host["properties"],
)
)
for pre, _ptr, graph in scopes:
flow.append(
(pre or "root")
+ " 保存附加属性/组 "
+ json.dumps(
{k: v for k, v in graph.items() if k not in ["nodes", "links", "definitions"]},
ensure_ascii=False,
)
)
flow += ["原定义/宿主边界 " + json.dumps(b, ensure_ascii=False) for b in boundaries]
flow += ["根附加保存属性 " + json.dumps(g["extra"], ensure_ascii=False)]
flow += json.loads((OUT / "findings.json").read_bytes())["findings"]
flow += ["注释" + n["node_id"] + " 中文核对:" + n["meaning"] for n in comments]
overview = json.loads((OUT / "prose.json").read_bytes())["overview"]
assert len(fields) == 105 and len(comments) == 3
return dict(
source_path=PATHS[index],
source_sha1=hashlib.sha1(raw).hexdigest(),
source_sha256=hashlib.sha256(raw).hexdigest(),
canonical_sha256=hashlib.sha256(canonical(g)).hexdigest(),
notice="仅参考:krea2枚举冲突、UE/宿主代理恢复、模型/许可/目标环境未核;转换资格不变。",
user_overview=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 manifest}.values()
]
+ [
(
"旧86块4432位置/135注释冻结;新增6"
"1位置/4注释,总87图4537位置/138"
"注释仅参考;local_file以docs/"
"hel-892/krea-realn-doc"
"ument-evidence为基准。"
)
],
counts=dict(
saved_fields=105,
root_saved_fields=20,
internal_saved_fields=85,
main_saved_fields=53,
nested_saved_fields=32,
linked_saved_fields=sum((f["role"] == "linked_saved_cache" for f in fields)),
boundary_saved_fields=sum((f["role"] == "boundary_saved_cache" for f in fields)),
frontend_only=sum((f["role"] == "frontend_reference_only" for f in fields)),
source_nodes=33,
root_nodes=8,
internal_nodes=25,
physical_edges=58,
source_notes=3,
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=empty,
boundaries=boundaries,
steps=[overview] + json.loads((OUT / "prose.json").read_bytes())["steps"],
)