""" 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). """ import os import glob import importlib.util import yaml from pathlib import Path from typing import Callable, Dict, List, Optional # 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 (refreshed on each list_workflows call) _workflow_cache: Dict[str, dict] = {} 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) -> Optional[Dict]: """Load YAML schema for a workflow if it exists.""" yaml_path = os.path.join(os.path.dirname(__file__), "workflows", f"{workflow_name}.yaml") if not os.path.exists(yaml_path): return None with open(yaml_path, "r", encoding="utf-8") as f: return yaml.safe_load(f) 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 resolve_options_source(parameters: List[Dict]) -> List[Dict]: """ Resolve options_source references in parameters to actual options. Returns a new list with resolved options. """ 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"] = [] resolved.append(param_copy) return resolved 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: 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 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 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 = True) -> list: """ Get list of available workflow names with their metadata. Set refresh=True to 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() ]