nifty-coder
Voice control
8cbe6eb
Raw History Blame Contribute Delete
12.8 kB
"""
Utility functions for the voice control optimization system.
This module provides common utility functions used throughout the
voice control system.
"""
import hashlib
import time
import asyncio
import logging
from typing import Any, Dict, List, Optional, Callable, TypeVar, Union
from functools import wraps
from datetime import datetime, timedelta
logger = logging.getLogger(__name__)
T = TypeVar('T')
def generate_fingerprint(data: bytes, algorithm: str = "sha256") -> str:
"""
Generate a fingerprint hash for binary data.
Args:
data: Binary data to hash
algorithm: Hash algorithm to use
Returns:
Hexadecimal hash string
"""
if algorithm == "sha256":
return hashlib.sha256(data).hexdigest()
elif algorithm == "md5":
return hashlib.md5(data).hexdigest()
elif algorithm == "sha1":
return hashlib.sha1(data).hexdigest()
else:
raise ValueError(f"Unsupported hash algorithm: {algorithm}")
def generate_session_id() -> str:
"""Generate a unique session ID."""
timestamp = str(int(time.time() * 1000))
random_part = hashlib.md5(str(time.time()).encode()).hexdigest()[:8]
return f"session_{timestamp}_{random_part}"
def calculate_audio_duration(data_size: int, sample_rate: int, channels: int, bit_depth: int) -> float:
"""
Calculate audio duration from raw audio parameters.
Args:
data_size: Size of audio data in bytes
sample_rate: Sample rate in Hz
channels: Number of audio channels
bit_depth: Bit depth (8, 16, 24, 32)
Returns:
Duration in seconds
"""
bytes_per_sample = bit_depth // 8
total_samples = data_size // (bytes_per_sample * channels)
return total_samples / sample_rate
def format_duration(seconds: float) -> str:
"""
Format duration in seconds to human-readable string.
Args:
seconds: Duration in seconds
Returns:
Formatted duration string (e.g., "1m 30s", "2h 15m")
"""
if seconds < 60:
return f"{seconds:.1f}s"
elif seconds < 3600:
minutes = int(seconds // 60)
remaining_seconds = seconds % 60
return f"{minutes}m {remaining_seconds:.0f}s"
else:
hours = int(seconds // 3600)
remaining_minutes = int((seconds % 3600) // 60)
return f"{hours}h {remaining_minutes}m"
def format_bytes(bytes_count: int) -> str:
"""
Format byte count to human-readable string.
Args:
bytes_count: Number of bytes
Returns:
Formatted byte string (e.g., "1.5 KB", "2.3 MB")
"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if bytes_count < 1024.0:
return f"{bytes_count:.1f} {unit}"
bytes_count /= 1024.0
return f"{bytes_count:.1f} PB"
def safe_divide(numerator: float, denominator: float, default: float = 0.0) -> float:
"""
Safely divide two numbers, returning default if denominator is zero.
Args:
numerator: Numerator
denominator: Denominator
default: Default value if denominator is zero
Returns:
Division result or default
"""
return numerator / denominator if denominator != 0 else default
def clamp(value: float, min_value: float, max_value: float) -> float:
"""
Clamp a value between minimum and maximum bounds.
Args:
value: Value to clamp
min_value: Minimum allowed value
max_value: Maximum allowed value
Returns:
Clamped value
"""
return max(min_value, min(value, max_value))
def exponential_backoff(attempt: int, base_delay: float = 1.0, max_delay: float = 60.0, jitter: bool = True) -> float:
"""
Calculate exponential backoff delay.
Args:
attempt: Attempt number (0-based)
base_delay: Base delay in seconds
max_delay: Maximum delay in seconds
jitter: Whether to add random jitter
Returns:
Delay in seconds
"""
import random
delay = min(base_delay * (2 ** attempt), max_delay)
if jitter:
# Add ±25% jitter
jitter_range = delay * 0.25
delay += random.uniform(-jitter_range, jitter_range)
return max(0, delay)
def retry_with_backoff(
max_retries: int = 3,
base_delay: float = 1.0,
max_delay: float = 60.0,
exceptions: tuple = (Exception,)
):
"""
Decorator for retrying functions with exponential backoff.
Args:
max_retries: Maximum number of retry attempts
base_delay: Base delay between retries
max_delay: Maximum delay between retries
exceptions: Tuple of exceptions to catch and retry
Returns:
Decorated function
"""
def decorator(func: Callable[..., T]) -> Callable[..., T]:
@wraps(func)
async def async_wrapper(*args, **kwargs) -> T:
last_exception = None
for attempt in range(max_retries + 1):
try:
if asyncio.iscoroutinefunction(func):
return await func(*args, **kwargs)
else:
return func(*args, **kwargs)
except exceptions as e:
last_exception = e
if attempt == max_retries:
logger.error(f"Function {func.__name__} failed after {max_retries} retries: {e}")
raise e
delay = exponential_backoff(attempt, base_delay, max_delay)
logger.warning(f"Function {func.__name__} failed (attempt {attempt + 1}), retrying in {delay:.2f}s: {e}")
await asyncio.sleep(delay)
# This should never be reached, but just in case
raise last_exception
@wraps(func)
def sync_wrapper(*args, **kwargs) -> T:
last_exception = None
for attempt in range(max_retries + 1):
try:
return func(*args, **kwargs)
except exceptions as e:
last_exception = e
if attempt == max_retries:
logger.error(f"Function {func.__name__} failed after {max_retries} retries: {e}")
raise e
delay = exponential_backoff(attempt, base_delay, max_delay)
logger.warning(f"Function {func.__name__} failed (attempt {attempt + 1}), retrying in {delay:.2f}s: {e}")
time.sleep(delay)
# This should never be reached, but just in case
raise last_exception
# Return appropriate wrapper based on function type
if asyncio.iscoroutinefunction(func):
return async_wrapper
else:
return sync_wrapper
return decorator
class CircuitBreaker:
"""
Circuit breaker implementation for handling failing services.
States:
- CLOSED: Normal operation, requests pass through
- OPEN: Service is failing, requests are rejected immediately
- HALF_OPEN: Testing if service has recovered
"""
def __init__(
self,
failure_threshold: int = 5,
recovery_timeout: float = 60.0,
expected_exception: type = Exception
):
"""
Initialize circuit breaker.
Args:
failure_threshold: Number of failures before opening circuit
recovery_timeout: Time to wait before trying to recover
expected_exception: Exception type that counts as failure
"""
self.failure_threshold = failure_threshold
self.recovery_timeout = recovery_timeout
self.expected_exception = expected_exception
self.failure_count = 0
self.last_failure_time: Optional[datetime] = None
self.state = "CLOSED" # CLOSED, OPEN, HALF_OPEN
def __call__(self, func: Callable[..., T]) -> Callable[..., T]:
"""Use circuit breaker as a decorator."""
@wraps(func)
async def async_wrapper(*args, **kwargs) -> T:
# Check if we should attempt the call
if not self._should_attempt_call():
raise Exception(f"Circuit breaker is OPEN for {func.__name__}")
try:
result = await func(*args, **kwargs) if asyncio.iscoroutinefunction(func) else func(*args, **kwargs)
self._on_success()
return result
except self.expected_exception as e:
self._on_failure()
raise e
@wraps(func)
def sync_wrapper(*args, **kwargs) -> T:
# Check if we should attempt the call
if not self._should_attempt_call():
raise Exception(f"Circuit breaker is OPEN for {func.__name__}")
try:
result = func(*args, **kwargs)
self._on_success()
return result
except self.expected_exception as e:
self._on_failure()
raise e
# Return appropriate wrapper
if asyncio.iscoroutinefunction(func):
return async_wrapper
else:
return sync_wrapper
def _should_attempt_call(self) -> bool:
"""Check if we should attempt the call based on circuit state."""
if self.state == "CLOSED":
return True
elif self.state == "OPEN":
# Check if recovery timeout has passed
if (self.last_failure_time and
datetime.utcnow() - self.last_failure_time >= timedelta(seconds=self.recovery_timeout)):
self.state = "HALF_OPEN"
return True
return False
elif self.state == "HALF_OPEN":
return True
return False
def _on_success(self):
"""Handle successful call."""
self.failure_count = 0
self.state = "CLOSED"
def _on_failure(self):
"""Handle failed call."""
self.failure_count += 1
self.last_failure_time = datetime.utcnow()
if self.failure_count >= self.failure_threshold:
self.state = "OPEN"
elif self.state == "HALF_OPEN":
self.state = "OPEN"
def validate_audio_format(format_str: str) -> bool:
"""
Validate if an audio format string is supported.
Args:
format_str: Audio format string (e.g., "webm", "wav")
Returns:
True if format is supported, False otherwise
"""
supported_formats = {
"webm", "wav", "mp3", "ogg", "flac", "aac", "m4a", "opus"
}
return format_str.lower() in supported_formats
def validate_language_code(language: str) -> bool:
"""
Validate if a language code is in the correct format.
Args:
language: Language code (e.g., "en-US", "fr-FR")
Returns:
True if language code format is valid, False otherwise
"""
import re
# Match pattern like "en-US", "zh-CN", etc.
pattern = r'^[a-z]{2}-[A-Z]{2}$'
return bool(re.match(pattern, language))
def merge_dictionaries(*dicts: Dict[str, Any]) -> Dict[str, Any]:
"""
Merge multiple dictionaries, with later ones taking precedence.
Args:
*dicts: Dictionaries to merge
Returns:
Merged dictionary
"""
result = {}
for d in dicts:
if d:
result.update(d)
return result
def get_nested_value(data: Dict[str, Any], key_path: str, default: Any = None) -> Any:
"""
Get a nested value from a dictionary using dot notation.
Args:
data: Dictionary to search
key_path: Dot-separated key path (e.g., "audio.processing.enabled")
default: Default value if key not found
Returns:
Value at key path or default
"""
keys = key_path.split('.')
current = data
try:
for key in keys:
current = current[key]
return current
except (KeyError, TypeError):
return default
def set_nested_value(data: Dict[str, Any], key_path: str, value: Any) -> None:
"""
Set a nested value in a dictionary using dot notation.
Args:
data: Dictionary to modify
key_path: Dot-separated key path
value: Value to set
"""
keys = key_path.split('.')
current = data
for key in keys[:-1]:
if key not in current:
current[key] = {}
current = current[key]
current[keys[-1]] = value