HEL-892: add offline workflow catalogue and conservative conversion framework

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
leefer
2026-10-27 23:39:54 +08:00
co-authored by multica-agent
parent 1fc8bdb8bb
commit 3cf6ae4241
189 changed files with 404584 additions and 44 deletions
@@ -9,8 +9,13 @@ from typing import Any
import httpx
from calliope.comfyui.registry import (
AUDIO_CLASSES,
IMAGE_CLASSES,
VIDEO_CLASSES,
VIDEO_FILE_CLASSES,
)
from calliope.config import settings
from calliope.comfyui.registry import IMAGE_CLASSES, AUDIO_CLASSES, VIDEO_CLASSES, VIDEO_FILE_CLASSES
logger = logging.getLogger("calliope.comfyui")
@@ -336,6 +341,9 @@ class ComfyUIClient:
_VIDEO_EXTS = frozenset({".mp4", ".webm", ".mkv", ".mov", ".gif", ".m4v", ".avi", ".flv"})
_IMAGE_EXTS = frozenset({".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tif", ".tiff"})
_AUDIO_EXTS = frozenset({".wav", ".mp3", ".flac", ".ogg", ".opus", ".m4a", ".aac"})
_FILE_EXTS = frozenset({".srt", ".vtt", ".txt", ".json"})
@classmethod
def _infer_media_kind(cls, filename: str, history_key: str) -> str | None:
ext = Path(str(filename)).suffix.lower()
@@ -343,6 +351,12 @@ class ComfyUIClient:
return "video"
if ext in cls._IMAGE_EXTS:
return "image"
if ext in cls._AUDIO_EXTS:
return "audio"
if ext in cls._FILE_EXTS:
return "file"
if history_key in ("audio", "audios"):
return "audio"
if history_key in ("gifs", "videos"):
return "video"
return None
@@ -361,9 +375,14 @@ class ComfyUIClient:
for node_id, node_out in (history.get("outputs") or {}).items():
if node_kinds is not None and str(node_id) not in node_kinds:
continue
for key in ("images", "gifs", "videos"):
for item in node_out.get(key) or []:
filename = item.get("filename", "")
for key in ("images", "gifs", "videos", "audio", "audios", "files"):
items = node_out.get(key) or []
if not isinstance(items, list):
continue
for item in items:
if not isinstance(item, dict) or not item.get("filename"):
continue
filename = item["filename"]
outputs.append(
{
"filename": filename,
@@ -0,0 +1,443 @@
"""Source-tracked, disabled-by-default example library with reversible batches."""
from __future__ import annotations
import hashlib
import json
import sqlite3
import uuid
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from calliope.comfyui.lint import workflow_warnings
from calliope.comfyui.output_map import auto_output_map, needs_user_output_map
from calliope.comfyui.parser import classify_usage, parse_dynamic_inputs, parse_dynamic_outputs
from calliope.comfyui.preflight import check_workflow_against
from calliope.comfyui.ui2api import convert
LIBRARY_COLUMNS = {
"source_repo_path": "TEXT",
"source_sha": "TEXT",
"source_commit": "TEXT",
"batch_id": "TEXT",
"raw_source_json": "TEXT",
"doc_json": "TEXT",
"import_state": "TEXT",
"import_issues": "TEXT",
"imported_at": "TEXT",
"doc_completed_at": "TEXT",
"exec_verified_at": "TEXT",
"library_fingerprint": "TEXT",
}
def migrate_library(conn: sqlite3.Connection) -> None:
"""Rebuild only the legacy kind constraint; preserve columns, indexes and FKs."""
sql = conn.execute("SELECT sql FROM sqlite_master WHERE name='workflows'").fetchone()[0]
old = "CHECK(kind IN ('image', 'video'))"
if old in sql:
conn.commit()
foreign_keys = conn.execute("PRAGMA foreign_keys").fetchone()[0]
conn.execute("PRAGMA foreign_keys=OFF")
try:
conn.execute("BEGIN")
has_sequence = conn.execute(
"SELECT 1 FROM sqlite_master WHERE name='sqlite_sequence'"
).fetchone()
sequence = (
conn.execute("SELECT seq FROM sqlite_sequence WHERE name='workflows'").fetchone()
if has_sequence
else None
)
objects = conn.execute(
"SELECT sql FROM sqlite_master WHERE tbl_name='workflows' "
"AND type IN ('index','trigger') AND sql IS NOT NULL"
).fetchall()
conn.execute(
sql.replace(
"CREATE TABLE workflows", "CREATE TABLE workflows_library_new", 1
).replace(old, "CHECK(kind IN ('image', 'video', 'audio', 'file', 'unknown'))")
)
columns = ",".join(
'"' + r[1] + '"' for r in conn.execute("PRAGMA table_info(workflows)")
)
conn.execute(
f"INSERT INTO workflows_library_new ({columns}) SELECT {columns} FROM workflows"
)
conn.execute("DROP TABLE workflows")
conn.execute("ALTER TABLE workflows_library_new RENAME TO workflows")
if sequence is not None:
conn.execute(
"UPDATE sqlite_sequence SET seq=MAX(seq,?) WHERE name='workflows'",
(sequence[0],),
)
for obj in objects:
conn.execute(obj[0])
conn.commit()
except Exception:
conn.rollback()
raise
finally:
conn.execute(f"PRAGMA foreign_keys={foreign_keys}")
existing = {r[1] for r in conn.execute("PRAGMA table_info(workflows)")}
for name, kind in LIBRARY_COLUMNS.items():
if name not in existing:
conn.execute(f"ALTER TABLE workflows ADD COLUMN {name} {kind}")
conn.execute(
"CREATE UNIQUE INDEX IF NOT EXISTS uq_workflow_source ON workflows(source_repo_path) "
"WHERE source_repo_path IS NOT NULL"
)
conn.execute(
"CREATE TABLE IF NOT EXISTS workflow_revisions ("
"id INTEGER PRIMARY KEY, batch_id TEXT NOT NULL, workflow_id INTEGER NOT NULL, "
"before_json TEXT, after_fingerprint TEXT NOT NULL, rolled_back INTEGER DEFAULT 0)"
)
def _json(value: Any) -> str:
return json.dumps(value, ensure_ascii=False, sort_keys=True)
def fingerprint(row: dict[str, Any]) -> str:
# Include enable/map/description edits so a later import cannot discard user work.
data = {k: v for k, v in row.items() if k not in ("id", "created_at", "library_fingerprint")}
return hashlib.sha256(_json(data).encode()).hexdigest()
def load_snapshot(path: Path | None) -> dict[str, Any] | None:
if path is None:
return None
value = json.loads(path.read_text())
if (
value.get("status") != "captured"
or not value.get("source_url", "").endswith("/object_info")
or not value.get("captured_at")
or not isinstance(value.get("object_info"), dict)
):
raise ValueError("需要含来源、时间和 object_info 的成功快照;连接失败记录不可用于转换")
return value
def build_document(
path: str, source: Any, prompt: dict | None, snapshot: dict | None, issues: list[dict]
) -> dict:
"""Evidence draft: keep UI values unnamed, never invent units or parameter ranges."""
info = (snapshot or {}).get("object_info", {})
params, inventory, notes, links = [], [], [], []
def inspect(graph: dict, scope: str = "") -> None:
is_ui = isinstance(graph.get("nodes"), list)
nodes = (
graph["nodes"]
if is_ui
else [
dict(v, id=k, type=v.get("class_type"))
for k, v in graph.items()
if isinstance(v, dict) and "class_type" in v
]
)
for node in nodes:
nid = scope + str(node.get("id", ""))
ct = node.get("type", "")
values = node.get("widgets_values", []) if is_ui else node.get("inputs", {})
inventory.append(
{
"node_id": nid,
"class_type": ct,
"title": node.get("title") or (node.get("_meta") or {}).get("title"),
"mode": node.get("mode", 0),
"source_values": values,
"inputs": node.get("inputs", []) if is_ui else values,
}
)
if ct in ("Note", "MarkdownNote"):
notes.append({"node_id": nid, "content": values})
# Only API/named fields have a defensible node+field association.
if not is_ui:
declared = {
**info.get(ct, {}).get("input", {}).get("required", {}),
**info.get(ct, {}).get("input", {}).get("optional", {}),
}
for name, value in values.items():
if isinstance(value, list) and len(value) == 2:
continue
spec = declared.get(name, [])
cfg = spec[1] if len(spec) > 1 and isinstance(spec[1], dict) else {}
params.append(
{
"name": name,
"node_id": nid,
"field": name,
"type": spec[0]
if spec and isinstance(spec[0], str)
else type(value).__name__,
"default": value,
"unit": None,
"min": cfg.get("min"),
"max": cfg.get("max"),
"options": spec[0] if spec and isinstance(spec[0], list) else None,
"range_source": "object_info" if spec else "unverified",
"default_source": "source_file",
"effect": cfg.get("tooltip") or "待节点定义及人工核对",
"advanced": False,
}
)
links.extend({"scope": scope, "link": link} for link in graph.get("links", []))
for sub in (graph.get("definitions") or {}).get("subgraphs", []):
inspect(sub, scope + str(sub.get("id", "?")) + "/")
if isinstance(source, dict):
inspect(source)
model_exts = (".safetensors", ".ckpt", ".pt", ".pth", ".bin", ".gguf", ".onnx")
models = set()
def strings(value: Any) -> None:
if isinstance(value, str) and value.lower().endswith(model_exts):
models.add(value)
elif isinstance(value, (list, dict)):
for v in value.values() if isinstance(value, dict) else value:
strings(v)
# Editor metadata and note download URLs are not active model selections.
for node in inventory:
if node["class_type"] not in ("Note", "MarkdownNote"):
strings(node["source_values"])
inputs = parse_dynamic_inputs(prompt or {})
outputs = parse_dynamic_outputs(prompt or {})
return {
"title": Path(path).stem,
"purpose": f"源目录:{Path(path).parent};工作流:{Path(path).stem}。用途待逐节点复核。",
"draft": True,
"source_path": path,
"materials": [
{"slot": i.get("nodeId"), "desc": i.get("label"), "required": i.get("required", False)}
for i in inputs
if i.get("kind") in ("image", "video", "audio", "image_list")
],
"dependencies": {
"models": sorted(models),
"node_types": sorted({n["class_type"] for n in inventory}),
"node_packs": [],
"missing": [],
"check_state": "unchecked",
"source": (snapshot or {}).get("source_url"),
"checked_at": None,
"model_locations": "待目标机提供",
},
"params": params,
"source_nodes": inventory,
"source_links": links,
"source_notes": notes,
"steps": [
f"打开源工作流 {path},逐项核对下列源节点与注释。",
"补齐节点定义、模型来源及所需素材;完成输入输出映射核对。",
"明确触发真实测试后核对产物;本批未提交生成任务。",
],
"io": {"inputs": inputs, "outputs": outputs},
"errors": [
{"symptom": i["message"], "fix": "按具体节点补材料或提供原 ComfyUI API 导出。"}
for i in issues
],
"status": {"imported": True, "doc_done": False, "exec_verified": False},
}
def import_library(
conn: sqlite3.Connection, root: Path, *, source_commit: str, snapshot: dict | None = None
) -> dict:
"""Caller supplies a migrated local DB. Single transaction; no network or jobs."""
batch = str(uuid.uuid4())
report: dict[str, Any] = {"batch_id": batch, "source_commit": source_commit, "files": []}
info = (snapshot or {}).get("object_info")
conn.row_factory = sqlite3.Row
with conn:
conn.execute("BEGIN IMMEDIATE")
for path in sorted(p for p in root.rglob("*") if p.is_file()):
relative = root.name + "/" + path.relative_to(root).as_posix()
raw = path.read_bytes()
sha = hashlib.sha1(raw).hexdigest()
existing = conn.execute(
"SELECT * FROM workflows WHERE source_repo_path=?", (relative,)
).fetchone()
record = {"path": relative, "source_sha": sha}
if existing and fingerprint(dict(existing)) != existing["library_fingerprint"]:
report["files"].append(
{
**record,
"result": "conflict",
"workflow_id": existing["id"],
"issues": [
{
"code": "user_modified",
"message": "已有条目被用户修改,完整保留;未覆盖",
}
],
}
)
continue
# A fresh snapshot may improve the conversion even when source bytes are unchanged.
snapshot_sha = hashlib.sha256(_json(snapshot).encode()).hexdigest()
if (
existing
and existing["source_sha"] == sha
and existing["import_state"] != "rolled_back"
):
old_doc = json.loads(existing["doc_json"])
if old_doc.get("snapshot_sha") == snapshot_sha:
report["files"].append(
{
**record,
"result": "skipped",
"workflow_id": existing["id"],
"state": existing["import_state"],
"issues": json.loads(existing["import_issues"]),
}
)
continue
source = None
try:
text = raw.decode("utf-8-sig")
source = json.loads(text)
result = convert(source, info)
prompt, issues = result.prompt, result.issues
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
text = raw.hex()
prompt, issues = (
None,
[{"code": "invalid_source", "message": f"源文件无法读取为 JSON:{exc}"}],
)
if prompt:
issues.extend(i for i in workflow_warnings(prompt) if i["level"] == "error")
findings = check_workflow_against(info, prompt) if info else []
issues.extend(findings)
if not info:
issues.append(
{"code": "environment_unchecked", "message": "目标机节点和模型尚未核对"}
)
if needs_user_output_map(prompt) or not auto_output_map(prompt):
issues.append(
{"code": "output_unconfirmed", "message": "输出节点或类型待人工确认"}
)
state = (
"needs_conversion"
if prompt is None
else "pending_check"
if issues
else "pending_test"
)
doc = build_document(relative, source, prompt, snapshot, issues)
doc["snapshot_sha"] = snapshot_sha
judgment = classify_usage(prompt or {})
outputs = auto_output_map(prompt or {})
kinds = {o["kind"] for o in outputs}
kind = next(iter(kinds)) if len(kinds) == 1 else "unknown"
values = {
"name": path.stem,
"kind": kind,
"workflow_json": _json(prompt or {}),
"input_schema": _json(parse_dynamic_inputs(prompt or {})),
"output_schema": _json(parse_dynamic_outputs(prompt or {})),
"output_map": _json(outputs),
"output_map_source": "auto" if outputs else None,
"usage": judgment["usage"],
"usage_source": "auto",
"is_enabled": 0,
"source_repo_path": relative,
"source_sha": sha,
"source_commit": source_commit,
"batch_id": batch,
"raw_source_json": text,
"doc_json": _json(doc),
"import_state": state,
"import_issues": _json(issues),
"imported_at": datetime.now(timezone.utc).isoformat(),
"doc_completed_at": None,
"exec_verified_at": None,
}
before = dict(existing) if existing else None
if existing:
wid = existing["id"]
conn.execute(
"UPDATE workflows SET " + ",".join(f"{k}=?" for k in values) + " WHERE id=?",
[*values.values(), wid],
)
else:
cur = conn.execute(
"INSERT INTO workflows ("
+ ",".join(values)
+ ") VALUES ("
+ ",".join("?" for _ in values)
+ ")",
list(values.values()),
)
wid = cur.lastrowid
row = dict(conn.execute("SELECT * FROM workflows WHERE id=?", (wid,)).fetchone())
digest = fingerprint(row)
conn.execute("UPDATE workflows SET library_fingerprint=? WHERE id=?", (digest, wid))
conn.execute(
"INSERT INTO workflow_revisions "
"(batch_id,workflow_id,before_json,after_fingerprint) "
"VALUES (?,?,?,?)",
(batch, wid, _json(before) if before else None, digest),
)
report["files"].append(
{
**record,
"result": "updated" if existing else "imported",
"workflow_id": wid,
"state": state,
"issues": issues,
}
)
report["counts"] = dict(Counter(r["result"] for r in report["files"]))
report["states"] = dict(Counter(r.get("state", "conflict") for r in report["files"]))
report["total"] = len(report["files"])
report["doc_completed"] = 0
report["exec_verified"] = 0
return report
def rollback_batch(conn: sqlite3.Connection, batch_id: str) -> dict:
"""Restore previous snapshots. Refuse user edits and referenced new rows."""
conn.row_factory = sqlite3.Row
results = []
with conn:
conn.execute("BEGIN IMMEDIATE")
revisions = conn.execute(
"SELECT * FROM workflow_revisions WHERE batch_id=? AND rolled_back=0 ORDER BY id DESC",
(batch_id,),
).fetchall()
for revision in revisions:
wid = revision["workflow_id"]
row = conn.execute("SELECT * FROM workflows WHERE id=?", (wid,)).fetchone()
if row is None or fingerprint(dict(row)) != revision["after_fingerprint"]:
results.append({"workflow_id": wid, "result": "conflict"})
continue
if revision["before_json"]:
before = json.loads(revision["before_json"])
conn.execute(
"UPDATE workflows SET " + ",".join(f"{k}=?" for k in before) + " WHERE id=?",
[*before.values(), wid],
)
else:
# Deleting a new row could detach jobs/canvas references. Keep it disabled instead.
conn.execute(
"UPDATE workflows SET is_enabled=0, import_state=? WHERE id=?",
("rolled_back", wid),
)
new = dict(conn.execute("SELECT * FROM workflows WHERE id=?", (wid,)).fetchone())
conn.execute(
"UPDATE workflows SET library_fingerprint=? WHERE id=?", (fingerprint(new), wid)
)
conn.execute(
"UPDATE workflow_revisions SET rolled_back=1 WHERE id=?", (revision["id"],)
)
results.append(
{
"workflow_id": wid,
"result": "restored" if revision["before_json"] else "disabled",
}
)
return {"batch_id": batch_id, "files": results}
@@ -0,0 +1,98 @@
"""Explicit local library import/rollback and read-only object_info snapshot CLI."""
from __future__ import annotations
import argparse
import asyncio
import hashlib
import json
from datetime import datetime, timezone
from pathlib import Path
import httpx
from calliope.comfyui.library import import_library, load_snapshot, rollback_batch
from calliope.db import get_db, migrate_db
def write(path: Path, data: object) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest="command", required=True)
snap = commands.add_parser("snapshot")
snap.add_argument("--url", required=True)
snap.add_argument("--output", type=Path, required=True)
for command in ("import", "rollback"):
sub = commands.add_parser(command)
sub.add_argument(
"--db", type=Path, required=True, help="Explicit local database; never a remote service"
)
sub.add_argument("--output-dir", type=Path, required=True)
if command == "import":
sub.add_argument("--root", type=Path, required=True)
sub.add_argument("--source-commit", required=True)
sub.add_argument("--snapshot", type=Path)
else:
sub.add_argument("--batch-id", required=True)
args = parser.parse_args()
if args.command == "snapshot":
data = {
"source_url": args.url.rstrip("/") + "/object_info",
"captured_at": datetime.now(timezone.utc).isoformat(),
}
try:
response = httpx.get(data["source_url"], timeout=10, trust_env=False)
response.raise_for_status()
info = response.json()
if not isinstance(info, dict) or not info:
raise ValueError("object_info must be a nonempty object")
data.update(status="captured", object_info=info)
except (httpx.HTTPError, ValueError) as exc:
data.update(status="unavailable", error=f"{type(exc).__name__}: {exc}")
write(args.output, data)
print(data["status"])
if data["status"] != "captured":
raise SystemExit(1)
return
if args.command == "import" and not args.root.is_dir():
parser.error("--root 必须为存在的目录,避免误报空库成功")
snapshot = load_snapshot(args.snapshot) if args.command == "import" else None
asyncio.run(migrate_db(args.db))
conn = get_db(args.db)
try:
if args.command == "import":
report = import_library(
conn, args.root, source_commit=args.source_commit, snapshot=snapshot
)
documents = []
for row in conn.execute(
"SELECT source_repo_path, source_sha, import_state, doc_json "
"FROM workflows WHERE source_repo_path IS NOT NULL ORDER BY source_repo_path"
):
doc = json.loads(row["doc_json"])
key = hashlib.sha256(row["source_repo_path"].encode()).hexdigest()[:16]
write(args.output_dir / "documents" / (key + ".json"), doc)
documents.append(
{
"path": row["source_repo_path"],
"source_sha": row["source_sha"],
"state": row["import_state"],
"doc_done": bool(row["doc_json"] and doc["status"]["doc_done"]),
"document": "documents/" + key + ".json",
}
)
write(args.output_dir / "manifest.json", documents)
else:
report = rollback_batch(conn, args.batch_id)
write(args.output_dir / (args.command + "_report.json"), report)
print(json.dumps({k: v for k, v in report.items() if k != "files"}, ensure_ascii=False))
finally:
conn.close()
if __name__ == "__main__":
main()
@@ -91,7 +91,7 @@ def workflow_warnings(workflow: dict[str, Any]) -> list[dict[str, str]]:
from calliope.comfyui.parser import detect_output_nodes
outputs = detect_output_nodes(workflow)
if not any(o.get("kind") in ("image", "video") for o in outputs):
if not any(o.get("kind") in ("image", "video", "audio", "file") for o in outputs):
unknown = [o for o in outputs if o.get("evidence") == "unknown_node"]
if not unknown:
found.append(
@@ -19,13 +19,12 @@ from typing import Any
from calliope.comfyui.parser import parse_dynamic_outputs
from calliope.comfyui.registry import (
IMAGE_OUTPUT_CLASSES,
NUMBER_CLASSES,
OUTPUT_CLASSES,
TEXT_AREA_CLASSES,
VIDEO_OUTPUT_CLASSES,
)
VALID_OUTPUT_KINDS = ("image", "video")
VALID_OUTPUT_KINDS = ("image", "video", "audio", "file")
def _wiring_class(class_type: str) -> bool:
@@ -91,10 +90,10 @@ def validate_output_map(
ct = str(node.get("class_type") or "").strip()
if not ct:
problems.append(f"节点 {nid} 缺少节点类型,不能作为输出节点")
elif _wiring_class(ct) and ct not in (IMAGE_OUTPUT_CLASSES | VIDEO_OUTPUT_CLASSES):
elif _wiring_class(ct) and ct not in OUTPUT_CLASSES:
problems.append(f"节点 {nid}({ct})是参数/连线节点,不能作为输出节点")
if entry.get("kind") not in VALID_OUTPUT_KINDS:
problems.append(f"输出节点 {nid} 的媒体类型必须是图片或视频")
problems.append(f"输出节点 {nid} 的媒体类型必须是图片、视频、音频或文件")
if nid in seen:
problems.append(f"输出节点 {nid} 重复指定")
seen.add(nid)
+14 -14
View File
@@ -10,13 +10,12 @@ 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,
OPTIONAL_FRAME_INPUTS,
OUTPUT_CLASSES,
TEXT_AREA_CLASSES,
VIDEO_CLASSES,
VIDEO_OUTPUT_CLASSES,
ComfyOutputKind,
class_to_input_kind,
class_to_output_kind,
@@ -791,10 +790,8 @@ def parse_dynamic_outputs(workflow: dict[str, Any]) -> list[dict[str, Any]]:
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"
if canon in ("image", "video", "audio", "file"):
out_kind = canon
results.append(
{
"nodeId": str(node_id),
@@ -944,13 +941,13 @@ def detect_output_nodes(workflow: dict[str, Any]) -> list[dict[str, Any]]:
# 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:
if ct in 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",
"kind": class_to_output_kind(ct),
"class_type": ct,
"evidence": "registry",
}
@@ -963,14 +960,14 @@ def detect_output_nodes(workflow: dict[str, Any]) -> list[dict[str, Any]]:
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):
if nid in seen or ct not in 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",
"kind": class_to_output_kind(ct),
"class_type": ct,
"evidence": "registry",
}
@@ -983,7 +980,7 @@ def detect_output_nodes(workflow: dict[str, Any]) -> list[dict[str, Any]]:
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):
if nid in seen or _is_wiring(ct) or ct in OUTPUT_CLASSES:
continue
if _unknown_sink_looks_like_save(node, workflow) or not has_trusted:
candidates.append(_unknown_output_entry(nid, node, workflow, videoish))
@@ -998,7 +995,7 @@ def detect_output_nodes(workflow: dict[str, Any]) -> list[dict[str, Any]]:
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):
if nid in seen or _is_wiring(ct) or ct in OUTPUT_CLASSES:
continue
if _node_has_save_widget(node):
candidates.append(_unknown_output_entry(nid, node, workflow, videoish))
@@ -1045,7 +1042,7 @@ def classify_usage(workflow: dict[str, Any]) -> dict[str, Any]:
"""
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")]
media_outputs = [o for o in outputs if o.get("kind") in ("image", "video", "audio", "file")]
unknown_outputs = [o for o in outputs if o.get("evidence") == "unknown_node"]
out_kinds = sorted({o["kind"] for o in media_outputs})
@@ -1079,7 +1076,7 @@ def classify_usage(workflow: dict[str, Any]) -> dict[str, Any]:
summary: list[str] = []
for o in media_outputs:
zh = "图片" if o["kind"] == "image" else "视频"
zh = {"image": "图片", "video": "视频", "audio": "音频", "file": "文件"}[o["kind"]]
summary.append(f"输出:节点 {o['nodeId']}({o.get('class_type') or o['label']})→ {zh}")
if unknown_outputs:
names = "、".join(
@@ -1118,6 +1115,9 @@ def classify_usage(workflow: dict[str, Any]) -> dict[str, Any]:
elif len(out_kinds) == 1:
if out_kinds[0] == "image":
usage = "image2image" if bulk else "text2image"
elif out_kinds[0] in ("audio", "file"):
ambiguous = True
problem = "音频/文件输出已识别,请人工确认语音、音乐、转写或工具用途"
elif has_ref_group or len(bulk) >= 2:
usage = "ref2video"
elif has_frame and not bulk:
@@ -4,7 +4,7 @@ from __future__ import annotations
from typing import Any, Literal
ComfyInputKind = Literal["text", "textarea", "number", "image", "image_url", "audio", "video"]
ComfyOutputKind = Literal["image", "video", "other"]
ComfyOutputKind = Literal["image", "video", "audio", "file", "other"]
PatchField = Literal["image", "url", "audio", "video", "file", "text", "value", "int", "float"]
TEXT_AREA_CLASSES = frozenset(
@@ -33,6 +33,9 @@ IMAGE_OUTPUT_CLASSES = frozenset(
{"SaveImage", "PreviewImage", "SaveImageWebsocket", "ETN_SendImageWebSocket",
"SaveImageAdvanced"}
)
AUDIO_OUTPUT_CLASSES = frozenset({"SaveAudio", "SaveAudioMP3", "SaveAudioOpus", "PreviewAudio"})
OUTPUT_CLASSES = IMAGE_OUTPUT_CLASSES | VIDEO_OUTPUT_CLASSES | AUDIO_OUTPUT_CLASSES
# Frame-conditioned video nodes and the optional frame input an export may
# leave unwired. MiniMax H3's FL2VA node takes `first_frame` plus an
# optional `last_frame`; the studio offers the slot and the patcher adds
@@ -110,6 +113,8 @@ def class_to_patch_field(class_type: str) -> PatchField:
def class_to_output_kind(class_type: str) -> ComfyOutputKind:
if class_type in AUDIO_OUTPUT_CLASSES:
return "audio"
if class_type in VIDEO_OUTPUT_CLASSES or "video" in class_type.lower():
return "video"
if class_type in IMAGE_OUTPUT_CLASSES or "image" in class_type.lower():
@@ -28,6 +28,8 @@ INPUT_ROLE_ALIASES: dict[str, frozenset[str]] = {
OUTPUT_ROLE_ALIASES: dict[str, frozenset[str]] = {
"image": frozenset({"image", "img"}),
"video": frozenset({"video", "vid"}),
"audio": frozenset({"audio", "sound"}),
"file": frozenset({"file", "subtitle", "srt"}),
}
# The five workflow usages the studio distinguishes (HEL-636). Derived from
@@ -40,6 +42,7 @@ USAGE_VALUES: tuple[str, ...] = (
"text2video",
"image2video",
"ref2video",
"text2speech", "speech2text", "text2music", "utility", "audio2video", "pose2video",
)
@@ -47,7 +50,11 @@ def usage_to_kind(usage: str | None) -> str | None:
"""Output media kind of a usage (image / video); None when unknown."""
if usage in ("text2image", "image2image"):
return "image"
if usage in ("text2video", "image2video", "ref2video"):
if usage in ("text2speech", "text2music"):
return "audio"
if usage == "speech2text":
return "file"
if usage in ("text2video", "image2video", "ref2video", "audio2video", "pose2video"):
return "video"
return None
@@ -0,0 +1,117 @@
"""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.
Subgraphs, virtual nodes, seed extra controls, mute and bypass need API exports.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
@dataclass
class Conversion:
prompt: dict[str, Any] | None
issues: list[dict[str, Any]] = field(default_factory=list)
def convert(source: Any, object_info: dict[str, Any] | None = None) -> 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()
):
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
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
spec = info.get(ct)
if not isinstance(spec, dict):
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 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
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
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]]
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)
+9 -4
View File
@@ -113,7 +113,7 @@ CREATE INDEX IF NOT EXISTS idx_clips_project ON clips(project_id);
CREATE TABLE IF NOT EXISTS workflows (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
kind TEXT NOT NULL CHECK(kind IN ('image', 'video')),
kind TEXT NOT NULL CHECK(kind IN ('image', 'video', 'audio', 'file', 'unknown')),
workflow_json TEXT NOT NULL,
input_node_map TEXT,
output_node_name TEXT,
@@ -355,7 +355,8 @@ def _backfill_workflow_usage(conn: sqlite3.Connection) -> None:
from calliope.comfyui.parser import classify_usage
rows = conn.execute(
"SELECT id, workflow_json FROM workflows WHERE usage IS NULL OR usage = ''"
"SELECT id, workflow_json FROM workflows WHERE source_repo_path IS NULL"
" AND (usage IS NULL OR usage = '')"
).fetchall()
for row in rows: # plain connect — positional access
try:
@@ -388,7 +389,8 @@ def _backfill_workflow_output_map(conn: sqlite3.Connection) -> None:
rows = conn.execute(
"SELECT id, workflow_json FROM workflows"
" WHERE output_map_source IS NULL OR output_map_source != 'user'"
" WHERE source_repo_path IS NULL"
" AND (output_map_source IS NULL OR output_map_source != 'user')"
).fetchall()
for row in rows:
try:
@@ -423,7 +425,7 @@ _FL2VA_DESCRIPTION = "首帧必填,尾帧可选:只传首帧为图生视频
def _rename_workflows(conn: sqlite3.Connection) -> None:
for wid, name, wf_json in conn.execute(
"SELECT id, name, workflow_json FROM workflows"
"SELECT id, name, workflow_json FROM workflows WHERE source_repo_path IS NULL"
).fetchall():
if not name or "尾帧" in name or not _FIRST_FRAME_NAME_RE.search(name):
continue
@@ -452,6 +454,9 @@ async def migrate_db(db_path: Path) -> None:
db_path.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(db_path)
conn.executescript(SCHEMA)
from calliope.comfyui.library import migrate_library
migrate_library(conn)
# Additive migrations for existing DBs
# Dedupe guard: ARTIFACT nodes keyed by (canvas_id, job_id). Without the
# unique index, the agent's post_artifact_to_canvas and the frontend
@@ -204,12 +204,13 @@ WorkflowUsageKind = Literal[
"text2video",
"image2video",
"ref2video",
"text2speech", "speech2text", "text2music", "utility", "audio2video", "pose2video",
]
class WorkflowCreate(BaseModel):
name: str = Field(..., min_length=1)
kind: Literal["image", "video"] | None = None
kind: Literal["image", "video", "audio", "file"] | None = None
workflow_json: dict[str, Any]
description: str | None = None
prompt_profile: Literal["prose", "minimax_h3_ref"] | None = None
@@ -231,7 +232,7 @@ class WorkflowCreate(BaseModel):
class WorkflowUpdate(BaseModel):
name: str | None = None
kind: Literal["image", "video"] | None = None
kind: Literal["image", "video", "audio", "file"] | None = None
description: str | None = None
prompt_profile: Literal["prose", "minimax_h3_ref"] | None = None
is_enabled: bool | None = None
@@ -224,6 +224,10 @@ class QueueWorker:
raise RuntimeError(
"找不到该任务使用的工作流(可能已被删除),请重新选择工作流后再生成"
)
if workflow_row.get("import_state") in (
"needs_conversion", "pending_check", "rolled_back"
):
raise RuntimeError("工作流库条目尚未完成转换或依赖核对,禁止提交生成任务")
workflow = workflow_row["workflow_json"]
broken = blocking_problem(workflow)
if broken:
@@ -279,7 +283,8 @@ class QueueWorker:
if not outputs_meta:
checked = "、".join(sorted(node_kinds))
raise RuntimeError(
f"ComfyUI 显示任务已结束(任务 ID {prompt_id}),但没有返回任何图片或视频,"
f"ComfyUI 显示任务已结束(任务 ID {prompt_id}),"
"但没有返回任何图片、视频、音频或文件,"
"不算生成完成。已按输出映射检查节点:" f"{checked};"
"请到 ComfyUI 历史中核对该任务,并确认所指定的输出节点正确。"
)
@@ -539,7 +544,7 @@ class QueueWorker:
conn = get_db(config.settings.db_path)
try:
row = conn.execute(
"SELECT workflow_json, output_map, output_map_source FROM workflows"
"SELECT workflow_json, output_map, output_map_source, import_state FROM workflows"
" WHERE id = ?",
(workflow_id,),
).fetchone()
@@ -549,6 +554,7 @@ class QueueWorker:
"workflow_json": json.loads(row["workflow_json"]),
"output_map": row["output_map"],
"output_map_source": row["output_map_source"],
"import_state": row["import_state"],
}
finally:
conn.close()
@@ -45,9 +45,15 @@ from calliope.queue.workflow_test import (
router = APIRouter()
def _serialize_workflow(row: Any) -> dict[str, Any]:
def _serialize_workflow(row: Any, *, include_document: bool = True) -> dict[str, Any]:
data = row_to_dict(row)
data["workflow_json"] = json.loads(data["workflow_json"])
if not include_document:
data.pop("doc_json", None)
for field in (("doc_json", "import_issues") if include_document else ("import_issues",)):
data[field] = json.loads(data[field]) if data.get(field) else None
data.pop("raw_source_json", None)
data.pop("library_fingerprint", None)
stored = json.loads(data["input_schema"]) if data.get("input_schema") else []
data["input_schema"] = effective_input_schema(stored, data["workflow_json"])
# Outputs are pure graph derivation (no manual overrides) — always fresh,
@@ -172,6 +178,8 @@ async def reanalyze_workflow(workflow_id: int) -> dict[str, Any]:
else:
output_map, output_map_source = json.dumps(auto_output_map(workflow)), "auto"
is_enabled = data["is_enabled"]
if data.get("import_state") in ("needs_conversion", "pending_check", "rolled_back"):
is_enabled = 0
if output_map_source is None or usage is None:
is_enabled = 0
conn.execute(
@@ -220,7 +228,7 @@ async def list_workflows() -> list[dict[str, Any]]:
conn = get_db(settings.db_path)
try:
rows = conn.execute("SELECT * FROM workflows ORDER BY id DESC").fetchall()
out = [_serialize_workflow(r) for r in rows]
out = [_serialize_workflow(r, include_document=False) for r in rows]
# 上次测试 state is read live from the newest test job per workflow —
# no cached column that could go stale (HEL-643).
latest: dict[int, dict[str, Any]] = {}
@@ -246,12 +254,15 @@ async def check_workflow(workflow_id: int, payload: WorkflowCheckRequest) -> dic
conn = get_db(settings.db_path)
try:
row = conn.execute(
"SELECT workflow_json, endpoint_id FROM workflows WHERE id = ?", (workflow_id,)
"SELECT workflow_json, endpoint_id, import_state FROM workflows WHERE id = ?",
(workflow_id,)
).fetchone()
finally:
conn.close()
if not row:
raise HTTPException(status_code=404, detail="Workflow not found")
if row["import_state"] in ("needs_conversion", "rolled_back"):
raise HTTPException(status_code=400, detail="请先完成转换或恢复库条目,不能核查空图")
endpoint_id = payload.endpoint_id or row["endpoint_id"]
return await _connection_check(endpoint_id, json.loads(row["workflow_json"]), payload.refresh)
@@ -266,7 +277,8 @@ async def dedupe_workflows() -> dict[str, Any]:
conn = get_db(settings.db_path)
try:
rows = conn.execute(
"SELECT id, name, kind, workflow_json FROM workflows ORDER BY id"
"SELECT id, name, kind, workflow_json FROM workflows"
" WHERE source_repo_path IS NULL ORDER BY id"
).fetchall()
seen: dict[tuple[str, str, str], int] = {}
drop_ids: list[int] = []
@@ -303,9 +315,9 @@ async def create_workflow(payload: WorkflowCreate) -> dict[str, Any]:
out_kinds = {
o.get("kind")
for o in parse_dynamic_outputs(payload.workflow_json)
if o.get("kind") in ("image", "video")
if o.get("kind") in ("image", "video", "audio", "file")
}
kind = "video" if out_kinds == {"video"} else "image"
kind = next(iter(out_kinds)) if len(out_kinds) == 1 else "image"
profile = payload.prompt_profile or detect_prompt_profile(payload.workflow_json)
# HEL-638: an explicit user output map wins; otherwise the trusted auto
# map. Either way a graph with unknown output candidates is unusable
@@ -393,6 +405,12 @@ async def update_workflow(workflow_id: int, payload: WorkflowUpdate) -> dict[str
if not existing:
raise HTTPException(status_code=404, detail="Workflow not found")
data = payload.model_dump(exclude_unset=True)
if existing["import_state"] in ("needs_conversion", "pending_check", "rolled_back"):
if data.get("is_enabled"):
raise HTTPException(
status_code=400, detail="该库条目尚未完成转换或依赖核对,不能启用"
)
data["is_enabled"] = 0
if "is_enabled" in data and data["is_enabled"] is not None:
data["is_enabled"] = 1 if data["is_enabled"] else 0
workflow_json = json.loads(existing["workflow_json"])
@@ -486,11 +504,13 @@ async def test_workflow(workflow_id: int, payload: WorkflowTestRequest) -> dict[
try:
wf = conn.execute(
"SELECT id, kind, workflow_json, input_schema, output_map, output_map_source,"
" endpoint_id FROM workflows WHERE id = ?",
" endpoint_id, import_state FROM workflows WHERE id = ?",
(workflow_id,),
).fetchone()
if not wf:
raise HTTPException(status_code=404, detail="Workflow not found")
if wf["import_state"] in ("needs_conversion", "pending_check", "rolled_back"):
raise HTTPException(status_code=400, detail="该库条目尚未完成转换或依赖核对,不能测试")
workflow_json = json.loads(wf["workflow_json"])
broken = blocking_problem(workflow_json)
if broken: