|
| 1 | +"""BYOC-specific utilities that depend on pytrickle. |
| 2 | +
|
| 3 | +This module contains utilities that are only needed for the BYOC (Bring Your Own Compute) |
| 4 | +server implementation and require pytrickle as a dependency. |
| 5 | +""" |
| 6 | + |
| 7 | +import json |
| 8 | + |
| 9 | +# Import from core utils to avoid duplication |
| 10 | +import sys |
| 11 | +from pathlib import Path |
| 12 | +from typing import Any, Dict |
| 13 | + |
| 14 | +from pytrickle.api import StreamParamsUpdateRequest |
| 15 | + |
| 16 | +# Add src to path for imports |
| 17 | +src_path = Path(__file__).parent.parent / "src" |
| 18 | +sys.path.insert(0, str(src_path)) |
| 19 | + |
| 20 | +from comfystream.utils import convert_prompt |
| 21 | + |
| 22 | + |
| 23 | +class ComfyStreamParamsUpdateRequest(StreamParamsUpdateRequest): |
| 24 | + """ComfyStream parameter validation.""" |
| 25 | + |
| 26 | + def __init__(self, **data): |
| 27 | + # Handle prompts parameter |
| 28 | + if "prompts" in data: |
| 29 | + prompts = data["prompts"] |
| 30 | + |
| 31 | + # Parse JSON string if needed |
| 32 | + if isinstance(prompts, str) and prompts.strip(): |
| 33 | + try: |
| 34 | + prompts = json.loads(prompts) |
| 35 | + except json.JSONDecodeError: |
| 36 | + data.pop("prompts") |
| 37 | + |
| 38 | + # Handle list - use first valid dict |
| 39 | + elif isinstance(prompts, list): |
| 40 | + prompts = next((p for p in prompts if isinstance(p, dict)), None) |
| 41 | + if not prompts: |
| 42 | + data.pop("prompts") |
| 43 | + |
| 44 | + # Validate prompts |
| 45 | + if "prompts" in data and isinstance(prompts, dict): |
| 46 | + try: |
| 47 | + data["prompts"] = convert_prompt(prompts, return_dict=True) |
| 48 | + except Exception: |
| 49 | + data.pop("prompts") |
| 50 | + |
| 51 | + # Call parent constructor |
| 52 | + super().__init__(**data) |
| 53 | + |
| 54 | + @classmethod |
| 55 | + def model_validate(cls, obj): |
| 56 | + return cls(**obj) |
| 57 | + |
| 58 | + def model_dump(self): |
| 59 | + return super().model_dump() |
| 60 | + |
| 61 | + |
| 62 | +def normalize_stream_params(params: Any) -> Dict[str, Any]: |
| 63 | + """Normalize stream parameters from various formats to a dict. |
| 64 | +
|
| 65 | + Args: |
| 66 | + params: Parameters in dict, list, or other format |
| 67 | +
|
| 68 | + Returns: |
| 69 | + Dict containing normalized parameters, empty dict if invalid |
| 70 | + """ |
| 71 | + if params is None: |
| 72 | + return {} |
| 73 | + if isinstance(params, dict): |
| 74 | + return dict(params) |
| 75 | + if isinstance(params, list): |
| 76 | + for candidate in params: |
| 77 | + if isinstance(candidate, dict): |
| 78 | + return dict(candidate) |
| 79 | + return {} |
| 80 | + return {} |
0 commit comments