File size: 23,176 Bytes
2a90493 a1b9b51 2a90493 a1b9b51 2a90493 7368923 |
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 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 |
import os
import random
import sys
import json
import argparse
import contextlib
from typing import Sequence, Mapping, Any, Union
import torch
from random import randrange
def get_value_at_index(obj: Union[Sequence, Mapping], index: int) -> Any:
"""Returns the value at the given index of a sequence or mapping.
If the object is a sequence (like list or string), returns the value at the given index.
If the object is a mapping (like a dictionary), returns the value at the index-th key.
Some return a dictionary, in these cases, we look for the "results" key
Args:
obj (Union[Sequence, Mapping]): The object to retrieve the value from.
index (int): The index of the value to retrieve.
Returns:
Any: The value at the given index.
Raises:
IndexError: If the index is out of bounds for the object and the object is not a mapping.
"""
try:
return obj[index]
except KeyError:
return obj["result"][index]
def find_path(name: str, path: str = None) -> str:
"""
Recursively looks at parent folders starting from the given path until it finds the given name.
Returns the path as a Path object if found, or None otherwise.
"""
# If no path is given, use the current working directory
if path is None:
if args is None or args.comfyui_directory is None:
path = os.getcwd()
else:
path = args.comfyui_directory
# Check if the current directory contains the name
if name in os.listdir(path):
path_name = os.path.join(path, name)
print(f"{name} found: {path_name}")
return path_name
# Get the parent directory
parent_directory = os.path.dirname(path)
# If the parent directory is the same as the current directory, we've reached the root and stop the search
if parent_directory == path:
return None
# Recursively call the function with the parent directory
return find_path(name, parent_directory)
def add_comfyui_directory_to_sys_path() -> None:
"""
Add 'ComfyUI' to the sys.path
"""
comfyui_path = find_path("ComfyUI")
if comfyui_path is not None and os.path.isdir(comfyui_path):
sys.path.append(comfyui_path)
manager_path = os.path.join(
comfyui_path, "custom_nodes", "ComfyUI-Manager", "glob"
)
if os.path.isdir(manager_path) and os.listdir(manager_path):
sys.path.append(manager_path)
global has_manager
has_manager = True
import __main__
if getattr(__main__, "__file__", None) is None:
__main__.__file__ = os.path.join(comfyui_path, "main.py")
print(f"'{comfyui_path}' added to sys.path")
def add_extra_model_paths() -> None:
"""
Parse the optional extra_model_paths.yaml file and add the parsed paths to the sys.path.
"""
from comfy.options import enable_args_parsing
enable_args_parsing()
from utils.extra_config import load_extra_path_config
extra_model_paths = find_path("extra_model_paths.yaml")
if extra_model_paths is not None:
load_extra_path_config(extra_model_paths)
else:
print("Could not find the extra_model_paths config file.")
def import_custom_nodes() -> None:
"""Find all custom nodes in the custom_nodes folder and add those node objects to NODE_CLASS_MAPPINGS
This function sets up a new asyncio event loop, initializes the PromptServer,
creates a PromptQueue, and initializes the custom nodes.
"""
if has_manager:
try:
import manager_core as manager
except ImportError:
print("Could not import manager_core, proceeding without it.")
return
else:
if hasattr(manager, "get_config"):
print("Patching manager_core.get_config to enforce offline mode.")
try:
get_config = manager.get_config
def _get_config(*args, **kwargs):
config = get_config(*args, **kwargs)
config["network_mode"] = "offline"
return config
manager.get_config = _get_config
except Exception as e:
print("Failed to patch manager_core.get_config:", e)
import asyncio
import execution
from nodes import init_extra_nodes
import server
# Creating a new event loop and setting it as the default loop
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
async def inner():
# Creating an instance of PromptServer with the loop
server_instance = server.PromptServer(loop)
execution.PromptQueue(server_instance)
# Initializing custom nodes
await init_extra_nodes(init_custom_nodes=True)
loop.run_until_complete(inner())
def save_image_wrapper(context, cls):
if args.output is None:
return cls
from PIL import Image, ImageOps, ImageSequence
from PIL.PngImagePlugin import PngInfo
import numpy as np
class WrappedSaveImage(cls):
counter = 0
def save_images(
self, images, filename_prefix="ComfyUI", prompt=None, extra_pnginfo=None
):
if args.output is None:
return super().save_images(
images, filename_prefix, prompt, extra_pnginfo
)
else:
if len(images) > 1 and args.output == "-":
raise ValueError("Cannot save multiple images to stdout")
filename_prefix += self.prefix_append
results = list()
for batch_number, image in enumerate(images):
i = 255.0 * image.cpu().numpy()
img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
metadata = None
if not args.disable_metadata:
metadata = PngInfo()
if prompt is not None:
metadata.add_text("prompt", json.dumps(prompt))
if extra_pnginfo is not None:
for x in extra_pnginfo:
metadata.add_text(x, json.dumps(extra_pnginfo[x]))
if args.output == "-":
# Hack to briefly restore stdout
if context is not None:
context.__exit__(None, None, None)
try:
img.save(
sys.stdout.buffer,
format="png",
pnginfo=metadata,
compress_level=self.compress_level,
)
finally:
if context is not None:
context.__enter__()
else:
subfolder = ""
if len(images) == 1:
if os.path.isdir(args.output):
subfolder = args.output
file = "output.png"
else:
subfolder, file = os.path.split(args.output)
if subfolder == "":
subfolder = os.getcwd()
else:
if os.path.isdir(args.output):
subfolder = args.output
file = filename_prefix
else:
subfolder, file = os.path.split(args.output)
if subfolder == "":
subfolder = os.getcwd()
files = os.listdir(subfolder)
file_pattern = file
while True:
filename_with_batch_num = file_pattern.replace(
"%batch_num%", str(batch_number)
)
file = (
f"{filename_with_batch_num}_{self.counter:05}.png"
)
self.counter += 1
if file not in files:
break
img.save(
os.path.join(subfolder, file),
pnginfo=metadata,
compress_level=self.compress_level,
)
print("Saved image to", os.path.join(subfolder, file))
results.append(
{
"filename": file,
"subfolder": subfolder,
"type": self.type,
}
)
return {"ui": {"images": results}}
return WrappedSaveImage
def parse_arg(s: Any, default: Any = None) -> Any:
"""Parses a JSON string, returning it unchanged if the parsing fails."""
if __name__ == "__main__" or not isinstance(s, str):
return s
try:
return json.loads(s)
except json.JSONDecodeError:
return s
parser = argparse.ArgumentParser(
description="A converted ComfyUI workflow. Node inputs listed below. Values passed should be valid JSON (assumes string if not valid JSON)."
)
parser.add_argument(
"--width1",
default=5176,
help='Argument 0, input `width` for node "Empty Latent Image" id 5 (autogenerated)',
)
parser.add_argument(
"--height2",
default=3784,
help='Argument 1, input `height` for node "Empty Latent Image" id 5 (autogenerated)',
)
parser.add_argument(
"--batch_size3",
default=1,
help='Argument 2, input `batch_size` for node "Empty Latent Image" id 5 (autogenerated)',
)
parser.add_argument(
"--ckpt_name4",
default="SDXLCheckpoint.safetensors",
help='Argument 0, input `ckpt_name` for node "Load Checkpoint" id 14 (autogenerated)',
)
parser.add_argument(
"--lora_name5",
default="dmd2_sdxl_4step_lora_fp16.safetensors",
help='Argument 2, input `lora_name` for node "Load LoRA" id 17 (autogenerated)',
)
parser.add_argument(
"--strength_model6",
default=1,
help='Argument 3, input `strength_model` for node "Load LoRA" id 17 (autogenerated)',
)
parser.add_argument(
"--strength_clip7",
default=1,
help='Argument 4, input `strength_clip` for node "Load LoRA" id 17 (autogenerated)',
)
parser.add_argument(
"--text8",
default="Xx_negative_xX",
help='Argument 0, input `text` for node "CLIP Text Encode (Prompt)" id 7 (autogenerated)',
)
parser.add_argument(
"--text9",
default="Xx_positive_xX",
help='Argument 0, input `text` for node "CLIP Text Encode (Prompt)" id 18 (autogenerated)',
)
parser.add_argument(
"--block_number10",
default=3,
help='Argument 1, input `block_number` for node "PatchModelAddDownscale (Kohya Deep Shrink)" id 16 (autogenerated)',
)
parser.add_argument(
"--downscale_factor11",
default=2,
help='Argument 2, input `downscale_factor` for node "PatchModelAddDownscale (Kohya Deep Shrink)" id 16 (autogenerated)',
)
parser.add_argument(
"--start_percent12",
default=0,
help='Argument 3, input `start_percent` for node "PatchModelAddDownscale (Kohya Deep Shrink)" id 16 (autogenerated)',
)
parser.add_argument(
"--end_percent13",
default=0.5000000000000001,
help='Argument 4, input `end_percent` for node "PatchModelAddDownscale (Kohya Deep Shrink)" id 16 (autogenerated)',
)
parser.add_argument(
"--downscale_after_skip14",
default=True,
help='Argument 5, input `downscale_after_skip` for node "PatchModelAddDownscale (Kohya Deep Shrink)" id 16 (autogenerated)',
)
parser.add_argument(
"--downscale_method15",
default="bicubic",
help='Argument 6, input `downscale_method` for node "PatchModelAddDownscale (Kohya Deep Shrink)" id 16 (autogenerated)',
)
parser.add_argument(
"--upscale_method16",
default="bicubic",
help='Argument 7, input `upscale_method` for node "PatchModelAddDownscale (Kohya Deep Shrink)" id 16 (autogenerated)',
)
parser.add_argument(
"--seed17",
default=64836095259134,
help='Argument 1, input `seed` for node "KSampler" id 3 (autogenerated)',
)
parser.add_argument(
"--steps18",
default=8,
help='Argument 2, input `steps` for node "KSampler" id 3 (autogenerated)',
)
parser.add_argument(
"--cfg19",
default=1,
help='Argument 3, input `cfg` for node "KSampler" id 3 (autogenerated)',
)
parser.add_argument(
"--sampler_name20",
default="lcm",
help='Argument 4, input `sampler_name` for node "KSampler" id 3 (autogenerated)',
)
parser.add_argument(
"--scheduler21",
default="beta",
help='Argument 5, input `scheduler` for node "KSampler" id 3 (autogenerated)',
)
parser.add_argument(
"--denoise22",
default=1,
help='Argument 9, input `denoise` for node "KSampler" id 3 (autogenerated)',
)
parser.add_argument(
"--filename_prefix23",
default="Fast",
help='Argument 1, input `filename_prefix` for node "Save Image" id 9 (autogenerated)',
)
parser.add_argument(
"--queue-size",
"-q",
type=int,
default=1,
help="How many times the workflow will be executed (default: 1)",
)
parser.add_argument(
"--comfyui-directory",
"-c",
default=None,
help="Where to look for ComfyUI (default: current directory)",
)
parser.add_argument(
"--output",
"-o",
default=None,
help="The location to save the output image. Either a file path, a directory, or - for stdout (default: the ComfyUI output directory)",
)
parser.add_argument(
"--disable-metadata",
action="store_true",
help="Disables writing workflow metadata to the outputs",
)
comfy_args = [sys.argv[0]]
if __name__ == "__main__" and "--" in sys.argv:
idx = sys.argv.index("--")
comfy_args += sys.argv[idx + 1 :]
sys.argv = sys.argv[:idx]
args = None
if __name__ == "__main__":
args = parser.parse_args()
sys.argv = comfy_args
if args is not None and args.output is not None and args.output == "-":
ctx = contextlib.redirect_stdout(sys.stderr)
else:
ctx = contextlib.nullcontext()
PROMPT_DATA = json.loads(
'{"3": {"inputs": {"seed": 64836095259134, "steps": 8, "cfg": 1, "sampler_name": "lcm", "scheduler": "beta", "denoise": 1, "model": ["16", 0], "positive": ["18", 0], "negative": ["7", 0], "latent_image": ["5", 0]}, "class_type": "KSampler", "_meta": {"title": "KSampler"}}, "5": {"inputs": {"width": 5176, "height": 3784, "batch_size": 1}, "class_type": "EmptyLatentImage", "_meta": {"title": "Empty Latent Image"}}, "7": {"inputs": {"text": "Xx_negative_xX", "clip": ["17", 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": "Fast", "images": ["8", 0]}, "class_type": "SaveImage", "_meta": {"title": "Save Image"}}, "14": {"inputs": {"ckpt_name": "SDXLCheckpoint.safetensors"}, "class_type": "CheckpointLoaderSimple", "_meta": {"title": "Load Checkpoint"}}, "16": {"inputs": {"block_number": 3, "downscale_factor": 2, "start_percent": 0, "end_percent": 0.5000000000000001, "downscale_after_skip": true, "downscale_method": "bicubic", "upscale_method": "bicubic", "model": ["17", 0]}, "class_type": "PatchModelAddDownscale", "_meta": {"title": "PatchModelAddDownscale (Kohya Deep Shrink)"}}, "17": {"inputs": {"lora_name": "dmd2_sdxl_4step_lora_fp16.safetensors", "strength_model": 1, "strength_clip": 1, "model": ["14", 0], "clip": ["14", 1]}, "class_type": "LoraLoader", "_meta": {"title": "Load LoRA"}}, "18": {"inputs": {"text": "Xx_positive_xX", "clip": ["17", 1]}, "class_type": "CLIPTextEncode", "_meta": {"title": "CLIP Text Encode (Prompt)"}}}'
)
def import_custom_nodes() -> None:
"""Find all custom nodes in the custom_nodes folder and add those node objects to NODE_CLASS_MAPPINGS
This function sets up a new asyncio event loop, initializes the PromptServer,
creates a PromptQueue, and initializes the custom nodes.
"""
if has_manager:
try:
import manager_core as manager
except ImportError:
print("Could not import manager_core, proceeding without it.")
return
else:
if hasattr(manager, "get_config"):
print("Patching manager_core.get_config to enforce offline mode.")
try:
get_config = manager.get_config
def _get_config(*args, **kwargs):
config = get_config(*args, **kwargs)
config["network_mode"] = "offline"
return config
manager.get_config = _get_config
except Exception as e:
print("Failed to patch manager_core.get_config:", e)
import asyncio
import execution
from nodes import init_extra_nodes
import server
# Creating a new event loop and setting it as the default loop
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
async def inner():
# Creating an instance of PromptServer with the loop
server_instance = server.PromptServer(loop)
execution.PromptQueue(server_instance)
# Initializing custom nodes
await init_extra_nodes(init_custom_nodes=True)
loop.run_until_complete(inner())
_custom_nodes_imported = False
_custom_path_added = False
def main(*func_args, **func_kwargs):
global args, _custom_nodes_imported, _custom_path_added
if __name__ == "__main__":
if args is None:
args = parser.parse_args()
else:
defaults = dict(
(arg, parser.get_default(arg))
for arg in ["queue_size", "comfyui_directory", "output", "disable_metadata"]
+ [
"width1",
"height2",
"batch_size3",
"ckpt_name4",
"lora_name5",
"strength_model6",
"strength_clip7",
"text8",
"text9",
"block_number10",
"downscale_factor11",
"start_percent12",
"end_percent13",
"downscale_after_skip14",
"downscale_method15",
"upscale_method16",
"seed17",
"steps18",
"cfg19",
"sampler_name20",
"scheduler21",
"denoise22",
"filename_prefix23",
]
)
all_args = dict()
all_args.update(defaults)
all_args.update(func_kwargs)
args = argparse.Namespace(**all_args)
with ctx:
if not _custom_path_added:
add_comfyui_directory_to_sys_path()
add_extra_model_paths()
_custom_path_added = True
if not _custom_nodes_imported:
import_custom_nodes()
_custom_nodes_imported = True
from nodes import NODE_CLASS_MAPPINGS
with torch.inference_mode(), ctx:
emptylatentimage = NODE_CLASS_MAPPINGS["EmptyLatentImage"]()
emptylatentimage_5 = emptylatentimage.generate(
width=parse_arg(args.width1),
height=parse_arg(args.height2),
batch_size=parse_arg(args.batch_size3),
)
checkpointloadersimple = NODE_CLASS_MAPPINGS["CheckpointLoaderSimple"]()
checkpointloadersimple_14 = checkpointloadersimple.load_checkpoint(
ckpt_name=parse_arg(args.ckpt_name4)
)
loraloader = NODE_CLASS_MAPPINGS["LoraLoader"]()
loraloader_17 = loraloader.load_lora(
lora_name=parse_arg(args.lora_name5),
strength_model=parse_arg(args.strength_model6),
strength_clip=parse_arg(args.strength_clip7),
model=get_value_at_index(checkpointloadersimple_14, 0),
clip=get_value_at_index(checkpointloadersimple_14, 1),
)
cliptextencode = NODE_CLASS_MAPPINGS["CLIPTextEncode"]()
cliptextencode_7 = cliptextencode.encode(
text=parse_arg(args.text8), clip=get_value_at_index(loraloader_17, 1)
)
cliptextencode_18 = cliptextencode.encode(
text=parse_arg(args.text9), clip=get_value_at_index(loraloader_17, 1)
)
patchmodeladddownscale = NODE_CLASS_MAPPINGS["PatchModelAddDownscale"]()
ksampler = NODE_CLASS_MAPPINGS["KSampler"]()
vaedecode = NODE_CLASS_MAPPINGS["VAEDecode"]()
saveimage = save_image_wrapper(ctx, NODE_CLASS_MAPPINGS["SaveImage"])()
for q in range(args.queue_size):
patchmodeladddownscale_16 = patchmodeladddownscale.patch(
block_number=parse_arg(args.block_number10),
downscale_factor=parse_arg(args.downscale_factor11),
start_percent=parse_arg(args.start_percent12),
end_percent=parse_arg(args.end_percent13),
downscale_after_skip=parse_arg(args.downscale_after_skip14),
downscale_method=parse_arg(args.downscale_method15),
upscale_method=parse_arg(args.upscale_method16),
model=get_value_at_index(loraloader_17, 0),
)
ksampler_3 = ksampler.sample(
seed=randrange(1000000000),
steps=parse_arg(args.steps18),
cfg=parse_arg(args.cfg19),
sampler_name=parse_arg(args.sampler_name20),
scheduler=parse_arg(args.scheduler21),
denoise=parse_arg(args.denoise22),
model=get_value_at_index(patchmodeladddownscale_16, 0),
positive=get_value_at_index(cliptextencode_18, 0),
negative=get_value_at_index(cliptextencode_7, 0),
latent_image=get_value_at_index(emptylatentimage_5, 0),
)
vaedecode_8 = vaedecode.decode(
samples=get_value_at_index(ksampler_3, 0),
vae=get_value_at_index(checkpointloadersimple_14, 2),
)
if __name__ != "__main__":
return dict(
filename_prefix=parse_arg(args.filename_prefix23),
images=get_value_at_index(vaedecode_8, 0),
prompt=PROMPT_DATA,
)
else:
saveimage_9 = saveimage.save_images(
filename_prefix=parse_arg(args.filename_prefix23),
images=get_value_at_index(vaedecode_8, 0),
prompt=PROMPT_DATA,
)
if __name__ == "__main__":
main()
|