File size: 13,970 Bytes
e609fe4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
#!/usr/bin/env python3
"""Minimal ComfyUI client: upload an image, queue a workflow, stream progress.

Talks to ComfyUI's own HTTP + WebSocket API. Designed to run on the same pod as
ComfyUI so the host stays 127.0.0.1 and nothing is exposed publicly.

    from comfy_client import ComfyClient

    c = ComfyClient()
    name = c.upload_image(open("face.jpg", "rb").read(), "face.jpg")
    wf = c.load_workflow("workflow_api.json")
    c.apply({"image": name, "prompt": "red raincoat", "aspect": "3:4 (Portrait Standard)"}, wf)
    for img in c.run(wf, on_progress=lambda d, t: print(f"{d}/{t}")):
        open(img.filename, "wb").write(img.data)

Requires: requests, websocket-client
"""
from __future__ import annotations

import json
import random
import uuid
from dataclasses import dataclass
from typing import Callable, Iterator

import requests
import websocket


@dataclass
class ResultImage:
    filename: str
    subfolder: str
    data: bytes


class ComfyError(RuntimeError):
    pass


class ComfyClient:
    LORA_EXTS = (".safetensors", ".ckpt", ".pt", ".bin", ".sft")

    def __init__(self, host: str = "127.0.0.1:8188",
                 map_path: str = "workflow_map.json",
                 timeout: int = 900,
                 lora_dirs: list[str] | None = None):
        # Directories scanned directly from disk, in addition to whatever
        # /object_info reports. ComfyUI caches its filename list and there is
        # no core endpoint to invalidate it, so a freshly dropped LoRA can stay
        # invisible until restart. Reading the folder ourselves sidesteps that.
        self.lora_dirs = [d for d in (lora_dirs or []) if d]
        self.host = host
        self.base = f"http://{host}"
        self.timeout = timeout
        self.client_id = str(uuid.uuid4())
        self.session = requests.Session()
        with open(map_path) as fh:
            self.map = json.load(fh)

    # ------------------------------------------------------------- workflow
    @staticmethod
    def load_workflow(path: str) -> dict:
        with open(path) as fh:
            wf = json.load(fh)
        if "nodes" in wf and "links" in wf:
            raise ComfyError("UI-format workflow; export with Export (API)")
        return wf

    def apply(self, params: dict, wf: dict, strict: bool = True) -> list[str]:
        """Set job parameters using the node map. Mutates wf in place.

        Returns the keys that were skipped. With strict=False an unmapped or
        unreachable key is dropped rather than failing the job — one missing
        map entry shouldn't cost you the whole generation.
        """
        skipped = []
        for key, value in params.items():
            target = self.map.get(key)
            if not target or "input" not in target:
                if strict:
                    raise ComfyError(f"no mapping for '{key}'")
                skipped.append(f"{key} (not in map)")
                continue
            nid, field = str(target["node"]), target["input"]
            if nid not in wf:
                if strict:
                    raise ComfyError(f"'{key}' maps to node {nid}, "
                                     f"not in workflow")
                skipped.append(f"{key} (node {nid} absent)")
                continue
            if field not in wf[nid].get("inputs", {}):
                if strict:
                    raise ComfyError(f"'{key}' maps to {nid}.{field}, "
                                     f"which that node does not have")
                skipped.append(f"{key} ({nid} has no '{field}')")
                continue
            wf[nid]["inputs"][field] = value
        return skipped

    def diagnose(self, wf: dict) -> list[str]:
        """One line per mapped key saying whether it resolves in this workflow."""
        out = []
        for key, target in sorted(self.map.items()):
            if key.startswith("_") and "input" not in (target or {}):
                nid = str((target or {}).get("node", ""))
                out.append(f"{'ok ' if nid in wf else 'BAD'} {key} -> node {nid}")
                continue
            if not isinstance(target, dict) or "input" not in target:
                continue
            nid, field = str(target["node"]), target["input"]
            if nid not in wf:
                out.append(f"BAD {key} -> node {nid} not in workflow")
            elif field not in wf[nid].get("inputs", {}):
                have = [k for k, v in wf[nid]["inputs"].items()
                        if not isinstance(v, list)]
                out.append(f"BAD {key} -> {nid}.{field} missing; has {have}")
            else:
                out.append(f"ok  {key} -> {nid}.{field}")
        missing = [k for k in ("prompt", "image", "seed") if k not in self.map]
        for k in missing:
            out.append(f"BAD {k} has no map entry at all")
        return out

    def set_loras(self, loras: list[dict], wf: dict) -> dict:
        """Rewrite the rgthree Power Lora Loader's dynamic lora_N slots."""
        target = self.map.get("_power_lora_loader")
        if not target:
            raise ComfyError("map has no _power_lora_loader entry")
        node = wf[str(target["node"])]["inputs"]
        for key in [k for k in node if k.startswith("lora_")]:
            del node[key]
        for i, entry in enumerate(loras, start=1):
            slot = {"on": entry.get("on", True), "lora": entry["lora"],
                    "strength": entry.get("strength", 1.0)}
            if entry.get("strengthTwo") is not None:
                slot["strengthTwo"] = entry["strengthTwo"]
            node[f"lora_{i}"] = slot
        return wf

    def randomize_seed(self, wf: dict) -> int:
        seed = random.randint(0, 2 ** 53 - 1)
        self.apply({"seed": seed}, wf)
        return seed

    # --------------------------------------------------------------- assets
    @staticmethod
    def _combo_options(entry) -> list[str] | None:
        """Pull the option list out of an input spec, whichever shape it is.

        Older ComfyUI inlines the options:   [["a", "b"], {...}]
        Newer ComfyUI names the type:        ["COMBO", {"options": ["a", "b"]}]
        Both are live in the wild, so handle both rather than assuming.
        """
        if not isinstance(entry, list) or not entry:
            return None
        if isinstance(entry[0], list):
            return [str(x) for x in entry[0]]
        if len(entry) > 1 and isinstance(entry[1], dict):
            opts = entry[1].get("options")
            if isinstance(opts, list):
                return [str(x) for x in opts]
        return None

    def _field_spec(self, class_type: str, field: str):
        r = self.session.get(f"{self.base}/object_info/{class_type}", timeout=30)
        r.raise_for_status()
        info = r.json()
        if class_type not in info:
            raise ComfyError(f"{class_type} is not loaded in ComfyUI")
        spec = info[class_type]["input"]
        for section in ("required", "optional"):
            entry = (spec.get(section) or {}).get(field)
            if entry is not None:
                return entry
        known = [k for sec in ("required", "optional")
                 for k in (spec.get(sec) or {})]
        raise ComfyError(f"{class_type} has no input '{field}'; has: {known}")

    def scan_lora_dirs(self) -> list[str]:
        """Walk the configured folders, returning ComfyUI-style relative names
        (forward slashes, subfolder prefix included)."""
        import os
        found = []
        for root in self.lora_dirs:
            if not os.path.isdir(root):
                continue
            for dirpath, dirs, files in os.walk(root):
                dirs[:] = [d for d in dirs if not d.startswith(".")]
                for f in files:
                    # ComfyUI skips dotfiles; matching that keeps the two
                    # listings comparable and hides editor/sync junk.
                    if f.startswith(".") or not f.lower().endswith(self.LORA_EXTS):
                        continue
                    rel = os.path.relpath(os.path.join(dirpath, f), root)
                    found.append(rel.replace(os.sep, "/"))
        return found

    def list_loras(self) -> list[str]:
        """Union of what ComfyUI reports and what is actually on disk.

        The disk half is what makes a just-added LoRA appear without a
        restart. Safe with the rgthree Power Lora Loader, which stores LoRAs as
        free-form dicts and resolves the path at execution time rather than
        validating against the cached dropdown. If you switch to the core
        LoraLoader, a name ComfyUI has not re-scanned will be rejected at queue
        time — restart ComfyUI in that case.
        """
        try:
            known = set(self._combo_options(
                self._field_spec("LoraLoader", "lora_name")) or [])
        except ComfyError:
            known = set()
        known.update(self.scan_lora_dirs())
        if not known:
            raise ComfyError(
                "no LoRAs found — check LORA_DIRS and models/loras")
        return sorted(known)

    def lora_sources(self) -> tuple[list[str], list[str]]:
        """(reported by ComfyUI, found on disk) — for diagnosing staleness."""
        try:
            reported = self._combo_options(
                self._field_spec("LoraLoader", "lora_name")) or []
        except ComfyError:
            reported = []
        return sorted(reported), sorted(set(self.scan_lora_dirs()))

    def options_for(self, class_type: str, field: str) -> list[str]:
        """Enum values for a widget — e.g. ResolutionSelector/aspect_ratio."""
        entry = self._field_spec(class_type, field)
        opts = self._combo_options(entry)
        if opts is None:
            raise ComfyError(
                f"{class_type}.{field} is not an enum; spec was {entry!r}")
        return opts

    def upload_image(self, data: bytes, filename: str,
                     subfolder: str = "") -> str:
        """Returns the name to put in a LoadImage node. ComfyUI may rename on
        collision, so always use the returned value rather than `filename`."""
        files = {"image": (filename, data, "application/octet-stream")}
        form = {"type": "input", "overwrite": "false"}
        if subfolder:
            form["subfolder"] = subfolder
        r = self.session.post(f"{self.base}/upload/image", files=files,
                              data=form, timeout=120)
        r.raise_for_status()
        body = r.json()
        name = body["name"]
        return f"{body['subfolder']}/{name}" if body.get("subfolder") else name

    # ------------------------------------------------------------ execution
    def run(self, wf: dict,
            on_progress: Callable[[int, int], None] | None = None,
            on_node: Callable[[str], None] | None = None) -> Iterator[ResultImage]:
        """Queue the workflow and yield output images as they finish.

        Uses the websocket rather than polling /history, so on_progress fires
        per sampler step — that's what makes a live progress display possible.
        """
        ws = websocket.WebSocket()
        ws.settimeout(self.timeout)
        ws.connect(f"ws://{self.host}/ws?clientId={self.client_id}")
        try:
            r = self.session.post(f"{self.base}/prompt",
                                  json={"prompt": wf,
                                        "client_id": self.client_id},
                                  timeout=60)
            if r.status_code == 400:
                # ComfyUI's validator names the offending node and input.
                raise ComfyError(f"workflow rejected: {r.text}")
            r.raise_for_status()
            prompt_id = r.json()["prompt_id"]

            while True:
                msg = ws.recv()
                if isinstance(msg, bytes):
                    continue          # binary preview frames
                event = json.loads(msg)
                kind, data = event.get("type"), event.get("data", {})
                if data.get("prompt_id") not in (None, prompt_id):
                    continue

                if kind == "progress" and on_progress:
                    on_progress(data.get("value", 0), data.get("max", 0))
                elif kind == "executing":
                    if data.get("node") is None:
                        break          # null node = this prompt is done
                    if on_node:
                        on_node(data["node"])
                elif kind == "execution_error":
                    raise ComfyError(
                        f"{data.get('node_type')} "
                        f"[{data.get('node_id')}]: {data.get('exception_message')}")
                elif kind == "execution_interrupted":
                    raise ComfyError("execution interrupted")
        finally:
            ws.close()

        yield from self.fetch_outputs(prompt_id)

    def fetch_outputs(self, prompt_id: str) -> Iterator[ResultImage]:
        r = self.session.get(f"{self.base}/history/{prompt_id}", timeout=60)
        r.raise_for_status()
        entry = r.json().get(prompt_id)
        if not entry:
            raise ComfyError(f"no history for {prompt_id}")
        for node_output in entry.get("outputs", {}).values():
            for img in node_output.get("images", []):
                if img.get("type") != "output":
                    continue
                yield ResultImage(img["filename"], img.get("subfolder", ""),
                                  self.view(img))

    def view(self, img: dict) -> bytes:
        r = self.session.get(f"{self.base}/view", timeout=120, params={
            "filename": img["filename"],
            "subfolder": img.get("subfolder", ""),
            "type": img.get("type", "output")})
        r.raise_for_status()
        return r.content

    def interrupt(self) -> None:
        self.session.post(f"{self.base}/interrupt", timeout=30)