fred-dev/comfy_ui_ali
0
1import argparse2import enum3import os4import comfy.options5 6 7class EnumAction(argparse.Action):8 """9 Argparse action for handling Enums10 """11 def __init__(self, **kwargs):12 # Pop off the type value13 enum_type = kwargs.pop("type", None)14 15 # Ensure an Enum subclass is provided16 if enum_type is None:17 raise ValueError("type must be assigned an Enum when using EnumAction")18 if not issubclass(enum_type, enum.Enum):19 raise TypeError("type must be an Enum when using EnumAction")20 21 # Generate choices from the Enum22 choices = tuple(e.value for e in enum_type)23 kwargs.setdefault("choices", choices)24 kwargs.setdefault("metavar", f"[{','.join(list(choices))}]")25 26 super(EnumAction, self).__init__(**kwargs)27 28 self._enum = enum_type29 30 def __call__(self, parser, namespace, values, option_string=None):31 # Convert value back into an Enum32 value = self._enum(values)33 setattr(namespace, self.dest, value)34 35 36parser = argparse.ArgumentParser()37 38parser.add_argument("--listen", type=str, default="0.0.0.0", metavar="IP", nargs="?", const="0.0.0.0,::", help="Specify the IP address to listen on (default: 127.0.0.1). You can give a list of ip addresses by separating them with a comma like: 127.2.2.2,127.3.3.3 If --listen is provided without an argument, it defaults to 0.0.0.0,:: (listens on all ipv4 and ipv6)")39parser.add_argument("--port", type=int, default=7860, help="Set the listen port.")40parser.add_argument("--tls-keyfile", type=str, help="Path to TLS (SSL) key file. Enables TLS, makes app accessible at https://... requires --tls-certfile to function")41parser.add_argument("--tls-certfile", type=str, help="Path to TLS (SSL) certificate file. Enables TLS, makes app accessible at https://... requires --tls-keyfile to function")42parser.add_argument("--enable-cors-header", type=str, default=None, metavar="ORIGIN", nargs="?", const="*", help="Enable CORS (Cross-Origin Resource Sharing) with optional origin or allow all with default '*'.")43parser.add_argument("--max-upload-size", type=float, default=100, help="Set the maximum upload size in MB.")44 45parser.add_argument("--base-directory", type=str, default=None, help="Set the ComfyUI base directory for models, custom_nodes, input, output, temp, and user directories.")46parser.add_argument("--extra-model-paths-config", type=str, default=None, metavar="PATH", nargs='+', action='append', help="Load one or more extra_model_paths.yaml files.")47parser.add_argument("--output-directory", type=str, default=None, help="Set the ComfyUI output directory. Overrides --base-directory.")48parser.add_argument("--temp-directory", type=str, default=None, help="Set the ComfyUI temp directory (default is in the ComfyUI directory). Overrides --base-directory.")49parser.add_argument("--input-directory", type=str, default=None, help="Set the ComfyUI input directory. Overrides --base-directory.")50parser.add_argument("--auto-launch", action="store_true", help="Automatically launch ComfyUI in the default browser.")51parser.add_argument("--disable-auto-launch", action="store_true", help="Disable auto launching the browser.")52parser.add_argument("--cuda-device", type=int, default=None, metavar="DEVICE_ID", help="Set the id of the cuda device this instance will use.")53cm_group = parser.add_mutually_exclusive_group()54cm_group.add_argument("--cuda-malloc", action="store_true", help="Enable cudaMallocAsync (enabled by default for torch 2.0 and up).")55cm_group.add_argument("--disable-cuda-malloc", action="store_true", help="Disable cudaMallocAsync.")56 57 58fp_group = parser.add_mutually_exclusive_group()59fp_group.add_argument("--force-fp32", action="store_true", help="Force fp32 (If this makes your GPU work better please report it).")60fp_group.add_argument("--force-fp16", action="store_true", help="Force fp16.")61 62fpunet_group = parser.add_mutually_exclusive_group()63fpunet_group.add_argument("--fp32-unet", action="store_true", help="Run the diffusion model in fp32.")64fpunet_group.add_argument("--fp64-unet", action="store_true", help="Run the diffusion model in fp64.")65fpunet_group.add_argument("--bf16-unet", action="store_true", help="Run the diffusion model in bf16.")66fpunet_group.add_argument("--fp16-unet", action="store_true", help="Run the diffusion model in fp16")67fpunet_group.add_argument("--fp8_e4m3fn-unet", action="store_true", help="Store unet weights in fp8_e4m3fn.")68fpunet_group.add_argument("--fp8_e5m2-unet", action="store_true", help="Store unet weights in fp8_e5m2.")69 70fpvae_group = parser.add_mutually_exclusive_group()71fpvae_group.add_argument("--fp16-vae", action="store_true", help="Run the VAE in fp16, might cause black images.")72fpvae_group.add_argument("--fp32-vae", action="store_true", help="Run the VAE in full precision fp32.")73fpvae_group.add_argument("--bf16-vae", action="store_true", help="Run the VAE in bf16.")74 75parser.add_argument("--cpu-vae", action="store_true", help="Run the VAE on the CPU.")76 77fpte_group = parser.add_mutually_exclusive_group()78fpte_group.add_argument("--fp8_e4m3fn-text-enc", action="store_true", help="Store text encoder weights in fp8 (e4m3fn variant).")79fpte_group.add_argument("--fp8_e5m2-text-enc", action="store_true", help="Store text encoder weights in fp8 (e5m2 variant).")80fpte_group.add_argument("--fp16-text-enc", action="store_true", help="Store text encoder weights in fp16.")81fpte_group.add_argument("--fp32-text-enc", action="store_true", help="Store text encoder weights in fp32.")82 83parser.add_argument("--force-channels-last", action="store_true", help="Force channels last format when inferencing the models.")84 85parser.add_argument("--directml", type=int, nargs="?", metavar="DIRECTML_DEVICE", const=-1, help="Use torch-directml.")86 87parser.add_argument("--oneapi-device-selector", type=str, default=None, metavar="SELECTOR_STRING", help="Sets the oneAPI device(s) this instance will use.")88parser.add_argument("--disable-ipex-optimize", action="store_true", help="Disables ipex.optimize default when loading models with Intel's Extension for Pytorch.")89 90class LatentPreviewMethod(enum.Enum):91 NoPreviews = "none"92 Auto = "auto"93 Latent2RGB = "latent2rgb"94 TAESD = "taesd"95 96parser.add_argument("--preview-method", type=LatentPreviewMethod, default=LatentPreviewMethod.NoPreviews, help="Default preview method for sampler nodes.", action=EnumAction)97 98parser.add_argument("--preview-size", type=int, default=512, help="Sets the maximum preview size for sampler nodes.")99 100cache_group = parser.add_mutually_exclusive_group()101cache_group.add_argument("--cache-classic", action="store_true", help="Use the old style (aggressive) caching.")102cache_group.add_argument("--cache-lru", type=int, default=0, help="Use LRU caching with a maximum of N node results cached. May use more RAM/VRAM.")103 104attn_group = parser.add_mutually_exclusive_group()105attn_group.add_argument("--use-split-cross-attention", action="store_true", help="Use the split cross attention optimization. Ignored when xformers is used.")106attn_group.add_argument("--use-quad-cross-attention", action="store_true", help="Use the sub-quadratic cross attention optimization . Ignored when xformers is used.")107attn_group.add_argument("--use-pytorch-cross-attention", action="store_true", help="Use the new pytorch 2.0 cross attention function.")108attn_group.add_argument("--use-sage-attention", action="store_true", help="Use sage attention.")109attn_group.add_argument("--use-flash-attention", action="store_true", help="Use FlashAttention.")110 111parser.add_argument("--disable-xformers", action="store_true", help="Disable xformers.")112 113upcast = parser.add_mutually_exclusive_group()114upcast.add_argument("--force-upcast-attention", action="store_true", help="Force enable attention upcasting, please report if it fixes black images.")115upcast.add_argument("--dont-upcast-attention", action="store_true", help="Disable all upcasting of attention. Should be unnecessary except for debugging.")116 117 118vram_group = parser.add_mutually_exclusive_group()119vram_group.add_argument("--gpu-only", action="store_true", help="Store and run everything (text encoders/CLIP models, etc... on the GPU).")120vram_group.add_argument("--highvram", action="store_true", help="By default models will be unloaded to CPU memory after being used. This option keeps them in GPU memory.")121vram_group.add_argument("--normalvram", action="store_true", help="Used to force normal vram use if lowvram gets automatically enabled.")122vram_group.add_argument("--lowvram", action="store_true", help="Split the unet in parts to use less vram.")123vram_group.add_argument("--novram", action="store_true", help="When lowvram isn't enough.")124vram_group.add_argument("--cpu", action="store_true", help="To use the CPU for everything (slow).")125 126parser.add_argument("--reserve-vram", type=float, default=None, help="Set the amount of vram in GB you want to reserve for use by your OS/other software. By default some amount is reserved depending on your OS.")127 128 129parser.add_argument("--default-hashing-function", type=str, choices=['md5', 'sha1', 'sha256', 'sha512'], default='sha256', help="Allows you to choose the hash function to use for duplicate filename / contents comparison. Default is sha256.")130 131parser.add_argument("--disable-smart-memory", action="store_true", help="Force ComfyUI to agressively offload to regular ram instead of keeping models in vram when it can.")132parser.add_argument("--deterministic", action="store_true", help="Make pytorch use slower deterministic algorithms when it can. Note that this might not make images deterministic in all cases.")133 134class PerformanceFeature(enum.Enum):135 Fp16Accumulation = "fp16_accumulation"136 Fp8MatrixMultiplication = "fp8_matrix_mult"137 138parser.add_argument("--fast", nargs="*", type=PerformanceFeature, help="Enable some untested and potentially quality deteriorating optimizations. --fast with no arguments enables everything. You can pass a list specific optimizations if you only want to enable specific ones. Current valid optimizations: fp16_accumulation fp8_matrix_mult")139 140parser.add_argument("--dont-print-server", action="store_true", help="Don't print server output.")141parser.add_argument("--quick-test-for-ci", action="store_true", help="Quick test for CI.")142parser.add_argument("--windows-standalone-build", action="store_true", help="Windows standalone build: Enable convenient things that most people using the standalone windows build will probably enjoy (like auto opening the page on startup).")143 144parser.add_argument("--disable-metadata", action="store_true", help="Disable saving prompt metadata in files.")145parser.add_argument("--disable-all-custom-nodes", action="store_true", help="Disable loading all custom nodes.")146 147parser.add_argument("--multi-user", action="store_true", help="Enables per-user storage.")148 149parser.add_argument("--verbose", default='INFO', const='DEBUG', nargs="?", choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], help='Set the logging level')150parser.add_argument("--log-stdout", action="store_true", help="Send normal process output to stdout instead of stderr (default).")151 152# The default built-in provider hosted under web/153DEFAULT_VERSION_STRING = "comfyanonymous/ComfyUI@latest"154 155parser.add_argument(156 "--front-end-version",157 type=str,158 default=DEFAULT_VERSION_STRING,159 help="""160 Specifies the version of the frontend to be used. This command needs internet connectivity to query and161 download available frontend implementations from GitHub releases.162 163 The version string should be in the format of:164 [repoOwner]/[repoName]@[version]165 where version is one of: "latest" or a valid version number (e.g. "1.0.0")166 """,167)168 169def is_valid_directory(path: str) -> str:170 """Validate if the given path is a directory, and check permissions."""171 if not os.path.exists(path):172 raise argparse.ArgumentTypeError(f"The path '{path}' does not exist.")173 if not os.path.isdir(path):174 raise argparse.ArgumentTypeError(f"'{path}' is not a directory.")175 if not os.access(path, os.R_OK):176 raise argparse.ArgumentTypeError(f"You do not have read permissions for '{path}'.")177 return path178 179parser.add_argument(180 "--front-end-root",181 type=is_valid_directory,182 default=None,183 help="The local filesystem path to the directory where the frontend is located. Overrides --front-end-version.",184)185 186parser.add_argument("--user-directory", type=is_valid_directory, default=None, help="Set the ComfyUI user directory with an absolute path. Overrides --base-directory.")187 188parser.add_argument("--enable-compress-response-body", action="store_true", help="Enable compressing response body.")189 190if comfy.options.args_parsing:191 args = parser.parse_args()192else:193 args = parser.parse_args([])194 195if args.windows_standalone_build:196 args.auto_launch = True197 198if args.disable_auto_launch:199 args.auto_launch = False200 201if args.force_fp16:202 args.fp16_unet = True203 204 205# '--fast' is not provided, use an empty set206if args.fast is None:207 args.fast = set()208# '--fast' is provided with an empty list, enable all optimizations209elif args.fast == []:210 args.fast = set(PerformanceFeature)211# '--fast' is provided with a list of performance features, use that list212else:213 args.fast = set(args.fast)214 