"""Versioned runtime configuration with a single secret environment value.""" from __future__ import annotations import json import os from dataclasses import dataclass, fields from functools import lru_cache from pathlib import Path from typing import Any PROJECT_ROOT = Path(__file__).resolve().parent.parent RUNTIME_CONFIG_PATH = PROJECT_ROOT / "config" / "runtime.json" def parse_bool(value: str | bool | None, default: bool = False) -> bool: """Convert common boolean representations without raising.""" if isinstance(value, bool): return value if value is None: return default normalised = value.strip().lower() if normalised in {"1", "true", "yes", "on"}: return True if normalised in {"0", "false", "no", "off"}: return False return default @dataclass(frozen=True, slots=True) class Settings: """Typed NovaGuide settings loaded from ``config/runtime.json``.""" app_name: str = "NovaGuide" app_env: str = "production" debug: bool = False whisper_model_size: str = "tiny" whisper_device: str = "cpu" whisper_compute_type: str = "int8" clip_model_name: str = "openai/clip-vit-base-patch32" ocr_enabled: bool = True ocr_languages: str = "en" image_confidence_threshold: float = 0.25 max_image_size_mb: float = 10.0 qwen_enabled: bool = False qwen_model_id: str = "Qwen/Qwen2.5-VL-3B-Instruct" qwen_api_url: str = "https://router.huggingface.co/v1/chat/completions" qwen_timeout_seconds: int = 30 qwen_max_output_tokens: int = 200 qwen_max_calls_per_day: int = 10 qwen_max_image_width: int = 1024 qwen_baseline_confidence_threshold: float = 0.35 database_url: str = "" hf_token: str = "" log_to_neon: bool = True fallback_to_csv_logs: bool = False analytics_data_source: str = "manual_user" configuration_version: str = "novaguide-minilm-faiss-v4-eval-clean" local_interactions_log: str = "logs/local_interactions.csv" local_feedback_log: str = "logs/local_feedback_events.csv" local_api_call_log: str = "logs/local_api_call_logs.csv" intent_model_path: str = "artifacts/intent_classifier" faiss_index_path: str = "artifacts/faiss.index" faiss_metadata_path: str = "artifacts/faiss_metadata.json" airport_kb_json: str = "data/airport_kb.json" airport_kb_csv: str = "data/airport_kb.csv" faiss_documents_jsonl: str = "data/faiss_documents.jsonl" sample_queries_csv: str = "data/sample_queries.csv" intent_confidence_threshold: float = 0.55 retrieval_confidence_threshold: float = 0.55 final_confidence_threshold: float = 0.55 max_audio_seconds: int = 20 @classmethod def from_config(cls, path: str | Path | None = None) -> "Settings": """Load versioned non-secret settings and inject only approved secrets.""" config_path = Path(path) if path else RUNTIME_CONFIG_PATH try: payload: dict[str, Any] = json.loads(config_path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError, TypeError) as exc: raise RuntimeError(f"Invalid NovaGuide runtime configuration: {config_path}") from exc allowed = {item.name for item in fields(cls)} - {"database_url", "hf_token"} unknown = sorted(set(payload) - allowed) if unknown: raise ValueError(f"Unknown runtime configuration keys: {', '.join(unknown)}") # DATABASE_URL is deliberately the only deployment secret. Qwen remains # disabled unless a future secure provider-authentication design is added. payload["database_url"] = os.getenv("DATABASE_URL", "") payload["hf_token"] = "" return cls(**payload) @classmethod def from_env(cls) -> "Settings": """Compatibility alias retained for existing callers and tests.""" return cls.from_config() @property def neon_configured(self) -> bool: return bool(self.log_to_neon and self.database_url) @property def qwen_fallback_enabled(self) -> bool: return bool(self.qwen_enabled and self.hf_token and self.qwen_model_id) @lru_cache(maxsize=1) def get_settings() -> Settings: """Return the immutable process-wide configuration.""" return Settings.from_config()