Files
aigc-home/docs/hel-892/krea-anything-document-evidence/build_definition.py
T
2026-10-31 23:38:38 +08:00

458 lines
19 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 static reference; never execute upstream."""
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-anything-reference"
PATHS = [
(
"example_ComfyUI_workflows/3-图像生成"
+ "/krea2/krea2-Edit-Anything2Real_"
+ "动漫转真人v3.json"
)
]
LAYOUTS = {
"CLIPLoader": ["clip_name", "type", "device"],
"KSampler": [
"seed",
"control_after_generate",
"steps",
"cfg",
"sampler_name",
"scheduler",
"denoise",
],
"FluxKontextMultiReferenceLatentMethod": ["reference_latents_method"],
"TextEncodeKrea2OstrisEdit": ["prompt"],
"LayerUtility: ImageScaleByAspectRatio V2": [
"aspect_ratio",
"proportional_width",
"proportional_height",
"fit",
"method",
"round_to_multiple",
"scale_to_side",
"scale_to_length",
"background_color",
],
"Krea2OstrisEditModelPatch": ["kv_cache"],
"VAELoader": ["vae_name"],
"LoadImage": ["image", "upload"],
"SaveImage": ["filename_prefix"],
"Image Comparer (rgthree)": ["comparison_history"],
"UNETLoader": ["unet_name", "weight_dtype"],
"LoraLoaderModelOnly": ["lora_name", "strength_model"],
}
LABELS = dict(
clip_name="文本模型文件引用",
type="文本编码器类型",
device="设备选择",
seed="采样种子保存值",
control_after_generate="前端种子控制辅助",
steps="采样步数",
cfg="引导系数",
sampler_name="采样器选择",
scheduler="调度器原拼保存值",
denoise="降噪系数",
reference_latents_method="参考latent方法",
prompt="完整编辑意图保存值",
aspect_ratio="比例保存值(实现未知)",
proportional_width="比例宽保存值",
proportional_height="比例高保存值",
fit="适配保存值(实现未知)",
method="方法保存值(实现未知)",
round_to_multiple="对齐保存字符串",
scale_to_side="尺度侧保存值",
scale_to_length="尺度长度保存值",
background_color="背景颜色保存文本",
kv_cache="参考KV缓存开关保存值",
vae_name="VAE文件引用",
image="输入图片文件名",
upload="前端上传状态",
filename_prefix="正式保存文件名前缀",
comparison_history="完整比较历史列表(仅文本)",
unet_name="扩散模型文件引用",
weight_dtype="权重类型",
lora_name="Anything2Real v3 LoRA引用",
strength_model="LoRA模型强度",
)
def canonical(value):
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
def schema_for(node):
("Extract declarations a" + "s text without evaluat" + "ing any upstream expre" + "ssion.")
result = {}
for d in ast.walk(node):
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;不从源现值或声明输入推补schema默认"
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)
result[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 isinstance(arg, ast.Constant) and isinstance(arg.value, str):
default = next(
(ast.unparse(k.value) for k in d.keywords if k.arg == "default"),
"无显式default;枚举条件独立,不以现值认证默认",
)
result[arg.value] = (default, ast.unparse(d))
return result
def build(index=0):
raw = (REPO / PATHS[index]).read_bytes()
g = json.loads(raw)
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-anything-reference/" + e["local_file"],
lines=[1, len(data.decode().splitlines())],
claim=(
"本图准确frontend锁定LiteGraph发布成员;本轮仅重算成员SHA,Git身份未知,不重算整包"
if e["id"] == "litegraph"
else "本图准确声明Git文本与许可;静态读取未执行,不认证目标安装/模型许可"
),
)
)
if e["file"].endswith(".py"):
trees[e["local_file"]] = ast.parse(data)
editorial = json.loads((OUT / "editorial.json").read_bytes())
prose = json.loads((OUT / "prose.json").read_bytes())
fields, comments, empty, flow, bindings = [], [], [], [], []
for i, n in enumerate(g["nodes"]):
nid, cls, ptr = str(n["id"]), n["type"], f"/nodes/{i}"
if cls == "Note":
comments.append(
dict(
node_id=nid,
pointer=ptr + "/widgets_values/0",
text=n["widgets_values"][0],
meaning=prose["notes"][nid],
evidence=[],
)
)
continue
version = n["properties"].get("ver", "未知:原图未声明提供方/版本")
key = {
"0.25.0": "core0250",
"0.28.3": "core0283",
"0.5.1": "core051",
"7756566160c4a1b24bb1bd9f0ff3ced1a83d7547": "kreaostris",
"6b76ee6f2c5a007710b5a16f97c94330d6ecc871": "rgthree",
}.get(version, "unknown")
symbol = "RgthreeImageComparer" if cls == "Image Comparer (rgthree)" else cls
refs, schemas, candidates = [], {}, []
for j, e in enumerate(manifest):
if e["id"] != key or not e["file"].endswith(".py") or e["file"] == "comfy/samplers.py":
continue
tree = trees[e["local_file"]]
for c in tree.body:
if not isinstance(c, ast.ClassDef) or c.name != symbol:
continue
candidates.append(dict(source=j, symbol=symbol, lines=[c.lineno, c.end_lineno]))
sources.append(
dict(
sources[j],
lines=[c.lineno, c.end_lineno],
claim=f"节点{nid}准确{version}注册类/schema/实现静态参考",
)
)
refs.extend([j, len(sources) - 1])
schemas.update(schema_for(c))
if cls == "LoraLoaderModelOnly":
parent = next(
c
for c in tree.body
if isinstance(c, ast.ClassDef) and c.name == "LoraLoader"
)
sources.append(
dict(
sources[j],
lines=[parent.lineno, parent.end_lineno],
claim="准确父类的模型LoRA加载条件;不执行",
)
)
refs.append(len(sources) - 1)
assert len(candidates) == (0 if key == "unknown" else 1), (nid, candidates)
bindings.append(
dict(node_id=nid, class_type=cls, version=version, source_id=key, candidates=candidates)
)
refs += [
j
for j, e in enumerate(manifest)
if e["id"] == key
and e["file"] in ("__init__.py", "py/constants.py", "web/comfyui/constants.js")
]
if cls == "KSampler":
refs += [
j
for j, e in enumerate(manifest)
if e["id"] == key and e["file"] == "comfy/samplers.py"
]
if cls in ("KSampler", "LoadImage", "Image Comparer (rgthree)"):
refs += [
j
for j, e in enumerate(manifest)
if e["id"] == "frontend"
and e["file"].endswith(
(
"widgets.ts",
"LGraphNode.ts",
"useImageUploadWidget.ts",
"useNodeImageUpload.ts",
)
)
]
if cls in ("KSampler", "LoadImage", "Image Comparer (rgthree)"):
refs += [j for j, e in enumerate(manifest) if e["id"] == "litegraph"]
if key == "rgthree":
refs += [
j
for j, e in enumerate(manifest)
if e["id"] == key and "image_comparer" in e["file"]
]
# Inherited SaveImage/PreviewImage UI behavior has its own core binding.
refs += [
j
for j, e in enumerate(manifest)
if e["id"] == "core0250" and e["file"] == "nodes.py"
]
effect = (
editorial[nid]
+ f" 原mode={n['mode']}"
+ (
"(旁路保存态,不模拟穿透/恢复)。"
if n["mode"] == 4
else "(活动保存态,不认证已执行)。"
)
)
flow += [
effect,
nid + " 原属性 " + json.dumps(n["properties"], ensure_ascii=False),
nid
+ " 原输入/输出 "
+ json.dumps({k: n[k] for k in ["inputs", "outputs"]}, ensure_ascii=False),
nid
+ " 原具名保存 "
+ json.dumps(n.get("widgets_values_named", "missing"), ensure_ascii=False),
]
if not n.get("widgets_values"):
empty.append(
dict(
node_id=nid,
class_type=cls,
pointer=ptr,
scope="root",
state="missing"
if "widgets_values" not in n
else "null"
if n["widgets_values"] is None
else "empty_list",
effect=effect,
)
)
continue
for j, (name, value) in enumerate(zip(LAYOUTS[cls], n["widgets_values"], strict=True)):
found = [k for k, 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
default, limits = schemas.get(
name,
(
"未知:前端历史/辅助保存,没有独立后端参数默认",
"仅保存参考,不按端口顺序推断schema或恢复",
),
)
unit = "字符串/枚举/文件引用,无物理单位;保存值不证明安装或运行"
if key == "unknown":
default = "未知:原图无提供方/版本,不能由具名键或相邻实现补默认"
limits = (
"未知:九位置与具名保存逐项互证;声明输入不等于后端schema,"
+ "不保证算法、尺寸、mask或背景行为"
)
unit = "单位未知:无准确实现身份,仅保留原JSON类型与值"
if name in ("seed", "steps"):
unit = "整数种子/步数接口;不生成随机或计算最终执行值"
if name in ("cfg", "denoise", "strength_model"):
unit = "无物理单位接口系数;原JSON int与FLOAT默认独立,不认证效果"
if name == "control_after_generate":
default = "准确frontend1.23.0辅助默认randomize;不是后端seed默认"
limits = (
"fixed/increment/decrement/random"
+ "ize;前端种子辅助与保存具名键独立,不执行随机或认证恢复"
)
if name == "upload":
default = "前端上传状态,无独立后端upload默认"
limits = (
"准确frontend1.23.0 IMAGEUPLOAD与Lit"
+ "eGraph0.15.15序列化静态参考;不读取/上传素材,不认"
+ "证具名插件恢复"
)
if name == "comparison_history":
default = "未知:前端历史列表,无独立后端widget默认"
limits = (
"位置两完整对象与具名rgthree_comparer.image"
+ "s两完整对象分别保留;具名各多img:{},不强作相等;temp"
+ "_rjutl历史URL仅文本,不GET /api/view"
)
unit = "完整JSON列表/对象/布尔/URL文本,无物理单位"
if cls == "CLIPLoader" and name == "type":
limits += (
";准确core0.25.0枚举不含krea2,load_clip"
+ "有getattr fallback仍不证明支持;不借0.26.0"
+ "填缺口"
)
if cls == "KSampler" and name == "scheduler":
limits += (
";准确core0.25.0调度器表无原拼beta57;beta不"
+ "是beta57,不修正原图或认证可执行"
)
if name == "kv_cache":
unit = "布尔开关,无物理单位;保存true不证明LoRA训练条件满足"
limits += (
";准确default False,保存True要求LoRA以对应"
+ "kv_cache训练;不执行patch、预计算或缓存,不认证训练"
+ "条件"
)
named_key = "rgthree_comparer" if name == "comparison_history" else name
named = n.get("widgets_values_named", {})
assert named_key in named
named_pointer = ptr + "/widgets_values_named/" + named_key
named_value = named[named_key]
if name == "comparison_history":
named_pointer += "/images"
named_value = named_value["images"]
else:
assert canonical(named_value) == canonical(value)
fields.append(
dict(
node_id=nid,
definition_node_id=nid,
scope="root",
class_type=cls,
field=name,
label=LABELS[name],
pointer=f"{ptr}/widgets_values/{j}",
value=value,
json_type=type(value).__name__,
named_pointer=named_pointer,
named_value=named_value,
input_pointer=f"{ptr}/inputs/{inp}"
if inp is not None
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="frontend_reference_only"
if name in ("upload", "control_after_generate", "comparison_history")
else "linked_saved_cache"
if linked
else "saved_reference",
schema_default=default,
limits=limits,
unit=unit,
effect=effect
+ (
" 具名保存完整形态(与位置历史分列):"
+ json.dumps(named_value, ensure_ascii=False, indent=2)
if canonical(named_value) != canonical(value)
else ""
),
evidence=list(dict.fromkeys(refs)),
execution_note=(
"仅静态参考;全部提示/指南/历史URL只作源"
"数据,不构造prompt,不执行上游、插件、"
"SDK、模型、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 g["links"]]
flow += [
"原附加属性/组 "
+ json.dumps(
{k: v for k, v in g.items() if k not in ("nodes", "links")}, ensure_ascii=False
)
]
flow += prose["steps"] + [
"注释" + n["node_id"] + " 中文核对:" + n["meaning"] for n in comments
]
assert len(fields) == 33 and len(comments) == 0
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=(
"仅参考:编码初始latent与参考条件分层;LayerUtili"
+ "ty身份、beta57/krea2枚举缺口及输出声明冲突保留;目"
+ "标安装、兼容、模型许可、尺寸与效果未知。转换执行资格不变。"
),
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 manifest}.values()
]
+ [
(
"旧88块4579位置/146注释冻结;新增33位置/零Note,"
+ "总89图4612位置/146注释仅参考。local_file以d"
+ "ocs/hel-892/krea-anything-docume"
+ "nt-evidence为基准。"
)
],
counts=dict(
saved_fields=33,
root_saved_fields=33,
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=17,
root_nodes=17,
internal_nodes=0,
physical_edges=23,
source_notes=0,
saved_objects=1,
history_objects=2,
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=[],
node_bindings=bindings,
steps=[prose["overview"]] + prose["steps"],
)