""" Abstract base classes and interfaces for the voice control optimization system. This module defines the contracts that all components must implement, ensuring consistent behavior and enabling easy testing and extensibility. """ from abc import ABC, abstractmethod from typing import Dict, List, Optional, Any, AsyncIterator from .models import ( ProviderConfig, TranscriptionResult, UsageStats, ProviderStatus, ProcessedAudio, CacheStats, CostSummary, BudgetAlert, QuotaStatus, AudioSegment ) class STTProvider(ABC): """ Abstract base class for speech-to-text providers. All STT providers must implement this interface to be compatible with the provider manager system. """ def __init__(self, config: ProviderConfig): """Initialize the provider with configuration.""" self.config = config self.name = config.name self.provider_type = config.provider_type @abstractmethod async def transcribe_audio( self, audio_data: bytes, format: str, language: str = "en-US", **kwargs ) -> TranscriptionResult: """ Transcribe audio data to text. Args: audio_data: Raw audio bytes format: Audio format (e.g., "webm", "wav", "mp3") language: Language code for transcription **kwargs: Provider-specific options Returns: TranscriptionResult with transcribed text and metadata Raises: ProviderError: When transcription fails QuotaExceededError: When provider quota is exceeded UnsupportedFormatError: When audio format is not supported """ pass @abstractmethod async def transcribe_streaming( self, audio_stream: AsyncIterator[bytes], format: str, language: str = "en-US", **kwargs ) -> AsyncIterator[TranscriptionResult]: """ Transcribe streaming audio data. Args: audio_stream: Async iterator of audio chunks format: Audio format language: Language code for transcription **kwargs: Provider-specific options Yields: TranscriptionResult for each processed chunk """ pass @abstractmethod async def check_health(self) -> bool: """ Check if the provider is healthy and available. Returns: True if provider is healthy, False otherwise """ pass @abstractmethod async def get_quota_status(self) -> Dict[str, QuotaStatus]: """ Get current quota usage status. Returns: Dictionary mapping quota types to their status """ pass @abstractmethod def supports_format(self, format: str) -> bool: """ Check if the provider supports a given audio format. Args: format: Audio format to check Returns: True if format is supported, False otherwise """ pass @abstractmethod def supports_language(self, language: str) -> bool: """ Check if the provider supports a given language. Args: language: Language code to check Returns: True if language is supported, False otherwise """ pass @abstractmethod async def estimate_cost(self, audio_duration: float) -> float: """ Estimate the cost for transcribing audio of given duration. Args: audio_duration: Duration in seconds Returns: Estimated cost in USD """ pass class ProviderManagerInterface(ABC): """Interface for managing multiple STT providers.""" @abstractmethod async def transcribe_audio( self, audio_data: bytes, format: str, language: str = "en-US", preferred_provider: Optional[str] = None ) -> TranscriptionResult: """ Transcribe audio using the best available provider. Args: audio_data: Raw audio bytes format: Audio format language: Language code preferred_provider: Preferred provider name (optional) Returns: TranscriptionResult from the selected provider """ pass @abstractmethod async def transcribe_streaming( self, audio_stream: AsyncIterator[bytes], format: str, language: str = "en-US", preferred_provider: Optional[str] = None ) -> AsyncIterator[TranscriptionResult]: """ Transcribe streaming audio using the best available provider. Args: audio_stream: Async iterator of audio chunks format: Audio format language: Language code preferred_provider: Preferred provider name (optional) Yields: TranscriptionResult for each processed chunk """ pass @abstractmethod async def get_provider_status(self) -> Dict[str, ProviderStatus]: """ Get status of all registered providers. Returns: Dictionary mapping provider names to their status """ pass @abstractmethod async def register_provider(self, provider: STTProvider) -> None: """ Register a new STT provider. Args: provider: STTProvider instance to register """ pass @abstractmethod async def unregister_provider(self, provider_name: str) -> None: """ Unregister an STT provider. Args: provider_name: Name of provider to unregister """ pass @abstractmethod async def update_provider_config( self, provider_name: str, config: ProviderConfig ) -> bool: """ Update configuration for a provider. Args: provider_name: Name of provider to update config: New configuration Returns: True if update was successful, False otherwise """ pass @abstractmethod async def get_cache_stats(self) -> Optional[Dict[str, Any]]: """ Get cache performance statistics if cache manager is available. Returns: Cache statistics dictionary or None if no cache manager """ pass @abstractmethod async def get_system_stats(self) -> Dict[str, Any]: """ Get comprehensive system statistics including providers and cache. Returns: Dictionary with provider metrics, cache stats, and system overview """ pass class RateLimiterInterface(ABC): """Interface for rate limiting and quota management.""" @abstractmethod async def check_quota( self, provider: str, audio_duration: float ) -> QuotaStatus: """ Check if a request would exceed quota limits. Args: provider: Provider name audio_duration: Duration of audio in seconds Returns: QuotaStatus indicating current usage and limits """ pass @abstractmethod async def consume_quota( self, provider: str, audio_duration: float, request_count: int = 1 ) -> bool: """ Consume quota for a request. Args: provider: Provider name audio_duration: Duration of audio in seconds request_count: Number of requests (default 1) Returns: True if quota was consumed successfully, False if exceeded """ pass @abstractmethod async def get_usage_stats( self, provider: str, time_window: str ) -> UsageStats: """ Get usage statistics for a provider and time window. Args: provider: Provider name time_window: Time window ("minute", "hour", "day", "month") Returns: UsageStats for the specified period """ pass @abstractmethod async def reset_quota(self, provider: str, quota_type: str) -> None: """ Reset quota counters for a provider. Args: provider: Provider name quota_type: Type of quota to reset """ pass class AudioProcessorInterface(ABC): """Interface for audio processing and optimization.""" @abstractmethod async def optimize_for_provider( self, audio_data: bytes, provider: str, target_format: Optional[str] = None ) -> ProcessedAudio: """ Optimize audio for a specific provider. Args: audio_data: Raw audio bytes provider: Target provider name target_format: Desired output format (optional) Returns: ProcessedAudio optimized for the provider """ pass @abstractmethod async def detect_silence( self, audio_data: bytes, threshold: float = 0.01 ) -> List[AudioSegment]: """ Detect silence in audio and return non-silent segments. Args: audio_data: Raw audio bytes threshold: Silence detection threshold Returns: List of AudioSegment objects for non-silent parts """ pass @abstractmethod async def apply_noise_reduction( self, audio_data: bytes, strength: float = 0.5 ) -> bytes: """ Apply noise reduction to audio data. Args: audio_data: Raw audio bytes strength: Noise reduction strength (0.0 to 1.0) Returns: Processed audio bytes with reduced noise """ pass @abstractmethod async def convert_format( self, audio_data: bytes, source_format: str, target_format: str, **kwargs ) -> bytes: """ Convert audio from one format to another. Args: audio_data: Raw audio bytes source_format: Current audio format target_format: Desired audio format **kwargs: Format-specific options Returns: Converted audio bytes """ pass @abstractmethod async def chunk_audio( self, audio_data: bytes, chunk_duration: float, overlap: float = 0.0 ) -> List[AudioSegment]: """ Split audio into chunks of specified duration. Args: audio_data: Raw audio bytes chunk_duration: Duration of each chunk in seconds overlap: Overlap between chunks in seconds Returns: List of AudioSegment objects """ pass class CacheManagerInterface(ABC): """Interface for caching transcription results.""" @abstractmethod async def get_cached_transcription( self, audio_fingerprint: str ) -> Optional[TranscriptionResult]: """ Retrieve cached transcription result. Args: audio_fingerprint: Unique fingerprint of audio data Returns: Cached TranscriptionResult or None if not found """ pass @abstractmethod async def cache_transcription( self, audio_fingerprint: str, result: TranscriptionResult, ttl: int = 3600 ) -> bool: """ Cache a transcription result. Args: audio_fingerprint: Unique fingerprint of audio data result: TranscriptionResult to cache ttl: Time to live in seconds Returns: True if caching was successful, False otherwise """ pass @abstractmethod async def generate_audio_fingerprint(self, audio_data: bytes) -> str: """ Generate a unique fingerprint for audio data. Args: audio_data: Raw audio bytes Returns: Unique fingerprint string """ pass @abstractmethod async def get_cache_stats(self) -> CacheStats: """ Get cache performance statistics. Returns: CacheStats with hit rates and usage information """ pass @abstractmethod async def clear_cache(self) -> None: """Clear all cached entries.""" pass @abstractmethod async def evict_expired(self) -> int: """ Remove expired cache entries. Returns: Number of entries evicted """ pass async def get_detailed_cache_stats(self) -> Dict[str, Any]: """ Get detailed cache performance statistics for optimization analysis. Returns: Dictionary with comprehensive cache metrics """ # Default implementation - can be overridden by concrete classes basic_stats = await self.get_cache_stats() return { "basic_stats": { "total_requests": basic_stats.total_requests, "cache_hits": basic_stats.cache_hits, "cache_misses": basic_stats.cache_misses, "hit_rate": basic_stats.hit_rate, "evictions": basic_stats.evictions } } async def warm_cache( self, audio_fingerprints: List[str], transcription_callback: Optional[Any] = None ) -> Dict[str, bool]: """ Warm the cache by preloading frequently accessed transcriptions. Args: audio_fingerprints: List of audio fingerprints to warm transcription_callback: Optional callback to generate transcriptions Returns: Dictionary mapping fingerprints to success status """ # Default implementation - can be overridden by concrete classes return {fp: False for fp in audio_fingerprints} async def optimize_cache_performance(self) -> Dict[str, Any]: """ Perform cache performance optimization operations. Returns: Dictionary with optimization results """ # Default implementation - can be overridden by concrete classes return {"optimizations_applied": []} async def get_cached_transcription_batch( self, audio_fingerprints: List[str] ) -> Dict[str, Optional[TranscriptionResult]]: """ Retrieve multiple cached transcription results in a single operation. Args: audio_fingerprints: List of unique fingerprints of audio data Returns: Dictionary mapping fingerprints to cached results (None if not found) """ # Default implementation - can be overridden by concrete classes results = {} for fingerprint in audio_fingerprints: results[fingerprint] = await self.get_cached_transcription(fingerprint) return results class CostMonitorInterface(ABC): """Interface for cost monitoring and alerting.""" @abstractmethod async def track_usage( self, provider: str, audio_duration: float, estimated_cost: float, success: bool = True ) -> None: """ Track usage and cost for a provider. Args: provider: Provider name audio_duration: Duration of audio processed estimated_cost: Estimated cost of the operation success: Whether the operation was successful """ pass @abstractmethod async def get_cost_summary( self, time_period: str, provider: Optional[str] = None ) -> CostSummary: """ Get cost summary for a time period. Args: time_period: Time period ("day", "week", "month") provider: Specific provider (optional, all if None) Returns: CostSummary for the specified period """ pass @abstractmethod async def check_budget_alerts(self) -> List[BudgetAlert]: """ Check for budget threshold violations. Returns: List of active budget alerts """ pass @abstractmethod async def set_budget_threshold( self, provider: str, threshold: float, time_period: str ) -> None: """ Set a budget threshold for alerts. Args: provider: Provider name threshold: Budget threshold in USD time_period: Time period for the threshold """ pass @abstractmethod async def acknowledge_alert(self, alert_id: str) -> None: """ Acknowledge a budget alert. Args: alert_id: ID of the alert to acknowledge """ pass