From 7d20d3a1485ba00cff53cd2f0839b829e505be9b Mon Sep 17 00:00:00 2001 From: ml-favorfit-develop <122414946+MiddleKD@users.noreply.github.com> Date: Mon, 17 Jun 2024 13:24:50 +0900 Subject: [PATCH] first commit --- .env | 3 + .gitignore | 9 +- README.md | 240 +--------- ai_api.py | 155 ++++++ async_server.py | 257 ++++++++++ make_models_symlink.py | 39 ++ middlk_tools.py | 172 +++++++ server.py | 4 +- user/default/comfy.settings.json | 3 + user/default/comfy.templates.json | 0 web/lib/litegraph.core.js | 76 +++ web/scripts/app.js | 8 +- workflows/I2I_basic.json | 126 +++++ workflows/I2I_stylecomp.json | 176 +++++++ workflows/I2V_svdxt.json | 169 +++++++ workflows/T2I_juggernaut.json | 111 +++++ workflows/VFI_anime.json | 54 +++ workflows/favorfit_kandinsky_adapter_api.json | 316 ++++++++++++ .../favorfit_kandinsky_text_enhance_api.json | 449 ++++++++++++++++++ 19 files changed, 2127 insertions(+), 240 deletions(-) create mode 100644 .env create mode 100644 ai_api.py create mode 100644 async_server.py create mode 100644 make_models_symlink.py create mode 100644 middlk_tools.py create mode 100644 user/default/comfy.settings.json create mode 100644 user/default/comfy.templates.json create mode 100644 workflows/I2I_basic.json create mode 100644 workflows/I2I_stylecomp.json create mode 100644 workflows/I2V_svdxt.json create mode 100644 workflows/T2I_juggernaut.json create mode 100644 workflows/VFI_anime.json create mode 100644 workflows/favorfit_kandinsky_adapter_api.json create mode 100644 workflows/favorfit_kandinsky_text_enhance_api.json diff --git a/.env b/.env new file mode 100644 index 000000000..e956e5232 --- /dev/null +++ b/.env @@ -0,0 +1,3 @@ +HOST=127.0.0.1 +PORT=8000 +COMFYUI_SERVERS=127.0.0.1:8188,127.0.0.1:8189 \ No newline at end of file diff --git a/.gitignore b/.gitignore index 9f0389241..0b764e112 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,8 @@ __pycache__/ *.py[cod] /output/ /input/ -!/input/example.png +# !/input/example.png # middlek +!/input/**/*example* /models/ /temp/ /custom_nodes/ @@ -15,4 +16,8 @@ venv/ !/web/extensions/logging.js.example !/web/extensions/core/ /tests-ui/data/object_info.json -/user/ \ No newline at end of file +# /user/ # middlek +*.log +/client_app/ +!client_app/test_wf/ +!client_app/client.py \ No newline at end of file diff --git a/README.md b/README.md index a40dd07dd..0ff2a71c3 100644 --- a/README.md +++ b/README.md @@ -1,236 +1,4 @@ -ComfyUI -======= -The most powerful and modular stable diffusion GUI and backend. ------------ -![ComfyUI Screenshot](comfyui_screenshot.png) - -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: -### [ComfyUI Examples](https://comfyanonymous.github.io/ComfyUI_examples/) - -### [Installing ComfyUI](#installing) - -## Features -- Nodes/graph/flowchart interface to experiment and create complex Stable Diffusion workflows without needing to code anything. -- 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/) and [SD3](https://comfyanonymous.github.io/ComfyUI_examples/sd3/) -- Asynchronous Queue system -- Many optimizations: Only re-executes the parts of the workflow that changes between executions. -- Command line option: ```--lowvram``` to make it work on GPUs with less than 3GB vram (enabled automatically on GPUs with low vram) -- Works even if you don't have a GPU with: ```--cpu``` (slow) -- Can load ckpt, safetensors and diffusers models/checkpoints. Standalone VAEs and CLIP models. -- Embeddings/Textual inversion -- [Loras (regular, locon and loha)](https://comfyanonymous.github.io/ComfyUI_examples/lora/) -- [Hypernetworks](https://comfyanonymous.github.io/ComfyUI_examples/hypernetworks/) -- Loading full workflows (with seeds) from generated PNG files. -- Saving/Loading workflows as Json files. -- 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. -- [Area Composition](https://comfyanonymous.github.io/ComfyUI_examples/area_composition/) -- [Inpainting](https://comfyanonymous.github.io/ComfyUI_examples/inpaint/) with both regular and inpainting models. -- [ControlNet and T2I-Adapter](https://comfyanonymous.github.io/ComfyUI_examples/controlnet/) -- [Upscale Models (ESRGAN, ESRGAN variants, SwinIR, Swin2SR, etc...)](https://comfyanonymous.github.io/ComfyUI_examples/upscale_models/) -- [unCLIP Models](https://comfyanonymous.github.io/ComfyUI_examples/unclip/) -- [GLIGEN](https://comfyanonymous.github.io/ComfyUI_examples/gligen/) -- [Model Merging](https://comfyanonymous.github.io/ComfyUI_examples/model_merging/) -- [LCM models and Loras](https://comfyanonymous.github.io/ComfyUI_examples/lcm/) -- [SDXL Turbo](https://comfyanonymous.github.io/ComfyUI_examples/sdturbo/) -- Latent previews with [TAESD](#how-to-show-high-quality-previews) -- Starts up very fast. -- Works fully offline: will never download anything. -- [Config file](extra_model_paths.yaml.example) to set the search paths for models. - -Workflow examples can be found on the [Examples page](https://comfyanonymous.github.io/ComfyUI_examples/) - -## Shortcuts - -| Keybind | Explanation | -|------------------------------------|--------------------------------------------------------------------------------------------------------------------| -| Ctrl + Enter | Queue up current graph for generation | -| Ctrl + Shift + Enter | Queue up current graph as first for generation | -| Ctrl + Z/Ctrl + Y | Undo/Redo | -| Ctrl + S | Save workflow | -| Ctrl + O | Load workflow | -| Ctrl + A | Select all nodes | -| Alt + C | Collapse/uncollapse selected nodes | -| Ctrl + M | Mute/unmute selected nodes | -| Ctrl + B | Bypass selected nodes (acts like the node was removed from the graph and the wires reconnected through) | -| Delete/Backspace | Delete selected nodes | -| Ctrl + Backspace | Delete the current graph | -| Space | Move the canvas around when held and moving the cursor | -| Ctrl/Shift + Click | Add clicked node to selection | -| Ctrl + C/Ctrl + V | Copy and paste selected nodes (without maintaining connections to outputs of unselected nodes) | -| Ctrl + C/Ctrl + Shift + V | Copy and paste selected nodes (maintaining connections from outputs of unselected nodes to inputs of pasted nodes) | -| Shift + Drag | Move multiple selected nodes at the same time | -| Ctrl + D | Load default graph | -| Alt + `+` | Canvas Zoom in | -| Alt + `-` | Canvas Zoom out | -| Ctrl + Shift + LMB + Vertical drag | Canvas Zoom in/out | -| Q | Toggle visibility of the queue | -| H | Toggle visibility of history | -| R | Refresh graph | -| Double-Click LMB | Open node quick search palette | - -Ctrl can also be replaced with Cmd instead for macOS users - -# Installing - -## Windows - -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). - -### [Direct link to download](https://github.com/comfyanonymous/ComfyUI/releases/download/latest/ComfyUI_windows_portable_nvidia_cu121_or_cpu.7z) - -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 - -If you have trouble extracting it, right click the file -> properties -> unblock - -#### How do I share models between another UI and ComfyUI? - -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. - -## Jupyter Notebook - -To run it on services like paperspace, kaggle or colab you can use my [Jupyter Notebook](notebooks/comfyui_colab.ipynb) - -## Manual Install (Windows, Linux) - -Git clone this repo. - -Put your SD checkpoints (the huge ckpt/safetensors files) in: models/checkpoints - -Put your VAE in: models/vae - - -### AMD GPUs (Linux only) -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: - -```pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/rocm6.0``` - -This is the command to install the nightly with ROCm 6.0 which might have some performance improvements: - -```pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/rocm6.1``` - -### NVIDIA - -Nvidia users should install stable pytorch using this command: - -```pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu121``` - -This is the command to install pytorch nightly instead which might have performance improvements: - -```pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/cu124``` - -#### Troubleshooting - -If you get the "Torch not compiled with CUDA enabled" error, uninstall torch with: - -```pip uninstall torch``` - -And install it again with the command above. - -### Dependencies - -Install the dependencies by opening your terminal inside the ComfyUI folder and: - -```pip install -r requirements.txt``` - -After this you should have everything installed and can proceed to running ComfyUI. - -### Others: - -#### Intel GPUs - -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: - -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. -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. -1. Install the packages for IPEX using the instructions provided in the Installation page for your platform. -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. - -Additional discussion and help can be found [here](https://github.com/comfyanonymous/ComfyUI/discussions/476). - -#### Apple Mac silicon - -You can install ComfyUI in Apple Mac silicon (M1 or M2) with any recent macOS version. - -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). -1. Follow the [ComfyUI manual installation](#manual-install-windows-linux) instructions for Windows and Linux. -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). -1. Launch ComfyUI by running `python main.py` - -> **Note**: Remember to add your models, VAE, LoRAs etc. to the corresponding Comfy folders, as discussed in [ComfyUI manual installation](#manual-install-windows-linux). - -#### DirectML (AMD Cards on Windows) - -```pip install torch-directml``` Then you can launch ComfyUI with: ```python main.py --directml``` - -### I already have another UI for Stable Diffusion installed do I really have to install all of these dependencies? - -You don't. If you have another UI installed and working with its own python venv you can use that venv to run ComfyUI. You can open up your favorite terminal and activate it: - -```source path_to_other_sd_gui/venv/bin/activate``` - -or on Windows: - -With Powershell: ```"path_to_other_sd_gui\venv\Scripts\Activate.ps1"``` - -With cmd.exe: ```"path_to_other_sd_gui\venv\Scripts\activate.bat"``` - -And then you can use that terminal to run ComfyUI without installing any dependencies. Note that the venv folder might be called something else depending on the SD UI. - -# Running - -```python main.py``` - -### For AMD cards not officially supported by ROCm - -Try running it with this command if you have issues: - -For 6700, 6600 and maybe other RDNA2 or older: ```HSA_OVERRIDE_GFX_VERSION=10.3.0 python main.py``` - -For AMD 7600 and maybe other RDNA3 cards: ```HSA_OVERRIDE_GFX_VERSION=11.0.0 python main.py``` - -# Notes - -Only parts of the graph that have an output with all the correct inputs will be executed. - -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. - -Dragging a generated png on the webpage or loading one will give you the full workflow including seeds that were used to create it. - -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 \\). - -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 \\}. - -Dynamic prompts also support C-style comments, like `// comment` or `/* comment */`. - -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): - -```embedding:embedding_filename.pt``` - - -## How to show high-quality previews? - -Use ```--preview-method auto``` to enable previews. - -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. - -## How to use TLS/SSL? -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"` - -Use `--tls-keyfile key.pem --tls-certfile cert.pem` to enable TLS/SSL, the app will now be accessible with `https://...` instead of `http://...`. - -> 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. -

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. - -## Support and dev channel - -[Matrix space: #comfyui_space:matrix.org](https://app.element.io/#/room/%23comfyui_space%3Amatrix.org) (it's like discord but open source). - -# QA - -### Why did you make this? - -I wanted to learn how Stable Diffusion worked in detail. I also wanted something clean and powerful that would let me experiment with SD without restrictions. - -### Who is this for? - -This is for anyone that wants to make complex workflows with SD or that wants to learn more how SD works. The interface follows closely how SD works and the code should be much more simple to understand than other SD UIs. +# comfy ui server +--- +comfy ui의 포크입니다. Bridge server 기능을 추가하고, +이를 활용한 어플리케이션을 개발 중입니다. \ No newline at end of file diff --git a/ai_api.py b/ai_api.py new file mode 100644 index 000000000..59987250f --- /dev/null +++ b/ai_api.py @@ -0,0 +1,155 @@ +import os, json, io +import urllib +import magic +from requests_toolbelt import MultipartEncoder + + +# Assume mime type +def get_mime_type(file_path): + mime = magic.Magic(mime=True) + mime_type = mime.from_file(file_path) + if mime_type is None: + mime_type = 'application/octet-stream' + return mime_type + +def get_mime_type_from_binary(binary_data): + mime = magic.Magic(mime=True) + mime_type = mime.from_buffer(binary_data) + if mime_type is None: + mime_type = 'application/octet-stream' + return mime_type + + +# API +def queue_prompt(prompt, client_id, server_address): + p = {"prompt": prompt, "client_id": client_id} + headers = {'Content-Type': 'application/json'} + data = json.dumps(p).encode('utf-8') + req = urllib.request.Request(f"http://{server_address}/prompt", data=data, headers=headers) + return json.loads(urllib.request.urlopen(req).read()) + +def get_queue_state(server_address): + with urllib.request.urlopen(f"http://{server_address}/queue") as response: + return json.loads(response.read()) + +def get_history(client_id, server_address): + with urllib.request.urlopen(f"http://{server_address}/history/{client_id}") as response: + return json.loads(response.read()) + +def upload_image(file_data, name, server_address, image_type="input", overwrite=False): + + mime_type = get_mime_type_from_binary(file_data) + multipart_data = MultipartEncoder( + fields={ + 'image': (name, file_data, mime_type), + 'type': image_type, + 'overwrite': str(overwrite).lower() + } + ) + headers = {'Content-Type': multipart_data.content_type} + + request = urllib.request.Request(f"http://{server_address}/upload/image", data=multipart_data, headers=headers) + with urllib.request.urlopen(request) as response: + return response.read() + +# Parsing text +def get_parsed_input_nodes(workflow_json): + if isinstance(workflow_json, str): + with open(workflow_json, mode="r") as f: + workflow_json = json.load(f) + + parsed_input_nodes = {} + + for node_number in workflow_json: + favorfit_inputs = [] + + cur_node = workflow_json[node_number] + meta_data = cur_node["_meta"].get("Favorfitinput", None) + if meta_data is not None: favorfit_inputs.extend(meta_data.split(",")) + # if "seed" in cur_node["inputs"].keys(): favorfit_inputs.append("seed") + + for favorfit_input in favorfit_inputs: + if favorfit_input is not None: + input_value = cur_node["inputs"].get(favorfit_input, None) + input_type = type(input_value) + + if (input_type == None) or (input_value == ''): + raise ValueError(f"{node_number}:{favorfit_input}, is wrong data('{input_type}', '{input_value}')") + + parsed_input_nodes[f"{node_number}/{favorfit_input}"] = { + "type":input_type.__name__, + "title":cur_node["_meta"]["title"], + "class":cur_node["class_type"], + "default":cur_node["inputs"][favorfit_input] + } + return parsed_input_nodes + +def parse_workflow_prompt(workflow_path, **kwargs): + + with open(workflow_path, mode="r") as f: + workflow_json = json.load(f) + + parsed_input_nodes = get_parsed_input_nodes(workflow_json) + prompt = workflow_json + + for node_id_and_key, node_info in parsed_input_nodes.items(): + node_id, input_key = node_id_and_key.split("/") + + input_value = kwargs.get(node_id_and_key, None) + if input_value is not None: + if type(input_value).__name__ != node_info["type"]: + raise ValueError(f"'{node_id_and_key}' need to have type of {node_info["type"]} but got {type(input_value)} from {input_value})") + else: + input_value = node_info.get("default", None) + prompt[node_id]["inputs"][input_key] = input_value + + return prompt + +def parse_outputs(outputs:dict): + file_paths, mime_types, file_contents = [], [], [] + + output_nodes = list(outputs.values()) + for output_node in output_nodes: + for key, values in output_node.items(): + for value in values: + if not isinstance(value, dict): continue + if value.get("filename", None) == None: continue + + file_path = os.path.join("./output", value["filename"]) + if not os.path.isfile(file_path): continue + mime_type = get_mime_type(file_path) + with open(file_path, 'rb') as f: + file_content = f.read() + + file_paths.append(file_path) + mime_types.append(mime_type) + file_contents.append(file_content) + + return file_paths, mime_types, file_contents + + +# File system +def save_binary_file(data, file_name, directory='./input', return_root_dir=False): + # Ensure the directory exists + if not os.path.exists(directory): + os.makedirs(directory) + + # Split the file name into base name and extension + base_name, extension = os.path.splitext(file_name) + new_file_name = file_name + + # Check if the file exists and find a new name if it does + counter = 1 + while os.path.exists(os.path.join(directory, new_file_name)): + new_file_name = f"{base_name} ({counter}){extension}" + counter += 1 + + # Save the binary data to the file + save_path = os.path.join(directory, new_file_name) + with open(save_path, 'wb') as file: + file.write(data) + + if return_root_dir==True: + return save_path + else: + return new_file_name diff --git a/async_server.py b/async_server.py new file mode 100644 index 000000000..765b13361 --- /dev/null +++ b/async_server.py @@ -0,0 +1,257 @@ +from ai_api import (queue_prompt, + get_history, + get_queue_state, + get_parsed_input_nodes, + parse_workflow_prompt, + parse_outputs, + save_binary_file) +import asyncio +import aiohttp +import logging +from aiohttp import web +import json, os + +class BridgeServer(): + + def __init__(self, loop, server_address:list) -> None: + self.sockets_res = {} + self.sockets_req = {} + self.sid_server_map = {} + self.ws_connection_status = {} + self.loop = loop + self.server_address = server_address + + async def send_socket_catch_exception(self, sid, message): + try: + await self.sockets_res[sid].send_json(message) + self.ws_connection_status[sid] = message.get("status", None) + except (aiohttp.ClientError, aiohttp.ClientPayloadError, ConnectionResetError) as err: + logging.warning(f"send error: {err} / {message}") + + async def init_app(self): + app = web.Application() + app.add_routes([ + web.post('/generate-based-workflow', self.generate_based_workflow), + web.get('/ws', self.websocket_connection), + web.get("/", self.main_page), + web.get("/history", self.get_history), + web.post("/upload/image", self.upload_image), + web.post("/workflow-info", self.workflow_info) + ]) + return app + + async def track_progress(self, sid): + ws_req = self.sockets_req[sid] + finished_nodes = [] + + while True: + out = await ws_req.receive() + out = out.data + + if isinstance(out, str): + message = json.loads(out) + if message['type'] == 'progress': + data = message['data'] + current_step = data['value'] + progress_message = { + 'status': 'progress_update', + 'details': f'In K-Sampler -> Step: {current_step} of {data["max"]}' + } + await self.send_socket_catch_exception(sid, progress_message) + + if message['type'] == 'execution_cached': + data = message['data'] + for itm in data['nodes']: + if itm not in finished_nodes: + finished_nodes.append(itm) + progress_message = { + 'status': 'progress_update', + 'details': f'Progress: {len(finished_nodes)} / {len(data['nodes'])} Tasks done' + } + await self.send_socket_catch_exception(sid, progress_message) + + if message['type'] == 'executing': + data = message['data'] + if data['node'] not in finished_nodes: + finished_nodes.append(data['node']) + progress_message = { + 'status': 'progress_update', + 'details': f'Progress: {len(finished_nodes)} / ) Tasks done' + } + await self.send_socket_catch_exception(sid, progress_message) + + if data['node'] is None and data['prompt_id'] == sid: + completion_message = { + 'status': 'closed', + 'details': 'Execution is done' + } + await self.send_socket_catch_exception(sid, completion_message) + break # Execution is done + elif out == None: + completion_message = { + 'status': 'closed', + 'details': 'comfy ui out is None' + } + await self.send_socket_catch_exception(sid, completion_message) + break + else: + continue + return + + + async def websocket_connection(self, request): + sid = request.rel_url.query.get('clientId', '') + + async with aiohttp.ClientSession() as session: + server_address = await self.get_not_busy_server_address() + self.sid_server_map[sid] = server_address + + ws_res = web.WebSocketResponse() + ws_req = await session.ws_connect(f"ws://{server_address}/ws?clientId={sid}") + + self.sockets_res[sid] = ws_res + self.sockets_req[sid] = ws_req + + try: + await self.sockets_res[sid].prepare(request) + + await self.send_socket_catch_exception(sid, {"status":"connected", "details":"web socket connected"}) + self.ws_connection_status[sid] = "connected" + + task = asyncio.create_task(self.track_progress(sid)) + + while True: + out = await ws_res.receive() + out = out.data + + if isinstance(out, str): + message = json.loads(out) + if message['status'] == 'error': + break + if self.ws_connection_status[sid] == "closed": + break + + await task + + except aiohttp.ServerDisconnectedError as e: + await self.send_socket_catch_exception(sid, {"status":"error", "details":"server disconnected"}) + + except Exception as e: + await self.send_socket_catch_exception(sid, {"status":"error", "details":str(e)}) + + finally: + await self.send_socket_catch_exception(sid, {"status":"closed", "details":"connection will be closed"}) + await self.sockets_req[sid].close() + await self.sockets_res[sid].close() + self.sockets_req.pop(sid, None) + self.sockets_res.pop(sid, None) + self.ws_connection_status.pop(sid, None) + + async def get_not_busy_server_address(self): + queue_lenghs = [] + for server_address in self.server_address: + try: + queue_state = get_queue_state(server_address) + except Exception as e: + print(f"{server_address} in error {e}") + + queue_length = sum([len(cur) for cur in queue_state.values()]) + queue_lenghs.append(queue_length) + + target_server_address = self.server_address[queue_lenghs.index(min(queue_lenghs))] + + return target_server_address + + async def generate_based_workflow(self, request): + data = await request.json() + sid = request.rel_url.query.get('clientId', '') + + workflow = data.pop("workflow", None) + kwargs = data + + prompt = parse_workflow_prompt(workflow, **kwargs) + prompt = queue_prompt(prompt, sid, self.sid_server_map[sid]) + + return web.Response(status=200) + + async def upload_image(self, request): + reader = await request.multipart() + + fns={} + async for part in reader: + file_name = part.headers.get('Content-Disposition', '').split('filename=')[1].strip('"') + file_data = await part.read() + + fn = save_binary_file(file_data, file_name) + fns[part.headers.get("ori_file_id", None)] = fn + + return web.Response( + status=200, + body=json.dumps(fns), + headers={"Content-Type": "application/json"} + ) + + async def get_history(self, request): + sid = request.rel_url.query.get('clientId', '') + + history = get_history(sid, self.sid_server_map[sid]) + history = history.get(sid, None) + self.sid_server_map.pop(sid, None) + + if history is not None: + output = history["outputs"], + if isinstance(output, tuple): + output = (output) + + writer = aiohttp.MultipartWriter("form-data") + + file_paths, mime_types, file_contents = parse_outputs(output[0]) + for file_path, mime_type, file_content in zip(file_paths, mime_types, file_contents): + + headers = {'Content-Type': mime_type, 'Content-Disposition': f'attachment; filename="{file_path.split("/")[-1]}"'} + writer.append(file_content, headers) + + headers = { + 'Content-Type': writer.content_type, + } + + return web.Response( + status=200, + body=writer, + headers=headers + ) + else: + return web.Response( + status=204, + text="No contents with that client id." + ) + + async def workflow_info(self, request): + data = await request.json() + + workflow = data.pop("workflow", None) + node_info = get_parsed_input_nodes(workflow) + + return web.Response(status=200, body=json.dumps(node_info), content_type="application/json") + + async def main_page(self, request): + return web.Response(text="Hello, this is Favorfit Bridge Server!") + +def main(): + from dotenv import load_dotenv + load_dotenv() + + servers_str = os.getenv('COMFYUI_SERVERS') + host = os.getenv("HOST") + port = os.getenv("PORT") + + server_list = servers_str.split(',') if servers_str else [] + + loop = asyncio.get_event_loop() + server = BridgeServer(loop, server_list) + app = loop.run_until_complete(server.init_app()) + web.run_app(app, host=host, port=int(port)) + + +if __name__ == '__main__': + main() diff --git a/make_models_symlink.py b/make_models_symlink.py new file mode 100644 index 000000000..b883d09c7 --- /dev/null +++ b/make_models_symlink.py @@ -0,0 +1,39 @@ +import os + +def create_symbolic_links(src_dir, dst_dir): + # Ensure the destination directory exists + if not os.path.exists(dst_dir): + os.makedirs(dst_dir) + + # Walk through the source directory + for root, dirs, files in os.walk(src_dir): + # Compute the relative path from the source directory + rel_path = os.path.relpath(root, src_dir) + dest_root = os.path.join(dst_dir, rel_path) + + # Ensure the corresponding destination directory exists + if not os.path.exists(dest_root): + os.makedirs(dest_root) + + # Create symbolic links for the files + for file in files: + src_file = os.path.join(root, file) + dest_file = os.path.join(dest_root, file) + + if os.path.exists(dest_file): + os.remove(dest_file) + + os.symlink(src_file, dest_file) + print(f"Created symbolic link: {dest_file} -> {src_file}") + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument("--src", type=str) + args = parser.parse_args() + + # Example usage + src_directory = args.src + dst_directory = './models' + create_symbolic_links(src_directory, dst_directory) diff --git a/middlk_tools.py b/middlk_tools.py new file mode 100644 index 000000000..b5b40898d --- /dev/null +++ b/middlk_tools.py @@ -0,0 +1,172 @@ +import os +import aiohttp +from ai_api import get_mime_type_from_binary + +import json + +def log_parameters_to_json(file_name="parameters.json"): + def convert_value_to_str(value): + if hasattr(value, "__dict__"): + return {attr: str(getattr(value, attr)) for attr in value.__dict__} + else: + return str(value) + + # Retrieve the local variables from the calling function's scope + import inspect + frame = inspect.currentframe().f_back + local_vars = frame.f_locals + + # Create a list to hold the detailed parameter information + detailed_params = [] + + # Print each parameter and its type, and collect the detailed information + for key, value in local_vars.items(): + detail = { + "name": key, + "value": convert_value_to_str(value), + "type": type(value).__name__ + } + detailed_params.append(detail) + print(f"{key}: {value}, type: {type(value)}") + + # Save detailed parameter information to a JSON file + with open(file_name, 'w') as f: + json.dump(detailed_params, f, indent=4) + + +import tracemalloc +def trace_memory(): + # 메모리 추적 시작 + tracemalloc.start() + + # 코드 실행 (예시) + x = [i for i in range(1000000)] # 큰 리스트 생성 + + # 현재 메모리 스냅샷 생성 + snapshot = tracemalloc.take_snapshot() + + # 가장 많은 메모리를 사용하고 있는 top 10 개의 객체 출력 + top_stats = snapshot.statistics('lineno') + + print("[ Top 10 ]") + for stat in top_stats[:10]: + print(stat) + +def test(a): + return a + 1 +async def upload_file(file_path, client_id, server_address): + url = f"http://{server_address}/upload/image?clientId={client_id}" + + with open(file_path, 'rb') as file: + file_data = file.read() + + async with aiohttp.ClientSession() as session: + writer = aiohttp.MultipartWriter('form-data') + writer.append(file_data, headers={'Content-Disposition': + f'inline; \ + filename="{os.path.basename(file_path)}"; \ + name="uploaded_content"', + 'Content-type':get_mime_type_from_binary(file_data)}) + writer.append(file_data, headers={'Content-Disposition': + f'inline; \ + filename="{os.path.basename(file_path)}"; \ + name="uploaded_content2"', + 'Content-type':get_mime_type_from_binary(file_data)}) + + async with session.post(url, data=writer) as response: + if response.status == 200: + response_data = await response.text() + print(response_data) + else: + print(f"Error uploading file: {response.status}") + +# 클라이언트 코드에서 사용 예시 +async def main(): + client_id = '100000' + image_path = '/home/mlfavorfit/Downloads/mask.jpg' + response = await upload_file(image_path, client_id, "0.0.0.0:8080") + print(response) + + +import subprocess +import json +from pathlib import Path + +class PackageFilter: + def __init__(self, project_path, necessary_package_list, output_file="requirements_production.txt"): + self.project_path = project_path + self.output_file = output_file + self.necessary_package_list = necessary_package_list + + def run_command(self, command): + result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True) + if result.returncode != 0: + raise Exception(f"Command failed: {command}\n{result.stderr}") + return result.stdout + + def get_installed_packages(self): + output = self.run_command("pip freeze") + return {line.split('==')[0]: line for line in output.splitlines()} + + def get_project_dependencies(self): + self.run_command(f"pipreqs {self.project_path} --force --savepath requirements_temp.txt") + with open("requirements_temp.txt", "r") as file: + project_requirements = {line.split('==')[0] for line in file} + Path("requirements_temp.txt").unlink() + return project_requirements + + def get_dependency_tree(self): + output = self.run_command("pipdeptree --json") + return json.loads(output) + + def filter_needed_packages(self): + installed_packages = self.get_installed_packages() + project_dependencies = self.get_project_dependencies() + dependency_tree = self.get_dependency_tree() + + needed_packages = set() + + def add_package(package_name): + if package_name in project_dependencies and package_name not in needed_packages: + needed_packages.add(package_name) + for dependency in dependency_tree: + if dependency['package']['key'] == package_name: + for req in dependency.get('dependencies', []): + add_package(req['package_name']) + + for package in project_dependencies: + add_package(package) + + return {pkg: installed_packages[pkg] for pkg in needed_packages if pkg in installed_packages} + + def write_requirements_file(self): + needed_packages = self.filter_needed_packages() + + with open(self.output_file, "w") as file: + for package in needed_packages.values(): + file.write(f"{package}\n") + + with open(self.output_file, "a") as file: + for package in self.necessary_package_list: + file.write(f"{package}\n") + + print(f"Filtered requirements written to {self.output_file}") + + +# 비동기 이벤트 루프 실행 +if __name__ == "__main__": + # import asyncio + # asyncio.run(main()) + + filter_instance = PackageFilter( + project_path=".", + necessary_package_list=[ + "open-clip-torch==2.24.0", + "lightning==2.2.5", + "insightface==0.7.3", + "cupy-cuda12x==12.3.0", + "python-magic==0.4.27", + "requests_toolbelt==1.0.0", + ], + output_file="requirements_production.txt") + filter_instance.write_requirements_file() \ No newline at end of file diff --git a/server.py b/server.py index bab3b0600..eed337d92 100644 --- a/server.py +++ b/server.py @@ -474,7 +474,9 @@ class PromptServer(): if "client_id" in json_data: extra_data["client_id"] = json_data["client_id"] if valid[0]: - prompt_id = str(uuid.uuid4()) + # prompt_id = str(uuid.uuid4()) + prompt_id = json_data["client_id"] # middlek + outputs_to_execute = valid[2] self.prompt_queue.put((number, prompt_id, prompt, extra_data, outputs_to_execute)) response = {"prompt_id": prompt_id, "number": number, "node_errors": valid[3]} diff --git a/user/default/comfy.settings.json b/user/default/comfy.settings.json new file mode 100644 index 000000000..364da1a1c --- /dev/null +++ b/user/default/comfy.settings.json @@ -0,0 +1,3 @@ +{ + "Comfy.DevMode": true +} \ No newline at end of file diff --git a/user/default/comfy.templates.json b/user/default/comfy.templates.json new file mode 100644 index 000000000..e69de29bb diff --git a/web/lib/litegraph.core.js b/web/lib/litegraph.core.js index 427a62b59..f1d9f843e 100644 --- a/web/lib/litegraph.core.js +++ b/web/lib/litegraph.core.js @@ -1,5 +1,68 @@ //packer version +async function getNodeInputs(node) { + const inputs = {}; + + // Store all widget values + const widgets = node.widgets; + if (widgets) { + for (const i in widgets) { + const widget = widgets[i]; + if (!widget.options || widget.options.serialize !== false) { + inputs[widget.name] = widget.serializeValue ? await widget.serializeValue(node, i) : widget.value; + } + } + } + + // Store all node links + for (let i in node.inputs) { + let parent = node.getInputNode(i); + if (parent) { + let link = node.getInputLink(i); + while (parent.mode === 4 || parent.isVirtualNode) { + let found = false; + if (parent.isVirtualNode) { + link = parent.getInputLink(link.origin_slot); + if (link) { + parent = parent.getInputNode(link.target_slot); + if (parent) { + found = true; + } + } + } else if (link && parent.mode === 4) { + let allInputs = [link.origin_slot]; + if (parent.inputs) { + allInputs = allInputs.concat(Object.keys(parent.inputs)); + for (let parentInput of allInputs) { + if (parent.inputs[parentInput]?.type === node.inputs[i].type) { + link = parent.getInputLink(parentInput); + if (link) { + parent = parent.getInputNode(parentInput); + } + found = true; + break; + } + } + } + } + + if (!found) { + break; + } + } + + if (link) { + if (parent?.updateLink) { + link = parent.updateLink(link); + } + if (link) { + inputs[node.inputs[i].name] = [String(link.origin_id), parseInt(link.origin_slot)]; + } + } + } + } + return Object.keys(inputs); +} // middlek (function(global) { // ************************************************************* @@ -12578,6 +12641,9 @@ LGraphNode.prototype.executeAction = function(action) case "Title": node.title = value; break; + case "Favorfit input": // middlek + node.Favorfitinput = value; + break; case "Mode": var kV = Object.values(LiteGraph.NODE_MODES).indexOf(value); if (kV>=0 && LiteGraph.NODE_MODES[kV]){ @@ -12604,6 +12670,16 @@ LGraphNode.prototype.executeAction = function(action) panel.addWidget( "string", "Title", node.title, {}, fUpdate); + (async () => { // middlek + try { + const inputs = await getNodeInputs(node); + const inputsList = Object.values(inputs); + panel.addWidget("string", "Favorfit input", inputsList, {}, fUpdate); + } catch (error) { + console.error("Error while getting inputs:", error); + } + })(); // middlek + panel.addWidget( "combo", "Mode", LiteGraph.NODE_MODES[node.mode], {values: LiteGraph.NODE_MODES}, fUpdate); var nodeCol = ""; diff --git a/web/scripts/app.js b/web/scripts/app.js index f96d197a8..c412bb197 100644 --- a/web/scripts/app.js +++ b/web/scripts/app.js @@ -2040,7 +2040,12 @@ export class ComfyApp { if (this.ui.settings.getSettingValue("Comfy.DevMode")) { // Ignored by the backend. node_data["_meta"] = { - title: node.title, + title: node.title + }; + + // Favorfitinput이 존재하고 길이가 0이 아닌 경우 추가 + if (node.Favorfitinput && node.Favorfitinput.length > 0) { + node_data["_meta"].Favorfitinput = node.Favorfitinput; // middlek } } @@ -2239,6 +2244,7 @@ export class ComfyApp { const node = LiteGraph.createNode(data.class_type); node.id = isNaN(+id) ? id : +id; node.title = data._meta?.title ?? node.title + node.Favorfitinput = data._meta?.Favorfitinput ?? node.Favorfitinput // middlek graph.add(node); } diff --git a/workflows/I2I_basic.json b/workflows/I2I_basic.json new file mode 100644 index 000000000..df315c6d3 --- /dev/null +++ b/workflows/I2I_basic.json @@ -0,0 +1,126 @@ +{ + "3": { + "inputs": { + "seed": 1029869223633439, + "steps": 22, + "cfg": 8, + "sampler_name": "dpmpp_3m_sde", + "scheduler": "karras", + "denoise": 0.6, + "model": [ + "4", + 0 + ], + "positive": [ + "6", + 0 + ], + "negative": [ + "7", + 0 + ], + "latent_image": [ + "11", + 0 + ] + }, + "class_type": "KSampler", + "_meta": { + "title": "KSampler", + "Favorfitinput": "seed,denoise" + } + }, + "4": { + "inputs": { + "ckpt_name": "juggernaut_reborn.safetensors" + }, + "class_type": "CheckpointLoaderSimple", + "_meta": { + "title": "Load Checkpoint" + } + }, + "6": { + "inputs": { + "text": "beautiful scenery nature glass bottle landscape, , purple galaxy bottle,", + "clip": [ + "4", + 1 + ] + }, + "class_type": "CLIPTextEncode", + "_meta": { + "title": "CLIP Text Encode (Prompt)", + "Favorfitinput": "text" + } + }, + "7": { + "inputs": { + "text": "text, watermark", + "clip": [ + "4", + 1 + ] + }, + "class_type": "CLIPTextEncode", + "_meta": { + "title": "CLIP Text Encode (Prompt)", + "Favorfitinput": "text" + } + }, + "8": { + "inputs": { + "samples": [ + "3", + 0 + ], + "vae": [ + "4", + 2 + ] + }, + "class_type": "VAEDecode", + "_meta": { + "title": "VAE Decode" + } + }, + "9": { + "inputs": { + "filename_prefix": "ComfyUI", + "images": [ + "8", + 0 + ] + }, + "class_type": "SaveImage", + "_meta": { + "title": "Save Image" + } + }, + "10": { + "inputs": { + "image": "i2i_example.jpg", + "upload": "image" + }, + "class_type": "LoadImage", + "_meta": { + "title": "Load Image", + "Favorfitinput": "image" + } + }, + "11": { + "inputs": { + "pixels": [ + "10", + 0 + ], + "vae": [ + "4", + 2 + ] + }, + "class_type": "VAEEncode", + "_meta": { + "title": "VAE Encode" + } + } +} \ No newline at end of file diff --git a/workflows/I2I_stylecomp.json b/workflows/I2I_stylecomp.json new file mode 100644 index 000000000..345992b6b --- /dev/null +++ b/workflows/I2I_stylecomp.json @@ -0,0 +1,176 @@ +{ + "3": { + "inputs": { + "seed": 626308590510521, + "steps": 30, + "cfg": 6.5, + "sampler_name": "dpmpp_2m_sde", + "scheduler": "karras", + "denoise": 0.7000000000000001, + "model": [ + "15", + 0 + ], + "positive": [ + "6", + 0 + ], + "negative": [ + "7", + 0 + ], + "latent_image": [ + "5", + 0 + ] + }, + "class_type": "KSampler", + "_meta": { + "title": "KSampler", + "Favorfitinput": "seed,denoise" + } + }, + "4": { + "inputs": { + "ckpt_name": "realvisxlV40_v40LightningBakedvae.safetensors" + }, + "class_type": "CheckpointLoaderSimple", + "_meta": { + "title": "Load Checkpoint" + } + }, + "5": { + "inputs": { + "width": 1024, + "height": 1024, + "batch_size": 1 + }, + "class_type": "EmptyLatentImage", + "_meta": { + "title": "Empty Latent Image" + } + }, + "6": { + "inputs": { + "text": "sports car running fast on the highway\n\nhigh quality, detailed", + "clip": [ + "4", + 1 + ] + }, + "class_type": "CLIPTextEncode", + "_meta": { + "title": "CLIP Text Encode (Prompt)", + "Favorfitinput": "text" + } + }, + "7": { + "inputs": { + "text": "blurry, noisy, messy, lowres, jpeg, artifacts, ill, distorted, malformed", + "clip": [ + "4", + 1 + ] + }, + "class_type": "CLIPTextEncode", + "_meta": { + "title": "CLIP Text Encode (Prompt)", + "Favorfitinput": "text" + } + }, + "8": { + "inputs": { + "samples": [ + "3", + 0 + ], + "vae": [ + "4", + 2 + ] + }, + "class_type": "VAEDecode", + "_meta": { + "title": "VAE Decode" + } + }, + "9": { + "inputs": { + "filename_prefix": "IPAdapter", + "images": [ + "8", + 0 + ] + }, + "class_type": "SaveImage", + "_meta": { + "title": "Save Image" + } + }, + "11": { + "inputs": { + "preset": "PLUS (high strength)", + "model": [ + "4", + 0 + ] + }, + "class_type": "IPAdapterUnifiedLoader", + "_meta": { + "title": "IPAdapter Unified Loader" + } + }, + "12": { + "inputs": { + "image": "i2i_example.jpg", + "upload": "image" + }, + "class_type": "LoadImage", + "_meta": { + "title": "Load Image", + "Favorfitinput": "image" + } + }, + "15": { + "inputs": { + "weight_style": 1.2, + "weight_composition": 1, + "expand_style": false, + "combine_embeds": "average", + "start_at": 0, + "end_at": 1, + "embeds_scaling": "V only", + "model": [ + "11", + 0 + ], + "ipadapter": [ + "11", + 1 + ], + "image_style": [ + "16", + 0 + ], + "image_composition": [ + "12", + 0 + ] + }, + "class_type": "IPAdapterStyleComposition", + "_meta": { + "title": "IPAdapter Style & Composition SDXL" + } + }, + "16": { + "inputs": { + "image": "style_example.jpg", + "upload": "image" + }, + "class_type": "LoadImage", + "_meta": { + "title": "Load Image", + "Favorfitinput": "image" + } + } +} \ No newline at end of file diff --git a/workflows/I2V_svdxt.json b/workflows/I2V_svdxt.json new file mode 100644 index 000000000..011b33aeb --- /dev/null +++ b/workflows/I2V_svdxt.json @@ -0,0 +1,169 @@ +{ + "8": { + "inputs": { + "samples": [ + "38", + 0 + ], + "vae": [ + "89", + 0 + ] + }, + "class_type": "VAEDecode", + "_meta": { + "title": "VAE Decode" + } + }, + "12": { + "inputs": { + "width": [ + "84", + 0 + ], + "height": [ + "84", + 1 + ], + "video_frames": 24, + "motion_bucket_id": 40, + "fps": 12, + "augmentation_level": 0.05, + "clip_vision": [ + "15", + 1 + ], + "init_image": [ + "23", + 0 + ], + "vae": [ + "89", + 0 + ] + }, + "class_type": "SVD_img2vid_Conditioning", + "_meta": { + "title": "SVD_img2vid_Conditioning" + } + }, + "14": { + "inputs": { + "min_cfg": 1, + "model": [ + "15", + 0 + ] + }, + "class_type": "VideoLinearCFGGuidance", + "_meta": { + "title": "VideoLinearCFGGuidance" + } + }, + "15": { + "inputs": { + "ckpt_name": "svd_xt.safetensors" + }, + "class_type": "ImageOnlyCheckpointLoader", + "_meta": { + "title": "Image Only Checkpoint Loader (img2vid model)" + } + }, + "23": { + "inputs": { + "image": "i2v_example.jpg", + "upload": "image" + }, + "class_type": "LoadImage", + "_meta": { + "title": "Load Image", + "Favorfitinput": "image" + } + }, + "26": { + "inputs": { + "frame_rate": 12, + "loop_count": 0, + "filename_prefix": "SVD-", + "format": "video/nvenc_h264-mp4", + "pix_fmt": "yuv420p", + "bitrate": 10, + "megabit": true, + "save_metadata": true, + "pingpong": false, + "save_output": true, + "images": [ + "8", + 0 + ] + }, + "class_type": "VHS_VideoCombine", + "_meta": { + "title": "Video Combine 🎥🅥🅗🅢" + } + }, + "38": { + "inputs": { + "seed": [ + "90", + 0 + ], + "steps": 27, + "cfg": 5.5, + "sampler_name": "euler", + "scheduler": "normal", + "denoise": 1, + "model": [ + "14", + 0 + ], + "positive": [ + "12", + 0 + ], + "negative": [ + "12", + 1 + ], + "latent_image": [ + "12", + 2 + ] + }, + "class_type": "KSampler", + "_meta": { + "title": "KSampler" + } + }, + "84": { + "inputs": { + "image": [ + "23", + 0 + ] + }, + "class_type": "CM_NearestSDXLResolution", + "_meta": { + "title": "NearestSDXLResolution" + } + }, + "89": { + "inputs": { + "vae_name": "vae-ft-mse-840000-ema-pruned.safetensors" + }, + "class_type": "VAELoader", + "_meta": { + "title": "Load VAE" + } + }, + "90": { + "inputs": { + "seed": 859503508675372 + }, + "class_type": "CR Seed", + "_meta": { + "title": "🌱 CR Seed", + "Favorfitinput": "seed" + } + } +} \ No newline at end of file diff --git a/workflows/T2I_juggernaut.json b/workflows/T2I_juggernaut.json new file mode 100644 index 000000000..27f132d06 --- /dev/null +++ b/workflows/T2I_juggernaut.json @@ -0,0 +1,111 @@ +{ + "3": { + "inputs": { + "seed": 184755451696737, + "steps": 20, + "cfg": 6.7, + "sampler_name": "dpmpp_3m_sde", + "scheduler": "karras", + "denoise": 1, + "model": [ + "4", + 0 + ], + "positive": [ + "6", + 0 + ], + "negative": [ + "7", + 0 + ], + "latent_image": [ + "5", + 0 + ] + }, + "class_type": "KSampler", + "_meta": { + "title": "KSampler", + "Favorfitinput": "seed" + } + }, + "4": { + "inputs": { + "ckpt_name": "juggernaut_reborn.safetensors" + }, + "class_type": "CheckpointLoaderSimple", + "_meta": { + "title": "Load Checkpoint" + } + }, + "5": { + "inputs": { + "width": 512, + "height": 512, + "batch_size": 1 + }, + "class_type": "EmptyLatentImage", + "_meta": { + "title": "Empty Latent Image", + "Favorfitinput": "width,height" + } + }, + "6": { + "inputs": { + "text": "beautiful scenery nature glass bottle landscape, , purple galaxy bottle,", + "clip": [ + "4", + 1 + ] + }, + "class_type": "CLIPTextEncode", + "_meta": { + "title": "CLIP Text Encode (Prompt)", + "Favorfitinput": "text" + } + }, + "7": { + "inputs": { + "text": "text, watermark", + "clip": [ + "4", + 1 + ] + }, + "class_type": "CLIPTextEncode", + "_meta": { + "title": "CLIP Text Encode (Prompt)", + "Favorfitinput": "text" + } + }, + "8": { + "inputs": { + "samples": [ + "3", + 0 + ], + "vae": [ + "4", + 2 + ] + }, + "class_type": "VAEDecode", + "_meta": { + "title": "VAE Decode" + } + }, + "9": { + "inputs": { + "filename_prefix": "ComfyUI", + "images": [ + "8", + 0 + ] + }, + "class_type": "SaveImage", + "_meta": { + "title": "Save Image" + } + } +} \ No newline at end of file diff --git a/workflows/VFI_anime.json b/workflows/VFI_anime.json new file mode 100644 index 000000000..d5485af2a --- /dev/null +++ b/workflows/VFI_anime.json @@ -0,0 +1,54 @@ +{ + "1": { + "inputs": { + "video": "video/vfi_example.gif", + "frame_start": 0, + "frame_limit": 500, + "$$comfy_animation_preview": { + "height": 200 + } + }, + "class_type": "LoadVideo", + "_meta": { + "title": "Load Video", + "Favorfitinput": "video" + } + }, + "3": { + "inputs": { + "ckpt_name": "GMFSS_fortuna_union", + "clear_cache_after_n_frames": 10, + "multiplier": 2, + "frames": [ + "1", + 0 + ] + }, + "class_type": "GMFSS Fortuna VFI", + "_meta": { + "title": "GMFSS Fortuna VFI" + } + }, + "5": { + "inputs": { + "frame_rate": 60, + "loop_count": 0, + "filename_prefix": "vfi_", + "format": "video/h264-mp4", + "pix_fmt": "yuv420p", + "crf": 19, + "save_metadata": false, + "pingpong": false, + "save_output": true, + "images": [ + "3", + 0 + ] + }, + "class_type": "VHS_VideoCombine", + "_meta": { + "title": "Video Combine 🎥🅥🅗🅢", + "Favorfitinput": "frame_rate" + } + } +} \ No newline at end of file diff --git a/workflows/favorfit_kandinsky_adapter_api.json b/workflows/favorfit_kandinsky_adapter_api.json new file mode 100644 index 000000000..2db02b477 --- /dev/null +++ b/workflows/favorfit_kandinsky_adapter_api.json @@ -0,0 +1,316 @@ +{ + "27": { + "inputs": { + "ckpt": "kandinsky-prior" + }, + "class_type": "comfy-kandinsky22-prior-loader", + "_meta": { + "title": "Kandinsky2.2 Prior Loader" + } + }, + "32": { + "inputs": { + "ckpt": "kandinsky-decoder" + }, + "class_type": "comfy-kandinsky22-decoder-loader", + "_meta": { + "title": "Kandinsky2.2 Decoder Loader" + } + }, + "33": { + "inputs": { + "movq": [ + "32", + 0 + ], + "latents": [ + "98", + 0 + ] + }, + "class_type": "comfy-kandinsky22-movq-decoder", + "_meta": { + "title": "Kandinsky2.2 MovQ Decoder" + } + }, + "67": { + "inputs": { + "batch_size": 1, + "height": [ + "88", + 2 + ], + "width": [ + "88", + 1 + ], + "seed": 238094222304379, + "lat_info": [ + "32", + 2 + ] + }, + "class_type": "comfy-kandinsky22-latents", + "_meta": { + "title": "Kandinsky2.2 Latents" + } + }, + "72": { + "inputs": { + "image": "i2i_example.jpg", + "upload": "image" + }, + "class_type": "LoadImage", + "_meta": { + "title": "Load Image", + "Favorfitinput": "image" + } + }, + "73": { + "inputs": { + "encoder": [ + "27", + 0 + ], + "image": [ + "89", + 0 + ] + }, + "class_type": "comfy-kandinsky22-image-encoder", + "_meta": { + "title": "Kandinsky2.2 Image Encoder" + } + }, + "78": { + "inputs": { + "controlnet_name": "kandinsky_controlnet/outpaint" + }, + "class_type": "KandinskyControlnetLoader", + "_meta": { + "title": "Kandinsky Controlnet Loader" + } + }, + "87": { + "inputs": { + "strength": 1, + "latents": [ + "67", + 0 + ], + "control_net": [ + "78", + 0 + ], + "control_image": [ + "91", + 0 + ] + }, + "class_type": "KandinskyControlNetApply", + "_meta": { + "title": "Kandinsky Controlnet Apply" + } + }, + "88": { + "inputs": { + "image": [ + "100", + 0 + ] + }, + "class_type": "GetImageSizeAndCount", + "_meta": { + "title": "Get Image Size & Count" + } + }, + "89": { + "inputs": { + "image": "style_example.jpg", + "upload": "image" + }, + "class_type": "LoadImage", + "_meta": { + "title": "Load Image", + "Favorfitinput": "image" + } + }, + "90": { + "inputs": { + "ckpt": "remove_bg.pth", + "image": [ + "100", + 0 + ] + }, + "class_type": "FavorfitRemoveBg", + "_meta": { + "title": "Favorfit Remove Background" + } + }, + "91": { + "inputs": { + "image": [ + "100", + 0 + ], + "mask": [ + "90", + 0 + ] + }, + "class_type": "FavorfitMakeOutpaintCondition", + "_meta": { + "title": "Favorfit Make Outpaint Condition" + } + }, + "92": { + "inputs": { + "images": [ + "91", + 0 + ] + }, + "class_type": "PreviewImage", + "_meta": { + "title": "Preview Image" + } + }, + "98": { + "inputs": { + "strength": 1, + "num_inference_steps": 20, + "guidance_scale": 1.5, + "seed": 485573436624520, + "decoder": [ + "32", + 1 + ], + "latents": [ + "106", + 0 + ], + "image_embeds": [ + "107", + 0 + ], + "negative_image_embeds": [ + "99", + 0 + ] + }, + "class_type": "KandinskyControlUnetDecoder", + "_meta": { + "title": "Kandinsky Control Unet Decoder", + "Favorfitinput": "seed" + } + }, + "99": { + "inputs": { + "file_name": "negative_embedding.npy" + }, + "class_type": "FavorfitLoadEmbedTensor", + "_meta": { + "title": "Favorfit Load Embed Tensor" + } + }, + "100": { + "inputs": { + "target_size": -1, + "max_size": 2048, + "min_size": 512, + "image": [ + "72", + 0 + ] + }, + "class_type": "FavorfitResizeDiffusionAvailable", + "_meta": { + "title": "Favorfit Resize Dif Avail" + } + }, + "102": { + "inputs": { + "movq": [ + "32", + 0 + ], + "images": [ + "100", + 0 + ] + }, + "class_type": "Kandinsky22MovqEncoder", + "_meta": { + "title": "Kandinsky Movq Encoder" + } + }, + "106": { + "inputs": { + "latents": [ + "87", + 0 + ], + "inject_image_embed": [ + "102", + 0 + ], + "inject_mask": [ + "90", + 0 + ] + }, + "class_type": "KandinskyImageInject", + "_meta": { + "title": "Kandinsky Image Inject Apply" + } + }, + "107": { + "inputs": { + "w1": 0.7000000000000001, + "w2": 0.3, + "in1": [ + "73", + 0 + ], + "in2": [ + "110", + 0 + ] + }, + "class_type": "comfy-kandinsky22-prior-averaging-2", + "_meta": { + "title": "Kandinsky2.2 Prior 2-Averaging" + } + }, + "110": { + "inputs": { + "num_inference_steps": 20, + "guidance_scale": 8, + "seed": 920369955893834, + "prompt": "product background, masterpiece", + "text_encoder": [ + "27", + 1 + ] + }, + "class_type": "comfy-kandinsky22-positive-text-encoder", + "_meta": { + "title": "Kandinsky2.2 Positive Text Encoder", + "Favorfitinput": "prompt" + } + }, + "111": { + "inputs": { + "filename_prefix": "favorfit_adapter_", + "images": [ + "33", + 0 + ] + }, + "class_type": "SaveImage", + "_meta": { + "title": "Save Image" + } + } +} \ No newline at end of file diff --git a/workflows/favorfit_kandinsky_text_enhance_api.json b/workflows/favorfit_kandinsky_text_enhance_api.json new file mode 100644 index 000000000..91097bac4 --- /dev/null +++ b/workflows/favorfit_kandinsky_text_enhance_api.json @@ -0,0 +1,449 @@ +{ + "6": { + "inputs": { + "ckpt": "remove_bg.pth", + "image": [ + "8", + 0 + ] + }, + "class_type": "FavorfitRemoveBg", + "_meta": { + "title": "Favorfit Remove Background" + } + }, + "7": { + "inputs": { + "image": "i2i_example.jpg", + "upload": "image" + }, + "class_type": "LoadImage", + "_meta": { + "title": "Load Image", + "Favorfitinput": "image" + } + }, + "8": { + "inputs": { + "target_size": -1, + "max_size": 2048, + "min_size": 512, + "image": [ + "7", + 0 + ] + }, + "class_type": "FavorfitResizeDiffusionAvailable", + "_meta": { + "title": "Favorfit Resize Dif Avail" + } + }, + "10": { + "inputs": { + "image": [ + "8", + 0 + ], + "mask": [ + "6", + 0 + ] + }, + "class_type": "FavorfitMakeOutpaintCondition", + "_meta": { + "title": "Favorfit Make Outpaint Condition" + } + }, + "11": { + "inputs": { + "controlnet_name": "kandinsky_controlnet/outpaint" + }, + "class_type": "KandinskyControlnetLoader", + "_meta": { + "title": "Kandinsky Controlnet Loader" + } + }, + "12": { + "inputs": { + "ckpt": "kandinsky-prior" + }, + "class_type": "comfy-kandinsky22-prior-loader", + "_meta": { + "title": "Kandinsky2.2 Prior Loader" + } + }, + "13": { + "inputs": { + "ckpt": "kandinsky-decoder" + }, + "class_type": "comfy-kandinsky22-decoder-loader", + "_meta": { + "title": "Kandinsky2.2 Decoder Loader" + } + }, + "15": { + "inputs": { + "num_inference_steps": 20, + "guidance_scale": 8, + "seed": 550370223430666, + "prompt": "product photo, professional photography, beautiful landscape, natural materials :: high detail, behance. polished, trending on textures. com, clean 3 d render, raytraced 3d set design, raytracing shadows, image on the store website", + "negative_prior": "low quality, worst quality, wrinkled, deformed, distorted, jpeg artifacts,nsfw, paintings, sketches, text, watermark, username, spikey", + "text_encoder": [ + "12", + 1 + ] + }, + "class_type": "comfy-kandinsky22-text-encoder", + "_meta": { + "title": "Kandinsky2.2 Text Encoder", + "Favorfitinput": "seed,prompt,negative_prior" + } + }, + "16": { + "inputs": { + "strength": 1, + "latents": [ + "19", + 0 + ], + "control_net": [ + "11", + 0 + ], + "control_image": [ + "10", + 0 + ] + }, + "class_type": "KandinskyControlNetApply", + "_meta": { + "title": "Kandinsky Controlnet Apply" + } + }, + "19": { + "inputs": { + "batch_size": 1, + "height": [ + "8", + 1 + ], + "width": [ + "8", + 2 + ], + "seed": 539365995819067, + "movq": [ + "13", + 0 + ], + "image": [ + "8", + 0 + ], + "lat_info": [ + "13", + 2 + ] + }, + "class_type": "comfy-kandinsky22-img-latents", + "_meta": { + "title": "Kandinsky2.2 Image Latents" + } + }, + "20": { + "inputs": { + "strength": 1, + "num_inference_steps": 20, + "guidance_scale": 2, + "seed": 118431456914217, + "decoder": [ + "13", + 1 + ], + "latents": [ + "27", + 0 + ], + "image_embeds": [ + "15", + 0 + ], + "negative_image_embeds": [ + "15", + 1 + ] + }, + "class_type": "KandinskyControlUnetDecoder", + "_meta": { + "title": "Kandinsky Control Unet Decoder" + } + }, + "21": { + "inputs": { + "movq": [ + "13", + 0 + ], + "latents": [ + "20", + 0 + ] + }, + "class_type": "comfy-kandinsky22-movq-decoder", + "_meta": { + "title": "Kandinsky2.2 MovQ Decoder" + } + }, + "27": { + "inputs": { + "latents": [ + "16", + 0 + ], + "inject_image_embed": [ + "28", + 0 + ], + "inject_mask": [ + "6", + 0 + ] + }, + "class_type": "KandinskyImageInject", + "_meta": { + "title": "Kandinsky Image Inject Apply" + } + }, + "28": { + "inputs": { + "movq": [ + "13", + 0 + ], + "images": [ + "8", + 0 + ] + }, + "class_type": "Kandinsky22MovqEncoder", + "_meta": { + "title": "Kandinsky Movq Encoder" + } + }, + "29": { + "inputs": { + "ckpt_name": "juggernaut_reborn.safetensors" + }, + "class_type": "CheckpointLoaderSimple", + "_meta": { + "title": "Load Checkpoint" + } + }, + "30": { + "inputs": { + "control_net_name": "control_v11f1e_sd15_tile.pth" + }, + "class_type": "ControlNetLoader", + "_meta": { + "title": "Load ControlNet Model" + } + }, + "31": { + "inputs": { + "strength": 1, + "conditioning": [ + "41", + 0 + ], + "control_net": [ + "30", + 0 + ], + "image": [ + "21", + 0 + ] + }, + "class_type": "ControlNetApply", + "_meta": { + "title": "Apply ControlNet" + } + }, + "32": { + "inputs": { + "seed": 842477950861808, + "steps": 20, + "cfg": 8, + "sampler_name": "dpmpp_2m_sde", + "scheduler": "karras", + "denoise": 0.5, + "model": [ + "29", + 0 + ], + "positive": [ + "31", + 0 + ], + "negative": [ + "36", + 0 + ], + "latent_image": [ + "33", + 0 + ] + }, + "class_type": "KSampler", + "_meta": { + "title": "KSampler" + } + }, + "33": { + "inputs": { + "pixels": [ + "21", + 0 + ], + "vae": [ + "29", + 2 + ] + }, + "class_type": "VAEEncode", + "_meta": { + "title": "VAE Encode" + } + }, + "36": { + "inputs": { + "text": "bright, blur, lowres, bad anatomy, bad hands, cropped, worst quality", + "clip": [ + "29", + 1 + ] + }, + "class_type": "CLIPTextEncode", + "_meta": { + "title": "CLIP Text Encode (Prompt)" + } + }, + "40": { + "inputs": { + "dir_name": "clip", + "image": [ + "21", + 0 + ] + }, + "class_type": "FavorfitImageToText", + "_meta": { + "title": "Favorfit Image To Text" + } + }, + "41": { + "inputs": { + "text": [ + "40", + 0 + ], + "clip": [ + "29", + 1 + ] + }, + "class_type": "CLIPTextEncode", + "_meta": { + "title": "CLIP Text Encode (Prompt)" + } + }, + "42": { + "inputs": { + "samples": [ + "32", + 0 + ], + "vae": [ + "29", + 2 + ] + }, + "class_type": "VAEDecode", + "_meta": { + "title": "VAE Decode" + } + }, + "44": { + "inputs": { + "x": 0, + "y": 0, + "resize_source": false, + "destination": [ + "42", + 0 + ], + "source": [ + "21", + 0 + ], + "mask": [ + "6", + 0 + ] + }, + "class_type": "ImageCompositeMasked", + "_meta": { + "title": "ImageCompositeMasked" + } + }, + "53": { + "inputs": { + "model_name": "RealESRGAN_x2.pth" + }, + "class_type": "Upscale Model Loader", + "_meta": { + "title": "Upscale Model Loader" + } + }, + "54": { + "inputs": { + "upscale_model": [ + "53", + 0 + ], + "image": [ + "44", + 0 + ] + }, + "class_type": "ImageUpscaleWithModel", + "_meta": { + "title": "Upscale Image (using Model)" + } + }, + "55": { + "inputs": { + "images": [ + "54", + 0 + ] + }, + "class_type": "PreviewImage", + "_meta": { + "title": "Preview Image" + } + }, + "56": { + "inputs": { + "filename_prefix": "favorfit_text_", + "images": [ + "54", + 0 + ] + }, + "class_type": "SaveImage", + "_meta": { + "title": "Save Image" + } + } +} \ No newline at end of file