Archived
implemented api and progress updates via websocket
This commit is contained in:
1 parent
5441b0d8ff
commit
7c8768ac1f
8 files changed
+325
-50
No files matched your search
@@ -99,3 +99,32 @@ def run_workflow(**kwargs):
|
|||||||
'output': result
|
'output': result
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Javascript Examples
|
||||||
|
|
||||||
|
Cancel a specific job by prompt_id
|
||||||
|
|
||||||
|
```Javascript
|
||||||
|
const axios = require('axios');
|
||||||
|
let data = JSON.stringify({
|
||||||
|
"prompt_id": "f244551d-3dff-4390-a7b5-1491bbe42409"
|
||||||
|
});
|
||||||
|
|
||||||
|
let config = {
|
||||||
|
method: 'post',
|
||||||
|
maxBodyLength: Infinity,
|
||||||
|
url: 'http://localhost:8188/interrupt',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
},
|
||||||
|
data : data
|
||||||
|
};
|
||||||
|
|
||||||
|
axios.request(config)
|
||||||
|
.then((response) => {
|
||||||
|
console.log(JSON.stringify(response.data));
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.log(error);
|
||||||
|
});
|
||||||
|
```
|
||||||
+10
@@ -6,6 +6,16 @@ from .workflows import *
|
|||||||
# Your custom progress callback
|
# Your custom progress callback
|
||||||
def my_progress_callback(value, total, preview_image, prompt_id, node_id):
|
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}")
|
print(f"Progress: {value}/{total}, Prompt: {prompt_id}, Node: {node_id}, Preview: {preview_image}")
|
||||||
|
|
||||||
|
# Broadcast to ALL WebSocket clients using ComfyUI's system (sid=None means broadcast to all)
|
||||||
|
PromptServer.instance.send_sync("imagelab_progress", {
|
||||||
|
'value': value,
|
||||||
|
'total': total,
|
||||||
|
# 'preview_image': preview_image,
|
||||||
|
'prompt_id': prompt_id,
|
||||||
|
'node_id': node_id,
|
||||||
|
'progress_percent': round((value / total * 100), 2) if total > 0 else 0
|
||||||
|
}, sid=None)
|
||||||
|
|
||||||
add_progress_hook(my_progress_callback)
|
add_progress_hook(my_progress_callback)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
"""
|
||||||
|
Base workflow class with common functionality.
|
||||||
|
All workflows should inherit from this class.
|
||||||
|
"""
|
||||||
|
from comfy_script.runtime import *
|
||||||
|
from comfy_script.runtime.nodes import *
|
||||||
|
|
||||||
|
class BaseWorkflow:
|
||||||
|
"""Base class for ComfyScript workflows with common utilities."""
|
||||||
|
|
||||||
|
def __init__(self, params):
|
||||||
|
self.params = params
|
||||||
|
|
||||||
|
def load_checkpoints(self):
|
||||||
|
"""
|
||||||
|
Load and optionally merge checkpoints.
|
||||||
|
Automatically merges if multiple checkpoints are provided.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
tuple: (model, clip, vae)
|
||||||
|
"""
|
||||||
|
checkpoints = self.params.checkpoints
|
||||||
|
|
||||||
|
if not checkpoints:
|
||||||
|
raise ValueError("At least one checkpoint is required")
|
||||||
|
|
||||||
|
if len(checkpoints) == 1:
|
||||||
|
# Single checkpoint - load directly
|
||||||
|
self.model, self.clip, self.vae = CheckpointLoaderSimple(checkpoints[0])
|
||||||
|
else:
|
||||||
|
# Multiple checkpoints - merge them
|
||||||
|
self.model, self.clip, self.vae = self._merge_checkpoints(checkpoints)
|
||||||
|
|
||||||
|
return self.model, self.clip, self.vae
|
||||||
|
|
||||||
|
def _merge_checkpoints(self, checkpoints):
|
||||||
|
# Load first checkpoint
|
||||||
|
model, clip, vae = CheckpointLoaderSimple(checkpoints[0])
|
||||||
|
|
||||||
|
# Merge with each additional checkpoint
|
||||||
|
merge_ratio = 1.0 / len(checkpoints)
|
||||||
|
|
||||||
|
for i in range(1, len(checkpoints)):
|
||||||
|
model_next, clip_next, _ = CheckpointLoaderSimple(checkpoints[i])
|
||||||
|
model = ModelMergeSimple(model, model_next, merge_ratio)
|
||||||
|
clip = CLIPMergeSimple(clip, clip_next, merge_ratio)
|
||||||
|
|
||||||
|
return model, clip, vae
|
||||||
|
|
||||||
|
def apply_loras(self, model=None, clip=None):
|
||||||
|
for lora in self.params.loras:
|
||||||
|
if not lora.disabled:
|
||||||
|
model, clip = LoraLoader(
|
||||||
|
model, clip, lora.apiName,
|
||||||
|
lora.parameters.strength_model,
|
||||||
|
lora.parameters.strength_clip
|
||||||
|
)
|
||||||
|
|
||||||
|
return model, clip
|
||||||
|
|
||||||
|
def run(self):
|
||||||
|
"""
|
||||||
|
Main execution method. Override this in subclasses.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict: Result with prompt_id, status, and output data
|
||||||
|
"""
|
||||||
|
raise NotImplementedError("Subclasses must implement run() method")
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
"""
|
||||||
|
Shared type definitions for workflows.
|
||||||
|
Keep all reusable parameter types here.
|
||||||
|
"""
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
class LoraParameters(BaseModel):
|
||||||
|
strength_model: float = 1.0
|
||||||
|
strength_clip: float = 1.0
|
||||||
|
|
||||||
|
class Lora(BaseModel):
|
||||||
|
apiName: str
|
||||||
|
disabled: bool = False
|
||||||
|
parameters: LoraParameters = LoraParameters()
|
||||||
|
|
||||||
|
class ControlnetParameters(BaseModel):
|
||||||
|
strength: float = 1.0
|
||||||
|
start_percent: float = 0.0
|
||||||
|
end_percent: float = 1.0
|
||||||
|
|
||||||
|
class Controlnet(BaseModel):
|
||||||
|
apiName: str
|
||||||
|
disabled: bool = False
|
||||||
|
parameters: ControlnetParameters = ControlnetParameters()
|
||||||
|
|
||||||
|
# Add more shared types as needed
|
||||||
@@ -4,18 +4,35 @@ API routes for external workflow execution.
|
|||||||
from aiohttp import web
|
from aiohttp import web
|
||||||
from server import PromptServer
|
from server import PromptServer
|
||||||
|
|
||||||
from .workflows import get_workflow, list_workflows
|
from .workflows import get_workflow, get_workflow_metadata, list_workflows
|
||||||
|
|
||||||
def SetupRoutes(server: PromptServer):
|
def SetupRoutes(server: PromptServer):
|
||||||
"""Register API routes with the ComfyUI server."""
|
"""Register API routes with the ComfyUI server."""
|
||||||
|
|
||||||
@server.instance.routes.get("/external-api/workflows")
|
@server.instance.routes.get("/external-api/workflows")
|
||||||
async def list_available_workflows(request):
|
async def list_available_workflows(request):
|
||||||
"""List all available workflows."""
|
"""List all available workflows with metadata."""
|
||||||
return web.json_response({
|
return web.json_response({
|
||||||
'workflows': list_workflows()
|
'workflows': list_workflows()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
@server.instance.routes.get("/external-api/workflow/{workflow_name}/metadata")
|
||||||
|
async def get_workflow_info(request):
|
||||||
|
"""Get metadata for a specific workflow."""
|
||||||
|
workflow_name = request.match_info['workflow_name']
|
||||||
|
try:
|
||||||
|
metadata = get_workflow_metadata(workflow_name)
|
||||||
|
return web.json_response({
|
||||||
|
'success': True,
|
||||||
|
'workflow': workflow_name,
|
||||||
|
'metadata': metadata
|
||||||
|
})
|
||||||
|
except ValueError as e:
|
||||||
|
return web.json_response({
|
||||||
|
'success': False,
|
||||||
|
'error': str(e)
|
||||||
|
}, status=404)
|
||||||
|
|
||||||
@server.instance.routes.post("/external-api/workflow/{workflow_name}")
|
@server.instance.routes.post("/external-api/workflow/{workflow_name}")
|
||||||
async def execute_workflow(request):
|
async def execute_workflow(request):
|
||||||
"""Execute a specific workflow by name."""
|
"""Execute a specific workflow by name."""
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"""
|
||||||
|
WebSocket management for external API progress updates.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import asyncio
|
||||||
|
from aiohttp import web
|
||||||
|
|
||||||
|
# Store active WebSocket connections
|
||||||
|
active_connections = set()
|
||||||
|
|
||||||
|
async def websocket_handler(request):
|
||||||
|
"""Handle WebSocket connections at /imagelab/ws"""
|
||||||
|
ws = web.WebSocketResponse()
|
||||||
|
await ws.prepare(request)
|
||||||
|
|
||||||
|
# Add to active connections
|
||||||
|
active_connections.add(ws)
|
||||||
|
print(f"[ImageLab WS] Client connected. Active connections: {len(active_connections)}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Send connection confirmation
|
||||||
|
await ws.send_json({
|
||||||
|
'type': 'connection',
|
||||||
|
'status': 'connected',
|
||||||
|
'message': 'Connected to ImageLab WebSocket'
|
||||||
|
})
|
||||||
|
|
||||||
|
# Keep connection alive and listen for messages
|
||||||
|
async for msg in ws:
|
||||||
|
if msg.type == web.WSMsgType.TEXT:
|
||||||
|
# Handle incoming messages if needed
|
||||||
|
pass
|
||||||
|
elif msg.type == web.WSMsgType.ERROR:
|
||||||
|
print(f'[ImageLab WS] Connection closed with exception {ws.exception()}')
|
||||||
|
finally:
|
||||||
|
# Remove from active connections
|
||||||
|
active_connections.discard(ws)
|
||||||
|
print(f"[ImageLab WS] Client disconnected. Active connections: {len(active_connections)}")
|
||||||
|
|
||||||
|
return ws
|
||||||
|
|
||||||
|
async def broadcast_progress(data: dict):
|
||||||
|
"""Broadcast progress data to all connected WebSocket clients."""
|
||||||
|
if not active_connections:
|
||||||
|
return
|
||||||
|
|
||||||
|
message = json.dumps(data)
|
||||||
|
|
||||||
|
# Remove closed connections and send to active ones
|
||||||
|
disconnected = set()
|
||||||
|
for ws in active_connections:
|
||||||
|
if ws.closed:
|
||||||
|
disconnected.add(ws)
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
await ws.send_str(message)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[ImageLab WS] Error sending to client: {e}")
|
||||||
|
disconnected.add(ws)
|
||||||
|
|
||||||
|
# Clean up disconnected clients
|
||||||
|
for ws in disconnected:
|
||||||
|
active_connections.discard(ws)
|
||||||
|
|
||||||
|
def broadcast_progress_sync(data: dict):
|
||||||
|
"""Synchronous wrapper for broadcast_progress. Schedules the broadcast on the event loop."""
|
||||||
|
if not active_connections:
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Get the event loop from the first active connection
|
||||||
|
loop = None
|
||||||
|
for ws in active_connections:
|
||||||
|
if hasattr(ws, '_req') and hasattr(ws._req, 'app') and hasattr(ws._req.app, '_loop'):
|
||||||
|
loop = ws._req.app._loop
|
||||||
|
break
|
||||||
|
|
||||||
|
if loop is None:
|
||||||
|
# Fallback to getting the running loop
|
||||||
|
try:
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
except RuntimeError:
|
||||||
|
return
|
||||||
|
|
||||||
|
# Schedule the coroutine on the event loop from any thread
|
||||||
|
asyncio.run_coroutine_threadsafe(broadcast_progress(data), loop)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[ImageLab WS] Error scheduling broadcast: {e}")
|
||||||
+36
-9
@@ -11,20 +11,31 @@ def load_workflow_module(workflow_name: str):
|
|||||||
"""Dynamically load/reload a workflow module from the workflows folder."""
|
"""Dynamically load/reload a workflow module from the workflows folder."""
|
||||||
workflow_path = os.path.join(os.path.dirname(__file__), "workflows", f"{workflow_name}.py")
|
workflow_path = os.path.join(os.path.dirname(__file__), "workflows", f"{workflow_name}.py")
|
||||||
if not os.path.exists(workflow_path):
|
if not os.path.exists(workflow_path):
|
||||||
raise FileNotFoundError(f"Workflow file not found: {workflow_path}")
|
raise FileNotFoundError(f"Workflow script not found: {workflow_path}")
|
||||||
|
|
||||||
spec = importlib.util.spec_from_file_location(f"workflows.{workflow_name}", workflow_path)
|
spec = importlib.util.spec_from_file_location(f"workflows.{workflow_name}", workflow_path)
|
||||||
module = importlib.util.module_from_spec(spec)
|
module = importlib.util.module_from_spec(spec)
|
||||||
spec.loader.exec_module(module)
|
spec.loader.exec_module(module)
|
||||||
return module
|
return module
|
||||||
|
|
||||||
# Workflow registry - map workflow names to their file names
|
# Workflow registry - map workflow names to their config (file + metadata)
|
||||||
# The modules will be reloaded on each execution for hot reloading
|
# The modules will be reloaded on each execution for hot reloading
|
||||||
WORKFLOW_FILES: Dict[str, str] = {
|
WORKFLOW_FILES: Dict[str, dict] = {
|
||||||
"test_workflow": "test",
|
"test_workflow": {
|
||||||
|
"script": "test",
|
||||||
|
"name": "Test Workflow",
|
||||||
|
"description": "Simple test workflow for image generation",
|
||||||
|
"model_types": ["SDXL", "Pony", "Illustrious"],
|
||||||
|
"category": "generation"
|
||||||
|
},
|
||||||
# Add more workflows here as you create them
|
# Add more workflows here as you create them
|
||||||
# "image_generation": "example_image_gen",
|
# "image_generation": {
|
||||||
# "upscale": "upscale_workflow",
|
# "file": "example_image_gen",
|
||||||
|
# "name": "Image Generation",
|
||||||
|
# "description": "Advanced image generation with controlnets",
|
||||||
|
# "model_types": ["checkpoint", "lora", "controlnet"],
|
||||||
|
# "category": "generation"
|
||||||
|
# },
|
||||||
}
|
}
|
||||||
|
|
||||||
def get_workflow(name: str) -> Callable:
|
def get_workflow(name: str) -> Callable:
|
||||||
@@ -36,9 +47,25 @@ def get_workflow(name: str) -> Callable:
|
|||||||
raise ValueError(f"Workflow '{name}' not found. Available: {list(WORKFLOW_FILES.keys())}")
|
raise ValueError(f"Workflow '{name}' not found. Available: {list(WORKFLOW_FILES.keys())}")
|
||||||
|
|
||||||
# Reload the module from disk each time
|
# Reload the module from disk each time
|
||||||
module = load_workflow_module(WORKFLOW_FILES[name])
|
workflow_config = WORKFLOW_FILES[name]
|
||||||
|
module = load_workflow_module(workflow_config["script"])
|
||||||
return module.run_workflow
|
return module.run_workflow
|
||||||
|
|
||||||
|
def get_workflow_metadata(name: str) -> dict:
|
||||||
|
"""Get metadata for a specific workflow."""
|
||||||
|
if name not in WORKFLOW_FILES:
|
||||||
|
raise ValueError(f"Workflow '{name}' not found. Available: {list(WORKFLOW_FILES.keys())}")
|
||||||
|
|
||||||
|
config = WORKFLOW_FILES[name].copy()
|
||||||
|
config.pop("script") # Don't expose internal file path
|
||||||
|
return config
|
||||||
|
|
||||||
def list_workflows() -> list:
|
def list_workflows() -> list:
|
||||||
"""Get list of available workflow names."""
|
"""Get list of available workflow names with their metadata."""
|
||||||
return list(WORKFLOW_FILES.keys())
|
return [
|
||||||
|
{
|
||||||
|
"id": name,
|
||||||
|
**get_workflow_metadata(name)
|
||||||
|
}
|
||||||
|
for name in WORKFLOW_FILES.keys()
|
||||||
|
]
|
||||||
+48
-39
@@ -2,51 +2,60 @@ from comfy_script.runtime import *
|
|||||||
load('http://127.0.0.1:8188/')
|
load('http://127.0.0.1:8188/')
|
||||||
from comfy_script.runtime.nodes import *
|
from comfy_script.runtime.nodes import *
|
||||||
|
|
||||||
from dataclasses import dataclass
|
from pydantic import BaseModel
|
||||||
from typing import List, Optional
|
from typing import List
|
||||||
import random
|
import sys
|
||||||
|
import os
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||||
|
from base import BaseWorkflow
|
||||||
|
from parameters import Lora
|
||||||
|
|
||||||
|
# Workflow-specific parameters
|
||||||
|
class WorkflowParams(BaseModel):
|
||||||
|
prompt: str
|
||||||
|
negativePrompt: str = "text, watermark"
|
||||||
|
checkpoints: List[str]
|
||||||
|
loras: List[Lora] = []
|
||||||
|
steps: int = 20
|
||||||
|
seed: int = None
|
||||||
|
width: int = 512
|
||||||
|
height: int = 512
|
||||||
|
|
||||||
|
# Workflow definition
|
||||||
|
class TestWorkflow(BaseWorkflow):
|
||||||
|
def run(self):
|
||||||
|
params: WorkflowParams = self.params
|
||||||
|
|
||||||
|
with Workflow(wait=False):
|
||||||
|
model, clip, vae = self.load_checkpoints()
|
||||||
|
model, clip = self.apply_loras(model, clip)
|
||||||
|
|
||||||
|
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': self.params.model_dump()
|
||||||
|
}
|
||||||
|
|
||||||
|
# Module-level entry point
|
||||||
def run_workflow(**kwargs):
|
def run_workflow(**kwargs):
|
||||||
|
"""Entry point for the workflow."""
|
||||||
required = ['prompt', 'checkpoints', 'seed', 'steps', 'negativePrompt', 'width', 'height']
|
required = ['prompt', 'checkpoints', 'seed', 'steps', 'negativePrompt', 'width', 'height']
|
||||||
missing = [f for f in required if f not in kwargs]
|
missing = [f for f in required if f not in kwargs]
|
||||||
if missing:
|
if missing:
|
||||||
raise ValueError(f"Missing required fields: {', '.join(missing)}")
|
raise ValueError(f"Missing required fields: {', '.join(missing)}")
|
||||||
|
|
||||||
params = WorkflowParams(**kwargs)
|
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 {
|
# Create and run workflow
|
||||||
'prompt_id': preview.task.prompt_id,
|
workflow = TestWorkflow(params)
|
||||||
'status': 'queued',
|
return workflow.run()
|
||||||
'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
|
|
||||||
Reference in new issue
Block a user