Files
aigc-home/docs/hel-892/zimage-seed8k-document-evidence/build_definition.py
T
2026-10-31 17:54:19 +08:00

463 lines
21 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 nested upscale 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 / "zimage-seed8k-reference"
PATHS = [
(
"example_ComfyUI_workflows/3-图像生成/Z"
+ "-Image/12_Z_Image_Tubro_文生图_SeedVR2高"
+ "清放大8K.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"],
"LoraLoaderModelOnly": ["lora_name", "strength_model"],
"CLIPTextEncode": ["text"],
"CR Prompt Text": ["prompt"],
"SetNode": ["alias"],
"GetNode": ["alias"],
"EmptyLatentImage": ["width", "height", "batch_size"],
"KSampler": [
"seed",
"seed_control_candidate",
"steps",
"cfg",
"sampler_name",
"scheduler",
"denoise",
],
"SaveImage": ["filename_prefix"],
"Image Comparer (rgthree)": ["saved_comparison_history"],
"LayerUtility: PurgeVRAM": ["purge_cache", "purge_models"],
"VAEDecodeTiled": ["tile_size", "overlap", "temporal_size", "temporal_overlap"],
"VAEEncodeTiled": ["tile_size", "overlap", "temporal_size", "temporal_overlap"],
"ResizeImageMaskNode": ["resize_type", "resize_type.multiplier", "scale_method"],
"SeedVR2PostProcessing": ["color_correction_method"],
"bb1cc547-34f0-4c5a-a987-dbaad079b39d": [
"resize_type.multiplier",
"seed",
"steps",
"cfg",
"sampler_name",
"scheduler",
"denoise",
"unet_name",
"vae_name",
"color_correction_method",
"temporal_size",
],
}
LABELS = {
"vae_name": "VAE文件引用",
"clip_name": "文本模型引用",
"type": "编码器类型",
"device": "设备选择",
"unet_name": "扩散模型引用",
"weight_dtype": "权重类型",
"lora_name": "LoRA文件引用",
"strength_model": "LoRA模型强度",
"text": "完整编码文本缓存",
"prompt": "完整作者文本(末尾换行保留)",
"alias": "保存别名(未认证恢复)",
"width": "latent宽度",
"height": "latent高度",
"batch_size": "latent批量",
"seed": "种子保存值",
"seed_control_candidate": "种子前端辅助候选",
"steps": "步数保存值",
"cfg": "引导系数",
"sampler_name": "采样器",
"scheduler": "调度器",
"denoise": "降噪系数",
"filename_prefix": "正式保存前缀",
"saved_comparison_history": "完整比较历史列表(仅文本)",
"purge_cache": "清理缓存保存开关",
"purge_models": "卸载模型保存开关",
"tile_size": "空间分块尺寸",
"overlap": "空间重叠",
"temporal_size": "时间分块尺寸",
"temporal_overlap": "时间重叠",
"resize_type": "动态缩放模式",
"resize_type.multiplier": "缩放乘数",
"scale_method": "插值方法",
"color_correction_method": "匹色保存选择",
}
NOTE_MEANING = {}
def provider(node):
p = node.get("properties", {})
if p.get("cnr_id") == "comfy-core":
return "core" + p["ver"].replace(".", "")
return {
"rgthree-comfy": "rgthree",
"ComfyUI_Comfyroll_CustomNodes": "cr",
"comfyui_layerstyle": "layer",
}.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), ("110", "/definitions/subgraphs/0", g["definitions"]["subgraphs"][0])]
nodes = [
(pre + ":" + str(n["id"]) if pre else str(n["id"]), ptr + f"/nodes/{i}", pre or "root", n)
for pre, ptr, sg in scopes
for i, n in enumerate(sg["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-seed8k-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 = {
"CR Prompt Text": "CR_PromptText",
"LayerUtility: PurgeVRAM": "PurgeVRAM",
"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 nid, ptr, scope, n in nodes:
cls = n["type"]
if cls == "MarkdownNote":
comments.append(
dict(
node_id=nid,
pointer=ptr + "/widgets_values/0",
text=n["widgets_values"][0],
meaning=NOTE_MEANING[nid],
evidence=[],
)
)
continue
effect = editorial[nid] + " 原始mode=" + str(n["mode"]) + ",活动保存态不等于可靠执行。"
flow.extend(
[
effect,
nid + " 原属性 " + json.dumps(n.get("properties", {}), ensure_ascii=False),
nid
+ " 原具名保存(缺键与空对象分列,仅文本) "
+ (
json.dumps(n["widgets_values_named"], ensure_ascii=False)
if "widgets_values_named" in n
else "missing"
),
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=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)
boundary = (
nid.startswith("110:")
and inp is not None
and n["inputs"][inp].get("link") in [50, 51, 52, 53, 54, 55, 56, 57, 58, 64, 65]
)
linked = inp is not None and n["inputs"][inp].get("link") is not None
aux = name in ["upload", "seed_control_candidate", "saved_comparison_history", "alias"]
default, limits = schemas.get(
(nid, name), ("无准确独立后端widget默认", "完整保存位置/前端辅助,不补运行值")
)
if name == "seed_control_candidate":
default, limits = (
"准确frontend1.23.0辅助缺省randomize,保存fixed与函数缺省/恢复顺序分开",
(
"fixed/increment/decrement/ra"
+ "ndomize;函数缺省与节点调用/恢复顺序分开,不执行"
),
)
unit = {
"largest_size": "最长边目标像素;按本版分支设置,非仅超限截断",
"scale_by": "图像宽高乘数,非denoise",
"steps": "采样步数接口,不保证实际完整执行",
"cfg": "引导系数,无物理单位",
"denoise": "采样降噪系数,与0.5图像缩放分开",
"text": "完整作者文本/空串,非产物保证",
"shift": "AuraFlow采样参数,无物理单位",
"seed": "整数种子保存值,非最终执行seed",
"filename_prefix": "保存文件前缀字符串",
"saved_comparison_history": "完整A/B历史列表,仅文本,不访问/view",
"width": "空latent请求宽度,像素;非最终输出保证",
"height": "空latent请求高度,像素;非最终输出保证",
"batch_size": "图像批量数量,非帧率或分辨率",
"strength_model": "LoRA模型权重强度,无物理单位;兼容与效果未知",
"tile_size": "空间分块尺寸接口,像素;准确实现可调整,不保证显存",
"overlap": "空间分块重叠接口,像素;非时间重叠",
"temporal_size": "时间分块尺寸接口,非秒;准确VAE/模型压缩关系待核",
"temporal_overlap": "时间分块重叠接口,非空间像素或秒",
"resize_type.multiplier": "图像宽高乘数,非denoise;动态接口实现未定位",
"prompt": "完整作者文本字符串,末尾换行保留;非生成请求",
"purge_cache": "布尔保存开关;准确实现未判断该参数,不能据此阻止清理",
"purge_models": "布尔保存开关;准确实现控制模型卸载,未执行",
}.get(name, "保存枚举/模型或文件引用/前端标记,无独立物理单位;目标环境未知")
fields.append(
dict(
node_id=nid,
definition_node_id=str(n["id"]),
scope=scope,
class_type=cls,
field=name,
label=LABELS[name],
pointer=f"{ptr}/widgets_values/{j}",
value=value,
json_type=type(value).__name__,
named_pointer=(
ptr
+ "/widgets_values_named/"
+ {
"alias": "Constant",
"seed_control_candidate": "control_after_generate",
"saved_comparison_history": "rgthree_comparer",
}.get(name, name)
)
if {
"alias": "Constant",
"seed_control_candidate": "control_after_generate",
"saved_comparison_history": "rgthree_comparer",
}.get(name, name)
in n.get("widgets_values_named", {})
else "源无此具名保存键,不构造值",
**(
{
"named_value": n["widgets_values_named"][
{
"alias": "Constant",
"seed_control_candidate": "control_after_generate",
"saved_comparison_history": "rgthree_comparer",
}.get(name, name)
]
}
if {
"alias": "Constant",
"seed_control_candidate": "control_after_generate",
"saved_comparison_history": "rgthree_comparer",
}.get(name, name)
in n.get("widgets_values_named", {})
else {}
),
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=effect,
evidence=class_refs[nid]
+ (
[
i
for i, e in enumerate(manifest)
if e["id"] == "frontend" and e["file"] == "src/scripts/widgets.ts"
]
if name == "seed_control_candidate"
else []
),
execution_note=(
"仅静态参考,不构造prompt或执行上游/模型/GPU/"
+ "媒体/随机/钩子/恢复/表达式/缓存清理;转换执行资格不"
+ "变。"
),
)
)
for (nid, name), (default, limits) in schemas.items():
flow.append(
f"节点{nid}准确具名schema {name}:default={default};{limits}。"
"仅接口参考,不补缺保存或认证运行恢复。"
)
for pre, ptr, sg in scopes:
flow.extend(
(pre or "root") + " 物理边 " + json.dumps(e, ensure_ascii=False) for e in sg["links"]
)
sg = g["definitions"]["subgraphs"][0]
host = next(n for n in g["nodes"] if n["id"] == 110)
boundaries = [
dict(
scope="110",
definition_pointer="/definitions/subgraphs/0",
**{k: sg[k] for k in ["id", "inputNode", "outputNode", "inputs", "outputs", "widgets"]},
host_pointer=f"/nodes/{g['nodes'].index(host)}",
host_saved=host["widgets_values"],
proxyWidgets_state="missing",
previewExposures=host["properties"]["previewExposures"],
host_inputs=host["inputs"],
)
]
flow.extend("原定义/宿主边界 " + json.dumps(b, ensure_ascii=False) for b in boundaries)
flow.extend(json.loads((OUT / "findings.json").read_bytes())["findings"])
for note in comments:
flow.append("注释" + note["node_id"] + " 中文核对:" + note["meaning"])
overview = (
"原图以Z-Image Tubro文生图,活动LoRA后采样解码;106只正式保存根8结果。"
"Get112送SeedVR2子图,内部合并alpha(50旁路)、4倍插值、预处理、分块编码、"
"采样、分块解码、后处理,输出只预览/比较/清理。比较A为原文生图、B为Seed处理。"
"宿主11缓存与13输入边界独立,标题8K不等于精确尺寸或永久导出;模型、alpha、"
"动态接口、恢复及实际效果未知。"
)
assert len(fields) == 61 and len(comments) == 0
assert sum(f["scope"] == "root" for f in fields) == 39
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/宿主恢复、目标模型与环境、实际尺寸及效果未核,转换执行资格不变。",
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()
]
+ [
"旧71块3053位置+82注释冻结;新增61位置/0注释,总72图3114位置+82注释仅参考;local_file以docs/hel-892/zimage-seed8k-document-evidence为基准。"
],
counts=dict(
saved_fields=61,
root_saved_fields=39,
internal_saved_fields=22,
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=29,
root_nodes=19,
internal_nodes=10,
physical_edges=46,
source_notes=0,
history_objects=1,
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=boundaries,
steps=[
overview,
"阅读1:核61位置/0注释,17作者文本末尾换行与5缓存无末尾换行分列;CR外线193覆盖缓存,qwen_image枚举不改lumina2。不构造prompt,不访问历史媒体。",
"阅读2:文生图1→19→4→8,7空latent采样起点;8分别到正式Save106、Set113、Purge49,Set/Get无准确版本,不造物理跨别名线。",
(
"阅读3:13边界/11宿主缓存/内部22保存分开。根image195外接、alpha=null;"
"50 mode4不模拟恢复,57四倍插值不保证超分质量;109编码才有"
"temporal_size边界65,55解码无此线。"
),
"阅读4:A=Get原文生图、B=宿主Seed处理;Seed输出无正式Save。124身份未知、106和48源IMAGE出口与准确后端返回差异保留。155定稿、可靠转换、环境核对与必要实跑未完成。",
"常见问题:8K只是标题;不保证尺寸、显存、耗时、保真、文字或可复现。Seedvr2/seedvr2大小写、两VAE异名不归一化,LoRA/模型许可与兼容待核;UE/0246/LG/组开关/宿主恢复均不认证。",
],
)