Archived
1349 lines
31 KiB
Markdown
1349 lines
31 KiB
Markdown
# 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.
|
|
|
|
---
|
|
|
|
## 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)
|
|
|
|
---
|
|
|
|
## Architecture Overview
|
|
|
|
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
|
|
|
|
### Technology Stack
|
|
|
|
- **Server**: ComfyUI (aiohttp web server)
|
|
- **Workflow Engine**: ComfyScript (Python runtime for ComfyUI)
|
|
- **Validation**: Pydantic (parameter validation)
|
|
- **Communication**: REST + WebSocket (JSON and Binary)
|
|
|
|
---
|
|
|
|
## ImageLab API Endpoints
|
|
|
|
### Workflow Endpoints
|
|
|
|
#### `GET /imagelab/workflows`
|
|
|
|
List all available workflows with metadata.
|
|
|
|
**Response Type:** `application/json`
|
|
|
|
**Response Schema:**
|
|
|
|
```json
|
|
{
|
|
"workflows": [
|
|
{
|
|
"id": "test_workflow",
|
|
"name": "Test Workflow",
|
|
"description": "Simple test workflow for image generation",
|
|
"model_types": ["SDXL", "Pony", "Illustrious"],
|
|
"category": "Image Generation"
|
|
}
|
|
]
|
|
}
|
|
```
|
|
|
|
**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:**
|
|
|
|
```json
|
|
{
|
|
"success": true,
|
|
"workflow": "test_workflow",
|
|
"metadata": {
|
|
"name": "Test Workflow",
|
|
"description": "Simple test workflow for image generation",
|
|
"model_types": ["SDXL", "Pony", "Illustrious"],
|
|
"category": "generation"
|
|
}
|
|
}
|
|
```
|
|
|
|
**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);
|
|
```
|
|
|
|
---
|
|
|
|
#### `POST /imagelab/workflow/{workflow_name}`
|
|
|
|
Execute a workflow with parameters.
|
|
|
|
**Parameters:**
|
|
|
|
- `workflow_name` (path): Workflow identifier
|
|
|
|
**Request Type:** `application/json`
|
|
|
|
**Request Body:** Varies by workflow. Example:
|
|
|
|
```json
|
|
{
|
|
"prompt": "a beautiful sunset over mountains",
|
|
"negativePrompt": "blurry, low quality",
|
|
"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
|
|
}
|
|
```
|
|
|
|
**Response Type:** `application/json`
|
|
|
|
**Response Schema:**
|
|
|
|
```json
|
|
{
|
|
"success": true,
|
|
"workflow": "test_workflow",
|
|
"result": {
|
|
"prompt_id": "abc123-def456-...",
|
|
"status": "queued",
|
|
"parameters": {
|
|
/* echo of input parameters */
|
|
}
|
|
}
|
|
}
|
|
```
|
|
|
|
**Error Response:**
|
|
|
|
```json
|
|
{
|
|
"success": false,
|
|
"type": "ValueError",
|
|
"error": "Workflow 'invalid_name' not found. Available: ['test_workflow']"
|
|
}
|
|
```
|
|
|
|
**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
|
|
|
|
#### `GET /imagelab/resources`
|
|
|
|
Get all available resources (models, samplers, schedulers).
|
|
|
|
**Response Type:** `application/json`
|
|
|
|
**Response Schema:**
|
|
|
|
```json
|
|
{
|
|
"success": true,
|
|
"resources": {
|
|
"checkpoints": [
|
|
{
|
|
"label": "dreamshaper_8",
|
|
"apiName": "dreamshaper_8.safetensors",
|
|
"indexed": true
|
|
}
|
|
],
|
|
"loras": [
|
|
/* ... */
|
|
],
|
|
"samplers": [{ "label": "euler", "apiName": "euler", "metadata": null }],
|
|
"schedulers": [
|
|
{ "label": "normal", "apiName": "normal", "metadata": null }
|
|
],
|
|
"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:**
|
|
|
|
- `resource_type` (path): Type of resource (`checkpoints`, `loras`, `vae`, `samplers`, `schedulers`, `upscale_methods`, etc.)
|
|
|
|
**Response Type:** `application/json`
|
|
|
|
**Response Schema:**
|
|
|
|
```json
|
|
{
|
|
"success": true,
|
|
"resource_type": "loras",
|
|
"items": [
|
|
{
|
|
"label": "add_detail",
|
|
"apiName": "add_detail.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.
|
|
|
|
**Parameters:**
|
|
|
|
- `resource_type` (path): Type of resource (`checkpoints`, `loras`, etc.)
|
|
- `filename` (path): Exact filename including extension
|
|
|
|
**Response Type:** `application/json`
|
|
|
|
**Response Schema:**
|
|
|
|
```json
|
|
{
|
|
"success": true,
|
|
"resource_type": "checkpoints",
|
|
"filename": "dreamshaper_8.safetensors",
|
|
"metadata": {
|
|
"filename": "dreamshaper_8.safetensors",
|
|
"hash": "9aba26abdf...",
|
|
"civitai": {
|
|
"id": 12345,
|
|
"name": "DreamShaper 8",
|
|
"description": "...",
|
|
"images": [
|
|
/* preview images */
|
|
]
|
|
},
|
|
"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.
|
|
|
|
**Response Type:** `application/json`
|
|
|
|
**Response Schema:**
|
|
|
|
```json
|
|
{
|
|
"success": true,
|
|
"message": "Indexing complete",
|
|
"indexed": {
|
|
"checkpoints": 5,
|
|
"loras": 12,
|
|
"vae": 2
|
|
}
|
|
}
|
|
```
|
|
|
|
**JavaScript Example:**
|
|
|
|
```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);
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## ComfyUI API Endpoints
|
|
|
|
These are the core ComfyUI endpoints you'll use alongside ImageLab endpoints.
|
|
|
|
### Model Discovery
|
|
|
|
#### `GET /models`
|
|
|
|
List all model types available in ComfyUI.
|
|
|
|
**Response Type:** `application/json`
|
|
|
|
**Response:** Array of model type strings
|
|
|
|
```json
|
|
["checkpoints", "loras", "vae", "embeddings", "controlnet", ...]
|
|
```
|
|
|
|
---
|
|
|
|
#### `GET /models/{folder}`
|
|
|
|
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
|
|
{
|
|
"queue_running": [
|
|
[
|
|
1,
|
|
"prompt_id",
|
|
{
|
|
/* prompt */
|
|
},
|
|
{
|
|
/* extra_data */
|
|
},
|
|
[]
|
|
]
|
|
],
|
|
"queue_pending": []
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
#### `POST /queue`
|
|
|
|
Modify the queue (clear or delete items).
|
|
|
|
**Request Type:** `application/json`
|
|
|
|
**Request Body:**
|
|
|
|
```json
|
|
{
|
|
"clear": true // Clear all pending items
|
|
}
|
|
```
|
|
|
|
or
|
|
|
|
```json
|
|
{
|
|
"delete": ["prompt_id1", "prompt_id2"] // Delete specific items
|
|
}
|
|
```
|
|
|
|
**JavaScript Example:**
|
|
|
|
```javascript
|
|
// Clear the queue
|
|
await fetch("http://127.0.0.1:8188/queue", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ clear: true }),
|
|
});
|
|
```
|
|
|
|
---
|
|
|
|
#### `POST /interrupt`
|
|
|
|
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 = `
|
|
<h3>${metadata.civitai.name}</h3>
|
|
<p>${metadata.civitai.description}</p>
|
|
${
|
|
metadata.civitai.images && metadata.civitai.images[0]
|
|
? `<img src="${metadata.civitai.images[0].url}" />`
|
|
: ""
|
|
}
|
|
`;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Usage
|
|
const resourceManager = new ResourceManager();
|
|
|
|
// Load all resources
|
|
const resources = await resourceManager.loadAllResources();
|
|
console.log("Available checkpoints:", resources.checkpoints.length);
|
|
|
|
// Populate dropdown
|
|
const select = document.getElementById("checkpoint-select");
|
|
await resourceManager.populateCheckpointSelector(select);
|
|
|
|
// Show model info on selection
|
|
select.addEventListener("change", async (e) => {
|
|
const filename = e.target.value;
|
|
const infoDiv = document.getElementById("model-info");
|
|
await resourceManager.showModelInfo("checkpoints", filename, infoDiv);
|
|
});
|
|
```
|
|
|
|
---
|
|
|
|
## Core Systems
|
|
|
|
### 1. Workflow System
|
|
|
|
**Location:** `workflows/`, `workflows.py`, `base.py`
|
|
|
|
**Purpose:** Execute ComfyScript-based workflows via REST API with hot reloading.
|
|
|
|
**Architecture:**
|
|
|
|
```
|
|
workflows.py (registry)
|
|
├── WORKFLOW_FILES: Dict[str, dict] // Maps workflow IDs to config
|
|
├── load_workflow_module() // Dynamically loads workflow files
|
|
└── get_workflow() // Returns workflow function (reloads each time)
|
|
|
|
base.py (base class)
|
|
├── BaseWorkflow // Abstract base for all workflows
|
|
│ ├── load_checkpoints() // Load/merge checkpoint models
|
|
│ ├── apply_loras() // Apply LoRA models
|
|
│ └── run() // Abstract method (override in subclass)
|
|
└── Exports: WorkflowParams, Lora, etc.
|
|
|
|
workflows/test.py (example)
|
|
├── WorkflowParams // Pydantic model for parameters
|
|
├── TestWorkflow(BaseWorkflow) // Workflow implementation
|
|
└── run_workflow(**kwargs) // Module entry point
|
|
```
|
|
|
|
**Key Features:**
|
|
|
|
- **Hot Reload**: Workflows are reloaded from disk on each execution
|
|
- **Validation**: Pydantic validates parameters before execution
|
|
- **Base Class**: Common operations (checkpoint loading, LoRA application) in BaseWorkflow
|
|
- **Metadata**: Each workflow has name, description, model types, category
|
|
|
|
**Adding a New Workflow:**
|
|
|
|
1. Create `workflows/my_workflow.py`
|
|
2. Define `WorkflowParams(BaseModel)` with your parameters
|
|
3. Create `MyWorkflow(BaseWorkflow)` and implement `run()`
|
|
4. Add `run_workflow(**kwargs)` entry point
|
|
5. Register in `workflows.py` WORKFLOW_FILES dict
|
|
|
|
---
|
|
|
|
### 2. Resource System
|
|
|
|
**Location:** `resources.py`
|
|
|
|
**Purpose:** Discover models, calculate hashes, fetch CivitAI metadata.
|
|
|
|
**Architecture:**
|
|
|
|
```
|
|
resources.py
|
|
├── RESOURCES_DIR // Stores .index files
|
|
├── calculate_sha256() // Hash calculation
|
|
├── get_index() / save_index() // Index file I/O
|
|
├── get_civitai_metadata() // Fetch from CivitAI API
|
|
├── index_model() // Index single model
|
|
├── get_models_by_type() // List models (fast, no indexing)
|
|
├── index_model_by_name() // Index specific model on-demand
|
|
└── index_all_new_models() // Batch index unindexed models
|
|
```
|
|
|
|
**Index File Format:**
|
|
|
|
```json
|
|
{
|
|
"filename": "model.safetensors",
|
|
"hash": "9aba26abdf...",
|
|
"civitai": {
|
|
"id": 12345,
|
|
"name": "Model Name",
|
|
"description": "...",
|
|
"images": [...]
|
|
},
|
|
"imagelab": {}
|
|
}
|
|
```
|
|
|
|
**Key Features:**
|
|
|
|
- **Lazy Indexing**: Only index when explicitly requested
|
|
- **Caching**: Index files stored as `{filename}.index` in resources folder
|
|
- **CivitAI Integration**: Automatically fetches model info by hash
|
|
- **Batch Operations**: Can index all new models at once
|
|
|
|
---
|
|
|
|
### 3. Progress System
|
|
|
|
**Location:** `progress.py`, `__init__.py`
|
|
|
|
**Purpose:** Monitor workflow execution progress in real-time.
|
|
|
|
**Architecture:**
|
|
|
|
```
|
|
progress.py
|
|
└── add_progress_hook() // Wraps ComfyUI's progress system
|
|
|
|
__init__.py
|
|
├── IMAGELAB_PROGRESS_EVENT (100) // Binary event for progress JSON
|
|
├── IMAGELAB_PREVIEW_EVENT (101) // Binary event for preview images
|
|
└── my_progress_callback() // Sends progress via WebSocket
|
|
```
|
|
|
|
**Flow:**
|
|
|
|
1. ComfyUI calls progress hook during execution
|
|
2. `my_progress_callback()` receives: `(value, total, preview_image, prompt_id, node_id)`
|
|
3. Sends two separate binary WebSocket messages:
|
|
- Event 100: Progress data as JSON
|
|
- Event 101: Preview image as JPEG/PNG bytes
|
|
|
|
**Key Features:**
|
|
|
|
- **Non-blocking**: Uses binary events to avoid slowing down execution
|
|
- **Separate Preview**: Images sent as binary for efficiency
|
|
- **Broadcast**: Sent to all connected WebSocket clients
|
|
|
|
---
|
|
|
|
### 4. WebSocket System
|
|
|
|
**Location:** ComfyUI's `server.py` (built-in)
|
|
|
|
**Purpose:** Real-time bidirectional communication for progress, events, status.
|
|
|
|
**Message Types:**
|
|
|
|
- **Text Messages (JSON)**: ComfyUI status updates, execution events
|
|
- **Binary Messages**: ImageLab progress and preview images
|
|
|
|
**Binary Message Structure:**
|
|
|
|
```
|
|
Byte 0-3: Event type (uint32, big-endian)
|
|
Byte 4-end: Payload (JSON or raw bytes)
|
|
```
|
|
|
|
**Client Implementation:**
|
|
|
|
- Connect to `ws://127.0.0.1:8188/ws`
|
|
- Handle both text (JSON) and binary (Blob/ArrayBuffer) messages
|
|
- Parse binary: Read first 4 bytes as event type, remaining as payload
|
|
|
|
---
|
|
|
|
### 5. Parameter Validation System
|
|
|
|
**Location:** `parameters.py`
|
|
|
|
**Purpose:** Type-safe parameter validation using Pydantic.
|
|
|
|
**Models:**
|
|
|
|
```python
|
|
LoraParameters(BaseModel)
|
|
├── strength_model: float = 1.0
|
|
└── strength_clip: float = 1.0
|
|
|
|
Lora(BaseModel)
|
|
├── apiName: str
|
|
├── disabled: bool = False
|
|
└── parameters: LoraParameters
|
|
|
|
WorkflowParams (base class, extend in workflow files)
|
|
├── prompt: str
|
|
├── negativePrompt: str
|
|
├── checkpoints: List[str]
|
|
├── loras: List[Lora]
|
|
├── steps: int
|
|
├── seed: int
|
|
└── width/height: int
|
|
```
|
|
|
|
**Key Features:**
|
|
|
|
- **Type Safety**: Automatic validation and type conversion
|
|
- **Defaults**: Sensible defaults for optional parameters
|
|
- **Extensible**: Workflows can extend base classes with custom fields
|
|
- **Error Messages**: Clear validation errors sent to client
|
|
|
|
---
|
|
|
|
## Best Practices
|
|
|
|
### Frontend Development
|
|
|
|
1. **Always use WebSocket**: Connect to `/ws` before executing workflows for progress monitoring
|
|
2. **Handle Binary Events**: Implement proper binary message parsing for Event 100/101
|
|
3. **Cache Resources**: Load resource lists once, cache locally
|
|
4. **Lazy Load Metadata**: Only index models when user requests info (tooltip, detail view)
|
|
5. **Error Handling**: Always check `success` field in responses
|
|
6. **Clean Up URLs**: Revoke object URLs created from blobs to prevent memory leaks
|
|
|
|
### Workflow Development
|
|
|
|
1. **Extend BaseWorkflow**: Always inherit from BaseWorkflow for common functionality
|
|
2. **Validate Parameters**: Use Pydantic models for all workflow parameters
|
|
3. **Return Prompt ID**: Always return the prompt_id for tracking
|
|
4. **Handle Errors**: Wrap ComfyScript calls in try/catch and return meaningful errors
|
|
5. **Document Metadata**: Add clear metadata to WORKFLOW_FILES for frontend discovery
|
|
|
|
### Performance
|
|
|
|
1. **Skip Indexing by Default**: Use fast endpoints for listing, index on-demand
|
|
2. **Batch Operations**: Use `/resources/index-all` for bulk indexing (startup or manual trigger)
|
|
3. **WebSocket Connection**: Reuse WebSocket connection for multiple workflows
|
|
4. **Image Formats**: Use JPEG for previews, PNG for final output
|
|
5. **Query Optimization**: Fetch only needed data (avoid loading all resources repeatedly)
|
|
|
|
---
|
|
|
|
## Troubleshooting
|
|
|
|
### WebSocket Issues
|
|
|
|
- **Connection Refused**: Ensure ComfyUI server is running
|
|
- **No Progress Events**: Check that workflow is using ComfyScript runtime
|
|
- **Binary Parse Errors**: Verify big-endian uint32 parsing for event type
|
|
|
|
### Workflow Errors
|
|
|
|
- **Import Errors**: Check that `base.py` is properly loading parameters module
|
|
- **Validation Errors**: Ensure all required parameters are provided
|
|
- **Execution Hangs**: Check ComfyUI logs, may be out of memory
|
|
|
|
### Resource Issues
|
|
|
|
- **Missing Models**: Verify model files exist in ComfyUI model directories
|
|
- **Indexing Slow**: SHA256 calculation is CPU-intensive, normal for large models
|
|
- **CivitAI Errors**: Rate limiting or network issues, retry with exponential backoff
|
|
|
|
---
|
|
|
|
## API Change Log
|
|
|
|
### Version 1.0
|
|
|
|
- Initial release
|
|
- Workflow execution endpoints
|
|
- Resource discovery with lazy indexing
|
|
- Binary WebSocket events for progress
|
|
- CivitAI metadata integration
|
|
|
|
---
|
|
|
|
**End of Documentation**
|