"""UI→API converter for ComfyUI workflow JSON (HEL-681 / S2 data layer). ComfyUI saves two formats: the editor ("UI") format with ``nodes``/``links`` arrays, and the API ("prompt") format ``{node_id: {class_type, inputs}}`` the product executes. This module converts UI→API offline and deterministically: * links are rewritten through ``Reroute`` chains and bypassed (mode 4) nodes; * packed subgraph instances (frontend ≥1.x ``definitions.subgraphs``) expand into their inner nodes under qualified ids ``:`` — the same scheme ComfyUI itself exports; * widget values map through, in priority order: the node's serialized input list (entries carrying a ``widget`` marker — authoritative, this corpus's frontend version always writes them), the ``widgets_values_named`` dict, then a generated registry of widget orders learned from the corpus and the repo's ground-truth API exports (``ui_widget_orders``). Anything that cannot be mapped with certainty is reported as an issue and the file is flagged ``needs_confirmation`` — never silently guessed: a wrong widget order produces a runnable-looking workflow with swapped seed/steps, which is worse than an honest「需人工确认」. """ from __future__ import annotations from dataclasses import dataclass, field from typing import Any from calliope.comfyui.ui_widget_orders import WIDGET_ORDERS # Values of the frontend-only "control_after_generate" control that serializes # right after every seed-like INT widget (and is not a real server input). _CONTROL_MODES = frozenset({"fixed", "increment", "decrement", "randomize"}) # Widget names that are pure UI buttons/previews — never serialized in # widgets_values (named dicts skip them too) and never API inputs. _BUTTON_WIDGETS = frozenset( {"preview", "audioUI", "compare_view", "ToggleableColorPicker", "imagebrowser"} ) # Leftover positional values that are provably action buttons, not data: # known labels, self-describing ids, or emoji-prefixed actions. Anything # else left over keeps the file in the needs-confirmation queue. _BUTTON_LEFTOVER_LABELS = frozenset({"Edit", "lanpaint_star_button"}) _BUTTON_LEFTOVER_EMOJI = ("🖼", "🎬", "🎵", "➕", "🔁", "🗑", "📂", "🔎", "✨") def _is_button_leftover(value: Any) -> bool: if value is None or value == "": return True if isinstance(value, str): return ( value in _BUTTON_LEFTOVER_LABELS or "button" in value.lower() or value.startswith(_BUTTON_LEFTOVER_EMOJI) ) return False # Virtual editor-only nodes. Links pass *through* reroute-style ones (see # _resolve_source); the rest are dropped from the graph entirely. _REROUTE_TYPES = frozenset({"Reroute", "Reroute (rgthree)"}) # Frontend-virtual variable nodes: SetNode captures a value under a name, # GetNode reads it. Neither reaches the server — links through a Get resolve # to whatever its same-named Set captured (scope-local). _SET_TYPES = frozenset({"SetNode"}) _GET_TYPES = frozenset({"GetNode"}) _UI_ONLY_TYPES = frozenset( { "Note", "MarkdownNote", "Image Comparer (rgthree)", "GH_ImageVideoComparer", "Label (rgthree)", "Fast Groups Bypasser (rgthree)", "Fast Groups Muter (rgthree)", "Fast Muter (rgthree)", "FastGroupsBypassSwitch", "Mute / Bypass Repeater (rgthree)", } ) # Server-side OUTPUT nodes: the closure roots. Learned from the repo's # ground-truth API exports (their unreferenced classes) + the corpus's # real save/preview sinks (SaveVideo/SaveImageAdvanced/… custom nodes). _OUTPUT_CLASSES = frozenset( { "SaveImage", "PreviewImage", "SaveImageAdvanced", "SaveImageKJ", "SaveAnimatedWEBP", "SaveAnimatedPNG", "SaveAnimatedGIF", "SaveVideo", "SaveAudio", "SaveAudioMP3", "SaveAudioAdvanced", "PreviewAudio", "MaskPreview", "MaskPreview+", "ImageAndMaskPreview", "VHS_VideoCombine", "easy saveVideo", "easy multitrackProjectVideoCombine", "easy multiTrackInfoOutput", "easy multiTrackTaskOutput", "easy compareVideos", "easy compareImages", "easy showText", "easy imageWall", "CR Prompt Text", "PreviewAny", "easy clearGpuUsed", "easy clearCacheAll", "easy showSpentTime", } ) MODE_ACTIVE = 0 MODE_MUTED = 2 MODE_BYPASSED = 4 _SUBGRAPH_IN = -10 # pseudo-node id of a subgraph's boundary input _SUBGRAPH_OUT = -20 # pseudo-node id of a subgraph's boundary output @dataclass class ConvertIssue: node_id: str code: str message: str level: str = "warning" # 'error' | 'warning' @dataclass class ConvertResult: workflow: dict[str, Any] | None status: str # 'ok' | 'warn' | 'fail' issues: list[ConvertIssue] = field(default_factory=list) @property def needs_confirmation(self) -> bool: """Widget mapping uncertain — must not be imported as runnable.""" return any( i.code in ("widget_unmapped", "widget_order_mismatch") for i in self.issues ) def _norm_link(link: Any) -> tuple[int, int, int, int, int, str] | None: """(id, origin_id, origin_slot, target_id, target_slot, type) from either form.""" if isinstance(link, dict): try: return ( int(link["id"]), int(link["origin_id"]), int(link["origin_slot"]), int(link["target_id"]), int(link["target_slot"]), str(link.get("type") or "*"), ) except (KeyError, TypeError, ValueError): return None if isinstance(link, (list, tuple)) and len(link) >= 5: try: return ( int(link[0]), int(link[1]), int(link[2]), int(link[3]), int(link[4]), str(link[5]) if len(link) > 5 and link[5] else "*", ) except (TypeError, ValueError): return None return None def _is_seed_like(name: str) -> bool: lowered = name.lower() return lowered in ("seed", "noise_seed", "value", "rand_seed", "random_seed") or ( lowered.endswith("seed") ) def _is_upload_entry(name: str, type_: str) -> bool: return type_.upper().endswith("UPLOAD") or name == "upload" or "UPLOAD" in type_.upper() class _Converter: """One conversion run over a single UI-format document.""" def __init__(self, ui: dict[str, Any]) -> None: self.ui = ui self.issues: list[ConvertIssue] = [] self.subgraphs: dict[str, dict[str, Any]] = { str(s.get("id")): s for s in self.ui.get("definitions", {}).get("subgraphs", []) or [] if isinstance(s, dict) } # qualified id → UI node + owning scope self.nodes: dict[str, dict[str, Any]] = {} # scope key ('' for top level) → link table / node-id index / owner self.scope_links: dict[str, dict[int, tuple[int, int, int, int, str]]] = {} self.scope_ids: dict[str, dict[str, str]] = {} self.scope_owner: dict[str, str] = {} self._set_capture_cache: dict[str, dict[str, tuple[str, int]]] = {} self._set_names: dict[str, set[str]] = {} self._depth = 0 self._cycle_warned = False self._set_building: set[str] = set() # -------------------------------------------------------------- indexing def _index_scope(self, scope: str, links: list[Any], owner: str | None) -> None: table = self.scope_links.setdefault(scope, {}) for link in links or []: norm = _norm_link(link) if norm is not None: table[norm[0]] = norm[1:] self.scope_ids.setdefault(scope, {}) if owner is not None: self.scope_owner[scope] = owner def _flatten( self, node: dict[str, Any], scope: str, prefix: str ) -> None: qualified = f"{prefix}{node.get('id')}" self.nodes[qualified] = {"node": node, "scope": scope} self.scope_ids.setdefault(scope, {})[str(node.get("id"))] = qualified sub = self.subgraphs.get(str(node.get("type") or "")) if sub is None: return if not isinstance(sub.get("nodes"), list): self.issues.append( ConvertIssue(qualified, "subgraph_bad_definition", "子图缺少内部节点定义") ) return sub_scope = f"{scope}|{node.get('type')}" if scope else f"{node.get('type')}" if sub_scope not in self.scope_links: self._index_scope(sub_scope, sub.get("links") or [], qualified) for inner in sub["nodes"]: if isinstance(inner, dict): self._flatten(inner, sub_scope, f"{qualified}:") # --------------------------------------------------------------- lookups def _node(self, qualified: str) -> dict[str, Any] | None: entry = self.nodes.get(qualified) return entry["node"] if entry else None def _scope(self, qualified: str) -> str: entry = self.nodes.get(qualified) return entry["scope"] if entry else "" def _link(self, scope: str, link_id: Any) -> tuple[int, int, int, int, str] | None: if link_id is None: return None try: key = int(link_id) except (TypeError, ValueError): return None return self.scope_links.get(scope, {}).get(key) def _boundary_source(self, scope: str, link_id: Any) -> tuple[str, int] | None: """(packed qualified id, boundary slot) when this link leaves a subgraph through its -10 input boundary.""" link = self._link(scope, link_id) if link is None or link[0] != _SUBGRAPH_IN: return None packed_q = self.scope_owner.get(scope) if packed_q is None: return None return packed_q, link[1] def _subgraph_of(self, qualified: str) -> dict[str, Any] | None: node = self._node(qualified) if node is None: return None return self.subgraphs.get(str(node.get("type") or "")) @staticmethod def _virtual_name(node: dict[str, Any]) -> str: """A Set/Get node's captured variable name (its first widget value).""" named = node.get("widgets_values_named") if isinstance(named, dict): for key in ("const_name", "name", "value"): if key in named: return str(named[key]) values = node.get("widgets_values") if isinstance(values, list) and values and isinstance(values[0], str): return values[0] return "" def _set_captures(self, scope: str) -> dict[str, tuple[str, int]]: """{variable name → resolved source} for the Set nodes in one scope.""" table = self._set_capture_cache.get(scope) if table is not None: return table table = {} # Seed before resolving: a Set feeding a same-named Get (FOR-loop # graphs) would otherwise recurse into this builder forever. A miss # while building is not a missing Set — never warn mid-construction. self._set_capture_cache[scope] = table self._set_building.add(scope) try: return self._build_set_captures(scope, table) finally: self._set_building.discard(scope) def _build_set_captures( self, scope: str, table: dict[str, tuple[str, int]] ) -> dict[str, tuple[str, int]]: names: set[str] = set() for qualified, entry in self.nodes.items(): if entry["scope"] != scope: continue node = entry["node"] if str(node.get("type") or "") not in _SET_TYPES: continue name = self._virtual_name(node) if not name: continue names.add(name) ins = self._inputs_of(node) link = self._link(scope, ins[0].get("link")) if ins else None resolved = self._resolve_link(scope, link) if resolved is not None: table.setdefault(name, resolved) self._set_names[scope] = names self._set_capture_cache[scope] = table return table @staticmethod def _inputs_of(node: dict[str, Any]) -> list[dict[str, Any]]: return [i for i in node.get("inputs") or [] if isinstance(i, dict)] @staticmethod def _outputs_of(node: dict[str, Any]) -> list[dict[str, Any]]: return [o for o in node.get("outputs") or [] if isinstance(o, dict)] # ------------------------------------------------------------- resolution def _resolve_link( self, scope: str, link: tuple[int, int, int, int, str] | None ) -> tuple[str, int] | None: """Resolve one link (in scope) to an API source (qualified id, slot).""" if link is None: return None if self._depth > 200: # Set/Get cycles (FOR-loop graphs) never unwind if not self._cycle_warned: self._cycle_warned = True self.issues.append( ConvertIssue( "", "cyclic_variable", "变量/Set-Get 连线存在循环(常见于 FOR 循环流),该连线按未连接处理", ) ) return None self._depth += 1 try: return self._resolve_link_inner(scope, link) finally: self._depth -= 1 def _resolve_link_inner( self, scope: str, link: tuple[int, int, int, int, str] ) -> tuple[str, int] | None: origin_id, origin_slot = link[0], link[1] if origin_id == _SUBGRAPH_IN: # Boundary: hand off to the packed instance's own input slot. packed_q = self.scope_owner.get(scope) if packed_q is None: return None node = self._node(packed_q) if node is None: return None entries = self._inputs_of(node) if origin_slot >= len(entries): return None entry = entries[origin_slot] if entry.get("link") is None: return None # unlinked boundary → inner widget value applies outer = self._scope(packed_q) return self._resolve_link(outer, self._link(outer, entry.get("link"))) qualified = self.scope_ids.get(scope, {}).get(str(origin_id)) if qualified is None: return None return self._resolve_source(qualified, origin_slot) def _resolve_source(self, qualified: str, slot: int) -> tuple[str, int] | None: """What an outgoing edge from (node, output slot) really connects to.""" node = self._node(qualified) if node is None: return None node_type = str(node.get("type") or "") mode = node.get("mode") or 0 scope = self._scope(qualified) if node_type in _UI_ONLY_TYPES: return None if node_type in _REROUTE_TYPES: ins = self._inputs_of(node) if not ins: return None return self._resolve_link(scope, self._link(scope, ins[0].get("link"))) if node_type in _SET_TYPES: ins = self._inputs_of(node) if not ins: return None return self._resolve_link(scope, self._link(scope, ins[0].get("link"))) if node_type in _GET_TYPES: name = self._virtual_name(node) captured = self._set_captures(scope).get(name) if captured is None and scope not in self._set_building: if name in self._set_names.get(scope, set()): self.issues.append( ConvertIssue( qualified, "variable_upstream_dropped", f"变量「{name}」的上游被旁路或未连接,取值按未连接处理", ) ) else: self.issues.append( ConvertIssue( qualified, "get_without_set", f"变量节点「{name}」没有对应的 Set 节点", ) ) return captured sub = self._subgraph_of(qualified) if sub is not None: outputs = [o for o in sub.get("outputs") or [] if isinstance(o, dict)] if slot >= len(outputs): return None sub_scope = f"{scope}|{node_type}" if scope else node_type for link in self.scope_links.get(sub_scope, {}).values(): if link[2] == _SUBGRAPH_OUT and link[3] == slot: inner_q = self.scope_ids.get(sub_scope, {}).get(str(link[0])) return self._resolve_source(inner_q, link[1]) if inner_q else None return None # boundary output with no inner source if mode == MODE_MUTED: return None if mode == MODE_BYPASSED: return self._bypass_through(qualified, slot) return (qualified, slot) def _bypass_through(self, qualified: str, slot: int) -> tuple[str, int] | None: """Pass-through of a bypassed node: same-name input first, then same-type.""" node = self._node(qualified) if node is None: return None outputs = self._outputs_of(node) out = outputs[slot] if slot < len(outputs) else {} out_name = str(out.get("name") or "") out_type = str(out.get("type") or "*") linkable = [ e for e in self._inputs_of(node) if not e.get("widget") and e.get("link") is not None ] pick = None if out_name: pick = next((e for e in linkable if str(e.get("name") or "") == out_name), None) if pick is None: pick = next( ( e for e in linkable if out_type == "*" or str(e.get("type") or "*") in (out_type, "*") ), None, ) if pick is None: return None scope = self._scope(qualified) return self._resolve_link(scope, self._link(scope, pick.get("link"))) # --------------------------------------------------------- widget mapping def _widget_entries(self, node: dict[str, Any]) -> list[tuple[str, str]]: """[(name, type)] of entries carrying the ``widget`` marker, in order.""" out: list[tuple[str, str]] = [] for entry in self._inputs_of(node): marker = entry.get("widget") if isinstance(marker, dict): name = str(marker.get("name") or entry.get("name") or "") if name: out.append((name, str(entry.get("type") or ""))) return out def _widgets_from_entries( self, node_id: str, entries: list[tuple[str, str]], values: Any, ) -> tuple[dict[str, Any], list[ConvertIssue]]: """Map widget values using the node's serialized input list.""" inputs: dict[str, Any] = {} issues: list[ConvertIssue] = [] if isinstance(values, dict): for name, type_ in entries: if name in _BUTTON_WIDGETS or self._is_upload(name, type_): continue if name in values: inputs[name] = values[name] else: issues.append( ConvertIssue(node_id, "widget_unmapped", f"控件「{name}」没有序列化值") ) return inputs, issues if not isinstance(values, list): return inputs, issues if not values: return inputs, issues # nothing serialized — server defaults apply i = 0 for name, type_ in entries: if name in _BUTTON_WIDGETS: continue # button widgets never serialize if i >= len(values): issues.append( ConvertIssue(node_id, "widget_order_mismatch", f"控件值数量不足({name})") ) break value = values[i] i += 1 if self._is_upload(name, type_): continue # consumes a slot, never an API input inputs[name] = value if ( type_.upper() == "INT" and _is_seed_like(name) and i < len(values) and values[i] in _CONTROL_MODES ): i += 1 # control_after_generate rides right after its seed leftover_ok = all(_is_button_leftover(v) for v in values[i:]) if not issues and i != len(values) and not leftover_ok: issues.append( ConvertIssue( node_id, "widget_order_mismatch", f"有 {len(values)} 个控件值,输入清单只覆盖 {i} 个", ) ) return inputs, issues @staticmethod def _is_upload(name: str, type_: str) -> bool: return _is_upload_entry(name, type_) def _widgets_from_registry( self, node: dict[str, Any], values: list[Any] ) -> tuple[dict[str, Any], list[ConvertIssue]]: node_type = str(node.get("type") or "") if not values: return {}, [] # nothing serialized — server defaults apply for order in WIDGET_ORDERS.get(node_type) or []: inputs: dict[str, Any] = {} i = 0 for name in order: if name in _BUTTON_WIDGETS: continue if i >= len(values): break value = values[i] i += 1 if _is_upload_entry(name, ""): continue inputs[name] = value if _is_seed_like(name) and i < len(values) and values[i] in _CONTROL_MODES: i += 1 if i == len(values) or all(_is_button_leftover(v) for v in values[i:]): return inputs, [] # exact fit, or trailing button leftovers return {}, [ ConvertIssue( node.get("id", ""), "widget_unmapped" if not WIDGET_ORDERS.get(node_type) else "widget_order_mismatch", f"「{node_type}」的 {len(values)} 个控件值无法可靠对应到输入名", ) ] def _packed_widget_values(self, qualified: str) -> Any: """Exposed widget values of a packed instance as {boundary name: value}.""" node = self._node(qualified) sub = self._subgraph_of(qualified) if node is None or sub is None: return None boundary = [i for i in sub.get("inputs") or [] if isinstance(i, dict)] named = node.get("widgets_values_named") if isinstance(named, dict): return named values = node.get("widgets_values") if not isinstance(values, list): return None out: dict[str, Any] = {} i = 0 for entry in boundary: name = str(entry.get("name") or "") type_ = str(entry.get("type") or "") if name and i < len(values): out[name] = values[i] i += 1 if ( type_.upper() == "INT" and _is_seed_like(name) and i < len(values) and values[i] in _CONTROL_MODES ): i += 1 return out # -------------------------------------------------------------- serialize def _serialize_node(self, qualified: str) -> dict[str, Any] | None: node = self._node(qualified) if node is None: return None node_type = str(node.get("type") or "") if ( not node_type or node_type in _UI_ONLY_TYPES or node_type in _REROUTE_TYPES or node_type in _SET_TYPES or node_type in _GET_TYPES ): return None scope = self._scope(qualified) inputs: dict[str, Any] = {} widget_values = node.get("widgets_values_named") if not isinstance(widget_values, dict): widget_values = node.get("widgets_values") if self._subgraph_of(qualified) is not None: widget_values = self._packed_widget_values(qualified) widget_inputs: dict[str, Any] = {} entries = self._widget_entries(node) if widget_values is not None: if entries: widget_inputs, w_issues = self._widgets_from_entries( qualified, entries, widget_values ) self.issues.extend(w_issues) elif isinstance(widget_values, dict): widget_inputs = { k: v for k, v in widget_values.items() if k not in _BUTTON_WIDGETS } elif isinstance(widget_values, list): widget_inputs, w_issues = self._widgets_from_registry(node, widget_values) self.issues.extend(w_issues) for entry in self._inputs_of(node): name = str(entry.get("name") or "") if not name or name in inputs: continue if entry.get("link") is None: continue # unconnected optional input; widget values applied below # Widget entries fed from the subgraph boundary (-10): when the # packed instance left that boundary slot unlinked, the value is # the packed node's own exposed widget value, not the inner one. boundary = self._boundary_source(scope, entry.get("link")) if boundary is not None: packed_q, boundary_slot = boundary packed_node = self._node(packed_q) packed_entries = self._inputs_of(packed_node) if packed_node else [] if boundary_slot < len(packed_entries) and packed_entries[ boundary_slot ].get("link") is None: values = self._packed_widget_values(packed_q) boundary_name = str(packed_entries[boundary_slot].get("name") or "") if isinstance(values, dict) and boundary_name in values: inputs[name] = values[boundary_name] continue # linked boundary falls through to normal resolution link = self._link(scope, entry.get("link")) if link is None: self.issues.append( ConvertIssue(qualified, "dangling_link", f"输入「{name}」的连线不存在") ) continue resolved = self._resolve_link(scope, link) if resolved is not None: inputs[name] = [resolved[0], resolved[1]] elif entry.get("widget"): pass # muted upstream: the widget value below takes over else: self.issues.append( ConvertIssue( qualified, "muted_input_dropped", f"输入「{name}」上游被静音,已按未连接处理", ) ) for name, value in widget_inputs.items(): inputs.setdefault(name, value) api_node: dict[str, Any] = {"class_type": node_type, "inputs": inputs} title = str(node.get("title") or "").strip() if title: api_node["_meta"] = {"title": title} return api_node # ------------------------------------------------------------------- main def run(self) -> ConvertResult: nodes = self.ui.get("nodes") if not isinstance(nodes, list) or not nodes: return ConvertResult( None, "fail", [ConvertIssue("", "no_nodes", "文件不含 nodes 数组,不是 UI 格式工作流", "error")], ) try: self._index_scope("", self.ui.get("links") or [], None) for node in nodes: if isinstance(node, dict): self._flatten(node, "", "") except RecursionError: return ConvertResult( None, "fail", [ConvertIssue("", "subgraph_recursion", "子图嵌套过深", "error")] ) # Closure from known output nodes (ComfyUI's own graphToPrompt roots). roots = [ q for q, entry in self.nodes.items() if str(entry["node"].get("type") or "") in _OUTPUT_CLASSES and (entry["node"].get("mode") or 0) == MODE_ACTIVE ] keep: dict[str, None] = {} stack = list(roots) while stack: qualified = stack.pop() if qualified in keep: continue entry = self.nodes.get(qualified) if entry is None: continue keep[qualified] = None node = entry["node"] scope = entry["scope"] for e in self._inputs_of(node): if e.get("link") is None: continue link = self._link(scope, e.get("link")) resolved = self._resolve_link(scope, link) if resolved is not None: stack.append(resolved[0]) if not keep: # No known output node: keep every active computed node and warn — # the import lint will report the missing output separately. for qualified, entry in self.nodes.items(): node = entry["node"] node_type = str(node.get("type") or "") if ( node_type in _UI_ONLY_TYPES or node_type in _REROUTE_TYPES or (node.get("mode") or 0) != MODE_ACTIVE or self._subgraph_of(qualified) is not None ): continue keep[qualified] = None self.issues.append( ConvertIssue( "", "no_output_node", "图中没有已知输出节点(SaveImage / 视频合成等)," "全部活跃节点已保留,需人工确认", ) ) workflow: dict[str, Any] = {} for qualified in keep: api_node = self._serialize_node(qualified) if api_node is not None and api_node["class_type"]: workflow[qualified] = api_node if not workflow: return ConvertResult( None, "fail", self.issues or [ConvertIssue("", "empty", "转换后没有任何节点", "error")], ) status = ( "fail" if any(i.level == "error" for i in self.issues) else ("ok" if not self.issues else "warn") ) return ConvertResult(workflow, status, self.issues) def convert_ui_workflow(ui: dict[str, Any]) -> ConvertResult: """Convert one ComfyUI UI-format workflow dict into API format.""" if not isinstance(ui, dict) or not isinstance(ui.get("nodes"), list): return ConvertResult( None, "fail", [ConvertIssue("", "not_ui_format", "不是 UI 格式(缺少 nodes 数组)", "error")], ) return _Converter(ui).run()