394 lines
17 KiB
Python
394 lines
17 KiB
Python
"""Conservative offline conversion; partial or ambiguous prompts are never returned.
|
|
|
|
object_info does not define custom frontend widget serialization. Only named
|
|
widgets pass. Even input_order cannot prove arbitrary frontend serialization.
|
|
The separate convert_reference entry point supports a bounded public-source
|
|
profile for offline comparison only; it never changes production eligibility.
|
|
Explicit structural profiles expose subgraph diagnostics only. Production
|
|
subgraphs, seed extra controls, mute and bypass remain unsupported.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass, field
|
|
from typing import Any
|
|
|
|
from .serialization_reference import (
|
|
ASR_PROFILE,
|
|
AUX_PROFILE,
|
|
CASE04_PROFILE,
|
|
CROP_SPLIT_PROFILES,
|
|
MEDIA_PROFILES,
|
|
PREVIEW_PROFILE,
|
|
PRIMITIVE_PROFILE,
|
|
PROFILE,
|
|
SEPARATION_PROFILE,
|
|
VHS_PROFILES,
|
|
case04_definitions,
|
|
fold_reference_primitives,
|
|
promoted_definitions,
|
|
reference_definitions,
|
|
resolve_reference_link,
|
|
serialize_case04_node,
|
|
serialize_promoted_node,
|
|
serialize_reference_widgets,
|
|
validate_reroute,
|
|
)
|
|
from .structure_reference import PROMOTED_PROFILES, STRUCTURE_PROFILES, expand_reference_subgraphs
|
|
|
|
|
|
@dataclass
|
|
class Conversion:
|
|
prompt: dict[str, Any] | None
|
|
issues: list[dict[str, Any]] = field(default_factory=list)
|
|
reference_only: bool = False
|
|
diagnostic_graph: dict[str, Any] | None = None
|
|
unresolved_boundaries: list[dict[str, Any]] = field(default_factory=list)
|
|
resolved_boundaries: list[dict[str, Any]] = field(default_factory=list)
|
|
serialization_stage: str | None = None
|
|
|
|
|
|
def convert(source: Any, object_info: dict[str, Any] | None = None) -> Conversion:
|
|
return _convert(source, object_info)
|
|
|
|
|
|
def convert_reference(source: Any, profile: str = PROFILE) -> Conversion:
|
|
"""Offline candidate only. Never consumed by production library import.
|
|
|
|
An unknown profile is rejected, not interpreted as a widget-order contract.
|
|
Public reference definitions cannot establish target execution eligibility.
|
|
"""
|
|
if (
|
|
profile
|
|
not in (
|
|
PROFILE,
|
|
ASR_PROFILE,
|
|
*MEDIA_PROFILES,
|
|
SEPARATION_PROFILE,
|
|
*CROP_SPLIT_PROFILES,
|
|
*VHS_PROFILES,
|
|
AUX_PROFILE,
|
|
PRIMITIVE_PROFILE,
|
|
PREVIEW_PROFILE,
|
|
CASE04_PROFILE,
|
|
*STRUCTURE_PROFILES,
|
|
*PROMOTED_PROFILES,
|
|
)
|
|
or not isinstance(source, dict)
|
|
or "nodes" not in source
|
|
):
|
|
return Conversion(
|
|
None,
|
|
[{"code": "invalid_reference_contract", "message": "未知参考版本或不是 UI 图"}],
|
|
True,
|
|
)
|
|
try:
|
|
if (
|
|
profile in VHS_PROFILES
|
|
and VHS_PROFILES[profile] == "1.48.6"
|
|
and (source.get("extra") or {}).get("frontendVersion") != "1.48.6"
|
|
):
|
|
raise ValueError("VHS 1.48.6参考要求显式前端声明;缺失仅选择1.37.11")
|
|
if profile in (*STRUCTURE_PROFILES, *PROMOTED_PROFILES, CASE04_PROFILE):
|
|
case04 = profile == CASE04_PROFILE
|
|
promoted = profile in PROMOTED_PROFILES or case04
|
|
structure_profile = (
|
|
"comfy-frontend-1.53.6-structure-reference"
|
|
if case04
|
|
else profile.replace("-promoted-reference", "-structure-reference")
|
|
)
|
|
structure = expand_reference_subgraphs(
|
|
source, structure_profile, widgets=promoted, case04=case04
|
|
)
|
|
if structure.graph is None:
|
|
return Conversion(None, structure.issues, True)
|
|
# Structural scope never supplies widget contracts for newer versions.
|
|
# List the concrete remaining node gaps instead of one subgraph error.
|
|
result = _convert(
|
|
structure.graph,
|
|
case04_definitions() if case04 else promoted_definitions() if promoted else {},
|
|
reference=True,
|
|
reference_profile=profile,
|
|
boundary_values=structure.resolved,
|
|
)
|
|
result.issues = structure.issues + result.issues
|
|
for boundary in structure.unresolved:
|
|
result.issues.append(
|
|
{
|
|
"code": "boundary_widget_unverified",
|
|
**boundary,
|
|
"message": boundary.get(
|
|
"reason", "边界无外部连线;不按位置猜 promoted widget 值"
|
|
),
|
|
}
|
|
)
|
|
if not promoted or result.issues:
|
|
result.prompt = None
|
|
result.reference_only = True
|
|
if case04:
|
|
result.serialization_stage = "restored_saved_state_before_queue_hooks"
|
|
result.diagnostic_graph = structure.graph
|
|
result.unresolved_boundaries = structure.unresolved
|
|
result.resolved_boundaries = structure.resolved
|
|
return result
|
|
if (
|
|
profile in (PREVIEW_PROFILE, ASR_PROFILE)
|
|
and (source.get("extra") or {}).get("frontendVersion") != "1.37.11"
|
|
):
|
|
raise ValueError("PreviewAny 需要显式1.37.11前端声明")
|
|
if profile in (
|
|
*MEDIA_PROFILES,
|
|
SEPARATION_PROFILE,
|
|
*CROP_SPLIT_PROFILES,
|
|
*VHS_PROFILES,
|
|
) and any(node.get("type") == "Reroute" for node in source.get("nodes", [])):
|
|
raise ValueError("媒体最小参考仅覆盖直接连线,不扩展虚拟节点")
|
|
if profile in (SEPARATION_PROFILE, *CROP_SPLIT_PROFILES, *VHS_PROFILES) and any(
|
|
(source.get("extra") or {}).get(k) for k in ("ue_links", "links_added_by_ue")
|
|
):
|
|
raise ValueError("音频分离参考不覆盖UE附加连线")
|
|
original = source
|
|
if profile in (PRIMITIVE_PROFILE, PREVIEW_PROFILE):
|
|
source = fold_reference_primitives(source, profile)
|
|
result = _convert(
|
|
source, reference_definitions(profile), reference=True, reference_profile=profile
|
|
)
|
|
if profile in (PRIMITIVE_PROFILE, PREVIEW_PROFILE) and source != original:
|
|
result.diagnostic_graph = source
|
|
except (ValueError, TypeError, KeyError, AttributeError, IndexError) as exc:
|
|
return Conversion(None, [{"code": "invalid_reference_contract", "message": str(exc)}], True)
|
|
result.reference_only = True
|
|
if profile in (
|
|
ASR_PROFILE,
|
|
*MEDIA_PROFILES,
|
|
SEPARATION_PROFILE,
|
|
*CROP_SPLIT_PROFILES,
|
|
*VHS_PROFILES,
|
|
):
|
|
result.serialization_stage = "restored_saved_state_before_queue_hooks"
|
|
return result
|
|
|
|
|
|
def _convert(
|
|
source, object_info=None, *, reference=False, reference_profile=PROFILE, boundary_values=()
|
|
) -> Conversion:
|
|
issues: list[dict[str, Any]] = []
|
|
|
|
def fail(code: str, message: str, node_id: Any = "") -> None:
|
|
issues.append({"code": code, "message": message, "node_id": str(node_id)})
|
|
|
|
if not isinstance(source, dict):
|
|
return Conversion(None, [{"code": "invalid_format", "message": "源文件不是 JSON 对象"}])
|
|
if "nodes" not in source:
|
|
if source and all(
|
|
isinstance(n, dict)
|
|
and isinstance(n.get("class_type"), str)
|
|
and isinstance(n.get("inputs"), dict)
|
|
for n in source.values()
|
|
):
|
|
for nid, node in source.items():
|
|
for name, value in node["inputs"].items():
|
|
if isinstance(value, list):
|
|
if (
|
|
len(value) != 2
|
|
or not isinstance(value[0], str)
|
|
or value[0] not in source
|
|
or type(value[1]) is not int
|
|
or value[1] < 0
|
|
):
|
|
fail("invalid_api_link", f"输入 {name} 的 API 连线无法核对", nid)
|
|
if issues:
|
|
return Conversion(None, issues)
|
|
return Conversion(source)
|
|
return Conversion(
|
|
None, [{"code": "invalid_format", "message": "无法识别 API 或 UI 图格式"}]
|
|
)
|
|
if not isinstance(source["nodes"], list):
|
|
return Conversion(None, [{"code": "invalid_format", "message": "nodes 必须为数组"}])
|
|
if (source.get("definitions") or {}).get("subgraphs"):
|
|
fail("subgraph_requires_export", "包含子图:需原 ComfyUI API 导出及差分核对")
|
|
info = object_info or {}
|
|
nodes = {str(n["id"]): n for n in source["nodes"] if isinstance(n, dict) and "id" in n}
|
|
if len(nodes) != len(source["nodes"]):
|
|
fail("invalid_nodes", "节点 ID 缺失或重复")
|
|
links = {}
|
|
for link in source.get("links") or []:
|
|
if not isinstance(link, list) or len(link) < 6:
|
|
fail("unsupported_links", "连线格式需原 ComfyUI API 导出核对")
|
|
else:
|
|
if str(link[0]) in links:
|
|
fail("duplicate_link", "连线 ID 重复")
|
|
links[str(link[0])] = link
|
|
if reference:
|
|
frontend_version = (source.get("extra") or {}).get("frontendVersion")
|
|
expected_version = {
|
|
**STRUCTURE_PROFILES,
|
|
**PROMOTED_PROFILES,
|
|
CASE04_PROFILE: "1.53.6",
|
|
**VHS_PROFILES,
|
|
}.get(reference_profile, "1.37.11")
|
|
if frontend_version is not None and frontend_version != expected_version:
|
|
fail("reference_frontend_mismatch", "源图声明的前端版本与固定参考不一致")
|
|
# Validate every stored link, even unused branches: never silently drop
|
|
# an unsupported connection to obtain a partial candidate.
|
|
for node in nodes.values():
|
|
for slot, socket in enumerate(node.get("inputs", [])):
|
|
lid = socket.get("link")
|
|
if lid is not None:
|
|
link = links.get(str(lid))
|
|
if not link or str(link[3]) != str(node["id"]) or link[4] != slot:
|
|
fail("reference_link_invalid", "输入与连线目标记录不对应", node["id"])
|
|
for slot, socket in enumerate(node.get("outputs", [])):
|
|
for lid in socket.get("links") or []:
|
|
link = links.get(str(lid))
|
|
if not link or str(link[1]) != str(node["id"]) or link[2] != slot:
|
|
fail("reference_link_invalid", "输出与连线来源记录不对应", node["id"])
|
|
for lid in links:
|
|
try:
|
|
resolve_reference_link(nodes, links, lid)
|
|
if reference_profile in (
|
|
*MEDIA_PROFILES,
|
|
SEPARATION_PROFILE,
|
|
*CROP_SPLIT_PROFILES,
|
|
*VHS_PROFILES,
|
|
):
|
|
link = links[lid]
|
|
upstream = nodes[str(link[1])]["outputs"][link[2]]
|
|
downstream = nodes[str(link[3])]["inputs"][link[4]]
|
|
if link[5] != upstream.get("type") or link[5] != downstream.get("type"):
|
|
raise ValueError("媒体连线类型记录与两端槽不符")
|
|
except (ValueError, TypeError, KeyError, AttributeError) as exc:
|
|
fail("reference_link_invalid", str(exc))
|
|
prompt = {}
|
|
for nid, node in nodes.items():
|
|
ct = node.get("type", "")
|
|
if ct in ("Note", "MarkdownNote"):
|
|
continue
|
|
if node.get("mode", 0) != 0:
|
|
fail("mode_requires_export", f"{ct} 包含静音/旁路状态,需 API 导出核对", nid)
|
|
continue
|
|
if reference and ct == "Reroute":
|
|
try:
|
|
validate_reroute(node)
|
|
resolve_reference_link(nodes, links, node["inputs"][0].get("link"))
|
|
except (ValueError, TypeError, KeyError, AttributeError) as exc:
|
|
fail("reference_link_invalid", str(exc), nid)
|
|
continue
|
|
spec = info.get(ct)
|
|
if not isinstance(spec, dict):
|
|
if reference:
|
|
fail("reference_node_unsupported", f"固定参考契约未覆盖节点:{ct}", nid)
|
|
else:
|
|
fail("node_definition_unavailable", f"待提供目标机节点定义:{ct}", nid)
|
|
continue
|
|
declared = {
|
|
**spec.get("input", {}).get("required", {}),
|
|
**spec.get("input", {}).get("optional", {}),
|
|
}
|
|
sockets = {s["name"]: s for s in node.get("inputs", []) if "name" in s}
|
|
widgets = node.get("widgets_values") or []
|
|
inputs = {}
|
|
if reference:
|
|
try:
|
|
inputs.update(
|
|
serialize_case04_node(node)
|
|
if reference_profile == CASE04_PROFILE
|
|
else serialize_promoted_node(node, PROMOTED_PROFILES[reference_profile])
|
|
if reference_profile in PROMOTED_PROFILES
|
|
else serialize_reference_widgets(node, reference_profile)
|
|
)
|
|
if [s.get("type") for s in node.get("outputs", [])] != spec["output"]:
|
|
raise ValueError("源输出槽不符合固定参考契约")
|
|
names = [s.get("name") for s in node.get("inputs", [])]
|
|
allowed = set(declared) | ({"upload"} if ct == "LoadImage" else set())
|
|
if (
|
|
reference_profile
|
|
in (
|
|
PRIMITIVE_PROFILE,
|
|
PREVIEW_PROFILE,
|
|
ASR_PROFILE,
|
|
*MEDIA_PROFILES,
|
|
SEPARATION_PROFILE,
|
|
*CROP_SPLIT_PROFILES,
|
|
)
|
|
and ct == "LoadAudio"
|
|
):
|
|
allowed |= {"upload", "audioUI"}
|
|
if len(names) != len(set(names)) or set(names) - allowed:
|
|
raise ValueError("额外或重复输入槽不在固定参考契约内")
|
|
except (ValueError, TypeError, AttributeError) as exc:
|
|
fail("reference_widget_unverified", str(exc), nid)
|
|
continue
|
|
elif isinstance(widgets, dict):
|
|
if set(widgets) - set(declared):
|
|
fail("unknown_widget", f"{ct} 存在节点定义以外的具名控件", nid)
|
|
inputs.update({k: v for k, v in widgets.items() if k in declared})
|
|
elif widgets:
|
|
fail(
|
|
"widget_layout_unverified",
|
|
f"{ct} 控件为位置数组;input_order 不证明前端序列化顺序,需 API 导出核对",
|
|
nid,
|
|
)
|
|
continue
|
|
# graphToPrompt writes resolved promoted widgetInfo after the ordinary
|
|
# serializer, before/alongside resolved links. Values bypass the inner
|
|
# custom serializeValue; external links still take priority below.
|
|
for boundary in boundary_values:
|
|
if boundary["node_id"] == nid:
|
|
inputs[boundary["input_name"]] = boundary["value"]
|
|
for name, socket in sockets.items():
|
|
lid = socket.get("link")
|
|
if lid is None:
|
|
continue
|
|
link = links.get(str(lid))
|
|
if (
|
|
not link
|
|
or str(link[3]) != nid
|
|
or not isinstance(link[4], int)
|
|
or not 0 <= link[4] < len(node.get("inputs", []))
|
|
):
|
|
fail("invalid_link", f"输入 {name} 的连线无效", nid)
|
|
continue
|
|
if node["inputs"][link[4]].get("name") != name or name not in declared:
|
|
fail("invalid_socket", f"输入 {name} 的目标槽不匹配", nid)
|
|
continue
|
|
if reference:
|
|
try:
|
|
resolved = resolve_reference_link(nodes, links, lid)
|
|
link = [link[0], resolved[0], resolved[1], *link[3:]]
|
|
except (ValueError, TypeError, KeyError, AttributeError) as exc:
|
|
fail("reference_link_invalid", str(exc), nid)
|
|
continue
|
|
upstream = nodes.get(str(link[1]))
|
|
outputs = info.get((upstream or {}).get("type"), {}).get("output", [])
|
|
if not upstream or not isinstance(link[2], int) or not 0 <= link[2] < len(outputs):
|
|
fail("invalid_output_slot", f"输入 {name} 的来源槽无法核对", nid)
|
|
continue
|
|
inputs[name] = [str(link[1]), link[2]]
|
|
expected = declared[name][0] if declared[name] else None
|
|
actual = outputs[link[2]]
|
|
# Custom unions/wildcards need frontend evidence; do not guess coercions.
|
|
if expected != actual and not (
|
|
reference
|
|
and reference_profile in (PREVIEW_PROFILE, CASE04_PROFILE, ASR_PROFILE)
|
|
and ct == "PreviewAny"
|
|
and name == "source"
|
|
and expected == "*"
|
|
):
|
|
fail(
|
|
"link_type_unverified",
|
|
f"输入 {name} 的槽类型不一致:{actual} → {expected}",
|
|
nid,
|
|
)
|
|
for name in spec.get("input", {}).get("required", {}):
|
|
if name not in inputs:
|
|
fail("missing_required_input", f"{ct}.{name} 缺少源文件值或连线", nid)
|
|
prompt[nid] = {
|
|
"class_type": ct,
|
|
"inputs": inputs,
|
|
"_meta": {"title": node.get("title") or ct},
|
|
}
|
|
if not prompt:
|
|
fail("empty_prompt", "未得到可执行节点")
|
|
return Conversion(None if issues else prompt, issues)
|