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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
"""
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