Albator2570 commited on
Commit
c47587f
·
verified ·
1 Parent(s): 2f0ff31

Upload REAL ComfyUI backend that connects to the local server

Browse files
Files changed (1) hide show
  1. fix/backend_comfyui.py +264 -0
fix/backend_comfyui.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ ComfyUI local image generation backend for PPT Master.
4
+ Connects to a running ComfyUI server and generates real images via the API.
5
+ """
6
+ import io, json, os, random, subprocess, sys, time, uuid, threading
7
+ from pathlib import Path
8
+
9
+ import requests
10
+ from PIL import Image, ImageDraw, ImageFont, ImageFilter
11
+
12
+ from image_backends.backend_common import (
13
+ MAX_RETRIES, normalize_image_size, resolve_output_path, save_image_bytes
14
+ )
15
+
16
+ DEFAULT_SERVER = "http://127.0.0.1:8188"
17
+ VALID_ASPECT_RATIOS = ["1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9"]
18
+ VALID_IMAGE_SIZES = ["512px","1K","2K","4K","0.5K"]
19
+
20
+
21
+ def _bool_env(name, default=False):
22
+ v = os.environ.get(name)
23
+ if v is None: return default
24
+ return v.strip().lower() in ("1","true","yes","y","on")
25
+
26
+
27
+ def _server():
28
+ return os.environ.get("COMFYUI_SERVER", DEFAULT_SERVER).rstrip("/")
29
+
30
+
31
+ def _ping(server):
32
+ try:
33
+ r = requests.get(f"{server}/system_stats", timeout=3)
34
+ return r.status_code == 200
35
+ except:
36
+ return False
37
+
38
+
39
+ def _dimensions(aspect_ratio, image_size):
40
+ image_size = normalize_image_size(image_size)
41
+ long_edge = {"0.5K":512,"512px":512,"1K":1024,"2K":1536,"4K":2048}.get(image_size, 1024)
42
+ w_r, h_r = [int(x) for x in aspect_ratio.split(":")]
43
+ if w_r >= h_r:
44
+ width, height = long_edge, round(long_edge * h_r / w_r)
45
+ else:
46
+ height, width = long_edge, round(long_edge * w_r / h_r)
47
+ # SD checkpoints want multiples of 8
48
+ width = max(256, (width // 8) * 8)
49
+ height = max(256, (height // 8) * 8)
50
+ return width, height
51
+
52
+
53
+ def _build_workflow(prompt, negative, width, height, model):
54
+ """Build a standard txt2img workflow for ComfyUI API."""
55
+ seed = random.randint(1, 2**31 - 1)
56
+
57
+ # Check if user has a custom workflow JSON
58
+ workflow_path = os.environ.get("COMFYUI_WORKFLOW")
59
+ if workflow_path and Path(workflow_path).exists():
60
+ data = json.loads(Path(workflow_path).read_text(encoding="utf-8"))
61
+ raw = json.dumps(data)
62
+ for k, v in {"{{prompt}}": prompt, "{{negative_prompt}}": negative,
63
+ "{{width}}": str(width), "{{height}}": str(height),
64
+ "{{seed}}": str(seed), "{{model}}": model or ""}.items():
65
+ raw = raw.replace(k, v)
66
+ return json.loads(raw)
67
+
68
+ # Default workflow: CheckpointLoader -> CLIP -> KSampler -> VAEDecode -> SaveImage
69
+ if not model:
70
+ raise RuntimeError(
71
+ "No COMFYUI_MODEL or COMFYUI_WORKFLOW set. "
72
+ "Set COMFYUI_MODEL to the checkpoint filename in ComfyUI/models/checkpoints/."
73
+ )
74
+
75
+ return {
76
+ "1": {
77
+ "class_type": "CheckpointLoaderSimple",
78
+ "inputs": {"ckpt_name": model}
79
+ },
80
+ "2": {
81
+ "class_type": "CLIPTextEncode",
82
+ "inputs": {"text": prompt, "clip": ["1", 1]}
83
+ },
84
+ "3": {
85
+ "class_type": "CLIPTextEncode",
86
+ "inputs": {"text": negative, "clip": ["1", 1]}
87
+ },
88
+ "4": {
89
+ "class_type": "EmptyLatentImage",
90
+ "inputs": {"width": width, "height": height, "batch_size": 1}
91
+ },
92
+ "5": {
93
+ "class_type": "KSampler",
94
+ "inputs": {
95
+ "seed": seed,
96
+ "steps": 25,
97
+ "cfg": 7.0,
98
+ "sampler_name": "euler_ancestral",
99
+ "scheduler": "normal",
100
+ "denoise": 1.0,
101
+ "model": ["1", 0],
102
+ "positive": ["2", 0],
103
+ "negative": ["3", 0],
104
+ "latent_image": ["4", 0]
105
+ }
106
+ },
107
+ "6": {
108
+ "class_type": "VAEDecode",
109
+ "inputs": {"samples": ["5", 0], "vae": ["1", 2]}
110
+ },
111
+ "7": {
112
+ "class_type": "SaveImage",
113
+ "inputs": {"filename_prefix": "pptmaster", "images": ["6", 0]}
114
+ }
115
+ }
116
+
117
+
118
+ def _queue_and_wait(server, workflow, timeout=600):
119
+ """Queue prompt on ComfyUI and wait for the result image."""
120
+ client_id = str(uuid.uuid4())
121
+
122
+ # Queue the prompt
123
+ resp = requests.post(
124
+ f"{server}/prompt",
125
+ json={"prompt": workflow, "client_id": client_id},
126
+ timeout=30
127
+ )
128
+ if resp.status_code >= 400:
129
+ raise RuntimeError(f"ComfyUI /prompt error {resp.status_code}: {resp.text[:500]}")
130
+
131
+ prompt_id = resp.json()["prompt_id"]
132
+ print(f" Queued prompt_id: {prompt_id}")
133
+
134
+ # Poll history until done
135
+ deadline = time.time() + timeout
136
+ while time.time() < deadline:
137
+ try:
138
+ hist = requests.get(f"{server}/history/{prompt_id}", timeout=10)
139
+ if hist.status_code == 200:
140
+ data = hist.json()
141
+ if prompt_id in data:
142
+ outputs = data[prompt_id].get("outputs", {})
143
+ for node_output in outputs.values():
144
+ images = node_output.get("images", [])
145
+ for img_info in images:
146
+ # Download the generated image
147
+ params = {
148
+ "filename": img_info["filename"],
149
+ "subfolder": img_info.get("subfolder", ""),
150
+ "type": img_info.get("type", "output")
151
+ }
152
+ img_resp = requests.get(f"{server}/view", params=params, timeout=60)
153
+ img_resp.raise_for_status()
154
+ return img_resp.content
155
+ # If outputs exist but no images, there was an error
156
+ if outputs:
157
+ raise RuntimeError(f"ComfyUI completed but no images in output: {json.dumps(outputs)[:500]}")
158
+ except requests.RequestException:
159
+ pass
160
+ time.sleep(1.5)
161
+
162
+ raise RuntimeError(f"Timeout ({timeout}s) waiting for ComfyUI generation.")
163
+
164
+
165
+ def _placeholder(prompt, width, height):
166
+ """Fallback: generate a deterministic placeholder image."""
167
+ rng = random.Random(hash(prompt) & 0xFFFFFFFF)
168
+ img = Image.new("RGB", (width, height), (9, 12, 24))
169
+ d = ImageDraw.Draw(img, "RGBA")
170
+ pal = [(28,38,70),(52,67,105),(121,33,48),(186,137,64),(30,90,96),(88,20,60)]
171
+ for i in range(30):
172
+ c = pal[i % len(pal)] + (rng.randint(50, 140),)
173
+ x0, y0 = rng.randint(-width//4, width), rng.randint(-height//4, height)
174
+ r = rng.randint(max(60, width//10), max(160, width//3))
175
+ d.ellipse((x0-r, y0-r, x0+r, y0+r), fill=c)
176
+ img = img.filter(ImageFilter.GaussianBlur(radius=max(8, width//100)))
177
+ d = ImageDraw.Draw(img, "RGBA")
178
+ for i in range(60):
179
+ d.rectangle((i, i, width-i, height-i), outline=(0,0,0,max(0,140-int(2.5*i))), width=2)
180
+ try:
181
+ fb = ImageFont.truetype("DejaVuSans-Bold.ttf", max(28, width//22))
182
+ fs = ImageFont.truetype("DejaVuSans.ttf", max(14, width//50))
183
+ except:
184
+ fb = fs = ImageFont.load_default()
185
+ pad = max(24, width//30)
186
+ bh = max(100, height//5)
187
+ d.rounded_rectangle((pad, height-bh-pad, width-pad, height-pad), radius=18,
188
+ fill=(0,0,0,130), outline=(200,160,80,200), width=2)
189
+ d.text((pad*1.6, height-bh-pad+18), "PLACEHOLDER (ComfyUI offline)", fill=(240,220,170,255), font=fb)
190
+ d.text((pad*1.6, height-bh-pad+60), prompt[:120], fill=(230,235,245,220), font=fs)
191
+ buf = io.BytesIO()
192
+ img.save(buf, format="PNG")
193
+ return buf.getvalue()
194
+
195
+
196
+ def generate(prompt, aspect_ratio="1:1", image_size="1K",
197
+ output_dir=None, filename=None, model=None, max_retries=MAX_RETRIES):
198
+ """Main entry point called by image_gen.py."""
199
+
200
+ if aspect_ratio not in VALID_ASPECT_RATIOS:
201
+ raise ValueError(f"Invalid aspect ratio '{aspect_ratio}'. Valid: {VALID_ASPECT_RATIOS}")
202
+ image_size = normalize_image_size(image_size)
203
+ if image_size not in VALID_IMAGE_SIZES:
204
+ raise ValueError(f"Invalid image size '{image_size}'. Valid: {VALID_IMAGE_SIZES}")
205
+
206
+ width, height = _dimensions(aspect_ratio, image_size)
207
+ path = resolve_output_path(prompt, output_dir, filename, ".png")
208
+ server = _server()
209
+ model = model or os.environ.get("COMFYUI_MODEL")
210
+ negative = os.environ.get("COMFYUI_NEGATIVE_PROMPT",
211
+ "low quality, blurry, watermark, text, distorted, deformed, ugly, nsfw")
212
+ fallback = os.environ.get("COMFYUI_FALLBACK", "error").strip().lower()
213
+
214
+ print(f"[ComfyUI]")
215
+ print(f" Server: {server}")
216
+ print(f" Model: {model or '(not set)'}")
217
+ print(f" Prompt: {prompt[:100]}{'...' if len(prompt)>100 else ''}")
218
+ print(f" Size: {width}x{height}")
219
+ print(f" Aspect Ratio: {aspect_ratio}")
220
+ print()
221
+
222
+ # Check if server is reachable
223
+ if not _ping(server):
224
+ msg = (f"ComfyUI server not reachable at {server}.\n"
225
+ f" Launch ComfyUI first: python main.py --listen 127.0.0.1 --port 8188")
226
+ if fallback == "placeholder":
227
+ print(f" [WARN] {msg}")
228
+ print(f" [WARN] Using placeholder image.")
229
+ return save_image_bytes(_placeholder(prompt, width, height), path)
230
+ raise RuntimeError(msg)
231
+
232
+ # Build and queue workflow
233
+ try:
234
+ workflow = _build_workflow(prompt, negative, width, height, model)
235
+
236
+ start = time.time()
237
+ print(f" Generating...", end="", flush=True)
238
+
239
+ # Heartbeat
240
+ stop_evt = threading.Event()
241
+ def heartbeat():
242
+ while not stop_evt.is_set():
243
+ stop_evt.wait(5)
244
+ if not stop_evt.is_set():
245
+ print(f" {time.time()-start:.0f}s...", end="", flush=True)
246
+ hb = threading.Thread(target=heartbeat, daemon=True)
247
+ hb.start()
248
+
249
+ try:
250
+ image_bytes = _queue_and_wait(server, workflow)
251
+ finally:
252
+ stop_evt.set()
253
+ hb.join(timeout=1)
254
+
255
+ elapsed = time.time() - start
256
+ print(f"\n [DONE] Generated in {elapsed:.1f}s")
257
+ return save_image_bytes(image_bytes, path)
258
+
259
+ except Exception as e:
260
+ if fallback == "placeholder":
261
+ print(f"\n [WARN] Generation failed: {e}")
262
+ print(f" [WARN] Using placeholder image.")
263
+ return save_image_bytes(_placeholder(prompt, width, height), path)
264
+ raise