Files
aigc-home/calliope-backend/src/calliope/routers/workflows.py
T
总工andmultica-agent e6f761f8c8 feat(workflows): 五类用途识别与导入确认闭环 (HEL-636)
- 判型器 classify_usage:按输出节点(sink 检测)与被消费图片槽判定
  文生图/图生图/文生视频/图生视频/参考图生视频,不依赖文件名/模型名/
  固定节点 ID;歧义(单散装图+视频、同图双输出)与无输出给中文说明
- 参考图组泛化:任意 <group>.<prefix>N 连续编号且均接图源的输入成组
  (MiniMaxH3 特判仅剩标签美化);patcher 支持通用组回填
- workflows 表新增 usage/usage_source,幂等迁移回填;判不出的存量行
  停用待确认;kind 语义收窄为输出媒体,历史无损
- 导入改两步向导:分析→预览(判定依据/输出节点/媒体槽角色可改/
  参数预览/警告)→确认保存;usage_source=user 的纠正不被重分析覆盖
- 生成页按 usage 过滤;待确认工作流不进生成页且提交被拒
- 新增 test_usage_classifier / test_workflow_import_confirm;
  两个旧测试夹具补输出节点以匹配新守卫

Co-authored-by: multica-agent <github@multica.ai>
2026-09-29 12:13:33 +08:00

267 lines
11 KiB
Python

from __future__ import annotations
import json
from typing import Any
from fastapi import APIRouter, HTTPException
from calliope.comfyui.lint import workflow_warnings
from calliope.comfyui.parser import (
classify_usage,
effective_input_schema,
parse_dynamic_inputs,
parse_dynamic_outputs,
)
from calliope.comfyui.profiles import detect_prompt_profile
from calliope.comfyui.roles import usage_to_kind
from calliope.config import settings
from calliope.db import get_db, row_to_dict
from calliope.models.schemas import WorkflowAnalyze, WorkflowCreate, WorkflowUpdate
router = APIRouter()
def _serialize_workflow(row: Any) -> dict[str, Any]:
data = row_to_dict(row)
data["workflow_json"] = json.loads(data["workflow_json"])
stored = json.loads(data["input_schema"]) if data.get("input_schema") else []
data["input_schema"] = effective_input_schema(stored, data["workflow_json"])
data["output_schema"] = json.loads(data["output_schema"]) if data.get("output_schema") else []
data["is_enabled"] = bool(data.get("is_enabled"))
data["warnings"] = workflow_warnings(data["workflow_json"])
return data
@router.post("/analyze")
async def analyze_workflow(payload: WorkflowAnalyze) -> dict[str, Any]:
inputs = parse_dynamic_inputs(payload.workflow_json)
outputs = parse_dynamic_outputs(payload.workflow_json)
judgment = classify_usage(payload.workflow_json)
return {
"inputs": inputs,
"outputs": outputs,
"suggested_profile": detect_prompt_profile(payload.workflow_json),
"warnings": workflow_warnings(payload.workflow_json),
"usage": judgment["usage"],
"usage_ambiguous": judgment["ambiguous"],
"needs_mapping": judgment["needs_mapping"],
"usage_problem": judgment["problem"],
"usage_evidence": judgment["evidence"],
"usable_usage": judgment["usable_usage"],
}
def _stored_schema(payload_schema: list[dict[str, Any]] | None, workflow: dict[str, Any]) -> str:
"""Schema to persist: the confirm page's corrected copy, else the auto one."""
if payload_schema and all(isinstance(e, dict) for e in payload_schema):
return json.dumps(payload_schema)
return json.dumps(parse_dynamic_inputs(workflow))
@router.post("/{workflow_id}/reanalyze")
async def reanalyze_workflow(workflow_id: int) -> dict[str, Any]:
"""Recompute usage and input/output schemas from the stored workflow JSON.
Workflows imported before a parser upgrade keep stale (often empty)
schemas — this refreshes them without re-importing. A usage the user
set by hand is never overwritten; only ``auto`` (and pending NULL)
rows get the new judgment.
"""
conn = get_db(settings.db_path)
try:
row = conn.execute("SELECT * FROM workflows WHERE id = ?", (workflow_id,)).fetchone()
if not row:
raise HTTPException(status_code=404, detail="Workflow not found")
data = row_to_dict(row)
workflow = json.loads(data["workflow_json"])
judgment = classify_usage(workflow)
usage = data["usage"]
usage_source = data["usage_source"]
if data["usage_source"] != "user" and judgment["usage"]:
usage = judgment["usage"]
usage_source = "auto"
stored = json.loads(data["input_schema"]) if data["input_schema"] else []
schema = effective_input_schema(stored, workflow)
outputs = parse_dynamic_outputs(workflow)
conn.execute(
"UPDATE workflows SET input_schema = ?, output_schema = ?,"
" usage = ?, usage_source = ? WHERE id = ?",
(json.dumps(schema), json.dumps(outputs), usage, usage_source, workflow_id),
)
conn.commit()
fresh = conn.execute(
"SELECT * FROM workflows WHERE id = ?", (workflow_id,)
).fetchone()
return _serialize_workflow(fresh)
finally:
conn.close()
@router.get("")
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()
return [_serialize_workflow(r) for r in rows]
finally:
conn.close()
@router.post("/dedupe")
async def dedupe_workflows() -> dict[str, Any]:
"""Delete byte-identical duplicate workflows, keeping the lowest id.
Two rows are duplicates only when name, kind AND workflow_json all match —
same name with different JSON is a user's variant, never touched.
"""
conn = get_db(settings.db_path)
try:
rows = conn.execute(
"SELECT id, name, kind, workflow_json FROM workflows ORDER BY id"
).fetchall()
seen: dict[tuple[str, str, str], int] = {}
drop_ids: list[int] = []
for r in rows:
key = (r["name"], r["kind"], r["workflow_json"])
if key in seen:
drop_ids.append(r["id"])
else:
seen[key] = r["id"]
removed = 0
for wid in drop_ids:
cur = conn.execute("DELETE FROM workflows WHERE id = ?", (wid,))
removed += cur.rowcount
conn.commit()
return {
"ok": True,
"removed": removed,
"kept_ids": sorted(seen.values()),
"removed_ids": drop_ids,
}
finally:
conn.close()
@router.post("")
async def create_workflow(payload: WorkflowCreate) -> dict[str, Any]:
judgment = classify_usage(payload.workflow_json)
usage = payload.usage or judgment["usage"]
usage_source = "user" if payload.usage else "auto"
kind = payload.kind or usage_to_kind(usage)
if kind is None:
# Indeterminate and nothing chosen: classify_output hint keeps old
# callers working while the workflow stays pending confirmation.
out_kinds = {
o.get("kind")
for o in parse_dynamic_outputs(payload.workflow_json)
if o.get("kind") in ("image", "video")
}
kind = "video" if out_kinds == {"video"} else "image"
profile = payload.prompt_profile or detect_prompt_profile(payload.workflow_json)
conn = get_db(settings.db_path)
try:
# Byte-identical re-imports are the main way the library fills up with
# same-named clones (the "@" typeahead then shows 20 identical rows).
existing = conn.execute(
"SELECT id, name FROM workflows WHERE name = ? AND kind = ? AND workflow_json = ?",
(payload.name, kind, json.dumps(payload.workflow_json)),
).fetchone()
if existing:
raise HTTPException(
status_code=409,
detail=(
f"An identical workflow already exists (id {existing['id']},"
f" “{existing['name']}”)."
),
)
# Unconfirmed workflows (ambiguous / unknown outputs) are stored but
# disabled: they must not reach the generate pages until the user
# confirms a usage on the connections page (PATCH sets it back on).
is_enabled = 1 if usage else 0
cur = conn.execute(
"""
INSERT INTO workflows (name, kind, workflow_json, input_schema,
output_schema, description, prompt_profile,
endpoint_id, is_enabled, usage, usage_source)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
payload.name,
kind,
json.dumps(payload.workflow_json),
_stored_schema(payload.input_schema, payload.workflow_json),
json.dumps(parse_dynamic_outputs(payload.workflow_json)),
payload.description,
profile,
payload.endpoint_id,
is_enabled,
usage,
usage_source,
),
)
conn.commit()
row = conn.execute("SELECT * FROM workflows WHERE id = ?", (cur.lastrowid,)).fetchone()
return _serialize_workflow(row)
finally:
conn.close()
@router.get("/{workflow_id}")
async def get_workflow(workflow_id: int) -> dict[str, Any]:
conn = get_db(settings.db_path)
try:
row = conn.execute("SELECT * FROM workflows WHERE id = ?", (workflow_id,)).fetchone()
if not row:
raise HTTPException(status_code=404, detail="Workflow not found")
return _serialize_workflow(row)
finally:
conn.close()
@router.patch("/{workflow_id}")
async def update_workflow(workflow_id: int, payload: WorkflowUpdate) -> dict[str, Any]:
conn = get_db(settings.db_path)
try:
existing = conn.execute("SELECT * FROM workflows WHERE id = ?", (workflow_id,)).fetchone()
if not existing:
raise HTTPException(status_code=404, detail="Workflow not found")
data = payload.model_dump(exclude_unset=True)
if "is_enabled" in data and data["is_enabled"] is not None:
data["is_enabled"] = 1 if data["is_enabled"] else 0
if data.get("usage"):
# Confirming / correcting the usage is an explicit user decision:
# it re-enables the workflow and keeps kind (output media) in sync.
data.setdefault("usage_source", "user")
data["kind"] = usage_to_kind(data["usage"]) or existing["kind"]
if "is_enabled" not in data:
data["is_enabled"] = 1
if "input_schema" in data and data["input_schema"] is not None:
if not all(isinstance(e, dict) for e in data["input_schema"]):
raise HTTPException(status_code=422, detail="input_schema 必须是参数对象数组")
data["input_schema"] = json.dumps(data["input_schema"])
# endpoint_id: explicit null clears the binding; other Nones are skips.
explicit_null = {"endpoint_id"} & {k for k, v in data.items() if v is None}
data = {k: v for k, v in data.items() if v is not None or k in explicit_null}
if data:
fields = ", ".join(f"{k} = :{k}" for k in data)
data["id"] = workflow_id
conn.execute(f"UPDATE workflows SET {fields} WHERE id = :id", data)
conn.commit()
row = conn.execute("SELECT * FROM workflows WHERE id = ?", (workflow_id,)).fetchone()
return _serialize_workflow(row)
finally:
conn.close()
@router.delete("/{workflow_id}")
async def delete_workflow(workflow_id: int) -> dict[str, bool]:
conn = get_db(settings.db_path)
try:
cur = conn.execute("DELETE FROM workflows WHERE id = ?", (workflow_id,))
conn.commit()
if cur.rowcount == 0:
raise HTTPException(status_code=404, detail="Workflow not found")
return {"ok": True}
finally:
conn.close()