412 lines
18 KiB
Python
412 lines
18 KiB
Python
"""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-upscale-reference"
|
||
PATHS = [
|
||
(
|
||
"example_ComfyUI_workflows/3-图像生成/Z"
|
||
+ "-Image/11_Z_Image_Turbo+模型放大_图像4K高"
|
||
+ "清放大.json"
|
||
)
|
||
]
|
||
|
||
|
||
def canonical(v):
|
||
return json.dumps(v, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
|
||
|
||
|
||
LAYOUTS = {
|
||
"ImageScaleToMaxDimension": ["upscale_method", "largest_size"],
|
||
"ImageScaleBy": ["upscale_method", "scale_by"],
|
||
"UpscaleModelLoader": ["model_name"],
|
||
"LoadImage": ["image", "upload"],
|
||
"KSampler": [
|
||
"seed",
|
||
"seed_control_candidate",
|
||
"steps",
|
||
"cfg",
|
||
"sampler_name",
|
||
"scheduler",
|
||
"denoise",
|
||
],
|
||
"SaveImage": ["filename_prefix"],
|
||
"Image Comparer (rgthree)": ["saved_comparison_history"],
|
||
"UNETLoader": ["unet_name", "weight_dtype"],
|
||
"CLIPLoader": ["clip_name", "type", "device"],
|
||
"VAELoader": ["vae_name"],
|
||
"CLIPTextEncode": ["text"],
|
||
"ModelSamplingAuraFlow": ["shift"],
|
||
}
|
||
LABELS = {
|
||
"upscale_method": "缩放插值",
|
||
"largest_size": "最长边目标像素",
|
||
"scale_by": "图像缩放系数(非denoise)",
|
||
"model_name": "放大模型文件引用",
|
||
"image": "原图文件引用",
|
||
"upload": "上传标记(前端参考)",
|
||
"seed": "种子保存值",
|
||
"seed_control_candidate": "种子辅助候选(非独立后端参数)",
|
||
"steps": "采样步数保存值",
|
||
"cfg": "引导保存值",
|
||
"sampler_name": "采样器选择",
|
||
"scheduler": "调度器选择",
|
||
"denoise": "denoise",
|
||
"filename_prefix": "保存文件前缀",
|
||
"saved_comparison_history": "完整比较历史列表(仅文本)",
|
||
"unet_name": "扩散模型引用",
|
||
"weight_dtype": "权重类型",
|
||
"clip_name": "文本模型引用",
|
||
"type": "编码器类型",
|
||
"device": "设备保存选择",
|
||
"vae_name": "VAE引用",
|
||
"text": "完整条件文本缓存",
|
||
"shift": "AuraFlow shift保存值",
|
||
}
|
||
NOTE_MEANING = {
|
||
"138": "作者空MarkdownNote,空串完整保留,不当缺键或缺失注释。",
|
||
"134": (
|
||
"作者英文介绍Z Image Turbo放大与Floren"
|
||
+ "ce2Run自动分析;本图没有Florence2Run节"
|
||
+ "点,不能当已接自动分析或质量保证。"
|
||
),
|
||
"133": (
|
||
"完整Upscaling/Automatic Image Analys"
|
||
+ "is段落保留字面反斜杠n。放大保真、去噪增加像素和Florence分"
|
||
+ "析均是作者描述;实际正向仍masterpiece, 8k,不认证自动"
|
||
+ "分析已实现。"
|
||
),
|
||
"160": (
|
||
"作者提示进入子图了解放大,原Markdown链接及字面反"
|
||
+ "斜杠n完整保留,只文本,不浏览或执行Note链接。"
|
||
),
|
||
"165": (
|
||
"作者低denoise表格原文含0.2 - 0.35建议,与当前0.3"
|
||
+ "3分别保留;低降噪细节增强只是意图,不保证内容/文字/质量。字面反斜"
|
||
+ "杠n/空格/表格不规范化。"
|
||
),
|
||
"162:163": (
|
||
"作者说明先预放大再KSampler重采样,两条编号建议/字面反斜杠n保留"
|
||
+ ";实际为最长边目标缩放、模型放大、0.5图像缩放、编码后采样,不保证"
|
||
+ "保真或精确4K。"
|
||
),
|
||
}
|
||
|
||
|
||
def provider(node):
|
||
p = node.get("properties", {})
|
||
if p.get("cnr_id") == "comfy-core":
|
||
return "core" + p["ver"].replace(".", "")
|
||
return "rgpkg" if p.get("cnr_id") == "rgthree-comfy" else None
|
||
|
||
|
||
def build(index=0):
|
||
raw = (REPO / PATHS[index]).read_bytes()
|
||
g = json.loads(raw)
|
||
editorial = json.loads((OUT / "editorial.json").read_bytes())
|
||
scopes = [("", "", g), ("162", "/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-upscale-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 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 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
|
||
+ " 原输入/输出(缺键/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 in ["162:66", "162:62", "162:63", "162:76"] and name in [
|
||
"unet_name",
|
||
"clip_name",
|
||
"vae_name",
|
||
"model_name",
|
||
]
|
||
linked = inp is not None and n["inputs"][inp].get("link") is not None
|
||
aux = name in ["upload", "seed_control_candidate", "saved_comparison_history"]
|
||
default, limits = schemas.get(
|
||
(nid, name), ("无准确独立后端widget默认", "完整保存位置/前端辅助,不补运行值")
|
||
)
|
||
if name == "seed_control_candidate":
|
||
default, limits = (
|
||
"准确frontend1.41.13辅助缺省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": "完整空历史列表,仅文本",
|
||
}.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="源无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",
|
||
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}。"
|
||
"仅接口参考,不补缺保存或认证运行恢复。"
|
||
)
|
||
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"] == 162)
|
||
boundaries = [
|
||
dict(
|
||
scope="162",
|
||
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=host["properties"]["proxyWidgets"],
|
||
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 = (
|
||
"原图先按最长边目标2048缩放,再经模型放大和0.5图像缩放,随后V"
|
||
+ "AE编码、Z-Image Turbo低降噪重采样并解码保存。比较A为"
|
||
+ "处理图、B为原图。标题4K和作者8k/Florence自动分析介绍均"
|
||
+ "不是实测事实;实际没有Florence2Run,正向仍masterp"
|
||
+ "iece, 8k。九代理与五边界输入分开,宿主恢复和模型兼容未知,当"
|
||
+ "前仅参考。"
|
||
)
|
||
assert len(fields) == 25 and len(comments) == 6
|
||
assert sum(f["scope"] == "root" for f in fields) == 4
|
||
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()
|
||
]
|
||
+ [
|
||
(
|
||
"旧70块3028位置+76注释冻结;本批25位置+6注释,总71图3"
|
||
+ "053位置+82注释仅参考;local_file以docs/hel-"
|
||
+ "892/zimage-upscale-document-eviden"
|
||
+ "ce为基准。"
|
||
)
|
||
],
|
||
counts=dict(
|
||
saved_fields=25,
|
||
root_saved_fields=4,
|
||
internal_saved_fields=21,
|
||
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=23,
|
||
root_nodes=9,
|
||
internal_nodes=14,
|
||
physical_edges=24,
|
||
source_notes=6,
|
||
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:核25位置、六完整Note与空串/空历史,原文件"
|
||
+ "/模型名和推荐异名分列,不浏览Note或模型链接。"
|
||
),
|
||
(
|
||
"阅读2:按2048最长边目标→模型放大→0.5缩放→VAE编码→69"
|
||
+ "采样→65解码核物理路径;0.5非denoise,0.33与作者建议"
|
||
+ "分开,不能保证精确4K或保真。"
|
||
),
|
||
(
|
||
"阅读3:九proxyWidgets/五输入/四COMBO边界/空宿主"
|
||
+ "与定义widgets分列,重复97声明不复制物理边;保存和比较返回按"
|
||
+ "准确版本核,不构造promoted或prompt。"
|
||
),
|
||
(
|
||
"阅读4:A处理/B原图,完整空历史不是产物;保持停用未检"
|
||
+ "查/空时间戳,155最终定稿/可靠转换/环境核对/必要实"
|
||
+ "跑未完成。"
|
||
),
|
||
],
|
||
)
|