diff --git a/parameter_schema.py b/parameter_schema.py new file mode 100644 index 0000000..a2a8ea6 --- /dev/null +++ b/parameter_schema.py @@ -0,0 +1,503 @@ +""" +Parameter Schema for ImageLab Workflows +======================================== + +This module defines the parameter schema system for workflows. +Each parameter is a dictionary that describes: +- What data it holds (type, name) +- How it should be rendered (component) +- Where it belongs (category) +- Validation rules (min, max, required, etc.) + +Usage in workflow files: +------------------------ +from ..parameter_schema import param, ParameterType, ParameterCategory, ComponentType + +WORKFLOW_PARAMETERS = [ + param.text_area( + name="prompt", + label="Prompt", + category=ParameterCategory.PROMPTS, + required=True, + placeholder="Enter your prompt...", + ), + param.slider( + name="steps", + label="Steps", + category=ParameterCategory.PARAMETERS, + min_val=1, + max_val=150, + default=20, + ), + param.model_select( + name="checkpoint", + label="Checkpoint", + category=ParameterCategory.MODELS, + model_type="checkpoints", + required=True, + ), +] +""" + +from typing import Any, Dict, List, Optional, Union +from enum import Enum + + +# ============================================ +# Enums for Type Safety +# ============================================ + +class ParameterType(str, Enum): + """Data types for parameters.""" + STRING = "string" + INTEGER = "integer" + FLOAT = "float" + BOOLEAN = "boolean" + ARRAY = "array" # For lists of items (e.g., multiple loras) + + +class ComponentType(str, Enum): + """ + UI component types for rendering parameters. + Maps to frontend React components. + """ + # Text inputs + TEXT_INPUT = "text_input" # Single line text + TEXT_AREA = "text_area" # Multi-line text (prompts) + + # Numeric inputs + SLIDER = "slider" # Range slider with number + NUMBER_INPUT = "number_input" # Direct number input + SEED_INPUT = "seed_input" # Seed with randomize button + + # Selection inputs + SELECT = "select" # Dropdown with fixed options + MODEL_SELECT = "model_select" # Model/resource selector + MULTI_SELECT = "multi_select" # Multiple selection dropdown + + # Toggle input (use style="switch" or style="checkbox") + TOGGLE = "toggle" # Boolean toggle + + +class ParameterCategory(str, Enum): + """ + Categories for grouping parameters in the UI. + Maps to frontend tabs/sections. + """ + PROMPTS = "prompts" # Prompt, negative prompt, helpers + MODELS = "models" # Checkpoints, LoRAs, VAE + PARAMETERS = "parameters" # Steps, CFG, sampler, scheduler, seed + COMPOSITION = "composition" # Dimensions, input images + ADVANCED = "advanced" # Advanced/experimental options + OUTPUT = "output" # Post processing, filtering, etc. + + +# ============================================ +# Parameter Schema Definition +# ============================================ + +class ParameterSchema: + """ + Base schema for all parameters. + Contains common fields and validation. + """ + + @staticmethod + def _base( + name: str, + param_type: ParameterType, + component: ComponentType, + category: ParameterCategory, + label: str, + description: str = "", + required: bool = False, + default: Any = None, + hidden: bool = False, + disabled: bool = False, + depends_on: Optional[Dict[str, Any]] = None, + ) -> Dict[str, Any]: + """ + Create base parameter structure. + + Args: + name: Unique identifier (used as API field name) + param_type: Data type of the parameter + component: UI component to render + category: Which tab/section this belongs to + label: Display label in UI + description: Help text / tooltip + required: Whether the field is required + default: Default value + hidden: Hide from UI (for internal params) + disabled: Show but disable interaction + depends_on: Conditional visibility based on other params + e.g., {"loopback": True} shows only when loopback is enabled + """ + schema = { + "name": name, + "type": param_type.value, + "component": component.value, + "category": category.value, + "label": label, + "required": required, + } + + if description: + schema["description"] = description + if default is not None: + schema["default"] = default + if hidden: + schema["hidden"] = hidden + if disabled: + schema["disabled"] = disabled + if depends_on: + schema["depends_on"] = depends_on + + return schema + + # ============================================ + # Text Components + # ============================================ + + @staticmethod + def text_input( + name: str, + label: str, + category: ParameterCategory, + description: str = "", + required: bool = False, + default: str = "", + placeholder: str = "", + max_length: Optional[int] = None, + **kwargs + ) -> Dict[str, Any]: + """Single line text input.""" + schema = ParameterSchema._base( + name=name, + param_type=ParameterType.STRING, + component=ComponentType.TEXT_INPUT, + category=category, + label=label, + description=description, + required=required, + default=default, + **kwargs + ) + if placeholder: + schema["placeholder"] = placeholder + if max_length: + schema["max_length"] = max_length + return schema + + @staticmethod + def text_area( + name: str, + label: str, + category: ParameterCategory, + description: str = "", + required: bool = False, + default: str = "", + placeholder: str = "", + rows: int = 4, + max_length: Optional[int] = None, + **kwargs + ) -> Dict[str, Any]: + """Multi-line text area (for prompts).""" + schema = ParameterSchema._base( + name=name, + param_type=ParameterType.STRING, + component=ComponentType.TEXT_AREA, + category=category, + label=label, + description=description, + required=required, + default=default, + **kwargs + ) + if placeholder: + schema["placeholder"] = placeholder + schema["rows"] = rows + if max_length: + schema["max_length"] = max_length + return schema + + # ============================================ + # Numeric Components + # ============================================ + + @staticmethod + def slider( + name: str, + label: str, + category: ParameterCategory, + min_val: Union[int, float], + max_val: Union[int, float], + default: Union[int, float], + step: Union[int, float] = 1, + description: str = "", + required: bool = False, + is_float: bool = False, + **kwargs + ) -> Dict[str, Any]: + """Slider with numeric input.""" + schema = ParameterSchema._base( + name=name, + param_type=ParameterType.FLOAT if is_float else ParameterType.INTEGER, + component=ComponentType.SLIDER, + category=category, + label=label, + description=description, + required=required, + default=default, + **kwargs + ) + schema["min"] = min_val + schema["max"] = max_val + schema["step"] = step + return schema + + @staticmethod + def number_input( + name: str, + label: str, + category: ParameterCategory, + min_val: Optional[Union[int, float]] = None, + max_val: Optional[Union[int, float]] = None, + default: Union[int, float] = 0, + step: Union[int, float] = 1, + description: str = "", + required: bool = False, + is_float: bool = False, + **kwargs + ) -> Dict[str, Any]: + """Direct number input field.""" + schema = ParameterSchema._base( + name=name, + param_type=ParameterType.FLOAT if is_float else ParameterType.INTEGER, + component=ComponentType.NUMBER_INPUT, + category=category, + label=label, + description=description, + required=required, + default=default, + **kwargs + ) + if min_val is not None: + schema["min"] = min_val + if max_val is not None: + schema["max"] = max_val + schema["step"] = step + return schema + + @staticmethod + def seed_input( + name: str = "seed", + label: str = "Seed", + category: ParameterCategory = ParameterCategory.PARAMETERS, + default: int = -1, + description: str = "Random seed (-1 for random)", + **kwargs + ) -> Dict[str, Any]: + """Seed input with randomize button.""" + schema = ParameterSchema._base( + name=name, + param_type=ParameterType.INTEGER, + component=ComponentType.SEED_INPUT, + category=category, + label=label, + description=description, + default=default, + **kwargs + ) + schema["min"] = -1 + schema["max"] = 2147483647 # Max int32 + return schema + + # ============================================ + # Selection Components + # ============================================ + + @staticmethod + def select( + name: str, + label: str, + category: ParameterCategory, + options: List[Dict[str, str]], # [{"value": "x", "label": "X"}, ...] + default: str = "", + description: str = "", + required: bool = False, + searchable: bool = False, + clearable: bool = False, + **kwargs + ) -> Dict[str, Any]: + """Dropdown select with fixed options.""" + schema = ParameterSchema._base( + name=name, + param_type=ParameterType.STRING, + component=ComponentType.SELECT, + category=category, + label=label, + description=description, + required=required, + default=default, + **kwargs + ) + schema["options"] = options + schema["searchable"] = searchable + schema["clearable"] = clearable + return schema + + @staticmethod + def multi_select( + name: str, + label: str, + category: ParameterCategory, + options: List[Dict[str, str]], + default: List[str] = None, + description: str = "", + required: bool = False, + searchable: bool = True, + max_selections: Optional[int] = None, + **kwargs + ) -> Dict[str, Any]: + """Multi-select dropdown.""" + schema = ParameterSchema._base( + name=name, + param_type=ParameterType.ARRAY, + component=ComponentType.MULTI_SELECT, + category=category, + label=label, + description=description, + required=required, + default=default or [], + **kwargs + ) + schema["options"] = options + schema["searchable"] = searchable + if max_selections: + schema["max_selections"] = max_selections + return schema + + @staticmethod + def model_select( + name: str, + label: str, + category: ParameterCategory, + model_type: str, # "checkpoints", "loras", "vae", "controlnet", etc. + default: str = "", + description: str = "", + required: bool = False, + multiple: bool = False, + max_selections: Optional[int] = None, + **kwargs + ) -> Dict[str, Any]: + """Model/resource selector that loads options from API.""" + schema = ParameterSchema._base( + name=name, + param_type=ParameterType.ARRAY if multiple else ParameterType.STRING, + component=ComponentType.MODEL_SELECT, + category=category, + label=label, + description=description, + required=required, + default=[] if multiple else default, + **kwargs + ) + schema["model_type"] = model_type + schema["multiple"] = multiple + if max_selections and multiple: + schema["max_selections"] = max_selections + return schema + + # ============================================ + # Toggle Component + # ============================================ + + @staticmethod + def toggle( + name: str, + label: str, + category: ParameterCategory, + default: bool = False, + description: str = "", + style: str = "switch", # "switch" or "checkbox" + **kwargs + ) -> Dict[str, Any]: + """ + Boolean toggle component. + + Args: + style: Visual style - "switch" for toggle switch, "checkbox" for checkbox + """ + schema = ParameterSchema._base( + name=name, + param_type=ParameterType.BOOLEAN, + component=ComponentType.TOGGLE, + category=category, + label=label, + description=description, + default=default, + **kwargs + ) + schema["style"] = style + return schema + + +# ============================================ +# Convenience Alias +# ============================================ + +# Use `param.text_area(...)` instead of `ParameterSchema.text_area(...)` +param = ParameterSchema + + +# ============================================ +# Validation Helpers +# ============================================ + +def validate_parameter_schema(schema: Dict[str, Any]) -> List[str]: + """ + Validate a parameter schema and return list of errors. + Returns empty list if valid. + """ + errors = [] + + required_fields = ["name", "type", "component", "category", "label"] + for field in required_fields: + if field not in schema: + errors.append(f"Missing required field: {field}") + + if "type" in schema: + valid_types = [t.value for t in ParameterType] + if schema["type"] not in valid_types: + errors.append(f"Invalid type '{schema['type']}'. Must be one of: {valid_types}") + + if "component" in schema: + valid_components = [c.value for c in ComponentType] + if schema["component"] not in valid_components: + errors.append(f"Invalid component '{schema['component']}'. Must be one of: {valid_components}") + + if "category" in schema: + valid_categories = [c.value for c in ParameterCategory] + if schema["category"] not in valid_categories: + errors.append(f"Invalid category '{schema['category']}'. Must be one of: {valid_categories}") + + return errors + + +def validate_workflow_parameters(parameters: List[Dict[str, Any]]) -> List[str]: + """Validate a list of parameter schemas.""" + errors = [] + names_seen = set() + + for i, param in enumerate(parameters): + param_errors = validate_parameter_schema(param) + for error in param_errors: + errors.append(f"Parameter {i}: {error}") + + if "name" in param: + if param["name"] in names_seen: + errors.append(f"Parameter {i}: Duplicate name '{param['name']}'") + names_seen.add(param["name"]) + + return errors diff --git a/routes.py b/routes.py index 8dac129..1dfc333 100644 --- a/routes.py +++ b/routes.py @@ -4,7 +4,7 @@ API routes for external workflow execution. from aiohttp import web from server import PromptServer -from .workflows import get_workflow, get_workflow_metadata, list_workflows +from .workflows import get_workflow, get_workflow_metadata, get_workflow_parameters, list_workflows from . import resources def SetupRoutes(server: PromptServer): @@ -34,6 +34,32 @@ def SetupRoutes(server: PromptServer): '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'] + 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 + }) + except ValueError as e: + 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.""" diff --git a/workflows.py b/workflows.py index 5013968..235874d 100644 --- a/workflows.py +++ b/workflows.py @@ -1,11 +1,16 @@ """ Workflow registry for external API. -Import workflow functions from the workflows/ folder and map them here. +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 +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.""" @@ -18,75 +23,123 @@ def load_workflow_module(workflow_name: str): spec.loader.exec_module(module) return module -# Workflow registry - map workflow names to their config (file + metadata) -# The modules will be reloaded on each execution for hot reloading -WORKFLOW_FILES: Dict[str, dict] = { - "test_workflow": { - "script": "test", - "name": "Test Workflow", - "description": "Simple test workflow for image generation", - "model_types": ["SDXL", "Pony", "Illustrious"], - "category": "Image Generation" - }, - # Add more workflows here as you create them - "basic_sdxl": { - "script": "basic_sdxl", - "name": "Basic SDXL Text to Image", - "description": "Workflow with SDXL presets for quick iteration.", - "model_types": ["SDXL"], - "category": "Image Generation" - }, - "basic_sd15": { - "script": "basic_sd15", - "name": "Basic SD15 Text to Image", - "description": "Workflow with SD15 presets for quick iteration.", - "model_types": ["SD15"], - "category": "Image Generation" - }, - "basic_pony": { - "script": "basic_pony", - "name": "Basic Pony Text to Image", - "description": "Workflow with Pony presets for quick iteration.", - "model_types": ["Pony"], - "category": "Image Generation" - }, - "basic_illustrious": { - "script": "basic_illustrious", - "name": "Basic Illustrious Text to Image", - "description": "Workflow with Illustrious presets for quick iteration.", - "model_types": ["Illustrious"], - "category": "Image Generation" - }, -} + +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. """ - if name not in WORKFLOW_FILES: - raise ValueError(f"Workflow '{name}' not found. Available: {list(WORKFLOW_FILES.keys())}") + 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 - workflow_config = WORKFLOW_FILES[name] - module = load_workflow_module(workflow_config["script"]) + module = load_workflow_module(name) return module.run_workflow + def get_workflow_metadata(name: str) -> dict: """Get metadata for a specific workflow.""" - if name not in WORKFLOW_FILES: - raise ValueError(f"Workflow '{name}' not found. Available: {list(WORKFLOW_FILES.keys())}") + workflows = discover_workflows() - config = WORKFLOW_FILES[name].copy() + 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 list_workflows() -> list: - """Get list of available workflow names with their metadata.""" + +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, - **get_workflow_metadata(name) + **{k: v for k, v in config.items() if k != "script"} } - for name in WORKFLOW_FILES.keys() + for name, config in workflows.items() ] diff --git a/workflows/basic_illustrious.py b/workflows/basic_illustrious.py deleted file mode 100644 index 3c67094..0000000 --- a/workflows/basic_illustrious.py +++ /dev/null @@ -1,61 +0,0 @@ -from comfy_script.runtime import * -load('http://127.0.0.1:8188/') -from comfy_script.runtime.nodes import * - -from pydantic import BaseModel -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 Lora - -# Workflow-specific parameters -class WorkflowParams(BaseModel): - prompt: str - negativePrompt: str = "text, watermark" - checkpoints: List[str] - loras: List[Lora] = [] - steps: int = 20 - seed: int = None - width: int = 512 - height: int = 512 - -# 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.width, params.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() - } - -# Module-level entry point -def run_workflow(**kwargs): - """Entry point for the workflow.""" - required = ['prompt', 'checkpoints', 'seed', 'steps', 'negativePrompt', 'width', 'height'] - 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() diff --git a/workflows/basic_pony.py b/workflows/basic_pony.py deleted file mode 100644 index 3c67094..0000000 --- a/workflows/basic_pony.py +++ /dev/null @@ -1,61 +0,0 @@ -from comfy_script.runtime import * -load('http://127.0.0.1:8188/') -from comfy_script.runtime.nodes import * - -from pydantic import BaseModel -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 Lora - -# Workflow-specific parameters -class WorkflowParams(BaseModel): - prompt: str - negativePrompt: str = "text, watermark" - checkpoints: List[str] - loras: List[Lora] = [] - steps: int = 20 - seed: int = None - width: int = 512 - height: int = 512 - -# 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.width, params.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() - } - -# Module-level entry point -def run_workflow(**kwargs): - """Entry point for the workflow.""" - required = ['prompt', 'checkpoints', 'seed', 'steps', 'negativePrompt', 'width', 'height'] - 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() diff --git a/workflows/basic_sd15.py b/workflows/basic_sd15.py deleted file mode 100644 index 3c67094..0000000 --- a/workflows/basic_sd15.py +++ /dev/null @@ -1,61 +0,0 @@ -from comfy_script.runtime import * -load('http://127.0.0.1:8188/') -from comfy_script.runtime.nodes import * - -from pydantic import BaseModel -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 Lora - -# Workflow-specific parameters -class WorkflowParams(BaseModel): - prompt: str - negativePrompt: str = "text, watermark" - checkpoints: List[str] - loras: List[Lora] = [] - steps: int = 20 - seed: int = None - width: int = 512 - height: int = 512 - -# 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.width, params.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() - } - -# Module-level entry point -def run_workflow(**kwargs): - """Entry point for the workflow.""" - required = ['prompt', 'checkpoints', 'seed', 'steps', 'negativePrompt', 'width', 'height'] - 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() diff --git a/workflows/basic_sdxl.py b/workflows/basic_sdxl.py index 28ad39a..e27d878 100644 --- a/workflows/basic_sdxl.py +++ b/workflows/basic_sdxl.py @@ -9,9 +9,206 @@ import os sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) from base import BaseWorkflow -from parameters import Lora, LoopbackParameters +from parameters import Lora +from parameter_schema import param, ParameterCategory + +# ============================================ +# Workflow Metadata +# ============================================ + +WORKFLOW_METADATA = { + "name": "Basic SDXL Text to Image", + "description": "Workflow with SDXL presets for quick iteration.", + "model_types": ["SDXL"], + "category": "Image Generation", +} + +# ============================================ +# Workflow Parameters Schema +# ============================================ + +WORKFLOW_PARAMETERS = [ + # Prompts + param.text_area( + name="prompt", + label="Prompt", + category=ParameterCategory.PROMPTS, + required=True, + placeholder="Enter your prompt...", + rows=4, + ), + param.text_area( + name="negativePrompt", + label="Negative Prompt", + category=ParameterCategory.PROMPTS, + default="text, watermark", + placeholder="Enter negative prompt...", + rows=2, + ), + + # Models + param.model_select( + name="checkpoints", + label="Checkpoint", + category=ParameterCategory.MODELS, + model_type="checkpoints", + required=True, + multiple=True, + max_selections=1, + ), + param.model_select( + name="loras", + label="LoRAs", + category=ParameterCategory.MODELS, + model_type="loras", + multiple=True, + description="Add LoRA models to apply", + ), + + # Parameters (Sampling) + param.slider( + name="steps", + label="Steps", + category=ParameterCategory.PARAMETERS, + min_val=1, + max_val=150, + default=20, + ), + param.slider( + name="cfg", + label="CFG Scale", + category=ParameterCategory.PARAMETERS, + min_val=1.0, + max_val=20.0, + default=8.0, + step=0.5, + is_float=True, + ), + param.select( + name="sampler", + label="Sampler", + category=ParameterCategory.PARAMETERS, + options=[ + {"value": "euler", "label": "Euler"}, + {"value": "euler_ancestral", "label": "Euler Ancestral"}, + {"value": "heun", "label": "Heun"}, + {"value": "dpm_2", "label": "DPM 2"}, + {"value": "dpm_2_ancestral", "label": "DPM 2 Ancestral"}, + {"value": "lms", "label": "LMS"}, + {"value": "dpmpp_2m", "label": "DPM++ 2M"}, + {"value": "dpmpp_2m_sde", "label": "DPM++ 2M SDE"}, + {"value": "dpmpp_sde", "label": "DPM++ SDE"}, + {"value": "ddim", "label": "DDIM"}, + ], + default="euler", + searchable=True, + ), + param.select( + name="scheduler", + label="Scheduler", + category=ParameterCategory.PARAMETERS, + options=[ + {"value": "normal", "label": "Normal"}, + {"value": "karras", "label": "Karras"}, + {"value": "exponential", "label": "Exponential"}, + {"value": "sgm_uniform", "label": "SGM Uniform"}, + {"value": "simple", "label": "Simple"}, + {"value": "ddim_uniform", "label": "DDIM Uniform"}, + ], + default="normal", + ), + param.seed_input( + name="seed", + label="Seed", + category=ParameterCategory.PARAMETERS, + ), + + # Composition + param.slider( + name="width", + label="Width", + category=ParameterCategory.COMPOSITION, + min_val=64, + max_val=2048, + default=1024, + step=8, + ), + param.slider( + name="height", + label="Height", + category=ParameterCategory.COMPOSITION, + min_val=64, + max_val=2048, + default=1024, + step=8, + ), + + # Advanced - Loopback + param.toggle( + name="loopback", + label="Enable Loopback", + category=ParameterCategory.ADVANCED, + default=False, + style="switch", + description="Enable iterative upscaling and refinement", + ), + param.slider( + name="loopbackIterations", + label="Loopback Iterations", + category=ParameterCategory.ADVANCED, + min_val=1, + max_val=5, + default=1, + depends_on={"loopback": True}, + ), + param.slider( + name="loopbackUpscale", + label="Loopback Upscale", + category=ParameterCategory.ADVANCED, + min_val=1.0, + max_val=2.0, + default=1.25, + step=0.05, + is_float=True, + depends_on={"loopback": True}, + ), + param.slider( + name="loopbackDenoise", + label="Loopback Denoise", + category=ParameterCategory.ADVANCED, + min_val=0.0, + max_val=1.0, + default=0.5, + step=0.05, + is_float=True, + depends_on={"loopback": True}, + ), + param.slider( + name="loopbackSteps", + label="Loopback Steps", + category=ParameterCategory.ADVANCED, + min_val=1, + max_val=50, + default=10, + depends_on={"loopback": True}, + ), + param.slider( + name="loopbackCfg", + label="Loopback CFG", + category=ParameterCategory.ADVANCED, + min_val=1.0, + max_val=20.0, + default=7.0, + step=0.5, + is_float=True, + depends_on={"loopback": True}, + ), +] + +# ============================================ +# Workflow Parameters Model (for validation) +# ============================================ -# Workflow-specific parameters class WorkflowParams(BaseModel): prompt: str negativePrompt: str = "text, watermark" @@ -20,15 +217,20 @@ class WorkflowParams(BaseModel): steps: int = 20 seed: int = None cfg: float = 8.0 - width: int = 512 - height: int = 512 + width: int = 1024 + height: int = 1024 sampler: str = 'euler' scheduler: str = 'normal' loopback: bool = False - loopbackParameters: LoopbackParameters = LoopbackParameters() + # Flattened loopback parameters + loopbackIterations: int = 1 + loopbackUpscale: float = 1.25 + loopbackDenoise: float = 0.5 + loopbackSteps: int = 10 + loopbackCfg: float = 7.0 # Workflow definition -class TestWorkflow(BaseWorkflow): +class SDXLWorkflow(BaseWorkflow): def run(self): params: WorkflowParams = self.params @@ -43,9 +245,9 @@ class TestWorkflow(BaseWorkflow): latent = KSampler(model, params.seed, params.steps, params.cfg, params.sampler, params.scheduler, conditioning, conditioning2, latent, 1) if params.loopback: - for _ in range(params.loopbackParameters.iterations): - latent = LatentUpscaleBy(latent, 'nearest-exact', params.loopbackParameters.upscale) - latent = KSampler(model, params.seed + 1, params.loopbackParameters.steps, params.loopbackParameters.cfg, params.sampler, params.scheduler, conditioning, conditioning2, latent, params.loopbackParameters.denoise) + for _ in range(params.loopbackIterations): + latent = LatentUpscaleBy(latent, 'nearest-exact', params.loopbackUpscale) + latent = KSampler(model, params.seed + 1, params.loopbackSteps, params.loopbackCfg, params.sampler, params.scheduler, conditioning, conditioning2, latent, params.loopbackDenoise) image = VAEDecode(latent, vae) preview = PreviewImage(image) @@ -67,5 +269,5 @@ def run_workflow(**kwargs): params = WorkflowParams(**kwargs) # Create and run workflow - workflow = TestWorkflow(params) + workflow = SDXLWorkflow(params) return workflow.run() diff --git a/workflows/basic_test1.py b/workflows/basic_test1.py new file mode 100644 index 0000000..e327914 --- /dev/null +++ b/workflows/basic_test1.py @@ -0,0 +1,189 @@ +from comfy_script.runtime import * +load('http://127.0.0.1:8188/') +from comfy_script.runtime.nodes import * + +from pydantic import BaseModel +from typing import List +import sys +import os + +sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) +from base import BaseWorkflow +from parameter_schema import param, ParameterCategory + +# ============================================ +# Workflow Metadata +# ============================================ + +WORKFLOW_METADATA = { + "name": "Test Workflow 1 (No LoRAs)", + "description": "Test workflow without LoRA support.", + "model_types": ["SDXL"], + "category": "Testing", +} + +# ============================================ +# Workflow Parameters Schema +# ============================================ + +WORKFLOW_PARAMETERS = [ + # Prompts + param.text_area( + name="prompt", + label="Prompt", + category=ParameterCategory.PROMPTS, + required=True, + placeholder="Enter your prompt...", + rows=4, + ), + param.text_area( + name="negativePrompt", + label="Negative Prompt", + category=ParameterCategory.PROMPTS, + default="text, watermark", + placeholder="Enter negative prompt...", + rows=2, + ), + + # Models - NO LORAS + param.model_select( + name="checkpoints", + label="Checkpoint", + category=ParameterCategory.MODELS, + model_type="checkpoints", + required=True, + multiple=True, + max_selections=1, + ), + + # Parameters (Sampling) + param.slider( + name="steps", + label="Steps", + category=ParameterCategory.PARAMETERS, + min_val=1, + max_val=150, + default=20, + ), + param.slider( + name="cfg", + label="CFG Scale", + category=ParameterCategory.PARAMETERS, + min_val=1.0, + max_val=20.0, + default=8.0, + step=0.5, + is_float=True, + ), + param.select( + name="sampler", + label="Sampler", + category=ParameterCategory.PARAMETERS, + options=[ + {"value": "euler", "label": "Euler"}, + {"value": "euler_ancestral", "label": "Euler Ancestral"}, + {"value": "heun", "label": "Heun"}, + {"value": "dpm_2", "label": "DPM 2"}, + {"value": "dpm_2_ancestral", "label": "DPM 2 Ancestral"}, + {"value": "lms", "label": "LMS"}, + {"value": "dpmpp_2m", "label": "DPM++ 2M"}, + {"value": "dpmpp_2m_sde", "label": "DPM++ 2M SDE"}, + {"value": "dpmpp_sde", "label": "DPM++ SDE"}, + {"value": "ddim", "label": "DDIM"}, + ], + default="euler", + searchable=True, + ), + param.select( + name="scheduler", + label="Scheduler", + category=ParameterCategory.PARAMETERS, + options=[ + {"value": "normal", "label": "Normal"}, + {"value": "karras", "label": "Karras"}, + {"value": "exponential", "label": "Exponential"}, + {"value": "sgm_uniform", "label": "SGM Uniform"}, + {"value": "simple", "label": "Simple"}, + {"value": "ddim_uniform", "label": "DDIM Uniform"}, + ], + default="normal", + ), + param.seed_input( + name="seed", + label="Seed", + category=ParameterCategory.PARAMETERS, + ), + + # Composition + param.slider( + name="width", + label="Width", + category=ParameterCategory.COMPOSITION, + min_val=64, + max_val=2048, + default=1024, + step=8, + ), + param.slider( + name="height", + label="Height", + category=ParameterCategory.COMPOSITION, + min_val=64, + max_val=2048, + default=1024, + step=8, + ), +] + +# ============================================ +# Workflow Parameters Model (for validation) +# ============================================ + +class WorkflowParams(BaseModel): + prompt: str + negativePrompt: str = "text, watermark" + checkpoints: List[str] + steps: int = 20 + seed: int = None + cfg: float = 8.0 + width: int = 1024 + height: int = 1024 + sampler: str = 'euler' + scheduler: str = 'normal' + +# 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.width, params.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() + } + +# Module-level entry point +def run_workflow(**kwargs): + """Entry point for the workflow.""" + required = ['prompt', 'checkpoints', 'seed', 'steps', 'negativePrompt', 'width', 'height', '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() diff --git a/workflows/basic_test2.py b/workflows/basic_test2.py new file mode 100644 index 0000000..cee98bb --- /dev/null +++ b/workflows/basic_test2.py @@ -0,0 +1,166 @@ +from comfy_script.runtime import * +load('http://127.0.0.1:8188/') +from comfy_script.runtime.nodes import * + +from pydantic import BaseModel +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 Lora +from parameter_schema import param, ParameterCategory + +# ============================================ +# 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 Schema +# ============================================ + +WORKFLOW_PARAMETERS = [ + # Prompts + param.text_area( + name="prompt", + label="Prompt", + category=ParameterCategory.PROMPTS, + required=True, + placeholder="Enter your prompt...", + rows=4, + ), + param.text_area( + name="negativePrompt", + label="Negative Prompt", + category=ParameterCategory.PROMPTS, + default="text, watermark", + placeholder="Enter negative prompt...", + rows=2, + ), + + # Models + param.model_select( + name="checkpoints", + label="Checkpoint", + category=ParameterCategory.MODELS, + model_type="checkpoints", + required=True, + multiple=True, + max_selections=1, + ), + param.model_select( + name="loras", + label="LoRAs", + category=ParameterCategory.MODELS, + model_type="loras", + multiple=True, + description="Add LoRA models to apply", + ), + + # Parameters (Sampling) - NO SAMPLER/SCHEDULER + param.slider( + name="steps", + label="Steps", + category=ParameterCategory.PARAMETERS, + min_val=1, + max_val=150, + default=20, + ), + param.slider( + name="cfg", + label="CFG Scale", + category=ParameterCategory.PARAMETERS, + min_val=1.0, + max_val=20.0, + default=8.0, + step=0.5, + is_float=True, + ), + param.seed_input( + name="seed", + label="Seed", + category=ParameterCategory.PARAMETERS, + ), + + # Composition + param.slider( + name="width", + label="Width", + category=ParameterCategory.COMPOSITION, + min_val=64, + max_val=2048, + default=1024, + step=8, + ), + param.slider( + name="height", + label="Height", + category=ParameterCategory.COMPOSITION, + min_val=64, + max_val=2048, + default=1024, + step=8, + ), +] + +# ============================================ +# Workflow Parameters Model (for validation) +# ============================================ + +class WorkflowParams(BaseModel): + prompt: str + negativePrompt: str = "text, watermark" + checkpoints: List[str] + loras: List[Lora] = [] + steps: int = 20 + seed: int = None + cfg: float = 8.0 + width: int = 1024 + height: int = 1024 + +# 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.width, params.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() + } + +# Module-level entry point +def run_workflow(**kwargs): + """Entry point for the workflow.""" + required = ['prompt', 'checkpoints', 'seed', 'steps', 'negativePrompt', 'width', 'height', '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()