Archived
146 lines
4.9 KiB
Python
146 lines
4.9 KiB
Python
"""
|
|
Workflow registry for external API.
|
|
Auto-discovers workflow files from the workflows/ folder.
|
|
Supports hot reloading - workflows are reloaded from disk on each execution.
|
|
"""
|
|
import os
|
|
import glob
|
|
import importlib.util
|
|
from typing import Callable, Dict, List, Optional
|
|
|
|
# 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 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
|
|
|
|
# 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": hasattr(module, "WORKFLOW_PARAMETERS"),
|
|
}
|
|
|
|
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") # Don't expose internal file path
|
|
return config
|
|
|
|
|
|
def get_workflow_parameters(name: str) -> Optional[List[dict]]:
|
|
"""
|
|
Get parameter schema for a specific workflow.
|
|
Returns None if workflow doesn't define WORKFLOW_PARAMETERS.
|
|
"""
|
|
workflows = discover_workflows()
|
|
|
|
if name not in workflows:
|
|
raise ValueError(f"Workflow '{name}' not found. Available: {list(workflows.keys())}")
|
|
|
|
# Load the module to get parameters
|
|
module = load_workflow_module(name)
|
|
|
|
if not hasattr(module, "WORKFLOW_PARAMETERS"):
|
|
return None
|
|
|
|
return module.WORKFLOW_PARAMETERS
|
|
|
|
|
|
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 != "script"}
|
|
}
|
|
for name, config in workflows.items()
|
|
]
|