"""Environment settings and the model registry loaded from a JSON file.""" import json from pathlib import Path from pydantic import BaseModel, ValidationError from pydantic_settings import BaseSettings, SettingsConfigDict from .errors import ConfigError REPO_ROOT = Path(__file__).resolve().parent.parent class ModelEntry(BaseModel): """A registry record: an API model id maps to one workflow file.""" workflow: Path owned_by: str = "comfy-adapter" class Settings(BaseSettings): model_config = SettingsConfigDict(env_file=".env", extra="ignore") comfy_base_url: str = "http://192.168.0.3:8188" adapter_api_key: str = "" execution_timeout: float = 300.0 poll_interval: float = 1.5 # JSON file mapping an API model id to its workflow. Required; no defaults in code. models_file: Path = REPO_ROOT / "models.json" # Validate collected graphs on the ComfyUI server (POST /prompt?front=false) at startup. validate_templates_on_server: bool = True def load_registry(self) -> dict[str, ModelEntry]: """Load the model registry, preserving declaration order (first = preferred). Fail-fast: a missing or malformed file raises ConfigError and blocks startup. """ try: raw = json.loads(self.models_file.read_text(encoding="utf-8")) except FileNotFoundError as e: raise ConfigError(f"model registry file not found: {self.models_file}") from e except json.JSONDecodeError as e: raise ConfigError(f"model registry is not valid JSON ({self.models_file}): {e}") from e if not isinstance(raw, dict) or not raw: raise ConfigError(f"model registry must be a non-empty object of model entries: {self.models_file}") registry: dict[str, ModelEntry] = {} for model_id, spec in raw.items(): try: registry[model_id] = ModelEntry.model_validate(spec) except ValidationError as e: raise ConfigError(f"model '{model_id}' has an invalid entry: {e}") from e return registry def get_settings() -> Settings: return Settings()