From 5441b0d8ff90e69f2647ef3cf85a563386030cc4 Mon Sep 17 00:00:00 2001 From: donnyjang Date: Sat, 3 Jan 2026 14:42:05 -0700 Subject: [PATCH] initial commit --- .gitignore | 216 +++++++++++++++++++++++++++++++++ README.md | 101 +++++++++++++++ __init__.py | 16 +++ api-request-example.json | 71 +++++++++++ progress.py | 43 +++++++ routes.py | 62 ++++++++++ workflows.py | 44 +++++++ workflows/example.py | 42 +++++++ workflows/example_image_gen.py | 67 ++++++++++ workflows/test.py | 52 ++++++++ 10 files changed, 714 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 __init__.py create mode 100644 api-request-example.json create mode 100644 progress.py create mode 100644 routes.py create mode 100644 workflows.py create mode 100644 workflows/example.py create mode 100644 workflows/example_image_gen.py create mode 100644 workflows/test.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..64d49ae --- /dev/null +++ b/.gitignore @@ -0,0 +1,216 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[codz] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py.cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +# Pipfile.lock + +# UV +# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# uv.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +# poetry.lock +# poetry.toml + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. +# https://pdm-project.org/en/latest/usage/project/#working-with-version-control +# pdm.lock +# pdm.toml +.pdm-python +.pdm-build/ + +# pixi +# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. +# pixi.lock +# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one +# in the .venv directory. It is recommended not to include this directory in version control. +.pixi + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# Redis +*.rdb +*.aof +*.pid + +# RabbitMQ +mnesia/ +rabbitmq/ +rabbitmq-data/ + +# ActiveMQ +activemq-data/ + +# SageMath parsed files +*.sage.py + +# Environments +.env +.envrc +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +# .idea/ + +# Abstra +# Abstra is an AI-powered process automation framework. +# Ignore directories containing user credentials, local state, and settings. +# Learn more at https://abstra.io/docs +.abstra/ + +# Visual Studio Code +# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore +# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore +# and can be added to the global gitignore or merged into this file. However, if you prefer, +# you could uncomment the following to ignore the entire vscode folder +# .vscode/ + +# Ruff stuff: +.ruff_cache/ + +# PyPI configuration file +.pypirc + +# Marimo +marimo/_static/ +marimo/_lsp/ +__marimo__/ + +# Streamlit +.streamlit/secrets.toml \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..b741835 --- /dev/null +++ b/README.md @@ -0,0 +1,101 @@ +# External API Custom Node + +REST API endpoints for executing ComfyScript workflows. + +## Structure + +``` +external-api/ +├── __init__.py # Main entry point, registers routes +├── progress.py # Progress hook utilities +├── routes.py # API endpoint definitions +├── workflows.py # Workflow registry +└── workflows/ # Individual workflow scripts + ├── test.py + └── example_image_gen.py +``` + +## Adding New Workflows + +1. Create a new file in `workflows/` folder (e.g., `my_workflow.py`) +2. Define a `run_workflow(**kwargs)` function +3. Import and register it in `workflows.py`: + +```python +# In workflows.py +my_workflow = load_workflow_module("my_workflow") + +WORKFLOWS = { + "my_workflow": my_workflow.run_workflow, + # ... other workflows +} +``` + +## API Endpoints + +### List Available Workflows + +``` +GET /external-api/workflows +``` + +### Execute Workflow + +``` +POST /external-api/workflow/{workflow_name} +Content-Type: application/json + +{ + "prompt": "a beautiful landscape", + "steps": 20, + "seed": 12345 +} +``` + +### Test Endpoint + +``` +GET /external-api/hello +``` + +## Example Usage + +```bash +# List workflows +curl http://localhost:8188/external-api/workflows + +# Execute test workflow +curl -X POST http://localhost:8188/external-api/workflow/test_workflow \ + -H "Content-Type: application/json" \ + -d '{"prompt": "test", "steps": 10}' +``` + +## Workflow Template + +Each workflow file should follow this pattern: + +```python +def run_workflow(**kwargs): + """ + Your workflow description. + + Args: + **kwargs: Workflow parameters + + Returns: + dict: Result with status and output + """ + from comfy_script.runtime import * + load('http://127.0.0.1:8188/') + from comfy_script.runtime.nodes import * + + # Your workflow logic here + with Workflow(wait=True) as wf: + # ... nodes ... + pass + + return { + 'status': 'completed', + 'output': result + } +``` diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..73b7c1a --- /dev/null +++ b/__init__.py @@ -0,0 +1,16 @@ +from server import PromptServer +from .progress import add_progress_hook +from .routes import SetupRoutes +from .workflows import * + +# Your custom progress callback +def my_progress_callback(value, total, preview_image, prompt_id, node_id): + print(f"Progress: {value}/{total}, Prompt: {prompt_id}, Node: {node_id}, Preview: {preview_image}") + +add_progress_hook(my_progress_callback) + +# Register API routes +SetupRoutes(PromptServer.instance) + +NODE_CLASS_MAPPINGS = {} +NODE_DISPLAY_NAME_MAPPINGS = {} \ No newline at end of file diff --git a/api-request-example.json b/api-request-example.json new file mode 100644 index 0000000..2999baa --- /dev/null +++ b/api-request-example.json @@ -0,0 +1,71 @@ +{ + "serviceType": "comfyui", + "apiName": "comfyui_generate", + "bypass": false, + "parameters": { + "workflowApiName": "sd15_basic", + "checkpoints": [ + { + "label": "cyberrealistic_v90", + "apiName": "cyberrealistic_v90.safetensors" + } + ], + "vae": { + "label": "vae-ft-mse-840000-ema-pruned", + "apiName": "vae-ft-mse-840000-ema-pruned.safetensors" + }, + "unet": [], + "clipSkip": -2, + "advancedGuidance": { + "active": false, + "tonemapMultiplier": 1, + "rescaleMultiplier": 1 + }, + "guidance": 3.5, + "dimensions": { + "width": 512, + "height": 512 + }, + "seed": 745527, + "sampler": { + "label": "euler_ancestral", + "apiName": "euler_ancestral", + "metadata": {} + }, + "scheduler": { + "label": "normal", + "apiName": "normal", + "metadata": null + }, + "steps": 9, + "denoise": 1, + "triggerWords": [], + "promptPrefix": { + "active": false, + "value": "embedding:lazypos.safetensors, score_9, score_8_up, score_7_up, score_6_up, score_5_up, score_4_up" + }, + "prompt": "A powerful, dark-skinned warrior woman with a sleek, athletic build and sharp golden eyes. She wears a fitted red sleeveless top, black pants, and lightweight combat gear. Her long purple hair is tied back in a high ponytail, flowing behind her as she moves. She stands confidently on a rooftop under a moonlit sky, her pose dynamic and ready for battle. Her expression is fierce but composed, radiating speed, intelligence, and strength. Anime-style illustration, dramatic lighting, with a Japanese urban backdrop resembling the Soul Society.", + "promptStrength": 1, + "negativePromptStrength": 1, + "negativePrompt": "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature", + "inputImage": null, + "keepInputSize": false, + "loopback": { + "active": false, + "upscaleByModel": false, + "includeLowRes": false, + "loopbackSteps": 1, + "loopbackGuidance": 1.5, + "loopbackDenoise": 0.65, + "loopbackUpscaleMethod": { + "label": "nearest-exact", + "apiName": "nearest-exact", + "metadata": null + }, + "loopbackUpscalePercent": 1 + }, + "loras": [], + "controlnets": [], + "ipadapters": [] + } +} diff --git a/progress.py b/progress.py new file mode 100644 index 0000000..c5930d9 --- /dev/null +++ b/progress.py @@ -0,0 +1,43 @@ +import os +import sys +comfyui_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) +if comfyui_root not in sys.path: + sys.path.insert(0, comfyui_root) +import comfy.utils +from comfy_execution.utils import get_executing_context + +def add_progress_hook(callback, server_instance=None): + """Add a progress callback that chains with ComfyUI's built-in hook. + + Args: + callback: Function(value, total, preview_image, prompt_id, node_id) to call on progress updates + server_instance: Optional server instance for fallback prompt_id/node_id + """ + _original_hook = None + _original_set_hook = comfy.utils.set_progress_bar_global_hook + + def hook(value, total, preview_image, prompt_id=None, node_id=None): + # Populate prompt_id and node_id from executing context if not provided + executing_context = get_executing_context() + if prompt_id is None and executing_context is not None: + prompt_id = executing_context.prompt_id + if node_id is None and executing_context is not None: + node_id = executing_context.node_id + # Fallback to server instance if available + if server_instance is not None: + if prompt_id is None: + prompt_id = getattr(server_instance, 'last_prompt_id', None) + if node_id is None: + node_id = getattr(server_instance, 'last_node_id', None) + + callback(value, total, preview_image, prompt_id, node_id) + if _original_hook is not None: + _original_hook(value, total, preview_image, prompt_id=prompt_id, node_id=node_id) + + def wrapped_set_hook(function): + nonlocal _original_hook + _original_hook = function + _original_set_hook(hook) + + comfy.utils.set_progress_bar_global_hook = wrapped_set_hook + comfy.utils.set_progress_bar_global_hook(hook) \ No newline at end of file diff --git a/routes.py b/routes.py new file mode 100644 index 0000000..491f026 --- /dev/null +++ b/routes.py @@ -0,0 +1,62 @@ +""" +API routes for external workflow execution. +""" +from aiohttp import web +from server import PromptServer + +from .workflows import get_workflow, list_workflows + +def SetupRoutes(server: PromptServer): + """Register API routes with the ComfyUI server.""" + + @server.instance.routes.get("/external-api/workflows") + async def list_available_workflows(request): + """List all available workflows.""" + return web.json_response({ + 'workflows': list_workflows() + }) + + @server.instance.routes.post("/external-api/workflow/{workflow_name}") + async def execute_workflow(request): + """Execute a specific workflow by name.""" + workflow_name = request.match_info['workflow_name'] + + try: + # Get the workflow function + workflow_func = get_workflow(workflow_name) + + # Parse request body for parameters + try: + params = await request.json() + except: + params = {} + + # Execute workflow + result = workflow_func(**params) + + return web.json_response({ + 'success': True, + 'workflow': workflow_name, + 'result': result + }) + + except ValueError as e: + return web.json_response({ + 'success': False, + 'type': 'ValueError', + 'error': str(e) + }, status=404) + + except Exception as e: + return web.json_response({ + 'success': False, + 'type': 'Exception', + 'error': f"Workflow execution failed: {str(e)}" + }, status=500) + + @server.instance.routes.get("/external-api/hello") + async def get_hello(request): + """Test endpoint.""" + return web.json_response({ + 'message': 'Hello from external API!' + }) \ No newline at end of file diff --git a/workflows.py b/workflows.py new file mode 100644 index 0000000..fb6b15e --- /dev/null +++ b/workflows.py @@ -0,0 +1,44 @@ +""" +Workflow registry for external API. +Import workflow functions from the workflows/ folder and map them here. +Supports hot reloading - workflows are reloaded from disk on each execution. +""" +import os +import importlib.util +from typing import Callable, Dict + +def load_workflow_module(workflow_name: str): + """Dynamically load/reload a workflow module from the workflows folder.""" + workflow_path = os.path.join(os.path.dirname(__file__), "workflows", f"{workflow_name}.py") + if not os.path.exists(workflow_path): + raise FileNotFoundError(f"Workflow file not found: {workflow_path}") + + spec = importlib.util.spec_from_file_location(f"workflows.{workflow_name}", workflow_path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + +# Workflow registry - map workflow names to their file names +# The modules will be reloaded on each execution for hot reloading +WORKFLOW_FILES: Dict[str, str] = { + "test_workflow": "test", + # Add more workflows here as you create them + # "image_generation": "example_image_gen", + # "upscale": "upscale_workflow", +} + +def get_workflow(name: str) -> Callable: + """ + Get a workflow function by name. + Reloads the module from disk each time for hot reloading. + """ + if name not in WORKFLOW_FILES: + raise ValueError(f"Workflow '{name}' not found. Available: {list(WORKFLOW_FILES.keys())}") + + # Reload the module from disk each time + module = load_workflow_module(WORKFLOW_FILES[name]) + return module.run_workflow + +def list_workflows() -> list: + """Get list of available workflow names.""" + return list(WORKFLOW_FILES.keys()) diff --git a/workflows/example.py b/workflows/example.py new file mode 100644 index 0000000..c89ec03 --- /dev/null +++ b/workflows/example.py @@ -0,0 +1,42 @@ +""" +Test workflow - example ComfyScript workflow. + +Each workflow file should have a run_workflow() function that accepts parameters. + +comfyscript must be loaded outside of the run_workflow scope +""" + +from comfy_script.runtime import * +load('http://127.0.0.1:8188/') +from comfy_script.runtime.nodes import * +import random + +def run_workflow(**kwargs): + """ + Execute the test workflow. + + Args: + **kwargs: Workflow parameters (e.g., prompt, seed, steps, etc.) + + Returns: + dict: Result containing output data and metadata + """ + + prompt = kwargs.get('prompt', 'beautiful scenery') + + with Workflow(wait=False): + model, clip, vae = CheckpointLoaderSimple(kwargs.get('checkpoint', Checkpoints.anbanIllus_shinv1)) + conditioning = CLIPTextEncode(prompt, clip) + conditioning2 = CLIPTextEncode(kwargs.get('negative_prompt', 'text, watermark'), clip) + latent = EmptyLatentImage(512, 512, 1) + seed = kwargs.get('seed', random.randint(0, 15663308700286)) + steps = kwargs.get('steps', 20) + latent = KSampler(model, seed, steps, 8, 'euler', 'normal', conditioning, conditioning2, latent, 1) + image = VAEDecode(latent, vae) + preview = PreviewImage(image) + + return { + 'prompt_id': preview.task.prompt_id, + 'status': 'queued', + 'parameters': kwargs + } \ No newline at end of file diff --git a/workflows/example_image_gen.py b/workflows/example_image_gen.py new file mode 100644 index 0000000..f926d33 --- /dev/null +++ b/workflows/example_image_gen.py @@ -0,0 +1,67 @@ +""" +Example image generation workflow. +Copy this template to create new workflows. +""" + +def run_workflow(**kwargs): + """ + Generate an image using ComfyScript. + + Args: + prompt (str): Positive prompt + negative_prompt (str): Negative prompt + checkpoint (str): Model checkpoint name + seed (int): Random seed + steps (int): Number of sampling steps + cfg (float): CFG scale + width (int): Image width + height (int): Image height + + Returns: + dict: Contains prompt_id, status, and output data + """ + # Import ComfyScript - only when workflow is called + from comfy_script.runtime import * + load('http://127.0.0.1:8188/') + from comfy_script.runtime.nodes import * + import random + + # Parse parameters with defaults + prompt = kwargs.get('prompt', 'beautiful scenery') + negative_prompt = kwargs.get('negative_prompt', 'text, watermark') + checkpoint = kwargs.get('checkpoint', 'anbanIllus_shinv1') + seed = kwargs.get('seed', random.randint(0, 2**32 - 1)) + steps = kwargs.get('steps', 20) + cfg = kwargs.get('cfg', 8) + width = kwargs.get('width', 512) + height = kwargs.get('height', 512) + + # Execute workflow + with Workflow(wait=True) as wf: + model, clip, vae = CheckpointLoaderSimple(getattr(Checkpoints, checkpoint)) + conditioning = CLIPTextEncode(prompt, clip) + conditioning_neg = CLIPTextEncode(negative_prompt, clip) + latent = EmptyLatentImage(width, height, 1) + latent_out = KSampler( + model, seed, steps, cfg, 'euler', 'normal', + conditioning, conditioning_neg, latent, 1 + ) + image = VAEDecode(latent_out, vae) + preview = PreviewImage(image) + + # Wait for results + result = preview.task.wait_result(preview) + + return { + 'prompt_id': preview.task.prompt_id, + 'status': 'completed', + 'seed': seed, + 'parameters': { + 'prompt': prompt, + 'negative_prompt': negative_prompt, + 'steps': steps, + 'cfg': cfg, + 'size': f"{width}x{height}" + }, + 'output': result + } diff --git a/workflows/test.py b/workflows/test.py new file mode 100644 index 0000000..ea81d58 --- /dev/null +++ b/workflows/test.py @@ -0,0 +1,52 @@ +from comfy_script.runtime import * +load('http://127.0.0.1:8188/') +from comfy_script.runtime.nodes import * + +from dataclasses import dataclass +from typing import List, Optional +import random + +def run_workflow(**kwargs): + required = ['prompt', 'checkpoints', 'seed', 'steps', 'negativePrompt', 'width', 'height'] + missing = [f for f in required if f not in kwargs] + if missing: + raise ValueError(f"Missing required fields: {', '.join(missing)}") + + params = WorkflowParams(**kwargs) + + with Workflow(wait=False): + if len(params.checkpoints) > 1: + model1, clip1, vae = CheckpointLoaderSimple(params.checkpoints[0]) + model2, clip2, vae = CheckpointLoaderSimple(params.checkpoints[1]) + + model = ModelMergeSimple(model1, model2, 0.5) + clip = CLIPMergeSimple(clip1, clip2, 0.5) + + else: + model, clip, vae = CheckpointLoaderSimple(params.checkpoints[0]) + + conditioning = CLIPTextEncode(params.prompt, clip) + conditioning2 = CLIPTextEncode(params.negativePrompt, clip) + latent = EmptyLatentImage(params.width, params.height, 1) + seed = params.seed + steps = params.steps + latent = KSampler(model, seed, steps, 8, 'euler', 'normal', conditioning, conditioning2, latent, 1) + image = VAEDecode(latent, vae) + preview = PreviewImage(image) + + return { + 'prompt_id': preview.task.prompt_id, + 'status': 'queued', + 'parameters': kwargs + } + +# Parameters typing +@dataclass +class WorkflowParams: + prompt: str + checkpoints: List[str] + seed: Optional[int] = random.randint(0, 15663308700286) + steps: int = 20 + negativePrompt: str = "text, watermark" + width: int = 512 + height: int = 512 \ No newline at end of file