nifty-coder
Voice control
8cbe6eb
Raw History Blame Contribute Delete
10.1 kB
"""
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