This commit is contained in:
2026-11-13 00:57:30 +01:00
parent e7e3bcbbcb
commit 877f851160
7 changed files with 348 additions and 0 deletions

187
comfy_check.py Normal file
View File

@@ -0,0 +1,187 @@
"""ComfyUI check: inventory, workflow validation, recent errors - short output for the
comfyui-workflow-expert skill (so nothing has to be read by hand).
py -3.12 comfy_check.py inventory: server/GPU, custom nodes, models, ComfyGen workflows
py -3.12 comfy_check.py --full same, every model file name
py -3.12 comfy_check.py <workflow.json> validate: format, missing nodes, missing/unknown models,
broken links, placeholders, sampler/size summary
py -3.12 comfy_check.py --log [N] last errors from ComfyUI's log (default 40 lines context)
Workflow files may be ComfyGen templates ({{SEED}} etc., also unquoted) - they are filled with dummies
before parsing. With the server running, node types and model names are checked against /object_info
(exactly what causes "value not in list" / "node does not exist" errors).
"""
import json
import os
import re
import sys
import urllib.request
COMFY = r"D:\ComfyUI\ComfyUI"
MODELS = os.path.join(COMFY, "models")
HOST = "http://127.0.0.1:8188"
HERE = os.path.dirname(os.path.abspath(__file__))
MODEL_EXT = (".safetensors", ".ckpt", ".pt", ".pth", ".gguf", ".bin", ".onnx", ".sft")
def get(path, timeout=3):
try:
with urllib.request.urlopen(HOST + path, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8"))
except Exception:
return None
def model_index():
idx = {}
if not os.path.isdir(MODELS):
return idx
for folder in os.listdir(MODELS):
base = os.path.join(MODELS, folder)
if not os.path.isdir(base):
continue
for dp, _, fs in os.walk(base):
for f in fs:
if f.lower().endswith(MODEL_EXT):
rel = os.path.relpath(os.path.join(dp, f), base)
idx.setdefault(folder, []).append(rel)
return idx
def inventory(full):
out = []
st = get("/system_stats")
if st:
dev = st.get("devices", [{}])[0]
out.append(f"Server: läuft, ComfyUI {st.get('system', {}).get('comfyui_version', '?')}, "
f"{re.sub(r'^cuda:\d+\s*|\s*:.*$', '', dev.get('name', '?'))} "
f"VRAM {dev.get('vram_total', 0) / 2**30:.0f} GB (frei {dev.get('vram_free', 0) / 2**30:.1f} GB)")
else:
out.append("Server: aus (start: D:\\ComfyUI → .venv\\Scripts\\python.exe -s ComfyUI\\main.py)")
cn = os.path.join(COMFY, "custom_nodes")
packs = sorted(d for d in os.listdir(cn) if os.path.isdir(os.path.join(cn, d)) and not d.startswith((".", "_")) and d != "__pycache__") if os.path.isdir(cn) else []
out.append(f"Custom-Node-Pakete ({len(packs)}): " + ", ".join(packs))
idx = model_index()
out.append("Modelle:")
for folder in sorted(idx, key=str.lower):
names = sorted(idx[folder], key=str.lower)
shown = names if full or len(names) <= 6 else names[:6] + [f"+{len(names) - 6}"]
out.append(f" {folder} ({len(names)}): " + ", ".join(shown))
wf = os.path.join(HERE, "workflows")
if os.path.isdir(wf):
rows = []
for f in sorted(os.listdir(wf)):
if f.endswith(".json"):
fmt, data, _ = load_workflow(os.path.join(wf, f))
rows.append(f"{f} [{fmt}]")
out.append("ComfyGen-Workflows: " + " · ".join(rows))
print("\n".join(out))
def load_workflow(path):
text = open(path, encoding="utf-8-sig").read()
placeholders = sorted(set(re.findall(r"\{\{([A-Z0-9_]+)\}\}", text)))
# unquoted placeholders (numbers) -> 0, quoted ones stay strings
filled = re.sub(r'(?<!")\{\{[A-Z0-9_]+\}\}(?!")', "0", text)
try:
data = json.loads(filled)
except json.JSONDecodeError as e:
return f"kaputtes JSON ({e.msg}, Zeile {e.lineno})", None, placeholders
if isinstance(data, dict) and "nodes" in data and "links" in data:
return "UI", data, placeholders
if isinstance(data, dict) and all(isinstance(v, dict) and "class_type" in v for v in data.values()):
return "API", data, placeholders
return "unbekannt", data, placeholders
def options_for(info, ctype, inp):
spec = (info or {}).get(ctype, {}).get("input", {})
for group in ("required", "optional"):
v = spec.get(group, {}).get(inp)
if v and isinstance(v[0], list):
return v[0]
if v and v[0] == "COMBO" and len(v) > 1 and isinstance(v[1], dict):
return v[1].get("options")
return None
def validate(path):
fmt, data, ph = load_workflow(path)
out = [f"{os.path.basename(path)}: Format {fmt}" + (f", Platzhalter: {', '.join(ph)}" if ph else "")]
if data is None or fmt == "unbekannt":
print("\n".join(out)); return
info = get("/object_info", timeout=15)
if not info:
out.append("(Server aus – Node-Typen und Modellnamen nur gegen Dateien geprüft)")
idx = model_index()
all_models = {os.path.basename(m).lower() for ms in idx.values() for m in ms}
problems, summary = [], []
if fmt == "UI":
nodes = [(str(n.get("id")), n.get("type"), n.get("widgets_values") or []) for n in data["nodes"]]
out.append(f"{len(nodes)} Nodes, {len(data['links'])} Verbindungen – für ComfyGen/API: im Editor „Export (API)“ speichern")
for nid, ctype, widgets in nodes:
if ctype in ("Note", "MarkdownNote", "Reroute", "PrimitiveNode"):
continue
if info and ctype not in info:
problems.append(f"Node {nid} „{ctype}“ unbekannt (Custom Node fehlt/deaktiviert)")
for w in widgets if isinstance(widgets, list) else []:
if isinstance(w, str) and w.lower().endswith(MODEL_EXT) and "{{" not in w and os.path.basename(w).lower() not in all_models:
problems.append(f"Node {nid} ({ctype}): Modell fehlt: {w}")
else:
ids = set(data)
for nid, n in data.items():
ctype, inputs = n["class_type"], n.get("inputs", {})
if info and ctype not in info:
problems.append(f"Node {nid} „{ctype}“ unbekannt (Custom Node fehlt/deaktiviert)")
for k, v in inputs.items():
if isinstance(v, list) and len(v) == 2 and isinstance(v[1], int) and isinstance(v[0], str):
if v[0] not in ids:
problems.append(f"Node {nid}.{k} zeigt auf fehlenden Node {v[0]}")
continue
if isinstance(v, str) and "{{" not in v:
opts = options_for(info, ctype, k) if info else None
if opts is not None and v not in opts and (v.lower().endswith(MODEL_EXT) or k.endswith("_name") or k in ("model", "ckpt_name")):
problems.append(f"Node {nid} ({ctype}).{k} = „{v}“ nicht in der Liste des Servers")
elif opts is None and v.lower().endswith(MODEL_EXT) and os.path.basename(v).lower() not in all_models:
problems.append(f"Node {nid} ({ctype}).{k}: Modell fehlt: {v}")
if "sampler" in ctype.lower() or ctype in ("KSampler", "KSamplerAdvanced"):
keys = ("steps", "cfg", "sampler_name", "scheduler", "denoise")
vals = ", ".join(f"{k}={inputs[k]}" for k in keys if k in inputs and not isinstance(inputs[k], list))
if vals:
summary.append(f"{ctype}#{nid}: {vals}")
if ctype in ("Flux2Scheduler", "BasicScheduler", "CFGGuider", "ModelSamplingAuraFlow", "ModelSamplingFlux"):
vals = ", ".join(f"{k}={v}" for k, v in inputs.items() if not isinstance(v, list) and k in ("steps", "cfg", "shift", "scheduler", "denoise"))
if vals:
summary.append(f"{ctype}#{nid}: {vals}")
if "Latent" in ctype and "width" in inputs:
summary.append(f"{ctype}#{nid}: {inputs.get('width')}x{inputs.get('height')} batch {inputs.get('batch_size', 1)}")
if ctype in ("SaveImage", "SaveAudio", "SaveAudioMP3", "SaveGLB", "VHS_VideoCombine", "SaveVideo", "SaveAnimatedWEBP"):
summary.append(f"{ctype}#{nid}: prefix {inputs.get('filename_prefix', '?')}")
out.append(f"{len(data)} Nodes: " + ", ".join(sorted({n['class_type'] for n in data.values()})))
out += ["- " + s for s in summary]
out += ["PROBLEM " + p for p in problems] or ["Keine Probleme gefunden."]
print("\n".join(out))
def show_log(n):
log = os.path.join(COMFY, "user", "comfyui.log")
if not os.path.exists(log):
print("kein Log:", log); return
lines = open(log, encoding="utf-8", errors="replace").read().splitlines()
hits = [i for i, l in enumerate(lines) if re.search(r"Traceback|Error|Exception|out of memory|not in list|does not exist|Prompt outputs failed", l)]
if not hits:
print(f"Keine Fehler in {log} ({len(lines)} Zeilen)."); return
start = max(0, hits[-1] - n // 2)
print(f"{len(hits)} Fehlerzeilen in {log}; letzte Stelle (Zeile {hits[-1] + 1}):")
print("\n".join(lines[start:hits[-1] + n // 2]))
if __name__ == "__main__":
a = sys.argv[1:]
if not a or a == ["--full"]:
inventory("--full" in a)
elif a[0] == "--log":
show_log(int(a[1]) if len(a) > 1 else 40)
else:
validate(a[0])