Files
aigc-home/calliope-backend/src/calliope/comfyui/parser.py
T
总工andmultica-agent 2ed9d25c24 feat(workflows): import preflight, real test runs and media groups (HEL-643)
- L2 连接核查: /object_info preflight (node existence + combo values) with
  5-min cache + manual refresh; analyze accepts endpoint_id, saved workflows
  get POST /{id}/check; unreachable degrades to 无法核查, never blocks saving
- 测试工作流: jobs.origin='workflow_test' rides the real queue → ComfyUI →
  outputs pipeline; only a downloadable, correctly-typed output counts as a
  pass; dry-run refused; repeat clicks reuse the in-flight job; artifacts
  isolated under assets/_workflow_test/{id}; retention keeps newest 5;
  clear-tests + delete-workflow cascade cleanup; tasks page shows a 测试 badge
- Media groups: Autogrow detection generalized to video/audio lists
  (ref_videos/ref_audios etc.), patcher clones/rewires per media family,
  validation per list kind; entries appear only for actually-wired slots;
  MiniMax H3 Ref2VA official-limit hints keyed off the node class
- 25 new backend tests (preflight / workflow-test / media-groups) against the
  fake ComfyUI; fake server gains /object_info + drop_outputs knobs

Co-authored-by: multica-agent <github@multica.ai>
2026-09-29 19:07:20 +08:00

1104 lines
43 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.
"""Parse ComfyUI API-format workflows for (Input[:role]) / (Output[:role]) titled nodes."""
from __future__ import annotations
import math
import re
from typing import Any
from calliope.comfyui.patcher import FIELD_KEY_SEP, resolve_patch_field
from calliope.comfyui.registry import (
AUDIO_CLASSES,
IMAGE_CLASSES,
IMAGE_OUTPUT_CLASSES,
IMAGE_URL_CLASSES,
NUMBER_CLASSES,
TEXT_AREA_CLASSES,
VIDEO_CLASSES,
VIDEO_OUTPUT_CLASSES,
ComfyOutputKind,
class_to_input_kind,
class_to_output_kind,
)
from calliope.comfyui.roles import (
USAGE_VALUES,
normalize_input_role,
normalize_output_role,
parse_title_tag,
)
def extract_default_value(node: dict[str, Any]) -> str | int | float | None:
class_type = node.get("class_type", "")
inputs = node.get("inputs") or {}
if class_type in IMAGE_CLASSES or class_type in AUDIO_CLASSES or class_type in VIDEO_CLASSES:
return None
if isinstance(inputs.get("text"), str):
return inputs["text"]
value = inputs.get("value")
if isinstance(value, (str, int, float)):
return value
if isinstance(inputs.get("int"), (int, float)):
return inputs["int"]
if isinstance(inputs.get("float"), (int, float)):
return inputs["float"]
return None
def parse_dynamic_inputs(workflow: dict[str, Any]) -> list[dict[str, Any]]:
"""Tagged ``(Input:role)`` nodes; untagged workflows fall back to detection.
A workflow exported straight from ComfyUI carries default node titles
("CLIP Text Encode (Positive Prompt)", "KSampler", …) and no tags at all —
without the fallback it would expose nothing to fill in.
"""
results: list[dict[str, Any]] = []
for node_id, node in workflow.items():
if not isinstance(node, dict):
continue
title = (node.get("_meta") or {}).get("title") or ""
kind, role, label = parse_title_tag(title)
if kind != "input":
continue
results.append(
{
"nodeId": str(node_id),
"label": label or node.get("class_type", node_id),
"role": normalize_input_role(role),
"kind": class_to_input_kind(node.get("class_type", "")),
"defaultValue": extract_default_value(node),
"required": True,
}
)
if not results:
results = detect_untagged_inputs(workflow)
return results
def effective_input_schema(
stored: list[dict[str, Any]] | None, workflow: dict[str, Any]
) -> list[dict[str, Any]]:
"""The schema a stored workflow exposes now.
Auto-detected (and empty) schemas are re-derived from the workflow JSON
on every read, so parser upgrades reach workflows imported earlier
without a re-import. Tagged ``(Input:…)`` schemas are kept as stored.
Entries the user corrected on the import confirm page carry
``manual: true`` — their role/label survive re-derivation.
"""
if not stored:
return parse_dynamic_inputs(workflow)
manual_by_id = {
str(e.get("nodeId")): e for e in stored if isinstance(e, dict) and e.get("manual")
}
if any(isinstance(e, dict) and e.get("auto") for e in stored):
fresh = parse_dynamic_inputs(workflow)
return [manual_by_id.get(str(e.get("nodeId")), e) for e in fresh]
return stored
# ---------------------------------------------------------------------------
# Untagged detection
# ---------------------------------------------------------------------------
_MASK_IMAGE_CLASSES = frozenset({"LoadImageMask"})
_STRING_PRIMITIVES = frozenset({"PrimitiveString", "PrimitiveStringMultiline"})
_NUMBER_PRIMITIVES = frozenset({"PrimitiveInt", "PrimitiveFloat", "INT", "FLOAT"})
_SAMPLER_CLASSES = frozenset({"KSampler", "KSamplerAdvanced"})
_NEGATIVE_WORDS = ("negative", "负面", "反向", "反面")
_SYSTEM_WORDS = ("system", "系统")
_PROMPT_WORDS = ("prompt", "positive", "提示", "正向")
_NEGATIVE_TEXT_FIELDS = ("negative_prompt", "negative_text", "negative")
# Title keyword → (role, Chinese label) for untagged numeric primitives.
_NUMBER_TITLE_ROLES: tuple[tuple[tuple[str, ...], str, str], ...] = (
(("duration", "seconds", "second", "时长", "秒"), "duration", "时长(秒)"),
(("fps", "frame rate", "framerate", "帧率"), "fps", "帧率"),
(("seed", "种子"), "seed", "随机种子"),
(("width", "宽度"), "width", "宽度"),
(("height", "高度"), "height", "高度"),
(("steps", "步数"), "steps", "采样步数"),
(("cfg",), "cfg", "CFG"),
)
def _is_scalar(value: Any) -> bool:
return isinstance(value, (str, int, float)) and not isinstance(value, bool)
def _title_of(node: dict[str, Any]) -> str:
return str((node.get("_meta") or {}).get("title") or "").strip()
def _node_sort_key(node_id: str) -> tuple:
return tuple(
(0, int(p)) if p.isdigit() else (1, p)
for p in str(node_id).replace(FIELD_KEY_SEP, ":").split(":")
)
def _consumers(workflow: dict[str, Any]) -> dict[str, list[tuple[str, str]]]:
"""source nodeId → [(consumer nodeId, consumer input name), …]."""
out: dict[str, list[tuple[str, str]]] = {}
for nid, node in workflow.items():
if not isinstance(node, dict):
continue
for name, val in (node.get("inputs") or {}).items():
if isinstance(val, list) and len(val) == 2 and isinstance(val[0], (str, int)):
out.setdefault(str(val[0]), []).append((str(nid), str(name)))
return out
def _feeds_negative(
node_id: str, consumers: dict[str, list[tuple[str, str]]], depth: int = 4
) -> bool:
"""True when this node's output reaches a sampler/guider ``negative`` input
and never a ``positive`` one.
A text encoder wired into both (one conditioning reused for positive and
negative) is treated as the positive prompt; only a negative-sounding
title makes it negative (see ``_is_negative``).
"""
frontier = [node_id]
seen = {node_id}
negative = False
for _ in range(depth):
nxt: list[str] = []
for nid in frontier:
for cid, name in consumers.get(nid, []):
if name == "positive":
return False
if name == "negative":
negative = True
continue
if cid not in seen:
seen.add(cid)
nxt.append(cid)
frontier = nxt
return negative
_FRAME_INPUTS = frozenset({"length", "num_frames", "frames", "video_length", "frame_count"})
_SECONDS_INPUTS = frozenset({"duration", "seconds", "duration_seconds"})
_EXPRESSION_HINTS = ("expression", "math")
def _duration_hint(
node_id: str,
workflow: dict[str, Any],
consumers: dict[str, list[tuple[str, str]]],
depth: int = 3,
) -> str | None:
"""How an untitled number feeds the video length downstream.
``"seconds"`` — it reaches a seconds input, or a frame-count input only
after passing through a math/expression node (seconds × fps → frames);
``"frames"`` — it is wired straight into a frame-count input.
"""
frontier = [(node_id, False)]
seen = {node_id}
for _ in range(depth):
nxt: list[tuple[str, bool]] = []
for nid, via_expr in frontier:
for cid, name in consumers.get(nid, []):
if name in _SECONDS_INPUTS:
return "seconds"
if name in _FRAME_INPUTS:
return "seconds" if via_expr else "frames"
if cid in seen:
continue
seen.add(cid)
ct = str((workflow.get(cid) or {}).get("class_type") or "").lower()
nxt.append((cid, via_expr or any(h in ct for h in _EXPRESSION_HINTS)))
frontier = nxt
return None
def _entry(
key: str,
label: str,
role: str | None,
kind: str,
default: Any,
required: bool,
**extra: Any,
) -> dict[str, Any]:
entry = {
"nodeId": key,
"label": label,
"role": role,
"kind": kind,
"defaultValue": default if _is_scalar(default) else None,
"required": required,
"auto": True,
}
entry.update({k: v for k, v in extra.items() if v is not None})
return entry
# ComfyUI's own widget limits (nodes.py / comfy_extras) for the widgets we
# expose; the studio validates against them before a job is queued. Seeds
# stop at 2**53-1 (ComfyUI allows 2**64-1): larger values lose precision in
# the browser's JSON numbers.
_NUMBER_LIMITS: dict[str, dict[str, Any]] = {
"seed": {"min": 0, "max": 2**53 - 1, "step": 1, "integer": True},
"steps": {"min": 1, "max": 10000, "step": 1, "integer": True},
"cfg": {"min": 0.0, "max": 100.0, "step": 0.1},
"denoise": {"min": 0.0, "max": 1.0, "step": 0.01},
"width": {"min": 16, "max": 16384, "step": 8, "integer": True},
"height": {"min": 16, "max": 16384, "step": 8, "integer": True},
"batch": {"min": 1, "max": 4096, "step": 1, "integer": True},
"megapixels": {"min": 0.1, "max": 16.0, "step": 0.1},
}
# Text encoders whose ``resolution`` widget sizes the generated image when an
# input image is wired (edit mode); in text-to-image it only sizes references.
_RESOLUTION_ENCODERS: dict[str, dict[str, Any]] = {
"TextEncodeQwenImage21": {"min": 0, "max": 4096, "step": 32, "integer": True},
}
# comfy_extras/nodes_resolution.py — option strings must match exactly.
RESOLUTION_ASPECT_RATIOS: dict[str, tuple[int, int]] = {
"1:1 (Square)": (1, 1),
"2:3 (Portrait Photo)": (2, 3),
"3:2 (Photo)": (3, 2),
"3:4 (Portrait Standard)": (3, 4),
"4:3 (Standard)": (4, 3),
"9:16 (Portrait Widescreen)": (9, 16),
"16:9 (Widescreen)": (16, 9),
"21:9 (Ultrawide)": (21, 9),
}
def resolution_selector_size(aspect_ratio: str, megapixels: float, multiple: int) -> tuple[int, int]:
"""Width/height exactly as ComfyUI's ResolutionSelector computes them."""
w_ratio, h_ratio = RESOLUTION_ASPECT_RATIOS[aspect_ratio]
scale = math.sqrt(megapixels * 1024 * 1024 / (w_ratio * h_ratio))
multiple = max(1, int(multiple))
return (
round(w_ratio * scale / multiple) * multiple,
round(h_ratio * scale / multiple) * multiple,
)
# ComfyUI Autogrow media inputs a studio form fills as one 1…max list
# (HEL-643 generalizes the original image-only registry to three media
# kinds). The workflow wires ``<group>.<prefix>N``; extra items are cloned
# loader nodes added at patch time (patcher.py). This registry only
# beautifies known classes (label + real max + hint key); detection itself
# is generic — any ``<group>.<prefix>N`` run of same-family media-loader
# links folds into a group, image / video / audio alike.
MEDIA_GROUPS: dict[str, dict[str, dict[str, Any]]] = {
"MiniMaxH3ReferenceToVideo": {
"ref_images": {
"prefix": "ref_image_",
"max": 9,
"label": "参考图",
"kind": "image",
},
"ref_videos": {
"prefix": "ref_video_",
"max": 3,
"label": "参考视频",
"kind": "video",
},
"ref_audios": {
"prefix": "ref_audio_",
"max": 3,
"label": "参考音频",
"kind": "audio",
},
},
}
# Backwards-compatible alias for the original image-only view.
IMAGE_GROUPS = MEDIA_GROUPS
# Consuming-node classes whose groups carry official usage limits worth a
# hint in the UI. Purely cosmetic — detection never depends on it.
_MEDIA_HINTS: dict[str, str] = {
"MiniMaxH3ReferenceToVideo": "minimax_h3_ref2va",
}
# ``ref_images.ref_image_0`` / ``images.image_1`` style Autogrow input names.
_GROUP_INPUT_RE = re.compile(
r"^(?P<group>[A-Za-z0-9_+-]+)\.(?P<rest>[A-Za-z0-9_+-]+?)(?P<n>\d+)$"
)
# Consumer input name → (role, label) of the LoadImage wired into it.
_FRAME_SLOT_ROLES: dict[str, tuple[str, str]] = {
"first_frame": ("first_frame", "首帧"),
"start_image": ("first_frame", "首帧"),
"last_frame": ("last_frame", "尾帧"),
"end_image": ("last_frame", "尾帧"),
}
# Group media kind → (schema kind, role, default label, default max).
_GROUP_KIND_META: dict[str, tuple[str, str, str, int]] = {
"image": ("image_list", "reference_image", "参考图", 9),
"video": ("video_list", "reference_video", "参考视频", 9),
"audio": ("audio_list", "reference_audio", "参考音频", 9),
}
# Loader class family for each media kind (registry.py sets).
_GROUP_SOURCE_CLASSES: dict[str, frozenset[str]] = {
"image": IMAGE_CLASSES,
"video": VIDEO_CLASSES,
"audio": AUDIO_CLASSES,
}
def media_group_spec(class_type: str, group: str) -> dict[str, Any] | None:
return MEDIA_GROUPS.get(class_type, {}).get(group)
def image_group_spec(class_type: str, group: str) -> dict[str, Any] | None:
return media_group_spec(class_type, group)
def image_group_prefix(node: dict[str, Any], group: str) -> str | None:
"""The ``<prefix>`` this node numbers its ``<group>.<prefix>N`` inputs with.
Known classes read it from the registry; anything else derives it from
the node's own wired input names (generic Autogrow detection).
"""
spec = image_group_spec(str(node.get("class_type") or ""), group)
if spec:
return str(spec["prefix"])
head = f"{group}."
prefixes = set()
for name in (node.get("inputs") or {}):
if not name.startswith(head):
continue
m = _GROUP_INPUT_RE.match(name)
if m and m.group("group") == group:
prefixes.add(m.group("rest"))
if len(prefixes) == 1:
return prefixes.pop()
return None
def image_group_slots(
node: dict[str, Any], group: str, prefix: str
) -> list[tuple[int, str, Any]]:
"""``[(N, input name, link), …]`` wired into ``<group>.<prefix>N``, by N."""
head = f"{group}.{prefix}"
out: list[tuple[int, str, Any]] = []
for name, val in (node.get("inputs") or {}).items():
if name.startswith(head) and name[len(head):].isdigit():
out.append((int(name[len(head):]), name, val))
return sorted(out)
def _detected_group_runs(
workflow: dict[str, Any], node: dict[str, Any]
) -> list[tuple[str, str, list[str], str]]:
"""``[(group, prefix, source loader ids, media kind)]`` for Autogrow inputs.
A run qualifies when the numbers are consecutive, every slot links to a
loader of the SAME media family (image / video / audio), and the run
either starts at 0 (single-slot Autogrow exports like H3's
``ref_image_0``) or has ≥2 slots. Single runs numbered from 1 (e.g.
TextEncodeQwenImage21's ``images.image_1``) stay ordinary image slots.
"""
runs: dict[tuple[str, str], dict[int, Any]] = {}
for name, val in (node.get("inputs") or {}).items():
m = _GROUP_INPUT_RE.match(name)
if not m or not (isinstance(val, list) and len(val) == 2):
continue
runs.setdefault((m.group("group"), m.group("rest")), {})[int(m.group("n"))] = val
out: list[tuple[str, str, list[str], str]] = []
for (group, prefix), slots in sorted(runs.items()):
ns = sorted(slots)
if any(b - a != 1 for a, b in zip(ns, ns[1:])):
continue
if not (ns[0] == 0 or len(ns) >= 2):
continue
sources: list[str] = []
family: str | None = None
for n in ns:
link = slots[n]
src = workflow.get(str(link[0]))
if not isinstance(src, dict):
family = None
break
ct = str(src.get("class_type") or "")
kinds = [
kind
for kind, classes in _GROUP_SOURCE_CLASSES.items()
if ct in classes
]
if len(kinds) != 1 or (family is not None and kinds[0] != family):
family = None
break
family = kinds[0]
sources.append(str(link[0]))
if family and sources:
out.append((group, prefix, sources, family))
return out
def _media_groups(
workflow: dict[str, Any],
) -> tuple[list[dict[str, Any]], set[str]]:
"""Group entries for Autogrow reference inputs (image/video/audio) plus
the loader node ids they absorb."""
entries: list[dict[str, Any]] = []
absorbed: set[str] = set()
for nid, node in sorted(
((str(k), v) for k, v in workflow.items() if isinstance(v, dict)),
key=lambda kv: _node_sort_key(kv[0]),
):
class_type = str(node.get("class_type") or "")
for group, _prefix, sources, media_kind in _detected_group_runs(workflow, node):
spec = media_group_spec(class_type, group) or {}
kind, role, default_label, default_max = _GROUP_KIND_META[media_kind]
absorbed.update(sources)
hint = _MEDIA_HINTS.get(class_type)
entries.append(
_entry(
f"{nid}{FIELD_KEY_SEP}{group}",
str(spec.get("label") or default_label),
role,
kind,
None,
True,
min=1,
max=spec.get("max", default_max),
media_hint=hint,
)
)
return entries, absorbed
def _image_slot(
nid: str, workflow: dict[str, Any], consumers: dict[str, list[tuple[str, str]]]
) -> tuple[str, str] | None:
"""(role, label) of a LoadImage from what consumes it; None when unwired."""
uses = consumers.get(nid, [])
if not uses:
return None
for _cid, name in uses:
if name in _FRAME_SLOT_ROLES:
return _FRAME_SLOT_ROLES[name]
for cid, name in uses:
ct = str((workflow.get(cid) or {}).get("class_type") or "")
if "TextEncode" in ct and name.startswith("image"):
return "image", "输入图"
return "image", ""
def _key(node_id: str, node: dict[str, Any], field: str) -> str:
"""Plain nodeId when that already patches ``field``; else ``nodeId@field``."""
return (
str(node_id) if resolve_patch_field(node) == field else f"{node_id}{FIELD_KEY_SEP}{field}"
)
def detect_untagged_inputs(workflow: dict[str, Any]) -> list[dict[str, Any]]:
"""Infer fillable inputs from node classes and wiring of an untagged workflow.
Only scalar widgets are exposed (linked inputs are wiring, not values).
The positive prompt is the only required field; everything else keeps the
workflow's own value when left blank.
"""
if not isinstance(workflow, dict):
return []
consumers = _consumers(workflow)
nodes = sorted(
((str(k), v) for k, v in workflow.items() if isinstance(v, dict)),
key=lambda kv: _node_sort_key(kv[0]),
)
texts: list[tuple[str, dict[str, Any], str, bool]] = [] # (id, node, field, negative)
groups, grouped_loaders = _media_groups(workflow)
media: list[dict[str, Any]] = []
numbers: list[dict[str, Any]] = []
taken_roles: set[str] = set()
def add_number(nid: str, node: dict[str, Any], field: str, role: str, label: str) -> None:
if role in taken_roles:
return
value = (node.get("inputs") or {}).get(field)
if not _is_scalar(value) or isinstance(value, str):
return
taken_roles.add(role)
numbers.append(
_entry(
_key(nid, node, field), label, role, "number", value, False,
**_NUMBER_LIMITS.get(role, {}),
)
)
for nid, node in nodes:
ct = str(node.get("class_type") or "")
inputs = node.get("inputs") or {}
title = _title_of(node)
lowered = title.lower()
if ct in IMAGE_CLASSES or ct in _MASK_IMAGE_CLASSES:
if nid in grouped_loaders:
continue
is_mask = ct in _MASK_IMAGE_CLASSES or "mask" in lowered or "遮罩" in lowered
slot = _image_slot(nid, workflow, consumers)
if is_mask:
label = title if title and title != ct else "遮罩"
if "mask" not in label.lower() and "遮罩" not in label:
label = f"遮罩 · {label}"
has_default = isinstance(inputs.get("image"), str) and bool(inputs.get("image"))
media.append(
_entry(_key(nid, node, "image"), label, "mask", "image", None, not has_default)
)
continue
if slot is None:
# Nothing consumes it — ComfyUI never runs it, so no upload slot.
continue
role, label = slot
media.append(
_entry(
_key(nid, node, "image"),
label or (title if title and title != ct else "参考图"),
role,
"image",
None,
True,
)
)
continue
if ct in VIDEO_CLASSES or ct in AUDIO_CLASSES:
if nid in grouped_loaders:
# Absorbed into an Autogrow media group (HEL-643) — the
# group entry owns its upload slots.
continue
kind = "video" if ct in VIDEO_CLASSES else "audio"
field = resolve_patch_field(node)
has_default = isinstance(inputs.get(field), str) and bool(inputs.get(field))
media.append(_entry(str(nid), title or ct, kind, kind, None, not has_default))
continue
if ct in _STRING_PRIMITIVES and isinstance(inputs.get("value"), str):
texts.append((nid, node, "value", _is_negative(nid, lowered, consumers)))
continue
if ct == "CLIPTextEncode" or "TextEncode" in ct:
field = next((f for f in ("text", "prompt") if isinstance(inputs.get(f), str)), None)
neg_field = next(
(f for f in _NEGATIVE_TEXT_FIELDS if isinstance(inputs.get(f), str)), None
)
if field and neg_field:
# One encoder carrying both prompts (TextEncodeQwenImage21…):
# its outputs feed positive *and* negative, so wiring says nothing.
texts.append((nid, node, field, False))
texts.append((nid, node, neg_field, True))
elif field:
texts.append((nid, node, field, _is_negative(nid, lowered, consumers)))
edits_image = any(
k.startswith("images.") and isinstance(v, list) for k, v in inputs.items()
)
if ct in _RESOLUTION_ENCODERS and edits_image and "resolution" not in taken_roles:
value = inputs.get("resolution")
if _is_scalar(value) and not isinstance(value, str):
taken_roles.add("resolution")
numbers.append(
_entry(
_key(nid, node, "resolution"),
"输出分辨率",
"resolution",
"number",
value,
False,
**_RESOLUTION_ENCODERS[ct],
)
)
continue
if ct in _SAMPLER_CLASSES:
add_number(nid, node, "seed" if "seed" in inputs else "noise_seed", "seed", "随机种子")
add_number(nid, node, "steps", "steps", "采样步数")
add_number(nid, node, "cfg", "cfg", "CFG")
add_number(nid, node, "denoise", "denoise", "降噪强度")
continue
if ct == "RandomNoise":
add_number(nid, node, "noise_seed", "seed", "随机种子")
continue
if ct == "BasicScheduler":
add_number(nid, node, "steps", "steps", "采样步数")
add_number(nid, node, "denoise", "denoise", "降噪强度")
continue
if ct == "ResolutionSelector" and nid in consumers:
ratio = inputs.get("aspect_ratio")
if (
"aspect_ratio" not in taken_roles
and isinstance(ratio, str)
and ratio in RESOLUTION_ASPECT_RATIOS
):
taken_roles.add("aspect_ratio")
multiple = inputs.get("multiple")
numbers.append(
_entry(
_key(nid, node, "aspect_ratio"),
"画面比例",
"aspect_ratio",
"select",
ratio,
False,
options=list(RESOLUTION_ASPECT_RATIOS),
resolution={
"megapixels": _key(nid, node, "megapixels"),
"multiple": multiple if isinstance(multiple, int) else 8,
},
)
)
add_number(nid, node, "megapixels", "megapixels", "总像素(百万)")
continue
if ct == "CFGGuider":
add_number(nid, node, "cfg", "cfg", "CFG")
continue
if ct.startswith("Empty") and "Latent" in ct:
if nid not in consumers:
# Orphan latent (Qwen edit sizes from its encoder): editing it changes nothing.
continue
add_number(nid, node, "width", "width", "宽度")
add_number(nid, node, "height", "height", "高度")
add_number(nid, node, "batch_size", "batch", "批次数量")
continue
if ct in _NUMBER_PRIMITIVES and _is_scalar(inputs.get("value")):
role, label = None, title if title and title != ct else f"{ct} #{nid}"
for words, r, zh in _NUMBER_TITLE_ROLES:
if any(w in lowered for w in words):
role, label = r, (title if title and title != ct else zh)
break
if role is None and (not title or title == ct):
hint = _duration_hint(nid, workflow, consumers)
if hint == "seconds":
role, label = "duration", "时长(秒)"
elif hint == "frames":
label = "视频帧数"
if role and role in taken_roles:
role = None
if role:
taken_roles.add(role)
limits = dict(_NUMBER_LIMITS.get(role or "", {}))
if ct in ("PrimitiveInt", "INT"):
limits["integer"] = True
if role == "duration":
limits.setdefault("min", 0.1)
numbers.append(
_entry(
_key(nid, node, "value"), label, role, "number", inputs["value"], False,
**limits,
)
)
results: list[dict[str, Any]] = []
positives = [t for t in texts if not t[3]]
negatives = [t for t in texts if t[3]]
def rank(t: tuple[str, dict[str, Any], str, bool]) -> tuple[int, int]:
title = _title_of(t[1]).lower()
system = any(w in title for w in _SYSTEM_WORDS)
named = any(w in title for w in _PROMPT_WORDS)
return (1 if system else 0, 0 if named else 1)
positives.sort(key=rank)
for i, (nid, node, field, _neg) in enumerate(positives):
title = _title_of(node)
if i == 0:
results.append(
_entry(
_key(nid, node, field),
"正向提示词",
"prompt",
"textarea",
node["inputs"][field],
True,
)
)
else:
label = title if title and title != node.get("class_type") else f"文本 #{nid}"
results.append(
_entry(
_key(nid, node, field), label, None, "textarea", node["inputs"][field], False
)
)
for i, (nid, node, field, _neg) in enumerate(negatives):
role = "negative" if i == 0 else None
label = "反向提示词" if i == 0 else (_title_of(node) or f"文本 #{nid}")
results.append(
_entry(_key(nid, node, field), label, role, "textarea", node["inputs"][field], False)
)
results.extend(numbers)
results.extend(media)
results.extend(groups)
return results
def _is_negative(
node_id: str, lowered_title: str, consumers: dict[str, list[tuple[str, str]]]
) -> bool:
if any(w in lowered_title for w in _NEGATIVE_WORDS):
return True
return _feeds_negative(node_id, consumers)
def parse_dynamic_outputs(workflow: dict[str, Any]) -> list[dict[str, Any]]:
results: list[dict[str, Any]] = []
for node_id, node in workflow.items():
if not isinstance(node, dict):
continue
title = (node.get("_meta") or {}).get("title") or ""
kind, role, label = parse_title_tag(title)
if kind != "output":
continue
out_kind: ComfyOutputKind = class_to_output_kind(node.get("class_type", ""))
canon = normalize_output_role(role)
if canon == "video":
out_kind = "video"
elif canon == "image":
out_kind = "image"
results.append(
{
"nodeId": str(node_id),
"label": label or node.get("class_type", node_id),
"role": canon,
"kind": out_kind,
}
)
if not results:
results = detect_output_nodes(workflow)
return results
# ---------------------------------------------------------------------------
# Output (sink) detection + five-usage classification (HEL-636)
# ---------------------------------------------------------------------------
# Nodes whose output another node consumes are wiring, not results. A node
# nothing consumes is a sink; media sinks are the workflow's outputs.
_INPUT_ONLY_CLASSES = IMAGE_CLASSES | IMAGE_URL_CLASSES | AUDIO_CLASSES | VIDEO_CLASSES
# Latent/source shapers (EmptyLatentImage…) are wiring even when nothing
# consumes them — they never carry results out of the graph.
_SOURCE_ONLY_CLASSES = _INPUT_ONLY_CLASSES | TEXT_AREA_CLASSES | NUMBER_CLASSES
# Classes that are known-internal tails: standard decode steps and cache
# cleaners consume media but never emit history outputs, so they can never
# be output candidates (HEL-638: a graph ending in these has no output).
_NON_OUTPUT_CLASSES = frozenset(
{"VAEDecode", "VAEDecodeTiled", "VAEDecodeAudio", "easy cleanGpuUsed"}
)
# Widget names save-style custom nodes carry, and link input names that mark
# "consumes rendered media" — used to flag unknown sinks that need mapping.
_SAVE_WIDGET_NAMES = frozenset(
{"filename_prefix", "filename", "prefix", "path", "output_path", "save_output"}
)
_MEDIA_LINK_NAMES = frozenset(
{"images", "image", "video", "frames", "latent", "latents", "audio", "audios"}
)
def _sinks(
workflow: dict[str, Any], consumers: dict[str, list[tuple[str, str]]]
) -> list[tuple[str, dict[str, Any]]]:
out: list[tuple[str, dict[str, Any]]] = []
for nid, node in sorted(
((str(k), v) for k, v in workflow.items() if isinstance(v, dict)),
key=lambda kv: _node_sort_key(kv[0]),
):
if not consumers.get(nid):
out.append((nid, node))
return out
def _unknown_sink_looks_like_save(node: dict[str, Any], workflow: dict[str, Any]) -> bool:
inputs = node.get("inputs") or {}
for name, val in inputs.items():
if name in _SAVE_WIDGET_NAMES and isinstance(val, (str, int, float, bool)):
return True
if name in _MEDIA_LINK_NAMES and isinstance(val, list) and len(val) == 2:
src = workflow.get(str(val[0]))
if isinstance(src, dict) and "decode" in str(src.get("class_type") or "").lower():
return True
return False
def _node_has_save_widget(node: dict[str, Any]) -> bool:
"""A concrete save widget (filename/prefix/path) — the only signal that
counts for unknown nodes that something else consumes; media links from
decode steps are meaningless there (every transform has them)."""
inputs = node.get("inputs") or {}
return any(
name in _SAVE_WIDGET_NAMES and isinstance(val, (str, int, float, bool))
for name, val in inputs.items()
)
def _video_semantics(workflow: dict[str, Any]) -> bool:
"""Auxiliary evidence the graph renders video (frame counts, video nodes)."""
for node in workflow.values():
if not isinstance(node, dict):
continue
ct = str(node.get("class_type") or "").lower()
if "video" in ct or "animatediff" in ct:
return True
for name in (node.get("inputs") or {}):
if name in _FRAME_INPUTS:
return True
return False
def _suggest_output_kind(class_type: str, videoish: bool) -> str | None:
"""Best-guess media type for an unknown candidate — UI default only."""
lower = class_type.lower()
if "video" in lower or "animatediff" in lower:
return "video"
if "image" in lower or "save" in lower:
return "image"
return "video" if videoish else None
def _unknown_output_entry(
nid: str, node: dict[str, Any], workflow: dict[str, Any], videoish: bool
) -> dict[str, Any]:
ct = str(node.get("class_type") or "")
return {
"nodeId": nid,
"label": _title_of(node) or ct,
"role": None,
# HEL-638: unknown custom nodes are never auto-typed — the user
# picks the media type; `suggested_kind` is only a form default.
"kind": None,
"class_type": ct,
"evidence": "unknown_node",
"suggested_kind": _suggest_output_kind(ct, videoish),
}
def detect_output_nodes(workflow: dict[str, Any]) -> list[dict[str, Any]]:
"""Infer output nodes of an untagged workflow from its sinks.
Exact registry classes (SaveImage, VHS_VideoCombine…) count whether or
not something downstream consumes them (a SaveVideo feeding a
cache-cleanup tail is still the output). Every OTHER class at an output
position is an *unknown candidate*: kind stays null, the import page
asks the user to designate the real output node(s) and their media
type, and the workflow stays pending until then (HEL-638). Sinks with
no save features only become candidates when the graph has no trusted
output at all — next to a real saver they are utility tails.
"""
if not isinstance(workflow, dict):
return []
consumers = _consumers(workflow)
videoish = _video_semantics(workflow)
registry_outputs: list[dict[str, Any]] = []
candidates: list[dict[str, Any]] = []
seen: set[str] = set()
def _is_wiring(ct: str) -> bool:
return (
not ct
or ct in _SOURCE_ONLY_CLASSES
or ct in _NON_OUTPUT_CLASSES
or ct.startswith("Empty")
)
# 1) Trusted registry outputs at sink positions.
for nid, node in _sinks(workflow, consumers):
ct = str(node.get("class_type") or "")
if ct in IMAGE_OUTPUT_CLASSES or ct in VIDEO_OUTPUT_CLASSES:
registry_outputs.append(
{
"nodeId": nid,
"label": _title_of(node) or ct,
"role": None,
"kind": "video" if ct in VIDEO_OUTPUT_CLASSES else "image",
"class_type": ct,
"evidence": "registry",
}
)
seen.add(nid)
# 2) Registry output classes consumed by other nodes are outputs too.
for nid, node in sorted(
((str(k), v) for k, v in workflow.items() if isinstance(v, dict)),
key=lambda kv: _node_sort_key(kv[0]),
):
ct = str(node.get("class_type") or "")
if nid in seen or ct not in (IMAGE_OUTPUT_CLASSES | VIDEO_OUTPUT_CLASSES):
continue
registry_outputs.append(
{
"nodeId": nid,
"label": _title_of(node) or ct,
"role": None,
"kind": "video" if ct in VIDEO_OUTPUT_CLASSES else "image",
"class_type": ct,
"evidence": "registry",
}
)
seen.add(nid)
# 3) Unknown sink candidates. Save-looking sinks always need mapping;
# feature-less sinks only when nothing trusted exists (utility tails
# next to a real saver stay invisible).
has_trusted = bool(registry_outputs)
for nid, node in _sinks(workflow, consumers):
ct = str(node.get("class_type") or "")
if nid in seen or _is_wiring(ct) or ct in (IMAGE_OUTPUT_CLASSES | VIDEO_OUTPUT_CLASSES):
continue
if _unknown_sink_looks_like_save(node, workflow) or not has_trusted:
candidates.append(_unknown_output_entry(nid, node, workflow, videoish))
seen.add(nid)
# 4) Unknown save-looking nodes that something consumes (a custom saver
# feeding a cleanup tail is still an output candidate). Only concrete
# save widgets count here — decode-fed media links are ubiquitous among
# mid-graph transforms (CreateVideo & co.) and never mark an output.
for nid, node in sorted(
((str(k), v) for k, v in workflow.items() if isinstance(v, dict)),
key=lambda kv: _node_sort_key(kv[0]),
):
ct = str(node.get("class_type") or "")
if nid in seen or _is_wiring(ct) or ct in (IMAGE_OUTPUT_CLASSES | VIDEO_OUTPUT_CLASSES):
continue
if _node_has_save_widget(node):
candidates.append(_unknown_output_entry(nid, node, workflow, videoish))
seen.add(nid)
results = registry_outputs + candidates
results.sort(key=lambda r: _node_sort_key(r["nodeId"]))
return results
# Title heuristics the studio form applies to tagged (Input:…) slots; the
# classifier must judge a workflow the same way the form renders it.
_TAGGED_FIRST_RE = re.compile(r"first|start|首帧", re.IGNORECASE)
_TAGGED_LAST_RE = re.compile(r"last|end|尾帧", re.IGNORECASE)
_TAGGED_MASK_RE = re.compile(r"mask|遮罩", re.IGNORECASE)
def _slot_effective_role(entry: dict[str, Any]) -> str | None:
"""The role the generate form will act on for this schema entry."""
kind = str(entry.get("kind") or "")
if kind == "image_list":
return "reference_image"
role = normalize_input_role(entry.get("role"))
if entry.get("auto") or kind not in ("image", "image_url"):
return role
label = str(entry.get("label") or "")
if _TAGGED_MASK_RE.search(label):
return "mask"
if _TAGGED_FIRST_RE.search(label):
return "first_frame"
if _TAGGED_LAST_RE.search(label):
return "last_frame"
return role
def classify_usage(workflow: dict[str, Any]) -> dict[str, Any]:
"""Judge a workflow's usage from graph evidence (HEL-636 §2).
Returns ``usage`` plus everything the import confirm page shows:
``ambiguous`` (needs a human decision), ``needs_mapping`` (unknown
output nodes), ``problem`` (Chinese reason when usage is None) and
``evidence`` (output nodes, image/video slots, summary lines). Never
looks at file names, model names or fixed node ids.
"""
inputs = parse_dynamic_inputs(workflow) if isinstance(workflow, dict) else []
outputs = parse_dynamic_outputs(workflow)
media_outputs = [o for o in outputs if o.get("kind") in ("image", "video")]
unknown_outputs = [o for o in outputs if o.get("evidence") == "unknown_node"]
out_kinds = sorted({o["kind"] for o in media_outputs})
image_slots: list[dict[str, Any]] = []
video_slots: list[dict[str, Any]] = []
for entry in inputs:
kind = str(entry.get("kind") or "")
if kind in ("image", "image_list", "image_url"):
image_slots.append(
{
"nodeId": entry.get("nodeId"),
"label": entry.get("label"),
"kind": kind,
"role": _slot_effective_role(entry),
}
)
elif kind == "video":
video_slots.append(
{
"nodeId": entry.get("nodeId"),
"label": entry.get("label"),
"kind": kind,
"role": normalize_input_role(entry.get("role")),
}
)
effective = [s["role"] or "image" for s in image_slots if s["role"] != "mask"]
bulk = [r for r in effective if r in (None, "image")]
has_frame = any(r in ("first_frame", "last_frame") for r in effective)
has_ref_group = any(s["kind"] == "image_list" for s in image_slots)
summary: list[str] = []
for o in media_outputs:
zh = "图片" if o["kind"] == "image" else "视频"
summary.append(f"输出:节点 {o['nodeId']}({o.get('class_type') or o['label']})→ {zh}")
if unknown_outputs:
names = "、".join(
f"节点 {o['nodeId']}({o.get('class_type') or '?'})" for o in unknown_outputs[:4]
)
summary.append(f"存在无法识别的输出节点:{names},需人工指定输出节点及媒体类型")
for s in image_slots:
if s["role"] != "mask":
summary.append(f"图片输入:节点 {s['nodeId']}({s['label']})")
if video_slots:
summary.append("含视频输入槽(本版本不支持参考视频上传)")
usage: str | None = None
ambiguous = False
problem: str | None = None
if not out_kinds and not unknown_outputs:
problem = (
"未在图中找到输出节点(SaveImage / 视频合成等),"
"请确认导出的是 API 格式且包含保存节点"
)
elif unknown_outputs:
# HEL-638: any unknown custom output node keeps the workflow
# pending — no name-based guessing, and picking a usage alone must
# not bypass the output-node designation.
names = "、".join(
f"节点 {o['nodeId']}({o.get('class_type') or '?'})" for o in unknown_outputs[:4]
)
ambiguous = True
problem = (
f"存在无法识别的输出节点({names}),"
"需人工指定实际输出节点及其媒体类型(图片/视频)后才能保存启用"
)
elif len(out_kinds) > 1:
ambiguous = True
problem = "同一工作流同时输出图片和视频,需人工选择主用途"
elif len(out_kinds) == 1:
if out_kinds[0] == "image":
usage = "image2image" if bulk else "text2image"
elif has_ref_group or len(bulk) >= 2:
usage = "ref2video"
elif has_frame and not bulk:
usage = "image2video"
elif not effective:
usage = "text2video"
else:
ambiguous = True
problem = "视频工作流中的单张图片输入无法判定是首帧还是参考图,需人工确认"
return {
"usage": usage,
"ambiguous": ambiguous,
"needs_mapping": bool(unknown_outputs),
"problem": problem,
"evidence": {
"outputs": outputs,
"image_slots": image_slots,
"video_slots": video_slots,
"summary": summary,
},
"usable_usage": list(USAGE_VALUES),
}