""" Workflow registry for external API. 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, Any # Support both relative and absolute imports # Resources module requires ComfyUI context resources = None try: from . import resources except ImportError: try: import resources except ImportError: # Resources not available (running outside ComfyUI) pass # 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): """Dynamically load/reload a workflow module from the workflows folder.""" 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) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module 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: schema = yaml.safe_load(f) _yaml_schema_cache[workflow_name] = schema return schema def ensure_yaml_schema(workflow_name: str, module) -> Optional[Dict]: """ Ensure YAML schema exists for a workflow. Auto-generates from WorkflowParams if missing. 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 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}") 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 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") 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, "name": metadata.get("name", workflow_id), "description": metadata.get("description", ""), "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), } 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") return discovered def get_workflow(name: str) -> Callable: """ Get a workflow function by name. 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())}") # Reload the module from disk each time module = load_workflow_module(name) return module.run_workflow 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())}") 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]]: """ 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. 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 """ workflows = discover_workflows() if name not in workflows: 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 # 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")} } 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")