Files
aigc-home/docs/hel-892/flux2-person-document-evidence/build_definition.py
T

580 lines
27 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.
"Source-bound character replacement editorial text; never an execution prompt."
import ast
import copy
import hashlib
import json
import subprocess
from pathlib import Path
REPO = Path(__file__).resolve().parents[3]
OUT = Path(__file__).resolve().parent
REF = OUT.parent / "flux2-person-reference"
PATHS = [("example_ComfyUI_workflows/3-图像生成/Flux/flux2_klein_图生图_人物迁移.json")]
def canonical(v):
return json.dumps(v, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
MEANING = {
"70": (
"第一原图ComfyUI_00150_.png/image,经144→52缩放→215→1"
"31.image第一参考。MASK出口缺links键,不是null或[],没有已接遮罩证"
"据;不读取图片内容。"
),
"69": (
"第二原图ComfyUI_01759_.png/image,经219→132去背景定义→2"
"20→131.image_1第二参考。MASK出口缺links键,不能据文件名判断人物内"
"容或遮罩连接。"
),
"52": (
"准确Layer881bc91790da6b907d3d28e5b91b295b9aef0"
"6ee来自源aux仓库aining2022/ComfyUI_Swwan,不借89014d"
"。保存original/1/1/letterbox/lanczos/字符串8/heigh"
"t/1280/#000000。original取首图宽高比;两ratio分支的heigh"
"t均令目标高=scale_to_length、宽=int(高×ratio),随后宽高各向"
"上取整到8倍数。1/1仅custom分支使用。tensor2pil做clip/uint8"
",图像转RGB丢弃alpha;letterbox按比例缩放并居中贴到background"
"_color RGB底,非遮罩合成。仅静态说明,不试算实际尺寸/比例/像素;mask输入"
"缺link,mask出口缺links,宽slot3/高slot4均links=[]未接,"
"不能直接覆盖调度器。"
),
"43": (
"131生成经217→43正式SaveImage,前缀Flux2-Klein。源声明一个i"
"mages IMAGE出口(缺links),准确core0.9.2 RETURN_TYP"
"ES=(),存在输出协议冲突,原样保留且转换/执行关闭。PNG output目录、递增文"
"件名和ui.images仅静态代码参考,未证明成功、实际路径/history或透明效果。"
),
"131:102": "保存euler,SAMPLER→103;准确core0.8.2动态枚举仅静态阅读,不构造采样器。",
"131:105": (
"保存192921483949477/randomize,准确core0.8.2 seed"
"默认0/UINT64范围与前端1.36.14生成后辅助分列。宿主只有代理没有具名保存;不"
"运行钩子/种子/状态/缓存,不计算下一值、不保证复现。"
),
"131:106": (
"保存Flux反斜杠flux-2-klein-9b-fp8.safetensors/def"
"ault,直接→114.model,无LoRA。边界159来自宿主unet_name无外"
"线;内部缓存与8代理分列。properties.models另写base模型名,不据文件"
"名确认兼容、模型许可或安装。"
),
"131:107": (
"VAE实际full_encoder_small_decoder.safetensors,"
"三扇出148→104解码、204→126第一参考编码、212→129第二参考编码。准确0"
".8.2动态枚举/文件解析/读取后构造并校验条件仅静态参考,不改为flux2-vae,不"
"据名称认定家族、轻量效果、兼容或已安装。宿主vae_name经161,无外线/保存。"
),
"131:109": (
"保存1024/1024/1;109空latent才是103.latent_image采样"
"起点。108宽slot0经172覆盖width、高slot1经174覆盖height;b"
"atch_size缓存1未连线。参考latent只进条件,不是像素拼接或图生图采样起点。"
),
"131:110": (
"第一参考52→131.image→边界175→110,保存lanczos/JSON in"
"t1/JSON int1;准确0.8.2 megapixels为FLOAT默认1.0范围"
"0.01~16步0.01,resolution_steps INT默认1范围1~256。"
"total=megapixels×1024×1024;scale_by=sqrt(tot"
"al/(宽×高));宽高分别round(原边×scale_by/resolution_s"
"teps)×resolution_steps,再common_upscale crop="
"disabled。lanczos经PIL uint8、返回原device/dtype;无"
"独立透明合成/去背景分支,通道能否被PIL处理依输入,不能保证精确百万像素、尺寸或比例。"
"110同时→108读尺寸与126第一参考编码。"
),
"131:85": (
"第二参考69→132去背景→131.image_1→边界186→85,保存lanczos"
"/JSON int1/int1,准确0.8.2同110公式及FLOAT/default/"
"通道条件。85只供129第二参考编码,不连108、不控制输出画布;不保证与110同尺寸或"
"Alpha保留、比例及精确像素数。"
),
"131:111": (
"保存qwen_3_8b_fp8mixed.safetensors/flux2/defau"
"lt,151供113正向、189供87负向。准确core0.8.2 CLIP schem"
"a;宿主clip_name经160无外线,内部缓存与代理分列。元数据模型/目录仅作者引用"
",不证明dtype、设备、安装或兼容。"
),
"131:113": (
"完整中文正向缓存:把图2的人物替换图1的人物,只替换人物及服装,同时保持图1场景、动作不"
"变,场景光效一致。113→127先追加126第一参考,再→130追加129第二参考→11"
"4正向。宿主text经162无外线且保存[];作者意图不保证人物身份、服装、场景光照/动"
"作或未编辑像素一致。"
),
"131:87": (
"空字符串负向完整保留,不制造负向词;本节点独立core0.9.1,不继承宿主0.8.2。"
"87→125先追加126第一参考,再→128追加129第二参考→114负向;空串不等于无"
"负向条件。"
),
"131:114": (
"保存JSON int1,准确0.8.2 CFG schema FLOAT默认8.0,模型"
"直接来自106,正向130、负向128→103.guider;无LoRA/Compare"
"r/历史列表,不制造这些参数。"
),
"131:115": (
"保存steps4/width1024/height1024;108读110第一参考实际宽"
"slot0经171覆盖width、高slot1经173覆盖height,同时覆盖109两"
"处1024共四缓存。第二参考85不控制输出画布;不求sigmas或实际尺寸。"
),
"132:14": (
"保存birefnet.safetensors,准确core0.28.3已找到LoadBa"
"ckgroundRemovalModel定义/BackgroundRemovalExte"
"nsion注册,非旧图0.19.3未知结论。动态background_removal目录"
"文件列表排序,无显式默认/固定成员;路径解析后load、None时抛错。准确load先读"
"state_dict,需含bb.layers.1.blocks.0.attn.relat"
"ive_position_index才选择birefnet.json,否则None;内部"
"模型构造/加载和encode_image GPU、预处理/逐批/插值/sigmoid仅静"
"态代码,不执行或认定M极性。14→13背景模型;宿主bg_removal_name经边界"
"12无外线/保存。仅静态读取源码,文件名不证明模型存在、兼容、许可、下载资格或去背景成功"
"。"
),
}
EMPTY = {
"133": "Label无提供方/版本,不因rgthree字样赋予身份或下载字体。",
"134": "第二Label同样无身份,布局属性独立保留。",
"131": (
"宿主widgets_values=[]与定义widgets="
"[]分开;8代理6输入,四模型/提示口无外线、image与i"
"mage_1有外线,不造promoted值。"
),
"132": (
"宿主widgets_values=[]与第二定义widget"
"s=[]分开;1代理2输入,mask输出links=[]未接"
",不能把内部原MASK出口当主图已接遮罩。"
),
"131:103": (
"109空latent采样起点;第一LATENT slot0经"
"147→104解码;第二LATENT denoised_ou"
"tput links=[]未接,不冒充已取得去噪产物。"
),
"131:104": "103第一LATENT与107.VAE→104解码,定义输出153→131→43正式保存,无预览比较支路。",
"131:108": (
"110第一参考→108 GetImageSize,准确0.8.2宽slot0/高slot"
"1分别覆盖115与109四1024缓存;batch_size slot2 links=["
"]未接。"
),
"131:126": "110第一图与107.VAE→126,200到127正向、199到125负向,分别先追加第一参考。",
"131:129": "85第二图与107.VAE→129,208到130正向、207到128负向,分别再追加第二参考。",
"131:127": (
"113正向先append126第一参考latent,再209"
"→130;准确reference_latents原列表+[l"
"atent],非像素拼接。"
),
"131:125": "87空负向先append126第一参考latent,再210→128;负向同样有参考,不能省略。",
"131:130": "127正向已有第一参考,再append129第二参考,213→114.positive;顺序第一再第二。",
"131:128": "125负向已有第一参考,再append129第二参考,214→114.negative;两条append链独立。",
"132:13": (
"准确core0.28.3 RemoveBackground已定义/注册,调用bg_rem"
"oval_model.encode_image(image)输出MASK;原69同时经边"
"界5供13、7供16,不读取媒体。不从类名或schema的foreground文字推定运"
"行M的前景/背景极性。13原MASK既经4→15也经11输出定义mask;主图132.m"
"ask=[]未接。"
),
"132:15": ("准确0.28.3 InvertMask.execute是1.0-mask;13.MASK→15→16.alpha。未运行、不猜M极性。"),
"132:16": (
"准确0.28.3 JoinImageWithAlpha先bilinear resize_"
"mask(alpha.to(image),image.shape[1:]),再1.0-,"
"按max批次repeat,cat(image[..., :3],alpha.unsque"
"eze(-1))。15已反转一次,Join内部另反转;13原M与经15/16的Alpha"
"链分开,不靠代数简化声称实际极性/透明成功。16经8输出IMAGE→132→131第二参"
"考;不保证通道/批次/透明效果或未编辑像素不变。"
),
}
def build(index=0):
raw = (REPO / PATHS[index]).read_bytes()
g = json.loads(raw)
manifest = json.loads((REF / "sources.json").read_bytes())["sources"]
sources = []
def cite(key, file, symbol=None, span=None, claim="本图准确版本静态参考"):
e = next(e for e in manifest if e["id"] == key and e["file"] == file)
data = (REF / e["local_file"]).read_bytes()
assert hashlib.sha256(data).hexdigest() == e["sha256"]
if symbol:
node = next(
n
for n in ast.walk(ast.parse(data))
if isinstance(n, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef))
and n.name == symbol
)
span = [node.lineno, node.end_lineno]
span = span or [1, len(data.decode().splitlines())]
sources.append(
dict(
e,
local_file="../flux2-person-reference/" + e["local_file"],
lines=span,
claim=claim,
)
)
return len(sources) - 1
refs = {}
for cls, file in [
("CLIPTextEncode", "nodes.py"),
("VAELoader", "nodes.py"),
("UNETLoader", "nodes.py"),
("CLIPLoader", "nodes.py"),
("VAEEncode", "nodes.py"),
("VAEDecode", "nodes.py"),
("CFGGuider", "comfy_extras/nodes_custom_sampler.py"),
("RandomNoise", "comfy_extras/nodes_custom_sampler.py"),
("KSamplerSelect", "comfy_extras/nodes_custom_sampler.py"),
("SamplerCustomAdvanced", "comfy_extras/nodes_custom_sampler.py"),
("EmptyFlux2LatentImage", "comfy_extras/nodes_flux.py"),
("Flux2Scheduler", "comfy_extras/nodes_flux.py"),
("ReferenceLatent", "comfy_extras/nodes_edit_model.py"),
]:
refs[cls] = [cite("core", file, cls)]
refs["LoadImage"] = [cite("save", "nodes.py", "LoadImage")]
refs["SaveImage"] = [cite("save", "nodes.py", "SaveImage")]
refs["ImageScaleToTotalPixels"] = [
cite("scale", "comfy_extras/nodes_post_processing.py", "ImageScaleToTotalPixels"),
cite("scale", "comfy/utils.py", "lanczos"),
cite("scale", "comfy/utils.py", "common_upscale"),
]
refs["GetImageSize"] = [cite("scale", "comfy_extras/nodes_images.py", "GetImageSize")]
refs["LayerUtility: ImageScaleByAspectRatio V2"] = [
cite("layer", "image_scale_by_aspect_ratio_v2.py", "ImageScaleByAspectRatioV2")
]
for sym in ["fit_resize_image", "num_round_up_to_multiple", "tensor2pil", "pil2tensor"]:
refs["LayerUtility: ImageScaleByAspectRatio V2"].append(
cite("layer", "layerstyle_utils.py", sym)
)
for cls, file in [
("LoadBackgroundRemovalModel", "nodes_bg_removal.py"),
("RemoveBackground", "nodes_bg_removal.py"),
("InvertMask", "nodes_mask.py"),
("JoinImageWithAlpha", "nodes_compositing.py"),
]:
refs[cls] = [cite("background", "comfy_extras/" + file, cls)]
cite("background", "comfy_extras/nodes_bg_removal.py", "BackgroundRemovalExtension")
cite("background", "comfy_extras/nodes_compositing.py", "resize_mask")
cite("background", "comfy/bg_removal_model.py")
cite(
"background",
"nodes.py",
span=[2375, 2516],
claim="准确0.28.3额外节点加载/注册范围,绑定本图背景定义",
)
cite(
"layer",
"__init__.py",
span=[1, 58],
claim="aux仓库准确完整提交的模块导入/节点映射,非仅同名",
)
cite(
"frontsub",
"src/lib/litegraph/src/subgraph/SubgraphNode.ts",
span=[226, 340],
claim="准确1.36.14 configure边界及连接widget恢复",
)
cite(
"frontsub",
"src/lib/litegraph/src/subgraph/SubgraphNode.ts",
span=[606, 631],
claim="准确1.36.14 serialize先同步相连widget",
)
cite(
"frontend",
"src/lib/litegraph/src/LGraphNode.ts",
span=[778, 929],
claim="父configure/serialize_widgets/serialize=false条件",
)
cite(
"frontend",
"src/scripts/widgets.ts",
span=[53, 281],
claim="生成后辅助控制与randomize初始值,仅读不运行",
)
negative = cite("negative", "nodes.py", "CLIPTextEncode")
for e in manifest:
if e["id"] == "frontend":
# All frontend source and lock/license originals remain individually bound.
cite(
e["id"],
e["file"],
span=[1, min(len((REF / e["local_file"]).read_text().splitlines()), 45)],
claim=(
"仅本图准确frontend1.36.14与锁定依赖/许可,序"
"列化/seed规则需对应原文全文;UE/tab目标恢复未知"
),
)
# Reuse schema descriptions only after matching the exact implementation above.
reviews = json.loads(
subprocess.check_output(
[
"git",
"show",
(
"89e37c198a53d2069ff6607673fbb19be61d0f68:cal"
"liope-backend/src/calliope/comfyui/source_re"
"views.json"
),
],
cwd=REPO,
)
)
common = {}
for r in reviews.values():
for f in r.get("fixed_version_document", {}).get("fields", []):
common[f["class_type"], f["field"]] = f
names = {
"LoadImage": ["image", "upload"],
"SaveImage": ["filename_prefix"],
"LayerUtility: ImageScaleByAspectRatio V2": [
"aspect_ratio",
"proportional_width",
"proportional_height",
"fit",
"method",
"round_to_multiple",
"scale_to_side",
"scale_to_length",
"background_color",
],
"RandomNoise": ["noise_seed", "control_after_generate"],
"UNETLoader": ["unet_name", "weight_dtype"],
"VAELoader": ["vae_name"],
"EmptyFlux2LatentImage": ["width", "height", "batch_size"],
"ImageScaleToTotalPixels": ["upscale_method", "megapixels", "resolution_steps"],
"CLIPLoader": ["clip_name", "type", "device"],
"CLIPTextEncode": ["text"],
"CFGGuider": ["cfg"],
"Flux2Scheduler": ["steps", "width", "height"],
"KSamplerSelect": ["sampler_name"],
"LoadBackgroundRemovalModel": ["bg_removal_name"],
}
fields = []
empty = []
boundaries = []
flow = []
scopes = [("", g, None)] + [
(f"/definitions/subgraphs/{i}", s, 131 + i)
for i, s in enumerate(g["definitions"]["subgraphs"])
]
for prefix, graph, host in scopes:
for i, n in enumerate(graph["nodes"]):
ptr = f"{prefix}/nodes/{i}"
display = str(n["id"]) if host is None else f"{host}:{n['id']}"
effect = MEANING.get(display, EMPTY.get(display))
assert effect, display
flow.append(effect)
flow.append(
f"{display} 独立源属性 " + json.dumps(n.get("properties", {}), ensure_ascii=False)
)
if not n.get("widgets_values"):
state = "missing" if "widgets_values" not in n else "empty_list"
empty.append(
dict(
node_id=display,
class_type=n["type"],
pointer=ptr,
scope=prefix or "root",
state=state,
effect=(
"源缺widgets_values键;"
if state == "missing"
else "源widgets_values=[]零位置;"
)
+ effect,
)
)
continue
for j, (name, v) in enumerate(zip(names[n["type"]], n["widgets_values"], strict=True)):
previous = common.get((n["type"], name), {})
f = {
k: copy.deepcopy(previous[k])
for k in ["label", "unit", "schema_default", "limits"]
if k in previous
}
inp = next(
(k for k, x in enumerate(n.get("inputs", [])) if x["name"] == name), None
)
aux = name in ["upload", "control_after_generate"]
linked = not aux and inp is not None and n["inputs"][inp].get("link") is not None
evidence = refs[n["type"]]
if display == "131:87":
evidence = [negative]
if display == "132:14":
f.update(
label="背景移除模型引用",
schema_default="无显式default;动态排序文件列表",
limits="background_removal动态成员,路径解析/load及None报错条件;模型/素材/许可/安装未知",
unit="模型引用",
)
f.update(
node_id=display,
definition_node_id=str(n["id"]),
scope=prefix or "root",
class_type=n["type"],
field=name,
pointer=f"{ptr}/widgets_values/{j}",
value=v,
json_type=type(v).__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 "linked_saved_cache"
if linked
else "saved_layout_reference",
effect=effect,
evidence=evidence,
execution_note=(
"准确默认、源JSON现值、外线覆盖和宿主代理分列;目标安装/"
"许可/目录/恢复/模型素材兼容与效果未知,保持停用,不新增转"
"换或执行资格。"
),
)
if n["type"] == "LayerUtility: ImageScaleByAspectRatio V2":
f["limits"] = f["limits"].replace(
";仅89014d参考假设,源版本未知",
";仅准确881bc917 aux仓库参考,cnr提供方差异保留",
)
if name == "scale_to_length":
f["unit"] = "像素INT(当前height;total_pixel分支另为千像素)"
if display == "131:105" and name == "noise_seed":
f["schema_default"] = "0"
if display == "131:105" and name == "control_after_generate":
f["limits"] = (
"准确frontend1.36.14 fixed/increm"
"ent/decrement/randomize,仅前端辅助,"
"不运行钩子或计算种子"
)
if n["type"] == "CLIPTextEncode":
f.update(
label="完整中文正向缓存" if display == "131:113" else "空串负向缓存",
schema_default="无显式default;保存文本不冒充默认",
limits=(
"准确core0.8.2 STRING multiline/dynamicPrompts"
if display == "131:113"
else "准确core0.9.1 STRING multiline=True"
)
+ ";只读原文,不执行指令",
unit="编码文本",
)
fields.append(f)
flow.extend(
("根物理边 " if not prefix else prefix + " 物理边 ") + json.dumps(e, ensure_ascii=False)
for e in graph["links"]
)
if prefix:
h = next(n for n in g["nodes"] if n["id"] == host)
boundaries.append(
dict(
scope=prefix,
**{
k: graph[k]
for k in ["id", "inputNode", "outputNode", "inputs", "outputs", "widgets"]
},
)
)
boundaries.append(
dict(
host_pointer=f"/nodes/{g['nodes'].index(h)}",
host_saved=h["widgets_values"],
proxyWidgets=h["properties"]["proxyWidgets"],
inputs=h["inputs"],
effect=f"宿主{host}仅声明,不赋予内部身份;空保存、代理和边界分列,不造有效值。",
)
)
assert len(fields) == 39 and sum(f["scope"] == "root" for f in fields) == 14
overview = (
"这张图希望把第二图的人物及服装替换到第一图,保持第一图场景、动作和光效:第一图先缩放,第"
"二图先去背景,两参考依次加入正负条件,再从空latent生成并正式保存。人物、服装与场景"
"保持只是作者意图,实际效果尚未验证。"
)
flow.insert(
0,
(
"根8节点5边;第一定义21节点36含边界边;第二定义4节点8边,全mode0。根14+第"
"一定义24+第二定义1=39标量,无Note/具名保存;两个Label缺键、两个空宿主和"
"内部[]及定义widgets=[]分开。"
),
)
flow.extend(
[
(
"第一定义8代理6输入、第二定义1代理2输入,跨作用域相同ID"
"/UUID不合并。无LoRA/Comparer/历史列表,不"
"制造这些字段。"
),
(
"原件cnr_id为comfyui_layerstyle但aux_id为aining202"
"2/ComfyUI_Swwan;完整881bc917对象仅在aux仓库取得,LayerS"
"tyle仓库精确提交获取失败,身份差异保留,不以同名等同提供方。"
),
(
"前端准确1.36.14、锁文件与同树代码仅绑定本图;SubgraphNode.confi"
"gure恢复边界/相连widget、serialize前同步与serialize_wid"
"gets/serialize=false条件仅静态说明;8/1代理不证明保存或目标恢复。"
"UE7.5.2/7.7/7.8和tab实现未知,不模拟回填。"
),
(
"常见问题:52宽高出口未接;实际四尺寸覆盖源自110→108,第二图不控制画布。43输出"
"声明与准确0.9.2冲突,保留并关闭;MASK缺键、空列表、反转及Alpha链不能视为已"
"证明透明或局部编辑。"
),
]
)
flow.extend("原定义边界/宿主声明 " + json.dumps(x, ensure_ascii=False) for x in boundaries)
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="仅参考:目标安装/恢复、模型/素材/许可与实际人物迁移效果未核;43输出协议冲突保留,停用且转换关闭。",
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()
]
+ [
(
"旧58块2238位置+66注释逐对象冻结;local_fil"
"e以docs/hel-892/flux2-person-do"
"cument-evidence为基准。"
)
],
counts=dict(
saved_fields=39,
root_saved_fields=14,
internal_saved_fields=25,
linked_saved_fields=sum(f["role"] == "linked_saved_cache" for f in fields),
frontend_only=sum(f["role"] == "frontend_reference_only" for f in fields),
source_nodes=33,
root_nodes=8,
internal_nodes=25,
physical_edges=49,
source_notes=0,
history_objects=0,
final_scalars=0,
final_prompt_constructed=False,
),
fields=fields,
sources=sources,
comments=[],
flow=flow,
flow_evidence=list(range(len(sources))),
zero_saved_nodes=empty,
boundaries=boundaries,
steps=[
overview,
"阅读1:核对39位置原值/类型、完整正向与空负向、模型异名、两个独立子图及代理;仅读文本,不打开媒体/链接。",
(
"阅读2:第一图尺寸覆盖四缓存、正负分别先第一再第二参考、空l"
"atent起点、背景模型/Invert/Join双反转链与正"
"式保存;不试算尺寸或推定M极性。"
),
(
"阅读3:保持停用、未检查和空时间戳;155完整定稿及必要实跑"
"未完成,全量审核后才发布;不构造prompt、不执行上游/模"
"型/种子/GPU/媒体,不连接目标或下载。"
),
],
)