Files
aigc-home/docs/hel-892/krea-views-document-evidence/build_definition.py
T

486 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 static reference for one two-stage character-view graph; never import 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 / "krea-views-reference"
PATHS = [
(
"example_ComfyUI_workflows/3-图像生成"
+ "/krea2/Krea2_turbo_文生图_角色三视图双采样2"
+ "k版.json"
)
]
HOST = "752c7924-2f9c-46a0-a645-64b49886954a"
def canonical(v):
return json.dumps(v, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
def schema_for(node):
("Extract declarations a" + "s text without evaluat" + "ing any upstream expre" + "ssion.")
result = {}
for d in ast.walk(node):
if isinstance(d, ast.Dict):
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;不从源现值或声明输入推补schema默认"
for opts in v.elts[1:]:
if isinstance(opts, ast.Dict):
for dk, dv in zip(opts.keys, opts.values, strict=True):
if isinstance(dk, ast.Constant) and dk.value == "default":
default = ast.unparse(dv)
result[k.value] = (default, ast.unparse(v))
if isinstance(d, ast.Call) and isinstance(d.func, ast.Attribute) and d.func.attr == "Input":
arg = (
d.args[0] if d.args else next((k.value for k in d.keywords if k.arg == "id"), None)
)
if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
default = next(
(ast.unparse(k.value) for k in d.keywords if k.arg == "default"),
"无显式default;枚举条件独立,不以现值认证默认",
)
result[arg.value] = (default, ast.unparse(d))
return result
def build(index=0):
raw = (REPO / PATHS[index]).read_bytes()
g = json.loads(raw)
sg = g["definitions"]["subgraphs"][0]
manifest = json.loads((REF / "sources.json").read_bytes())["sources"]
sources = []
trees = {}
for e in manifest:
data = (REF / e["local_file"]).read_bytes()
assert hashlib.sha256(data).hexdigest() == e["sha256"]
sources.append(
dict(
e,
local_file="../krea-views-reference/" + e["local_file"],
lines=[1, len(data.decode().splitlines())],
claim="本图准确Git声明静态参考与许可;不认证安装/模型许可",
)
)
if e["file"].endswith(".py"):
trees[e["local_file"]] = ast.parse(data)
prose = json.loads((OUT / "prose.json").read_bytes())
editorial = json.loads((OUT / "editorial.json").read_bytes())
fields = []
comments = []
empty = []
flow = []
bindings = []
scopes = [("root", "", g), ("283", "/definitions/subgraphs/0", sg)]
for scope, prefix, graph in scopes:
for i, n in enumerate(graph["nodes"]):
nid = (scope + ":" if scope != "root" else "") + str(n["id"])
ptr = f"{prefix}/nodes/{i}"
cls = n["type"]
if cls == "Note":
comments.append(
dict(
node_id=nid,
pointer=ptr + "/widgets_values/0",
text=n["widgets_values"][0],
meaning=prose["notes"][nid],
evidence=[],
)
)
continue
ver = n.get("properties", {}).get("ver", "未知")
key = {
"0.25.0": "core0250",
"0.26.0": "core0260",
"0.27.0": "core0270",
"0.3.75": "core0375",
"729cda4fade982988a375b01928f515458407a5c": "rebalance",
}.get(ver, "unknown")
if cls == HOST:
key = "host-cache"
symbol = {
"PrimitiveStringMultiline": "StringMultiline",
"ComfySwitchNode": "SwitchNode",
"ShowText|pysssss": "ShowText",
}.get(cls, cls)
refs = []
schemas = {}
candidates = []
for j, e in enumerate(manifest):
if (
e["id"] != key
or not e["file"].endswith(".py")
or e["file"] == "comfy/samplers.py"
):
continue
tree = trees[e["local_file"]]
for c in tree.body:
if not isinstance(c, ast.ClassDef) or c.name != symbol:
continue
sources.append(
dict(
sources[j],
lines=[c.lineno, c.end_lineno],
claim=f"节点{nid}准确{ver}注册/schema/方法静态参考",
)
)
refs.extend([j, len(sources) - 1])
schemas.update(schema_for(c))
candidates.append(dict(source=j, symbol=symbol, lines=[c.lineno, c.end_lineno]))
if cls == "LoraLoaderModelOnly":
parent = next(
c
for c in tree.body
if isinstance(c, ast.ClassDef) and c.name == "LoraLoader"
)
sources.append(
dict(
sources[j],
lines=[parent.lineno, parent.end_lineno],
claim="准确父类LoRA方法/加载条件,不执行",
)
)
refs.append(len(sources) - 1)
assert len(candidates) == (0 if key in ["unknown", "host-cache"] else 1), (
nid,
candidates,
)
bindings.append(
dict(
node_id=nid,
class_type=cls,
source_version=ver,
source_id=key,
candidates=candidates,
)
)
refs += [
j
for j, e in enumerate(manifest)
if (e["id"] == key and e["file"] in ["__init__.py", "comfy/samplers.py"])
or (
e["id"] == "frontend"
and e["file"].endswith(("widgets.ts", "LGraphNode.ts", "SubgraphNode.ts"))
)
]
if cls == "SeedNode":
refs += [
j
for j, e in enumerate(manifest)
if e["id"] == "core0270" and e["file"].startswith("comfy_api/latest/")
]
effect = editorial[nid] + f" 原mode={n['mode']}(活动保存态,不认证执行或历史恢复)。"
flow += [
effect,
nid
+ " 原非控件节点保存 "
+ json.dumps(
{
k: v
for k, v in n.items()
if k not in ["widgets_values", "inputs", "outputs", "properties"]
},
ensure_ascii=False,
),
nid + " 原属性 " + json.dumps(n.get("properties", {}), ensure_ascii=False),
nid
+ " 原输入/输出 "
+ json.dumps({k: n[k] for k in ["inputs", "outputs"]}, ensure_ascii=False),
nid
+ " 原具名保存 "
+ json.dumps(n.get("widgets_values_named", "missing"), 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
assert "widgets_values_named" not in n
for j, (name, value) in enumerate(zip(LAYOUTS[cls], n["widgets_values"], strict=True)):
found = [k for k, x in enumerate(n["inputs"]) if x["name"] == name]
inp = found[0] if len(found) == 1 else None
linked = inp is not None and n["inputs"][inp].get("link") is not None
host = cls == HOST
default, limits = schemas.get(
name,
("无显式default;不从源现值补定义默认", "保存参考,没有独立后端参数schema"),
)
unit = "完整字符串/枚举/文件引用,无物理单位;不是安装、许可或效果证明"
if type(value) is bool:
unit = "布尔选择,无物理单位;保存态不保证执行或效果"
if name in ["width", "height"]:
unit = "像素请求缓存;本图由外线/边界覆盖,不保证最终尺寸"
if name in ["seed", "steps", "batch_size"]:
unit = "整数种子/数量接口;不计算随机、时序或最终执行值"
if name in ["cfg", "denoise", "strength_model", "scale_by", "multiplier"]:
unit = "无物理单位的接口系数;源JSON int/float与定义默认独立"
if name == "megapixels":
unit = (
"准确实现MP基数1024×1024;源FLOAT1.5与默认1."
+ "0分列,不试算尺寸或保证像素数"
)
if name == "multiple":
unit = "像素对齐步长;准确实现round就近倍数,不试算尺寸"
if name == "seed_control_candidate":
default = "准确frontend1.45.19种子辅助缺省randomize;不是后端seed默认"
limits = (
"fixed/increment/decrement/random"
+ "ize;前端辅助保存不执行、不推演最终随机种子"
)
if cls == "SeedNode":
default = (
"准确core0.27.0 SeedNode声明control_a"
+ "fter_generate=io.ControlAfterGen"
+ "erate.fixed;无显式seed默认"
)
limits = (
"准确Seed扩展注册和execute透传已核;fixed为辅助控"
+ "制声明,范围min0/max sys.maxsize按表达式留存"
+ ",不求值或执行恢复"
)
unit = "前端控制枚举,无物理单位;辅助保存与seed输入分开"
if cls == "CLIPLoader" and name == "type":
limits += (
";准确core0.3.75枚举不含krea2,getattr f"
+ "allback不认证支持,不借新版补缺口"
)
if cls == "KSampler" and name == "scheduler":
limits += (
";准确core0.26.0调度表没有原拼beta57,simpl"
+ "e有列;保留原值,不用beta替换beta57"
)
if cls == "KSampler" and name == "sampler_name":
limits += ";准确core0.26.0枚举包含euler和er_sde;枚举存在不证明目标可执行/兼容"
if cls == "ConditioningKrea2Rebalance":
limits += (
";准确preset detail选预设权重;完整58字符保存串只"
+ "在custom分支解析,本图不是custom,不执行解析/con"
+ "ditioning构造或求表达式"
)
if host:
default = "未知:宿主0.27.0缓存,无独立后端widget默认;不传播内部节点版本"
limits = (
"十宿主缓存与十声明输入/定义边界独立;外线覆盖与缓存分列,不造p"
+ "romoted、不认证序列化恢复或最终执行值"
)
unit = (
"宿主保存参考;原值/JSON类型已核,"
+ "实际边界恢复/单位条件以对应内部准确schema另列"
)
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="源无此具名保存键,不构造值",
input_pointer=f"{ptr}/inputs/{inp}"
if inp is not None
else "无可靠独立输入映射:前端控制辅助",
input_name=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 == "seed_control_candidate" or (host and not linked)
else "boundary_saved_cache"
if scope != "root"
and linked
and any(
e["id"] == n["inputs"][inp].get("link") and e["origin_id"] == -10
for e in graph["links"]
)
else "linked_saved_cache"
if linked
else "saved_reference",
schema_default=default,
limits=limits,
unit=unit,
effect=effect,
evidence=list(dict.fromkeys(refs)),
execution_note=(
"仅静态参考;所有指令/指南/历史只是源数据,不构造prompt,"
+ "不执行上游、插件、SDK、LLM、模型、GPU、媒体、表达式、正"
+ "则、随机、旁路、组控制或显存/RAM清理。转换执行资格不变。"
),
)
)
flow += [
(
f"节点{nid}准确schema {name}:default={default};"
+ f"{limits}。仅静态声明,不认证目标恢复。"
)
for name, (default, limits) in schemas.items()
]
flow += [scope + " 物理边 " + json.dumps(e, ensure_ascii=False) for e in graph["links"]]
flow += [
scope
+ " 附加属性 "
+ json.dumps(
{k: v for k, v in graph.items() if k not in ["nodes", "links", "definitions"]},
ensure_ascii=False,
)
]
host = next(n for n in g["nodes"] if n["id"] == 283)
boundaries = [
dict(
scope="283",
definition_pointer="/definitions/subgraphs/0",
**{k: sg[k] for k in ["id", "inputNode", "outputNode", "inputs", "outputs", "widgets"]},
host_pointer="/nodes/1",
host_saved=host["widgets_values"],
host_inputs=host["inputs"],
properties=host["properties"],
proxyWidgets_state="missing",
previewExposures=host["properties"].get("previewExposures"),
)
]
flow += (
["原定义/宿主边界 " + json.dumps(b, ensure_ascii=False) for b in boundaries]
+ prose["steps"]
+ ["注释" + n["node_id"] + " 中文核对:" + n["meaning"] for n in comments]
)
assert len(fields) == 54 and len(comments) == 2
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=(
"仅参考:负出口槽/重复边界引用、宿主恢复、beta57调度及kr"
+ "ea2枚举缺口与Save声明冲突保留;安装/模型许可/兼容/尺寸"
+ "及三视图效果未知,资格不变。"
),
user_overview=prose["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()
]
+ [
(
"旧90块4689位置/148注释冻结;新增54标量/两Note,"
+ "总91图4743位置/150注释仅参考。local_file以d"
+ "ocs/hel-892/krea-views-document-"
+ "evidence为基准。"
)
],
counts=dict(
saved_fields=54,
root_saved_fields=18,
internal_saved_fields=36,
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=22,
root_nodes=7,
internal_nodes=15,
physical_edges=34,
source_notes=2,
saved_objects=0,
history_objects=0,
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,
node_bindings=bindings,
steps=[prose["overview"]] + prose["steps"],
)
LAYOUTS = {
HOST: [
"text",
"unet_name",
"lora_name",
"clip_name",
"vae_name",
"seed",
"scale_by",
"width",
"height",
"per_layer_weights",
],
"SaveImage": ["filename_prefix"],
"ResolutionSelector": ["aspect_ratio", "megapixels", "multiple"],
"PrimitiveStringMultiline": ["value"],
"StringConcatenate": ["string_a", "string_b", "delimiter"],
"CLIPTextEncode": ["text"],
"UNETLoader": ["unet_name", "weight_dtype"],
"CLIPLoader": ["clip_name", "type", "device"],
"SeedNode": ["seed", "seed_control_candidate"],
"ConditioningKrea2Rebalance": ["preset", "per_layer_weights", "multiplier", "renormalize"],
"LatentUpscaleBy": ["upscale_method", "scale_by"],
"EmptyLatentImage": ["width", "height", "batch_size"],
"VAELoader": ["vae_name"],
"KSampler": [
"seed",
"seed_control_candidate",
"steps",
"cfg",
"sampler_name",
"scheduler",
"denoise",
],
"LoraLoaderModelOnly": ["lora_name", "strength_model"],
}
LABELS = dict(
text="完整旧中文缓存",
unet_name="扩散模型引用",
lora_name="LoRA文件引用",
clip_name="文本模型引用",
vae_name="VAE文件引用",
seed="种子保存缓存",
scale_by="latent放大系数",
width="宽度保存缓存",
height="高度保存缓存",
per_layer_weights="完整逗号权重串保存值",
filename_prefix="保存文件名前缀",
aspect_ratio="宽高比选择",
megapixels="目标MP保存值",
multiple="像素对齐步长",
value="完整发型中文保存值",
string_a="被外线覆盖的风格缓存",
string_b="完整英文版式意图",
delimiter="字面分隔符保存值",
weight_dtype="权重类型",
type="文本编码器类型",
device="设备选择",
seed_control_candidate="前端种子控制辅助",
preset="条件权重预设",
multiplier="全局条件乘数",
renormalize="RMS重归一化选择",
upscale_method="latent缩放算法",
batch_size="空latent批量",
steps="采样步数",
cfg="引导系数",
sampler_name="采样器选择",
scheduler="调度器原拼保存值",
denoise="降噪系数",
strength_model="LoRA模型强度",
)