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

433 lines
18 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.
"""Pinned static reference; 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 / "krea-identity-reference"
PATHS = [
("example_ComfyUI_workfl" + "ows/3-图像生成/krea2/krea2" + "_identity_edit_图像编辑.js" + "on")
]
LAYOUTS = {
"CLIPLoader": ["clip_name", "type", "device"],
"EmptySD3LatentImage": ["width", "height", "batch_size"],
"KSampler": [
"seed",
"seed_control_candidate",
"steps",
"cfg",
"sampler_name",
"scheduler",
"denoise",
],
"ResolutionSelector": ["aspect_ratio", "megapixels", "multiple"],
"Krea2EditGroundedEncode": ["prompt", "grounding_px", "system_prompt"],
"Krea2EditModelPatch": ["ref_boost", "ref_boost_a", "fit_mode"],
"VAELoader": ["vae_name"],
"LoadImage": ["image", "upload"],
"ImageScaleToTotalPixels": ["upscale_method", "megapixels", "resolution_steps"],
"SaveImage": ["filename_prefix"],
"Image Comparer (rgthree)": ["comparison_history"],
"UNETLoader": ["unet_name", "weight_dtype"],
"LoraLoaderModelOnly": ["lora_name", "strength_model"],
}
LABELS = dict(
clip_name="文本模型文件引用",
type="文本编码器类型",
device="设备选择",
width="宽度保存缓存(外线覆盖)",
height="高度保存缓存(外线覆盖)",
batch_size="空latent批量",
seed="采样种子保存值",
seed_control_candidate="前端种子控制辅助",
steps="采样步数",
cfg="引导系数",
sampler_name="采样器选择",
scheduler="调度器选择",
denoise="降噪系数",
aspect_ratio="未消费的宽高比选择",
megapixels="目标MP保存值",
multiple="尺寸对齐倍数",
prompt="完整编辑指令保存值",
grounding_px="视觉编码最长边上限",
system_prompt="完整系统提示保存值",
ref_boost="末参考注意力系数",
ref_boost_a="前参考注意力系数",
fit_mode="参考适配模式",
vae_name="VAE文件引用",
image="输入图片文件名",
upload="前端上传状态",
upscale_method="缩放算法选择",
resolution_steps="缩放尺寸对齐步长",
filename_prefix="正式保存文件名前缀",
comparison_history="完整比较历史列表(仅文本)",
unet_name="扩散模型文件引用",
weight_dtype="权重类型",
lora_name="身份编辑LoRA引用",
strength_model="LoRA模型强度",
)
def canonical(value):
return json.dumps(value, 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;动态文件枚举/类属性不从现值补默认"
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)
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-identity-reference/" + e["local_file"],
lines=[1, len(data.decode().splitlines())],
claim="本图准确声明Git文本与许可;静态读取未执行,不认证目标安装/模型许可",
)
)
if e["file"].endswith(".py"):
trees[e["local_file"]] = ast.parse(data)
editorial = json.loads((OUT / "editorial.json").read_bytes())
prose = json.loads((OUT / "prose.json").read_bytes())
fields, comments, empty, flow, bindings = [], [], [], [], []
for i, n in enumerate(g["nodes"]):
nid, cls, ptr = str(n["id"]), n["type"], f"/nodes/{i}"
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
version = n["properties"]["ver"]
key = {
"0.26.0": "core0260",
"0.28.0": "core0280",
("223a9383eabf991cb21206" + "63162441383da50f27"): "kreaedit",
("27b4f4cdcf3b127c29d5d8" + "135ac1536ecbd4c383"): "rgthree",
}[version]
symbol = "RgthreeImageComparer" if cls == "Image Comparer (rgthree)" else 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
candidates.append(dict(source=j, symbol=symbol, lines=[c.lineno, c.end_lineno]))
sources.append(
dict(
sources[j],
lines=[c.lineno, c.end_lineno],
claim=f"节点{nid}准确{version}注册类/schema/实现静态参考",
)
)
refs.extend([j, len(sources) - 1])
schemas.update(schema_for(c))
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) == 1, (nid, candidates)
bindings.append(
dict(node_id=nid, class_type=cls, version=version, source_id=key, candidates=candidates)
)
refs += [
j
for j, e in enumerate(manifest)
if e["id"] == key
and e["file"] in ("__init__.py", "py/constants.py", "web/comfyui/constants.js")
]
if cls == "KSampler":
refs += [
j
for j, e in enumerate(manifest)
if e["id"] == key and e["file"] == "comfy/samplers.py"
]
if cls in ("KSampler", "LoadImage"):
refs += [
j
for j, e in enumerate(manifest)
if e["id"] == "frontend"
and e["file"].endswith(
(
"widgets.ts",
"LGraphNode.ts",
"useImageUploadWidget.ts",
"useNodeImageUpload.ts",
)
)
]
if key == "rgthree":
refs += [
j
for j, e in enumerate(manifest)
if e["id"] == key and "image_comparer" in e["file"]
]
# Inherited SaveImage/PreviewImage UI behavior has its own core binding.
refs += [
j
for j, e in enumerate(manifest)
if e["id"] == "core0260" and e["file"] == "nodes.py"
]
effect = (
editorial[nid]
+ f" 原mode={n['mode']}"
+ (
"(旁路保存态,不模拟穿透/恢复)。"
if n["mode"] == 4
else "(活动保存态,不认证已执行)。"
)
)
flow += [
effect,
nid + " 原属性 " + json.dumps(n["properties"], ensure_ascii=False),
nid
+ " 原输入/输出 "
+ json.dumps({k: n[k] for k in ["inputs", "outputs"]}, ensure_ascii=False),
nid + " 原具名保存 missing",
]
if not n["widgets_values"]:
empty.append(
dict(
node_id=nid,
class_type=cls,
pointer=ptr,
scope="root",
state="empty_list",
effect=effect,
)
)
continue
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]["link"] is not None
default, limits = schemas.get(
name,
(
"未知:前端历史/辅助保存,没有独立后端参数默认",
"仅保存参考,不按端口顺序推断schema或恢复",
),
)
unit = "字符串/枚举/模型文件引用,无物理单位;保存值不是安装或实际运行证明"
if name in ("width", "height"):
unit = "像素请求缓存;本图由112经30/31覆盖,非最终尺寸保证"
if name == "megapixels":
unit = (
"准确实现MP基数1024×1024目标像素;"
+ "源JSON int1与FLOAT defau"
+ "lt1.0分开,不计算/保证像素"
)
if name in ("multiple", "resolution_steps"):
unit = "像素对齐步长;准确实现round就近倍数条件,不试算尺寸"
if name == "grounding_px":
unit = "视觉编码最长边像素上限;0为不设缩小上限,不是采样输出尺寸"
if name in ("seed", "steps", "batch_size"):
unit = "整数数量/种子接口;不计算随机或最终执行值"
if name in ("cfg", "denoise", "strength_model", "ref_boost", "ref_boost_a"):
unit = "无物理单位的接口系数;原JSON int与FLOAT默认独立,不认证效果"
if name == "seed_control_candidate":
default = "准确frontend1.45.19种子辅助缺省randomize"
limits = (
"fixed/increment/decrem"
+ "ent/randomize;前端控制不作后端"
+ "seed参数,不执行随机或恢复"
)
unit = "前端控制枚举,无物理单位"
if name == "upload":
default = "前端上传控件状态,无独立后端upload默认"
limits = (
"源upload口与准确frontend1.4"
+ "5.19 IMAGEUPLOAD保存独立;不"
+ "读取/上传素材或认证恢复"
)
unit = "前端上传状态字符串,无物理单位"
if name == "comparison_history":
default = "未知:前端已序列化历史列表,无独立后端widget默认"
limits = (
"准确rgthree属性Slide及历史两对象"
+ "全文;URL只作数据,不GET /api/v"
+ "iew,不冒充本次产物"
)
unit = "两个对象的完整JSON列表/布尔/URL文本;无像素或时间单位"
if cls == "CLIPLoader" and name == "type":
limits += (
";准确0.26.0枚举包含krea2;loa"
"d_clip仍有getattr fallba"
"ck,不从枚举或fallback认证目标支持"
"/兼容"
)
if cls == "Krea2EditModelPatch" and name == "ref_boost":
limits += (
";作用于最后一组参考,单参考即唯一参考;No"
+ "te建议4不等于schema默认1.0或效果"
+ "保证"
)
if cls == "Krea2EditModelPatch" and name == "ref_boost_a":
limits += (
";只作用于更早参考,单参考无此系数分配;物理" + "第二链mode4不模拟运行参考数量"
)
if cls == "ImageScaleToTotalPixels" and name == "upscale_method":
limits += (
";类枚举nearest-exact/bili"
"near/area/bicubic/lanc"
"zos;裁剪disabled;不从无显式de"
"fault认证恢复"
)
fields.append(
dict(
node_id=nid,
definition_node_id=nid,
scope="root",
class_type=cls,
field=name,
label=LABELS[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=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", "comparison_history")
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=(
"仅静态参考;全部提示/指南/历史URL只作源"
"数据,不构造prompt,不执行上游、插件、"
"SDK、模型、GPU、图像处理、随机、旁路、"
"组控制或清理。转换执行资格不变。"
),
)
)
flow += [
f"节点{nid}准确schema {name}:default={default};{limits}。仅接口参考,不认证目标恢复。"
for name, (default, limits) in schemas.items()
]
flow += ["root 物理边 " + json.dumps(e, ensure_ascii=False) for e in g["links"]]
flow += [
"原附加属性/组 "
+ json.dumps(
{k: v for k, v in g.items() if k not in ("nodes", "links")}, ensure_ascii=False
)
]
flow += prose["steps"] + [
"注释" + n["node_id"] + " 中文核对:" + n["meaning"] for n in comments
]
assert len(fields) == 42 and len(comments) == 8
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=(
"仅参考:参考与空latent起点分层;tar"
+ "get_latent接口差异、mode4恢复"
+ "、目标安装/模型许可/兼容及真实效果未核;转"
+ "换资格不变。"
),
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()
]
+ [
(
"旧87块4537位置/138注释冻结;新增4"
"2位置/八注释,总88图4579位置/146"
"注释仅参考。local_file以docs/"
"hel-892/krea-identity-"
"document-evidence为基准。"
)
],
counts=dict(
saved_fields=42,
root_saved_fields=42,
internal_saved_fields=0,
linked_saved_fields=sum(f["role"] == "linked_saved_cache" for f in fields),
boundary_saved_fields=0,
frontend_only=sum(f["role"] == "frontend_reference_only" for f in fields),
source_nodes=28,
root_nodes=28,
internal_nodes=0,
physical_edges=31,
source_notes=8,
saved_objects=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=[],
node_bindings=bindings,
steps=[prose["overview"]] + prose["steps"],
)