refactor: reorganize imports and enhance workflow caching mechanisms; add input image support in workflows

This commit is contained in:
donny committed 2026-01-06 19:08:18 -07:00
1 parent 7792f228b1
commit 5b4a19b1bc
10 files changed
+415 -42

No files matched your search

+1 -2
View File
@@ -33,5 +33,4 @@ if AUTO_INDEX_ON_STARTUP:
print("[ImageLab] Initialization complete")
NODE_CLASS_MAPPINGS = {}
NODE_DISPLAY_NAME_MAPPINGS = {}
from .imagelab_nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
+158
View File
@@ -0,0 +1,158 @@
from __future__ import annotations
import os
import sys
import json
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy"))
import folder_paths
from PIL.PngImagePlugin import PngInfo
from PIL import Image
import numpy as np
class ImageLabSaveImage:
def __init__(self):
self.output_dir = folder_paths.get_output_directory()
self.type = "output"
self.prefix_append = ""
self.compress_level = 4
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"images": ("IMAGE", {"tooltip": "The images to save."}),
"filename_prefix": ("STRING", {"default": "ImageLab", "tooltip": "The prefix for the file to save. This may include formatting information such as %date:yyyy-MM-dd% or %Empty Latent Image.width% to include values from nodes."})
},
"hidden": {
"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"
},
}
RETURN_TYPES = ()
FUNCTION = "save_images"
OUTPUT_NODE = True
CATEGORY = "image"
DESCRIPTION = "Saves the input images to your ComfyUI output directory."
def save_images(self, images, filename_prefix="ImageLab", prompt=None, extra_pnginfo=None):
filename_prefix += self.prefix_append
full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir, images[0].shape[1], images[0].shape[0])
results = list()
for (batch_number, image) in enumerate(images):
i = 255. * image.cpu().numpy()
img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
metadata = PngInfo()
# add comfyui specific workflow metadata
if prompt is not None:
metadata.add_text("prompt", json.dumps(prompt))
# add imagelab parameters metadata
if extra_pnginfo is not None:
for x in extra_pnginfo:
metadata.add_text(x, json.dumps(extra_pnginfo[x]))
filename_with_batch_num = filename.replace("%batch_num%", str(batch_number))
file = f"{filename_with_batch_num}_{counter:05}_.png"
img.save(os.path.join(full_output_folder, file), pnginfo=metadata, compress_level=self.compress_level)
results.append({
"filename": file,
"subfolder": subfolder,
"type": self.type
})
counter += 1
return { "ui": { "images": results } }
import hashlib
import os
import torch
import numpy as np
from PIL import Image
from io import BytesIO
def is_changed_file(filepath):
"""Check if file has changed using MD5 hash."""
try:
with open(filepath, "rb") as f:
file_hash = hashlib.md5(f.read()).hexdigest()
if not hasattr(is_changed_file, "file_hashes"):
is_changed_file.file_hashes = {}
if filepath in is_changed_file.file_hashes:
if is_changed_file.file_hashes[filepath] == file_hash:
return False
is_changed_file.file_hashes[filepath] = file_hash
return float("NaN") # Signals ComfyUI that the node needs re-execution
except Exception as e:
print(f"Error checking file {filepath}: {e}")
return False
class WatchImageFile:
"""Watches a specific image file for changes and loads it when changed."""
_watched_path = None # Class variable to store path for IS_CHANGED
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"file_path": ("STRING", {
"default": "C:/path/to/your/image.png",
"multiline": False
}),
"wait_for_changes": ("BOOLEAN", {"default": True}),
}
}
RETURN_TYPES = ("IMAGE", "INT", "INT")
RETURN_NAMES = ("image", "width", "height")
FUNCTION = "load_image"
CATEGORY = "image"
def load_image(self, file_path, wait_for_changes):
# Store path for IS_CHANGED to access
WatchImageFile._watched_path = file_path
if not os.path.exists(file_path):
# Return a blank image if file doesn't exist
print(f"File not found: {file_path}")
blank = Image.new("RGB", (512, 512), (0, 0, 0))
img_array = np.array(blank).astype(np.float32) / 255.0
return (torch.from_numpy(img_array)[None,], 512, 512)
try:
with open(file_path, "rb") as f:
img_data = f.read()
img = Image.open(BytesIO(img_data))
img = img.convert("RGB")
width, height = img.size
img_array = np.array(img).astype(np.float32) / 255.0
img_tensor = torch.from_numpy(img_array)[None,]
return (img_tensor, width, height)
except Exception as e:
print(f"Error loading image: {e}")
blank = Image.new("RGB", (512, 512), (0, 0, 0))
img_array = np.array(blank).astype(np.float32) / 255.0
return (torch.from_numpy(img_array)[None,], 512, 512)
@classmethod
def IS_CHANGED(cls, file_path, wait_for_changes):
if not wait_for_changes:
return float("NaN") # Always re-execute if not waiting
return is_changed_file(file_path)
NODE_CLASS_MAPPINGS = {
"WatchImageFile": WatchImageFile,
"ImageLabSaveImage": ImageLabSaveImage,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"WatchImageFile": "Watch Image File",
"ImageLabSaveImage": "ImageLab Save Image",
}
+24 -8
View File
@@ -29,6 +29,13 @@ Seed = Annotated[int, Field(
json_schema_extra={"component": "seed", "category": "parameters"}
)]
# Input image (for img2img, controlnet, etc.)
# Value is the filename string (e.g., "uploaded_image.png")
InputImage = Annotated[Optional[str], Field(
default=None,
json_schema_extra={"component": "input_image", "category": "composition"}
)]
# Enum types (selections from options_source)
Sampler = Annotated[str, Field(
json_schema_extra={"component": "sampler", "options_source": "samplers", "category": "parameters"}
@@ -63,6 +70,12 @@ class LoopbackParams(BaseModel):
steps: int = Field(default=10, ge=1, le=50)
cfg: float = Field(default=7.0, ge=1.0, le=20.0)
# class InputImageParams(BaseModel):
# """Input Image parameters."""
# use_image_size: bool = False
# width: int = Field(default=1024, ge=64, le=2048, multiple_of=8)
# height: int = Field(default=1024, ge=64, le=2048, multiple_of=8)
# Annotated types for nested objects
Dimensions = Annotated[DimensionsParams, Field(
default_factory=DimensionsParams,
@@ -74,17 +87,22 @@ Loopback = Annotated[LoopbackParams, Field(
json_schema_extra={"component": "loopback", "category": "advanced"}
)]
# InputImage = Annotated[InputImageParams, Field(
# default_factory=InputImageParams,
# json_schema_extra={"component": "input_image", "category": "composition"}
# )]
# =============================================================================
# Models with Parameters (for model_with_params type)
# =============================================================================
# Legacy - kept for reference, use LoopbackParams instead
class LoopbackParameters(BaseModel):
iterations: int = 1
upscale: float = 1.0
denoise: float = 0.5
steps: int = 10
cfg: float = 7.0
# class LoopbackParameters(BaseModel):
# iterations: int = 1
# upscale: float = 1.0
# denoise: float = 0.5
# steps: int = 10
# cfg: float = 7.0
class LoraParameters(BaseModel):
strength_model: float = 1.0
@@ -120,5 +138,3 @@ Controlnets = Annotated[List[Controlnet], Field(
default=[],
json_schema_extra={"component": "controlnets", "options_source": "controlnets", "category": "models"}
)]
# Add more shared types as needed
+64 -4
View File
@@ -4,7 +4,14 @@ 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
from .workflows import (
get_workflow,
get_workflow_metadata,
get_workflow_parameters,
list_workflows,
invalidate_workflow_cache,
invalidate_options_cache
)
from . import resources
def SetupRoutes(server: PromptServer):
@@ -12,9 +19,25 @@ def SetupRoutes(server: PromptServer):
@server.instance.routes.get("/imagelab/workflows")
async def list_available_workflows(request):
"""List all available workflows with metadata."""
"""
List all available workflows with metadata.
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()
'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
})
@server.instance.routes.get("/imagelab/workflow/{workflow_name}/metadata")
@@ -195,4 +218,41 @@ def SetupRoutes(server: PromptServer):
"""Test endpoint."""
return web.json_response({
'message': 'Hello from external API!'
})
})
@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
try:
input_dir = folder_paths.get_input_directory()
images = []
# Supported image extensions
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
})
# Sort by modified time (newest first)
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)
+103 -18
View File
@@ -4,13 +4,19 @@ Auto-discovers workflow files from the workflows/ folder.
Supports hot reloading - workflows are reloaded from disk on each execution.
Schema is loaded from YAML files (auto-generated from WorkflowParams).
Performance optimizations:
- Workflow list is cached and only refreshed when explicitly requested
- YAML schemas are cached after first load
- Options resolution is cached with TTL
"""
import os
import glob
import time
import importlib.util
import yaml
from pathlib import Path
from typing import Callable, Dict, List, Optional
from typing import Callable, Dict, List, Optional, Any
# Support both relative and absolute imports
# Resources module requires ComfyUI context
@@ -24,8 +30,17 @@ except ImportError:
# Resources not available (running outside ComfyUI)
pass
# Cache for discovered workflows (refreshed on each list_workflows call)
# Cache for discovered workflows
_workflow_cache: Dict[str, dict] = {}
_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):
@@ -40,15 +55,27 @@ def load_workflow_module(workflow_name: str):
return module
def load_yaml_schema(workflow_name: str) -> Optional[Dict]:
"""Load YAML schema for a workflow if it exists."""
def load_yaml_schema(workflow_name: str, use_cache: bool = True) -> Optional[Dict]:
"""
Load YAML schema for a workflow if it exists.
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")
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:
return yaml.safe_load(f)
schema = yaml.safe_load(f)
_yaml_schema_cache[workflow_name] = schema
return schema
def ensure_yaml_schema(workflow_name: str, module) -> Optional[Dict]:
@@ -109,39 +136,73 @@ def get_options_resolver() -> Dict[str, Callable[[], List[Dict]]]:
}
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.
"""
resolvers = get_options_resolver()
resolved = []
for param in parameters:
param_copy = param.copy()
options_source = param_copy.get("options_source")
if options_source and options_source in resolvers:
try:
param_copy["options"] = resolvers[options_source]()
except Exception as e:
print(f"[workflows] Error resolving {options_source}: {e}")
param_copy["options"] = []
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
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.
"""
global _workflow_cache
if _workflow_cache and not force_refresh:
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")
@@ -172,7 +233,7 @@ def discover_workflows(force_refresh: bool = False) -> Dict[str, dict]:
metadata = module.WORKFLOW_METADATA
# Check for YAML schema
# Check for YAML schema (uses its own cache)
yaml_schema = load_yaml_schema(workflow_id)
has_yaml = yaml_schema is not None
@@ -197,6 +258,8 @@ def discover_workflows(force_refresh: bool = False) -> Dict[str, dict]:
continue
_workflow_cache = discovered
_workflow_cache_time = current_time
print(f"[workflows] Cache refreshed with {len(discovered)} workflows")
return discovered
@@ -265,10 +328,12 @@ def get_workflow_parameters(name: str, resolve_options: bool = True) -> Optional
return None
def list_workflows(refresh: bool = True) -> list:
def list_workflows(refresh: bool = False) -> list:
"""
Get list of available workflow names with their metadata.
Set refresh=True to re-scan the workflows directory.
Uses cached data by default for fast response.
Set refresh=True to force re-scan the workflows directory.
"""
workflows = discover_workflows(force_refresh=refresh)
@@ -279,3 +344,23 @@ def list_workflows(refresh: bool = True) -> list:
}
for name, config in workflows.items()
]
def invalidate_workflow_cache():
"""
Invalidate all workflow caches.
Call this when you know workflows have changed (e.g., after adding/editing files).
"""
global _workflow_cache, _workflow_cache_time, _yaml_schema_cache
_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")
+24 -7
View File
@@ -15,7 +15,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
Loras, Dimensions, Loopback, InputImage
)
# ============================================
@@ -46,6 +46,7 @@ class WorkflowParams(BaseModel):
sampler: Sampler = "euler"
scheduler: Scheduler = "normal"
seed: Seed # Required, no default
inputImage: InputImage = "" # Optional input image for img2img
# Nested objects using shared types
dimensions: Dimensions
@@ -54,21 +55,30 @@ class WorkflowParams(BaseModel):
# Inline Field() for one-off constraints
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})
denoise: float = Field(default=1.0, ge=0.0, le=1.0, json_schema_extra={"step": 0.01, "category": "composition", "depends_on": {"inputImage": True}})
# Workflow definition
class SDXLWorkflow(BaseWorkflow):
def run(self):
params: WorkflowParams = self.params
with Workflow(wait=False):
with Workflow(wait=False) as wf:
model, clip, vae = self.load_checkpoints()
model, clip = self.apply_loras(model, clip)
vae = VAELoader(VAEs.sdxl_vae)
if params.inputImage != "" and params.inputImage is not None:
image, mask = LoadImage(params.inputImage)
image = ResizeImagesByLongerEdge(image, max(params.dimensions.width, params.dimensions.height))
latent = VAEEncode(image, vae)
else:
latent = EmptyLatentImage(params.dimensions.width, params.dimensions.height, 1)
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)
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):
@@ -76,12 +86,19 @@ class SDXLWorkflow(BaseWorkflow):
latent = KSampler(model, params.seed + 1, params.loopback.steps, params.loopback.cfg, params.sampler, params.scheduler, conditioning, conditioning2, latent, params.loopback.denoise)
image = VAEDecode(latent, vae)
preview = PreviewImage(image)
# We can have some base class method here to handle saving based on a flag so we can control if an image is saved on the server
# or if we return it to the client via websocket, etc.
PreviewImage(image, extra_pnginfo={"imagelab_parameters": params.model_dump(mode='json')})
# TODO: pass paramsRaw here to get the actual imagelab parameters in the metadata
# SaveImage(image, extra_pnginfo={"imagelab_parameters": params.model_dump(mode='json')})
return {
'prompt_id': preview.task.prompt_id,
'prompt_id': wf.task.prompt_id,
'status': 'queued',
'parameters': self.params.model_dump()
'parameters': self.params.model_dump(mode='json')
}
# Module-level entry point
+1 -1
View File
@@ -65,7 +65,7 @@ class TestWorkflow1(BaseWorkflow):
return {
'prompt_id': preview.task.prompt_id,
'status': 'queued',
'parameters': self.params.model_dump()
'parameters': self.params.model_dump(mode='json')
}
# Module-level entry point
+1 -1
View File
@@ -65,7 +65,7 @@ class TestWorkflow2(BaseWorkflow):
return {
'prompt_id': preview.task.prompt_id,
'status': 'queued',
'parameters': self.params.model_dump()
'parameters': self.params.model_dump(mode='json')
}
# Module-level entry point
+38
View File
@@ -0,0 +1,38 @@
from comfy_script.runtime import *
load()
from comfy_script.runtime.nodes import *
def f(wf):
seed = 0
pos = 'an ancient tree in the jungle, highly detailed, intricate, digital art'
neg = 'blurry, lowres, bad anatomy, worst quality'
model, clip, vae = CheckpointLoaderSimple(Checkpoints.aniversePonyXL_v60)
model, clip = LoraLoader(model, clip, Loras.LCMV2_PONYplus_PAseer, 1.0, 1.0)
# Watch your specific file instead of Photoshop
image, width, height = WatchImageFile(
file_path="H:/test.png",
wait_for_changes=True
)
latent = VAEEncode(image, vae)
latent = KSampler(model, seed, steps=4, cfg=1.7, sampler_name=Samplers.lcm,
positive=CLIPTextEncode(pos, clip),
negative=CLIPTextEncode(neg, clip),
latent_image=latent, denoise=0.65)
PreviewImage(VAEDecode(latent, vae))
# This queues the workflow whenever the queue is empty
# Combined with IS_CHANGED, it only re-generates when the file changes
# queue.when_empty(f)
# # Keep the script running so the watch loop can monitor the queue
# import time
# try:
# while True:
# time.sleep(1)
# except KeyboardInterrupt:
# print("\nStopped watching.")
+1 -1
View File
@@ -66,7 +66,7 @@ class TestWorkflow(BaseWorkflow):
return {
'prompt_id': preview.task.prompt_id,
'status': 'queued',
'parameters': self.params.model_dump()
'parameters': self.params.model_dump(mode='json')
}
# Module-level entry point