Files
aigc-home/docs/hel-892/t8-two-document-evidence/build_definition.py
T
2026-11-01 08:02:36 +08:00

677 lines
28 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 MiniMax H3 image-to-video reference; no upstream 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 / "t8-two-reference"
PATHS = [
"example_ComfyUI_workflows/4-视频生成/Minimax-h3/Minimax_H3_T8双采样_潜空间放大_参考生视频.json"
]
HOST = "no-subgraph"
LAYOUTS = {
"SetNode": ["Constant"],
"ComfyMathExpression": ["expression"],
"GetNode": ["Constant"],
"LoadImage": ["image", "upload"],
"LoadAudio": ["audio", "upload"],
"LayerUtility: ImageScaleByAspectRatio V2": [
"aspect_ratio",
"proportional_width",
"proportional_height",
"fit",
"method",
"round_to_multiple",
"scale_to_side",
"scale_to_length",
"background_color",
],
"MiniMaxH3LearnedTwoPassParityPlanT8Advanced": ["base_steps", "coarse_steps", "refine_steps"],
"RandomNoise": ["noise_seed", "control_after_generate"],
"VHS_VideoCombine": [
"frame_rate",
"loop_count",
"filename_prefix",
"format",
"pix_fmt",
"crf",
"save_metadata",
"pingpong",
"save_output",
"videopreview",
],
"MiniMaxH3TwoPassDetailMixerT8Advanced": [
"shift_video",
"shift_audio",
"enable_tail",
"extra_tail_steps",
"tail_spacing",
"enable_model_time_bias",
"bias",
"bias_start_progress",
"bias_end_progress",
"bias_domain",
"enable_stg",
"stg_scale",
"stg_double_blocks",
"stg_start_progress",
"stg_end_progress",
"enable_restart",
"restart_video_sigma",
"restart_steps",
"restart_seed",
"control_after_generate",
],
"MiniMaxH3TwoPassLatentReconcileT8Advanced": [
"audio_policy",
"second_pass_audio_source",
"second_pass_audio_strength",
],
"MiniMaxH3AudioConditioningT8": [
"prompt",
"width",
"height",
"length",
"task_type",
"audio_mode",
"audio_denoise_strength",
"add_source_as_reference",
"prompt_primary_audio_ordinal",
"strict_prompt_tags",
"ref_image_size",
"reference_video_policy",
"allow_above_reference_area",
],
"ResolutionSelector": ["aspect_ratio", "megapixels", "multiple"],
"PrimitiveFloat": ["value"],
"ModelAttentionBackend": ["attention"],
"MiniMaxH3DualClockSamplerT8": [
"steps",
"shift_video",
"shift_audio",
"sampler_name",
"scheduler",
],
"MiniMaxH3LearnedLatentUpscaleT8Advanced": [
"model_name",
"size_mode",
"scale_by",
"target_megapixels",
"target_width",
"target_height",
"aspect_policy",
"max_anisotropy",
"precision",
"release_policy",
],
"UNETLoader": ["unet_name", "weight_dtype"],
"LoraLoaderBypassModelOnly": ["lora_name", "strength_model"],
"CLIPLoader": ["clip_name", "type", "device"],
"VAELoader": ["vae_name"],
"CR Prompt Text": ["prompt"],
}
LABELS = {
"base_steps": "计划基础步数保存",
"coarse_steps": "第一段计划步数保存",
"refine_steps": "第二段计划步数保存",
"size_mode": "潜放尺寸模式",
"scale_by": "潜放倍率缓存",
"target_megapixels": "目标MP保存",
"target_width": "目标宽度保存",
"target_height": "目标高度保存",
"aspect_policy": "宽高比策略",
"max_anisotropy": "各向异性接口限制",
"release_policy": "模型释放策略",
"audio_policy": "协调音频策略",
"second_pass_audio_source": "第二段音频来源策略",
"second_pass_audio_strength": "第二段显式音频强度",
"enable_tail": "尾段细分开关",
"enable_model_time_bias": "模型时间偏移开关",
"enable_stg": "STG开关",
"enable_restart": "联合AV重启开关",
"restart_seed": "重启种子保存",
"stg_double_blocks": "STG块索引原字符串",
"audio": "音频文件引用",
"round_to_multiple": "缩放对齐倍数保存",
"scale_to_side": "缩放目标策略",
"scale_to_length": "缩放目标数值保存",
"task_type": "任务类型原保存与接口冲突",
"audio_mode": "音频条件模式",
"audio_denoise_strength": "音频降噪强度保存",
"add_source_as_reference": "驱动音频作为参考保存",
"prompt_primary_audio_ordinal": "主要提示音频序号",
"strict_prompt_tags": "提示媒体标签严格检查",
"reference_video_policy": "参考视频时长策略",
"allow_above_reference_area": "额外面积开关(准确接口不存在)",
"videopreview": "完整历史预览对象(仅文本)",
"frame_rate": "VHS帧率保存",
"loop_count": "循环次数保存",
"pix_fmt": "编码像素格式",
"crf": "编码质量参数",
"save_metadata": "元数据保存开关",
"trim_to_audio": "按音频裁剪保存",
"pingpong": "往返播放保存",
"save_output": "输出目录保存开关",
"Constant": "别名名称保存(实现未知)",
"model_name": "潜放模型完整文件引用",
"mode": "放大模式保存",
"mode.scale": "动态模式倍率保存",
"align": "像素对齐接口",
"enable_temporal_chunking": "时间分块保存(准确接口不存在)",
"force_unload": "卸载保存与类型冲突",
"precision": "计算精度保存",
"extra_steps": "低噪区附加步数接口",
"start_at_sigma": "低噪细化开始阈值",
"end_at_sigma": "低噪细化结束阈值",
"spacing": "尾段插值分布",
"step": "sigmas分割索引",
"max_resolution": "预览最大边像素",
"jpeg_quality": "预览JPEG质量",
"suppress_default_preview": "默认预览抑制保存",
"preview_frames": "预览帧数缓存",
"preview_fps": "预览播放帧率",
"tiny_vae": "预览VAE引用",
"preview": "额外预览空串",
"purge_cache": "缓存清理保存(实现未知)",
"purge_models": "模型清理保存(实现未知)",
"ref_image_size": "参考尺寸策略",
"attention": "注意力后端选择(准确0.33.2)",
"selection": "稀疏选择保存(实现未知)",
"selection.keep_percent": "嵌套选择保存值(单位未知)",
"start_percent": "开始保存值(单位未知)",
"end_percent": "结束保存值(单位未知)",
"dense_blocks": "完整稠密块保存字符串",
"min_tokens": "最小token保存值(实现未知)",
"extra_tokens": "额外token保存值(实现未知)",
"sink_conditioning": "条件保存选择(实现未知)",
"verbose": "详细信息保存开关(实现未知)",
"shift_video": "视频shift保存值(准确版本另列)",
"shift_audio": "音频shift保存值(准确版本另列)",
"color_space": "源额外色彩空间保存",
"format.codec": "源额外嵌套编码保存",
"image": "图像文件引用(本图准确版本另列)",
"upload": "上传辅助原保存值",
"upscale_method": "缩放插值方法",
"resolution_steps": "缩放对齐倍数",
"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)]
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="../t8-two-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",
"CR Prompt Text": "CR_PromptText",
"VHS_VideoCombine": "VideoCombine",
"LayerUtility: ImageScaleByAspectRatio V2": "ImageScaleByAspectRatioV2",
"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.2": "core0332",
"0.33.0": "core0330",
"0.34.2": "core0342",
"0.30.1": "core0301",
"b8b887cee3bb697c35002a29cc66bd35514b3ebe": "kjpatch",
"64f976fec8492ea4930c0e30c32369573189b23d": "layer",
"3c414d5d259ad4d00e392bdc7da8318f4c760ec8": "t8base",
"755b4554b1e4b437d4e36c8ec3ca2ed43bc71105": "t8two",
"4ee72c065db22c9d96c2427954dc69e7b908444b": "vhs",
"d78b780ae43fcf8c6b7c6505e6ffb4584281ceca": "cr",
}.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 in ["LoraLoaderModelOnly", "LoraLoaderBypassModelOnly"]:
parent = next(
p
for p in trees[e["local_file"]].body
if isinstance(p, ast.ClassDef)
and p.name
== (
"LoraLoaderBypass"
if cls == "LoraLoaderBypassModelOnly"
else "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(
n["widgets_values"].items()
if isinstance(n["widgets_values"], dict)
else zip(LAYOUTS[cls], n["widgets_values"], strict=True)
):
saved_key = (
name.replace("~", "~0").replace("/", "~1")
if isinstance(n["widgets_values"], dict)
else str(j)
)
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",
"videopreview",
]
(default, limits) = schemas.get(
(nid, name),
(
"未知:本准确类未给出该保存字段的独立schema默认",
"源保存位置与准确schema字段缺口分列,不认证后端执行映射",
),
)
unit = "无准确物理单位时只按原接口文本;源JSON类型与schema分列,不计算实际结果"
meta = prose.get("field_meta", {}).get(cls, {}).get(name, {})
default = meta.get("default", default)
limits = meta.get("limits", limits)
unit = meta.get("unit", unit)
if name in ["control_after_generate", "upload"]:
default = "前端辅助原值;准确frontend1.23.0条件参考,不当后端schema默认"
limits = "前端保存/恢复条件与本节点后端输入分开,不执行随机或上传"
unit = "前端辅助原JSON保存值,无物理单位"
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/{saved_key}",
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"]
)
)
boundaries = []
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) == 208 and len(comments) == 4
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="仅固定参考:两采样出口、两套T8准确版本与别名/旁路保存态分列;原null/缺键/历史对象保留,不认证参考、放大、采样或输出成功。",
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()
]
+ [
"旧115块6361保存条目/204注释冻结;新增208条目含3null和1完整历史对象/四Note,总116图6569条目/208注释仅参考。local_file以docs/hel-892/t8-two-document-evidence为基准。"
],
counts=dict(
saved_fields=208,
root_saved_fields=208,
internal_saved_fields=0,
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=94,
root_nodes=94,
internal_nodes=0,
physical_edges=95,
source_notes=4,
saved_objects=1,
history_objects=1,
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"],
)