Freak-ppa commited on
Commit
f3ed624
·
verified ·
1 Parent(s): 9bd4957

Upload 4 files

Browse files
ComfyUI/README.md ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ComfyUI
2
+ =======
3
+ The most powerful and modular stable diffusion GUI and backend.
4
+ -----------
5
+ ![ComfyUI Screenshot](comfyui_screenshot.png)
6
+
7
+ This ui will let you design and execute advanced stable diffusion pipelines using a graph/nodes/flowchart based interface. For some workflow examples and see what ComfyUI can do you can check out:
8
+ ### [ComfyUI Examples](https://comfyanonymous.github.io/ComfyUI_examples/)
9
+
10
+ ### [Installing ComfyUI](#installing)
11
+
12
+ ## Features
13
+ - Nodes/graph/flowchart interface to experiment and create complex Stable Diffusion workflows without needing to code anything.
14
+ - Fully supports SD1.x, SD2.x, [SDXL](https://comfyanonymous.github.io/ComfyUI_examples/sdxl/), [Stable Video Diffusion](https://comfyanonymous.github.io/ComfyUI_examples/video/), [Stable Cascade](https://comfyanonymous.github.io/ComfyUI_examples/stable_cascade/), [SD3](https://comfyanonymous.github.io/ComfyUI_examples/sd3/) and [Stable Audio](https://comfyanonymous.github.io/ComfyUI_examples/audio/)
15
+ - [Flux](https://comfyanonymous.github.io/ComfyUI_examples/flux/)
16
+ - Asynchronous Queue system
17
+ - Many optimizations: Only re-executes the parts of the workflow that changes between executions.
18
+ - Smart memory management: can automatically run models on GPUs with as low as 1GB vram.
19
+ - Works even if you don't have a GPU with: ```--cpu``` (slow)
20
+ - Can load ckpt, safetensors and diffusers models/checkpoints. Standalone VAEs and CLIP models.
21
+ - Embeddings/Textual inversion
22
+ - [Loras (regular, locon and loha)](https://comfyanonymous.github.io/ComfyUI_examples/lora/)
23
+ - [Hypernetworks](https://comfyanonymous.github.io/ComfyUI_examples/hypernetworks/)
24
+ - Loading full workflows (with seeds) from generated PNG, WebP and FLAC files.
25
+ - Saving/Loading workflows as Json files.
26
+ - Nodes interface can be used to create complex workflows like one for [Hires fix](https://comfyanonymous.github.io/ComfyUI_examples/2_pass_txt2img/) or much more advanced ones.
27
+ - [Area Composition](https://comfyanonymous.github.io/ComfyUI_examples/area_composition/)
28
+ - [Inpainting](https://comfyanonymous.github.io/ComfyUI_examples/inpaint/) with both regular and inpainting models.
29
+ - [ControlNet and T2I-Adapter](https://comfyanonymous.github.io/ComfyUI_examples/controlnet/)
30
+ - [Upscale Models (ESRGAN, ESRGAN variants, SwinIR, Swin2SR, etc...)](https://comfyanonymous.github.io/ComfyUI_examples/upscale_models/)
31
+ - [unCLIP Models](https://comfyanonymous.github.io/ComfyUI_examples/unclip/)
32
+ - [GLIGEN](https://comfyanonymous.github.io/ComfyUI_examples/gligen/)
33
+ - [Model Merging](https://comfyanonymous.github.io/ComfyUI_examples/model_merging/)
34
+ - [LCM models and Loras](https://comfyanonymous.github.io/ComfyUI_examples/lcm/)
35
+ - [SDXL Turbo](https://comfyanonymous.github.io/ComfyUI_examples/sdturbo/)
36
+ - [AuraFlow](https://comfyanonymous.github.io/ComfyUI_examples/aura_flow/)
37
+ - [HunyuanDiT](https://comfyanonymous.github.io/ComfyUI_examples/hunyuan_dit/)
38
+ - Latent previews with [TAESD](#how-to-show-high-quality-previews)
39
+ - Starts up very fast.
40
+ - Works fully offline: will never download anything.
41
+ - [Config file](extra_model_paths.yaml.example) to set the search paths for models.
42
+
43
+ Workflow examples can be found on the [Examples page](https://comfyanonymous.github.io/ComfyUI_examples/)
44
+
45
+ ## Shortcuts
46
+
47
+ | Keybind | Explanation |
48
+ |------------------------------------|--------------------------------------------------------------------------------------------------------------------|
49
+ | Ctrl + Enter | Queue up current graph for generation |
50
+ | Ctrl + Shift + Enter | Queue up current graph as first for generation |
51
+ | Ctrl + Z/Ctrl + Y | Undo/Redo |
52
+ | Ctrl + S | Save workflow |
53
+ | Ctrl + O | Load workflow |
54
+ | Ctrl + A | Select all nodes |
55
+ | Alt + C | Collapse/uncollapse selected nodes |
56
+ | Ctrl + M | Mute/unmute selected nodes |
57
+ | Ctrl + B | Bypass selected nodes (acts like the node was removed from the graph and the wires reconnected through) |
58
+ | Delete/Backspace | Delete selected nodes |
59
+ | Ctrl + Backspace | Delete the current graph |
60
+ | Space | Move the canvas around when held and moving the cursor |
61
+ | Ctrl/Shift + Click | Add clicked node to selection |
62
+ | Ctrl + C/Ctrl + V | Copy and paste selected nodes (without maintaining connections to outputs of unselected nodes) |
63
+ | Ctrl + C/Ctrl + Shift + V | Copy and paste selected nodes (maintaining connections from outputs of unselected nodes to inputs of pasted nodes) |
64
+ | Shift + Drag | Move multiple selected nodes at the same time |
65
+ | Ctrl + D | Load default graph |
66
+ | Alt + `+` | Canvas Zoom in |
67
+ | Alt + `-` | Canvas Zoom out |
68
+ | Ctrl + Shift + LMB + Vertical drag | Canvas Zoom in/out |
69
+ | Q | Toggle visibility of the queue |
70
+ | H | Toggle visibility of history |
71
+ | R | Refresh graph |
72
+ | Double-Click LMB | Open node quick search palette |
73
+
74
+ Ctrl can also be replaced with Cmd instead for macOS users
75
+
76
+ # Installing
77
+
78
+ ## Windows
79
+
80
+ There is a portable standalone build for Windows that should work for running on Nvidia GPUs or for running on your CPU only on the [releases page](https://github.com/comfyanonymous/ComfyUI/releases).
81
+
82
+ ### [Direct link to download](https://github.com/comfyanonymous/ComfyUI/releases/latest/download/ComfyUI_windows_portable_nvidia.7z)
83
+
84
+ Simply download, extract with [7-Zip](https://7-zip.org) and run. Make sure you put your Stable Diffusion checkpoints/models (the huge ckpt/safetensors files) in: ComfyUI\models\checkpoints
85
+
86
+ If you have trouble extracting it, right click the file -> properties -> unblock
87
+
88
+ #### How do I share models between another UI and ComfyUI?
89
+
90
+ See the [Config file](extra_model_paths.yaml.example) to set the search paths for models. In the standalone windows build you can find this file in the ComfyUI directory. Rename this file to extra_model_paths.yaml and edit it with your favorite text editor.
91
+
92
+ ## Jupyter Notebook
93
+
94
+ To run it on services like paperspace, kaggle or colab you can use my [Jupyter Notebook](notebooks/comfyui_colab.ipynb)
95
+
96
+ ## Manual Install (Windows, Linux)
97
+
98
+ Git clone this repo.
99
+
100
+ Put your SD checkpoints (the huge ckpt/safetensors files) in: models/checkpoints
101
+
102
+ Put your VAE in: models/vae
103
+
104
+
105
+ ### AMD GPUs (Linux only)
106
+ AMD users can install rocm and pytorch with pip if you don't have it already installed, this is the command to install the stable version:
107
+
108
+ ```pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/rocm6.0```
109
+
110
+ This is the command to install the nightly with ROCm 6.0 which might have some performance improvements:
111
+
112
+ ```pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/rocm6.1```
113
+
114
+ ### NVIDIA
115
+
116
+ Nvidia users should install stable pytorch using this command:
117
+
118
+ ```pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu121```
119
+
120
+ This is the command to install pytorch nightly instead which might have performance improvements:
121
+
122
+ ```pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/cu124```
123
+
124
+ #### Troubleshooting
125
+
126
+ If you get the "Torch not compiled with CUDA enabled" error, uninstall torch with:
127
+
128
+ ```pip uninstall torch```
129
+
130
+ And install it again with the command above.
131
+
132
+ ### Dependencies
133
+
134
+ Install the dependencies by opening your terminal inside the ComfyUI folder and:
135
+
136
+ ```pip install -r requirements.txt```
137
+
138
+ After this you should have everything installed and can proceed to running ComfyUI.
139
+
140
+ ### Others:
141
+
142
+ #### Intel GPUs
143
+
144
+ Intel GPU support is available for all Intel GPUs supported by Intel's Extension for Pytorch (IPEX) with the support requirements listed in the [Installation](https://intel.github.io/intel-extension-for-pytorch/index.html#installation?platform=gpu) page. Choose your platform and method of install and follow the instructions. The steps are as follows:
145
+
146
+ 1. Start by installing the drivers or kernel listed or newer in the Installation page of IPEX linked above for Windows and Linux if needed.
147
+ 1. Follow the instructions to install [Intel's oneAPI Basekit](https://www.intel.com/content/www/us/en/developer/tools/oneapi/base-toolkit-download.html) for your platform.
148
+ 1. Install the packages for IPEX using the instructions provided in the Installation page for your platform.
149
+ 1. Follow the [ComfyUI manual installation](#manual-install-windows-linux) instructions for Windows and Linux and run ComfyUI normally as described above after everything is installed.
150
+
151
+ Additional discussion and help can be found [here](https://github.com/comfyanonymous/ComfyUI/discussions/476).
152
+
153
+ #### Apple Mac silicon
154
+
155
+ You can install ComfyUI in Apple Mac silicon (M1 or M2) with any recent macOS version.
156
+
157
+ 1. Install pytorch nightly. For instructions, read the [Accelerated PyTorch training on Mac](https://developer.apple.com/metal/pytorch/) Apple Developer guide (make sure to install the latest pytorch nightly).
158
+ 1. Follow the [ComfyUI manual installation](#manual-install-windows-linux) instructions for Windows and Linux.
159
+ 1. Install the ComfyUI [dependencies](#dependencies). If you have another Stable Diffusion UI [you might be able to reuse the dependencies](#i-already-have-another-ui-for-stable-diffusion-installed-do-i-really-have-to-install-all-of-these-dependencies).
160
+ 1. Launch ComfyUI by running `python main.py`
161
+
162
+ > **Note**: Remember to add your models, VAE, LoRAs etc. to the corresponding Comfy folders, as discussed in [ComfyUI manual installation](#manual-install-windows-linux).
163
+
164
+ #### DirectML (AMD Cards on Windows)
165
+
166
+ ```pip install torch-directml``` Then you can launch ComfyUI with: ```python main.py --directml```
167
+
168
+ # Running
169
+
170
+ ```python main.py```
171
+
172
+ ### For AMD cards not officially supported by ROCm
173
+
174
+ Try running it with this command if you have issues:
175
+
176
+ For 6700, 6600 and maybe other RDNA2 or older: ```HSA_OVERRIDE_GFX_VERSION=10.3.0 python main.py```
177
+
178
+ For AMD 7600 and maybe other RDNA3 cards: ```HSA_OVERRIDE_GFX_VERSION=11.0.0 python main.py```
179
+
180
+ # Notes
181
+
182
+ Only parts of the graph that have an output with all the correct inputs will be executed.
183
+
184
+ Only parts of the graph that change from each execution to the next will be executed, if you submit the same graph twice only the first will be executed. If you change the last part of the graph only the part you changed and the part that depends on it will be executed.
185
+
186
+ Dragging a generated png on the webpage or loading one will give you the full workflow including seeds that were used to create it.
187
+
188
+ You can use () to change emphasis of a word or phrase like: (good code:1.2) or (bad code:0.8). The default emphasis for () is 1.1. To use () characters in your actual prompt escape them like \\( or \\).
189
+
190
+ You can use {day|night}, for wildcard/dynamic prompts. With this syntax "{wild|card|test}" will be randomly replaced by either "wild", "card" or "test" by the frontend every time you queue the prompt. To use {} characters in your actual prompt escape them like: \\{ or \\}.
191
+
192
+ Dynamic prompts also support C-style comments, like `// comment` or `/* comment */`.
193
+
194
+ To use a textual inversion concepts/embeddings in a text prompt put them in the models/embeddings directory and use them in the CLIPTextEncode node like this (you can omit the .pt extension):
195
+
196
+ ```embedding:embedding_filename.pt```
197
+
198
+
199
+ ## How to show high-quality previews?
200
+
201
+ Use ```--preview-method auto``` to enable previews.
202
+
203
+ The default installation includes a fast latent preview method that's low-resolution. To enable higher-quality previews with [TAESD](https://github.com/madebyollin/taesd), download the [taesd_decoder.pth](https://github.com/madebyollin/taesd/raw/main/taesd_decoder.pth) (for SD1.x and SD2.x) and [taesdxl_decoder.pth](https://github.com/madebyollin/taesd/raw/main/taesdxl_decoder.pth) (for SDXL) models and place them in the `models/vae_approx` folder. Once they're installed, restart ComfyUI to enable high-quality previews.
204
+
205
+ ## How to use TLS/SSL?
206
+ Generate a self-signed certificate (not appropriate for shared/production use) and key by running the command: `openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -sha256 -days 3650 -nodes -subj "/C=XX/ST=StateName/L=CityName/O=CompanyName/OU=CompanySectionName/CN=CommonNameOrHostname"`
207
+
208
+ Use `--tls-keyfile key.pem --tls-certfile cert.pem` to enable TLS/SSL, the app will now be accessible with `https://...` instead of `http://...`.
209
+
210
+ > Note: Windows users can use [alexisrolland/docker-openssl](https://github.com/alexisrolland/docker-openssl) or one of the [3rd party binary distributions](https://wiki.openssl.org/index.php/Binaries) to run the command example above.
211
+ <br/><br/>If you use a container, note that the volume mount `-v` can be a relative path so `... -v ".\:/openssl-certs" ...` would create the key & cert files in the current directory of your command prompt or powershell terminal.
212
+
213
+ ## Support and dev channel
214
+
215
+ [Matrix space: #comfyui_space:matrix.org](https://app.element.io/#/room/%23comfyui_space%3Amatrix.org) (it's like discord but open source).
216
+
217
+ See also: [https://www.comfy.org/](https://www.comfy.org/)
218
+
219
+ # QA
220
+
221
+ ### Which GPU should I buy for this?
222
+
223
+ [See this page for some recommendations](https://github.com/comfyanonymous/ComfyUI/wiki/Which-GPU-should-I-buy-for-ComfyUI)
224
+
ComfyUI/pytest.ini ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ [pytest]
2
+ markers =
3
+ inference: mark as inference test (deselect with '-m "not inference"')
4
+ testpaths =
5
+ tests
6
+ tests-unit
7
+ addopts = -s
8
+ pythonpath = .
ComfyUI/requirements.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ torchsde
3
+ torchvision
4
+ torchaudio
5
+ einops
6
+ transformers>=4.28.1
7
+ tokenizers>=0.13.3
8
+ sentencepiece
9
+ safetensors>=0.4.2
10
+ aiohttp
11
+ pyyaml
12
+ Pillow
13
+ scipy
14
+ tqdm
15
+ psutil
16
+
17
+ #non essential dependencies:
18
+ kornia>=0.7.1
19
+ spandrel
20
+ soundfile
ComfyUI/server.py ADDED
@@ -0,0 +1,700 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import asyncio
4
+ import traceback
5
+
6
+ import nodes
7
+ import folder_paths
8
+ import execution
9
+ import uuid
10
+ import urllib
11
+ import json
12
+ import glob
13
+ import struct
14
+ import ssl
15
+ import hashlib
16
+ from PIL import Image, ImageOps
17
+ from PIL.PngImagePlugin import PngInfo
18
+ from io import BytesIO
19
+
20
+ import aiohttp
21
+ from aiohttp import web
22
+ import logging
23
+
24
+ import mimetypes
25
+ from comfy.cli_args import args
26
+ import comfy.utils
27
+ import comfy.model_management
28
+ import node_helpers
29
+ from app.frontend_management import FrontendManager
30
+ from app.user_manager import UserManager
31
+
32
+
33
+ class BinaryEventTypes:
34
+ PREVIEW_IMAGE = 1
35
+ UNENCODED_PREVIEW_IMAGE = 2
36
+
37
+ async def send_socket_catch_exception(function, message):
38
+ try:
39
+ await function(message)
40
+ except (aiohttp.ClientError, aiohttp.ClientPayloadError, ConnectionResetError) as err:
41
+ logging.warning("send error: {}".format(err))
42
+
43
+ @web.middleware
44
+ async def cache_control(request: web.Request, handler):
45
+ response: web.Response = await handler(request)
46
+ if request.path.endswith('.js') or request.path.endswith('.css'):
47
+ response.headers.setdefault('Cache-Control', 'no-cache')
48
+ return response
49
+
50
+ def create_cors_middleware(allowed_origin: str):
51
+ @web.middleware
52
+ async def cors_middleware(request: web.Request, handler):
53
+ if request.method == "OPTIONS":
54
+ # Pre-flight request. Reply successfully:
55
+ response = web.Response()
56
+ else:
57
+ response = await handler(request)
58
+
59
+ response.headers['Access-Control-Allow-Origin'] = allowed_origin
60
+ response.headers['Access-Control-Allow-Methods'] = 'POST, GET, DELETE, PUT, OPTIONS'
61
+ response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
62
+ response.headers['Access-Control-Allow-Credentials'] = 'true'
63
+ return response
64
+
65
+ return cors_middleware
66
+
67
+ class PromptServer():
68
+ def __init__(self, loop):
69
+ PromptServer.instance = self
70
+
71
+ mimetypes.init()
72
+ mimetypes.types_map['.js'] = 'application/javascript; charset=utf-8'
73
+
74
+ self.user_manager = UserManager()
75
+ self.supports = ["custom_nodes_from_web"]
76
+ self.prompt_queue = None
77
+ self.loop = loop
78
+ self.messages = asyncio.Queue()
79
+ self.number = 0
80
+
81
+ middlewares = [cache_control]
82
+ if args.enable_cors_header:
83
+ middlewares.append(create_cors_middleware(args.enable_cors_header))
84
+
85
+ max_upload_size = round(args.max_upload_size * 1024 * 1024)
86
+ self.app = web.Application(client_max_size=max_upload_size, middlewares=middlewares)
87
+ self.sockets = dict()
88
+ self.web_root = (
89
+ FrontendManager.init_frontend(args.front_end_version)
90
+ if args.front_end_root is None
91
+ else args.front_end_root
92
+ )
93
+ logging.info(f"[Prompt Server] web root: {self.web_root}")
94
+ routes = web.RouteTableDef()
95
+ self.routes = routes
96
+ self.last_node_id = None
97
+ self.client_id = None
98
+
99
+ self.on_prompt_handlers = []
100
+
101
+ @routes.get('/ws')
102
+ async def websocket_handler(request):
103
+ ws = web.WebSocketResponse()
104
+ await ws.prepare(request)
105
+ sid = request.rel_url.query.get('clientId', '')
106
+ if sid:
107
+ # Reusing existing session, remove old
108
+ self.sockets.pop(sid, None)
109
+ else:
110
+ sid = uuid.uuid4().hex
111
+
112
+ self.sockets[sid] = ws
113
+
114
+ try:
115
+ # Send initial state to the new client
116
+ await self.send("status", { "status": self.get_queue_info(), 'sid': sid }, sid)
117
+ # On reconnect if we are the currently executing client send the current node
118
+ if self.client_id == sid and self.last_node_id is not None:
119
+ await self.send("executing", { "node": self.last_node_id }, sid)
120
+
121
+ async for msg in ws:
122
+ if msg.type == aiohttp.WSMsgType.ERROR:
123
+ logging.warning('ws connection closed with exception %s' % ws.exception())
124
+ finally:
125
+ self.sockets.pop(sid, None)
126
+ return ws
127
+
128
+ @routes.get("/")
129
+ async def get_root(request):
130
+ response = web.FileResponse(os.path.join(self.web_root, "index.html"))
131
+ response.headers['Cache-Control'] = 'no-cache'
132
+ response.headers["Pragma"] = "no-cache"
133
+ response.headers["Expires"] = "0"
134
+ return response
135
+
136
+ @routes.get("/embeddings")
137
+ def get_embeddings(self):
138
+ embeddings = folder_paths.get_filename_list("embeddings")
139
+ return web.json_response(list(map(lambda a: os.path.splitext(a)[0], embeddings)))
140
+
141
+ @routes.get("/extensions")
142
+ async def get_extensions(request):
143
+ files = glob.glob(os.path.join(
144
+ glob.escape(self.web_root), 'extensions/**/*.js'), recursive=True)
145
+
146
+ extensions = list(map(lambda f: "/" + os.path.relpath(f, self.web_root).replace("\\", "/"), files))
147
+
148
+ for name, dir in nodes.EXTENSION_WEB_DIRS.items():
149
+ files = glob.glob(os.path.join(glob.escape(dir), '**/*.js'), recursive=True)
150
+ extensions.extend(list(map(lambda f: "/extensions/" + urllib.parse.quote(
151
+ name) + "/" + os.path.relpath(f, dir).replace("\\", "/"), files)))
152
+
153
+ return web.json_response(extensions)
154
+
155
+ def get_dir_by_type(dir_type):
156
+ if dir_type is None:
157
+ dir_type = "input"
158
+
159
+ if dir_type == "input":
160
+ type_dir = folder_paths.get_input_directory()
161
+ elif dir_type == "temp":
162
+ type_dir = folder_paths.get_temp_directory()
163
+ elif dir_type == "output":
164
+ type_dir = folder_paths.get_output_directory()
165
+
166
+ return type_dir, dir_type
167
+
168
+ def compare_image_hash(filepath, image):
169
+ hasher = node_helpers.hasher()
170
+
171
+ # function to compare hashes of two images to see if it already exists, fix to #3465
172
+ if os.path.exists(filepath):
173
+ a = hasher()
174
+ b = hasher()
175
+ with open(filepath, "rb") as f:
176
+ a.update(f.read())
177
+ b.update(image.file.read())
178
+ image.file.seek(0)
179
+ f.close()
180
+ return a.hexdigest() == b.hexdigest()
181
+ return False
182
+
183
+ def image_upload(post, image_save_function=None):
184
+ image = post.get("image")
185
+ overwrite = post.get("overwrite")
186
+ image_is_duplicate = False
187
+
188
+ image_upload_type = post.get("type")
189
+ upload_dir, image_upload_type = get_dir_by_type(image_upload_type)
190
+
191
+ if image and image.file:
192
+ filename = image.filename
193
+ if not filename:
194
+ return web.Response(status=400)
195
+
196
+ subfolder = post.get("subfolder", "")
197
+ full_output_folder = os.path.join(upload_dir, os.path.normpath(subfolder))
198
+ filepath = os.path.abspath(os.path.join(full_output_folder, filename))
199
+
200
+ if os.path.commonpath((upload_dir, filepath)) != upload_dir:
201
+ return web.Response(status=400)
202
+
203
+ if not os.path.exists(full_output_folder):
204
+ os.makedirs(full_output_folder)
205
+
206
+ split = os.path.splitext(filename)
207
+
208
+ if overwrite is not None and (overwrite == "true" or overwrite == "1"):
209
+ pass
210
+ else:
211
+ i = 1
212
+ while os.path.exists(filepath):
213
+ if compare_image_hash(filepath, image): #compare hash to prevent saving of duplicates with same name, fix for #3465
214
+ image_is_duplicate = True
215
+ break
216
+ filename = f"{split[0]} ({i}){split[1]}"
217
+ filepath = os.path.join(full_output_folder, filename)
218
+ i += 1
219
+
220
+ if not image_is_duplicate:
221
+ if image_save_function is not None:
222
+ image_save_function(image, post, filepath)
223
+ else:
224
+ with open(filepath, "wb") as f:
225
+ f.write(image.file.read())
226
+
227
+ return web.json_response({"name" : filename, "subfolder": subfolder, "type": image_upload_type})
228
+ else:
229
+ return web.Response(status=400)
230
+
231
+ @routes.post("/upload/image")
232
+ async def upload_image(request):
233
+ post = await request.post()
234
+ return image_upload(post)
235
+
236
+
237
+ @routes.post("/upload/mask")
238
+ async def upload_mask(request):
239
+ post = await request.post()
240
+
241
+ def image_save_function(image, post, filepath):
242
+ original_ref = json.loads(post.get("original_ref"))
243
+ filename, output_dir = folder_paths.annotated_filepath(original_ref['filename'])
244
+
245
+ # validation for security: prevent accessing arbitrary path
246
+ if filename[0] == '/' or '..' in filename:
247
+ return web.Response(status=400)
248
+
249
+ if output_dir is None:
250
+ type = original_ref.get("type", "output")
251
+ output_dir = folder_paths.get_directory_by_type(type)
252
+
253
+ if output_dir is None:
254
+ return web.Response(status=400)
255
+
256
+ if original_ref.get("subfolder", "") != "":
257
+ full_output_dir = os.path.join(output_dir, original_ref["subfolder"])
258
+ if os.path.commonpath((os.path.abspath(full_output_dir), output_dir)) != output_dir:
259
+ return web.Response(status=403)
260
+ output_dir = full_output_dir
261
+
262
+ file = os.path.join(output_dir, filename)
263
+
264
+ if os.path.isfile(file):
265
+ with Image.open(file) as original_pil:
266
+ metadata = PngInfo()
267
+ if hasattr(original_pil,'text'):
268
+ for key in original_pil.text:
269
+ metadata.add_text(key, original_pil.text[key])
270
+ original_pil = original_pil.convert('RGBA')
271
+ mask_pil = Image.open(image.file).convert('RGBA')
272
+
273
+ # alpha copy
274
+ new_alpha = mask_pil.getchannel('A')
275
+ original_pil.putalpha(new_alpha)
276
+ original_pil.save(filepath, compress_level=4, pnginfo=metadata)
277
+
278
+ return image_upload(post, image_save_function)
279
+
280
+ @routes.get("/view")
281
+ async def view_image(request):
282
+ if "filename" in request.rel_url.query:
283
+ filename = request.rel_url.query["filename"]
284
+ filename,output_dir = folder_paths.annotated_filepath(filename)
285
+
286
+ # validation for security: prevent accessing arbitrary path
287
+ if filename[0] == '/' or '..' in filename:
288
+ return web.Response(status=400)
289
+
290
+ if output_dir is None:
291
+ type = request.rel_url.query.get("type", "output")
292
+ output_dir = folder_paths.get_directory_by_type(type)
293
+
294
+ if output_dir is None:
295
+ return web.Response(status=400)
296
+
297
+ if "subfolder" in request.rel_url.query:
298
+ full_output_dir = os.path.join(output_dir, request.rel_url.query["subfolder"])
299
+ if os.path.commonpath((os.path.abspath(full_output_dir), output_dir)) != output_dir:
300
+ return web.Response(status=403)
301
+ output_dir = full_output_dir
302
+
303
+ filename = os.path.basename(filename)
304
+ file = os.path.join(output_dir, filename)
305
+
306
+ if os.path.isfile(file):
307
+ if 'preview' in request.rel_url.query:
308
+ with Image.open(file) as img:
309
+ preview_info = request.rel_url.query['preview'].split(';')
310
+ image_format = preview_info[0]
311
+ if image_format not in ['webp', 'jpeg'] or 'a' in request.rel_url.query.get('channel', ''):
312
+ image_format = 'webp'
313
+
314
+ quality = 90
315
+ if preview_info[-1].isdigit():
316
+ quality = int(preview_info[-1])
317
+
318
+ buffer = BytesIO()
319
+ if image_format in ['jpeg'] or request.rel_url.query.get('channel', '') == 'rgb':
320
+ img = img.convert("RGB")
321
+ img.save(buffer, format=image_format, quality=quality)
322
+ buffer.seek(0)
323
+
324
+ return web.Response(body=buffer.read(), content_type=f'image/{image_format}',
325
+ headers={"Content-Disposition": f"filename=\"{filename}\""})
326
+
327
+ if 'channel' not in request.rel_url.query:
328
+ channel = 'rgba'
329
+ else:
330
+ channel = request.rel_url.query["channel"]
331
+
332
+ if channel == 'rgb':
333
+ with Image.open(file) as img:
334
+ if img.mode == "RGBA":
335
+ r, g, b, a = img.split()
336
+ new_img = Image.merge('RGB', (r, g, b))
337
+ else:
338
+ new_img = img.convert("RGB")
339
+
340
+ buffer = BytesIO()
341
+ new_img.save(buffer, format='PNG')
342
+ buffer.seek(0)
343
+
344
+ return web.Response(body=buffer.read(), content_type='image/png',
345
+ headers={"Content-Disposition": f"filename=\"{filename}\""})
346
+
347
+ elif channel == 'a':
348
+ with Image.open(file) as img:
349
+ if img.mode == "RGBA":
350
+ _, _, _, a = img.split()
351
+ else:
352
+ a = Image.new('L', img.size, 255)
353
+
354
+ # alpha img
355
+ alpha_img = Image.new('RGBA', img.size)
356
+ alpha_img.putalpha(a)
357
+ alpha_buffer = BytesIO()
358
+ alpha_img.save(alpha_buffer, format='PNG')
359
+ alpha_buffer.seek(0)
360
+
361
+ return web.Response(body=alpha_buffer.read(), content_type='image/png',
362
+ headers={"Content-Disposition": f"filename=\"{filename}\""})
363
+ else:
364
+ return web.FileResponse(file, headers={"Content-Disposition": f"filename=\"{filename}\""})
365
+
366
+ return web.Response(status=404)
367
+
368
+ @routes.get("/view_metadata/{folder_name}")
369
+ async def view_metadata(request):
370
+ folder_name = request.match_info.get("folder_name", None)
371
+ if folder_name is None:
372
+ return web.Response(status=404)
373
+ if not "filename" in request.rel_url.query:
374
+ return web.Response(status=404)
375
+
376
+ filename = request.rel_url.query["filename"]
377
+ if not filename.endswith(".safetensors"):
378
+ return web.Response(status=404)
379
+
380
+ safetensors_path = folder_paths.get_full_path(folder_name, filename)
381
+ if safetensors_path is None:
382
+ return web.Response(status=404)
383
+ out = comfy.utils.safetensors_header(safetensors_path, max_size=1024*1024)
384
+ if out is None:
385
+ return web.Response(status=404)
386
+ dt = json.loads(out)
387
+ if not "__metadata__" in dt:
388
+ return web.Response(status=404)
389
+ return web.json_response(dt["__metadata__"])
390
+
391
+ @routes.get("/system_stats")
392
+ async def get_queue(request):
393
+ device = comfy.model_management.get_torch_device()
394
+ device_name = comfy.model_management.get_torch_device_name(device)
395
+ vram_total, torch_vram_total = comfy.model_management.get_total_memory(device, torch_total_too=True)
396
+ vram_free, torch_vram_free = comfy.model_management.get_free_memory(device, torch_free_too=True)
397
+ system_stats = {
398
+ "system": {
399
+ "os": os.name,
400
+ "python_version": sys.version,
401
+ "embedded_python": os.path.split(os.path.split(sys.executable)[0])[1] == "python_embeded"
402
+ },
403
+ "devices": [
404
+ {
405
+ "name": device_name,
406
+ "type": device.type,
407
+ "index": device.index,
408
+ "vram_total": vram_total,
409
+ "vram_free": vram_free,
410
+ "torch_vram_total": torch_vram_total,
411
+ "torch_vram_free": torch_vram_free,
412
+ }
413
+ ]
414
+ }
415
+ return web.json_response(system_stats)
416
+
417
+ @routes.get("/prompt")
418
+ async def get_prompt(request):
419
+ return web.json_response(self.get_queue_info())
420
+
421
+ def node_info(node_class):
422
+ obj_class = nodes.NODE_CLASS_MAPPINGS[node_class]
423
+ info = {}
424
+ info['input'] = obj_class.INPUT_TYPES()
425
+ info['output'] = obj_class.RETURN_TYPES
426
+ info['output_is_list'] = obj_class.OUTPUT_IS_LIST if hasattr(obj_class, 'OUTPUT_IS_LIST') else [False] * len(obj_class.RETURN_TYPES)
427
+ info['output_name'] = obj_class.RETURN_NAMES if hasattr(obj_class, 'RETURN_NAMES') else info['output']
428
+ info['name'] = node_class
429
+ info['display_name'] = nodes.NODE_DISPLAY_NAME_MAPPINGS[node_class] if node_class in nodes.NODE_DISPLAY_NAME_MAPPINGS.keys() else node_class
430
+ info['description'] = obj_class.DESCRIPTION if hasattr(obj_class,'DESCRIPTION') else ''
431
+ info['python_module'] = getattr(obj_class, "RELATIVE_PYTHON_MODULE", "nodes")
432
+ info['category'] = 'sd'
433
+ if hasattr(obj_class, 'OUTPUT_NODE') and obj_class.OUTPUT_NODE == True:
434
+ info['output_node'] = True
435
+ else:
436
+ info['output_node'] = False
437
+
438
+ if hasattr(obj_class, 'CATEGORY'):
439
+ info['category'] = obj_class.CATEGORY
440
+ return info
441
+
442
+ @routes.get("/object_info")
443
+ async def get_object_info(request):
444
+ out = {}
445
+ for x in nodes.NODE_CLASS_MAPPINGS:
446
+ try:
447
+ out[x] = node_info(x)
448
+ except Exception as e:
449
+ logging.error(f"[ERROR] An error occurred while retrieving information for the '{x}' node.")
450
+ logging.error(traceback.format_exc())
451
+ return web.json_response(out)
452
+
453
+ @routes.get("/object_info/{node_class}")
454
+ async def get_object_info_node(request):
455
+ node_class = request.match_info.get("node_class", None)
456
+ out = {}
457
+ if (node_class is not None) and (node_class in nodes.NODE_CLASS_MAPPINGS):
458
+ out[node_class] = node_info(node_class)
459
+ return web.json_response(out)
460
+
461
+ @routes.get("/history")
462
+ async def get_history(request):
463
+ max_items = request.rel_url.query.get("max_items", None)
464
+ if max_items is not None:
465
+ max_items = int(max_items)
466
+ return web.json_response(self.prompt_queue.get_history(max_items=max_items))
467
+
468
+ @routes.get("/history/{prompt_id}")
469
+ async def get_history(request):
470
+ prompt_id = request.match_info.get("prompt_id", None)
471
+ return web.json_response(self.prompt_queue.get_history(prompt_id=prompt_id))
472
+
473
+ @routes.get("/queue")
474
+ async def get_queue(request):
475
+ queue_info = {}
476
+ current_queue = self.prompt_queue.get_current_queue()
477
+ queue_info['queue_running'] = current_queue[0]
478
+ queue_info['queue_pending'] = current_queue[1]
479
+ return web.json_response(queue_info)
480
+
481
+ @routes.post("/prompt")
482
+ async def post_prompt(request):
483
+ logging.info("got prompt")
484
+ resp_code = 200
485
+ out_string = ""
486
+ json_data = await request.json()
487
+ json_data = self.trigger_on_prompt(json_data)
488
+
489
+ if "number" in json_data:
490
+ number = float(json_data['number'])
491
+ else:
492
+ number = self.number
493
+ if "front" in json_data:
494
+ if json_data['front']:
495
+ number = -number
496
+
497
+ self.number += 1
498
+
499
+ if "prompt" in json_data:
500
+ prompt = json_data["prompt"]
501
+ valid = execution.validate_prompt(prompt)
502
+ extra_data = {}
503
+ if "extra_data" in json_data:
504
+ extra_data = json_data["extra_data"]
505
+
506
+ if "client_id" in json_data:
507
+ extra_data["client_id"] = json_data["client_id"]
508
+ if valid[0]:
509
+ prompt_id = str(uuid.uuid4())
510
+ outputs_to_execute = valid[2]
511
+ self.prompt_queue.put((number, prompt_id, prompt, extra_data, outputs_to_execute))
512
+ response = {"prompt_id": prompt_id, "number": number, "node_errors": valid[3]}
513
+ return web.json_response(response)
514
+ else:
515
+ logging.warning("invalid prompt: {}".format(valid[1]))
516
+ return web.json_response({"error": valid[1], "node_errors": valid[3]}, status=400)
517
+ else:
518
+ return web.json_response({"error": "no prompt", "node_errors": []}, status=400)
519
+
520
+ @routes.post("/queue")
521
+ async def post_queue(request):
522
+ json_data = await request.json()
523
+ if "clear" in json_data:
524
+ if json_data["clear"]:
525
+ self.prompt_queue.wipe_queue()
526
+ if "delete" in json_data:
527
+ to_delete = json_data['delete']
528
+ for id_to_delete in to_delete:
529
+ delete_func = lambda a: a[1] == id_to_delete
530
+ self.prompt_queue.delete_queue_item(delete_func)
531
+
532
+ return web.Response(status=200)
533
+
534
+ @routes.post("/interrupt")
535
+ async def post_interrupt(request):
536
+ nodes.interrupt_processing()
537
+ return web.Response(status=200)
538
+
539
+ @routes.post("/free")
540
+ async def post_free(request):
541
+ json_data = await request.json()
542
+ unload_models = json_data.get("unload_models", False)
543
+ free_memory = json_data.get("free_memory", False)
544
+ if unload_models:
545
+ self.prompt_queue.set_flag("unload_models", unload_models)
546
+ if free_memory:
547
+ self.prompt_queue.set_flag("free_memory", free_memory)
548
+ return web.Response(status=200)
549
+
550
+ @routes.post("/history")
551
+ async def post_history(request):
552
+ json_data = await request.json()
553
+ if "clear" in json_data:
554
+ if json_data["clear"]:
555
+ self.prompt_queue.wipe_history()
556
+ if "delete" in json_data:
557
+ to_delete = json_data['delete']
558
+ for id_to_delete in to_delete:
559
+ self.prompt_queue.delete_history_item(id_to_delete)
560
+
561
+ return web.Response(status=200)
562
+
563
+ def add_routes(self):
564
+ self.user_manager.add_routes(self.routes)
565
+
566
+ # Prefix every route with /api for easier matching for delegation.
567
+ # This is very useful for frontend dev server, which need to forward
568
+ # everything except serving of static files.
569
+ # Currently both the old endpoints without prefix and new endpoints with
570
+ # prefix are supported.
571
+ api_routes = web.RouteTableDef()
572
+ for route in self.routes:
573
+ # Custom nodes might add extra static routes. Only process non-static
574
+ # routes to add /api prefix.
575
+ if isinstance(route, web.RouteDef):
576
+ api_routes.route(route.method, "/api" + route.path)(route.handler, **route.kwargs)
577
+ self.app.add_routes(api_routes)
578
+ self.app.add_routes(self.routes)
579
+
580
+ for name, dir in nodes.EXTENSION_WEB_DIRS.items():
581
+ self.app.add_routes([
582
+ web.static('/extensions/' + urllib.parse.quote(name), dir),
583
+ ])
584
+
585
+ self.app.add_routes([
586
+ web.static('/', self.web_root),
587
+ ])
588
+
589
+ def get_queue_info(self):
590
+ prompt_info = {}
591
+ exec_info = {}
592
+ exec_info['queue_remaining'] = self.prompt_queue.get_tasks_remaining()
593
+ prompt_info['exec_info'] = exec_info
594
+ return prompt_info
595
+
596
+ async def send(self, event, data, sid=None):
597
+ if event == BinaryEventTypes.UNENCODED_PREVIEW_IMAGE:
598
+ await self.send_image(data, sid=sid)
599
+ elif isinstance(data, (bytes, bytearray)):
600
+ await self.send_bytes(event, data, sid)
601
+ else:
602
+ await self.send_json(event, data, sid)
603
+
604
+ def encode_bytes(self, event, data):
605
+ if not isinstance(event, int):
606
+ raise RuntimeError(f"Binary event types must be integers, got {event}")
607
+
608
+ packed = struct.pack(">I", event)
609
+ message = bytearray(packed)
610
+ message.extend(data)
611
+ return message
612
+
613
+ async def send_image(self, image_data, sid=None):
614
+ image_type = image_data[0]
615
+ image = image_data[1]
616
+ max_size = image_data[2]
617
+ if max_size is not None:
618
+ if hasattr(Image, 'Resampling'):
619
+ resampling = Image.Resampling.BILINEAR
620
+ else:
621
+ resampling = Image.ANTIALIAS
622
+
623
+ image = ImageOps.contain(image, (max_size, max_size), resampling)
624
+ type_num = 1
625
+ if image_type == "JPEG":
626
+ type_num = 1
627
+ elif image_type == "PNG":
628
+ type_num = 2
629
+
630
+ bytesIO = BytesIO()
631
+ header = struct.pack(">I", type_num)
632
+ bytesIO.write(header)
633
+ image.save(bytesIO, format=image_type, quality=95, compress_level=1)
634
+ preview_bytes = bytesIO.getvalue()
635
+ await self.send_bytes(BinaryEventTypes.PREVIEW_IMAGE, preview_bytes, sid=sid)
636
+
637
+ async def send_bytes(self, event, data, sid=None):
638
+ message = self.encode_bytes(event, data)
639
+
640
+ if sid is None:
641
+ sockets = list(self.sockets.values())
642
+ for ws in sockets:
643
+ await send_socket_catch_exception(ws.send_bytes, message)
644
+ elif sid in self.sockets:
645
+ await send_socket_catch_exception(self.sockets[sid].send_bytes, message)
646
+
647
+ async def send_json(self, event, data, sid=None):
648
+ message = {"type": event, "data": data}
649
+
650
+ if sid is None:
651
+ sockets = list(self.sockets.values())
652
+ for ws in sockets:
653
+ await send_socket_catch_exception(ws.send_json, message)
654
+ elif sid in self.sockets:
655
+ await send_socket_catch_exception(self.sockets[sid].send_json, message)
656
+
657
+ def send_sync(self, event, data, sid=None):
658
+ self.loop.call_soon_threadsafe(
659
+ self.messages.put_nowait, (event, data, sid))
660
+
661
+ def queue_updated(self):
662
+ self.send_sync("status", { "status": self.get_queue_info() })
663
+
664
+ async def publish_loop(self):
665
+ while True:
666
+ msg = await self.messages.get()
667
+ await self.send(*msg)
668
+
669
+ async def start(self, address, port, verbose=True, call_on_start=None):
670
+ runner = web.AppRunner(self.app, access_log=None)
671
+ await runner.setup()
672
+ ssl_ctx = None
673
+ scheme = "http"
674
+ if args.tls_keyfile and args.tls_certfile:
675
+ ssl_ctx = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_SERVER, verify_mode=ssl.CERT_NONE)
676
+ ssl_ctx.load_cert_chain(certfile=args.tls_certfile,
677
+ keyfile=args.tls_keyfile)
678
+ scheme = "https"
679
+
680
+ site = web.TCPSite(runner, address, port, ssl_context=ssl_ctx)
681
+ await site.start()
682
+
683
+ if verbose:
684
+ logging.info("Starting server\n")
685
+ logging.info("To see the GUI go to: {}://{}:{}".format(scheme, address, port))
686
+ if call_on_start is not None:
687
+ call_on_start(scheme, address, port)
688
+
689
+ def add_on_prompt_handler(self, handler):
690
+ self.on_prompt_handlers.append(handler)
691
+
692
+ def trigger_on_prompt(self, json_data):
693
+ for handler in self.on_prompt_handlers:
694
+ try:
695
+ json_data = handler(json_data)
696
+ except Exception as e:
697
+ logging.warning(f"[ERROR] An error occurred during the on_prompt_handler processing")
698
+ logging.warning(traceback.format_exc())
699
+
700
+ return json_data