Files
aigc-home/docs/hel-892/zimage-hd-document-evidence/build_definition.py
T
2026-10-31 16:53:27 +08:00

466 lines
20 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-source static editorial definition; no upstream imports 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 / "zimage-hd-reference"
PATHS = [
(
"example_ComfyUI_workflows/3-图像生成/Z"
+ "-Image/10_Z_Image双采样+Fluax2-klein修"
+ "复-高清直出.json"
)
]
def canonical(v):
return json.dumps(v, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
LAYOUTS = {
"VAELoader": ["vae_name"],
"CLIPLoader": ["clip_name", "type", "device"],
"UNETLoader": ["unet_name", "weight_dtype"],
"SetNode": ["alias"],
"GetNode": ["alias"],
"CLIPTextEncode": ["text"],
"SeedVR2VideoUpscaler": [
"seed",
"seed_control_candidate",
"resolution",
"max_resolution",
"batch_size",
"uniform_batch_size",
"color_correction",
"temporal_overlap",
"prepend_frames",
"input_noise_scale",
"latent_noise_scale",
"offload_device",
"enable_debug",
],
"SeedVR2LoadDiTModel": [
"saved_position_0",
"saved_position_1",
"saved_position_2",
"saved_position_3",
"saved_position_4",
"saved_position_5",
"saved_position_6",
],
"SeedVR2LoadVAEModel": [
"model",
"device",
"encode_tiled",
"encode_tile_size",
"encode_tile_overlap",
"decode_tiled",
"decode_tile_size",
"decode_tile_overlap",
"tile_debug",
"offload_device",
"cache_model",
],
"Image Comparer (rgthree)": ["saved_comparison_history"],
"ImageScaleToTotalPixels": ["upscale_method", "megapixels", "resolution_steps"],
"SaveImage": ["filename_prefix"],
"KSamplerAdvanced": [
"add_noise",
"noise_seed",
"seed_control_candidate",
"steps",
"cfg",
"sampler_name",
"scheduler",
"start_at_step",
"end_at_step",
"return_with_leftover_noise",
],
"EmptyLatentImage": ["width", "height", "batch_size"],
"ColorMatch": ["method", "strength", "multithread"],
"RandomNoise": ["noise_seed", "seed_control_candidate"],
"KSamplerSelect": ["sampler_name"],
"CFGGuider": ["cfg"],
"Flux2Scheduler": ["steps", "width", "height"],
"EmptyFlux2LatentImage": ["width", "height", "batch_size"],
"LoraLoaderModelOnly": ["lora_name", "strength_model"],
"ModelSamplingAuraFlow": ["shift"],
"INTConstant": ["value"],
"CR Text": ["text"],
"LayerUtility: PurgeVRAM": ["purge_cache", "purge_models"],
"ImageSharpen": ["sharpen_radius", "sigma", "alpha"],
}
LABELS = {
"model": "模型引用",
"purge_cache": "清缓存保存开关",
"purge_models": "卸载模型保存开关",
"vae_name": "VAE引用",
"clip_name": "文本模型引用",
"type": "编码器类型",
"device": "设备保存选择",
"unet_name": "扩散模型引用",
"weight_dtype": "权重类型",
"alias": "具名别名字符串(恢复未知)",
"strength": "强度保存值",
"text": "完整条件文本缓存",
"method": "插值选择",
"seed": "种子保存值",
"seed_control_candidate": "种子辅助候选(非独立后端参数)",
"resolution": "预处理分辨率保存值",
"max_resolution": "最大分辨率",
"batch_size": "批量保存值",
"uniform_batch_size": "批次一致保存选择",
"color_correction": "色彩校正选择",
"temporal_overlap": "时间重叠",
"prepend_frames": "前置帧保存值",
"input_noise_scale": "输入噪声强度",
"latent_noise_scale": "latent噪声强度",
"offload_device": "卸载设备选择",
"enable_debug": "调试保存选择",
"encode_tiled": "编码分块开关",
"encode_tile_size": "编码块尺寸",
"encode_tile_overlap": "编码块重叠",
"decode_tiled": "解码分块开关",
"decode_tile_size": "解码块尺寸",
"decode_tile_overlap": "解码块重叠",
"tile_debug": "分块调试字符串",
"cache_model": "模型缓存保存选择",
"saved_comparison_history": "完整比较历史列表(仅文本)",
"upscale_method": "缩放插值",
"megapixels": "百万像素保存值",
"resolution_steps": "分辨率步进",
"filename_prefix": "保存文件前缀",
"steps": "采样步数保存值",
"cfg": "引导保存值",
"sampler_name": "采样器选择",
"scheduler": "调度器选择",
"add_noise": "添加噪声保存选择",
"noise_seed": "噪声种子保存缓存",
"start_at_step": "开始步数保存值",
"end_at_step": "结束步数保存值",
"return_with_leftover_noise": "剩余噪声返回选择",
"width": "宽度保存缓存",
"height": "高度保存缓存",
"shift": "AuraFlow shift保存值",
"value": "整数常量保存值",
"lora_name": "LoRA文件引用",
"strength_model": "LoRA模型强度保存值",
"sharpen_radius": "锐化半径",
"sigma": "高斯sigma",
"alpha": "锐化alpha",
}
def provider(node):
p = node.get("properties", {})
cnr = p.get("cnr_id")
v = p.get("ver")
if cnr == "comfy-core":
return "core" + v.replace(".", "")
if cnr == "comfyui-kjnodes":
return "kjpkg" if v == "1.4.7" else "kjold"
if cnr == "rgthree-comfy":
return "rgpkg" if v == "1.0.2606200020" else "rgactive"
return {
"ComfyUI_Comfyroll_CustomNodes": "cr",
"seedvr2_videoupscaler": "seed",
"comfyui-workflow-encrypt": "encryptpkg",
}.get(cnr)
def build(index=0):
raw = (REPO / PATHS[index]).read_bytes()
g = json.loads(raw)
editorial = json.loads((OUT / "editorial.json").read_bytes())
manifest = json.loads((REF / "sources.json").read_bytes())["sources"]
sources = []
for e in manifest:
data = (REF / e["local_file"]).read_bytes()
assert hashlib.sha256(data).hexdigest() == e["sha256"]
sources.append(
dict(
e,
local_file="../zimage-hd-reference/" + e["local_file"],
lines=[1, len(data.decode().splitlines())],
claim="本图独立准确来源原文;Git与发布成员分列,未执行",
)
)
class_refs = {}
schemas = {}
for node in g["nodes"]:
key = provider(node)
cls = node["type"]
nid = str(node["id"])
refs = []
for i, e in enumerate(manifest):
if e["id"] != key or not e["file"].endswith(".py"):
continue
data = (REF / e["local_file"]).read_bytes()
try:
tree = ast.parse(data)
except SyntaxError:
continue
symbol = {
"CR Text": "CR_Text",
"ImageSharpen": "Sharpen",
"easy seed": "easySeed",
"LayerUtility: ImageReel": "ImageReel",
"LayerUtility: ImageReelComposit": "ImageReelComposit",
"ShowText|pysssss": "ShowText",
"Image Comparer (rgthree)": "RgthreeImageComparer",
"LayerUtility: ImageScaleByAspectRatio V2": "ImageScaleByAspectRatioV2",
"LayerUtility: PurgeVRAM V2": "PurgeVRAM_V2",
}.get(cls, cls)
for c in ast.walk(tree):
if isinstance(c, ast.ClassDef) and c.name == symbol:
sources.append(
dict(
sources[i],
lines=[c.lineno, c.end_lineno],
claim="本图准确声明类实现;保存索引映射/运行恢复仍需区分",
)
)
refs.append(len(sources) - 1)
for d in ast.walk(c):
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 a in v.elts[1:]:
if isinstance(a, ast.Dict):
for dk, dv in zip(a.keys, a.values, strict=True):
if (
isinstance(dk, ast.Constant)
and dk.value == "default"
):
default = ast.unparse(dv)
schemas[nid, k.value] = (default, ast.unparse(v))
for call in ast.walk(c):
if (
isinstance(call, ast.Call)
and isinstance(call.func, ast.Attribute)
and call.func.attr == "Input"
and call.args
and isinstance(call.args[0], ast.Constant)
and isinstance(call.args[0].value, str)
):
name = call.args[0].value
default = next(
(ast.unparse(k.value) for k in call.keywords if k.arg == "default"),
"无显式default;不从方法缺省补值",
)
schemas[nid, name] = (default, ast.unparse(call))
# Registration and complete relevant original texts remain visible even for missing class.
class_refs[nid] = refs + [
i
for i, e in enumerate(manifest)
if e["id"] == key and (e["file"].endswith("__init__.py") or not refs)
]
fields, empty, comments, flow = [], [], [], []
for i, n in enumerate(g["nodes"]):
nid = str(n["id"])
cls = n["type"]
ptr = f"/nodes/{i}"
if cls == "Note":
comments.append(
dict(
node_id=nid,
pointer=ptr + "/widgets_values/0",
text=n["widgets_values"][0],
meaning="作者显存建议原文;Note自身mode4,不能当已核设备/块交换或执行命令。",
evidence=[],
)
)
continue
effect = (
editorial[nid]
+ " 原始mode="
+ str(n["mode"])
+ (";旁路保存态不模拟穿透。" if n["mode"] == 4 else ";活动保存态不证明可执行。")
)
flow.extend(
[
effect,
nid + " 原属性 " + json.dumps(n.get("properties", {}), ensure_ascii=False),
nid
+ " 原输入/输出(缺键/null/[]分别保留) "
+ json.dumps({k: n[k] for k in ["inputs", "outputs"]}, 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 "empty_list",
effect=effect,
)
)
continue
for j, (name, value) in enumerate(zip(LAYOUTS[cls], n["widgets_values"], strict=True)):
inp = next((k for k, x in enumerate(n["inputs"]) if x["name"] == name), None)
linked = inp is not None and n["inputs"][inp].get("link") is not None
default, limits = schemas.get(
(nid, name),
(
"未知:没有核准独立接口/位置映射",
"源值完整保留;不借类名、端口顺序或近版补默认范围",
),
)
unit = {
"width": "宽度像素接口;缓存与外线分列",
"height": "高度像素接口;缓存与外线分列",
"steps": "调度步数接口,不保证实际完整步数",
"start_at_step": "采样开始步序接口",
"end_at_step": "采样结束步序接口",
"megapixels": "本版目标像素数系数×1024×1024;不试算",
"resolution_steps": "宽高取整步进像素",
"resolution": "Seed短边目标像素接口;外线覆盖保存缓存",
"max_resolution": "Seed任一边像素上限接口,0为不限制",
"text": "完整作者文本/空缓存,不当产物保证",
"filename_prefix": "完整日期格式字符串,仅保存参考",
"saved_comparison_history": "完整历史列表,仅纯文本",
"strength_model": "LoRA模型系数,无物理单位",
"shift": "AuraFlow采样参数,无物理单位",
"sharpen_radius": "卷积半径像素接口",
"sigma": "高斯核参数,无独立物理单位",
"alpha": "锐化系数,无物理单位",
"seed": "种子整数参考,不执行随机",
"noise_seed": "种子整数参考,不执行随机",
"batch_size": "批次数量接口",
}.get(name, "保存枚举/引用/开关或系数;准确接口条件见来源,目标环境未知")
if cls in ["LayerUtility: PurgeVRAM", "ColorMatch", "SetNode", "GetNode"]:
default, limits, unit = (
"未知:准确实现身份或类注册未核准",
"仅源值、原类型与端口/属性线索,不认证映射或运行语义",
"未知:没有准确实现依据",
)
if name.startswith("saved_position_"):
default, limits, unit = (
"未知:七保存位置不按八接口强行映射",
"准确cache_model是BOOLEAN,但保存索引5保存字符串sdpa;不规范化或改名",
"完整位置原值/类型;映射未知",
)
if name == "seed_control_candidate":
default, limits = (
"准确前端辅助候选初始fixed,非独立后端输入",
"fixed/increment/decrement/randomize;恢复与执行时序未知,不运行",
)
aux = name in ["seed_control_candidate", "saved_comparison_history"]
fields.append(
dict(
node_id=nid,
definition_node_id=nid,
scope="root",
class_type=cls,
field=name,
label=(name + "保存值(语义未知)")
if cls in ["ColorMatch", "LayerUtility: PurgeVRAM"]
else "Seed短边分辨率保存缓存"
if cls == "SeedVR2VideoUpscaler" and name == "resolution"
else LABELS.get(name, "保存位置" + str(j) + "(映射未核准)"),
pointer=f"{ptr}/widgets_values/{j}",
value=value,
json_type=type(value).__name__,
named_pointer="源无widgets_values_named,不构造具名保存指针",
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 "linked_saved_cache"
if linked
else "saved_layout_reference",
schema_default=default,
limits=limits,
unit=unit,
effect=effect,
evidence=class_refs[nid],
execution_note="仅静态参考,不构造prompt或执行上游/插件/模型/GPU/媒体/种子/别名/旁路/组开关/缓存显存;转换执行资格不变。",
)
)
for (nid, name), (default, limits) in schemas.items():
flow.append(
f"节点{nid}准确具名schema {name}:default={default};{limits}。"
"仅接口参考,不按位置认证恢复或补缺保存值。"
)
flow.extend("根物理边 " + json.dumps(e, ensure_ascii=False) for e in g["links"])
flow.extend(json.loads((OUT / "findings.json").read_bytes())["findings"])
overview = (
"主链以Z-Image Base与Turbo两段采样生成并解码保存;常"
+ "量外线覆盖宽高、步数、两处起止和正向提示缓存。Flux2参考修复、匹"
+ "色锐化及SeedVR2均为旁路保存态,不能称可靠高清直出;参考条件l"
+ "atent与采样空latent分开,所有别名、旁路和组开关恢复未知。"
)
assert len(fields) == 114 and len(comments) == 1
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="仅参考:旁路/别名/UE恢复、ColorMatch注册、PurgeVRAM身份及Seed保存布局有缺口,未核环境或真实效果;转换执行关闭。",
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()
]
+ [
(
"旧69块2914位置+75注释逐对象冻结,本批114位置+1注释,总"
+ "70图3028位置+76注释仅参考;local_file以docs/"
+ "hel-892/zimage-hd-document-evidenc"
+ "e为基准。"
)
],
counts=dict(
saved_fields=114,
root_saved_fields=114,
internal_saved_fields=0,
linked_saved_fields=sum(f["role"] == "linked_saved_cache" for f in fields),
frontend_only=sum(f["role"] == "frontend_reference_only" for f in fields),
source_nodes=56,
root_nodes=56,
internal_nodes=0,
physical_edges=66,
source_notes=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=[],
steps=[
overview,
"阅读1:完整正负/参考中文、Note84、精确浮点和两历史只文本保留,七主链覆盖/四Flux尺寸/一Seed覆盖分别核,不请求媒体。",
(
"阅读2:两LoRA mode4,不保证模型贯通;12→13接力与se"
+ "ed/add_noise/leftover分别核,主解码先保存,不称"
+ "完整12步实跑。"
),
"阅读3:Flux参考条件与空latent分开,ColorMatch准确提供方类缺失不借KJ;锐化后保存/比较/Seed缩小各路径明确。",
(
"阅读4:Save0.27.1实际IMAGE返回与0.3.75空返回独"
+ "立;保持停用未检查/空时间戳,155最终定稿/可靠转换/环境核对/必"
+ "要实跑未完成。"
),
],
)