"""Exact-source static editorial definition; 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 / "zimage-style-reference" PATHS = [ ( "example_ComfyUI_workflows/3-图像生成/Z" + "-Image/9_Z-Image+Flux2-Klein_风格重新编" + "辑.json" ) ] def canonical(value): return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode() LAYOUTS = { "llama_cpp_model_loader": [ "model", "mmproj", "chat_handler", "n_ctx", "vram_limit", "image_min_tokens", "image_max_tokens", ], "llama_cpp_instruct_adv": [ "preset_prompt", "custom_prompt", "system_prompt", "inference_mode", "max_frames", "max_size", "seed", "seed_control_candidate", "force_offload", "save_states", ], "LayerUtility: PurgeVRAM V2": ["purge_cache", "purge_models"], "VAELoader": ["vae_name"], "CLIPLoader": ["clip_name", "type", "device"], "UNETLoader": ["unet_name", "weight_dtype"], "ModelPatchLoader": ["name"], "ShowText|pysssss": ["saved_text_history"], "SetNode": ["alias"], "GetNode": ["alias"], "ZImageFunControlnet": ["strength"], "CLIPTextEncode": ["text"], "DifferentialDiffusion": ["strength"], "ImagePadForOutpaint": ["left", "top", "right", "bottom", "feathering"], "LayerUtility: ImageScaleByAspectRatio V2": [ "aspect_ratio", "proportional_width", "proportional_height", "fit", "method", "round_to_multiple", "scale_to_side", "scale_to_length", "background_color", ], "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", ], # Do not coerce flash_attn into BOOLEAN cache_model. "SeedVR2LoadDiTModel": ["saved_position_" + str(i) for i in range(7)], "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"], "LanPaint_MaskBlend": ["blend_overlap"], "ImageStitch": ["direction", "match_image_size", "spacing_width", "spacing_color"], "KSampler": [ "seed", "seed_control_candidate", "steps", "cfg", "sampler_name", "scheduler", "denoise", ], "LoadImage": ["image", "upload"], "ImageAndMaskPreview": ["mask_opacity", "mask_color", "pass_through"], } LAYOUTS.update( { "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"], "easy seed": ["seed", "seed_control_candidate", "saved_aux_null"], "LayerColor: Exposure": ["exposure"], "LayerUtility: ImageReel": [ "image1_text", "image2_text", "image3_text", "image4_text", "reel_height", "border", ], "LayerUtility: ImageReelComposit": [ "font_file", "font_size", "border", "color_theme", ], "AIO_Preprocessor": ["preprocessor", "resolution"], } ) LAYOUTS.update( { "ColorMatch": ["method", "strength", "multithread"], "UpscaleModelLoader": ["model_name"], "RandomNoise": ["noise_seed", "seed_control_candidate"], "KSamplerSelect": ["sampler_name"], "CFGGuider": ["cfg"], "Flux2Scheduler": ["steps", "width", "height"], "EmptyFlux2LatentImage": ["width", "height", "batch_size"], } ) LABELS = dict( model="模型引用", mmproj="视觉投影引用", chat_handler="视觉处理器", n_ctx="上下文限制", vram_limit="显存限制参考", image_min_tokens="图像token下限", image_max_tokens="图像token上限", purge_cache="清缓存保存开关", purge_models="卸载模型保存开关", vae_name="VAE引用", clip_name="文本模型引用", type="编码器类型", device="设备保存选择", unet_name="扩散模型引用", weight_dtype="权重类型", name="模型补丁引用", saved_text_history="完整历史展示文本", alias="具名别名字符串(恢复未知)", strength="强度保存值", text="完整条件文本缓存", left="左侧扩展", top="顶部扩展", right="右侧扩展", bottom="底部扩展", feathering="羽化保存值", aspect_ratio="比例保存选择", proportional_width="比例宽", proportional_height="比例高", fit="适配方式", method="插值选择", round_to_multiple="对齐倍数字符串", scale_to_side="缩放边选择", scale_to_length="缩放长度", background_color="背景颜色串", 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="保存文件前缀", blend_overlap="混合重叠保存值", preset_prompt="提示预设", custom_prompt="自定义提示原文", system_prompt="完整中文系统要求", inference_mode="推理模式保存选择", max_frames="帧数保存上限", max_size="尺寸保存上限", force_offload="强制卸载保存选择", save_states="保存上下文选择", direction="拼接方向", match_image_size="匹配尺寸选择", spacing_width="间距保存值", spacing_color="间距颜色", steps="采样步数保存值", cfg="引导保存值", sampler_name="采样器选择", scheduler="调度器选择", denoise="降噪保存值", image="图片文件引用", upload="上传保存线索", mask_opacity="遮罩叠加透明度", mask_color="遮罩颜色原串", pass_through="透传保存开关", ) LABELS.update( dict( add_noise="添加噪声保存选择", noise_seed="噪声种子保存缓存", start_at_step="开始步数保存值", end_at_step="结束步数保存值", return_with_leftover_noise="剩余噪声返回选择", width="宽度保存缓存", height="高度保存缓存", batch_size="批量保存值", saved_aux_null="完整null保存位置(控件身份未认证)", exposure="曝光保存int10(单位/算法未知)", image1_text="第一路字幕原文", image2_text="第二路字幕原文", image3_text="第三路空字幕", image4_text="第四路空字幕", reel_height="卷轴高度保存值", border="边框保存值", font_file="字体文件名(不证明已安装)", font_size="字体尺寸保存值", color_theme="文字主题选择", preprocessor="当前选择深度预处理器", resolution="预处理分辨率保存值", ) ) def provider(node): p = node.get("properties", {}) if p.get("cnr_id") == "comfy-core": return { "0.3.75": "root", "0.8.2": "core082", "0.9.1": "negative", "0.10.0": "upscale", }[p["ver"]] return {"comfyui-kjnodes": "kj", "rgthree-comfy": "rgthree"}.get(p.get("cnr_id")) def build(index=0): raw = (REPO / PATHS[index]).read_bytes() g = json.loads(raw) editorial = json.loads((OUT / "editorial.json").read_bytes()) scopes = [ ("", "", g), ("75", "/definitions/subgraphs/0", g["definitions"]["subgraphs"][0]), ("75:79", "/definitions/subgraphs/1", g["definitions"]["subgraphs"][1]), ] nodes = [ ( prefix + ":" + str(n["id"]) if prefix else str(n["id"]), ptr + f"/nodes/{i}", prefix or "root", n, ) for prefix, ptr, scope in scopes for i, n in enumerate(scope["nodes"]) ] 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-style-reference/" + e["local_file"], lines=[1, len(data.decode().splitlines())], claim="本图独立准确Git来源;静态读取未执行,许可不代表模型素材许可", ) ) class_refs = {} schemas = {} for nid, _ptr, _scope, node in nodes: key = provider(node) cls = node["type"] 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 = { "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, flow, boundaries = [], [], [], [] for nid, ptr, scope, n in nodes: cls = n["type"] effect = editorial[nid] + " 原始mode=" + str(n["mode"]) + ";活动保存态不等于可执行。" flow.extend( [ effect, nid + " 原属性 " + json.dumps(n.get("properties", {}), ensure_ascii=False), nid + " 原输入/输出 " + 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=scope, 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 boundary = nid in [ "75:70", "75:71", "75:72", "75:73", "75:74", ] and name in ["unet_name", "clip_name", "vae_name", "noise_seed", "text"] aux = name in ["seed_control_candidate", "saved_comparison_history"] default, limits = schemas.get( (nid, name), ( "未知:非独立后端参数或动态前端保存", "保存位置完整保留,不补默认或执行值", ), ) if name == "seed_control_candidate": default, limits = ( "前端辅助初始fixed;非后端输入", "fixed/increment/decrement/randomize;实际恢复未知,不执行", ) 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="源无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 "boundary_saved_cache" if boundary else "linked_saved_cache" if linked else "saved_reference", unit={ "width": "图像宽度像素;外线覆盖与缓存分开", "height": "图像高度像素;外线覆盖与缓存分开", "steps": "调度/采样步数接口,不承诺实际完整执行", "batch_size": "批次数量", "megapixels": "本版目标像素数=保存值×1024×1024,不是固定宽高", "resolution_steps": "宽高取整步进像素", "seed": "整数种子参考,不执行", "noise_seed": "整数种子参考,边界恢复未知", "cfg": "条件引导系数,非物理单位", "denoise": "降噪比例接口", "strength": "匹色插值系数,非物理单位", "multithread": "布尔开关;实际线程条件依批次", "text": "完整作者文本,非效果保证", "filename_prefix": "文件名前缀字符串", "saved_comparison_history": "完整历史列表,仅文本", }.get(name, "枚举/引用/前端保存参考,无物理单位;目标环境未核"), schema_default=default, limits=limits, effect=effect, execution_note="仅静态参考;不构造prompt,不执行上游、模型、媒体、随机、线程、设备或清理;转换/执行资格不变。", evidence=class_refs[nid], ) ) for prefix, ptr, scope in scopes: flow.extend( (prefix or "root") + " 作用域物理边 " + json.dumps(e, ensure_ascii=False) for e in scope["links"] ) if prefix: hostid = 75 if prefix == "75" else 79 parent = g if hostid == 75 else g["definitions"]["subgraphs"][0] host = next(n for n in parent["nodes"] if n["id"] == hostid) b = dict( scope=prefix, definition_pointer=ptr, **{ k: scope[k] for k in [ "id", "inputNode", "outputNode", "inputs", "outputs", "widgets", ] }, host_saved=host["widgets_values"], proxyWidgets=host["properties"]["proxyWidgets"], host_inputs=host["inputs"], ) boundaries.append(b) flow.append("原定义/宿主边界 " + json.dumps(b, ensure_ascii=False)) for (nid, name), (default, limits) in schemas.items(): flow.append( f"节点{nid}准确具名schema {name}:default={default};{limits}。" "仅接口参考,不补缺保存或执行默认。" ) flow += [ ( "根15节点17边;外层15节点28含边界连线;内层3节点8含边界连线" + "。全mode0;根24+内部20=44位置,43标量+1完整历史列表" + ",无Note/具名保存。五个边界缓存仅代理线索,四个尺寸缓存才有具体" + "尺寸输出外线覆盖。" ), ( "frontendVersion准确1.37.11,workflowR" + "endererVersion LG独立;宿主proxyWidgets" + "/UE/动态恢复未知。跨作用域相同数字边号不合并,不构造promot" + "ed值或扁平prompt。" ), ( "ColorMatch准确包装:strength=0直接返回targe" + "t;当前保存1,调用ColorMatcher.transfer(sr" + "c=target,ref=ref,method=mkl)。stren" + "gth不等1才插值;异常逐图回退target。CPU/numpy,m" + "ultithread且batch>1才线程池,最后float32 c" + "lamp0..1。requirements未固定color-matc" + "her版本,底层算法/效果/环境未知。" ), ( "准确core0.10.0超分采用tile512/overlap32," + "OOM减半低于128重抛,finally移CPU,结果clamp0." + ".1。spandrel模型描述符/倍率来自加载对象,不由文件名认证;" + "未执行加载、OOM、GPU或清内存。" ), ( "Save109 core0.3.75与Save111 core0.8" + ".2准确RETURN_TYPES=(),返回ui.images;两源" + "均声明IMAGE/images/links:null,协议差异逐个保" + "留,不改成outputs=[]。rgthree准确继承运行宿主Pre" + "viewImage,compare_images只返回ui.a_im" + "ages/b_images;自身无RETURN_TYPES覆盖,目标" + "宿主身份未知,源IMAGE出口不认证实际结果。" ), ( "比较器同提交JS onExecuted/序列化与Slide属性仅静态" + "参考;完整历史列表中的URL仅文本,不加载Image或请求/view" + "。不把历史当当前产物。" ), ( "本图没有LoadImage/MASK/LoRA;没有SeedVR/A" + "IO/LLM/Easy/Reel适用来源。历史SeedVR误取整包及" + "删除记录不变,不复取。许可原文仅对应源码,模型/素材/设备/目标安装" + "/真实效果未知。" ), ( "FAQ:初始图来自照片吗?不是,根空latent文生图。参考late" + "nt是否采样起点?不是,内层VAEEncode追加参考条件,外层Em" + "ptyFlux2Latent才给采样。B是否匹色前图?不是,B为匹色" + "后再超分。保持内容不变是否保证?只是完整作者提示意图。" ), ] overview = ( "先由Z-Image空latent文生图并保存原始图,再以生成图作为F" + "lux2参考条件做风格编辑;原图作颜色参考、编辑图作匹色目标,匹色后" + "模型超分,再保存并与原图比较。两层子图与两套VAE分开,四个尺寸缓存" + "有明确外线覆盖,五个代理缓存的宿主恢复未知;内容保持只是作者意图,当" + "前仅参考。" ) assert len(fields) == 44 and sum(f["scope"] == "root" for f in fields) == 24 assert sum(f["role"] == "linked_saved_cache" for f in fields) == 4 assert sum(f["role"] == "boundary_saved_cache" for f in fields) == 5 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() ] + [ ( "旧68块2870位置+75注释逐对象冻结;本批44位置0注释,总69" + "图2914位置+75注释仅参考。来源local_file以docs/" + "hel-892/zimage-style-document-evid" + "ence为基准。" ) ], counts=dict( saved_fields=44, root_saved_fields=24, internal_saved_fields=20, linked_saved_fields=4, boundary_saved_fields=5, frontend_only=sum(f["role"] == "frontend_reference_only" for f in fields), source_nodes=33, root_nodes=15, internal_nodes=18, physical_edges=53, source_notes=0, history_objects=1, final_scalars=0, final_prompt_constructed=False, ), fields=fields, sources=sources, comments=[], flow=flow, flow_evidence=list(range(len(sources))), zero_saved_nodes=empty, boundaries=boundaries, steps=[ overview, "阅读1:逐44位置核完整中文提示/历史列表/原类型,来源准确版本不互借,不请求媒体。", "阅读2:沿两层作用域核参考条件与空latent、四尺寸覆盖及五代理缓存,边界不等于实际恢复。", "阅读3:原图先保存,匹色后超分再保存/比较;停用/未检查/空时间戳不变,155定稿与必要实跑未完成。", ], )