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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ import sys
4
+ import json
5
+ import argparse
6
+ import contextlib
7
+ from typing import Sequence, Mapping, Any, Union
8
+ import torch
9
+ from random import randrange
10
+
11
+
12
+ def get_value_at_index(obj: Union[Sequence, Mapping], index: int) -> Any:
13
+ """Returns the value at the given index of a sequence or mapping.
14
+
15
+ If the object is a sequence (like list or string), returns the value at the given index.
16
+ If the object is a mapping (like a dictionary), returns the value at the index-th key.
17
+
18
+ Some return a dictionary, in these cases, we look for the "results" key
19
+
20
+ Args:
21
+ obj (Union[Sequence, Mapping]): The object to retrieve the value from.
22
+ index (int): The index of the value to retrieve.
23
+
24
+ Returns:
25
+ Any: The value at the given index.
26
+
27
+ Raises:
28
+ IndexError: If the index is out of bounds for the object and the object is not a mapping.
29
+ """
30
+ try:
31
+ return obj[index]
32
+ except KeyError:
33
+ return obj["result"][index]
34
+
35
+
36
+ def find_path(name: str, path: str = None) -> str:
37
+ """
38
+ Recursively looks at parent folders starting from the given path until it finds the given name.
39
+ Returns the path as a Path object if found, or None otherwise.
40
+ """
41
+ # If no path is given, use the current working directory
42
+ if path is None:
43
+ if args is None or args.comfyui_directory is None:
44
+ path = os.getcwd()
45
+ else:
46
+ path = args.comfyui_directory
47
+
48
+ # Check if the current directory contains the name
49
+ if name in os.listdir(path):
50
+ path_name = os.path.join(path, name)
51
+ print(f"{name} found: {path_name}")
52
+ return path_name
53
+
54
+ # Get the parent directory
55
+ parent_directory = os.path.dirname(path)
56
+
57
+ # If the parent directory is the same as the current directory, we've reached the root and stop the search
58
+ if parent_directory == path:
59
+ return None
60
+
61
+ # Recursively call the function with the parent directory
62
+ return find_path(name, parent_directory)
63
+
64
+
65
+ def add_comfyui_directory_to_sys_path() -> None:
66
+ """
67
+ Add 'ComfyUI' to the sys.path
68
+ """
69
+ comfyui_path = find_path("ComfyUI")
70
+ if comfyui_path is not None and os.path.isdir(comfyui_path):
71
+ sys.path.append(comfyui_path)
72
+
73
+ manager_path = os.path.join(
74
+ comfyui_path, "custom_nodes", "ComfyUI-Manager", "glob"
75
+ )
76
+
77
+ if os.path.isdir(manager_path) and os.listdir(manager_path):
78
+ sys.path.append(manager_path)
79
+ global has_manager
80
+ has_manager = True
81
+
82
+ import __main__
83
+
84
+ if getattr(__main__, "__file__", None) is None:
85
+ __main__.__file__ = os.path.join(comfyui_path, "main.py")
86
+
87
+ print(f"'{comfyui_path}' added to sys.path")
88
+
89
+
90
+ def add_extra_model_paths() -> None:
91
+ """
92
+ Parse the optional extra_model_paths.yaml file and add the parsed paths to the sys.path.
93
+ """
94
+ from comfy.options import enable_args_parsing
95
+
96
+ enable_args_parsing()
97
+ from utils.extra_config import load_extra_path_config
98
+
99
+ extra_model_paths = find_path("extra_model_paths.yaml")
100
+
101
+ if extra_model_paths is not None:
102
+ load_extra_path_config(extra_model_paths)
103
+ else:
104
+ print("Could not find the extra_model_paths config file.")
105
+
106
+
107
+ def import_custom_nodes() -> None:
108
+ """Find all custom nodes in the custom_nodes folder and add those node objects to NODE_CLASS_MAPPINGS
109
+
110
+ This function sets up a new asyncio event loop, initializes the PromptServer,
111
+ creates a PromptQueue, and initializes the custom nodes.
112
+ """
113
+ if has_manager:
114
+ try:
115
+ import manager_core as manager
116
+ except ImportError:
117
+ print("Could not import manager_core, proceeding without it.")
118
+ return
119
+ else:
120
+ if hasattr(manager, "get_config"):
121
+ print("Patching manager_core.get_config to enforce offline mode.")
122
+ try:
123
+ get_config = manager.get_config
124
+
125
+ def _get_config(*args, **kwargs):
126
+ config = get_config(*args, **kwargs)
127
+ config["network_mode"] = "offline"
128
+ return config
129
+
130
+ manager.get_config = _get_config
131
+ except Exception as e:
132
+ print("Failed to patch manager_core.get_config:", e)
133
+
134
+ import asyncio
135
+ import execution
136
+ from nodes import init_extra_nodes
137
+ import server
138
+
139
+ # Creating a new event loop and setting it as the default loop
140
+ loop = asyncio.new_event_loop()
141
+ asyncio.set_event_loop(loop)
142
+
143
+ async def inner():
144
+ # Creating an instance of PromptServer with the loop
145
+ server_instance = server.PromptServer(loop)
146
+ execution.PromptQueue(server_instance)
147
+
148
+ # Initializing custom nodes
149
+ await init_extra_nodes(init_custom_nodes=True)
150
+
151
+ loop.run_until_complete(inner())
152
+
153
+
154
+ def save_image_wrapper(context, cls):
155
+ if args.output is None:
156
+ return cls
157
+
158
+ from PIL import Image, ImageOps, ImageSequence
159
+ from PIL.PngImagePlugin import PngInfo
160
+
161
+ import numpy as np
162
+
163
+ class WrappedSaveImage(cls):
164
+ counter = 0
165
+
166
+ def save_images(
167
+ self, images, filename_prefix="ComfyUI", prompt=None, extra_pnginfo=None
168
+ ):
169
+ if args.output is None:
170
+ return super().save_images(
171
+ images, filename_prefix, prompt, extra_pnginfo
172
+ )
173
+ else:
174
+ if len(images) > 1 and args.output == "-":
175
+ raise ValueError("Cannot save multiple images to stdout")
176
+ filename_prefix += self.prefix_append
177
+
178
+ results = list()
179
+ for batch_number, image in enumerate(images):
180
+ i = 255.0 * image.cpu().numpy()
181
+ img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
182
+ metadata = None
183
+ if not args.disable_metadata:
184
+ metadata = PngInfo()
185
+ if prompt is not None:
186
+ metadata.add_text("prompt", json.dumps(prompt))
187
+ if extra_pnginfo is not None:
188
+ for x in extra_pnginfo:
189
+ metadata.add_text(x, json.dumps(extra_pnginfo[x]))
190
+
191
+ if args.output == "-":
192
+ # Hack to briefly restore stdout
193
+ if context is not None:
194
+ context.__exit__(None, None, None)
195
+ try:
196
+ img.save(
197
+ sys.stdout.buffer,
198
+ format="png",
199
+ pnginfo=metadata,
200
+ compress_level=self.compress_level,
201
+ )
202
+ finally:
203
+ if context is not None:
204
+ context.__enter__()
205
+ else:
206
+ subfolder = ""
207
+ if len(images) == 1:
208
+ if os.path.isdir(args.output):
209
+ subfolder = args.output
210
+ file = "output.png"
211
+ else:
212
+ subfolder, file = os.path.split(args.output)
213
+ if subfolder == "":
214
+ subfolder = os.getcwd()
215
+ else:
216
+ if os.path.isdir(args.output):
217
+ subfolder = args.output
218
+ file = filename_prefix
219
+ else:
220
+ subfolder, file = os.path.split(args.output)
221
+
222
+ if subfolder == "":
223
+ subfolder = os.getcwd()
224
+
225
+ files = os.listdir(subfolder)
226
+ file_pattern = file
227
+ while True:
228
+ filename_with_batch_num = file_pattern.replace(
229
+ "%batch_num%", str(batch_number)
230
+ )
231
+ file = (
232
+ f"{filename_with_batch_num}_{self.counter:05}.png"
233
+ )
234
+ self.counter += 1
235
+
236
+ if file not in files:
237
+ break
238
+
239
+ img.save(
240
+ os.path.join(subfolder, file),
241
+ pnginfo=metadata,
242
+ compress_level=self.compress_level,
243
+ )
244
+ print("Saved image to", os.path.join(subfolder, file))
245
+ results.append(
246
+ {
247
+ "filename": file,
248
+ "subfolder": subfolder,
249
+ "type": self.type,
250
+ }
251
+ )
252
+
253
+ return {"ui": {"images": results}}
254
+
255
+ return WrappedSaveImage
256
+
257
+
258
+ def parse_arg(s: Any, default: Any = None) -> Any:
259
+ """Parses a JSON string, returning it unchanged if the parsing fails."""
260
+ if __name__ == "__main__" or not isinstance(s, str):
261
+ return s
262
+
263
+ try:
264
+ return json.loads(s)
265
+ except json.JSONDecodeError:
266
+ return s
267
+
268
+
269
+ parser = argparse.ArgumentParser(
270
+ description="A converted ComfyUI workflow. Node inputs listed below. Values passed should be valid JSON (assumes string if not valid JSON)."
271
+ )
272
+ parser.add_argument(
273
+ "--ckpt_name1",
274
+ default="SDXLCheckpoint.safetensors",
275
+ help='Argument 0, input `ckpt_name` for node "Load Checkpoint" id 14 (autogenerated)',
276
+ )
277
+
278
+ parser.add_argument(
279
+ "--text2",
280
+ default="Xx_negative_xX",
281
+ help='Argument 0, input `text` for node "CLIP Text Encode (Prompt)" id 7 (autogenerated)',
282
+ )
283
+
284
+ parser.add_argument(
285
+ "--text3",
286
+ default="Xx_positive_xX",
287
+ help='Argument 0, input `text` for node "CLIPTextEncode with BREAK syntax" id 15 (autogenerated)',
288
+ )
289
+
290
+ parser.add_argument(
291
+ "--image4",
292
+ default="Fast_00076_.png [output]",
293
+ help='Argument 0, input `image` for node "Load Image (from Outputs)" id 24 (autogenerated)',
294
+ )
295
+
296
+ parser.add_argument(
297
+ "--seed5",
298
+ default=550873067544100,
299
+ help='Argument 1, input `seed` for node "KSampler" id 3 (autogenerated)',
300
+ )
301
+
302
+ parser.add_argument(
303
+ "--steps6",
304
+ default=28,
305
+ help='Argument 2, input `steps` for node "KSampler" id 3 (autogenerated)',
306
+ )
307
+
308
+ parser.add_argument(
309
+ "--cfg7",
310
+ default=4.5,
311
+ help='Argument 3, input `cfg` for node "KSampler" id 3 (autogenerated)',
312
+ )
313
+
314
+ parser.add_argument(
315
+ "--sampler_name8",
316
+ default="euler_ancestral",
317
+ help='Argument 4, input `sampler_name` for node "KSampler" id 3 (autogenerated)',
318
+ )
319
+
320
+ parser.add_argument(
321
+ "--scheduler9",
322
+ default="normal",
323
+ help='Argument 5, input `scheduler` for node "KSampler" id 3 (autogenerated)',
324
+ )
325
+
326
+ parser.add_argument(
327
+ "--denoise10",
328
+ default=0.87,
329
+ help='Argument 9, input `denoise` for node "KSampler" id 3 (autogenerated)',
330
+ )
331
+
332
+ parser.add_argument(
333
+ "--filename_prefix11",
334
+ default="Fixed",
335
+ help='Argument 1, input `filename_prefix` for node "Save Image" id 9 (autogenerated)',
336
+ )
337
+
338
+ parser.add_argument(
339
+ "--queue-size",
340
+ "-q",
341
+ type=int,
342
+ default=1,
343
+ help="How many times the workflow will be executed (default: 1)",
344
+ )
345
+
346
+ parser.add_argument(
347
+ "--comfyui-directory",
348
+ "-c",
349
+ default=None,
350
+ help="Where to look for ComfyUI (default: current directory)",
351
+ )
352
+
353
+ parser.add_argument(
354
+ "--output",
355
+ "-o",
356
+ default=None,
357
+ help="The location to save the output image. Either a file path, a directory, or - for stdout (default: the ComfyUI output directory)",
358
+ )
359
+
360
+ parser.add_argument(
361
+ "--disable-metadata",
362
+ action="store_true",
363
+ help="Disables writing workflow metadata to the outputs",
364
+ )
365
+
366
+
367
+ comfy_args = [sys.argv[0]]
368
+ if __name__ == "__main__" and "--" in sys.argv:
369
+ idx = sys.argv.index("--")
370
+ comfy_args += sys.argv[idx + 1 :]
371
+ sys.argv = sys.argv[:idx]
372
+
373
+ args = None
374
+ if __name__ == "__main__":
375
+ args = parser.parse_args()
376
+ sys.argv = comfy_args
377
+ if args is not None and args.output is not None and args.output == "-":
378
+ ctx = contextlib.redirect_stdout(sys.stderr)
379
+ else:
380
+ ctx = contextlib.nullcontext()
381
+
382
+ PROMPT_DATA = json.loads(
383
+ '{"3": {"inputs": {"seed": 550873067544100, "steps": 28, "cfg": 4.5, "sampler_name": "euler_ancestral", "scheduler": "normal", "denoise": 0.87, "model": ["14", 0], "positive": ["15", 0], "negative": ["7", 0], "latent_image": ["22", 0]}, "class_type": "KSampler", "_meta": {"title": "KSampler"}}, "7": {"inputs": {"text": "Xx_negative_xX", "clip": ["14", 1]}, "class_type": "CLIPTextEncode", "_meta": {"title": "CLIP Text Encode (Prompt)"}}, "8": {"inputs": {"samples": ["3", 0], "vae": ["14", 2]}, "class_type": "VAEDecode", "_meta": {"title": "VAE Decode"}}, "9": {"inputs": {"filename_prefix": "Fixed", "images": ["8", 0]}, "class_type": "SaveImage", "_meta": {"title": "Save Image"}}, "14": {"inputs": {"ckpt_name": "SDXLCheckpoint.safetensors"}, "class_type": "CheckpointLoaderSimple", "_meta": {"title": "Load Checkpoint"}}, "15": {"inputs": {"text": "Xx_positive_xX", "clip": ["14", 1]}, "class_type": "CLIPTextEncodeWithBreak", "_meta": {"title": "CLIPTextEncode with BREAK syntax"}}, "22": {"inputs": {"pixels": ["24", 0], "vae": ["14", 2]}, "class_type": "VAEEncode", "_meta": {"title": "VAE Encode"}}, "24": {"inputs": {"image": "Fast_00076_.png [output]", "refresh": "refresh"}, "class_type": "LoadImageOutput", "_meta": {"title": "Load Image (from Outputs)"}}}'
384
+ )
385
+
386
+
387
+ def import_custom_nodes() -> None:
388
+ """Find all custom nodes in the custom_nodes folder and add those node objects to NODE_CLASS_MAPPINGS
389
+
390
+ This function sets up a new asyncio event loop, initializes the PromptServer,
391
+ creates a PromptQueue, and initializes the custom nodes.
392
+ """
393
+ if has_manager:
394
+ try:
395
+ import manager_core as manager
396
+ except ImportError:
397
+ print("Could not import manager_core, proceeding without it.")
398
+ return
399
+ else:
400
+ if hasattr(manager, "get_config"):
401
+ print("Patching manager_core.get_config to enforce offline mode.")
402
+ try:
403
+ get_config = manager.get_config
404
+
405
+ def _get_config(*args, **kwargs):
406
+ config = get_config(*args, **kwargs)
407
+ config["network_mode"] = "offline"
408
+ return config
409
+
410
+ manager.get_config = _get_config
411
+ except Exception as e:
412
+ print("Failed to patch manager_core.get_config:", e)
413
+
414
+ import asyncio
415
+ import execution
416
+ from nodes import init_extra_nodes
417
+ import server
418
+
419
+ # Creating a new event loop and setting it as the default loop
420
+ loop = asyncio.new_event_loop()
421
+ asyncio.set_event_loop(loop)
422
+
423
+ async def inner():
424
+ # Creating an instance of PromptServer with the loop
425
+ server_instance = server.PromptServer(loop)
426
+ execution.PromptQueue(server_instance)
427
+
428
+ # Initializing custom nodes
429
+ await init_extra_nodes(init_custom_nodes=True)
430
+
431
+ loop.run_until_complete(inner())
432
+
433
+
434
+ _custom_nodes_imported = False
435
+ _custom_path_added = False
436
+
437
+
438
+ def main(*func_args, **func_kwargs):
439
+ global args, _custom_nodes_imported, _custom_path_added
440
+ if __name__ == "__main__":
441
+ if args is None:
442
+ args = parser.parse_args()
443
+ else:
444
+ defaults = dict(
445
+ (arg, parser.get_default(arg))
446
+ for arg in ["queue_size", "comfyui_directory", "output", "disable_metadata"]
447
+ + [
448
+ "ckpt_name1",
449
+ "text2",
450
+ "text3",
451
+ "image4",
452
+ "seed5",
453
+ "steps6",
454
+ "cfg7",
455
+ "sampler_name8",
456
+ "scheduler9",
457
+ "denoise10",
458
+ "filename_prefix11",
459
+ ]
460
+ )
461
+
462
+ all_args = dict()
463
+ all_args.update(defaults)
464
+ all_args.update(func_kwargs)
465
+
466
+ args = argparse.Namespace(**all_args)
467
+
468
+ with ctx:
469
+ if not _custom_path_added:
470
+ add_comfyui_directory_to_sys_path()
471
+ add_extra_model_paths()
472
+
473
+ _custom_path_added = True
474
+
475
+ if not _custom_nodes_imported:
476
+ import_custom_nodes()
477
+
478
+ _custom_nodes_imported = True
479
+
480
+ from nodes import NODE_CLASS_MAPPINGS
481
+
482
+ with torch.inference_mode(), ctx:
483
+ checkpointloadersimple = NODE_CLASS_MAPPINGS["CheckpointLoaderSimple"]()
484
+ checkpointloadersimple_14 = checkpointloadersimple.load_checkpoint(
485
+ ckpt_name=parse_arg(args.ckpt_name1)
486
+ )
487
+
488
+ cliptextencode = NODE_CLASS_MAPPINGS["CLIPTextEncode"]()
489
+ cliptextencode_7 = cliptextencode.encode(
490
+ text=parse_arg(args.text2),
491
+ clip=get_value_at_index(checkpointloadersimple_14, 1),
492
+ )
493
+
494
+ cliptextencodewithbreak = NODE_CLASS_MAPPINGS["CLIPTextEncodeWithBreak"]()
495
+ cliptextencodewithbreak_15 = cliptextencodewithbreak.encode(
496
+ text=parse_arg(args.text3),
497
+ clip=get_value_at_index(checkpointloadersimple_14, 1),
498
+ )
499
+
500
+ loadimageoutput = NODE_CLASS_MAPPINGS["LoadImageOutput"]()
501
+ loadimageoutput_24 = loadimageoutput.load_image(image=parse_arg(args.image4))
502
+
503
+ vaeencode = NODE_CLASS_MAPPINGS["VAEEncode"]()
504
+ vaeencode_22 = vaeencode.encode(
505
+ pixels=get_value_at_index(loadimageoutput_24, 0),
506
+ vae=get_value_at_index(checkpointloadersimple_14, 2),
507
+ )
508
+
509
+ ksampler = NODE_CLASS_MAPPINGS["KSampler"]()
510
+ vaedecode = NODE_CLASS_MAPPINGS["VAEDecode"]()
511
+ saveimage = save_image_wrapper(ctx, NODE_CLASS_MAPPINGS["SaveImage"])()
512
+ for q in range(args.queue_size):
513
+ ksampler_3 = ksampler.sample(
514
+ seed=randrange(1000000000),
515
+ steps=parse_arg(args.steps6),
516
+ cfg=parse_arg(args.cfg7),
517
+ sampler_name=parse_arg(args.sampler_name8),
518
+ scheduler=parse_arg(args.scheduler9),
519
+ denoise=parse_arg(args.denoise10),
520
+ model=get_value_at_index(checkpointloadersimple_14, 0),
521
+ positive=get_value_at_index(cliptextencodewithbreak_15, 0),
522
+ negative=get_value_at_index(cliptextencode_7, 0),
523
+ latent_image=get_value_at_index(vaeencode_22, 0),
524
+ )
525
+
526
+ vaedecode_8 = vaedecode.decode(
527
+ samples=get_value_at_index(ksampler_3, 0),
528
+ vae=get_value_at_index(checkpointloadersimple_14, 2),
529
+ )
530
+
531
+ if __name__ != "__main__":
532
+ return dict(
533
+ filename_prefix=parse_arg(args.filename_prefix11),
534
+ images=get_value_at_index(vaedecode_8, 0),
535
+ prompt=PROMPT_DATA,
536
+ )
537
+ else:
538
+ saveimage_9 = saveimage.save_images(
539
+ filename_prefix=parse_arg(args.filename_prefix11),
540
+ images=get_value_at_index(vaedecode_8, 0),
541
+ prompt=PROMPT_DATA,
542
+ )
543
+
544
+
545
+ if __name__ == "__main__":
546
+ main()