File size: 10,082 Bytes
8cbe6eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Core data models for the voice control optimization system.

This module defines all the data structures used throughout the voice control
system, including provider configurations, transcription results, usage statistics,
and monitoring data.
"""

from dataclasses import dataclass, field
from typing import Dict, List, Optional, Any, Union
from datetime import datetime, timezone
from enum import Enum


class ProviderType(Enum):
    """Enumeration of supported STT provider types."""
    WEB_SPEECH_API = "web_speech_api"
    GOOGLE_SPEECH = "google_speech"
    AZURE_SPEECH = "azure_speech"
    ASSEMBLY_AI = "assembly_ai"
    DEEPGRAM = "deepgram"


class QuotaType(Enum):
    """Types of quota limits that can be enforced."""
    REQUESTS_PER_MINUTE = "requests_per_minute"
    REQUESTS_PER_HOUR = "requests_per_hour"
    REQUESTS_PER_DAY = "requests_per_day"
    AUDIO_MINUTES_PER_DAY = "audio_minutes_per_day"
    AUDIO_MINUTES_PER_MONTH = "audio_minutes_per_month"


@dataclass
class ProviderConfig:
    """Configuration for a speech-to-text provider."""
    name: str
    provider_type: ProviderType
    enabled: bool
    priority: int  # Lower number = higher priority
    free_tier_limits: Dict[str, Any]
    rate_limits: Dict[str, int]
    supported_formats: List[str]
    supported_languages: List[str]
    cost_per_minute: float
    api_credentials: Dict[str, str]
    endpoint_url: Optional[str] = None
    timeout_seconds: int = 30
    max_retries: int = 3
    
    def __post_init__(self):
        """Validate configuration after initialization."""
        if self.priority < 0:
            raise ValueError("Priority must be non-negative")
        if self.cost_per_minute < 0:
            raise ValueError("Cost per minute must be non-negative")
        if not self.supported_formats:
            raise ValueError("At least one supported format must be specified")


@dataclass
class WordTimestamp:
    """Timestamp information for a transcribed word."""
    word: str
    start_time: float
    end_time: float
    confidence: float


@dataclass
class TranscriptionResult:
    """Result of a speech-to-text transcription operation."""
    text: str
    confidence: float
    provider: str
    processing_time: float
    audio_duration: float
    language: str
    alternatives: List[str] = field(default_factory=list)
    word_timestamps: Optional[List[WordTimestamp]] = None
    is_final: bool = True
    session_id: Optional[str] = None
    created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
    
    def __post_init__(self):
        """Validate transcription result after initialization."""
        if self.confidence < 0 or self.confidence > 1:
            raise ValueError("Confidence must be between 0 and 1")
        if self.processing_time < 0:
            raise ValueError("Processing time must be non-negative")
        if self.audio_duration < 0:
            raise ValueError("Audio duration must be non-negative")


@dataclass
class UsageStats:
    """Usage statistics for a provider within a time window."""
    provider: str
    requests_count: int
    audio_minutes: float
    estimated_cost: float
    success_rate: float
    average_latency: float
    time_window: str
    window_start: datetime
    window_end: datetime
    
    def __post_init__(self):
        """Validate usage statistics after initialization."""
        if self.requests_count < 0:
            raise ValueError("Request count must be non-negative")
        if self.audio_minutes < 0:
            raise ValueError("Audio minutes must be non-negative")
        if self.estimated_cost < 0:
            raise ValueError("Estimated cost must be non-negative")
        if self.success_rate < 0 or self.success_rate > 1:
            raise ValueError("Success rate must be between 0 and 1")
        if self.average_latency < 0:
            raise ValueError("Average latency must be non-negative")


@dataclass
class ProviderStatus:
    """Current status and health information for a provider."""
    name: str
    available: bool
    current_load: float
    quota_remaining: Dict[str, float]
    last_error: Optional[str]
    response_time_avg: float
    last_health_check: datetime = field(default_factory=datetime.utcnow)
    circuit_breaker_state: str = "CLOSED"  # CLOSED, OPEN, HALF_OPEN
    consecutive_failures: int = 0
    
    def __post_init__(self):
        """Validate provider status after initialization."""
        if self.current_load < 0:
            raise ValueError("Current load must be non-negative")
        if self.response_time_avg < 0:
            raise ValueError("Response time average must be non-negative")
        if self.consecutive_failures < 0:
            raise ValueError("Consecutive failures must be non-negative")


@dataclass
class AudioSegment:
    """Represents a segment of audio data."""
    data: bytes
    start_time: float
    end_time: float
    sample_rate: int
    channels: int
    format: str
    
    @property
    def duration(self) -> float:
        """Calculate the duration of the audio segment."""
        return self.end_time - self.start_time
    
    def __post_init__(self):
        """Validate audio segment after initialization."""
        if self.start_time < 0:
            raise ValueError("Start time must be non-negative")
        if self.end_time <= self.start_time:
            raise ValueError("End time must be greater than start time")
        if self.sample_rate <= 0:
            raise ValueError("Sample rate must be positive")
        if self.channels <= 0:
            raise ValueError("Channels must be positive")


@dataclass
class ProcessedAudio:
    """Audio data that has been processed and optimized for a provider."""
    data: bytes
    format: str
    sample_rate: int
    channels: int
    duration: float
    provider: str
    compression_ratio: float = 1.0
    noise_reduced: bool = False
    silence_removed: bool = False
    
    def __post_init__(self):
        """Validate processed audio after initialization."""
        if self.duration <= 0:
            raise ValueError("Duration must be positive")
        if self.sample_rate <= 0:
            raise ValueError("Sample rate must be positive")
        if self.channels <= 0:
            raise ValueError("Channels must be positive")
        if self.compression_ratio <= 0:
            raise ValueError("Compression ratio must be positive")


@dataclass
class QuotaStatus:
    """Status of quota usage for a provider."""
    provider: str
    quota_type: QuotaType
    current_usage: float
    limit: float
    remaining: float
    reset_time: datetime
    percentage_used: float
    
    @property
    def is_exceeded(self) -> bool:
        """Check if quota is exceeded."""
        return self.current_usage >= self.limit
    
    def is_near_limit(self, threshold: float = 0.8) -> bool:
        """Check if quota is near the limit."""
        return self.percentage_used >= threshold
    
    def __post_init__(self):
        """Calculate derived fields and validate."""
        if self.limit > 0:
            self.percentage_used = min(self.current_usage / self.limit, 1.0)
            self.remaining = max(self.limit - self.current_usage, 0)
        else:
            self.percentage_used = 0.0
            self.remaining = 0.0
        
        if self.current_usage < 0:
            raise ValueError("Current usage must be non-negative")
        if self.limit < 0:
            raise ValueError("Limit must be non-negative")


@dataclass
class CacheStats:
    """Statistics about cache performance."""
    total_requests: int
    cache_hits: int
    cache_misses: int
    hit_rate: float
    total_size_bytes: int
    entry_count: int
    evictions: int
    
    @property
    def miss_rate(self) -> float:
        """Calculate cache miss rate."""
        return 1.0 - self.hit_rate
    
    def __post_init__(self):
        """Calculate hit rate and validate."""
        if self.total_requests > 0:
            self.hit_rate = self.cache_hits / self.total_requests
        else:
            self.hit_rate = 0.0
        
        if self.cache_hits < 0 or self.cache_misses < 0:
            raise ValueError("Cache hits and misses must be non-negative")
        if self.total_requests != self.cache_hits + self.cache_misses:
            raise ValueError("Total requests must equal hits plus misses")


@dataclass
class CostSummary:
    """Summary of costs across providers for a time period."""
    time_period: str
    start_date: datetime
    end_date: datetime
    total_cost: float
    provider_costs: Dict[str, float]
    total_requests: int
    total_audio_minutes: float
    average_cost_per_minute: float
    
    def __post_init__(self):
        """Validate cost summary after initialization."""
        if self.total_cost < 0:
            raise ValueError("Total cost must be non-negative")
        if self.total_requests < 0:
            raise ValueError("Total requests must be non-negative")
        if self.total_audio_minutes < 0:
            raise ValueError("Total audio minutes must be non-negative")
        if self.average_cost_per_minute < 0:
            raise ValueError("Average cost per minute must be non-negative")


@dataclass
class BudgetAlert:
    """Alert when budget thresholds are exceeded."""
    alert_id: str
    provider: str
    alert_type: str  # "threshold_warning", "threshold_exceeded", "quota_exceeded"
    message: str
    current_cost: float
    threshold: float
    time_period: str
    created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
    acknowledged: bool = False
    
    def __post_init__(self):
        """Validate budget alert after initialization."""
        if self.current_cost < 0:
            raise ValueError("Current cost must be non-negative")
        if self.threshold < 0:
            raise ValueError("Threshold must be non-negative")


# Type aliases for common data structures
ProviderMetrics = Dict[str, Union[float, int, str]]
ConfigurationDict = Dict[str, Any]
AudioFingerprint = str
CacheKey = str