Files
aigc-home/calliope-backend/src/calliope/comfyui/library.py
T
2026-10-30 08:17:25 +08:00

601 lines
26 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.
"""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.companions import resolve_companion
from calliope.comfyui.delivery_scope import exclusion_for
from calliope.comfyui.fixed_document import fixed_document_for
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.protocol_references import companion_protocol_reference
from calliope.comfyui.source_reviews import review_for
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],
review: dict | None = None,
) -> 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 isinstance(values, dict):
declared = {
**info.get(ct, {}).get("input", {}).get("required", {}),
**info.get(ct, {}).get("input", {}).get("optional", {}),
}
for name, value in values.items():
if is_ui and name == "videopreview":
# Editor preview metadata is preserved in source_nodes only.
continue
if not is_ui and isinstance(value, list) and len(value) == 2:
links.append(
{
"scope": scope,
"node_id": nid,
"field": name,
"upstream_node_id": str(value[0]),
"output_slot": value[1],
}
)
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",
"value_origin": "ui_named_widget" if is_ui else "api_input",
"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 {})
document = {
"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},
}
if review:
document["purpose"] = review["purpose"]
document["steps"].insert(0, review["instruction"])
if review.get("semantic_review"):
document["steps"].insert(1, review["semantic_review"]["operation_check"])
if review.get("fourth_review"):
document["steps"].insert(1, review["fourth_review"]["operation_check"])
document["source_review"] = {
**{k: v for k, v in review.items() if k != "fixed_version_document"},
"scope": review.get("scope", ["结构及用途局部审校"]),
"complete": False,
"unconfirmed": [
"逐参数语义、单位、范围和调整效果未定稿",
*(
["UI 位置控件未具名,含子图和旁路的实际执行路径待黄金导出"]
if isinstance(source, dict) and "nodes" in source
else []
),
"模型/节点包位置、素材可用性及实际输出未在目标环境核对",
],
"evidence": {
"node_count": len(inventory),
"link_count": len(links),
"named_value_count": len(params),
"note_node_ids": [n["node_id"] for n in notes],
"model_references": sorted(models),
"unnamed_widget_node_ids": [
n["node_id"]
for n in inventory
if n["class_type"] not in ("Note", "MarkdownNote")
and isinstance(n["source_values"], list)
and n["source_values"]
],
},
}
fixed = fixed_document_for(path, source, review)
if fixed:
document["fixed_version"] = fixed
if fixed["matched"]:
document["steps"] = document["steps"][:-3] + fixed["steps"]
return document
def import_library(
conn: sqlite3.Connection,
root: Path,
*,
source_commit: str,
snapshot: dict | None = None,
companions: 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()
review = review_for(relative, sha)
review_sha = hashlib.sha256(_json(review).encode()).hexdigest()
existing = conn.execute(
"SELECT * FROM workflows WHERE source_repo_path=?", (relative,)
).fetchone()
record = {"path": relative, "source_sha": sha}
excluded = exclusion_for(relative)
if excluded:
report["files"].append(
{
**record,
"result": "user_excluded",
"scope": excluded,
"workflow_id": existing["id"] if existing else None,
"historical_row_preserved": bool(existing),
}
)
continue
companion = (companions or {}).get(relative)
# Version companion documentation separately from the immutable received bytes.
companion_sha = hashlib.sha256(
_json(
{
"record": companion,
"doc_version": 2,
"output_protocol_reference": companion_protocol_reference(
companion["binding"], json.loads(companion["raw"].lstrip("\ufeff"))
),
}
if companion
else None
).encode()
).hexdigest()
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
and old_doc.get("source_review_sha") == review_sha
and old_doc.get("companion_sha", hashlib.sha256(b"null").hexdigest())
== companion_sha
):
report["files"].append(
{
**record,
"result": "skipped",
"workflow_id": existing["id"],
"state": existing["import_state"],
"issues": json.loads(existing["import_issues"]),
}
)
continue
source = None
companion_audit = None
try:
text = raw.decode("utf-8-sig")
source = json.loads(text)
result = convert(source, info)
prompt, issues = result.prompt, result.issues
if companion:
prompt, companion_audit, issues = resolve_companion(
companion, relative, raw, source
)
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, review)
doc["companion_sha"] = companion_sha
if companion_audit:
doc["api_companion"] = companion_audit
if prompt:
api_doc = build_document(relative, prompt, prompt, None, [], None)
# Retain source inventory/reviews separately from supplied API evidence.
doc["params"].extend(
{
**p,
"node_id": "配套API:" + p["node_id"],
"api_node_id": p["node_id"],
"value_origin": "supplied_api_companion",
"default_source": "supplied_api_companion",
"effect": (
f"配套API节点{p['node_id']}("
f"{prompt[p['node_id']]['class_type']})的具名输入{p['field']};"
"现值由导出保留,含义/单位/范围仍待定义。"
),
}
for p in api_doc["params"]
)
doc["dependencies"]["models"] = sorted(
set(doc["dependencies"]["models"] + api_doc["dependencies"]["models"])
)
doc["dependencies"]["node_types"] = sorted(
set(
doc["dependencies"]["node_types"]
+ api_doc["dependencies"]["node_types"]
)
)
doc["steps"].insert(0, companion_audit["binding"]["instruction"])
reference = companion_audit.get("output_protocol_reference")
if reference:
doc["steps"].extend(
"公开固定版本参考(目标版本未核对):" + c["summary"]
for c in reference["contracts"].values()
)
doc["steps"].extend(
"版本差异:" + difference
for difference in reference["binding"].get("version_differences", [])
)
doc["snapshot_sha"] = snapshot_sha
doc["source_review_sha"] = review_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"] if r["result"] != "user_excluded"
)
)
report["source_total"] = len(report["files"])
report["excluded_total"] = sum(r["result"] == "user_excluded" for r in report["files"])
report["target_total"] = report["source_total"] - report["excluded_total"]
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}