comfyui.py 9.78 KB
Newer Older
1
import asyncio
Timothy J. Baek's avatar
Timothy J. Baek committed
2
3
4
5
6
import websocket  # NOTE: websocket-client (https://github.com/websocket-client/websocket-client)
import json
import urllib.request
import urllib.parse
import random
7
8
9
10
11
12
import logging

from config import SRC_LOG_LEVELS

log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["COMFYUI"])
Timothy J. Baek's avatar
Timothy J. Baek committed
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

from pydantic import BaseModel

from typing import Optional

COMFYUI_DEFAULT_PROMPT = """
{
  "3": {
    "inputs": {
      "seed": 0,
      "steps": 20,
      "cfg": 8,
      "sampler_name": "euler",
      "scheduler": "normal",
      "denoise": 1,
      "model": [
        "4",
        0
      ],
      "positive": [
        "6",
        0
      ],
      "negative": [
        "7",
        0
      ],
      "latent_image": [
        "5",
        0
      ]
    },
    "class_type": "KSampler",
    "_meta": {
      "title": "KSampler"
    }
  },
  "4": {
    "inputs": {
      "ckpt_name": "model.safetensors"
    },
    "class_type": "CheckpointLoaderSimple",
    "_meta": {
      "title": "Load Checkpoint"
    }
  },
  "5": {
    "inputs": {
      "width": 512,
      "height": 512,
      "batch_size": 1
    },
    "class_type": "EmptyLatentImage",
    "_meta": {
      "title": "Empty Latent Image"
    }
  },
  "6": {
    "inputs": {
      "text": "Prompt",
      "clip": [
        "4",
        1
      ]
    },
    "class_type": "CLIPTextEncode",
    "_meta": {
      "title": "CLIP Text Encode (Prompt)"
    }
  },
  "7": {
    "inputs": {
      "text": "Negative Prompt",
      "clip": [
        "4",
        1
      ]
    },
    "class_type": "CLIPTextEncode",
    "_meta": {
      "title": "CLIP Text Encode (Prompt)"
    }
  },
  "8": {
    "inputs": {
      "samples": [
        "3",
        0
      ],
      "vae": [
        "4",
        2
      ]
    },
    "class_type": "VAEDecode",
    "_meta": {
      "title": "VAE Decode"
    }
  },
  "9": {
    "inputs": {
      "filename_prefix": "ComfyUI",
      "images": [
        "8",
        0
      ]
    },
    "class_type": "SaveImage",
    "_meta": {
      "title": "Save Image"
    }
  }
}
"""

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
FLUX_DEFAULT_PROMPT = """
{
    "5": {
        "inputs": {
            "width": 1024,
            "height": 1024,
            "batch_size": 1
        },
        "class_type": "EmptyLatentImage"
    },
    "6": {
        "inputs": {
            "text": "Input Text Here",
            "clip": [
                "11",
                0
            ]
        },
        "class_type": "CLIPTextEncode"
    },
    "8": {
        "inputs": {
            "samples": [
                "13",
                0
            ],
            "vae": [
                "10",
                0
            ]
        },
        "class_type": "VAEDecode"
    },
    "9": {
        "inputs": {
            "filename_prefix": "ComfyUI",
            "images": [
                "8",
                0
            ]
        },
        "class_type": "SaveImage"
    },
    "10": {
        "inputs": {
173
            "vae_name": "ae.safetensors"
174
175
176
177
178
179
180
181
182
183
184
185
186
        },
        "class_type": "VAELoader"
    },
    "11": {
        "inputs": {
            "clip_name1": "clip_l.safetensors",
            "clip_name2": "t5xxl_fp16.safetensors",
            "type": "flux"
        },
        "class_type": "DualCLIPLoader"
    },
    "12": {
        "inputs": {
187
            "unet_name": "flux1-dev.safetensors",
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
            "weight_dtype": "default"
        },
        "class_type": "UNETLoader"
    },
    "13": {
        "inputs": {
            "noise": [
                "25",
                0
            ],
            "guider": [
                "22",
                0
            ],
            "sampler": [
                "16",
                0
            ],
            "sigmas": [
                "17",
                0
            ],
            "latent_image": [
                "5",
                0
            ]
        },
        "class_type": "SamplerCustomAdvanced"
    },
    "16": {
        "inputs": {
            "sampler_name": "euler"
        },
        "class_type": "KSamplerSelect"
    },
    "17": {
        "inputs": {
            "scheduler": "simple",
            "steps": 20,
            "denoise": 1,
            "model": [
                "12",
                0
            ]
        },
        "class_type": "BasicScheduler"
    },
    "22": {
        "inputs": {
            "model": [
                "12",
                0
            ],
            "conditioning": [
                "6",
                0
            ]
        },
        "class_type": "BasicGuider"
    },
    "25": {
        "inputs": {
            "noise_seed": 778937779713005
        },
        "class_type": "RandomNoise"
    }
}
"""

Timothy J. Baek's avatar
Timothy J. Baek committed
257
258

def queue_prompt(prompt, client_id, base_url):
259
    log.info("queue_prompt")
Timothy J. Baek's avatar
Timothy J. Baek committed
260
261
262
263
264
265
266
    p = {"prompt": prompt, "client_id": client_id}
    data = json.dumps(p).encode("utf-8")
    req = urllib.request.Request(f"{base_url}/prompt", data=data)
    return json.loads(urllib.request.urlopen(req).read())


def get_image(filename, subfolder, folder_type, base_url):
267
    log.info("get_image")
Timothy J. Baek's avatar
Timothy J. Baek committed
268
269
270
271
272
273
274
    data = {"filename": filename, "subfolder": subfolder, "type": folder_type}
    url_values = urllib.parse.urlencode(data)
    with urllib.request.urlopen(f"{base_url}/view?{url_values}") as response:
        return response.read()


def get_image_url(filename, subfolder, folder_type, base_url):
275
    log.info("get_image")
Timothy J. Baek's avatar
Timothy J. Baek committed
276
277
278
279
280
281
    data = {"filename": filename, "subfolder": subfolder, "type": folder_type}
    url_values = urllib.parse.urlencode(data)
    return f"{base_url}/view?{url_values}"


def get_history(prompt_id, base_url):
282
    log.info("get_history")
Timothy J. Baek's avatar
Timothy J. Baek committed
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
    with urllib.request.urlopen(f"{base_url}/history/{prompt_id}") as response:
        return json.loads(response.read())


def get_images(ws, prompt, client_id, base_url):
    prompt_id = queue_prompt(prompt, client_id, base_url)["prompt_id"]
    output_images = []
    while True:
        out = ws.recv()
        if isinstance(out, str):
            message = json.loads(out)
            if message["type"] == "executing":
                data = message["data"]
                if data["node"] is None and data["prompt_id"] == prompt_id:
                    break  # Execution is done
        else:
            continue  # previews are binary data

    history = get_history(prompt_id, base_url)[prompt_id]
    for o in history["outputs"]:
        for node_id in history["outputs"]:
            node_output = history["outputs"][node_id]
            if "images" in node_output:
                for image in node_output["images"]:
                    url = get_image_url(
                        image["filename"], image["subfolder"], image["type"], base_url
                    )
                    output_images.append({"url": url})
    return {"data": output_images}


class ImageGenerationPayload(BaseModel):
    prompt: str
    negative_prompt: Optional[str] = ""
    steps: Optional[int] = None
    seed: Optional[int] = None
    width: int
    height: int
    n: int = 1
322
323
324
325
    cfg_scale: Optional[float] = None
    sampler: Optional[str] = None
    scheduler: Optional[str] = None
    sd3: Optional[bool] = None
326
327
328
    flux: Optional[bool] = None
    flux_weight_dtype: Optional[str] = None
    flux_fp8_clip: Optional[bool] = None
Timothy J. Baek's avatar
Timothy J. Baek committed
329

Timothy J. Baek's avatar
Timothy J. Baek committed
330

331
async def comfyui_generate_image(
Timothy J. Baek's avatar
Timothy J. Baek committed
332
333
    model: str, payload: ImageGenerationPayload, client_id, base_url
):
334
    ws_url = base_url.replace("http://", "ws://").replace("https://", "wss://")
Timothy J. Baek's avatar
Timothy J. Baek committed
335
336
337

    comfyui_prompt = json.loads(COMFYUI_DEFAULT_PROMPT)

338
339
340
341
342
343
344
345
346
347
348
349
    if payload.cfg_scale:
        comfyui_prompt["3"]["inputs"]["cfg"] = payload.cfg_scale

    if payload.sampler:
        comfyui_prompt["3"]["inputs"]["sampler"] = payload.sampler

    if payload.scheduler:
        comfyui_prompt["3"]["inputs"]["scheduler"] = payload.scheduler

    if payload.sd3:
        comfyui_prompt["5"]["class_type"] = "EmptySD3LatentImage"

350
351
352
    if payload.steps:
        comfyui_prompt["3"]["inputs"]["steps"] = payload.steps

Timothy J. Baek's avatar
Timothy J. Baek committed
353
    comfyui_prompt["4"]["inputs"]["ckpt_name"] = model
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
    comfyui_prompt["7"]["inputs"]["text"] = payload.negative_prompt
    comfyui_prompt["3"]["inputs"]["seed"] = (
        payload.seed if payload.seed else random.randint(0, 18446744073709551614)
    )

    # as Flux uses a completely different workflow, we must treat it specially
    if payload.flux:
        comfyui_prompt = json.loads(FLUX_DEFAULT_PROMPT)
        comfyui_prompt["12"]["inputs"]["unet_name"] = model
        comfyui_prompt["25"]["inputs"]["noise_seed"] = (
            payload.seed if payload.seed else random.randint(0, 18446744073709551614)
        )

        if payload.sampler:
            comfyui_prompt["16"]["inputs"]["sampler_name"] = payload.sampler

        if payload.steps:
            comfyui_prompt["17"]["inputs"]["steps"] = payload.steps

        if payload.scheduler:
            comfyui_prompt["17"]["inputs"]["scheduler"] = payload.scheduler

        if payload.flux_weight_dtype:
            comfyui_prompt["12"]["inputs"]["weight_dtype"] = payload.flux_weight_dtype
Timothy J. Baek's avatar
Timothy J. Baek committed
378

379
        if payload.flux_fp8_clip:
Michael Poluektov's avatar
Michael Poluektov committed
380
381
382
            comfyui_prompt["11"]["inputs"][
                "clip_name2"
            ] = "t5xxl_fp8_e4m3fn.safetensors"
383

Timothy J. Baek's avatar
Timothy J. Baek committed
384
385
386
387
388
389
390
391
392
    comfyui_prompt["5"]["inputs"]["batch_size"] = payload.n
    comfyui_prompt["5"]["inputs"]["width"] = payload.width
    comfyui_prompt["5"]["inputs"]["height"] = payload.height

    # set the text prompt for our positive CLIPTextEncode
    comfyui_prompt["6"]["inputs"]["text"] = payload.prompt

    try:
        ws = websocket.WebSocket()
393
        ws.connect(f"{ws_url}/ws?clientId={client_id}")
394
        log.info("WebSocket connection established.")
Timothy J. Baek's avatar
Timothy J. Baek committed
395
    except Exception as e:
396
        log.exception(f"Failed to connect to WebSocket server: {e}")
Timothy J. Baek's avatar
Timothy J. Baek committed
397
398
399
        return None

    try:
Michael Poluektov's avatar
Michael Poluektov committed
400
401
402
        images = await asyncio.to_thread(
            get_images, ws, comfyui_prompt, client_id, base_url
        )
Timothy J. Baek's avatar
Timothy J. Baek committed
403
    except Exception as e:
404
        log.exception(f"Error while receiving images: {e}")
Timothy J. Baek's avatar
Timothy J. Baek committed
405
406
407
408
409
        images = None

    ws.close()

    return images