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

627 lines
25 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, exact-source editorial definition; never import or 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-wash-reference"
PATHS = ["example_ComfyUI_workflows/3-图像生成/Z-Image/8_Z-image+Controlnet_姿势控制-洗图.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"],
}
)
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", {})
cnr = p.get("cnr_id")
ver = p.get("ver")
if cnr == "comfy-core":
return "core" + ver.replace(".", "") if ver != "0.5.0" else "core050"
return {
"comfyui_layerstyle": "reel"
if ver == "89014d833d2ad0998d724090eff1456692692a1d"
else "layer",
"comfyui_controlnet_aux": "aux",
"comfyui-easy-use": "easy",
"llama-cpp_vllm": "llama",
"comfyui-custom-scripts": "show",
"LanPaint": "lanpaint",
"comfyui-kjnodes": "kj",
"rgthree-comfy": "rgactive" if str(node["id"]) == "330" else "rgbypass",
"seedvr2_videoupscaler": "seedpkg" if ver == "2.5.22" else "seed",
}.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-wash-reference/" + e["local_file"],
lines=[1, len(data.decode().splitlines())],
claim="本图独立准确来源原文;Git/发布包身份与适用限制分列,静态读取未执行",
)
)
# Class-level spans where exact symbols exist; schema text is quoted by AST, not executed.
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 = {
"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)
]
schemas["303", "preprocessor"] = (
"'none'",
"INPUT.COMBO(PREPROCESSOR_OPTIONS, default='none');"
+ "动态枚举来自准确wrapper注册,不能推目标安装",
)
schemas["303", "resolution"] = (
"512",
"INPUT.RESOLUTION(default=512,min=64,max=16384,step=64),源码接口条件,不认证当前目标效果",
)
class_refs["303"] += [
i
for i, e in enumerate(manifest)
if e["id"] == "aux" and e["file"] in ["utils.py", "node_wrappers/depth_anything.py"]
]
ns = {n["id"]: n for n in g["nodes"]}
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="完整作者提示生图偏暗需调曝光;不证明单位/算法或调节已执行。",
evidence=[],
)
)
continue
if cls in ["SetNode", "GetNode"]:
alias = n["widgets_values"][0]
effect = (
f"{nid} {cls}仅aux字符串身份,保存别名“{alias}”;"
"无准确实现/版本,不能从别图赋予KJ身份。"
"模型输出/patch/VAE/CLIP/加载图像/反推提示词/洗图输出/SeedVR 修复各自独立;"
"同字符串仅配对线索,不造跨别名边、不补值、不认证加载模型已贯通。"
"别名恢复次序未知,物理入出边分别保留。"
)
elif cls == "Reroute":
effect = (
f"{nid} Reroute缺widgets_values键,不能当[]/null;"
"仅保留逐条物理边,不执行恢复或模拟透传。"
)
else:
effect = editorial[nid]
effect += (
" 原始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)
default, limits = schemas.get(
(nid, name),
(
"未知:准确schema无此独立控件或注册/映射未核准",
"未知:保存位置只为线索,不按索引认证范围/默认/运行参数",
),
)
# SeedVR2 exact release positional layout remains explicitly unresolved.
extra = ""
if name.startswith("saved_position_"):
extra = (
f" 第{j}保存位置原值与原类型独立保留;"
"8个具名输入含torch_compile_args,七保存位置不能硬映射为其顺序;"
"准确发布接口对照见流程。"
)
if name == "seed_control_candidate":
extra = " fixed/randomize只保存字符串及前端辅助候选,不作为独立后端输入或执行随机。"
if name in ["saved_comparison_history", "saved_text_history"]:
extra = (
" 历史完整保留为一个保存位置,仅纯文本,不加载或请求历史图片,不认证当前内容。"
)
fields.append(
dict(
node_id=nid,
definition_node_id=nid,
scope="root",
class_type=cls,
field=name,
label=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 name
in [
"upload",
"seed_control_candidate",
"saved_comparison_history",
"saved_text_history",
]
else "saved_reference",
unit="未知:679未声明准确实现身份,仅源值/类型/端口线索,不认证单位"
if nid == "679"
else "准确接口文本条件;源值/类型不规范化,不试算或认证目标环境",
schema_default=default,
limits=limits,
effect=effect + extra,
execution_note="仅静态参考,不构造prompt,不执行上游/模型/媒体/遮罩/种子/别名/清理;转换与执行资格不变。",
evidence=class_refs[nid],
)
)
for (nid, name), (default, limits) in schemas.items():
flow.append(
f"节点{nid}准确schema具名接口{name}:default={default};原定义{limits}。仅接口参考,不补缺保存、不按索引认证,不执行默认。"
)
for edge in g["links"]:
eid, a, ao, z, zi, kind = edge
flow.append(
f"物理边{eid}:{a}.{ns[a]['outputs'][ao]['name']}[{ao}] → "
f"{z}.{ns[z]['inputs'][zi]['name']}[{zi}] 类型{kind};"
"仅原件连线,不补别名或旁路边。"
)
flow += [
(
"独立原字节盘点66根节点63物理边,无子图/具名保存,56 mo"
"de0/10 mode4。138位置=136标量(含完整null"
")+两完整比较历史列表;Note681完整11字符另列。311/"
"322/617/294/233五[]零位置,Reroute/24"
"2Bypasser/682Label缺键独立保留,不混同outp"
"uts/null。"
),
(
"frontendVersion准确1.23.0,同树锁/Lite"
"Graph仅静态参考;LG是workflowRendererVe"
"rsion,0246/UE/tab都是独立保存态,宿主动态控件、"
"seed辅助、别名与组开关恢复未知,不借别版认证。"
),
(
"FAQ:已选姿态/骨架控制吗?图名写姿势控制,但303当前值是D"
"epthAnythingPreprocessor,深度条件不等于"
"姿态。初始latent是原图吗?675 EmptyLatentI"
"mage经3408供313,没有原图VAEEncode/nois"
"e_mask。两段都有ControlNet吗?只有313接656"
",314模型是Get290直出支路。9528是最终种子吗?外线覆"
"盖两个缓存只是物理事实,easy/前端辅助/UE调用时序未知,不"
"执行或认证。曝光10是什么单位?679无身份,未知,不能称EV或"
"已核亮度。拼图第二路是什么?Get230 SeedVR 修复,不"
"是主洗图输出,字幕意图与实际别名分开。历史是当前产物吗?不是,只"
"文本不请求。"
),
]
extra = REF / "findings.json"
if extra.exists():
flow += json.loads(extra.read_bytes())["findings"]
overview = (
"这张图当前把原图送入DepthAnything深度预处理并缩放,尺寸外线覆盖空latent的宽高,"
"再用两段采样和解码/曝光支路保存洗图。图名虽写姿势控制,当前不是已选姿态或骨架;"
"只有第一段接ControlNet,第二段模型来自另一条Get支路。easy seed外线覆盖缓存与"
"最终执行种子分开,679曝光无实现身份。所有Set/Get恢复次序未知,不能称模型可靠贯通"
"或自动提示已生效;旁路超分和字幕拼图不是已验证产物,当前仅参考。"
)
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()
]
+ [
(
"旧67块2732位置+74注释逐对象冻结;本批138位置+1注释,68图28"
"70位置+75注释仅参考;local_file以docs/hel-892/z"
"image-wash-document-evidence为基准。"
)
],
counts=dict(
saved_fields=len(fields),
root_saved_fields=len(fields),
internal_saved_fields=0,
linked_saved_fields=sum(
1
for f in fields
if f["input_pointer"].startswith("/")
and next(n for n in g["nodes"] if str(n["id"]) == f["node_id"])["inputs"][
int(f["input_pointer"].rsplit("/", 1)[1])
].get("link")
is not None
),
frontend_only=sum(f["role"] == "frontend_reference_only" for f in fields),
source_nodes=66,
root_nodes=66,
internal_nodes=0,
physical_edges=63,
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:核138保存位置、Note681、完整系统提示/两历史及准确来源;618的null与辅助候选独立保留,禁止请求历史URL或媒体。",
(
"阅读2:沿143→303深度→321,image给656,wid"
"th/height给675→313;313控制模型与314直接G"
"et模型分别核,618外线覆盖noise_seed缓存但时序未知"
"。"
),
(
"阅读3:313→319→314→294解码→679未知曝光→29"
"5/330A/Set297;比较B和LLM图像均需Get恢复,2"
"31第二路是SeedVR 修复而非主洗图输出,不保证曝光或超分效"
"果。"
),
(
"阅读4:widgets_values=[]只表示零保存位置,Pr"
"eview/Save及两比较器原声明出口与准确返回差异逐节点保留"
";停用/未检查/空时间戳不变,155定稿/可靠转换/环境核对/必"
"要实跑未完成。"
),
],
)