diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 9b77eec..e52e9dc 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -1,20 +1,24 @@ # ImageLab External API Documentation -**Version:** 1.0 -**Base URL:** `http://127.0.0.1:8188` -**Purpose:** This document serves as a complete reference for the ImageLab External API and relevant ComfyUI endpoints. Use this as a steering document for frontend development. +**Version:** 2.0 +**Base URL:** `http://127.0.0.1:8188` + +REST API endpoints for executing ComfyScript workflows with real-time progress monitoring. --- ## Table of Contents 1. [Architecture Overview](#architecture-overview) -2. [ImageLab API Endpoints](#imagelab-api-endpoints) -3. [ComfyUI API Endpoints](#comfyui-api-endpoints) -4. [WebSocket System](#websocket-system) -5. [Binary Events](#binary-events) -6. [JavaScript Examples](#javascript-examples) -7. [Core Systems](#core-systems) +2. [Directory Structure](#directory-structure) +3. [Quick Start](#quick-start) +4. [API Endpoints](#api-endpoints) +5. [WebSocket Events](#websocket-events) +6. [Workflow System](#workflow-system) +7. [YAML Schema System](#yaml-schema-system) +8. [Resource System](#resource-system) +9. [CLI Commands](#cli-commands) +10. [JavaScript Examples](#javascript-examples) --- @@ -22,21 +26,81 @@ The ImageLab External API extends ComfyUI with: -- **Workflow Management**: Execute ComfyScript-based workflows via REST API -- **Resource Discovery**: List and index models with metadata (hash, CivitAI info) -- **Progress Monitoring**: Real-time progress updates via WebSocket binary events -- **Hot Reloading**: Workflows reload from disk on each execution for development +- **Workflow Execution**: Execute ComfyScript-based workflows via REST API +- **YAML Schema System**: Auto-generated UI schemas from Pydantic models +- **Resource Discovery**: List and index models with CivitAI metadata +- **Progress Broadcasting**: Real-time updates via WebSocket binary events +- **Hot Reloading**: Workflows reload from disk on each execution ### Technology Stack -- **Server**: ComfyUI (aiohttp web server) -- **Workflow Engine**: ComfyScript (Python runtime for ComfyUI) -- **Validation**: Pydantic (parameter validation) -- **Communication**: REST + WebSocket (JSON and Binary) +| Component | Technology | +| ------------- | ---------------------- | +| Server | ComfyUI (aiohttp) | +| Workflows | ComfyScript + Pydantic | +| Schema | YAML (auto-generated) | +| Validation | Pydantic models | +| Communication | REST + WebSocket | --- -## ImageLab API Endpoints +## Directory Structure + +``` +external-api/ +├── __init__.py # Entry point, registers routes +├── __main__.py # CLI entry point (python -m external-api) +├── cli.py # CLI commands (generate, validate, list, watch) +├── schema_generator.py # YAML schema generation from Pydantic +├── workflows.py # Workflow registry and discovery +├── routes.py # API endpoint definitions +├── resources.py # Model discovery and indexing +├── progress.py # WebSocket progress broadcasting +├── parameters.py # Shared Annotated type definitions +├── base.py # BaseWorkflow class +├── resources/ # Model index files (.index) +└── workflows/ # Individual workflow scripts + ├── basic_sdxl.py # Workflow code + WorkflowParams + ├── basic_sdxl.yaml # Auto-generated UI schema + └── ... +``` + +--- + +## Quick Start + +### Execute a Workflow + +```bash +curl -X POST http://localhost:8188/imagelab/workflow/basic_sdxl \ + -H "Content-Type: application/json" \ + -d '{ + "prompt": "a beautiful sunset over mountains", + "negativePrompt": "blurry, low quality", + "checkpoints": ["model.safetensors"], + "seed": 42, + "steps": 20, + "width": 1024, + "height": 1024, + "cfg": 8.0 + }' +``` + +### List Available Workflows + +```bash +curl http://localhost:8188/imagelab/workflows +``` + +### Get Workflow Parameters + +```bash +curl http://localhost:8188/imagelab/workflow/basic_sdxl/parameters +``` + +--- + +## API Endpoints ### Workflow Endpoints @@ -44,67 +108,88 @@ The ImageLab External API extends ComfyUI with: List all available workflows with metadata. -**Response Type:** `application/json` - -**Response Schema:** +**Response:** ```json { "workflows": [ { - "id": "test_workflow", - "name": "Test Workflow", - "description": "Simple test workflow for image generation", - "model_types": ["SDXL", "Pony", "Illustrious"], - "category": "Image Generation" + "id": "basic_sdxl", + "name": "Basic SDXL Text to Image", + "description": "Workflow with SDXL presets for quick iteration.", + "model_types": ["SDXL"], + "category": "Image Generation", + "has_parameters": true } ] } ``` -**JavaScript Example:** - -```javascript -const response = await fetch("http://127.0.0.1:8188/imagelab/workflows"); -const { workflows } = await response.json(); -console.log("Available workflows:", workflows); -``` - --- #### `GET /imagelab/workflow/{workflow_name}/metadata` Get metadata for a specific workflow. -**Parameters:** - -- `workflow_name` (path): Workflow identifier - -**Response Type:** `application/json` - -**Response Schema:** +**Response:** ```json { "success": true, - "workflow": "test_workflow", + "workflow": "basic_sdxl", "metadata": { - "name": "Test Workflow", - "description": "Simple test workflow for image generation", - "model_types": ["SDXL", "Pony", "Illustrious"], - "category": "generation" + "name": "Basic SDXL Text to Image", + "description": "Workflow with SDXL presets for quick iteration.", + "model_types": ["SDXL"], + "category": "Image Generation", + "has_parameters": true } } ``` -**JavaScript Example:** +--- -```javascript -const response = await fetch( - "http://127.0.0.1:8188/imagelab/workflow/test_workflow/metadata" -); -const { metadata } = await response.json(); -console.log("Workflow info:", metadata); +#### `GET /imagelab/workflow/{workflow_name}/parameters` + +Get the UI parameter schema for a workflow. Returns resolved options from `options_source`. + +**Response:** + +```json +{ + "success": true, + "workflow": "basic_sdxl", + "parameters": [ + { + "name": "prompt", + "type": "text", + "category": "prompts", + "multiline": true, + "required": true, + "label": "Your Creative Prompt", + "rows": 4, + "placeholder": "Describe your image...", + "description": "Enter a detailed description of the image" + }, + { + "name": "sampler", + "type": "enum", + "options_source": "samplers", + "category": "parameters", + "default": "euler", + "label": "Sampler", + "searchable": true, + "options": [ + { "label": "euler", "apiName": "euler", "metadata": null }, + { + "label": "euler_ancestral", + "apiName": "euler_ancestral", + "metadata": null + } + ] + } + ] +} ``` --- @@ -113,50 +198,31 @@ console.log("Workflow info:", metadata); Execute a workflow with parameters. -**Parameters:** - -- `workflow_name` (path): Workflow identifier - -**Request Type:** `application/json` - -**Request Body:** Varies by workflow. Example: +**Request:** ```json { - "prompt": "a beautiful sunset over mountains", - "negativePrompt": "blurry, low quality", + "prompt": "a beautiful sunset", + "negativePrompt": "blurry", "checkpoints": ["model.safetensors"], - "loras": [ - { - "apiName": "detail_enhancer.safetensors", - "disabled": false, - "parameters": { - "strength_model": 1.0, - "strength_clip": 1.0 - } - } - ], - "steps": 20, "seed": 42, - "width": 512, - "height": 512 + "steps": 20, + "width": 1024, + "height": 1024, + "cfg": 8.0 } ``` -**Response Type:** `application/json` - -**Response Schema:** +**Response:** ```json { "success": true, - "workflow": "test_workflow", + "workflow": "basic_sdxl", "result": { "prompt_id": "abc123-def456-...", "status": "queued", - "parameters": { - /* echo of input parameters */ - } + "parameters": { ... } } } ``` @@ -167,31 +233,10 @@ Execute a workflow with parameters. { "success": false, "type": "ValueError", - "error": "Workflow 'invalid_name' not found. Available: ['test_workflow']" + "error": "Missing required fields: prompt, seed" } ``` -**JavaScript Example:** - -```javascript -const response = await fetch( - "http://127.0.0.1:8188/imagelab/workflow/test_workflow", - { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - prompt: "a serene landscape", - checkpoints: ["dreamshaper_8.safetensors"], - steps: 20, - seed: Math.floor(Math.random() * 1000000), - }), - } -); - -const { result } = await response.json(); -console.log("Workflow queued with prompt_id:", result.prompt_id); -``` - --- ### Resource Endpoints @@ -200,104 +245,53 @@ console.log("Workflow queued with prompt_id:", result.prompt_id); Get all available resources (models, samplers, schedulers). -**Response Type:** `application/json` - -**Response Schema:** +**Response:** ```json { "success": true, "resources": { "checkpoints": [ - { - "label": "dreamshaper_8", - "apiName": "dreamshaper_8.safetensors", - "indexed": true - } + { "label": "dreamshaper_8", "apiName": "dreamshaper_8.safetensors", "indexed": true } ], - "loras": [ - /* ... */ + "loras": [...], + "vae": [...], + "samplers": [ + { "label": "euler", "apiName": "euler", "metadata": null } ], - "samplers": [{ "label": "euler", "apiName": "euler", "metadata": null }], - "schedulers": [ - { "label": "normal", "apiName": "normal", "metadata": null } - ], - "upscale_methods": [ - /* ... */ - ] + "schedulers": [...], + "upscale_methods": [...] } } ``` -**JavaScript Example:** - -```javascript -const response = await fetch("http://127.0.0.1:8188/imagelab/resources"); -const { resources } = await response.json(); - -// Build dropdown for checkpoints -const checkpointSelect = document.getElementById("checkpoint-select"); -resources.checkpoints.forEach((model) => { - const option = document.createElement("option"); - option.value = model.apiName; - option.textContent = model.label; - if (model.indexed) { - option.textContent += " ✓"; // Indicates metadata available - } - checkpointSelect.appendChild(option); -}); -``` - --- #### `GET /imagelab/resources/{resource_type}` Get resources of a specific type. -**Parameters:** +**Types:** `checkpoints`, `loras`, `vae`, `embeddings`, `controlnet`, `samplers`, `schedulers`, `upscale_methods` -- `resource_type` (path): Type of resource (`checkpoints`, `loras`, `vae`, `samplers`, `schedulers`, `upscale_methods`, etc.) - -**Response Type:** `application/json` - -**Response Schema:** +**Response:** ```json { "success": true, "resource_type": "loras", "items": [ - { - "label": "add_detail", - "apiName": "add_detail.safetensors", - "indexed": false - } + { "label": "my_lora", "apiName": "my_lora.safetensors", "indexed": false } ] } ``` -**JavaScript Example:** - -```javascript -const response = await fetch("http://127.0.0.1:8188/imagelab/resources/loras"); -const { items } = await response.json(); -console.log("Available LoRAs:", items); -``` - --- #### `POST /imagelab/resources/{resource_type}/index/{filename}` -Index a specific model file to calculate hash and fetch metadata. +Index a model file (calculate SHA256 hash and fetch CivitAI metadata). -**Parameters:** - -- `resource_type` (path): Type of resource (`checkpoints`, `loras`, etc.) -- `filename` (path): Exact filename including extension - -**Response Type:** `application/json` - -**Response Schema:** +**Response:** ```json { @@ -306,218 +300,572 @@ Index a specific model file to calculate hash and fetch metadata. "filename": "dreamshaper_8.safetensors", "metadata": { "filename": "dreamshaper_8.safetensors", - "hash": "9aba26abdf...", + "hash": "abc123...", "civitai": { - "id": 12345, - "name": "DreamShaper 8", - "description": "...", - "images": [ - /* preview images */ - ] + "modelId": 4384, + "name": "DreamShaper", + "baseModel": "SD 1.5" }, "imagelab": {} } } ``` -**JavaScript Example:** - -```javascript -// Index a model when user requests metadata -async function indexModel(type, filename) { - const response = await fetch( - `http://127.0.0.1:8188/imagelab/resources/${type}/index/${encodeURIComponent(filename)}`, - { method: "POST" } - ); - const { metadata } = await response.json(); - - // Display CivitAI info - if (metadata.civitai) { - console.log("Model info:", metadata.civitai.name); - console.log("Preview:", metadata.civitai.images[0]?.url); - } - - return metadata; -} - -// Usage -await indexModel("checkpoints", "dreamshaper_8.safetensors"); -``` - --- #### `POST /imagelab/resources/index-all` -Index all models that don't have index files yet. Returns count of indexed models per type. +Index all unindexed models (background operation at startup by default). -**Response Type:** `application/json` - -**Response Schema:** +**Response:** ```json { "success": true, "message": "Indexing complete", "indexed": { - "checkpoints": 5, - "loras": 12, - "vae": 2 + "checkpoints": 3, + "loras": 12 } } ``` -**JavaScript Example:** +--- + +## WebSocket Events + +### Connection ```javascript -// Trigger bulk indexing (long-running operation) -async function indexAllModels() { - const response = await fetch( - "http://127.0.0.1:8188/imagelab/resources/index-all", - { - method: "POST", - } - ); - const { indexed } = await response.json(); - console.log("Indexed models:", indexed); +const ws = new WebSocket("ws://127.0.0.1:8188/ws?clientId=my-app"); +``` + +### Binary Event Types + +| Event Code | Name | Description | +| ---------- | ------------------------- | ---------------------------- | +| 100 | `IMAGELAB_PROGRESS_EVENT` | Sampler step progress (JSON) | +| 101 | `IMAGELAB_PREVIEW_EVENT` | Preview image with metadata | +| 102 | `IMAGELAB_WORKFLOW_EVENT` | Workflow lifecycle events | + +### Event 100: Progress + +**Format:** `[4 bytes: event type][JSON payload]` + +```json +{ + "event": "sampler_progress", + "node_id": "3", + "prompt_id": "abc123", + "value": 5, + "max": 20, + "progress_percent": 25.0 } ``` +### Event 101: Preview Image + +**Format:** `[4 bytes: event type][4 bytes: metadata length][JSON metadata][image bytes]` + +```json +{ + "node_id": "3", + "prompt_id": "abc123" +} +``` + +### Event 102: Workflow Event + +**Format:** `[4 bytes: event type][JSON payload]` + +```json +{ + "event": "executing", + "data": { "node": "3", "prompt_id": "abc123" } +} +``` + +**Event types:** `executing`, `execution_start`, `executed`, `execution_error`, `execution_cached` + +### JavaScript WebSocket Client + +```javascript +class ImageLabClient { + constructor(url = "ws://127.0.0.1:8188/ws") { + this.ws = new WebSocket(url); + this.handlers = {}; + + this.ws.onmessage = (event) => { + if (event.data instanceof Blob) { + this.handleBinary(event.data); + } else { + this.handleJSON(JSON.parse(event.data)); + } + }; + } + + async handleBinary(blob) { + const buffer = await blob.arrayBuffer(); + const view = new DataView(buffer); + const eventType = view.getUint32(0, false); // big-endian + + if (eventType === 100) { + // Progress event + const json = new TextDecoder().decode(buffer.slice(4)); + this.emit("progress", JSON.parse(json)); + } else if (eventType === 101) { + // Preview image with metadata + const metadataLen = view.getUint32(4, false); + const metadataJson = new TextDecoder().decode( + buffer.slice(8, 8 + metadataLen) + ); + const metadata = JSON.parse(metadataJson); + const imageData = buffer.slice(8 + metadataLen); + const imageUrl = URL.createObjectURL(new Blob([imageData])); + this.emit("preview", { url: imageUrl, metadata }); + } else if (eventType === 102) { + // Workflow event + const json = new TextDecoder().decode(buffer.slice(4)); + this.emit("workflow", JSON.parse(json)); + } + } + + handleJSON(data) { + this.emit(data.type, data.data); + } + + on(event, handler) { + this.handlers[event] = this.handlers[event] || []; + this.handlers[event].push(handler); + } + + emit(event, data) { + (this.handlers[event] || []).forEach((h) => h(data)); + } +} + +// Usage +const client = new ImageLabClient(); +client.on("progress", (data) => { + console.log(`Progress: ${data.progress_percent}%`); +}); +client.on("preview", ({ url, metadata }) => { + document.getElementById("preview").src = url; +}); +``` + --- -## ComfyUI API Endpoints +## Workflow System -These are the core ComfyUI endpoints you'll use alongside ImageLab endpoints. +### Creating a New Workflow + +1. Create `workflows/my_workflow.py`: + +```python +from pydantic import BaseModel, Field +from typing import List +from comfy_script.runtime import * +load('http://127.0.0.1:8188/') +from comfy_script.runtime.nodes import * + +import sys, os +sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) +from base import BaseWorkflow +from parameters import Prompt, NegativePrompt, Checkpoint, Seed, Width, Height + +WORKFLOW_METADATA = { + "name": "My Custom Workflow", + "description": "Description of what this workflow does.", + "model_types": ["SD1.5", "SDXL"], + "category": "Image Generation", +} + +class WorkflowParams(BaseModel): + prompt: Prompt + negativePrompt: NegativePrompt = "blurry, low quality" + checkpoints: Checkpoint + seed: Seed + width: Width = 512 + height: Height = 512 + steps: int = Field(default=20, ge=1, le=150) + +class MyWorkflow(BaseWorkflow): + def run(self): + params: WorkflowParams = self.params + + with Workflow(wait=False): + model, clip, vae = self.load_checkpoints() + # ... your workflow logic + preview = PreviewImage(image) + + return { + 'prompt_id': preview.task.prompt_id, + 'status': 'queued', + 'parameters': self.params.model_dump() + } + +def run_workflow(**kwargs): + params = WorkflowParams(**kwargs) + workflow = MyWorkflow(params) + return workflow.run() +``` + +2. Generate the YAML schema: + +```bash +python -m external-api generate my_workflow +``` + +3. Customize the generated `workflows/my_workflow.yaml` as needed. + +### Workflow Components + +| Component | Description | +| ------------------- | ---------------------------------------- | +| `WORKFLOW_METADATA` | Name, description, model_types, category | +| `WorkflowParams` | Pydantic model defining parameters | +| `run_workflow()` | Module entry point | +| `*.yaml` | Auto-generated UI schema | + +--- + +## YAML Schema System + +### Overview + +UI parameter schemas are auto-generated from Pydantic `WorkflowParams` models using `Annotated` types. The YAML files can be customized and changes are preserved on regeneration. + +### Annotated Types (parameters.py) + +```python +from typing import Annotated, List +from pydantic import Field + +# Text fields +Prompt = Annotated[str, Field( + json_schema_extra={"ui_type": "text", "category": "prompts", "multiline": True, "rows": 4} +)] + +# Special types +Seed = Annotated[int, Field( + json_schema_extra={"ui_type": "seed", "category": "parameters"} +)] + +# Enum types (options resolved from resources) +Sampler = Annotated[str, Field( + json_schema_extra={"ui_type": "enum", "options_source": "samplers", "category": "parameters"} +)] + +# Model selectors +Checkpoint = Annotated[List[str], Field( + json_schema_extra={"ui_type": "model", "options_source": "checkpoints", "category": "models"} +)] + +# Dimension fields +Width = Annotated[int, Field( + ge=64, le=2048, multiple_of=8, + json_schema_extra={"category": "composition"} +)] +``` + +### YAML Format + +```yaml +name: Basic SDXL Text to Image +description: Workflow with SDXL presets for quick iteration. +category: Image Generation +model_types: + - SDXL + +parameters: + - name: prompt + type: text + category: prompts + multiline: true + required: true + label: Your Creative Prompt + rows: 4 + placeholder: Describe your image... + description: Enter a detailed description + + - name: sampler + type: enum + options_source: samplers + category: parameters + default: euler + label: Sampler + searchable: true + + - name: width + type: int + category: composition + min: 64 + max: 2048 + step: 8 + default: 1024 + label: Width +``` + +### Merge Strategy + +When regenerating YAML schemas: + +**Preserved** (user customizations): + +- `label`, `description`, `placeholder` +- `rows`, `searchable`, `depends_on` +- `options`, `max_selections` + +**Updated** (from code): + +- `type`, `default`, `required` +- `min`, `max`, `step` +- `category`, `options_source` +- `multiple`, `params`, `multiline` + +### Parameter Types + +| Type | Description | Properties | +| ------------------- | ------------------- | ---------------------------------- | +| `text` | Text input | `multiline`, `rows`, `placeholder` | +| `int` | Integer | `min`, `max`, `step` | +| `float` | Decimal | `min`, `max`, `step` | +| `bool` | Boolean toggle | - | +| `enum` | Dropdown | `options_source`, `searchable` | +| `seed` | Random seed | - | +| `model` | Model selector | `options_source`, `multiple` | +| `model_with_params` | Model with settings | `options_source`, `params` | + +### options_source Values + +| Source | Description | +| ----------------- | ---------------------- | +| `samplers` | KSampler samplers | +| `schedulers` | KSampler schedulers | +| `upscale_methods` | Latent upscale methods | +| `checkpoints` | Checkpoint models | +| `loras` | LoRA models | +| `vae` | VAE models | +| `embeddings` | Text embeddings | +| `controlnet` | ControlNet models | + +--- + +## Resource System ### Model Discovery -#### `GET /models` +Resources are discovered from ComfyUI's configured model folders: -List all model types available in ComfyUI. - -**Response Type:** `application/json` - -**Response:** Array of model type strings - -```json -["checkpoints", "loras", "vae", "embeddings", "controlnet", ...] +```python +# resources.py +def get_models_by_type(model_type: str) -> List[Dict]: + """Returns list of {label, apiName, indexed}""" ``` ---- +### Model Indexing -#### `GET /models/{folder}` +Models can be indexed to calculate SHA256 hash and fetch CivitAI metadata: -Get filenames for a specific model type. - -**Parameters:** - -- `folder` (path): Model type (`checkpoints`, `loras`, etc.) - -**Response Type:** `application/json` - -**Response:** Array of filenames - -```json -["model1.safetensors", "model2.ckpt", ...] -``` - -**JavaScript Example:** - -```javascript -// Get all checkpoints -const response = await fetch("http://127.0.0.1:8188/models/checkpoints"); -const checkpoints = await response.json(); -console.log("Checkpoints:", checkpoints); -``` - ---- - -### Image Viewing - -#### `GET /view?filename={filename}&type={type}&subfolder={subfolder}` - -View/download generated images. - -**Parameters:** - -- `filename` (query): Image filename -- `type` (query): Directory type (`output`, `input`, `temp`) -- `subfolder` (query, optional): Subdirectory path -- `preview` (query, optional): Format and quality (e.g., `jpeg;80`) -- `channel` (query, optional): Color channel (`rgb`, `rgba`, `a`) - -**Response Type:** `image/*` or file download - -**JavaScript Example:** - -```javascript -// Display generated image -const imageUrl = `http://127.0.0.1:8188/view?filename=ComfyUI_00001.png&type=output`; -document.getElementById("result-img").src = imageUrl; - -// Get preview (smaller, compressed) -const previewUrl = `http://127.0.0.1:8188/view?filename=ComfyUI_00001.png&type=output&preview=jpeg;80`; -``` - ---- - -### Queue Management - -#### `GET /queue` - -Get current queue status. - -**Response Type:** `application/json` - -**Response Schema:** - -```json +```python +# Index file format (.index) { - "queue_running": [ - [ - 1, - "prompt_id", - { - /* prompt */ - }, - { - /* extra_data */ - }, - [] - ] - ], - "queue_pending": [] + "filename": "model.safetensors", + "hash": "sha256...", + "civitai": { + "modelId": 1234, + "name": "Model Name", + "baseModel": "SDXL" + }, + "imagelab": {} } ``` +### Auto-Indexing + +By default, new models are indexed in a background thread at startup: + +```python +# __init__.py +AUTO_INDEX_ON_STARTUP = True +``` + --- -#### `POST /queue` +## CLI Commands -Modify the queue (clear or delete items). +The CLI is used for managing YAML workflow schemas. -**Request Type:** `application/json` +```bash +# Generate schema for a workflow +python -m external-api generate basic_sdxl -**Request Body:** +# Generate for all workflows +python -m external-api generate --all -```json -{ - "clear": true // Clear all pending items -} +# Preview without writing (dry-run) +python -m external-api generate basic_sdxl --dry-run + +# Validate schema matches code +python -m external-api validate basic_sdxl +python -m external-api validate --all + +# List all workflows +python -m external-api list + +# Watch mode (auto-regenerate on file changes) +pip install watchdog # required for watch +python -m external-api watch ``` -or +### Watch Mode -```json -{ - "delete": ["prompt_id1", "prompt_id2"] // Delete specific items -} +Monitors the `workflows/` folder and auto-regenerates YAML when `.py` files change: + +```bash +$ python -m external-api watch +Watching for changes in: .../workflows +Press Ctrl+C to stop. +✓ basic_sdxl +✓ basic_test1 +✓ test + +[12:34:56] Regenerating: basic_sdxl +✓ basic_sdxl.yaml updated ``` -**JavaScript Example:** +--- + +## JavaScript Examples + +### Complete Workflow Execution ```javascript -// Clear the queue -await fetch("http://127.0.0.1:8188/queue", { +class ImageLabAPI { + constructor(baseUrl = "http://127.0.0.1:8188") { + this.baseUrl = baseUrl; + this.ws = null; + this.handlers = {}; + } + + // Connect WebSocket for progress updates + connect() { + return new Promise((resolve, reject) => { + const clientId = `client-${Date.now()}`; + this.ws = new WebSocket( + `${this.baseUrl.replace("http", "ws")}/ws?clientId=${clientId}` + ); + this.ws.onopen = () => resolve(); + this.ws.onerror = reject; + this.ws.onmessage = (e) => this.handleMessage(e); + }); + } + + async handleMessage(event) { + if (event.data instanceof Blob) { + const buffer = await event.data.arrayBuffer(); + const view = new DataView(buffer); + const eventType = view.getUint32(0, false); + + if (eventType === 100) { + const json = JSON.parse(new TextDecoder().decode(buffer.slice(4))); + this.emit("progress", json); + } else if (eventType === 101) { + const metaLen = view.getUint32(4, false); + const metadata = JSON.parse( + new TextDecoder().decode(buffer.slice(8, 8 + metaLen)) + ); + const imageBlob = new Blob([buffer.slice(8 + metaLen)]); + this.emit("preview", { url: URL.createObjectURL(imageBlob), metadata }); + } + } + } + + on(event, handler) { + this.handlers[event] = this.handlers[event] || []; + this.handlers[event].push(handler); + } + + emit(event, data) { + (this.handlers[event] || []).forEach((h) => h(data)); + } + + // List workflows + async getWorkflows() { + const res = await fetch(`${this.baseUrl}/imagelab/workflows`); + return (await res.json()).workflows; + } + + // Get workflow parameters with resolved options + async getParameters(workflowId) { + const res = await fetch( + `${this.baseUrl}/imagelab/workflow/${workflowId}/parameters` + ); + return (await res.json()).parameters; + } + + // Execute workflow + async execute(workflowId, params) { + const res = await fetch(`${this.baseUrl}/imagelab/workflow/${workflowId}`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(params), + }); + return await res.json(); + } + + // Get resources + async getResources() { + const res = await fetch(`${this.baseUrl}/imagelab/resources`); + return (await res.json()).resources; + } +} + +// Usage +const api = new ImageLabAPI(); +await api.connect(); + +api.on("progress", (data) => { + progressBar.style.width = `${data.progress_percent}%`; +}); + +api.on("preview", ({ url }) => { + previewImg.src = url; +}); + +const result = await api.execute("basic_sdxl", { + prompt: "a beautiful mountain landscape", + negativePrompt: "blurry", + checkpoints: ["dreamshaper_8.safetensors"], + seed: 42, + steps: 20, + width: 1024, + height: 1024, + cfg: 8.0, +}); + +console.log("Queued:", result.result.prompt_id); +``` + +### Cancel Execution + +```javascript +// Cancel current execution +await fetch("http://localhost:8188/interrupt", { method: "POST" }); + +// Cancel specific prompt +await fetch("http://localhost:8188/interrupt", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ prompt_id: "abc123" }), +}); +``` + +### Clear Queue + +```javascript +await fetch("http://localhost:8188/queue", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ clear: true }), @@ -526,822 +874,38 @@ await fetch("http://127.0.0.1:8188/queue", { --- -#### `POST /interrupt` +## Dependencies -Interrupt current execution. - -**Request Type:** `application/json` (optional) - -**Request Body (optional):** - -```json -{ - "prompt_id": "abc123" // Interrupt specific prompt -} -``` - -**JavaScript Example:** - -```javascript -// Interrupt all -await fetch("http://127.0.0.1:8188/interrupt", { method: "POST" }); - -// Interrupt specific prompt -await fetch("http://127.0.0.1:8188/interrupt", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ prompt_id: currentPromptId }), -}); -``` - ---- - -### History - -#### `GET /history` - -Get execution history. - -**Query Parameters:** - -- `max_items` (optional): Maximum items to return -- `offset` (optional): Pagination offset - -**Response Type:** `application/json` - -**Response:** Object with prompt IDs as keys - -```json -{ - "prompt_id_1": { - "prompt": [ - /* nodes */ - ], - "outputs": { - /* output data */ - }, - "status": { - /* execution status */ - } - } -} -``` - ---- - -#### `GET /history/{prompt_id}` - -Get history for a specific prompt. - -**Parameters:** - -- `prompt_id` (path): Prompt identifier - -**Response Type:** `application/json` - ---- - -### System Info - -#### `GET /system_stats` - -Get system information (RAM, VRAM, versions). - -**Response Type:** `application/json` - -**Response Schema:** - -```json -{ - "system": { - "os": "win32", - "ram_total": 34359738368, - "ram_free": 12884901888, - "comfyui_version": "1.0.0", - "python_version": "3.12.0", - "pytorch_version": "2.1.0" - }, - "devices": [ - { - "name": "NVIDIA GeForce RTX 4090", - "type": "cuda", - "index": 0, - "vram_total": 25769803776, - "vram_free": 20000000000 - } - ] -} -``` - -**JavaScript Example:** - -```javascript -const response = await fetch("http://127.0.0.1:8188/system_stats"); -const { system, devices } = await response.json(); - -console.log(`VRAM: ${devices[0].vram_free / 1024 / 1024 / 1024} GB free`); -console.log(`RAM: ${system.ram_free / 1024 / 1024 / 1024} GB free`); -``` - ---- - -## WebSocket System - -### Connection - -**Endpoint:** `ws://127.0.0.1:8188/ws` - -**Optional Query Parameter:** `?clientId=your_client_id` - -ComfyUI's WebSocket supports both JSON text messages and binary messages. - -### Message Types - -#### JSON Messages (from ComfyUI) - -- `status`: Queue status updates -- `executing`: Currently executing node -- `executed`: Node execution completed -- `execution_start`: Workflow execution started -- `execution_cached`: Nodes that were cached -- `execution_error`: Error during execution -- `progress`: Execution progress (deprecated, use binary events) - -#### Binary Messages (from ImageLab) - -- **Event 100**: `IMAGELAB_PROGRESS_EVENT` - Progress data (JSON) -- **Event 101**: `IMAGELAB_PREVIEW_EVENT` - Preview image (binary) - -### JavaScript WebSocket Client - -```javascript -class ComfyUIClient { - constructor(serverUrl = "ws://127.0.0.1:8188/ws") { - this.ws = null; - this.serverUrl = serverUrl; - this.handlers = { - progress: [], - preview: [], - status: [], - executed: [], - }; - } - - connect() { - return new Promise((resolve, reject) => { - this.ws = new WebSocket(this.serverUrl); - - this.ws.onopen = () => { - console.log("Connected to ComfyUI"); - resolve(); - }; - - this.ws.onerror = (error) => { - console.error("WebSocket error:", error); - reject(error); - }; - - this.ws.onmessage = (event) => { - if (event.data instanceof Blob) { - this.handleBinaryMessage(event.data); - } else { - const message = JSON.parse(event.data); - this.handleJsonMessage(message); - } - }; - }); - } - - handleBinaryMessage(blob) { - blob.arrayBuffer().then((buffer) => { - const view = new DataView(buffer); - const eventType = view.getUint32(0); // First 4 bytes = event type - const payload = buffer.slice(4); - - if (eventType === 100) { - // IMAGELAB_PROGRESS_EVENT - const decoder = new TextDecoder(); - const jsonString = decoder.decode(payload); - const progressData = JSON.parse(jsonString); - this.emit("progress", progressData); - } else if (eventType === 101) { - // IMAGELAB_PREVIEW_EVENT - const blob = new Blob([payload], { type: "image/jpeg" }); - const imageUrl = URL.createObjectURL(blob); - this.emit("preview", imageUrl); - } - }); - } - - handleJsonMessage(message) { - const { type, data } = message; - this.emit(type, data); - } - - on(event, handler) { - if (!this.handlers[event]) { - this.handlers[event] = []; - } - this.handlers[event].push(handler); - } - - emit(event, data) { - if (this.handlers[event]) { - this.handlers[event].forEach((handler) => handler(data)); - } - } - - disconnect() { - if (this.ws) { - this.ws.close(); - } - } -} - -// Usage -const client = new ComfyUIClient(); -await client.connect(); - -// Listen for progress updates -client.on("progress", (data) => { - console.log(`Progress: ${data.progress_percent}%`); - updateProgressBar(data.progress_percent); -}); - -// Listen for preview images -client.on("preview", (imageUrl) => { - document.getElementById("preview-img").src = imageUrl; -}); - -// Listen for completion -client.on("executed", (data) => { - console.log("Node executed:", data); -}); - -client.on("status", (data) => { - console.log("Queue status:", data.status); -}); -``` - ---- - -## Binary Events - -### Event 100: IMAGELAB_PROGRESS_EVENT - -**Structure:** - -``` -[4 bytes: event type (100)] [remaining bytes: JSON as UTF-8] -``` - -**JSON Payload:** - -```json -{ - "value": 5, - "total": 20, - "prompt_id": "abc123-def456-...", - "node_id": "KSampler.0", - "progress_percent": 25.0 -} -``` - -**JavaScript Parsing:** - -```javascript -// In handleBinaryMessage -if (eventType === 100) { - const decoder = new TextDecoder("utf-8"); - const jsonString = decoder.decode(payload); - const progress = JSON.parse(jsonString); - - console.log( - `${progress.value}/${progress.total} (${progress.progress_percent}%)` - ); -} -``` - ---- - -### Event 101: IMAGELAB_PREVIEW_EVENT - -**Structure:** - -``` -[4 bytes: event type (101)] [remaining bytes: image data (JPEG or PNG)] -``` - -**JavaScript Parsing:** - -```javascript -// In handleBinaryMessage -if (eventType === 101) { - // Create a blob from the raw image data - const imageBlob = new Blob([payload], { type: "image/jpeg" }); - - // Create object URL for display - const imageUrl = URL.createObjectURL(imageBlob); - - // Display in img element - document.getElementById("preview").src = imageUrl; - - // Don't forget to revoke when done - // URL.revokeObjectURL(imageUrl); -} -``` - ---- - -## JavaScript Examples - -### Complete Workflow Execution Example - -```javascript -class ImageLabClient { - constructor() { - this.baseUrl = "http://127.0.0.1:8188"; - this.ws = null; - } - - async executeWorkflow(workflowName, parameters) { - // 1. Connect WebSocket for progress monitoring - await this.connectWebSocket(); - - // 2. Execute workflow - const response = await fetch( - `${this.baseUrl}/imagelab/workflow/${workflowName}`, - { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(parameters), - } - ); - - const { result } = await response.json(); - console.log("Workflow started:", result.prompt_id); - - return result.prompt_id; - } - - async connectWebSocket() { - return new Promise((resolve, reject) => { - this.ws = new WebSocket("ws://127.0.0.1:8188/ws"); - - this.ws.onopen = () => resolve(); - this.ws.onerror = reject; - - this.ws.onmessage = (event) => { - if (event.data instanceof Blob) { - this.handleBinaryMessage(event.data); - } else { - const message = JSON.parse(event.data); - if (message.type === "executed") { - this.onWorkflowComplete(message.data); - } - } - }; - }); - } - - handleBinaryMessage(blob) { - blob.arrayBuffer().then((buffer) => { - const view = new DataView(buffer); - const eventType = view.getUint32(0); - const payload = buffer.slice(4); - - if (eventType === 100) { - // Progress - const decoder = new TextDecoder(); - const progress = JSON.parse(decoder.decode(payload)); - this.onProgress(progress); - } else if (eventType === 101) { - // Preview image - const imageUrl = URL.createObjectURL( - new Blob([payload], { type: "image/jpeg" }) - ); - this.onPreview(imageUrl); - } - }); - } - - onProgress(data) { - console.log(`Progress: ${data.progress_percent}%`); - // Update UI - document.getElementById("progress-bar").style.width = - `${data.progress_percent}%`; - document.getElementById("progress-text").textContent = - `${data.value}/${data.total} steps`; - } - - onPreview(imageUrl) { - document.getElementById("preview-image").src = imageUrl; - } - - onWorkflowComplete(data) { - console.log("Workflow complete!", data); - // Fetch final output images - this.displayOutputs(data); - } - - async displayOutputs(executionData) { - // Parse output data to get image filenames - const outputs = executionData.output; - - for (const nodeId in outputs) { - const output = outputs[nodeId]; - if (output.images) { - output.images.forEach((img) => { - const imageUrl = `${this.baseUrl}/view?filename=${img.filename}&type=${img.type}&subfolder=${img.subfolder || ""}`; - - // Display image - const imgElement = document.createElement("img"); - imgElement.src = imageUrl; - document.getElementById("output-gallery").appendChild(imgElement); - }); - } - } - } -} - -// Usage -const client = new ImageLabClient(); - -await client.executeWorkflow("test_workflow", { - prompt: "a beautiful sunset over mountains, highly detailed", - negativePrompt: "blurry, low quality, watermark", - checkpoints: ["dreamshaper_8.safetensors"], - loras: [ - { - apiName: "add_detail.safetensors", - disabled: false, - parameters: { strength_model: 0.8, strength_clip: 0.8 }, - }, - ], - steps: 20, - seed: Math.floor(Math.random() * 1000000), - width: 512, - height: 512, -}); -``` - ---- - -### Resource Management Example - -```javascript -class ResourceManager { - constructor(baseUrl = "http://127.0.0.1:8188") { - this.baseUrl = baseUrl; - this.cache = { - resources: null, - metadata: new Map(), - }; - } - - async loadAllResources() { - const response = await fetch(`${this.baseUrl}/imagelab/resources`); - const { resources } = await response.json(); - this.cache.resources = resources; - return resources; - } - - async loadResourceType(type) { - const response = await fetch(`${this.baseUrl}/imagelab/resources/${type}`); - const { items } = await response.json(); - return items; - } - - async getModelMetadata(type, filename) { - // Check cache first - const cacheKey = `${type}:${filename}`; - if (this.cache.metadata.has(cacheKey)) { - return this.cache.metadata.get(cacheKey); - } - - // Fetch and index - const response = await fetch( - `${this.baseUrl}/imagelab/resources/${type}/index/${encodeURIComponent(filename)}`, - { method: "POST" } - ); - const { metadata } = await response.json(); - - // Cache result - this.cache.metadata.set(cacheKey, metadata); - return metadata; - } - - async indexAllModels() { - const response = await fetch( - `${this.baseUrl}/imagelab/resources/index-all`, - { - method: "POST", - } - ); - return await response.json(); - } - - // Build UI dropdowns - async populateCheckpointSelector(selectElement) { - const checkpoints = await this.loadResourceType("checkpoints"); - - selectElement.innerHTML = ""; - checkpoints.forEach((model) => { - const option = document.createElement("option"); - option.value = model.apiName; - option.textContent = model.label; - option.dataset.indexed = model.indexed; - selectElement.appendChild(option); - }); - } - - // Show model info on hover/click - async showModelInfo(type, filename, targetElement) { - const metadata = await this.getModelMetadata(type, filename); - - if (metadata.civitai) { - targetElement.innerHTML = ` -
${metadata.civitai.description}
- ${ - metadata.civitai.images && metadata.civitai.images[0] - ? `