""" Configuration management for the voice control optimization system. This module handles loading, validation, and management of configuration settings for all voice control components. """ import os import json import logging from typing import Dict, Any, Optional, List from dataclasses import dataclass, field, asdict from pathlib import Path from datetime import datetime, timedelta from .models import ProviderConfig, ProviderType from .exceptions import ConfigurationError, ValidationError logger = logging.getLogger(__name__) @dataclass class VoiceControlConfig: """Main configuration class for the voice control system.""" # Provider configurations providers: Dict[str, ProviderConfig] = field(default_factory=dict) # Rate limiting settings rate_limiting: Dict[str, Any] = field(default_factory=lambda: { "enabled": True, "default_window_size": 60, # seconds "cleanup_interval": 300, # seconds "redis_url": None, # Use in-memory if None }) # Caching settings caching: Dict[str, Any] = field(default_factory=lambda: { "enabled": True, "max_size_mb": 100, "default_ttl": 3600, # seconds "cleanup_interval": 600, # seconds "redis_url": None, # Use in-memory if None }) # Audio processing settings audio_processing: Dict[str, Any] = field(default_factory=lambda: { # Silence detection settings "silence_threshold": 0.01, "min_silence_duration": 0.5, # seconds "min_speech_duration": 0.1, # seconds "silence_window_size_ms": 50, # milliseconds "silence_removal_enabled": True, # Noise reduction settings "noise_reduction_enabled": True, "noise_reduction_strength": 0.5, "noise_reduction_algorithm": "spectral_subtraction", # spectral_subtraction, wiener_filter, adaptive_filter "noise_reduction_adaptive": True, "noise_reduction_preserve_speech": True, # Audio chunking settings "default_chunk_duration": 30.0, # seconds "default_chunk_overlap": 0.0, # seconds "chunk_at_silence_boundaries": True, "min_chunk_duration": 1.0, # seconds "max_chunk_duration": 60.0, # seconds # General audio settings "max_audio_duration": 300.0, # seconds "supported_formats": ["webm", "wav", "mp3", "ogg"], }) # Cost monitoring settings cost_monitoring: Dict[str, Any] = field(default_factory=lambda: { "enabled": True, "alert_thresholds": { "daily": 10.0, # USD "monthly": 100.0 # USD }, "report_interval": 86400, # seconds (daily) }) # WebSocket settings websocket: Dict[str, Any] = field(default_factory=lambda: { "max_connections": 100, "heartbeat_interval": 30, # seconds "message_timeout": 10, # seconds "max_message_size": 1024 * 1024, # 1MB }) # Logging settings logging: Dict[str, Any] = field(default_factory=lambda: { "level": "INFO", "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s", "file": None, # Log to stdout if None "max_file_size": 10 * 1024 * 1024, # 10MB "backup_count": 5, }) # Environment-specific settings environment: str = "development" debug: bool = False def __post_init__(self): """Validate configuration after initialization.""" self._validate_config() def _validate_config(self): """Validate the configuration settings.""" # Validate rate limiting settings if self.rate_limiting["default_window_size"] <= 0: raise ValidationError("rate_limiting.default_window_size", self.rate_limiting["default_window_size"], "Must be positive") # Validate caching settings if self.caching["max_size_mb"] <= 0: raise ValidationError("caching.max_size_mb", self.caching["max_size_mb"], "Must be positive") # Validate audio processing settings if not (0.0 <= self.audio_processing["silence_threshold"] <= 1.0): raise ValidationError("audio_processing.silence_threshold", self.audio_processing["silence_threshold"], "Must be between 0.0 and 1.0") if not (0.0 <= self.audio_processing["noise_reduction_strength"] <= 1.0): raise ValidationError("audio_processing.noise_reduction_strength", self.audio_processing["noise_reduction_strength"], "Must be between 0.0 and 1.0") if self.audio_processing["min_silence_duration"] <= 0: raise ValidationError("audio_processing.min_silence_duration", self.audio_processing["min_silence_duration"], "Must be positive") if self.audio_processing["min_speech_duration"] <= 0: raise ValidationError("audio_processing.min_speech_duration", self.audio_processing["min_speech_duration"], "Must be positive") if self.audio_processing["default_chunk_duration"] <= 0: raise ValidationError("audio_processing.default_chunk_duration", self.audio_processing["default_chunk_duration"], "Must be positive") valid_algorithms = ["spectral_subtraction", "wiener_filter", "adaptive_filter"] if self.audio_processing["noise_reduction_algorithm"] not in valid_algorithms: raise ValidationError("audio_processing.noise_reduction_algorithm", self.audio_processing["noise_reduction_algorithm"], f"Must be one of: {valid_algorithms}") # Validate environment if self.environment not in ["development", "testing", "staging", "production"]: raise ValidationError("environment", self.environment, "Must be one of: development, testing, staging, production") class ConfigManager: """Manages configuration loading, validation, and updates.""" def __init__(self, config_path: Optional[str] = None): """ Initialize the configuration manager. Args: config_path: Path to configuration file (optional) """ self.config_path = config_path or self._get_default_config_path() self.config: Optional[VoiceControlConfig] = None self._config_history: List[Dict[str, Any]] = [] def _get_default_config_path(self) -> str: """Get the default configuration file path.""" # Check environment variable first env_path = os.environ.get("VOICE_CONTROL_CONFIG") if env_path and os.path.exists(env_path): return env_path # Check common locations possible_paths = [ "voice_control_config.json", "config/voice_control.json", "/etc/voice_control/config.json", os.path.expanduser("~/.voice_control/config.json") ] for path in possible_paths: if os.path.exists(path): return path # Return default path (may not exist yet) return "voice_control_config.json" def load_config(self) -> VoiceControlConfig: """ Load configuration from file or environment variables. Returns: VoiceControlConfig instance Raises: ConfigurationError: If configuration loading fails """ try: # Start with default configuration config_dict = {} # Load from file if it exists if os.path.exists(self.config_path): with open(self.config_path, 'r') as f: file_config = json.load(f) config_dict.update(file_config) logger.info(f"Loaded configuration from {self.config_path}") else: logger.info(f"Configuration file {self.config_path} not found, using defaults") # Override with environment variables env_overrides = self._load_from_environment() if env_overrides: config_dict.update(env_overrides) logger.info("Applied environment variable overrides") # Create configuration object self.config = self._create_config_from_dict(config_dict) # Save current config to history self._save_to_history("load", config_dict) return self.config except Exception as e: raise ConfigurationError("config_loading", f"Failed to load configuration: {e}") def _load_from_environment(self) -> Dict[str, Any]: """Load configuration overrides from environment variables.""" env_config = {} # Environment detection if "VOICE_CONTROL_ENV" in os.environ: env_config["environment"] = os.environ["VOICE_CONTROL_ENV"] if "VOICE_CONTROL_DEBUG" in os.environ: env_config["debug"] = os.environ["VOICE_CONTROL_DEBUG"].lower() in ("true", "1", "yes") # Redis URLs if "REDIS_URL" in os.environ: env_config["rate_limiting"] = {"redis_url": os.environ["REDIS_URL"]} env_config["caching"] = {"redis_url": os.environ["REDIS_URL"]} # Provider API keys provider_configs = {} # Google Speech API if "GOOGLE_SPEECH_API_KEY" in os.environ: provider_configs["google_speech"] = { "name": "google_speech", "provider_type": "google_speech", "enabled": True, "priority": 2, "api_credentials": {"api_key": os.environ["GOOGLE_SPEECH_API_KEY"]} } # Azure Speech API if "AZURE_SPEECH_KEY" in os.environ and "AZURE_SPEECH_REGION" in os.environ: provider_configs["azure_speech"] = { "name": "azure_speech", "provider_type": "azure_speech", "enabled": True, "priority": 3, "api_credentials": { "subscription_key": os.environ["AZURE_SPEECH_KEY"], "region": os.environ["AZURE_SPEECH_REGION"] } } # AssemblyAI if "ASSEMBLYAI_API_KEY" in os.environ: provider_configs["assembly_ai"] = { "name": "assembly_ai", "provider_type": "assembly_ai", "enabled": True, "priority": 4, "api_credentials": {"api_key": os.environ["ASSEMBLYAI_API_KEY"]} } # Deepgram (existing) if "DEEPGRAM_API_KEY" in os.environ: provider_configs["deepgram"] = { "name": "deepgram", "provider_type": "deepgram", "enabled": True, "priority": 5, "api_credentials": {"api_key": os.environ["DEEPGRAM_API_KEY"]} } if provider_configs: env_config["providers"] = provider_configs return env_config def _create_config_from_dict(self, config_dict: Dict[str, Any]) -> VoiceControlConfig: """Create VoiceControlConfig from dictionary.""" # Handle provider configurations specially providers = {} if "providers" in config_dict: for name, provider_dict in config_dict["providers"].items(): providers[name] = self._create_provider_config(provider_dict) config_dict["providers"] = providers return VoiceControlConfig(**config_dict) def _create_provider_config(self, provider_dict: Dict[str, Any]) -> ProviderConfig: """Create ProviderConfig from dictionary.""" # Convert provider_type string to enum if "provider_type" in provider_dict and isinstance(provider_dict["provider_type"], str): provider_type_str = provider_dict["provider_type"] # Handle both enum value strings and full enum representations if provider_type_str.startswith("ProviderType."): provider_type_str = provider_type_str.split(".")[-1] provider_dict["provider_type"] = ProviderType[provider_type_str.upper()] # Set defaults for missing fields defaults = { "enabled": True, "priority": 10, "free_tier_limits": {}, "rate_limits": {"requests_per_minute": 60}, "supported_formats": ["webm", "wav", "mp3"], "supported_languages": ["en-US"], "cost_per_minute": 0.0, "api_credentials": {}, "timeout_seconds": 30, "max_retries": 3 } for key, default_value in defaults.items(): if key not in provider_dict: provider_dict[key] = default_value return ProviderConfig(**provider_dict) def save_config(self, config: Optional[VoiceControlConfig] = None) -> None: """ Save configuration to file. Args: config: Configuration to save (uses current if None) Raises: ConfigurationError: If saving fails """ if config is None: config = self.config if config is None: raise ConfigurationError("save_config", "No configuration to save") try: # Convert to dictionary config_dict = self._config_to_dict(config) # Ensure directory exists config_dir = os.path.dirname(self.config_path) if config_dir: os.makedirs(config_dir, exist_ok=True) # Write to file with open(self.config_path, 'w') as f: json.dump(config_dict, f, indent=2, default=str) logger.info(f"Saved configuration to {self.config_path}") # Save to history self._save_to_history("save", config_dict) except Exception as e: raise ConfigurationError("save_config", f"Failed to save configuration: {e}") def _config_to_dict(self, config: VoiceControlConfig) -> Dict[str, Any]: """Convert VoiceControlConfig to dictionary.""" config_dict = asdict(config) # Convert provider configs to dictionaries if "providers" in config_dict: providers_dict = {} for name, provider_config in config_dict["providers"].items(): if isinstance(provider_config, ProviderConfig): provider_dict = asdict(provider_config) # Convert enum to string if "provider_type" in provider_dict: provider_dict["provider_type"] = provider_dict["provider_type"].value providers_dict[name] = provider_dict else: # Already a dictionary providers_dict[name] = provider_config config_dict["providers"] = providers_dict return config_dict def update_config(self, updates: Dict[str, Any]) -> VoiceControlConfig: """ Update configuration with new values. Args: updates: Dictionary of configuration updates Returns: Updated VoiceControlConfig Raises: ConfigurationError: If update fails """ if self.config is None: raise ConfigurationError("update_config", "No configuration loaded") try: # Convert current config to dict config_dict = self._config_to_dict(self.config) # Apply updates self._deep_update(config_dict, updates) # Create new config object new_config = self._create_config_from_dict(config_dict) # Validate new configuration new_config._validate_config() # Update current config self.config = new_config # Save to history self._save_to_history("update", updates) logger.info("Configuration updated successfully") return self.config except Exception as e: raise ConfigurationError("update_config", f"Failed to update configuration: {e}") def _deep_update(self, base_dict: Dict[str, Any], updates: Dict[str, Any]) -> None: """Recursively update nested dictionary.""" for key, value in updates.items(): if key in base_dict and isinstance(base_dict[key], dict) and isinstance(value, dict): self._deep_update(base_dict[key], value) else: base_dict[key] = value def _save_to_history(self, action: str, data: Dict[str, Any]) -> None: """Save configuration change to history.""" history_entry = { "timestamp": datetime.now().isoformat(), "action": action, "data": data, "user": os.environ.get("USER", "system") } self._config_history.append(history_entry) # Keep only last 100 entries if len(self._config_history) > 100: self._config_history = self._config_history[-100:] def get_config_history(self) -> List[Dict[str, Any]]: """Get configuration change history.""" return self._config_history.copy() def backup_config(self, backup_path: Optional[str] = None) -> str: """ Create a backup of the current configuration. Args: backup_path: Path for backup file (auto-generated if None) Returns: Path to backup file """ if backup_path is None: timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") backup_path = f"{self.config_path}.backup_{timestamp}" if self.config is None: raise ConfigurationError("backup_config", "No configuration to backup") try: config_dict = self._config_to_dict(self.config) with open(backup_path, 'w') as f: json.dump(config_dict, f, indent=2, default=str) logger.info(f"Configuration backed up to {backup_path}") return backup_path except Exception as e: raise ConfigurationError("backup_config", f"Failed to backup configuration: {e}") def restore_config(self, backup_path: str) -> VoiceControlConfig: """ Restore configuration from backup. Args: backup_path: Path to backup file Returns: Restored VoiceControlConfig """ try: with open(backup_path, 'r') as f: config_dict = json.load(f) self.config = self._create_config_from_dict(config_dict) # Save to history self._save_to_history("restore", {"backup_path": backup_path}) logger.info(f"Configuration restored from {backup_path}") return self.config except Exception as e: raise ConfigurationError("restore_config", f"Failed to restore configuration: {e}") # Global configuration manager instance _config_manager: Optional[ConfigManager] = None def get_config_manager() -> ConfigManager: """Get the global configuration manager instance.""" global _config_manager if _config_manager is None: _config_manager = ConfigManager() return _config_manager def get_config() -> VoiceControlConfig: """Get the current configuration.""" manager = get_config_manager() if manager.config is None: manager.load_config() return manager.config def reload_config() -> VoiceControlConfig: """Reload configuration from file.""" manager = get_config_manager() return manager.load_config()