Files
aigc-home/docs/hel-892/portrait-master-document-evidence/build_definition.py
T
2026-11-01 05:25:54 +08:00

345 lines
15 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 pinned string-only reference, parsed as data; 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 / "portrait-master-reference"
PATHS = ["example_ComfyUI_workflows/3-图像生成/肖像大师_美女提示词生成.json"]
IDENTITIES = {
"PortraitMasterStylePose": ("portrait", "PortraitMasterStylePose"),
"PortraitMaster_中文版": ("portraitzh", "PortraitMaster_中文版"),
"CR Prompt Text": ("cr", "CR_PromptText"),
"CR Text Input Switch (4 way)": ("cr", "CR_TextInputSwitch4way"),
"ShowText|pysssss": ("show", "ShowText"),
}
LABELS = {
"model_pose": "姿势模板选择",
"clothes": "衣着模板选择",
"female_lingerie": "内衣模板选择",
"makeup": "妆容模板选择",
"light_type": "灯光模板选择",
"light_direction": "灯光方向选择",
"light_weight": "灯光文本权重",
"style_1": "风格模板一",
"style_1_weight": "风格一文本权重",
"style_2": "风格模板二",
"style_2_weight": "风格二文本权重",
"photorealism_improvement": "写真文本追加开关",
"active": "模板分支启用保存",
"load_preset": "文件预设选择",
"save_preset_as": "预设保存名称",
"save_preset": "预设写文件开关保存",
"seed": "可选seed输入对应保存候选",
"seed_control_candidate": "首个randomize前端辅助候选",
"unmapped_saved_18": "末尾未映射空串位置18",
"unmapped_saved_19": "末尾未映射布尔位置19",
"unmapped_saved_20": "末尾未映射整数位置20",
"unmapped_saved_21": "末尾randomize未映射候选位置21",
"prompt": "完整英文字符串保存",
"history_text": "完整历史显示缓存",
"Input": "四路字符串选口保存",
}
def canonical(v):
return json.dumps(v, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
def extract_schema(cls):
method = next(m for m in cls.body if isinstance(m, ast.FunctionDef) and m.name == "INPUT_TYPES")
ret = next(
n.value
for n in ast.walk(method)
if isinstance(n, ast.Return) and isinstance(n.value, ast.Dict)
)
constants = {
n.targets[0].id: n.value.value
for n in method.body
if isinstance(n, ast.Assign)
and len(n.targets) == 1
and isinstance(n.targets[0], ast.Name)
and isinstance(n.value, ast.Constant)
}
result = {}
for k, group in zip(ret.keys, ret.values, strict=True):
if (
not isinstance(k, ast.Constant)
or k.value not in ["required", "optional"]
or not isinstance(group, ast.Dict)
):
continue
for name, spec in zip(group.keys, group.values, strict=True):
if not isinstance(name, ast.Constant) or not isinstance(spec, ast.Tuple):
continue
default = "未声明default;不借execute缺省或保存值补默认"
for opts in spec.elts[1:]:
if not isinstance(opts, ast.Dict):
continue
for dk, dv in zip(opts.keys, opts.values, strict=True):
if isinstance(dk, ast.Constant) and dk.value == "default":
default = ast.unparse(dv)
limits = ast.unparse(spec)
for key, value in constants.items():
limits += f";准确局部常量{key}={value!r}"
result[name.value] = dict(default=default, limits=limits, group=k.value)
return result
def build(index=0):
raw = (REPO / PATHS[index]).read_bytes()
g = json.loads(raw)
prose = json.loads((OUT / "prose.json").read_bytes())
editorial = json.loads((OUT / "editorial.json").read_bytes())
field_notes = json.loads((OUT / "field-notes.json").read_bytes())
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="../portrait-master-reference/" + e["local_file"],
lines=[1, len(data.decode().splitlines())],
claim="本图准确版本必要源码/词表/许可静态原文;目标安装与模型素材许可未认证",
)
)
if e["file"].endswith(".py"):
trees[e["local_file"]] = ast.parse(data)
fields, comments, flow, bindings = [], [], [], []
for i, n in enumerate(g["nodes"]):
nid, cls, ptr = str(n["id"]), n["type"], f"/nodes/{i}"
assert "widgets_values_named" not in n and n["mode"] == 0
if cls == "Note":
comments.append(
dict(
node_id=nid,
pointer=ptr + "/widgets_values/0",
text=n["widgets_values"][0],
meaning=prose["notes"][nid],
evidence=[],
)
)
flow.append(nid + " 原注释节点 " + json.dumps(n, ensure_ascii=False))
continue
key, symbol = IDENTITIES[cls]
matches = [
(k, c)
for k, e in enumerate(manifest)
if e["id"] == key and e["file"].endswith(".py")
for c in trees[e["local_file"]].body
if isinstance(c, ast.ClassDef) and c.name == symbol
]
assert len(matches) == 1, (nid, matches)
source_i, c = matches[0]
sources.append(
dict(
sources[source_i],
lines=[c.lineno, c.end_lineno],
claim="本节点准确声明类/schema/实现;不认证源控件恢复或真实输出",
)
)
refs = [source_i, len(sources) - 1] + [
k for k, e in enumerate(manifest) if e["id"] in [key, "frontend", "litegraph"]
]
refs = list(dict.fromkeys(refs))
schema = extract_schema(c)
bindings.append(
dict(
node_id=nid,
class_type=cls,
source_version=n["properties"]["ver"],
source_id=key,
candidates=[dict(source=source_i, symbol=symbol, lines=[c.lineno, c.end_lineno])],
)
)
if cls == "PortraitMasterStylePose":
layout = (
[k for k, v in schema.items() if v["group"] == "required"]
+ ["seed", "seed_control_candidate"]
+ [f"unmapped_saved_{j}" for j in range(18, 22)]
)
elif cls == "PortraitMaster_中文版":
layout = [k for k, v in schema.items() if v["group"] == "required"]
elif cls == "ShowText|pysssss":
layout = ["history_text"]
elif cls == "CR Prompt Text":
layout = ["prompt"]
else:
layout = ["Input"]
effect = editorial[nid] + " 原mode=0仅活动保存态,不认证插件运行/实际输出。"
flow += [
effect,
nid + " 原属性 " + json.dumps(n.get("properties", {}), ensure_ascii=False),
nid
+ " 原输入/输出 "
+ json.dumps({k: n[k] for k in ["inputs", "outputs"]}, ensure_ascii=False),
]
for j, (name, value) in enumerate(zip(layout, n["widgets_values"], strict=True)):
candidates = [k for k, x in enumerate(n["inputs"]) if x["name"] == name]
inp = candidates[0] if len(candidates) == 1 else None
default = schema.get(name, {}).get(
"default", "未知:没有与本位置一一匹配的准确schema默认"
)
limits = schema.get(name, {}).get(
"limits", "未知:仅保存位置;准确映射/默认/范围/算法/副作用未核准"
)
unit = "文本/枚举/布尔接口,无物理单位;不把保存模板关联实际人物或效果"
role = "saved_reference"
if nid == "30":
unit = (
"文本权重系数,无物理单位,不执行权重"
if "权重" in name
or name
in [
"国籍混合",
"面部对称性",
"头发蓬松度",
"皮肤细节",
"皮肤毛孔",
"酒窝",
"皱纹",
"雀斑",
"痣",
"皮肤瑕疵",
"痘痘",
"小麦色肤色",
"眼睛细节",
"虹膜细节",
"圆形虹膜",
"圆形瞳孔",
]
else "岁;仅模板年龄数值,非真实人物年龄"
if name == "年龄"
else unit
)
if default.endswith("_list[0]"):
default += ";准确构造先追加'-',因此默认'-',不从保存选择推定"
if nid == "31":
role = "schema_order_saved_candidate"
limits += (
";前16按准确required顺序静态候选,"
"源输入另含无本版schema的background/camera四口;"
"缺具名值,不认证前端恢复。"
)
if "weight" in name:
unit = "文本权重系数,无物理单位;max_float_value=2,非生成强度"
if name == "seed":
unit = (
"整数接口参考;本版pmsp没有读取/设定seed或random.seed,不能保证随机可复现"
)
if name == "seed_control_candidate":
default = "准确frontend1.23.0控制辅助缺省randomize;本位置仅seed后相邻候选"
limits = (
"fixed/increment/decrement/randomize;前端辅助不进后端参数,"
"不执行随机或认证此控件恢复"
)
role = "frontend_candidate_unknown"
if name.startswith("unmapped_saved_"):
default = "未知:末尾位置不在准确类schema映射中,不由值或相邻randomize补名称"
limits = (
"未知:无具名值/本版schema映射;连同末尾randomize仅原保存候选,"
"不造第二seed或后端参数"
)
unit = "未知:未核准此位置映射与单位/算法/副作用"
role = "unmapped_saved_candidate"
if name == "history_text":
default = "前端历史显示缓存,无history_text后端输入默认"
limits = (
"准确ShowText frontend只读text_N动态控件/历史恢复;"
"完整字符串不是本次计算结果;notify返回ui.text及result=(text,)"
"且输入输出均list语义"
)
role = "frontend_reference_only"
if name == "Input":
unit = "整数选口编号1..4;非表达式或执行次数"
fields.append(
dict(
node_id=nid,
definition_node_id=nid,
scope="root",
class_type=cls,
field=name,
label=LABELS.get(name, name + "保存值"),
pointer=f"{ptr}/widgets_values/{j}",
value=value,
json_type=type(value).__name__,
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=role,
schema_default=default,
limits=limits,
unit=unit,
effect=field_notes.get(nid, {}).get(
name, "当前字段用途及对应条件见本节点说明;仅保存参考。"
)
+ " "
+ effect,
evidence=refs,
execution_note="仅源数据静态参考;不构造/改写prompt,不导入上游/插件、读取目标词表或预设目录、执行随机/选口/SDK/LLM/模型/媒体或清理,转换执行资格不变。",
)
)
flow += [
f"节点{nid}准确schema {k}:default={v['default']};{v['limits']};仅静态参考。"
for k, v in schema.items()
]
flow += ["root 物理边 " + json.dumps(e, ensure_ascii=False) for e in g["links"]]
flow += ["根附加保存属性 " + json.dumps(g["extra"], ensure_ascii=False)] + prose["steps"]
flow += ["注释" + c["node_id"] + " 中文核对:" + c["meaning"] for c in comments]
assert len(fields) == 69 and len(comments) == 1
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="仅固定字符串参考:历史缓存不等于本次输出,StylePose额外位置与声明口不等于准确schema;没有模型/采样/图像保存链,资格不变。",
user_overview=prose["overview"],
versions=[
(
f"{e['id']} {e['tag']} commit {e.get('commit', '发布成员Git未知')};"
f"许可入口{e['license_file']}"
)
for e in {e["id"]: e for e in manifest}.values()
]
+ [
"frontend1.23.0同树package-lock绑定LiteGraph0.15.15准确发布成员,Git未知;许可/历史包摘要与本轮复核分列。",
"旧105块5777位置/183注释冻结;新增69位置/唯一Note,总106图5846位置/184注释仅参考。",
],
counts=dict(
saved_fields=69,
root_saved_fields=69,
internal_saved_fields=0,
linked_saved_fields=0,
boundary_saved_fields=0,
frontend_only=3,
frontend_candidate_fields=1,
unmapped_saved_fields=4,
source_nodes=9,
root_nodes=9,
internal_nodes=0,
physical_edges=7,
source_notes=1,
saved_objects=0,
history_objects=3,
scalar_saved_fields=69,
final_scalars=0,
final_prompt_constructed=False,
),
node_bindings=bindings,
fields=fields,
sources=sources,
comments=comments,
flow=flow,
flow_evidence=list(range(len(sources))),
zero_saved_nodes=[],
boundaries=[],
steps=[prose["overview"]] + prose["steps"],
)