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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
comfyui_meta.py
|
| 3 |
+
================
|
| 4 |
+
Extraction and readable structuring of the ComfyUI metadata embedded in
|
| 5 |
+
a PNG, MP3, FLAC or MP4/MOV file (workflow + prompt).
|
| 6 |
+
|
| 7 |
+
This module has no Gradio dependency: it can be tested standalone from
|
| 8 |
+
the command line:
|
| 9 |
+
|
| 10 |
+
python3 comfyui_meta.py my_file.png
|
| 11 |
+
|
| 12 |
+
General logic
|
| 13 |
+
-------------
|
| 14 |
+
ComfyUI embeds two JSON blobs in the files it produces:
|
| 15 |
+
|
| 16 |
+
- "prompt" : the "API" graph actually sent to the server for
|
| 17 |
+
generation. Values here are already resolved (e.g. a
|
| 18 |
+
dynamic prompt "{a|b}" already shows up picked as "a"
|
| 19 |
+
or "b").
|
| 20 |
+
- "workflow" : the "UI" graph as displayed in ComfyUI (positions,
|
| 21 |
+
titles, and most importantly "widgets_values" = what
|
| 22 |
+
the user typed/set on each node, BEFORE resolution ->
|
| 23 |
+
this is where the "{a|b|c}" template of a dynamic
|
| 24 |
+
prompt node is found).
|
| 25 |
+
|
| 26 |
+
We cross-reference the two to obtain, for each prompt actually used:
|
| 27 |
+
- the final (resolved) value that was really sent to the engine
|
| 28 |
+
- the original dynamic template, if a wildcard/dynamic prompt node
|
| 29 |
+
was detected upstream.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
from __future__ import annotations
|
| 33 |
+
|
| 34 |
+
import json
|
| 35 |
+
import re
|
| 36 |
+
import subprocess
|
| 37 |
+
from dataclasses import dataclass, field
|
| 38 |
+
from pathlib import Path
|
| 39 |
+
from typing import Any
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# ---------------------------------------------------------------------------
|
| 43 |
+
# 1. Raw extraction of the JSON blobs, depending on file type
|
| 44 |
+
# ---------------------------------------------------------------------------
|
| 45 |
+
|
| 46 |
+
class MetadataNotFound(Exception):
|
| 47 |
+
pass
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def extract_raw_metadata(path: str | Path) -> dict[str, Any]:
|
| 51 |
+
"""Returns {'prompt': <dict|None>, 'workflow': <dict|None>} for a
|
| 52 |
+
file. Raises MetadataNotFound if nothing could be extracted."""
|
| 53 |
+
path = Path(path)
|
| 54 |
+
suffix = path.suffix.lower()
|
| 55 |
+
|
| 56 |
+
if suffix in {".png", ".webp"}:
|
| 57 |
+
data = _extract_from_image(path)
|
| 58 |
+
elif suffix in {".mp3", ".flac", ".m4a", ".ogg"}:
|
| 59 |
+
data = _extract_from_audio(path)
|
| 60 |
+
elif suffix in {".mp4", ".mov", ".webm", ".mkv"}:
|
| 61 |
+
data = _extract_from_video(path)
|
| 62 |
+
else:
|
| 63 |
+
# last resort: try image, then audio
|
| 64 |
+
data = _extract_from_image(path) or _extract_from_audio(path)
|
| 65 |
+
|
| 66 |
+
if not data or not (data.get("prompt") or data.get("workflow")):
|
| 67 |
+
raise MetadataNotFound(
|
| 68 |
+
f"No ComfyUI metadata (prompt/workflow) found in {path.name}."
|
| 69 |
+
)
|
| 70 |
+
return data
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _try_json(text: Any) -> Any:
|
| 74 |
+
if not isinstance(text, str):
|
| 75 |
+
return None
|
| 76 |
+
text = text.strip()
|
| 77 |
+
if not text:
|
| 78 |
+
return None
|
| 79 |
+
try:
|
| 80 |
+
return json.loads(text)
|
| 81 |
+
except (json.JSONDecodeError, TypeError):
|
| 82 |
+
return None
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _extract_from_image(path: Path) -> dict[str, Any] | None:
|
| 86 |
+
try:
|
| 87 |
+
from PIL import Image
|
| 88 |
+
except ImportError:
|
| 89 |
+
return None
|
| 90 |
+
try:
|
| 91 |
+
img = Image.open(path)
|
| 92 |
+
except Exception:
|
| 93 |
+
return None
|
| 94 |
+
info = getattr(img, "info", {}) or {}
|
| 95 |
+
result = {"prompt": _try_json(info.get("prompt")), "workflow": _try_json(info.get("workflow"))}
|
| 96 |
+
|
| 97 |
+
if not result["prompt"] and not result["workflow"]:
|
| 98 |
+
# PNG stores "prompt"/"workflow" as plain text chunks, which PIL
|
| 99 |
+
# exposes directly through img.info (handled above). WEBP has no
|
| 100 |
+
# such text-chunk mechanism, so ComfyUI instead embeds the same
|
| 101 |
+
# JSON blobs inside EXIF tags, each value prefixed as
|
| 102 |
+
# "<label>:<json>" (e.g. "prompt:{...}"). Look there next.
|
| 103 |
+
result = _extract_from_exif(img, result)
|
| 104 |
+
|
| 105 |
+
return result
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _extract_from_exif(img, result: dict[str, Any]) -> dict[str, Any]:
|
| 109 |
+
exif = None
|
| 110 |
+
try:
|
| 111 |
+
exif = img.getexif()
|
| 112 |
+
except Exception:
|
| 113 |
+
exif = None
|
| 114 |
+
|
| 115 |
+
if not exif:
|
| 116 |
+
# Some Pillow/format combinations don't populate getexif()
|
| 117 |
+
# automatically even though raw EXIF bytes are present — parse
|
| 118 |
+
# those bytes directly as a fallback.
|
| 119 |
+
raw = (getattr(img, "info", {}) or {}).get("exif")
|
| 120 |
+
if raw:
|
| 121 |
+
try:
|
| 122 |
+
from PIL import Image as _Image
|
| 123 |
+
exif = _Image.Exif()
|
| 124 |
+
exif.load(raw)
|
| 125 |
+
except Exception:
|
| 126 |
+
exif = None
|
| 127 |
+
|
| 128 |
+
if not exif:
|
| 129 |
+
return result
|
| 130 |
+
|
| 131 |
+
for tag_id in exif:
|
| 132 |
+
try:
|
| 133 |
+
value = exif[tag_id]
|
| 134 |
+
except Exception:
|
| 135 |
+
continue
|
| 136 |
+
if isinstance(value, bytes):
|
| 137 |
+
try:
|
| 138 |
+
value = value.decode("utf-8", errors="ignore")
|
| 139 |
+
except Exception:
|
| 140 |
+
continue
|
| 141 |
+
if not isinstance(value, str):
|
| 142 |
+
continue
|
| 143 |
+
|
| 144 |
+
label, sep, json_part = value.partition(":")
|
| 145 |
+
candidate = json_part if sep else value
|
| 146 |
+
parsed = _try_json(candidate)
|
| 147 |
+
if parsed is None:
|
| 148 |
+
continue
|
| 149 |
+
|
| 150 |
+
label = label.strip().lower()
|
| 151 |
+
if "prompt" in label and not result.get("prompt"):
|
| 152 |
+
result["prompt"] = parsed
|
| 153 |
+
elif "workflow" in label and not result.get("workflow"):
|
| 154 |
+
result["workflow"] = parsed
|
| 155 |
+
elif not result.get("prompt") and not result.get("workflow") and isinstance(parsed, dict):
|
| 156 |
+
# Unlabeled (or differently labeled) but still a JSON object —
|
| 157 |
+
# guess which one it is from its shape: a "workflow" graph has
|
| 158 |
+
# top-level "nodes"/"links", the "prompt" API graph doesn't.
|
| 159 |
+
if "nodes" in parsed and "links" in parsed:
|
| 160 |
+
result["workflow"] = parsed
|
| 161 |
+
else:
|
| 162 |
+
result["prompt"] = parsed
|
| 163 |
+
|
| 164 |
+
return result
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def _extract_from_audio(path: Path) -> dict[str, Any] | None:
|
| 168 |
+
try:
|
| 169 |
+
import mutagen
|
| 170 |
+
except ImportError:
|
| 171 |
+
return None
|
| 172 |
+
|
| 173 |
+
result: dict[str, Any] = {"prompt": None, "workflow": None}
|
| 174 |
+
try:
|
| 175 |
+
f = mutagen.File(path)
|
| 176 |
+
except Exception:
|
| 177 |
+
f = None
|
| 178 |
+
|
| 179 |
+
if f is None:
|
| 180 |
+
return result
|
| 181 |
+
|
| 182 |
+
tags = getattr(f, "tags", None)
|
| 183 |
+
if tags is None:
|
| 184 |
+
return result
|
| 185 |
+
|
| 186 |
+
# MP3 / ID3 (TXXX:prompt, TXXX:workflow)
|
| 187 |
+
try:
|
| 188 |
+
from mutagen.id3 import ID3
|
| 189 |
+
if isinstance(tags, ID3) or path.suffix.lower() == ".mp3":
|
| 190 |
+
for frame_key in list(tags.keys()):
|
| 191 |
+
if frame_key.upper().startswith("TXXX:"):
|
| 192 |
+
label = frame_key.split(":", 1)[1].strip().lower()
|
| 193 |
+
frame = tags[frame_key]
|
| 194 |
+
value = frame.text[0] if getattr(frame, "text", None) else None
|
| 195 |
+
parsed = _try_json(value)
|
| 196 |
+
if parsed is None:
|
| 197 |
+
continue
|
| 198 |
+
if "prompt" in label:
|
| 199 |
+
result["prompt"] = parsed
|
| 200 |
+
elif "workflow" in label:
|
| 201 |
+
result["workflow"] = parsed
|
| 202 |
+
if result["prompt"] or result["workflow"]:
|
| 203 |
+
return result
|
| 204 |
+
except ImportError:
|
| 205 |
+
pass
|
| 206 |
+
|
| 207 |
+
# Vorbis comments (FLAC/OGG) or generic "dict-like" tags (M4A, etc.)
|
| 208 |
+
try:
|
| 209 |
+
items = tags.items() if hasattr(tags, "items") else []
|
| 210 |
+
except Exception:
|
| 211 |
+
items = []
|
| 212 |
+
for key, value in items:
|
| 213 |
+
key_l = str(key).lower()
|
| 214 |
+
raw = value[0] if isinstance(value, (list, tuple)) and value else value
|
| 215 |
+
parsed = _try_json(raw)
|
| 216 |
+
if parsed is None:
|
| 217 |
+
continue
|
| 218 |
+
if "prompt" in key_l and result["prompt"] is None:
|
| 219 |
+
result["prompt"] = parsed
|
| 220 |
+
elif "workflow" in key_l and result["workflow"] is None:
|
| 221 |
+
result["workflow"] = parsed
|
| 222 |
+
|
| 223 |
+
return result
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def _extract_from_video(path: Path) -> dict[str, Any] | None:
|
| 227 |
+
"""Best effort: clips exported by VideoHelperSuite generally embed
|
| 228 |
+
the workflow/prompt in container tags (comment, description...).
|
| 229 |
+
We query ffprobe if available."""
|
| 230 |
+
result: dict[str, Any] = {"prompt": None, "workflow": None}
|
| 231 |
+
try:
|
| 232 |
+
proc = subprocess.run(
|
| 233 |
+
[
|
| 234 |
+
"ffprobe", "-v", "quiet", "-print_format", "json",
|
| 235 |
+
"-show_entries", "format_tags", str(path),
|
| 236 |
+
],
|
| 237 |
+
capture_output=True, text=True, timeout=20,
|
| 238 |
+
)
|
| 239 |
+
info = json.loads(proc.stdout or "{}")
|
| 240 |
+
tags = info.get("format", {}).get("tags", {})
|
| 241 |
+
except Exception:
|
| 242 |
+
tags = {}
|
| 243 |
+
|
| 244 |
+
for key, value in tags.items():
|
| 245 |
+
key_l = key.lower()
|
| 246 |
+
parsed = _try_json(value)
|
| 247 |
+
if parsed is None:
|
| 248 |
+
continue
|
| 249 |
+
if "prompt" in key_l and result["prompt"] is None:
|
| 250 |
+
result["prompt"] = parsed
|
| 251 |
+
elif "workflow" in key_l and result["workflow"] is None:
|
| 252 |
+
result["workflow"] = parsed
|
| 253 |
+
|
| 254 |
+
# If nothing found, some exports put everything (prompt+workflow) in
|
| 255 |
+
# a single "comment" field as one object {"prompt":..,"workflow":..}
|
| 256 |
+
if not result["prompt"] and not result["workflow"]:
|
| 257 |
+
for key in ("comment", "description"):
|
| 258 |
+
parsed = _try_json(tags.get(key))
|
| 259 |
+
if isinstance(parsed, dict) and ("prompt" in parsed or "workflow" in parsed):
|
| 260 |
+
result["prompt"] = parsed.get("prompt")
|
| 261 |
+
result["workflow"] = parsed.get("workflow")
|
| 262 |
+
break
|
| 263 |
+
|
| 264 |
+
return result
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
# ---------------------------------------------------------------------------
|
| 268 |
+
# 2. Data model for the structured view
|
| 269 |
+
# ---------------------------------------------------------------------------
|
| 270 |
+
|
| 271 |
+
@dataclass
|
| 272 |
+
class ModelEntry:
|
| 273 |
+
node: str
|
| 274 |
+
kind: str # "Checkpoint", "UNET", "VAE", "CLIP", "LoRA"
|
| 275 |
+
name: str
|
| 276 |
+
detail: str = ""
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
@dataclass
|
| 280 |
+
class ParamEntry:
|
| 281 |
+
node: str
|
| 282 |
+
param: str
|
| 283 |
+
value: str
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
@dataclass
|
| 287 |
+
class PromptEntry:
|
| 288 |
+
node: str
|
| 289 |
+
role: str # e.g. "Positive", "Tags", "Lyrics"
|
| 290 |
+
resolved: str
|
| 291 |
+
template: str | None = None # raw { | } template, if found upstream
|
| 292 |
+
source_node: str | None = None
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
@dataclass
|
| 296 |
+
class StructuredView:
|
| 297 |
+
models: list[ModelEntry] = field(default_factory=list)
|
| 298 |
+
params: list[ParamEntry] = field(default_factory=list)
|
| 299 |
+
prompts: list[PromptEntry] = field(default_factory=list)
|
| 300 |
+
warnings: list[str] = field(default_factory=list)
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
# ---------------------------------------------------------------------------
|
| 304 |
+
# 3. Categorization
|
| 305 |
+
# ---------------------------------------------------------------------------
|
| 306 |
+
|
| 307 |
+
_MODEL_CLASS_RE = re.compile(
|
| 308 |
+
r"checkpoint|unetloader|vaeloader|cliploader|controlnet|ipadapter", re.I
|
| 309 |
+
)
|
| 310 |
+
_LORA_RE = re.compile(r"lora", re.I)
|
| 311 |
+
_PARAM_CLASS_RE = re.compile(
|
| 312 |
+
r"ksampler|samplercustom|emptylatent|emptyacestep|modelsampling|latentaudio",
|
| 313 |
+
re.I,
|
| 314 |
+
)
|
| 315 |
+
_ENCODE_CLASS_RE = re.compile(r"textencode|cliptextencode", re.I)
|
| 316 |
+
_DYNAMIC_CLASS_RE = re.compile(r"dynamic.?prompt|wildcard", re.I)
|
| 317 |
+
_BRACE_PATTERN_RE = re.compile(r"\{[^{}]*\|[^{}]*\}")
|
| 318 |
+
|
| 319 |
+
_TEXT_KEY_PRIORITY = ["Text", "text", "string", "STRING", "value",
|
| 320 |
+
"wildcard_text", "populated_text"]
|
| 321 |
+
|
| 322 |
+
_ROLE_LABELS = {
|
| 323 |
+
"text": "Prompt",
|
| 324 |
+
"positive": "Positive",
|
| 325 |
+
"negative": "Negative",
|
| 326 |
+
"tags": "Tags (style)",
|
| 327 |
+
"lyrics": "Lyrics",
|
| 328 |
+
"text_g": "Prompt (global)",
|
| 329 |
+
"text_l": "Prompt (local)",
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def _node_label(node_id: str, workflow_by_id: dict[str, dict], class_type: str) -> str:
|
| 334 |
+
wf_node = workflow_by_id.get(node_id)
|
| 335 |
+
title = wf_node.get("title") if wf_node else None
|
| 336 |
+
if title:
|
| 337 |
+
return f"{title} (#{node_id})"
|
| 338 |
+
return f"{class_type} (#{node_id})"
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def _flatten_strings(value: Any) -> list[str]:
|
| 342 |
+
"""Some nodes (e.g. ShowText|pysssss) store their widget as nested
|
| 343 |
+
lists (value history). We flatten to recover all non-empty strings,
|
| 344 |
+
in order."""
|
| 345 |
+
out: list[str] = []
|
| 346 |
+
if isinstance(value, str):
|
| 347 |
+
if value.strip():
|
| 348 |
+
out.append(value)
|
| 349 |
+
elif isinstance(value, (list, tuple)):
|
| 350 |
+
for item in value:
|
| 351 |
+
out.extend(_flatten_strings(item))
|
| 352 |
+
return out
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def _first_string_widget(wf_node: dict | None) -> str | None:
|
| 356 |
+
if not wf_node:
|
| 357 |
+
return None
|
| 358 |
+
strings = _flatten_strings(wf_node.get("widgets_values"))
|
| 359 |
+
if not strings:
|
| 360 |
+
return None
|
| 361 |
+
# prefer the longest string (usually the real prompt, rather than a
|
| 362 |
+
# short flag/mode string like "enable" or "randomize")
|
| 363 |
+
return max(strings, key=len)
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def _resolve_link_text(prompt_graph: dict, workflow_by_id: dict, link: list) -> tuple[str | None, str | None]:
|
| 367 |
+
"""Resolves the final value of a [node_id, output_index] link
|
| 368 |
+
pointing at a text "source" node. Returns (value, source_node_id)."""
|
| 369 |
+
src_id = str(link[0])
|
| 370 |
+
src_node = prompt_graph.get(src_id, {})
|
| 371 |
+
inputs = src_node.get("inputs", {})
|
| 372 |
+
for key in _TEXT_KEY_PRIORITY:
|
| 373 |
+
if key in inputs and isinstance(inputs[key], str) and inputs[key].strip():
|
| 374 |
+
return inputs[key], src_id
|
| 375 |
+
# fallback: last displayed/typed value on the source node (widget)
|
| 376 |
+
fallback = _first_string_widget(workflow_by_id.get(src_id))
|
| 377 |
+
if fallback:
|
| 378 |
+
return fallback, src_id
|
| 379 |
+
return None, src_id
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def build_structured_view(raw: dict[str, Any]) -> StructuredView:
|
| 383 |
+
view = StructuredView()
|
| 384 |
+
prompt_graph: dict = raw.get("prompt") or {}
|
| 385 |
+
workflow: dict = raw.get("workflow") or {}
|
| 386 |
+
workflow_nodes = workflow.get("nodes") or []
|
| 387 |
+
workflow_by_id = {str(n.get("id")): n for n in workflow_nodes}
|
| 388 |
+
|
| 389 |
+
if not prompt_graph:
|
| 390 |
+
view.warnings.append(
|
| 391 |
+
"No 'prompt' (API) graph found — only 'workflow' info "
|
| 392 |
+
"(if present) is shown."
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
# --- Model & LoRAs ---------------------------------------------
|
| 396 |
+
for node_id, node in prompt_graph.items():
|
| 397 |
+
class_type = node.get("class_type", "")
|
| 398 |
+
inputs = node.get("inputs", {})
|
| 399 |
+
label = _node_label(node_id, workflow_by_id, class_type)
|
| 400 |
+
|
| 401 |
+
if _MODEL_CLASS_RE.search(class_type):
|
| 402 |
+
for key in ("ckpt_name", "unet_name", "vae_name",
|
| 403 |
+
"clip_name", "clip_name1", "clip_name2", "clip_name3",
|
| 404 |
+
"control_net_name"):
|
| 405 |
+
if key in inputs and isinstance(inputs[key], str):
|
| 406 |
+
kind = {
|
| 407 |
+
"ckpt_name": "Checkpoint",
|
| 408 |
+
"unet_name": "UNET",
|
| 409 |
+
"vae_name": "VAE",
|
| 410 |
+
"control_net_name": "ControlNet",
|
| 411 |
+
}.get(key, "CLIP")
|
| 412 |
+
view.models.append(ModelEntry(node=label, kind=kind, name=inputs[key]))
|
| 413 |
+
|
| 414 |
+
if _LORA_RE.search(class_type):
|
| 415 |
+
# simple case: lora_name + strength(s)
|
| 416 |
+
if "lora_name" in inputs:
|
| 417 |
+
strength = inputs.get("strength_model", inputs.get("strength", ""))
|
| 418 |
+
view.models.append(ModelEntry(
|
| 419 |
+
node=label, kind="LoRA", name=inputs["lora_name"],
|
| 420 |
+
detail=f"weight {strength}" if strength != "" else "",
|
| 421 |
+
))
|
| 422 |
+
# "Power Lora Loader" case / lists of {on, lora, strength} dicts
|
| 423 |
+
for key, val in inputs.items():
|
| 424 |
+
if isinstance(val, dict) and "lora" in val:
|
| 425 |
+
if val.get("on", True) is False:
|
| 426 |
+
continue
|
| 427 |
+
strength = val.get("strength", val.get("strength_model", ""))
|
| 428 |
+
view.models.append(ModelEntry(
|
| 429 |
+
node=label, kind="LoRA", name=val["lora"],
|
| 430 |
+
detail=f"weight {strength}" if strength != "" else "",
|
| 431 |
+
))
|
| 432 |
+
|
| 433 |
+
# --- Main parameters --------------------------------------------
|
| 434 |
+
PARAM_KEYS = ["seed", "steps", "cfg", "sampler_name", "scheduler", "denoise",
|
| 435 |
+
"width", "height", "batch_size", "seconds", "duration",
|
| 436 |
+
"shift", "bpm", "timesignature", "language", "keyscale"]
|
| 437 |
+
for node_id, node in prompt_graph.items():
|
| 438 |
+
class_type = node.get("class_type", "")
|
| 439 |
+
inputs = node.get("inputs", {})
|
| 440 |
+
if not (_PARAM_CLASS_RE.search(class_type) or _ENCODE_CLASS_RE.search(class_type)):
|
| 441 |
+
continue
|
| 442 |
+
label = _node_label(node_id, workflow_by_id, class_type)
|
| 443 |
+
for key in PARAM_KEYS:
|
| 444 |
+
if key in inputs and not isinstance(inputs[key], (list, dict)):
|
| 445 |
+
view.params.append(ParamEntry(node=label, param=key, value=str(inputs[key])))
|
| 446 |
+
|
| 447 |
+
# --- Prompts (final resolved + dynamic template) ---------------------
|
| 448 |
+
for node_id, node in prompt_graph.items():
|
| 449 |
+
class_type = node.get("class_type", "")
|
| 450 |
+
if not _ENCODE_CLASS_RE.search(class_type):
|
| 451 |
+
continue
|
| 452 |
+
inputs = node.get("inputs", {})
|
| 453 |
+
label = _node_label(node_id, workflow_by_id, class_type)
|
| 454 |
+
for key, role_label in _ROLE_LABELS.items():
|
| 455 |
+
if key not in inputs:
|
| 456 |
+
continue
|
| 457 |
+
val = inputs[key]
|
| 458 |
+
template = None
|
| 459 |
+
source_node = None
|
| 460 |
+
if isinstance(val, str):
|
| 461 |
+
resolved = val
|
| 462 |
+
elif isinstance(val, list):
|
| 463 |
+
resolved, source_node = _resolve_link_text(prompt_graph, workflow_by_id, val)
|
| 464 |
+
resolved = resolved or "(value computed at generation time, not stored in the file)"
|
| 465 |
+
else:
|
| 466 |
+
continue
|
| 467 |
+
|
| 468 |
+
# Is the source node a (or does it contain a) dynamic prompt / wildcard?
|
| 469 |
+
check_id = source_node or node_id
|
| 470 |
+
src_prompt_node = prompt_graph.get(check_id, {})
|
| 471 |
+
src_class = src_prompt_node.get("class_type", "")
|
| 472 |
+
raw_widget = _first_string_widget(workflow_by_id.get(check_id))
|
| 473 |
+
if (_DYNAMIC_CLASS_RE.search(src_class) or (raw_widget and _BRACE_PATTERN_RE.search(raw_widget))):
|
| 474 |
+
if raw_widget and _BRACE_PATTERN_RE.search(raw_widget):
|
| 475 |
+
template = raw_widget
|
| 476 |
+
|
| 477 |
+
view.prompts.append(PromptEntry(
|
| 478 |
+
node=label, role=role_label, resolved=resolved,
|
| 479 |
+
template=template, source_node=source_node,
|
| 480 |
+
))
|
| 481 |
+
|
| 482 |
+
# --- "Orphan" dynamic prompt nodes (detected but not attached) --
|
| 483 |
+
linked_sources = {p.source_node for p in view.prompts if p.source_node}
|
| 484 |
+
for node_id, node in prompt_graph.items():
|
| 485 |
+
class_type = node.get("class_type", "")
|
| 486 |
+
if node_id in linked_sources:
|
| 487 |
+
continue
|
| 488 |
+
if not _DYNAMIC_CLASS_RE.search(class_type):
|
| 489 |
+
raw_widget = _first_string_widget(workflow_by_id.get(node_id))
|
| 490 |
+
if not (raw_widget and _BRACE_PATTERN_RE.search(raw_widget)):
|
| 491 |
+
continue
|
| 492 |
+
label = _node_label(node_id, workflow_by_id, class_type)
|
| 493 |
+
template = _first_string_widget(workflow_by_id.get(node_id))
|
| 494 |
+
inputs = node.get("inputs", {})
|
| 495 |
+
resolved = None
|
| 496 |
+
for key in _TEXT_KEY_PRIORITY:
|
| 497 |
+
if key in inputs and isinstance(inputs[key], str):
|
| 498 |
+
resolved = inputs[key]
|
| 499 |
+
break
|
| 500 |
+
if template and _BRACE_PATTERN_RE.search(template):
|
| 501 |
+
view.prompts.append(PromptEntry(
|
| 502 |
+
node=label, role="Dynamic prompt (unlinked)",
|
| 503 |
+
resolved=resolved or "(not found)", template=template,
|
| 504 |
+
))
|
| 505 |
+
|
| 506 |
+
# --- Deduplicate ------------------------------------------------
|
| 507 |
+
# ComfyUI graphs commonly feed the exact same text into two parallel
|
| 508 |
+
# branches (e.g. a positive pass and a separate "zeroed" / negative
|
| 509 |
+
# pass both reading the same tags/lyrics node). That produces two
|
| 510 |
+
# PromptEntry objects with identical content under the same role —
|
| 511 |
+
# collapse those so a file with several *distinct* dynamic prompts
|
| 512 |
+
# (e.g. one for music tags, one for lyrics, in Ace Step) shows one
|
| 513 |
+
# card per distinct prompt instead of duplicates.
|
| 514 |
+
seen: set[tuple[str, str, str | None]] = set()
|
| 515 |
+
deduped: list[PromptEntry] = []
|
| 516 |
+
for p in view.prompts:
|
| 517 |
+
signature = (p.role, p.resolved, p.template)
|
| 518 |
+
if signature in seen:
|
| 519 |
+
continue
|
| 520 |
+
seen.add(signature)
|
| 521 |
+
deduped.append(p)
|
| 522 |
+
view.prompts = deduped
|
| 523 |
+
|
| 524 |
+
return view
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
def analyze(path: str | Path) -> StructuredView:
|
| 528 |
+
raw = extract_raw_metadata(path)
|
| 529 |
+
return build_structured_view(raw)
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
if __name__ == "__main__":
|
| 533 |
+
import sys
|
| 534 |
+
|
| 535 |
+
if len(sys.argv) != 2:
|
| 536 |
+
print("Usage: python3 comfyui_meta.py <file>")
|
| 537 |
+
raise SystemExit(1)
|
| 538 |
+
|
| 539 |
+
view = analyze(sys.argv[1])
|
| 540 |
+
|
| 541 |
+
print("\n=== MODEL & LORAS ===")
|
| 542 |
+
for m in view.models:
|
| 543 |
+
print(f"[{m.kind}] {m.name} ({m.node}) {m.detail}")
|
| 544 |
+
|
| 545 |
+
print("\n=== MAIN PARAMETERS ===")
|
| 546 |
+
for p in view.params:
|
| 547 |
+
print(f"{p.node} :: {p.param} = {p.value}")
|
| 548 |
+
|
| 549 |
+
print("\n=== PROMPT & DYNAMIC PROMPT ===")
|
| 550 |
+
for pr in view.prompts:
|
| 551 |
+
print(f"\n-- {pr.node} :: {pr.role} --")
|
| 552 |
+
print("Resolved:", pr.resolved[:300])
|
| 553 |
+
if pr.template:
|
| 554 |
+
print("Dynamic template:", pr.template[:300])
|
| 555 |
+
|
| 556 |
+
if view.warnings:
|
| 557 |
+
print("\n=== WARNINGS ===")
|
| 558 |
+
for w in view.warnings:
|
| 559 |
+
print("-", w)
|