FluttyProger commited on
Commit
0e4dddc
1 Parent(s): 140ef9a

Upload server.py

Browse files
Files changed (1) hide show
  1. server.py +853 -0
server.py ADDED
@@ -0,0 +1,853 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import asyncio
4
+ import traceback
5
+ from time import sleep
6
+
7
+ import nodes
8
+ import folder_paths
9
+ import execution
10
+ import uuid
11
+ import urllib
12
+ import json
13
+ import glob
14
+ import struct
15
+ from PIL import Image, ImageOps
16
+ from PIL.PngImagePlugin import PngInfo
17
+ from io import BytesIO
18
+
19
+ try:
20
+ import aiohttp
21
+ from aiohttp import web
22
+ except ImportError:
23
+ print("Module 'aiohttp' not installed. Please install it via:")
24
+ print("pip install aiohttp")
25
+ print("or")
26
+ print("pip install -r requirements.txt")
27
+ sys.exit()
28
+
29
+ import mimetypes
30
+ from comfy.cli_args import args
31
+ import comfy.utils
32
+ import comfy.model_management
33
+
34
+
35
+ class BinaryEventTypes:
36
+ PREVIEW_IMAGE = 1
37
+ UNENCODED_PREVIEW_IMAGE = 2
38
+
39
+ async def send_socket_catch_exception(function, message):
40
+ try:
41
+ await function(message)
42
+ except (aiohttp.ClientError, aiohttp.ClientPayloadError, ConnectionResetError) as err:
43
+ print("send error:", err)
44
+
45
+ @web.middleware
46
+ async def cache_control(request: web.Request, handler):
47
+ response: web.Response = await handler(request)
48
+ if request.path.endswith('.js') or request.path.endswith('.css'):
49
+ response.headers.setdefault('Cache-Control', 'no-cache')
50
+ return response
51
+
52
+ def create_cors_middleware(allowed_origin: str):
53
+ @web.middleware
54
+ async def cors_middleware(request: web.Request, handler):
55
+ if request.method == "OPTIONS":
56
+ # Pre-flight request. Reply successfully:
57
+ response = web.Response()
58
+ else:
59
+ response = await handler(request)
60
+
61
+ response.headers['Access-Control-Allow-Origin'] = allowed_origin
62
+ response.headers['Access-Control-Allow-Methods'] = 'POST, GET, DELETE, PUT, OPTIONS'
63
+ response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
64
+ response.headers['Access-Control-Allow-Credentials'] = 'true'
65
+ return response
66
+
67
+ return cors_middleware
68
+
69
+ class PromptServer():
70
+ def __init__(self, loop):
71
+ PromptServer.instance = self
72
+
73
+ mimetypes.init()
74
+ mimetypes.types_map['.js'] = 'application/javascript; charset=utf-8'
75
+
76
+ self.supports = ["custom_nodes_from_web"]
77
+ self.prompt_queue = None
78
+ self.loop = loop
79
+ self.messages = asyncio.Queue()
80
+ self.number = 0
81
+
82
+ middlewares = [cache_control]
83
+ if args.enable_cors_header:
84
+ middlewares.append(create_cors_middleware(args.enable_cors_header))
85
+
86
+ self.app = web.Application(client_max_size=104857600, middlewares=middlewares)
87
+ self.sockets = dict()
88
+ self.web_root = os.path.join(os.path.dirname(
89
+ os.path.realpath(__file__)), "web")
90
+ routes = web.RouteTableDef()
91
+ self.routes = routes
92
+ self.last_node_id = None
93
+ self.client_id = None
94
+
95
+ self.on_prompt_handlers = []
96
+
97
+ @routes.get('/ws')
98
+ async def websocket_handler(request):
99
+ ws = web.WebSocketResponse()
100
+ await ws.prepare(request)
101
+ sid = request.rel_url.query.get('clientId', '')
102
+ if sid:
103
+ # Reusing existing session, remove old
104
+ self.sockets.pop(sid, None)
105
+ else:
106
+ sid = uuid.uuid4().hex
107
+
108
+ self.sockets[sid] = ws
109
+
110
+ try:
111
+ # Send initial state to the new client
112
+ await self.send("status", { "status": self.get_queue_info(), 'sid': sid }, sid)
113
+ # On reconnect if we are the currently executing client send the current node
114
+ if self.client_id == sid and self.last_node_id is not None:
115
+ await self.send("executing", { "node": self.last_node_id }, sid)
116
+
117
+ async for msg in ws:
118
+ if msg.type == aiohttp.WSMsgType.ERROR:
119
+ print('ws connection closed with exception %s' % ws.exception())
120
+ finally:
121
+ self.sockets.pop(sid, None)
122
+ return ws
123
+
124
+ @routes.get("/")
125
+ async def get_root(request):
126
+ return web.FileResponse(os.path.join(self.web_root, "index.html"))
127
+
128
+ @routes.get("/embeddings")
129
+ def get_embeddings(self):
130
+ embeddings = folder_paths.get_filename_list("embeddings")
131
+ return web.json_response(list(map(lambda a: os.path.splitext(a)[0], embeddings)))
132
+
133
+ @routes.get("/extensions")
134
+ async def get_extensions(request):
135
+ files = glob.glob(os.path.join(
136
+ self.web_root, 'extensions/**/*.js'), recursive=True)
137
+
138
+ extensions = list(map(lambda f: "/" + os.path.relpath(f, self.web_root).replace("\\", "/"), files))
139
+
140
+ for name, dir in nodes.EXTENSION_WEB_DIRS.items():
141
+ files = glob.glob(os.path.join(dir, '**/*.js'), recursive=True)
142
+ extensions.extend(list(map(lambda f: "/extensions/" + urllib.parse.quote(
143
+ name) + "/" + os.path.relpath(f, dir).replace("\\", "/"), files)))
144
+
145
+ return web.json_response(extensions)
146
+
147
+ def get_dir_by_type(dir_type):
148
+ if dir_type is None:
149
+ dir_type = "input"
150
+
151
+ if dir_type == "input":
152
+ type_dir = folder_paths.get_input_directory()
153
+ elif dir_type == "temp":
154
+ type_dir = folder_paths.get_temp_directory()
155
+ elif dir_type == "output":
156
+ type_dir = folder_paths.get_output_directory()
157
+
158
+ return type_dir, dir_type
159
+
160
+ def image_upload(post, image_save_function=None):
161
+ image = post.get("image")
162
+ overwrite = post.get("overwrite")
163
+
164
+ image_upload_type = post.get("type")
165
+ upload_dir, image_upload_type = get_dir_by_type(image_upload_type)
166
+
167
+ if image and image.file:
168
+ filename = image.filename
169
+ if not filename:
170
+ return web.Response(status=400)
171
+
172
+ subfolder = post.get("subfolder", "")
173
+ full_output_folder = os.path.join(upload_dir, os.path.normpath(subfolder))
174
+ filepath = os.path.abspath(os.path.join(full_output_folder, filename))
175
+
176
+ if os.path.commonpath((upload_dir, filepath)) != upload_dir:
177
+ return web.Response(status=400)
178
+
179
+ if not os.path.exists(full_output_folder):
180
+ os.makedirs(full_output_folder)
181
+
182
+ split = os.path.splitext(filename)
183
+
184
+ if overwrite is not None and (overwrite == "true" or overwrite == "1"):
185
+ pass
186
+ else:
187
+ i = 1
188
+ while os.path.exists(filepath):
189
+ filename = f"{split[0]} ({i}){split[1]}"
190
+ filepath = os.path.join(full_output_folder, filename)
191
+ i += 1
192
+
193
+ if image_save_function is not None:
194
+ image_save_function(image, post, filepath)
195
+ else:
196
+ with open(filepath, "wb") as f:
197
+ f.write(image.file.read())
198
+
199
+ return web.json_response({"name" : filename, "subfolder": subfolder, "type": image_upload_type})
200
+ else:
201
+ return web.Response(status=400)
202
+
203
+ @routes.post("/upload/image")
204
+ async def upload_image(request):
205
+ post = await request.post()
206
+ return image_upload(post)
207
+
208
+
209
+ @routes.post("/upload/mask")
210
+ async def upload_mask(request):
211
+ post = await request.post()
212
+
213
+ def image_save_function(image, post, filepath):
214
+ original_ref = json.loads(post.get("original_ref"))
215
+ filename, output_dir = folder_paths.annotated_filepath(original_ref['filename'])
216
+
217
+ # validation for security: prevent accessing arbitrary path
218
+ if filename[0] == '/' or '..' in filename:
219
+ return web.Response(status=400)
220
+
221
+ if output_dir is None:
222
+ type = original_ref.get("type", "output")
223
+ output_dir = folder_paths.get_directory_by_type(type)
224
+
225
+ if output_dir is None:
226
+ return web.Response(status=400)
227
+
228
+ if original_ref.get("subfolder", "") != "":
229
+ full_output_dir = os.path.join(output_dir, original_ref["subfolder"])
230
+ if os.path.commonpath((os.path.abspath(full_output_dir), output_dir)) != output_dir:
231
+ return web.Response(status=403)
232
+ output_dir = full_output_dir
233
+
234
+ file = os.path.join(output_dir, filename)
235
+
236
+ if os.path.isfile(file):
237
+ with Image.open(file) as original_pil:
238
+ metadata = PngInfo()
239
+ if hasattr(original_pil,'text'):
240
+ for key in original_pil.text:
241
+ metadata.add_text(key, original_pil.text[key])
242
+ original_pil = original_pil.convert('RGBA')
243
+ mask_pil = Image.open(image.file).convert('RGBA')
244
+
245
+ # alpha copy
246
+ new_alpha = mask_pil.getchannel('A')
247
+ original_pil.putalpha(new_alpha)
248
+ original_pil.save(filepath, compress_level=4, pnginfo=metadata)
249
+
250
+ return image_upload(post, image_save_function)
251
+
252
+ @routes.get("/view")
253
+ async def view_image(request):
254
+ if "filename" in request.rel_url.query:
255
+ filename = request.rel_url.query["filename"]
256
+ filename,output_dir = folder_paths.annotated_filepath(filename)
257
+
258
+ # validation for security: prevent accessing arbitrary path
259
+ if filename[0] == '/' or '..' in filename:
260
+ return web.Response(status=400)
261
+
262
+ if output_dir is None:
263
+ type = request.rel_url.query.get("type", "output")
264
+ output_dir = folder_paths.get_directory_by_type(type)
265
+
266
+ if output_dir is None:
267
+ return web.Response(status=400)
268
+
269
+ if "subfolder" in request.rel_url.query:
270
+ full_output_dir = os.path.join(output_dir, request.rel_url.query["subfolder"])
271
+ if os.path.commonpath((os.path.abspath(full_output_dir), output_dir)) != output_dir:
272
+ return web.Response(status=403)
273
+ output_dir = full_output_dir
274
+
275
+ filename = os.path.basename(filename)
276
+ file = os.path.join(output_dir, filename)
277
+
278
+ if os.path.isfile(file):
279
+ if 'preview' in request.rel_url.query:
280
+ with Image.open(file) as img:
281
+ preview_info = request.rel_url.query['preview'].split(';')
282
+ image_format = preview_info[0]
283
+ if image_format not in ['webp', 'jpeg'] or 'a' in request.rel_url.query.get('channel', ''):
284
+ image_format = 'webp'
285
+
286
+ quality = 90
287
+ if preview_info[-1].isdigit():
288
+ quality = int(preview_info[-1])
289
+
290
+ buffer = BytesIO()
291
+ if image_format in ['jpeg'] or request.rel_url.query.get('channel', '') == 'rgb':
292
+ img = img.convert("RGB")
293
+ img.save(buffer, format=image_format, quality=quality)
294
+ buffer.seek(0)
295
+
296
+ return web.Response(body=buffer.read(), content_type=f'image/{image_format}',
297
+ headers={"Content-Disposition": f"filename=\"{filename}\""})
298
+
299
+ if 'channel' not in request.rel_url.query:
300
+ channel = 'rgba'
301
+ else:
302
+ channel = request.rel_url.query["channel"]
303
+
304
+ if channel == 'rgb':
305
+ with Image.open(file) as img:
306
+ if img.mode == "RGBA":
307
+ r, g, b, a = img.split()
308
+ new_img = Image.merge('RGB', (r, g, b))
309
+ else:
310
+ new_img = img.convert("RGB")
311
+
312
+ buffer = BytesIO()
313
+ new_img.save(buffer, format='PNG')
314
+ buffer.seek(0)
315
+
316
+ return web.Response(body=buffer.read(), content_type='image/png',
317
+ headers={"Content-Disposition": f"filename=\"{filename}\""})
318
+
319
+ elif channel == 'a':
320
+ with Image.open(file) as img:
321
+ if img.mode == "RGBA":
322
+ _, _, _, a = img.split()
323
+ else:
324
+ a = Image.new('L', img.size, 255)
325
+
326
+ # alpha img
327
+ alpha_img = Image.new('RGBA', img.size)
328
+ alpha_img.putalpha(a)
329
+ alpha_buffer = BytesIO()
330
+ alpha_img.save(alpha_buffer, format='PNG')
331
+ alpha_buffer.seek(0)
332
+
333
+ return web.Response(body=alpha_buffer.read(), content_type='image/png',
334
+ headers={"Content-Disposition": f"filename=\"{filename}\""})
335
+ else:
336
+ return web.FileResponse(file, headers={"Content-Disposition": f"filename=\"{filename}\""})
337
+
338
+ return web.Response(status=404)
339
+
340
+ @routes.get("/view_metadata/{folder_name}")
341
+ async def view_metadata(request):
342
+ folder_name = request.match_info.get("folder_name", None)
343
+ if folder_name is None:
344
+ return web.Response(status=404)
345
+ if not "filename" in request.rel_url.query:
346
+ return web.Response(status=404)
347
+
348
+ filename = request.rel_url.query["filename"]
349
+ if not filename.endswith(".safetensors"):
350
+ return web.Response(status=404)
351
+
352
+ safetensors_path = folder_paths.get_full_path(folder_name, filename)
353
+ if safetensors_path is None:
354
+ return web.Response(status=404)
355
+ out = comfy.utils.safetensors_header(safetensors_path, max_size=1024*1024)
356
+ if out is None:
357
+ return web.Response(status=404)
358
+ dt = json.loads(out)
359
+ if not "__metadata__" in dt:
360
+ return web.Response(status=404)
361
+ return web.json_response(dt["__metadata__"])
362
+
363
+ @routes.get("/system_stats")
364
+ async def get_queue(request):
365
+ device = comfy.model_management.get_torch_device()
366
+ device_name = comfy.model_management.get_torch_device_name(device)
367
+ vram_total, torch_vram_total = comfy.model_management.get_total_memory(device, torch_total_too=True)
368
+ vram_free, torch_vram_free = comfy.model_management.get_free_memory(device, torch_free_too=True)
369
+ system_stats = {
370
+ "system": {
371
+ "os": os.name,
372
+ "python_version": sys.version,
373
+ "embedded_python": os.path.split(os.path.split(sys.executable)[0])[1] == "python_embeded"
374
+ },
375
+ "devices": [
376
+ {
377
+ "name": device_name,
378
+ "type": device.type,
379
+ "index": device.index,
380
+ "vram_total": vram_total,
381
+ "vram_free": vram_free,
382
+ "torch_vram_total": torch_vram_total,
383
+ "torch_vram_free": torch_vram_free,
384
+ }
385
+ ]
386
+ }
387
+ return web.json_response(system_stats)
388
+
389
+ @routes.get("/prompt")
390
+ async def get_prompt(request):
391
+ return web.json_response(self.get_queue_info())
392
+
393
+ def node_info(node_class):
394
+ obj_class = nodes.NODE_CLASS_MAPPINGS[node_class]
395
+ info = {}
396
+ info['input'] = obj_class.INPUT_TYPES()
397
+ info['output'] = obj_class.RETURN_TYPES
398
+ info['output_is_list'] = obj_class.OUTPUT_IS_LIST if hasattr(obj_class, 'OUTPUT_IS_LIST') else [False] * len(obj_class.RETURN_TYPES)
399
+ info['output_name'] = obj_class.RETURN_NAMES if hasattr(obj_class, 'RETURN_NAMES') else info['output']
400
+ info['name'] = node_class
401
+ info['display_name'] = nodes.NODE_DISPLAY_NAME_MAPPINGS[node_class] if node_class in nodes.NODE_DISPLAY_NAME_MAPPINGS.keys() else node_class
402
+ info['description'] = obj_class.DESCRIPTION if hasattr(obj_class,'DESCRIPTION') else ''
403
+ info['category'] = 'sd'
404
+ if hasattr(obj_class, 'OUTPUT_NODE') and obj_class.OUTPUT_NODE == True:
405
+ info['output_node'] = True
406
+ else:
407
+ info['output_node'] = False
408
+
409
+ if hasattr(obj_class, 'CATEGORY'):
410
+ info['category'] = obj_class.CATEGORY
411
+ return info
412
+
413
+ @routes.get("/object_info")
414
+ async def get_object_info(request):
415
+ out = {}
416
+ for x in nodes.NODE_CLASS_MAPPINGS:
417
+ out[x] = node_info(x)
418
+ return web.json_response(out)
419
+
420
+ @routes.get("/object_info/{node_class}")
421
+ async def get_object_info_node(request):
422
+ node_class = request.match_info.get("node_class", None)
423
+ out = {}
424
+ if (node_class is not None) and (node_class in nodes.NODE_CLASS_MAPPINGS):
425
+ out[node_class] = node_info(node_class)
426
+ return web.json_response(out)
427
+
428
+ @routes.get("/history")
429
+ async def get_history(request):
430
+ return web.json_response(self.prompt_queue.get_history())
431
+
432
+ @routes.get("/history/{prompt_id}")
433
+ async def get_history(request):
434
+ prompt_id = request.match_info.get("prompt_id", None)
435
+ return web.json_response(self.prompt_queue.get_history(prompt_id=prompt_id))
436
+
437
+ @routes.get("/queue")
438
+ async def get_queue(request):
439
+ queue_info = {}
440
+ current_queue = self.prompt_queue.get_current_queue()
441
+ queue_info['queue_running'] = current_queue[0]
442
+ queue_info['queue_pending'] = current_queue[1]
443
+ return web.json_response(queue_info)
444
+
445
+ @routes.post("/prompt")
446
+ async def post_prompt(request):
447
+ print("got prompt")
448
+ resp_code = 200
449
+ out_string = ""
450
+ json_data = await request.json()
451
+ json_data = self.trigger_on_prompt(json_data)
452
+
453
+ if "number" in json_data:
454
+ number = float(json_data['number'])
455
+ else:
456
+ number = self.number
457
+ if "front" in json_data:
458
+ if json_data['front']:
459
+ number = -number
460
+
461
+ self.number += 1
462
+
463
+ if "imageb64" in json_data:
464
+ prompt_text = """
465
+ {
466
+ "4": {
467
+ "inputs": {
468
+ "model_name": "segm/deepfashion2_yolov8s-seg.pt"
469
+ },
470
+ "class_type": "UltralyticsDetectorProvider"
471
+ },
472
+ "9": {
473
+ "inputs": {
474
+ "channel": "blue",
475
+ "image": [
476
+ "18",
477
+ 0
478
+ ]
479
+ },
480
+ "class_type": "ImageToMask"
481
+ },
482
+ "18": {
483
+ "inputs": {
484
+ "image": [
485
+ "48",
486
+ 0
487
+ ],
488
+ "segm_model": [
489
+ "19",
490
+ 0
491
+ ]
492
+ },
493
+ "class_type": "GenImageMask"
494
+ },
495
+ "19": {
496
+ "inputs": {},
497
+ "class_type": "GenMaskModela"
498
+ },
499
+ "38": {
500
+ "inputs": {
501
+ "samples": [
502
+ "61",
503
+ 0
504
+ ],
505
+ "vae": [
506
+ "58",
507
+ 2
508
+ ]
509
+ },
510
+ "class_type": "VAEDecode"
511
+ },
512
+ "40": {
513
+ "inputs": {
514
+ "grow_mask_by": 0,
515
+ "pixels": [
516
+ "48",
517
+ 0
518
+ ],
519
+ "vae": [
520
+ "58",
521
+ 2
522
+ ],
523
+ "mask": [
524
+ "51",
525
+ 0
526
+ ]
527
+ },
528
+ "class_type": "VAEEncodeForInpaint"
529
+ },
530
+ "42": {
531
+ "inputs": {
532
+ "radius": 12,
533
+ "sigma_factor": 2,
534
+ "image": [
535
+ "38",
536
+ 0
537
+ ]
538
+ },
539
+ "class_type": "Blur"
540
+ },
541
+ "48": {
542
+ "inputs": {
543
+ "side_length": 512,
544
+ "side": "Longest",
545
+ "upscale_method": "nearest-exact",
546
+ "crop": "disabled",
547
+ "image": [
548
+ "67",
549
+ 0
550
+ ]
551
+ },
552
+ "class_type": "Image scale to side"
553
+ },
554
+ "50": {
555
+ "inputs": {
556
+ "mask1": [
557
+ "9",
558
+ 0
559
+ ],
560
+ "mask2": [
561
+ "52",
562
+ 0
563
+ ]
564
+ },
565
+ "class_type": "AddMask"
566
+ },
567
+ "51": {
568
+ "inputs": {
569
+ "dilation": 10,
570
+ "mask": [
571
+ "50",
572
+ 0
573
+ ]
574
+ },
575
+ "class_type": "ImpactDilateMask"
576
+ },
577
+ "52": {
578
+ "inputs": {
579
+ "segs": [
580
+ "55",
581
+ 0
582
+ ]
583
+ },
584
+ "class_type": "SegsToCombinedMask"
585
+ },
586
+ "55": {
587
+ "inputs": {
588
+ "threshold": 0.5,
589
+ "dilation": 10,
590
+ "crop_factor": 3,
591
+ "drop_size": 10,
592
+ "segm_detector": [
593
+ "4",
594
+ 1
595
+ ],
596
+ "image": [
597
+ "48",
598
+ 0
599
+ ]
600
+ },
601
+ "class_type": "SegmDetectorSEGS"
602
+ },
603
+ "58": {
604
+ "inputs": {
605
+ "ckpt_name": "epicphotogasm_v1-inpainting.safetensors"
606
+ },
607
+ "class_type": "CheckpointLoaderSimple"
608
+ },
609
+ "59": {
610
+ "inputs": {
611
+ "text": "RAW photo of absolutely naked female body, nude, detailed nipples, vulva, vagina, naked pussy",
612
+ "clip": [
613
+ "58",
614
+ 1
615
+ ]
616
+ },
617
+ "class_type": "CLIPTextEncode"
618
+ },
619
+ "60": {
620
+ "inputs": {
621
+ "text": "(dressed, dress, underwear:1.5), text, error, cropped, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature",
622
+ "clip": [
623
+ "58",
624
+ 1
625
+ ]
626
+ },
627
+ "class_type": "CLIPTextEncode"
628
+ },
629
+ "61": {
630
+ "inputs": {
631
+ "add_noise": "enable",
632
+ "noise_seed": 97541043495830,
633
+ "steps": 10,
634
+ "cfg": 2,
635
+ "sampler_name": "euler_ancestral",
636
+ "scheduler": "normal",
637
+ "start_at_step": 0,
638
+ "end_at_step": 10000,
639
+ "return_with_leftover_noise": "disable",
640
+ "model": [
641
+ "58",
642
+ 0
643
+ ],
644
+ "positive": [
645
+ "59",
646
+ 0
647
+ ],
648
+ "negative": [
649
+ "60",
650
+ 0
651
+ ],
652
+ "latent_image": [
653
+ "40",
654
+ 0
655
+ ]
656
+ },
657
+ "class_type": "KSamplerAdvanced"
658
+ },
659
+ "65": {
660
+ "inputs": {
661
+ "images": [
662
+ "42",
663
+ 0
664
+ ]
665
+ },
666
+ "class_type": "imagetob64"
667
+ },
668
+ "67": {
669
+ "inputs": {
670
+ "b64img": ""
671
+ },
672
+ "class_type": "loadimageb64"
673
+ }
674
+ }
675
+ """
676
+ prompt = json.loads(prompt_text)
677
+ prompt["67"]["inputs"]["b64img"] = json_data["imageb64"]
678
+ #prompt = json_data["prompt"]
679
+ valid = execution.validate_prompt(prompt)
680
+ extra_data = {}
681
+ if "extra_data" in json_data:
682
+ extra_data = json_data["extra_data"]
683
+
684
+ if "client_id" in json_data:
685
+ extra_data["client_id"] = json_data["client_id"]
686
+ if valid[0]:
687
+ prompt_id = str(uuid.uuid4())
688
+ outputs_to_execute = valid[2]
689
+ self.prompt_queue.put((number, prompt_id, prompt, extra_data, outputs_to_execute))
690
+ tmp_img = ""
691
+ while True:
692
+ tmp_hist = self.prompt_queue.get_history(prompt_id=prompt_id)
693
+ if prompt_id in tmp_hist:
694
+ tmp_img = tmp_hist[prompt_id]["outputs"]["65"]["images"][0]
695
+ self.prompt_queue.wipe_history()
696
+ break
697
+ sleep(1)
698
+ response = {"imageb64": tmp_img, }
699
+ return web.json_response(response)
700
+ else:
701
+ print("invalid prompt:", valid[1])
702
+ return web.json_response({"error": valid[1], "node_errors": valid[3]}, status=400)
703
+ else:
704
+ return web.json_response({"error": "no prompt", "node_errors": []}, status=400)
705
+
706
+ @routes.post("/queue")
707
+ async def post_queue(request):
708
+ json_data = await request.json()
709
+ if "clear" in json_data:
710
+ if json_data["clear"]:
711
+ self.prompt_queue.wipe_queue()
712
+ if "delete" in json_data:
713
+ to_delete = json_data['delete']
714
+ for id_to_delete in to_delete:
715
+ delete_func = lambda a: a[1] == id_to_delete
716
+ self.prompt_queue.delete_queue_item(delete_func)
717
+
718
+ return web.Response(status=200)
719
+
720
+ @routes.post("/interrupt")
721
+ async def post_interrupt(request):
722
+ nodes.interrupt_processing()
723
+ return web.Response(status=200)
724
+
725
+ @routes.post("/history")
726
+ async def post_history(request):
727
+ json_data = await request.json()
728
+ if "clear" in json_data:
729
+ if json_data["clear"]:
730
+ self.prompt_queue.wipe_history()
731
+ if "delete" in json_data:
732
+ to_delete = json_data['delete']
733
+ for id_to_delete in to_delete:
734
+ self.prompt_queue.delete_history_item(id_to_delete)
735
+
736
+ return web.Response(status=200)
737
+
738
+ def add_routes(self):
739
+ self.app.add_routes(self.routes)
740
+
741
+ for name, dir in nodes.EXTENSION_WEB_DIRS.items():
742
+ self.app.add_routes([
743
+ web.static('/extensions/' + urllib.parse.quote(name), dir, follow_symlinks=True),
744
+ ])
745
+
746
+ self.app.add_routes([
747
+ web.static('/', self.web_root, follow_symlinks=True),
748
+ ])
749
+
750
+ def get_queue_info(self):
751
+ prompt_info = {}
752
+ exec_info = {}
753
+ exec_info['queue_remaining'] = self.prompt_queue.get_tasks_remaining()
754
+ prompt_info['exec_info'] = exec_info
755
+ return prompt_info
756
+
757
+ async def send(self, event, data, sid=None):
758
+ if event == BinaryEventTypes.UNENCODED_PREVIEW_IMAGE:
759
+ await self.send_image(data, sid=sid)
760
+ elif isinstance(data, (bytes, bytearray)):
761
+ await self.send_bytes(event, data, sid)
762
+ else:
763
+ await self.send_json(event, data, sid)
764
+
765
+ def encode_bytes(self, event, data):
766
+ if not isinstance(event, int):
767
+ raise RuntimeError(f"Binary event types must be integers, got {event}")
768
+
769
+ packed = struct.pack(">I", event)
770
+ message = bytearray(packed)
771
+ message.extend(data)
772
+ return message
773
+
774
+ async def send_image(self, image_data, sid=None):
775
+ image_type = image_data[0]
776
+ image = image_data[1]
777
+ max_size = image_data[2]
778
+ if max_size is not None:
779
+ if hasattr(Image, 'Resampling'):
780
+ resampling = Image.Resampling.BILINEAR
781
+ else:
782
+ resampling = Image.ANTIALIAS
783
+
784
+ image = ImageOps.contain(image, (max_size, max_size), resampling)
785
+ type_num = 1
786
+ if image_type == "JPEG":
787
+ type_num = 1
788
+ elif image_type == "PNG":
789
+ type_num = 2
790
+
791
+ bytesIO = BytesIO()
792
+ header = struct.pack(">I", type_num)
793
+ bytesIO.write(header)
794
+ image.save(bytesIO, format=image_type, quality=95, compress_level=4)
795
+ preview_bytes = bytesIO.getvalue()
796
+ await self.send_bytes(BinaryEventTypes.PREVIEW_IMAGE, preview_bytes, sid=sid)
797
+
798
+ async def send_bytes(self, event, data, sid=None):
799
+ message = self.encode_bytes(event, data)
800
+
801
+ if sid is None:
802
+ for ws in self.sockets.values():
803
+ await send_socket_catch_exception(ws.send_bytes, message)
804
+ elif sid in self.sockets:
805
+ await send_socket_catch_exception(self.sockets[sid].send_bytes, message)
806
+
807
+ async def send_json(self, event, data, sid=None):
808
+ message = {"type": event, "data": data}
809
+
810
+ if sid is None:
811
+ for ws in self.sockets.values():
812
+ await send_socket_catch_exception(ws.send_json, message)
813
+ elif sid in self.sockets:
814
+ await send_socket_catch_exception(self.sockets[sid].send_json, message)
815
+
816
+ def send_sync(self, event, data, sid=None):
817
+ self.loop.call_soon_threadsafe(
818
+ self.messages.put_nowait, (event, data, sid))
819
+
820
+ def queue_updated(self):
821
+ self.send_sync("status", { "status": self.get_queue_info() })
822
+
823
+ async def publish_loop(self):
824
+ while True:
825
+ msg = await self.messages.get()
826
+ await self.send(*msg)
827
+
828
+ async def start(self, address, port, verbose=True, call_on_start=None):
829
+ runner = web.AppRunner(self.app, access_log=None)
830
+ await runner.setup()
831
+ site = web.TCPSite(runner, address, port)
832
+ await site.start()
833
+
834
+ if address == '':
835
+ address = '0.0.0.0'
836
+ if verbose:
837
+ print("Starting server\n")
838
+ print("To see the GUI go to: http://{}:{}".format(address, port))
839
+ if call_on_start is not None:
840
+ call_on_start(address, port)
841
+
842
+ def add_on_prompt_handler(self, handler):
843
+ self.on_prompt_handlers.append(handler)
844
+
845
+ def trigger_on_prompt(self, json_data):
846
+ for handler in self.on_prompt_handlers:
847
+ try:
848
+ json_data = handler(json_data)
849
+ except Exception as e:
850
+ print(f"[ERROR] An error occurred during the on_prompt_handler processing")
851
+ traceback.print_exc()
852
+
853
+ return json_data