Files
aigc-home/docs/hel-892/minimax-h3-t2v-document-evidence/build_definition.py
T
2026-11-01 05:44:14 +08:00

541 lines
23 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 Qwen Image2.1 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 / "minimax-h3-t2v-reference"
PATHS = ["example_ComfyUI_workflows/4-视频生成/Minimax-h3/minimax_h3_t2v_文生视频.json"]
HOST = "79dd8a95-ce9d-4c14-b264-2162e8bec5ce"
LAYOUTS = {
"SaveVideo": ["filename_prefix", "format", "codec"],
"ResolutionSelector": ["aspect_ratio", "megapixels", "multiple"],
"79dd8a95-ce9d-4c14-b264-2162e8bec5ce": [
"prompt",
"width",
"height",
"value_1",
"noise_seed",
"unet_name",
"clip_name",
"vae_name",
"vae_name_1",
"value",
"lora_name",
"strength_model_1",
"value_2",
],
"VAELoader": ["vae_name"],
"KSamplerSelect": ["sampler_name"],
"BasicScheduler": ["scheduler", "steps", "denoise"],
"UNETLoader": ["unet_name", "weight_dtype"],
"CLIPLoader": ["clip_name", "type", "device"],
"RandomNoise": ["noise_seed", "control_after_generate"],
"CreateVideo": ["fps", "bit_depth"],
"MiniMaxH3ImageToVideo": ["prompt", "width", "height", "length"],
"ComfyMathExpression": ["expression"],
"PrimitiveFloat": ["value"],
"LoraLoaderModelOnly": ["lora_name", "strength_model"],
"ComfySwitchNode": ["switch"],
"PrimitiveInt": ["value", "fixed"],
"PrimitiveBoolean": ["value"],
}
LABELS = {
"filename_prefix": "完整视频保存前缀",
"format": "保存容器选择",
"codec": "保存编码选择",
"aspect_ratio": "宽高比保存",
"megapixels": "MP保存值",
"multiple": "像素对齐倍数",
"prompt": "完整提示词缓存",
"width": "宽度缓存",
"height": "高度缓存",
"value_1": "宿主时长缓存",
"noise_seed": "噪声种子缓存",
"unet_name": "完整扩散模型引用",
"clip_name": "完整文本模型引用",
"vae_name": "独立VAE文件引用",
"vae_name_1": "宿主音频VAE引用",
"value": "数值/布尔保存缓存",
"lora_name": "完整LoRA引用",
"strength_model_1": "宿主LoRA强度",
"value_2": "宿主步数缓存",
"sampler_name": "采样器选择",
"scheduler": "调度器选择",
"steps": "步数缓存",
"denoise": "降噪系数",
"weight_dtype": "权重dtype选择",
"type": "编码器类型选择",
"device": "设备选择",
"control_after_generate": "种子前端控制辅助",
"fixed": "整数前端控制辅助",
"fps": "视频帧率保存",
"bit_depth": "视频位深保存",
"length": "帧长缓存",
"expression": "完整表达式(不求值)",
"strength_model": "LoRA强度缓存",
"switch": "布尔选支缓存",
}
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)
editorial = json.loads((OUT / "editorial.json").read_bytes())
scopes = [("", "", g), ("140", "/definitions/subgraphs/0", g["definitions"]["subgraphs"][0])]
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="../minimax-h3-t2v-reference/" + e["local_file"],
lines=[1, len(data.decode().splitlines())],
claim="本图准确tag/commit原文与许可;静态读取未执行,源码许可不等于模型许可",
)
)
if e["file"].endswith(".py"):
trees[e["local_file"]] = ast.parse(data)
bindings = []
prose = json.loads((OUT / "prose.json").read_bytes())
refs = {}
schemas = {}
for nid, ptr, scope, n in nodes:
cls = n["type"]
if cls in ["Note", "MarkdownNote"]:
continue
symbol = {
"PrimitiveStringMultiline": "StringMultiline",
"PrimitiveFloat": "Float",
"PrimitiveInt": "Int",
"PrimitiveBoolean": "Boolean",
"ComfyMathExpression": "MathExpressionNode",
"ShowText|pysssss": "ShowText",
"Image Comparer (rgthree)": "RgthreeImageComparer",
"ComfySwitchNode": "SwitchNode",
"Images to RGB": "WAS_Images_To_RGB",
"忽略多组孤海": "IgnoreGroupsGuHai",
"GH_ImageVideoComparer": "GHImageVideoComparer",
}.get(cls, cls)
version = n.get("properties", {}).get("ver", "未知")
core_id = {"0.33.0": "core0330"}.get(version, "unknown")
if cls == HOST:
core_id = "subgraph-definition"
candidates = []
rs = []
for i, e in enumerate(manifest):
if e["id"] != core_id or not e["file"].endswith(".py"):
continue
if (
cls in ["PrimitiveInt", "PrimitiveFloat", "PrimitiveBoolean"]
and e["file"] != "comfy_extras/nodes_primitive.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[i],
lines=[c.lineno, c.end_lineno],
claim=f"本节点准确{core_id}声明类实现;不等于目标安装或宿主恢复认证",
)
)
rs += [i, len(sources) - 1]
candidates.append(dict(source=i, symbol=symbol, lines=[c.lineno, c.end_lineno]))
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函数缺省补值",
)
if cls == "SaveImageAdvanced" and name in [
"bit_depth",
"input_color_space",
]:
# Keep the first exact PNG DynamicCombo branch.
schemas.setdefault((nid, "format." + name), (default, ast.unparse(d)))
else:
schemas[nid, name] = (default, ast.unparse(d))
assert len(candidates) <= 1, (nid, candidates)
if not candidates and core_id not in ["unknown", "subgraph-definition"]:
core_id = "unresolved-" + core_id
bindings.append(
dict(
node_id=nid,
class_type=cls,
source_version=version,
source_id=core_id,
candidates=candidates,
)
)
if core_id.replace("unresolved-", "") in [
"goohai",
"rgthree",
"showtext",
"ghgroup",
"ghcompare",
"was",
"vosr",
]:
rs += [
i for i, e in enumerate(manifest) if e["id"] == core_id.replace("unresolved-", "")
]
if cls == "KSampler":
rs += [
i
for i, e in enumerate(manifest)
if e["id"] == core_id and e["file"] == "comfy/samplers.py"
]
if cls in [
"KSampler",
"LoadImage",
"ShowText|pysssss",
"Image Comparer (rgthree)",
"忽略多组孤海",
]:
rs += [i for i, e in enumerate(manifest) if e["id"] in ["frontend", "litegraph"]]
if cls == "QwenImage21Cache":
rs += [
i
for i, e in enumerate(manifest)
if e["id"] == core_id
and e["file"].startswith(("comfy/ldm/qwen_image21/", "comfy_api/latest/"))
]
rs += [i for i, e in enumerate(manifest) if e["id"] == core_id.removeprefix("unresolved-")]
rs += [i for i, e in enumerate(manifest) if e["id"] == "frontend"]
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=prose["notes"][nid],
named_pointer=ptr + "/widgets_values_named/text",
named_value=n["widgets_values_named"]["text"],
evidence=[],
)
)
flow.append(nid + " 原注释节点 " + json.dumps(n, ensure_ascii=False))
continue
core_id = next(b["source_id"] for b in bindings if b["node_id"] == nid)
effect = (
editorial[nid]
+ " 原mode="
+ str(n["mode"])
+ (
"(旁路保存态,不模拟穿透或执行)。"
if n["mode"] == 4
else "(mode2禁用/忽略保存态,不模拟组控制或执行)。"
if n["mode"] == 2
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
+ " 原具名保存 "
+ json.dumps(n.get("widgets_values_named", "missing"), ensure_ascii=False),
nid
+ " 原其它属性 "
+ json.dumps(
{
k: v
for k, v in n.items()
if k
not in [
"inputs",
"outputs",
"properties",
"widgets_values",
"widgets_values_named",
]
},
ensure_ascii=False,
),
]
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,
named_state="empty_object"
if n.get("widgets_values_named") == {}
else "missing",
)
)
continue
for j, (name, value) in enumerate(zip(LAYOUTS[cls], 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 = cls == HOST
aux = name in [
"control_after_generate",
"fixed",
"upload",
"text_0",
"rgthree_comparer",
"guhai_ig",
]
(default, limits) = schemas.get(
(nid, name),
(
"无准确独立宿主/前端widget默认",
"宿主保存位置/声明边界,不认证promoted或后端执行映射",
),
)
unit = "接口枚举/文本/布尔,无物理单位;实际目标未核"
if name in ["width", "height", "multiple"]:
unit = "像素标尺/对齐倍数;保存缓存与外线覆盖分别列,不试算输出尺寸"
if name == "megapixels":
unit = "MP接口,准确实现以1024×1024为基数;源float0.4原样,不计算像素"
if name in ["steps", "length", "value_2"]:
unit = "整数步数/帧长接口;缓存/边界覆盖分列,不计算实际采样或帧数"
if name == "noise_seed":
unit = "整数噪声种子接口,不执行随机或保证可复现"
if name in ["strength_model", "strength_model_1", "denoise"]:
unit = "无物理单位的接口系数;源JSON int与准确定义分列"
if name == "fps":
unit = "帧/秒;源JSON int24与FLOAT schema默认30.0分列,不证明实际时长"
if name == "bit_depth":
unit = "视频位深接口,准确8/10步长2;源int8不是实际编码效果证明"
if name == "expression":
unit = "纯表达式字符串;不调用eval/simpleeval或推导帧数/时长"
if name in ["control_after_generate", "fixed"]:
default = (
"PrimitiveInt按准确schema控制缺省fixed"
if cls == "PrimitiveInt"
else "前端控制辅助,准确frontend1.49.6通用缺省randomize;源fixed另列"
)
limits = (
"fixed/increment/decrement/randomize;非后端数值参数,"
"不执行随机、控制时序或认证恢复"
)
unit = "前端辅助枚举,无物理单位"
if cls == HOST:
default = "无独立宿主schema默认,不把缓存/内部默认当最终输入"
limits = (
"本图13保存缓存与15输入/定义边界分列;first_frame/last_frame无根输入,"
"不造图像控件或promoted恢复"
)
if name == "value_1":
unit = (
"秒的作者接口意图;源JSON int5与内部FLOAT schema/缓存int2分列,"
"不证明真实时长"
)
if cls == "PrimitiveFloat":
unit = "时长秒的边界意图;FLOAT schema而源JSON int2,未改保存类型或计算表达式"
if cls == "PrimitiveInt" and name == "value":
unit = "采样步数候选整数;20/6缓存与宿主8分列,不计算sigmas"
if core_id == "unknown" or core_id.startswith("unresolved-"):
default = "未知:未核准本声明准确类/schema,不由其它版本补实"
limits = "仅源保存/输入候选,准确默认/范围/算法/副作用未知"
unit = "未知:准确声明类/schema未核"
named_key = name
named = n["widgets_values_named"][named_key]
display_effect = effect
if canonical(value) != canonical(named):
display_effect += "\n具名保存完整形态(与位置历史分列):" + json.dumps(
named, ensure_ascii=False, indent=2
)
fields.append(
dict(
node_id=nid,
definition_node_id=str(n["id"]),
scope=scope,
class_type=cls,
field=name,
label=LABELS.get(name, name + "完整保存值"),
pointer=f"{ptr}/widgets_values/{j}",
value=value,
json_type=type(value).__name__,
named_pointer=ptr
+ "/widgets_values_named/"
+ name.replace("~", "~0").replace("/", "~1"),
named_value=n["widgets_values_named"][
"control_after_generate" if name == "seed_control_candidate" else name
],
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 aux
else "boundary_saved_cache"
if boundary
else "linked_saved_cache"
if linked
else "saved_reference",
schema_default=default,
limits=limits,
unit=unit,
effect=display_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"]
)
)
definition = g["definitions"]["subgraphs"][0]
boundaries = [
dict(
host_node_id="140",
definition_id=HOST,
definition_widgets=definition["widgets"],
proxy_widgets_present="proxyWidgets" in next(n for n in g["nodes"] if n["id"] == 140),
inputs=definition["inputs"],
outputs=definition["outputs"],
links=definition["links"],
notice="13宿主缓存、15输入与42含边界记录分列,definition.widgets=[]/无proxyWidgets,不认证promoted/UE恢复",
)
]
flow += ["根附加保存属性 " + json.dumps(g["extra"], ensure_ascii=False)]
flow += prose["steps"]
flow += ["注释" + n["node_id"] + " 中文核对:" + n["meaning"] for n in comments]
overview = json.loads((OUT / "prose.json").read_bytes())["overview"]
assert len(fields) == 49 and len(comments) == 3
assert all("widgets_values_named" in n for _, _, _, n in nodes if n.get("widgets_values"))
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="仅固定参考:首尾帧未接,宿主与内部英文/尺寸/时长/步数缓存分列;表达式不求值,目标模型/安装/音视频效果与宿主恢复未核,资格不变。",
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()
]
+ [
"旧106块5846位置/184注释冻结;新增49位置/三标准Note,总107图5895位置/187注释仅参考。local_file以docs/hel-892/minimax-h3-t2v-document-evidence为基准。"
],
counts=dict(
saved_fields=49,
root_saved_fields=19,
internal_saved_fields=30,
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=27,
root_nodes=6,
internal_nodes=21,
physical_edges=45,
source_notes=3,
saved_objects=0,
history_objects=0,
final_scalars=0,
final_prompt_constructed=False,
),
node_bindings=bindings,
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"],
)