Remove outdated test workflows and add CivitAI model management module with API routes

This commit is contained in:
donny committed 2026-01-11 21:48:46 -07:00
1 parent 2f64f3c80c
commit bea3ff3120
15 files changed
+1547 -1835

No files matched your search

-1042
View File
File diff suppressed because it is too large. Load diff
-147
View File
@@ -1,147 +0,0 @@
# External API Custom Node
REST API endpoints for executing ComfyScript workflows with YAML-based UI schemas.
> **Full documentation:** See [DOCUMENTATION.md](DOCUMENTATION.md) for complete API reference, WebSocket events, and JavaScript examples.
## Quick Start
```bash
# List workflows
curl http://localhost:8188/imagelab/workflows
# Get workflow parameters (with resolved options)
curl http://localhost:8188/imagelab/workflow/basic_sdxl/parameters
# Execute workflow
curl -X POST http://localhost:8188/imagelab/workflow/basic_sdxl \
-H "Content-Type: application/json" \
-d '{
"prompt": "a beautiful sunset",
"negativePrompt": "blurry",
"checkpoints": ["model.safetensors"],
"seed": 42,
"steps": 20,
"width": 1024,
"height": 1024,
"cfg": 8.0
}'
```
## Structure
```
external-api/
├── __init__.py # Entry point, registers routes
├── __main__.py # CLI entry point
├── cli.py # CLI commands (generate, validate, list, watch)
├── schema_generator.py # YAML schema generation
├── 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
└── workflows/
├── basic_sdxl.py # Workflow code
├── basic_sdxl.yaml # Auto-generated UI schema
└── ...
```
## Adding New Workflows
1. Create `workflows/my_workflow.py`:
```python
from pydantic import BaseModel, Field
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, Seed, Checkpoint, Width, Height
WORKFLOW_METADATA = {
"name": "My Workflow",
"description": "Description here.",
"model_types": ["SDXL"],
"category": "Image Generation",
}
class WorkflowParams(BaseModel):
prompt: Prompt
seed: Seed
checkpoints: Checkpoint
width: Width = 1024
height: Height = 1024
steps: int = Field(default=20, ge=1, le=150)
class MyWorkflow(BaseWorkflow):
def run(self):
with Workflow(wait=False):
model, clip, vae = self.load_checkpoints()
# ... workflow logic
preview = PreviewImage(image)
return {'prompt_id': preview.task.prompt_id, 'status': 'queued'}
def run_workflow(**kwargs):
return MyWorkflow(WorkflowParams(**kwargs)).run()
```
2. Generate the YAML schema:
```bash
python -m external-api generate my_workflow
```
3. Customize the generated `workflows/my_workflow.yaml` as needed.
## CLI Commands
```bash
# Generate schemas
python -m external-api generate --all
python -m external-api generate basic_sdxl
python -m external-api generate basic_sdxl --dry-run
# Validate schemas
python -m external-api validate --all
# List workflows
python -m external-api list
# Watch mode (auto-regenerate on changes)
pip install watchdog
python -m external-api watch
```
## API Endpoints
| Endpoint | Method | Description |
| ----------------------------------------- | ------ | ----------------------- |
| `/imagelab/workflows` | GET | List all workflows |
| `/imagelab/workflow/{name}/metadata` | GET | Get workflow metadata |
| `/imagelab/workflow/{name}/parameters` | GET | Get UI parameter schema |
| `/imagelab/workflow/{name}` | POST | Execute workflow |
| `/imagelab/resources` | GET | Get all resources |
| `/imagelab/resources/{type}` | GET | Get resources by type |
| `/imagelab/resources/{type}/index/{file}` | POST | Index a model file |
| `/imagelab/hello` | GET | Test endpoint |
## WebSocket Events
Connect to `ws://127.0.0.1:8188/ws` for real-time updates:
| Event | Code | Description |
| -------- | ---- | --------------------- |
| Progress | 100 | Sampler step progress |
| Preview | 101 | Preview images |
| Workflow | 102 | Lifecycle events |
## Dependencies
- `pydantic` - Parameter validation
- `pyyaml` - YAML schema files
- `watchdog` (optional) - Watch mode
+2 -2
View File
@@ -5,8 +5,8 @@ from .workflows import *
from . import resources
# Apply the send_sync patch to broadcast progress to all WebSocket clients
add_progress_hook()
print("[ImageLab] progress patch applied successfully")
# add_progress_hook()
# print("[ImageLab] progress patch applied successfully")
# Register API routes
SetupRoutes(PromptServer.instance)
+1
View File
@@ -34,6 +34,7 @@ class BaseWorkflow:
if len(checkpoints) == 1:
# Single checkpoint - load directly
self.model, self.clip, self.vae = CheckpointLoaderSimple(checkpoints[0])
# self.clip = CLIPSetLastLayer(self.clip, -2)
else:
# Multiple checkpoints - merge them
self.model, self.clip, self.vae = self._merge_checkpoints(checkpoints)
+586
View File
@@ -0,0 +1,586 @@
"""
CivitAI model management module.
Provides search, download, and management of CivitAI models.
"""
import os
import asyncio
import aiohttp
import json
from typing import Dict, List, Optional, Any, Literal, Callable
from dataclasses import dataclass, field
from enum import Enum
import folder_paths
from . import resources
from .websocket import broadcast_progress
# Constants
CIVITAI_API_BASE = "https://civitai.com/api/v1"
CIVITAI_DOWNLOAD_BASE = "https://civitai.com/api/download/models"
# Model type to ComfyUI folder mapping
MODEL_TYPE_TO_FOLDER = {
"Checkpoint": "checkpoints",
"LORA": "loras",
"LoCon": "loras",
"DoRA": "loras",
"TextualInversion": "embeddings",
"Hypernetwork": "hypernetworks",
"Controlnet": "controlnet",
"VAE": "vae",
"Upscaler": "upscale_models",
"Poses": "poses",
"AestheticGradient": "embeddings",
"MotionModule": "animatediff_motion_lora",
}
# Reverse mapping for API
FOLDER_TO_MODEL_TYPE = {v: k for k, v in MODEL_TYPE_TO_FOLDER.items()}
class CivitAIError(Exception):
"""Base exception for CivitAI operations."""
def __init__(self, message: str, code: str = "CIVITAI_ERROR"):
self.message = message
self.code = code
super().__init__(message)
class CivitAIAuthError(CivitAIError):
"""Authentication error."""
def __init__(self, message: str = "API token required or invalid"):
super().__init__(message, "AUTH_ERROR")
class CivitAINotFoundError(CivitAIError):
"""Resource not found."""
def __init__(self, message: str = "Resource not found"):
super().__init__(message, "NOT_FOUND")
class CivitAIRateLimitError(CivitAIError):
"""Rate limited."""
def __init__(self, retry_after: int = 60):
super().__init__(f"Rate limited. Retry after {retry_after}s", "RATE_LIMITED")
self.retry_after = retry_after
class CivitAIDownloadError(CivitAIError):
"""Download failed."""
def __init__(self, message: str, version_id: int):
super().__init__(message, "DOWNLOAD_FAILED")
self.version_id = version_id
@dataclass
class DownloadProgress:
"""Download progress information."""
model_id: int
version_id: int
filename: str
downloaded_bytes: int
total_bytes: int
status: Literal["downloading", "completed", "failed", "cancelled"]
error: Optional[str] = None
speed_bps: float = 0.0
class CivitAIClient:
"""Async client for CivitAI API operations."""
def __init__(self, api_token: Optional[str] = None):
self.api_token = api_token or os.environ.get("CIVITAI_TOKEN")
self._active_downloads: Dict[int, asyncio.Task] = {}
self._download_progress: Dict[int, DownloadProgress] = {}
self._cancelled_downloads: set = set()
def _get_headers(self) -> Dict[str, str]:
"""Get request headers with optional auth."""
headers = {"Content-Type": "application/json"}
if self.api_token:
headers["Authorization"] = f"Bearer {self.api_token}"
return headers
async def _handle_response(self, response: aiohttp.ClientResponse) -> Dict[str, Any]:
"""Handle API response and raise appropriate errors."""
if response.status == 200:
return await response.json()
elif response.status == 401:
raise CivitAIAuthError("Invalid or missing API token")
elif response.status == 403:
raise CivitAIAuthError("Access forbidden - check API token permissions")
elif response.status == 404:
raise CivitAINotFoundError()
elif response.status == 429:
retry_after = int(response.headers.get("Retry-After", 60))
raise CivitAIRateLimitError(retry_after)
else:
text = await response.text()
raise CivitAIError(f"API error {response.status}: {text}")
async def search_models(
self,
query: Optional[str] = None,
types: Optional[List[str]] = None,
sort: str = "Most Downloaded",
period: str = "AllTime",
nsfw: Optional[bool] = None,
limit: int = 20,
page: int = 1,
base_models: Optional[List[str]] = None,
tag: Optional[str] = None,
) -> Dict[str, Any]:
"""
Search CivitAI models.
Args:
query: Search term
types: Model types (Checkpoint, LORA, etc.)
sort: Sort order (Highest Rated, Most Downloaded, Newest)
period: Time period (AllTime, Year, Month, Week, Day)
nsfw: Filter NSFW content (None = user preference)
limit: Results per page (max 100)
page: Page number
base_models: Base model filters (SD 1.5, SDXL 1.0, etc.)
tag: Filter by tag
Returns:
Dict with items and metadata
"""
params = {
"limit": min(limit, 100),
"page": page,
"sort": sort,
"period": period,
}
if query:
params["query"] = query
if types:
params["types"] = ",".join(types)
if nsfw is not None:
params["nsfw"] = str(nsfw).lower()
if base_models:
params["baseModels"] = ",".join(base_models)
if tag:
params["tag"] = tag
async with aiohttp.ClientSession() as session:
async with session.get(
f"{CIVITAI_API_BASE}/models",
params=params,
headers=self._get_headers(),
timeout=aiohttp.ClientTimeout(total=30)
) as response:
return await self._handle_response(response)
async def get_model(self, model_id: int) -> Dict[str, Any]:
"""Get model details by ID."""
async with aiohttp.ClientSession() as session:
async with session.get(
f"{CIVITAI_API_BASE}/models/{model_id}",
headers=self._get_headers(),
timeout=aiohttp.ClientTimeout(total=30)
) as response:
return await self._handle_response(response)
async def get_model_version(self, version_id: int) -> Dict[str, Any]:
"""Get model version details."""
async with aiohttp.ClientSession() as session:
async with session.get(
f"{CIVITAI_API_BASE}/model-versions/{version_id}",
headers=self._get_headers(),
timeout=aiohttp.ClientTimeout(total=30)
) as response:
return await self._handle_response(response)
async def download_model(
self,
version_id: int,
model_type: str,
filename: Optional[str] = None,
progress_callback: Optional[Callable[[DownloadProgress], None]] = None,
) -> str:
"""
Download a model version to the appropriate folder.
Args:
version_id: CivitAI version ID
model_type: Target model type (Checkpoint, LORA, etc.)
filename: Optional custom filename
progress_callback: Optional callback for progress updates
Returns:
Path to downloaded file
"""
# Get target directory
folder_name = MODEL_TYPE_TO_FOLDER.get(model_type)
if not folder_name:
raise CivitAIError(f"Unknown model type: {model_type}")
if folder_name not in folder_paths.folder_names_and_paths:
raise CivitAIError(f"Folder not configured: {folder_name}")
paths = folder_paths.folder_names_and_paths[folder_name]
if not paths or not paths[0]:
raise CivitAIError(f"No path configured for: {folder_name}")
target_dir = paths[0][0] if isinstance(paths[0], list) else paths[0]
# Get version details for filename
version = await self.get_model_version(version_id)
if not version.get("files"):
raise CivitAIError("No files available for this version")
# Find primary file (prefer safetensors)
primary_file = None
for f in version["files"]:
if f.get("primary"):
primary_file = f
break
if f.get("name", "").endswith(".safetensors") and primary_file is None:
primary_file = f
if not primary_file:
primary_file = version["files"][0]
if not filename:
filename = primary_file["name"]
# Ensure .safetensors extension
if not filename.endswith((".safetensors", ".pt", ".ckpt", ".bin")):
filename += ".safetensors"
target_path = os.path.join(target_dir, filename)
temp_path = target_path + ".downloading"
# Build download URL
download_url = primary_file.get("downloadUrl") or f"{CIVITAI_DOWNLOAD_BASE}/{version_id}"
if self.api_token:
separator = "&" if "?" in download_url else "?"
download_url += f"{separator}token={self.api_token}"
# Initialize progress
total_bytes = primary_file.get("sizeKB", 0) * 1024
progress = DownloadProgress(
model_id=version.get("modelId", 0),
version_id=version_id,
filename=filename,
downloaded_bytes=0,
total_bytes=total_bytes,
status="downloading"
)
self._download_progress[version_id] = progress
self._cancelled_downloads.discard(version_id)
try:
async with aiohttp.ClientSession() as session:
async with session.get(
download_url,
timeout=aiohttp.ClientTimeout(total=None, connect=30),
allow_redirects=True
) as response:
if response.status == 401:
raise CivitAIAuthError("Download requires authentication")
if response.status != 200:
raise CivitAIDownloadError(
f"Download failed: HTTP {response.status}",
version_id
)
# Update total from Content-Length header
content_length = response.headers.get("Content-Length")
if content_length:
progress.total_bytes = int(content_length)
# Create temp file
os.makedirs(target_dir, exist_ok=True)
last_broadcast = 0
with open(temp_path, "wb") as f:
async for chunk in response.content.iter_chunked(65536):
# Check for cancellation
if version_id in self._cancelled_downloads:
progress.status = "cancelled"
if os.path.exists(temp_path):
os.remove(temp_path)
await self._broadcast_download_event(progress)
return None
f.write(chunk)
progress.downloaded_bytes += len(chunk)
# Broadcast progress every 500KB
if progress.downloaded_bytes - last_broadcast >= 524288:
last_broadcast = progress.downloaded_bytes
await self._broadcast_download_event(progress)
if progress_callback:
progress_callback(progress)
# Move completed download
if os.path.exists(target_path):
os.remove(target_path)
os.rename(temp_path, target_path)
progress.status = "completed"
# Auto-index the downloaded model with CivitAI metadata
print(f"[CivitAI] Indexing downloaded model: {filename}")
index_data = resources.index_model(target_path, filename)
# Store the version metadata directly if we have it
if not index_data.get("civitai") and version:
index_data["civitai"] = version
resources.save_index(filename, index_data)
# Broadcast completion
await self._broadcast_download_event(progress, index_data)
return target_path
except asyncio.CancelledError:
progress.status = "cancelled"
if os.path.exists(temp_path):
os.remove(temp_path)
await self._broadcast_download_event(progress)
raise
except Exception as e:
progress.status = "failed"
progress.error = str(e)
if os.path.exists(temp_path):
os.remove(temp_path)
await self._broadcast_download_event(progress)
raise
finally:
# Clean up
self._download_progress.pop(version_id, None)
self._active_downloads.pop(version_id, None)
async def _broadcast_download_event(
self,
progress: DownloadProgress,
index_data: Optional[Dict] = None
):
"""Broadcast download progress/completion to WebSocket clients."""
percent = 0
if progress.total_bytes > 0:
percent = round(progress.downloaded_bytes / progress.total_bytes * 100, 1)
event_type = f"civitai:download:{progress.status}"
if progress.status == "downloading":
event_type = "civitai:download:progress"
data = {
"type": event_type,
"data": {
"model_id": progress.model_id,
"version_id": progress.version_id,
"filename": progress.filename,
"downloaded_bytes": progress.downloaded_bytes,
"total_bytes": progress.total_bytes,
"percent": percent,
"status": progress.status,
"error": progress.error
}
}
# Include metadata on completion
if progress.status == "completed" and index_data:
data["data"]["civitai"] = index_data.get("civitai")
data["data"]["hash"] = index_data.get("hash")
await broadcast_progress(data)
async def cancel_download(self, version_id: int) -> bool:
"""Cancel an in-progress download."""
self._cancelled_downloads.add(version_id)
task = self._active_downloads.get(version_id)
if task and not task.done():
task.cancel()
return True
return version_id in self._download_progress
def get_download_progress(self, version_id: int) -> Optional[DownloadProgress]:
"""Get current download progress."""
return self._download_progress.get(version_id)
def get_all_downloads(self) -> List[DownloadProgress]:
"""Get all active downloads."""
return list(self._download_progress.values())
def start_download_task(
self,
version_id: int,
model_type: str,
filename: Optional[str] = None,
) -> asyncio.Task:
"""Start a download as a background task."""
task = asyncio.create_task(
self.download_model(version_id, model_type, filename)
)
self._active_downloads[version_id] = task
return task
# Singleton instance
_client: Optional[CivitAIClient] = None
def get_client() -> CivitAIClient:
"""Get or create CivitAI client instance."""
global _client
if _client is None:
_client = CivitAIClient()
return _client
def get_model_directory(model_type: str) -> Optional[str]:
"""Get the ComfyUI folder path for a model type."""
folder_name = MODEL_TYPE_TO_FOLDER.get(model_type)
if folder_name and folder_name in folder_paths.folder_names_and_paths:
paths = folder_paths.folder_names_and_paths[folder_name]
if paths and paths[0]:
return paths[0][0] if isinstance(paths[0], list) else paths[0]
return None
def list_local_models_with_metadata(model_type: Optional[str] = None) -> Dict[str, List[Dict]]:
"""
List local models with their CivitAI metadata from index files.
Args:
model_type: Optional filter by model type
Returns:
Dict of model type -> list of models with metadata
"""
result = {}
types_to_check = [model_type] if model_type else list(MODEL_TYPE_TO_FOLDER.values())
for folder_name in types_to_check:
if folder_name not in folder_paths.folder_names_and_paths:
continue
models = []
files = folder_paths.get_filename_list(folder_name)
for filename in files:
filepath = folder_paths.get_full_path(folder_name, filename)
if not filepath:
continue
# Get file info
try:
stat = os.stat(filepath)
size_bytes = stat.st_size
except:
size_bytes = 0
# Get index data if available
index = resources.get_index(filename)
models.append({
"filename": filename,
"type": folder_name,
"size_bytes": size_bytes,
"indexed": index.get("hash") is not None,
"hash": index.get("hash"),
"civitai": index.get("civitai"),
})
if models:
result[folder_name] = models
return result
def delete_local_model(model_type: str, filename: str) -> bool:
"""
Delete a local model file and its index.
Args:
model_type: The model type/folder name
filename: The filename to delete
Returns:
True if deleted successfully
"""
if model_type not in folder_paths.folder_names_and_paths:
raise CivitAIError(f"Invalid model type: {model_type}")
filepath = folder_paths.get_full_path(model_type, filename)
if not filepath or not os.path.exists(filepath):
raise CivitAINotFoundError(f"Model not found: {filename}")
# Delete the model file
os.remove(filepath)
# Delete the index file if it exists
index_path = os.path.join(resources.RESOURCES_DIR, f"{filename}.index")
if os.path.exists(index_path):
os.remove(index_path)
return True
def get_stats() -> Dict[str, Any]:
"""Get CivitAI statistics."""
client = get_client()
stats = {
"local_model_counts": {},
"indexed_count": 0,
"total_count": 0,
"total_size_bytes": 0,
"active_downloads": len(client.get_all_downloads()),
}
for folder_name in MODEL_TYPE_TO_FOLDER.values():
if folder_name not in folder_paths.folder_names_and_paths:
continue
files = folder_paths.get_filename_list(folder_name)
count = len(files)
if count > 0:
stats["local_model_counts"][folder_name] = count
stats["total_count"] += count
for filename in files:
filepath = folder_paths.get_full_path(folder_name, filename)
if filepath:
try:
stats["total_size_bytes"] += os.path.getsize(filepath)
except:
pass
index_path = os.path.join(resources.RESOURCES_DIR, f"{filename}.index")
if os.path.exists(index_path):
stats["indexed_count"] += 1
return stats
def get_config() -> Dict[str, Any]:
"""Get CivitAI configuration status."""
token = os.environ.get("CIVITAI_TOKEN")
directories = {}
for civitai_type, folder_name in MODEL_TYPE_TO_FOLDER.items():
if folder_name in folder_paths.folder_names_and_paths:
paths = folder_paths.folder_names_and_paths[folder_name]
if paths and paths[0]:
path = paths[0][0] if isinstance(paths[0], list) else paths[0]
directories[civitai_type] = path
return {
"token_configured": bool(token),
"token_preview": f"{token[:8]}..." if token and len(token) > 8 else None,
"model_directories": directories,
"supported_types": list(MODEL_TYPE_TO_FOLDER.keys()),
}
+398
View File
@@ -0,0 +1,398 @@
"""
CivitAI API routes for model management.
"""
from aiohttp import web
from server import PromptServer
from . import civitai
def SetupCivitAIRoutes(server: PromptServer):
"""Register CivitAI API routes with the ComfyUI server."""
# =========== SEARCH & DISCOVERY ===========
@server.instance.routes.get("/imagelab/civitai/models")
async def search_models(request):
"""
Search CivitAI models.
Query params:
- query: Search term
- types: Comma-separated model types (Checkpoint,LORA,etc)
- sort: Highest Rated, Most Downloaded, Newest
- period: AllTime, Year, Month, Week, Day
- nsfw: true/false
- limit: 1-100 (default 20)
- page: Page number
- baseModels: Comma-separated base models (SD 1.5, SDXL, etc)
- tag: Filter by tag
"""
try:
client = civitai.get_client()
# Parse query params
query = request.query.get("query")
types = request.query.get("types")
sort = request.query.get("sort", "Most Downloaded")
period = request.query.get("period", "AllTime")
nsfw_str = request.query.get("nsfw")
limit = int(request.query.get("limit", 20))
page = int(request.query.get("page", 1))
base_models = request.query.get("baseModels")
tag = request.query.get("tag")
# Parse comma-separated values
types_list = types.split(",") if types else None
base_models_list = base_models.split(",") if base_models else None
nsfw = nsfw_str.lower() == "true" if nsfw_str else None
result = await client.search_models(
query=query,
types=types_list,
sort=sort,
period=period,
nsfw=nsfw,
limit=limit,
page=page,
base_models=base_models_list,
tag=tag,
)
return web.json_response({
"success": True,
"items": result.get("items", []),
"metadata": result.get("metadata", {}),
})
except civitai.CivitAIAuthError as e:
return web.json_response(
{"success": False, "error": e.message, "code": e.code},
status=401
)
except civitai.CivitAIRateLimitError as e:
return web.json_response(
{"success": False, "error": e.message, "code": e.code, "retry_after": e.retry_after},
status=429
)
except civitai.CivitAIError as e:
return web.json_response(
{"success": False, "error": e.message, "code": e.code},
status=500
)
except Exception as e:
return web.json_response(
{"success": False, "error": str(e), "code": "INTERNAL_ERROR"},
status=500
)
@server.instance.routes.get("/imagelab/civitai/models/{model_id}")
async def get_model_details(request):
"""Get detailed info for a specific model."""
try:
model_id = int(request.match_info["model_id"])
client = civitai.get_client()
result = await client.get_model(model_id)
return web.json_response({
"success": True,
"model": result,
})
except civitai.CivitAINotFoundError as e:
return web.json_response(
{"success": False, "error": e.message, "code": e.code},
status=404
)
except civitai.CivitAIAuthError as e:
return web.json_response(
{"success": False, "error": e.message, "code": e.code},
status=401
)
except civitai.CivitAIError as e:
return web.json_response(
{"success": False, "error": e.message, "code": e.code},
status=500
)
except Exception as e:
return web.json_response(
{"success": False, "error": str(e), "code": "INTERNAL_ERROR"},
status=500
)
@server.instance.routes.get("/imagelab/civitai/versions/{version_id}")
async def get_version_details(request):
"""Get detailed info for a specific model version."""
try:
version_id = int(request.match_info["version_id"])
client = civitai.get_client()
result = await client.get_model_version(version_id)
return web.json_response({
"success": True,
"version": result,
})
except civitai.CivitAINotFoundError as e:
return web.json_response(
{"success": False, "error": e.message, "code": e.code},
status=404
)
except civitai.CivitAIAuthError as e:
return web.json_response(
{"success": False, "error": e.message, "code": e.code},
status=401
)
except civitai.CivitAIError as e:
return web.json_response(
{"success": False, "error": e.message, "code": e.code},
status=500
)
except Exception as e:
return web.json_response(
{"success": False, "error": str(e), "code": "INTERNAL_ERROR"},
status=500
)
# =========== DOWNLOADS ===========
@server.instance.routes.post("/imagelab/civitai/download")
async def download_model(request):
"""
Start a model download.
Body:
- version_id: CivitAI version ID (required)
- model_type: Target type - Checkpoint, LORA, etc. (required)
- filename: Optional custom filename
"""
try:
body = await request.json()
version_id = body.get("version_id")
model_type = body.get("model_type")
filename = body.get("filename")
if not version_id:
return web.json_response(
{"success": False, "error": "version_id is required", "code": "VALIDATION_ERROR"},
status=400
)
if not model_type:
return web.json_response(
{"success": False, "error": "model_type is required", "code": "VALIDATION_ERROR"},
status=400
)
if model_type not in civitai.MODEL_TYPE_TO_FOLDER:
return web.json_response(
{"success": False, "error": f"Invalid model_type: {model_type}", "code": "VALIDATION_ERROR"},
status=400
)
client = civitai.get_client()
# Start download as background task
task = client.start_download_task(
version_id=int(version_id),
model_type=model_type,
filename=filename,
)
return web.json_response({
"success": True,
"download_id": str(version_id),
"status": "started",
"message": f"Download started for version {version_id}",
})
except civitai.CivitAIAuthError as e:
return web.json_response(
{"success": False, "error": e.message, "code": e.code},
status=401
)
except civitai.CivitAIError as e:
return web.json_response(
{"success": False, "error": e.message, "code": e.code},
status=500
)
except Exception as e:
return web.json_response(
{"success": False, "error": str(e), "code": "INTERNAL_ERROR"},
status=500
)
@server.instance.routes.get("/imagelab/civitai/downloads")
async def list_downloads(request):
"""List all active and recent downloads with progress."""
try:
client = civitai.get_client()
downloads = client.get_all_downloads()
items = []
for progress in downloads:
percent = 0
if progress.total_bytes > 0:
percent = round(progress.downloaded_bytes / progress.total_bytes * 100, 1)
items.append({
"version_id": progress.version_id,
"model_id": progress.model_id,
"filename": progress.filename,
"downloaded_bytes": progress.downloaded_bytes,
"total_bytes": progress.total_bytes,
"percent": percent,
"status": progress.status,
"error": progress.error,
})
return web.json_response({
"success": True,
"downloads": items,
})
except Exception as e:
return web.json_response(
{"success": False, "error": str(e), "code": "INTERNAL_ERROR"},
status=500
)
@server.instance.routes.delete("/imagelab/civitai/downloads/{version_id}")
async def cancel_download(request):
"""Cancel an in-progress download."""
try:
version_id = int(request.match_info["version_id"])
client = civitai.get_client()
cancelled = await client.cancel_download(version_id)
return web.json_response({
"success": True,
"cancelled": cancelled,
"version_id": version_id,
})
except Exception as e:
return web.json_response(
{"success": False, "error": str(e), "code": "INTERNAL_ERROR"},
status=500
)
# =========== LOCAL MODEL MANAGEMENT ===========
@server.instance.routes.get("/imagelab/civitai/local")
async def list_local_models(request):
"""
List local models with CivitAI metadata.
Query params:
- type: Filter by model folder type (checkpoints, loras, etc.)
- indexed_only: If 'true', only return models with CivitAI metadata
"""
try:
model_type = request.query.get("type")
indexed_only = request.query.get("indexed_only", "false").lower() == "true"
result = civitai.list_local_models_with_metadata(model_type)
# Filter indexed only if requested
if indexed_only:
for folder_name, models in result.items():
result[folder_name] = [m for m in models if m.get("indexed")]
return web.json_response({
"success": True,
"models": result,
})
except Exception as e:
return web.json_response(
{"success": False, "error": str(e), "code": "INTERNAL_ERROR"},
status=500
)
@server.instance.routes.delete("/imagelab/civitai/local/{model_type}/{filename:.*}")
async def delete_model(request):
"""Delete a local model file."""
try:
model_type = request.match_info["model_type"]
filename = request.match_info["filename"]
civitai.delete_local_model(model_type, filename)
return web.json_response({
"success": True,
"deleted": filename,
"type": model_type,
})
except civitai.CivitAINotFoundError as e:
return web.json_response(
{"success": False, "error": e.message, "code": e.code},
status=404
)
except civitai.CivitAIError as e:
return web.json_response(
{"success": False, "error": e.message, "code": e.code},
status=500
)
except Exception as e:
return web.json_response(
{"success": False, "error": str(e), "code": "INTERNAL_ERROR"},
status=500
)
# =========== STATS & CONFIG ===========
@server.instance.routes.get("/imagelab/civitai/stats")
async def get_stats(request):
"""
Get CivitAI statistics.
Returns:
- local_model_counts: Count by type
- indexed_count: Models with CivitAI metadata
- total_size_bytes: Total disk usage
- active_downloads: Current download count
"""
try:
stats = civitai.get_stats()
return web.json_response({
"success": True,
"stats": stats,
})
except Exception as e:
return web.json_response(
{"success": False, "error": str(e), "code": "INTERNAL_ERROR"},
status=500
)
@server.instance.routes.get("/imagelab/civitai/config")
async def get_config(request):
"""
Get CivitAI configuration status.
Returns:
- token_configured: Whether CIVITAI_TOKEN is set
- model_directories: Available model directories
- supported_types: Supported model types
"""
try:
config = civitai.get_config()
return web.json_response({
"success": True,
"config": config,
})
except Exception as e:
return web.json_response(
{"success": False, "error": str(e), "code": "INTERNAL_ERROR"},
status=500
)
+39 -1
View File
@@ -10,6 +10,7 @@ import folder_paths
from PIL.PngImagePlugin import PngInfo
from PIL import Image
import numpy as np
import torch
from io import BytesIO
from server import PromptServer, BinaryEventTypes
@@ -157,9 +158,44 @@ class ImageLabSaveImage:
return {"ui": {"images": results}}
class ColorFillImage:
"""
A simple node that creates a solid color image of specified size.
"""
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"width": ("INT", {"default": 512, "min": 1, "max": 8192, "step": 1}),
"height": ("INT", {"default": 512, "min": 1, "max": 8192, "step": 1}),
"color_hex": ("STRING", {"default": "#FFFFFF"}),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "create_image"
CATEGORY = "imagelab"
DESCRIPTION = "Creates a solid color image of specified size from a hex color."
def create_image(self, width, height, color_hex):
# Parse hex color (handle with or without #)
hex_color = color_hex.lstrip("#")
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
# Create solid color image
img = Image.new("RGB", (width, height), (r, g, b))
# Convert to tensor format ComfyUI expects: [batch, height, width, channels], float32, 0-1
img_array = np.array(img).astype(np.float32) / 255.0
img_tensor = torch.from_numpy(img_array)[None,]
return (img_tensor,)
import hashlib
import torch
def is_changed_file(filepath):
"""Check if file has changed using MD5 hash."""
@@ -238,9 +274,11 @@ class WatchImageFile:
NODE_CLASS_MAPPINGS = {
"WatchImageFile": WatchImageFile,
"ImageLabSaveImage": ImageLabSaveImage,
"ColorFillImage": ColorFillImage,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"WatchImageFile": "Watch Image File",
"ImageLabSaveImage": "ImageLab Save Image",
"ColorFillImage": "Color Fill Image",
}
+7
View File
@@ -36,6 +36,13 @@ InputImage = Annotated[Optional[str], Field(
json_schema_extra={"component": "input_image", "category": "composition"}
)]
# Inpainting mask (white = regenerate, black = preserve)
# Value is the filename string (e.g., "mask.png")
MaskImage = Annotated[Optional[str], Field(
default=None,
json_schema_extra={"component": "mask", "category": "composition", "depends_on": {"inputImage": True}}
)]
# Enum types (selections from options_source)
Sampler = Annotated[str, Field(
json_schema_extra={"component": "sampler", "options_source": "samplers", "category": "parameters"}
+32 -51
View File
@@ -187,69 +187,50 @@ def get_all_models() -> Dict[str, List[Dict]]:
"""
Get all available models grouped by type (no indexing).
"""
model_types = [
'checkpoints',
'loras',
'vae',
'embeddings',
'upscale_models',
'controlnet',
'clip',
'clip_vision',
'diffusion_models',
'unet',
'gligen',
'photomaker',
'style_models'
]
# Map ComfyUI folder names to API response keys
# Some keys are pluralized for consistency with v1-server expectations
model_types = {
'checkpoints': 'checkpoints',
'loras': 'loras',
'vae': 'vaes', # Pluralize for v1-server compatibility
'embeddings': 'embeddings',
'upscale_models': 'upscale_models',
'controlnet': 'controlnet',
'clip': 'clip',
'clip_vision': 'clip_vision',
'diffusion_models': 'diffusion_models',
'unet': 'unet',
'gligen': 'gligen',
'photomaker': 'photomaker',
'style_models': 'style_models'
}
resources = {}
for model_type in model_types:
for folder_name, api_key in model_types.items():
try:
models = get_models_by_type(model_type)
models = get_models_by_type(folder_name)
if models: # Only include if models exist
resources[model_type] = models
resources[api_key] = models
except Exception as e:
print(f"[Resources] Error loading {model_type}: {e}")
print(f"[Resources] Error loading {folder_name}: {e}")
return resources
def get_samplers() -> List[Dict]:
"""Get available samplers."""
def get_samplers() -> List[str]:
"""Get available samplers as simple strings."""
import comfy.samplers
return [
{
'label': sampler,
'apiName': sampler,
'metadata': None
}
for sampler in comfy.samplers.KSampler.SAMPLERS
]
return list(comfy.samplers.KSampler.SAMPLERS)
def get_schedulers() -> List[Dict]:
"""Get available schedulers."""
def get_schedulers() -> List[str]:
"""Get available schedulers as simple strings."""
import comfy.samplers
return [
{
'label': scheduler,
'apiName': scheduler,
'metadata': None
}
for scheduler in comfy.samplers.KSampler.SCHEDULERS
]
return list(comfy.samplers.KSampler.SCHEDULERS)
def get_upscale_methods() -> List[Dict]:
"""Get available upscale methods."""
def get_upscale_methods() -> List[str]:
"""Get available upscale methods as simple strings."""
import nodes
return [
{
'label': method,
'apiName': method,
'metadata': None
}
for method in nodes.LatentUpscale.upscale_methods
]
return list(nodes.LatentUpscale.upscale_methods)
+183 -159
View File
@@ -1,22 +1,39 @@
"""
API routes for external workflow execution.
"""
from aiohttp import web
from server import PromptServer
from .workflows import (
get_workflow,
get_workflow_metadata,
get_workflow_parameters,
list_workflows,
invalidate_workflow_cache,
invalidate_options_cache
)
from . import resources
from .civitai_routes import SetupCivitAIRoutes
from .workflows import (
get_workflow,
get_workflow_metadata,
get_workflow_parameters,
invalidate_workflow_cache,
list_workflows,
)
def get_comfy_script_client_id():
"""
Get the comfy_script client_id lazily.
This must be called after comfy_script's load() has been invoked,
which happens when any workflow is first imported/executed.
"""
try:
import comfy_script.runtime as runtime
return getattr(runtime, "_client_id", None)
except ImportError:
return None
def SetupRoutes(server: PromptServer):
"""Register API routes with the ComfyUI server."""
@server.instance.routes.get("/imagelab/workflows")
async def list_available_workflows(request):
"""
@@ -24,235 +41,242 @@ def SetupRoutes(server: PromptServer):
Query params:
- refresh: If 'true', force refresh the workflow cache
"""
refresh = request.query.get('refresh', 'false').lower() == 'true'
return web.json_response({
'workflows': list_workflows(refresh=refresh)
})
refresh = request.query.get("refresh", "false").lower() == "true"
return web.json_response(
{"success": True, "workflows": list_workflows(refresh=refresh)}
)
@server.instance.routes.post("/imagelab/workflows/refresh")
async def refresh_workflows(request):
"""Force refresh workflow cache and return updated list."""
invalidate_workflow_cache()
workflows = list_workflows(refresh=True)
return web.json_response({
'success': True,
'message': f'Refreshed {len(workflows)} workflows',
'workflows': workflows
})
return web.json_response(
{
"success": True,
"message": f"Refreshed {len(workflows)} workflows",
"workflows": workflows,
}
)
@server.instance.routes.get("/imagelab/workflow/{workflow_name}/metadata")
async def get_workflow_info(request):
"""Get metadata for a specific workflow."""
workflow_name = request.match_info['workflow_name']
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
})
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)
return web.json_response({"success": False, "error": str(e)}, status=404)
@server.instance.routes.get("/imagelab/workflow/{workflow_name}/parameters")
async def get_workflow_params(request):
"""Get parameter schema for a specific workflow."""
workflow_name = request.match_info['workflow_name']
workflow_name = request.match_info["workflow_name"]
try:
parameters = get_workflow_parameters(workflow_name)
if parameters is None:
return web.json_response({
'success': True,
'workflow': workflow_name,
'parameters': [],
'message': 'Workflow does not define parameter schema'
})
return web.json_response({
'success': True,
'workflow': workflow_name,
'parameters': parameters
})
return web.json_response(
{
"success": True,
"workflow": workflow_name,
"parameters": [],
"message": "Workflow does not define parameter schema",
}
)
return web.json_response(
{"success": True, "workflow": workflow_name, "parameters": parameters}
)
except ValueError as e:
return web.json_response({
'success': False,
'error': str(e)
}, status=404)
return web.json_response({"success": False, "error": str(e)}, status=404)
@server.instance.routes.post("/imagelab/workflow/{workflow_name}")
async def execute_workflow(request):
"""Execute a specific workflow by name."""
workflow_name = request.match_info['workflow_name']
workflow_name = request.match_info["workflow_name"]
try:
# Get the workflow function
workflow_func = get_workflow(workflow_name)
# Parse request body for parameters
try:
params = await request.json()
except:
params = {}
# Execute workflow
result = workflow_func(**params)
return web.json_response({
'success': True,
'workflow': workflow_name,
'result': result
})
return web.json_response(
{"success": True, "workflow": workflow_name, "result": result}
)
except ValueError as e:
return web.json_response({
'success': False,
'type': 'ValueError',
'error': str(e)
}, status=404)
return web.json_response(
{"success": False, "type": "ValueError", "error": str(e)}, status=404
)
except Exception as e:
return web.json_response({
'success': False,
'type': 'Exception',
'error': f"Workflow execution failed: {str(e)}"
}, status=500)
return web.json_response(
{
"success": False,
"type": "Exception",
"error": f"Workflow execution failed: {str(e)}",
},
status=500,
)
@server.instance.routes.get("/imagelab/resources")
async def get_all_resources(request):
"""Get all available resources (models, samplers, etc.) - fast, no indexing"""
try:
models = resources.get_all_models()
return web.json_response({
'success': True,
'resources': {
**models,
'samplers': resources.get_samplers(),
'schedulers': resources.get_schedulers(),
'upscale_methods': resources.get_upscale_methods()
return web.json_response(
{
"success": True,
"resources": {
**models,
"samplers": resources.get_samplers(),
"schedulers": resources.get_schedulers(),
"upscale_methods": resources.get_upscale_methods(),
},
}
})
)
except Exception as e:
return web.json_response({
'success': False,
'error': str(e)
}, status=500)
return web.json_response({"success": False, "error": str(e)}, status=500)
@server.instance.routes.get("/imagelab/resources/{resource_type}")
async def get_resource_by_type(request):
"""Get resources of a specific type - fast, no indexing"""
resource_type = request.match_info['resource_type']
resource_type = request.match_info["resource_type"]
# Map API keys to ComfyUI folder names
folder_map = {
"vaes": "vae", # API uses plural, folder is singular
}
folder_name = folder_map.get(resource_type, resource_type)
try:
# Handle special resource types
if resource_type == 'samplers':
if resource_type == "samplers":
result = resources.get_samplers()
elif resource_type == 'schedulers':
elif resource_type == "schedulers":
result = resources.get_schedulers()
elif resource_type == 'upscale_methods':
elif resource_type == "upscale_methods":
result = resources.get_upscale_methods()
else:
# Try to get as a model type
result = resources.get_models_by_type(resource_type)
return web.json_response({
'success': True,
'resource_type': resource_type,
'items': result
})
result = resources.get_models_by_type(folder_name)
return web.json_response(
{"success": True, "resource_type": resource_type, "items": result}
)
except Exception as e:
return web.json_response({
'success': False,
'error': str(e)
}, status=500)
return web.json_response({"success": False, "error": str(e)}, status=500)
@server.instance.routes.post("/imagelab/resources/{resource_type}/index/{filename}")
async def index_model_file(request):
"""Index a specific model file - calculate hash and fetch metadata"""
resource_type = request.match_info['resource_type']
filename = request.match_info['filename']
resource_type = request.match_info["resource_type"]
filename = request.match_info["filename"]
try:
metadata = resources.index_model_by_name(resource_type, filename)
return web.json_response({
'success': True,
'resource_type': resource_type,
'filename': filename,
'metadata': metadata
})
return web.json_response(
{
"success": True,
"resource_type": resource_type,
"filename": filename,
"metadata": metadata,
}
)
except FileNotFoundError as e:
return web.json_response({
'success': False,
'error': str(e)
}, status=404)
return web.json_response({"success": False, "error": str(e)}, status=404)
except Exception as e:
return web.json_response({
'success': False,
'error': str(e)
}, status=500)
return web.json_response({"success": False, "error": str(e)}, status=500)
@server.instance.routes.post("/imagelab/resources/index-all")
async def index_all_models(request):
"""Index all models that don't have index files yet"""
try:
indexed_counts = resources.index_all_new_models()
return web.json_response({
'success': True,
'message': 'Indexing complete',
'indexed': indexed_counts
})
return web.json_response(
{
"success": True,
"message": "Indexing complete",
"indexed": indexed_counts,
}
)
except Exception as e:
return web.json_response({
'success': False,
'error': str(e)
}, status=500)
return web.json_response({"success": False, "error": str(e)}, status=500)
@server.instance.routes.get("/imagelab/hello")
async def get_hello(request):
"""Test endpoint."""
return web.json_response({
'message': 'Hello from external API!'
})
return web.json_response({"message": "Hello from external API!"})
@server.instance.routes.get("/imagelab/client-id")
async def get_client_id(request):
"""
Get the comfy_script client ID for WebSocket connections.
This ID is used by ComfyUI to route execution events.
Connect to /ws?clientId={client_id} to receive workflow events.
Note: This endpoint requires that at least one workflow has been
loaded (which initializes comfy_script's connection to ComfyUI).
"""
client_id = get_comfy_script_client_id()
if client_id is None:
return web.json_response(
{
"success": False,
"error": "comfy_script not initialized - run a workflow first",
},
status=503,
)
return web.json_response({"success": True, "client_id": client_id})
@server.instance.routes.get("/imagelab/input-images")
async def get_input_images(request):
"""List all images in the ComfyUI input folder."""
import folder_paths
import os
import folder_paths
try:
input_dir = folder_paths.get_input_directory()
images = []
# Supported image extensions
image_extensions = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp'}
image_extensions = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"}
for filename in os.listdir(input_dir):
ext = os.path.splitext(filename)[1].lower()
if ext in image_extensions:
filepath = os.path.join(input_dir, filename)
stat = os.stat(filepath)
images.append({
'filename': filename,
'size': stat.st_size,
'modified': stat.st_mtime
})
images.append(
{
"filename": filename,
"size": stat.st_size,
"modified": stat.st_mtime,
}
)
# Sort by modified time (newest first)
images.sort(key=lambda x: x['modified'], reverse=True)
return web.json_response({
'success': True,
'images': images
})
images.sort(key=lambda x: x["modified"], reverse=True)
return web.json_response({"success": True, "images": images})
except Exception as e:
return web.json_response({
'success': False,
'error': str(e)
}, status=500)
return web.json_response({"success": False, "error": str(e)}, status=500)
# Register CivitAI routes
SetupCivitAIRoutes(server)
+108 -163
View File
@@ -10,13 +10,15 @@ Performance optimizations:
- YAML schemas are cached after first load
- Options resolution is cached with TTL
"""
import os
import glob
import time
import importlib.util
import yaml
import os
import time
from pathlib import Path
from typing import Callable, Dict, List, Optional, Any
from typing import Any, Callable, Dict, List, Optional
import yaml
# Support both relative and absolute imports
# Resources module requires ComfyUI context
@@ -37,19 +39,18 @@ _workflow_cache_time: float = 0
# Cache for YAML schemas
_yaml_schema_cache: Dict[str, Optional[Dict]] = {}
# Cache for resolved options (with TTL)
_options_cache: Dict[str, Any] = {}
_options_cache_time: Dict[str, float] = {}
OPTIONS_CACHE_TTL = 30 # seconds
def load_workflow_module(workflow_name: str):
"""Dynamically load/reload a workflow module from the workflows folder."""
workflow_path = os.path.join(os.path.dirname(__file__), "workflows", f"{workflow_name}.py")
workflow_path = os.path.join(
os.path.dirname(__file__), "workflows", f"{workflow_name}.py"
)
if not os.path.exists(workflow_path):
raise FileNotFoundError(f"Workflow 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)
spec.loader.exec_module(module)
return module
@@ -61,17 +62,19 @@ def load_yaml_schema(workflow_name: str, use_cache: bool = True) -> Optional[Dic
Uses caching to avoid repeated disk reads.
"""
global _yaml_schema_cache
# Check cache first
if use_cache and workflow_name in _yaml_schema_cache:
return _yaml_schema_cache[workflow_name]
yaml_path = os.path.join(os.path.dirname(__file__), "workflows", f"{workflow_name}.yaml")
yaml_path = os.path.join(
os.path.dirname(__file__), "workflows", f"{workflow_name}.yaml"
)
if not os.path.exists(yaml_path):
_yaml_schema_cache[workflow_name] = None
return None
with open(yaml_path, "r", encoding="utf-8") as f:
schema = yaml.safe_load(f)
_yaml_schema_cache[workflow_name] = schema
@@ -81,108 +84,47 @@ def load_yaml_schema(workflow_name: str, use_cache: bool = True) -> Optional[Dic
def ensure_yaml_schema(workflow_name: str, module) -> Optional[Dict]:
"""
Ensure YAML schema exists for a workflow.
Auto-generates from WorkflowParams if missing.
Auto-generates from WorkflowParams if missing or if Python model has new fields.
Returns the schema dict or None.
"""
yaml_path = Path(os.path.dirname(__file__)) / "workflows" / f"{workflow_name}.yaml"
# Try to load existing YAML
schema = load_yaml_schema(workflow_name)
if schema is None and hasattr(module, "WorkflowParams"):
# Auto-generate YAML from WorkflowParams
try:
# Support both relative and absolute imports
if hasattr(module, "WorkflowParams"):
# Check if we need to regenerate (missing YAML or new fields in Python)
should_regenerate = schema is None
if schema is not None:
# Check for new fields in Python that aren't in YAML
yaml_field_names = {p.get("name") for p in schema.get("parameters", [])}
python_field_names = set(module.WorkflowParams.model_fields.keys())
new_fields = python_field_names - yaml_field_names
if new_fields:
print(f"[workflows] Found new fields in {workflow_name}: {new_fields}")
should_regenerate = True
if should_regenerate:
# Auto-generate YAML from WorkflowParams (merges with existing)
try:
from .schema_generator import generate_workflow_schema
except ImportError:
from schema_generator import generate_workflow_schema
py_path = yaml_path.with_suffix(".py")
schema = generate_workflow_schema(py_path)
print(f"[workflows] Auto-generated schema: {workflow_name}.yaml")
except Exception as e:
print(f"[workflows] Error generating schema for {workflow_name}: {e}")
# Support both relative and absolute imports
try:
from .schema_generator import generate_workflow_schema
except ImportError:
from schema_generator import generate_workflow_schema
py_path = yaml_path.with_suffix(".py")
schema = generate_workflow_schema(py_path)
# Clear cache so next load gets the new schema
_yaml_schema_cache.pop(workflow_name, None)
print(f"[workflows] {'Updated' if yaml_path.exists() else 'Generated'} schema: {workflow_name}.yaml")
except Exception as e:
print(f"[workflows] Error generating schema for {workflow_name}: {e}")
return schema
def get_options_resolver() -> Dict[str, Callable[[], List[Dict]]]:
"""
Get mapping from options_source to resolver functions.
Returns empty dict if resources module not available.
"""
if resources is None:
return {}
return {
# Enums
"samplers": resources.get_samplers,
"schedulers": resources.get_schedulers,
"upscale_methods": resources.get_upscale_methods,
# Models
"checkpoints": lambda: resources.get_models_by_type("checkpoints"),
"loras": lambda: resources.get_models_by_type("loras"),
"vae": lambda: resources.get_models_by_type("vae"),
"embeddings": lambda: resources.get_models_by_type("embeddings"),
"upscale_models": lambda: resources.get_models_by_type("upscale_models"),
"controlnet": lambda: resources.get_models_by_type("controlnet"),
"clip": lambda: resources.get_models_by_type("clip"),
"clip_vision": lambda: resources.get_models_by_type("clip_vision"),
"diffusion_models": lambda: resources.get_models_by_type("diffusion_models"),
"unet": lambda: resources.get_models_by_type("unet"),
"ipadapters": lambda: resources.get_models_by_type("ipadapter"),
}
def get_cached_options(source: str) -> Any:
"""Get options from cache if valid, otherwise fetch and cache."""
global _options_cache, _options_cache_time
current_time = time.time()
# Check if cache is valid
if source in _options_cache:
cache_age = current_time - _options_cache_time.get(source, 0)
if cache_age < OPTIONS_CACHE_TTL:
return _options_cache[source]
# Fetch fresh data
resolvers = get_options_resolver()
if source not in resolvers:
return []
try:
data = resolvers[source]()
_options_cache[source] = data
_options_cache_time[source] = current_time
return data
except Exception as e:
print(f"[workflows] Error fetching {source}: {e}")
return []
def resolve_options_source(parameters: List[Dict]) -> List[Dict]:
"""
Resolve options_source references in parameters to actual options.
Returns a new list with resolved options.
Uses caching with TTL to avoid repeated expensive lookups.
"""
resolved = []
for param in parameters:
param_copy = param.copy()
options_source = param_copy.get("options_source")
if options_source:
param_copy["options"] = get_cached_options(options_source)
resolved.append(param_copy)
return resolved
# Cache TTL for workflow discovery (5 minutes)
WORKFLOW_CACHE_TTL = 300
@@ -192,54 +134,56 @@ def discover_workflows(force_refresh: bool = False) -> Dict[str, dict]:
Discover all workflow files in the workflows/ folder.
Workflows must define WORKFLOW_METADATA dict to be discovered.
Returns a dict mapping workflow_id to its config.
Uses caching with TTL to avoid rescanning on every request.
Pass force_refresh=True to bypass cache.
"""
global _workflow_cache, _workflow_cache_time
current_time = time.time()
cache_age = current_time - _workflow_cache_time
# Return cached data if still valid and not forced refresh
if _workflow_cache and not force_refresh and cache_age < WORKFLOW_CACHE_TTL:
return _workflow_cache
workflows_dir = os.path.join(os.path.dirname(__file__), "workflows")
discovered = {}
# Find all Python files in workflows directory
for filepath in glob.glob(os.path.join(workflows_dir, "*.py")):
filename = os.path.basename(filepath)
# Skip __init__.py and other special files
if filename.startswith("_"):
continue
workflow_id = filename[:-3] # Remove .py extension
try:
# Load the module to check for WORKFLOW_METADATA
module = load_workflow_module(workflow_id)
# Check if module has required attributes
if not hasattr(module, "WORKFLOW_METADATA"):
print(f"[workflows] Skipping {filename}: No WORKFLOW_METADATA defined")
continue
if not hasattr(module, "run_workflow"):
print(f"[workflows] Skipping {filename}: No run_workflow function defined")
print(
f"[workflows] Skipping {filename}: No run_workflow function defined"
)
continue
metadata = module.WORKFLOW_METADATA
# Check for YAML schema (uses its own cache)
yaml_schema = load_yaml_schema(workflow_id)
has_yaml = yaml_schema is not None
# Check for legacy WORKFLOW_PARAMETERS (for backward compat)
has_legacy_params = hasattr(module, "WORKFLOW_PARAMETERS")
# Build workflow config
discovered[workflow_id] = {
"script": workflow_id,
@@ -248,15 +192,19 @@ def discover_workflows(force_refresh: bool = False) -> Dict[str, dict]:
"model_types": metadata.get("model_types", []),
"category": metadata.get("category", "Uncategorized"),
"has_parameters": has_yaml or has_legacy_params,
"schema_source": "yaml" if has_yaml else ("legacy" if has_legacy_params else None),
"schema_source": "yaml"
if has_yaml
else ("legacy" if has_legacy_params else None),
}
print(f"[workflows] Discovered: {workflow_id} - {metadata.get('name', workflow_id)}")
print(
f"[workflows] Discovered: {workflow_id} - {metadata.get('name', workflow_id)}"
)
except Exception as e:
print(f"[workflows] Error loading {filename}: {e}")
continue
_workflow_cache = discovered
_workflow_cache_time = current_time
print(f"[workflows] Cache refreshed with {len(discovered)} workflows")
@@ -269,10 +217,12 @@ def get_workflow(name: str) -> Callable:
Reloads the module from disk each time for hot reloading.
"""
workflows = discover_workflows()
if name not in workflows:
raise ValueError(f"Workflow '{name}' not found. Available: {list(workflows.keys())}")
raise ValueError(
f"Workflow '{name}' not found. Available: {list(workflows.keys())}"
)
# Reload the module from disk each time
module = load_workflow_module(name)
return module.run_workflow
@@ -281,66 +231,69 @@ def get_workflow(name: str) -> Callable:
def get_workflow_metadata(name: str) -> dict:
"""Get metadata for a specific workflow."""
workflows = discover_workflows()
if name not in workflows:
raise ValueError(f"Workflow '{name}' not found. Available: {list(workflows.keys())}")
raise ValueError(
f"Workflow '{name}' not found. Available: {list(workflows.keys())}"
)
config = workflows[name].copy()
config.pop("script", None) # Don't expose internal file path
config.pop("schema_source", None) # Internal use only
return config
def get_workflow_parameters(name: str, resolve_options: bool = True) -> Optional[List[dict]]:
def get_workflow_parameters(name: str) -> Optional[List[dict]]:
"""
Get parameter schema for a specific workflow.
Loads from YAML schema first, falls back to legacy WORKFLOW_PARAMETERS.
Auto-generates YAML if WorkflowParams exists but no schema.
Note: Options are NOT resolved - they should be fetched dynamically by the
v1-server using options_source references.
Args:
name: Workflow name/ID
resolve_options: If True, resolve options_source to actual options
Returns:
List of parameter definitions, or None if no schema exists
List of parameter definitions with options_source references (NOT resolved options)
"""
workflows = discover_workflows()
if name not in workflows:
raise ValueError(f"Workflow '{name}' not found. Available: {list(workflows.keys())}")
raise ValueError(
f"Workflow '{name}' not found. Available: {list(workflows.keys())}"
)
# Load the module
module = load_workflow_module(name)
# Try YAML schema first
schema = ensure_yaml_schema(name, module)
if schema and "parameters" in schema:
parameters = schema["parameters"]
if resolve_options:
parameters = resolve_options_source(parameters)
return parameters
return schema["parameters"]
# Fall back to legacy WORKFLOW_PARAMETERS
if hasattr(module, "WORKFLOW_PARAMETERS"):
return module.WORKFLOW_PARAMETERS
return None
def list_workflows(refresh: bool = False) -> list:
"""
Get list of available workflow names with their metadata.
Uses cached data by default for fast response.
Set refresh=True to force re-scan the workflows directory.
"""
workflows = discover_workflows(force_refresh=refresh)
return [
{
"id": name,
**{k: v for k, v in config.items() if k not in ("script", "schema_source")}
**{k: v for k, v in config.items() if k not in ("script", "schema_source")},
}
for name, config in workflows.items()
]
@@ -356,11 +309,3 @@ def invalidate_workflow_cache():
_workflow_cache_time = 0
_yaml_schema_cache = {}
print("[workflows] Cache invalidated")
def invalidate_options_cache():
"""Invalidate the options cache (e.g., after models change)."""
global _options_cache, _options_cache_time
_options_cache = {}
_options_cache_time = {}
print("[workflows] Options cache invalidated")
+191 -20
View File
@@ -3,6 +3,7 @@ Basic SDXL Text to Image workflow.
Schema is defined in basic_sdxl.yaml (auto-generated from WorkflowParams).
"""
from comfy_script.runtime import *
from comfy_script.runtime import _client_id
load('http://127.0.0.1:8188/')
from comfy_script.runtime.nodes import *
@@ -15,7 +16,7 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from base import BaseWorkflow
from parameters import (
Prompt, NegativePrompt, Checkpoint, Seed, Sampler, Scheduler,
Loras, Dimensions, Loopback, InputImage
Loras, Dimensions, Loopback, InputImage, MaskImage
)
# ============================================
@@ -41,6 +42,7 @@ class WorkflowParams(BaseModel):
# Use annotated types for automatic UI schema
prompt: Prompt
negativePrompt: NegativePrompt = "text, watermark"
vae: str = Field(default="", json_schema_extra={"category": "models", "label": "VAE", "options_source": "vaes"})
checkpoints: Checkpoint
loras: Loras # Uses shared type with category: models
sampler: Sampler = "euler"
@@ -55,7 +57,72 @@ class WorkflowParams(BaseModel):
steps: int = Field(default=20, ge=1, le=150)
cfg: float = Field(default=8.0, ge=1.0, le=20.0, json_schema_extra={"step": 0.5})
inputImage: InputImage = "" # Optional input image for img2img
mask: MaskImage = "" # Optional inpainting mask (white = regenerate, black = preserve)
inpaintMode: str = Field(default="noise_mask", json_schema_extra={
"category": "composition",
"label": "Inpaint Mode",
"depends_on": {"mask": True},
"options": [
{"label": "Noise Mask", "apiName": "noise_mask", "description": "Preserves image data under the mask, blending new content with existing pixels"},
{"label": "VAE Inpaint", "apiName": "vae_inpaint", "description": "Uses empty latent under the mask, generating completely new content in masked areas"}
]
})
inpaintFullRes: bool = Field(default=False, json_schema_extra={
"category": "composition",
"label": "Inpaint at Full Resolution",
"depends_on": {"mask": True},
"description": "Crops and upscales the masked area for higher detail inpainting, then composites back"
})
inpaintFullResSize: int = Field(default=0, ge=0, le=2048, json_schema_extra={
"category": "composition",
"label": "Full Res Size",
"depends_on": {"inpaintFullRes": True},
"description": "Target size for cropped region (0 = use input image dimensions)"
})
inpaintPadding: float = Field(default=1.5, ge=1.0, le=5.0, json_schema_extra={
"step": 0.1,
"category": "composition",
"label": "Inpaint Padding",
"depends_on": {"inpaintFullRes": True},
"description": "Padding multiplier around the mask for context (higher = more context)"
})
inpaintFeather: int = Field(default=20, ge=0, le=100, json_schema_extra={
"category": "composition",
"label": "Inpaint Feather",
"depends_on": {"inpaintFullRes": True},
"description": "Feathering radius for blending the inpainted region back"
})
denoise: float = Field(default=1.0, ge=0.0, le=1.0, json_schema_extra={"step": 0.01, "category": "composition", "depends_on": {"inputImage": True}})
upscale: float = Field(default=1.0, ge=-2.0, le=3.0, json_schema_extra={"step": 0.05, "category": "composition", "depends_on": {"inputImage": True}})
# Output processing parameters
upscaleModel: str = Field(default="", json_schema_extra={
"category": "output",
"label": "Upscale Model",
"options_source": "upscale_models",
"clearable": True,
"description": "AI upscaler model for enhancing output resolution"
})
maxOutputSize: str = Field(default="0", json_schema_extra={
"category": "output",
"label": "Max Output Size",
"description": "Maximum dimension for final output. Downscales if larger.",
"options": [
{"label": "No Limit", "apiName": "0"},
{"label": "1024 px", "apiName": "1024"},
{"label": "1536 px", "apiName": "1536"},
{"label": "2048 px", "apiName": "2048"},
{"label": "3072 px", "apiName": "3072"},
{"label": "4096 px", "apiName": "4096"},
{"label": "6144 px", "apiName": "6144"},
{"label": "8192 px", "apiName": "8192"}
]
})
removeBackground: bool = Field(default=False, json_schema_extra={
"category": "output",
"label": "Remove Background",
"description": "Remove background using BRIA RMBG AI model"
})
# Workflow definition
class SDXLWorkflow(BaseWorkflow):
@@ -65,34 +132,138 @@ class SDXLWorkflow(BaseWorkflow):
with Workflow(wait=False) as wf:
model, clip, vae = self.load_checkpoints()
model, clip = self.apply_loras(model, clip)
vae = VAELoader("sdxl_vae-fp16fix-blessed.safetensors")
if params.inputImage != "" and params.inputImage is not None:
image, mask = LoadImage(params.inputImage)
image = ResizeImagesByLongerEdge(image, max(params.dimensions.width, params.dimensions.height))
clip = CLIPSetLastLayer(clip, -2)
# Use custom VAE if specified, otherwise use checkpoint's VAE
if params.vae and params.vae != "":
vae = VAELoader(params.vae)
latent = VAEEncode(image, vae)
else:
latent = EmptyLatentImage(params.dimensions.width, params.dimensions.height, 1)
# Build conditioning early (needed for all paths)
conditioning = CLIPTextEncode(params.prompt, clip)
conditioning2 = CLIPTextEncode(params.negativePrompt, clip)
latent = KSampler(model, params.seed, params.steps, params.cfg, params.sampler, params.scheduler, conditioning, conditioning2, latent, params.denoise)
if params.loopback.enabled:
for _ in range(params.loopback.iterations):
latent = LatentUpscaleBy(latent, 'nearest-exact', params.loopback.upscale)
latent = KSampler(model, params.seed + 1, params.loopback.steps, params.loopback.cfg, params.sampler, params.scheduler, conditioning, conditioning2, latent, params.loopback.denoise)
# Track final output image
output_image = None
image = VAEDecode(latent, vae)
if params.inputImage != "" and params.inputImage is not None:
input_image, _ = LoadImage(params.inputImage)
input_image = ResizeImagesByLongerEdge(input_image, max(params.dimensions.width, params.dimensions.height))
# Check for inpainting mask
if params.mask and params.mask != "":
mask_image, _ = LoadImage(params.mask)
inpaint_mask = ImageToMask(mask_image, 'red')
# Full Resolution Inpainting using Impact Pack's MaskDetailer
if params.inpaintFullRes:
# Determine guide_size: 0 means use input image dimensions
guide_size = params.inpaintFullResSize
if guide_size == 0:
guide_size = max(params.dimensions.width, params.dimensions.height)
# Create BASIC_PIPE for MaskDetailer
basic_pipe = ToBasicPipe(model, clip, vae, conditioning, conditioning2)
# MaskDetailerPipe: crops masked region, upscales, inpaints, composites back
# Returns the composited image as first output
detailed_image, _, _, _, _ = MaskDetailerPipe(
image=input_image,
mask=inpaint_mask,
basic_pipe=basic_pipe,
guide_size=float(guide_size),
guide_size_for=True, # Use mask bbox for sizing
max_size=float(guide_size * 1.5), # Allow some headroom
mask_mode=True, # Masked only (not whole image)
seed=params.seed,
steps=params.steps,
cfg=params.cfg,
sampler_name=params.sampler,
scheduler=params.scheduler,
denoise=params.denoise,
feather=params.inpaintFeather,
crop_factor=params.inpaintPadding,
drop_size=10, # Min segment size
refiner_ratio=0.0, # No refiner
batch_size=1,
cycle=1,
inpaint_model=(params.inpaintMode == "vae_inpaint"),
noise_mask_feather=params.inpaintFeather
)
# Apply upscale if specified
if params.upscale != 1.0:
detailed_image = ImageScaleBy(detailed_image, 'lanczos', params.upscale)
output_image = detailed_image
else:
# Standard inpainting path (non-full-res)
if params.inpaintMode == "vae_inpaint":
latent = VAEEncodeForInpaint(input_image, vae, inpaint_mask)
else:
latent = VAEEncode(input_image, vae)
latent = SetLatentNoiseMask(latent, inpaint_mask)
# Apply upscale if specified
if params.upscale != 1.0:
latent = LatentUpscaleBy(latent, 'nearest-exact', params.upscale)
# Sample and decode
latent = KSampler(model, params.seed, params.steps, params.cfg, params.sampler, params.scheduler, conditioning, conditioning2, latent, params.denoise)
output_image = VAEDecode(latent, vae)
else:
# Img2img without mask
latent = VAEEncode(input_image, vae)
if params.upscale != 1.0:
latent = LatentUpscaleBy(latent, 'nearest-exact', params.upscale)
latent = KSampler(model, params.seed, params.steps, params.cfg, params.sampler, params.scheduler, conditioning, conditioning2, latent, params.denoise)
if params.loopback.enabled:
for _ in range(params.loopback.iterations):
latent = LatentUpscaleBy(latent, 'nearest-exact', params.loopback.upscale)
latent = KSampler(model, params.seed + 1, params.loopback.steps, params.loopback.cfg, params.sampler, params.scheduler, conditioning, conditioning2, latent, params.loopback.denoise)
output_image = VAEDecode(latent, vae)
else:
# Text-to-image (no input image)
latent = EmptyLatentImage(params.dimensions.width, params.dimensions.height, 1)
latent = KSampler(model, params.seed, params.steps, params.cfg, params.sampler, params.scheduler, conditioning, conditioning2, latent, params.denoise)
if params.loopback.enabled:
for _ in range(params.loopback.iterations):
latent = LatentUpscaleBy(latent, 'nearest-exact', params.loopback.upscale)
latent = KSampler(model, params.seed + 1, params.loopback.steps, params.loopback.cfg, params.sampler, params.scheduler, conditioning, conditioning2, latent, params.loopback.denoise)
output_image = VAEDecode(latent, vae)
# =============================================
# Output Processing Pipeline
# =============================================
# 1. Upscale with AI model if specified
if params.upscaleModel and params.upscaleModel != "":
upscale_model = UpscaleModelLoader(params.upscaleModel)
output_image = ImageUpscaleWithModel(upscale_model, output_image)
# 2. Cap output size if maxOutputSize is set (scales down if larger)
max_size = int(params.maxOutputSize) if params.maxOutputSize else 0
if max_size > 0:
output_image = ResizeImagesByLongerEdge(output_image, max_size)
# 3. Remove background if enabled
if params.removeBackground:
rmbg_model = BRIARMBGModelLoaderZho()
output_image, _ = BRIARMBGZho(rmbg_model, output_image)
# Save outputs using configured save mode (disk/temporary/stream)
# Automatically embeds params_raw in PNG metadata for parameter recall
self.save_outputs(image)
self.save_outputs(output_image)
return {
'prompt_id': wf.task.prompt_id,
'client_id': _client_id,
'status': 'queued',
'parameters': self.params.model_dump(mode='json')
}
@@ -111,7 +282,7 @@ def run_workflow(**kwargs):
save_mode = kwargs.pop('save_mode', 'disk')
params_raw = kwargs.pop('params_raw', None)
required = ['prompt', 'checkpoints', 'seed', 'steps', 'negativePrompt', 'width', 'height', 'cfg']
required = ['prompt', 'checkpoints', 'seed', 'steps', 'negativePrompt', 'dimensions', 'cfg']
missing = [f for f in required if f not in kwargs]
if missing:
raise ValueError(f"Missing required fields: {', '.join(missing)}")
-83
View File
@@ -1,83 +0,0 @@
"""
Test Workflow 1 (No LoRAs).
Schema is defined in basic_test1.yaml (auto-generated from WorkflowParams).
"""
from comfy_script.runtime import *
load('http://127.0.0.1:8188/')
from comfy_script.runtime.nodes import *
from pydantic import BaseModel, Field
from typing import List
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from base import BaseWorkflow
from parameters import (
Prompt, NegativePrompt, Checkpoint, Seed, Sampler, Scheduler,
Dimensions
)
# ============================================
# Workflow Metadata
# ============================================
WORKFLOW_METADATA = {
"name": "Test Workflow 1 (No LoRAs)",
"description": "Test workflow without LoRA support.",
"model_types": ["SDXL"],
"category": "Testing",
}
# ============================================
# Workflow Parameters Model
# ============================================
class WorkflowParams(BaseModel):
"""Parameters for test workflow without LoRAs."""
prompt: Prompt
negativePrompt: NegativePrompt = "text, watermark"
checkpoints: Checkpoint
sampler: Sampler = "euler"
scheduler: Scheduler = "normal"
seed: Seed
dimensions: Dimensions
steps: int = Field(default=20, ge=1, le=150)
cfg: float = Field(default=8.0, ge=1.0, le=20.0, json_schema_extra={"step": 0.5})
# Workflow definition
class TestWorkflow1(BaseWorkflow):
def run(self):
params: WorkflowParams = self.params
with Workflow(wait=False):
model, clip, vae = self.load_checkpoints()
conditioning = CLIPTextEncode(params.prompt, clip)
conditioning2 = CLIPTextEncode(params.negativePrompt, clip)
latent = EmptyLatentImage(params.dimensions.width, params.dimensions.height, 1)
latent = KSampler(model, params.seed, params.steps, params.cfg, params.sampler, params.scheduler, 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(mode='json')
}
# Module-level entry point
def run_workflow(**kwargs):
"""Entry point for the workflow."""
required = ['prompt', 'checkpoints', 'seed', 'steps', 'negativePrompt', 'dimensions', 'cfg']
missing = [f for f in required if f not in kwargs]
if missing:
raise ValueError(f"Missing required fields: {', '.join(missing)}")
params = WorkflowParams(**kwargs)
# Create and run workflow
workflow = TestWorkflow1(params)
return workflow.run()
-83
View File
@@ -1,83 +0,0 @@
"""
Test Workflow 2 (No Sampler/Scheduler).
Schema is defined in basic_test2.yaml (auto-generated from WorkflowParams).
"""
from comfy_script.runtime import *
load('http://127.0.0.1:8188/')
from comfy_script.runtime.nodes import *
from pydantic import BaseModel, Field
from typing import List
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from base import BaseWorkflow
from parameters import (
Prompt, NegativePrompt, Checkpoint, Seed, Dimensions, Loras
)
# ============================================
# Workflow Metadata
# ============================================
WORKFLOW_METADATA = {
"name": "Test Workflow 2 (No Sampler/Scheduler)",
"description": "Test workflow without sampler/scheduler selection.",
"model_types": ["SDXL"],
"category": "Testing",
}
# ============================================
# Workflow Parameters Model
# ============================================
class WorkflowParams(BaseModel):
"""Parameters for test workflow without sampler/scheduler."""
prompt: Prompt
negativePrompt: NegativePrompt = "text, watermark"
checkpoints: Checkpoint
loras: Loras
seed: Seed
dimensions: Dimensions
steps: int = Field(default=20, ge=1, le=150)
cfg: float = Field(default=8.0, ge=1.0, le=20.0, json_schema_extra={"step": 0.5})
# Workflow definition
class TestWorkflow2(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.dimensions.width, params.dimensions.height, 1)
# Hardcoded sampler/scheduler
latent = KSampler(model, params.seed, params.steps, params.cfg, '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(mode='json')
}
# Module-level entry point
def run_workflow(**kwargs):
"""Entry point for the workflow."""
required = ['prompt', 'checkpoints', 'seed', 'steps', 'negativePrompt', 'dimensions', 'cfg']
missing = [f for f in required if f not in kwargs]
if missing:
raise ValueError(f"Missing required fields: {', '.join(missing)}")
params = WorkflowParams(**kwargs)
# Create and run workflow
workflow = TestWorkflow2(params)
return workflow.run()
-84
View File
@@ -1,84 +0,0 @@
"""
Test Workflow.
Schema is defined in test.yaml (auto-generated from WorkflowParams).
"""
from comfy_script.runtime import *
load('http://127.0.0.1:8188/')
from comfy_script.runtime.nodes import *
from pydantic import BaseModel, Field
from typing import List
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from base import BaseWorkflow
from parameters import (
Prompt, NegativePrompt, Checkpoint, Seed, Loras, Dimensions, DimensionsParams
)
# ============================================
# Workflow Metadata
# ============================================
WORKFLOW_METADATA = {
"name": "Test Workflow",
"description": "Basic test workflow for development.",
"model_types": ["SDXL"],
"category": "Testing",
}
# ============================================
# Workflow Parameters Model
# ============================================
class WorkflowParams(BaseModel):
"""Parameters for test workflow."""
prompt: Prompt
negativePrompt: NegativePrompt = "text, watermark"
checkpoints: Checkpoint
loras: Loras
seed: Seed
dimensions: Dimensions = DimensionsParams(width=512, height=512)
steps: int = Field(default=20, ge=1, le=150)
# ============================================
# 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.dimensions.width, params.dimensions.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(mode='json')
}
# Module-level entry point
def run_workflow(**kwargs):
"""Entry point for the workflow."""
required = ['prompt', 'checkpoints', 'seed', 'steps', 'negativePrompt', 'dimensions']
missing = [f for f in required if f not in kwargs]
if missing:
raise ValueError(f"Missing required fields: {', '.join(missing)}")
params = WorkflowParams(**kwargs)
# Create and run workflow
workflow = TestWorkflow(params)
return workflow.run()