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

525 lines
22 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.
"""Exact declared registrations and raw scoped values; AST/text only."""
import ast
import copy
import hashlib
import json
import os
from pathlib import Path
REPO = Path(__file__).resolve().parents[3]
CONFIG = Path(__file__).resolve().parent
OUT = Path(os.environ.get("ANIMATE_EVIDENCE_OUT", CONFIG)).resolve()
REF = CONFIG.parent / "animate-reference"
PATHS = [
"example_ComfyUI_workflows/6-动作迁移/Wan2.2_Animate_SAM3-人物迁移-动作迁移-长视频循环(KJ流).json"
]
def canonical(v):
return json.dumps(v, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
def node_schema(class_node):
"""Extract INPUT_TYPES expressions only, never interpret plugin code."""
method = next(
(
m
for m in class_node.body
if isinstance(m, (ast.FunctionDef, ast.AsyncFunctionDef)) and m.name == "INPUT_TYPES"
),
None,
)
if method is None:
method = next(
(
m
for m in class_node.body
if isinstance(m, ast.FunctionDef) and m.name == "define_schema"
),
None,
)
if method is None:
return {}
schema = {}
for call in ast.walk(method):
if (
not isinstance(call, ast.Call)
or not isinstance(call.func, ast.Attribute)
or call.func.attr != "Input"
):
continue
if (
not call.args
or not isinstance(call.args[0], ast.Constant)
or not isinstance(call.args[0].value, str)
):
continue
default = next(
(ast.unparse(k.value) for k in call.keywords if k.arg == "default"),
"无显式default;动态选项由准确代码/目标决定",
)
schema[call.args[0].value] = (default, ast.unparse(call))
return schema
literals = {}
for assignment in method.body:
if isinstance(assignment, ast.Assign) and len(assignment.targets) == 1:
target = assignment.targets[0]
if isinstance(target, ast.Name):
try:
ast.literal_eval(assignment.value)
except (ValueError, TypeError):
continue
literals[target.id] = assignment.value
class LiteralNames(ast.NodeTransformer):
def visit_Name(self, node):
return copy.deepcopy(literals.get(node.id, node))
schema = {}
for d in ast.walk(method):
if not isinstance(d, ast.Dict):
continue
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)
schema[k.value] = (default, ast.unparse(LiteralNames().visit(copy.deepcopy(v))))
return schema
def scoped_graphs(g):
yield "", "", g
for i, s in enumerate(g.get("definitions", {}).get("subgraphs", [])):
host = next(n for n in g["nodes"] if n["type"] == s["id"])
yield str(host["id"]) + ":", f"/definitions/subgraphs/{i}", s
def declarations(rows):
"""Only exact registered keys; renamed similar classes never establish identity."""
classes = {}
keys = {}
trees = {}
for i, e in enumerate(rows):
if not e["file"].endswith(".py"):
continue
t = ast.parse((REF / e["local_file"]).read_bytes())
trees[i] = t
for c in t.body:
if isinstance(c, ast.ClassDef):
classes[(e["id"], c.name)] = (i, c)
for a in t.body:
if not isinstance(a, ast.Assign):
continue
if not any(
isinstance(n, ast.Name) and n.id in ["NODE_CLASS_MAPPINGS", "NODE_CONFIG"]
for n in a.targets
):
continue
if not isinstance(a.value, ast.Dict):
continue
for k, v in zip(a.value.keys, a.value.values):
if not isinstance(k, ast.Constant) or not isinstance(k.value, str):
continue
symbol = v.id if isinstance(v, ast.Name) else None
if isinstance(v, ast.Dict):
symbol = next(
(
vv.id
for kk, vv in zip(v.keys, v.values)
if isinstance(kk, ast.Constant)
and kk.value == "class"
and isinstance(vv, ast.Name)
),
None,
)
if symbol:
keys[(e["id"], k.value)] = symbol
for c in [x for x in t.body if isinstance(x, ast.ClassDef)]:
nodeid = next(
(
kw.value.value
for f in c.body
if isinstance(f, ast.FunctionDef) and f.name == "define_schema"
for call in ast.walk(f)
if isinstance(call, ast.Call)
for kw in call.keywords
if kw.arg == "node_id" and isinstance(kw.value, ast.Constant)
),
None,
)
if nodeid:
keys[(e["id"], nodeid)] = c.name
return classes, keys, trees
def source_key(n, rows):
p = n.get("properties", {})
v = p.get("ver")
typ = n["type"]
if typ in ["5f724af1-bc9e-4f8c-8fa8-6b7a23ca133e", "fe42f6d9-8e02-433f-bdc9-6dec30ce9571"]:
return "boundary"
if not v:
return "unknown"
if v.startswith("761b"):
return "missing761"
if v.startswith("58de"):
return "cleanup-58de13a6"
if v.startswith("afeee"):
return "wascanonical-afeee09b"
return next(e["id"] for e in rows if e.get("tag") in [v, "v" + v])
def layouts(n):
w = n.get("widgets_values", [])
if isinstance(w, dict):
return list(w)
names = [x["widget"]["name"] for x in n.get("inputs", []) if isinstance(x.get("widget"), dict)]
if n["id"] == 630:
names.insert(4, "control_after_generate")
if n["type"] == "ImageConcatMulti":
return names + ["position_3"]
if len(names) == len(w):
return names
if n["type"] == "LoadImage":
return ["image", "position_1"]
if n["type"] == "Seed (rgthree)":
return ["seed", "position_1", "position_2", "position_3"]
if n["type"] == "Int" and len(w) == 1:
return ["value"]
if n["type"] == "CLIPVisionLoader":
return ["clip_name"]
if n["type"] == "CheckpointLoaderSimple":
return ["ckpt_name"]
if n["type"] == "CLIPTextEncode":
return ["text"]
return [f"position_{j}" for j in range(len(w))]
def build(index=0):
raw = (REPO / PATHS[index]).read_bytes()
g = json.loads(raw)
rows = json.loads((REF / "sources.json").read_bytes())["sources"]
classes, keys, trees = declarations(rows)
prose = json.loads((CONFIG / "prose.json").read_bytes())
editorial = json.loads((CONFIG / "editorial.json").read_bytes())
sources = []
for e in rows:
data = (REF / e["local_file"]).read_bytes()
assert hashlib.sha256(data).hexdigest() == e["sha256"]
sources.append(
dict(
e,
local_file=os.path.relpath(REF / e["local_file"], OUT),
license_file=os.path.relpath(REF / e["license_file"], OUT)
if not e["license_file"].startswith("未知")
else e["license_file"],
lines=[1, len(data.decode().splitlines())] if data else [0, 0],
claim="本图准确必要文本/身份响应;仅静态核对,许可不认证模型素材,未执行;零字节原件"
if not data
else "本图准确必要源码或身份缺口响应;注册/协议缺口另列,不执行",
)
)
if e["file"] in {
"web_version/v2/easyuse.js",
"web_version/v2/assets/extensions-D7E6yQLT.js",
"video_formats/h264-mp4.json",
} and e["commit"] in {
"a1b402b4a9c0ddd35c0ac1197579f8f7b121ff3e",
"8e4d79471bf1952154768e8435a9300077b534fa",
}:
sources[-1]["claim"] += ";本次复核UTC:" + e["reverified_at"]
fields = []
comments = []
bindings = []
empty = []
boundaries = []
flow = []
for pre, prefix, graph in scoped_graphs(g):
scope = "root" if not pre else "宿主" + pre[:-1] + "内部定义"
edges = {e[0] if isinstance(e, list) else e["id"]: e for e in graph["links"]}
for ni, n in enumerate(graph["nodes"]):
nid = pre + str(n["id"])
ptr = f"{prefix}/nodes/{ni}"
flow.append(nid + " 原节点完整保存 " + json.dumps(n, ensure_ascii=False))
if n["type"] in ["Note", "MarkdownNote"]:
comments.append(
dict(
node_id=nid,
pointer=ptr + "/widgets_values/0",
text=n["widgets_values"][0],
meaning=prose["notes"][nid],
evidence=[],
)
)
continue
key = source_key(n, rows)
symbol = keys.get((key, n["type"]))
matched_class = classes.get((key, symbol))
schema = {}
candidates = []
rs = [
i
for i, e in enumerate(rows)
if e["id"] == key or e["id"] in ["frontend", "litegraph"]
]
if matched_class:
ei, c = matched_class
schema = node_schema(c)
if n["type"] == "VHS_VideoCombine":
fmt = next(
e
for e in rows
if e["id"] == key and e["file"] == "video_formats/h264-mp4.json"
)
assert n["widgets_values"]["format"] == "video/h264-mp4"
template = json.loads((REF / fmt["local_file"]).read_bytes())
widgets = [x for x in template["main_pass"] if isinstance(x, list)]
widgets += [template["save_metadata"], template["trim_to_audio"]]
for widget in widgets:
options = widget[2] if len(widget) > 2 else {}
default = (
json.dumps(options["default"], ensure_ascii=False)
if "default" in options
else "无显式default;准确模板选项另列"
)
schema[widget[0]] = (
default,
"准确本版本H264动态格式控件:" + json.dumps(widget, ensure_ascii=False),
)
sources.append(
dict(
sources[ei],
lines=[c.lineno, c.end_lineno],
claim=nid + "准确注册类" + symbol + ";原端口/额外项/保存协议冲突单列",
)
)
rs.append(len(sources) - 1)
candidates = [dict(source=ei, symbol=symbol, lines=[c.lineno, c.end_lineno])]
sid = (
"subgraph-definition"
if key == "boundary"
else "unknown-no-version"
if key == "unknown"
else key
if matched_class
else "unresolved-" + key
)
bindings.append(
dict(
node_id=nid,
class_type=n["type"],
source_id=sid,
source_version=n.get("properties", {}).get("ver", "未知:没有准确版本"),
declared_provider=n.get("properties", {}).get("cnr_id"),
declared_aux=n.get("properties", {}).get("aux_id"),
implementation_verified=matched_class is not None,
candidates=candidates,
scope=scope,
notice="仅准确注册键;宿主不传播版本,无版本及未匹配不借近似类",
)
)
effect = (
editorial[nid]
+ f" 原mode={n['mode']};保留原边,不模拟有效分支/旁路/执行;零具名,不造双指针。"
)
flow.append(effect)
w = n.get("widgets_values")
if "widgets_values" not in n or w in [None, [], {}]:
state = (
"missing"
if "widgets_values" not in n
else "null"
if w is None
else "empty_dict"
if w == {}
else "empty_list"
)
empty.append(
dict(
node_id=nid,
class_type=n["type"],
pointer=ptr,
scope=scope,
state=state,
named_state="missing",
effect=effect,
)
)
continue
names = layouts(n)
entries = list(w.items()) if isinstance(w, dict) else list(zip(names, w, strict=True))
for j, (name, value) in enumerate(entries):
inp = next(
(i for i, x in enumerate(n.get("inputs", [])) if x["name"] == name), None
)
known = name in schema
link = n["inputs"][inp].get("link") if inp is not None else None
e = edges.get(link)
boundary_link = bool(
pre and isinstance(e, dict) and e["origin_id"] == graph["inputNode"]["id"]
)
aux = name == "control_after_generate" or (n["type"] == "Seed (rgthree)" and j > 0)
default, limits = schema.get(
name,
(
"未知:准确类/字段未匹配或额外保存;不借后版/相似类",
"未知:不按位置/原口名认证后端支持、默认或恢复",
),
)
role = (
"boundary_saved_cache"
if known and boundary_link
else "linked_override"
if known and link is not None
else "frontend_only"
if aux
else "schema_input"
if known
else "extra_saved"
)
fields.append(
dict(
node_id=nid,
definition_node_id=str(n["id"]),
scope=scope,
class_type=n["type"],
field=name,
label=prose["labels"].get(name, name + "原保存(后端支持与缓存分列)"),
pointer=ptr
+ "/widgets_values/"
+ (name if isinstance(w, dict) else str(j)),
value=value,
json_type=type(value).__name__,
named_state="missing",
input_pointer=f"{ptr}/inputs/{inp}"
if known and inp is not None
else "未知:无准确后端映射;原widget/口名仅保存线索",
input_name=name if known and inp is not None else None,
type=limits,
role=role,
schema_default=default,
limits=limits,
unit=prose["units"].get(
nid + "." + name,
(
"像素(准确图像维度/schema);原缓存与外线分列,不计算实际尺寸"
if known
and name
in [
"width",
"height",
"custom_width",
"custom_height",
"tile_x",
"tile_y",
"tile_stride_x",
"tile_stride_y",
]
else "帧(准确schema/实现);非已读取帧数或实际窗口数"
if known
and name
in [
"num_frames",
"frame_window_size",
"context_frames",
"context_stride",
"context_overlap",
"frame_load_cap",
"skip_first_frames",
"select_every_nth",
]
else "帧/秒(准确视频接口/编码实现);缓存/外线/历史分列"
if known and name in ["frame_rate", "force_rate"]
else "CRF整数参数,无物理单位;准确动态模板范围另列"
if known and name == "crf"
else "准确schema类型与原JSON类型分列;无明确物理单位则未知"
),
),
effect=effect
+ (
" 此项不在准确已匹配schema,不能认证生效/恢复。"
if not known
else (
" 原widget/保存值与准确同名schema分列;"
"准确前端1.23.0与锁定LiteGraph0.15.15静态参考;不认证目标完整恢复。"
)
),
evidence=rs,
execution_note="仅静态保存与源码;未构造prompt/执行插件模型GPU/SAM/音频/播放/随机/循环/采样/视频/媒体/别名/组控/清理或I/O,资格不变。",
)
)
flow += [
scope + " 物理/边界记录 " + json.dumps(e, ensure_ascii=False) for e in graph["links"]
]
if pre:
host = next(n for n in g["nodes"] if str(n["id"]) + ":" == pre)
boundary = dict(
host_node_id=str(host["id"]),
definition_id=graph["id"],
pointer=prefix,
host=host,
**{
k: graph[k]
for k in [
"inputNode",
"outputNode",
"inputs",
"outputs",
"widgets",
"state",
"extra",
]
},
proxy_state="missing" if "proxyWidgets" not in host["properties"] else "present",
proxy_mappings=[],
)
boundaries.append(boundary)
flow.append(
"宿主" + str(host["id"]) + " 原边界 " + json.dumps(boundary, ensure_ascii=False)
)
flow += ["根附加属性 " + json.dumps(g["extra"], ensure_ascii=False)] + prose["steps"]
assert len(fields) == 270 and len(comments) == 1 and len(boundaries) == 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=prose["notice"],
user_overview=prose["overview"],
versions=prose["versions"],
counts=dict(
saved_fields=len(fields),
root_saved_fields=sum(f["scope"] == "root" for f in fields),
internal_saved_fields=sum(f["scope"] != "root" for f in fields),
linked_saved_fields=sum(f["role"] == "linked_override" for f in fields),
boundary_saved_fields=sum(f["role"] == "boundary_saved_cache" for f in fields),
frontend_only=sum(f["role"] == "frontend_only" for f in fields),
source_nodes=90,
root_nodes=90,
internal_nodes=0,
physical_edges=87,
source_notes=1,
proxy_widgets=0,
final_scalars=0,
final_prompt_constructed=False,
),
node_bindings=bindings,
fields=fields,
sources=sources,
comments=comments,
flow=flow,
flow_evidence=[],
zero_saved_nodes=empty,
boundaries=boundaries,
steps=[prose["overview"]] + prose["steps"],
)