Spaces:
Runtime error
Runtime error
Download voice_control/providers/azure_speech_provider.py from nifty-coder/stemsplit-backend: direct link, hf CLI and curl.
- Browser
- Download file 36.6 kB
-
https://huggingface.co/spaces/nifty-coder/stemsplit-backend/resolve/main/voice_control/providers/azure_speech_provider.py
- Command line
-
hf download hf://spaces/nifty-coder/stemsplit-backend/voice_control/providers/azure_speech_provider.py
-
curl -L -o azure_speech_provider.py https://huggingface.co/spaces/nifty-coder/stemsplit-backend/resolve/main/voice_control/providers/azure_speech_provider.py
36.6 kB
| """ | |
| Azure Speech Services provider implementation. | |
| This module implements a provider that integrates with Microsoft Azure Speech Services | |
| for high-quality speech recognition. It supports both streaming and batch transcription | |
| with comprehensive quota management for the free tier (5 hours/month). | |
| """ | |
| import asyncio | |
| import json | |
| import logging | |
| import base64 | |
| from typing import Dict, List, Optional, AsyncIterator, Any | |
| from datetime import datetime, timezone, timedelta | |
| import hashlib | |
| import io | |
| from ..interfaces import STTProvider | |
| from ..models import ( | |
| ProviderConfig, | |
| TranscriptionResult, | |
| QuotaStatus, | |
| QuotaType, | |
| WordTimestamp, | |
| ProviderType | |
| ) | |
| from ..exceptions import ( | |
| ProviderError, | |
| ProviderUnavailableError, | |
| ProviderAuthenticationError, | |
| ProviderTimeoutError, | |
| UnsupportedFormatError, | |
| UnsupportedLanguageError, | |
| QuotaExceededError, | |
| RateLimitExceededError, | |
| TranscriptionError | |
| ) | |
| logger = logging.getLogger(__name__) | |
| try: | |
| import azure.cognitiveservices.speech as speechsdk | |
| from azure.cognitiveservices.speech import ( | |
| SpeechConfig, | |
| AudioConfig, | |
| SpeechRecognizer, | |
| ResultReason, | |
| CancellationReason | |
| ) | |
| AZURE_SPEECH_AVAILABLE = True | |
| except ImportError: | |
| logger.warning("Azure Speech SDK not available. Install with: pip install azure-cognitiveservices-speech") | |
| AZURE_SPEECH_AVAILABLE = False | |
| # Create mock classes for type hints | |
| speechsdk = None | |
| SpeechConfig = None | |
| AudioConfig = None | |
| SpeechRecognizer = None | |
| ResultReason = None | |
| CancellationReason = None | |
| class AzureSpeechProvider(STTProvider): | |
| """ | |
| Azure Speech Services provider implementation. | |
| This provider integrates with Microsoft Azure Speech Services to provide | |
| high-quality speech recognition with support for neural voice models, | |
| multiple languages, streaming transcription, and advanced features. | |
| Key features: | |
| - Streaming and batch transcription | |
| - Neural voice model support | |
| - Free tier quota management (5 hours/month) | |
| - Multiple audio format support | |
| - Word-level timestamps | |
| - Confidence scoring | |
| - Language detection | |
| - Speaker diarization | |
| - Custom speech models | |
| """ | |
| # Supported audio formats for Azure Speech Services | |
| SUPPORTED_FORMATS = [ | |
| "wav", "flac", "mp3", "ogg", "webm", "amr", "alaw", "mulaw" | |
| ] | |
| # Supported languages (subset of Azure's extensive language support) | |
| SUPPORTED_LANGUAGES = [ | |
| "en-US", "en-GB", "en-AU", "en-CA", "en-IN", "en-NZ", "en-ZA", "en-IE", | |
| "es-ES", "es-MX", "es-AR", "es-CO", "es-CL", "es-PE", "es-VE", "es-US", | |
| "fr-FR", "fr-CA", "fr-BE", "fr-CH", | |
| "de-DE", "de-AT", "de-CH", | |
| "it-IT", "it-CH", | |
| "pt-BR", "pt-PT", | |
| "ru-RU", | |
| "ja-JP", | |
| "ko-KR", | |
| "zh-CN", "zh-TW", "zh-HK", | |
| "ar-SA", "ar-EG", "ar-AE", "ar-BH", "ar-DZ", "ar-IQ", "ar-JO", "ar-KW", "ar-LB", "ar-LY", "ar-MA", "ar-OM", "ar-QA", "ar-SY", "ar-TN", "ar-YE", | |
| "hi-IN", | |
| "th-TH", | |
| "tr-TR", | |
| "pl-PL", | |
| "nl-NL", "nl-BE", | |
| "sv-SE", | |
| "da-DK", | |
| "no-NO", | |
| "fi-FI", | |
| "cs-CZ", | |
| "hu-HU", | |
| "ro-RO", | |
| "sk-SK", | |
| "sl-SI", | |
| "bg-BG", | |
| "hr-HR", | |
| "et-EE", | |
| "lv-LV", | |
| "lt-LT", | |
| "mt-MT", | |
| "uk-UA", | |
| "vi-VN", | |
| "id-ID", | |
| "ms-MY", | |
| "ta-IN", | |
| "te-IN", | |
| "bn-IN", | |
| "gu-IN", | |
| "kn-IN", | |
| "ml-IN", | |
| "mr-IN", | |
| "pa-IN", | |
| "ur-IN" | |
| ] | |
| # Free tier limits (as of 2024) | |
| FREE_TIER_LIMITS = { | |
| "audio_hours_per_month": 5.0, # 5 hours per month | |
| "requests_per_minute": 20, | |
| "requests_per_day": 5000 | |
| } | |
| # Pricing (per hour, in USD) | |
| PRICING = { | |
| "standard": 1.0, # $1.00 per hour for standard models | |
| "neural": 2.5 # $2.50 per hour for neural models | |
| } | |
| def __init__(self, config: ProviderConfig): | |
| """ | |
| Initialize the Azure Speech Services provider. | |
| Args: | |
| config: Provider configuration | |
| Raises: | |
| ImportError: If Azure Speech SDK is not available | |
| ProviderAuthenticationError: If credentials are invalid | |
| """ | |
| super().__init__(config) | |
| if not AZURE_SPEECH_AVAILABLE: | |
| raise ImportError( | |
| "Azure Speech SDK not available. " | |
| "Install with: pip install azure-cognitiveservices-speech" | |
| ) | |
| # Validate configuration | |
| if config.provider_type != ProviderType.AZURE_SPEECH: | |
| raise ValueError(f"Invalid provider type: {config.provider_type}") | |
| # Initialize speech config | |
| self._speech_config = None | |
| self._recognizer = None | |
| # Usage tracking for quota management | |
| self._usage_stats = { | |
| "requests_today": 0, | |
| "requests_this_minute": 0, | |
| "audio_hours_this_month": 0.0, | |
| "last_minute_reset": datetime.now(timezone.utc).replace(second=0, microsecond=0), | |
| "last_daily_reset": datetime.now(timezone.utc).date(), | |
| "last_monthly_reset": datetime.now(timezone.utc).replace(day=1, hour=0, minute=0, second=0, microsecond=0) | |
| } | |
| # Streaming session management | |
| self._active_streams = {} | |
| # Initialize the client (will be done lazily when needed) | |
| self._client_initialized = False | |
| logger.info(f"Initialized AzureSpeechProvider: {self.name}") | |
| async def _initialize_client(self) -> None: | |
| """Initialize the Azure Speech client with credentials.""" | |
| try: | |
| # Get credentials from config | |
| credentials_info = self.config.api_credentials | |
| if "subscription_key" in credentials_info and "region" in credentials_info: | |
| # Use subscription key and region | |
| subscription_key = credentials_info["subscription_key"] | |
| region = credentials_info["region"] | |
| self._speech_config = SpeechConfig( | |
| subscription=subscription_key, | |
| region=region | |
| ) | |
| elif "endpoint" in credentials_info and "subscription_key" in credentials_info: | |
| # Use custom endpoint | |
| endpoint = credentials_info["endpoint"] | |
| subscription_key = credentials_info["subscription_key"] | |
| self._speech_config = SpeechConfig( | |
| endpoint=endpoint, | |
| subscription=subscription_key | |
| ) | |
| else: | |
| raise ValueError( | |
| "Azure Speech credentials must include either " | |
| "(subscription_key + region) or (endpoint + subscription_key)" | |
| ) | |
| # Configure speech settings | |
| self._speech_config.speech_recognition_language = "en-US" # Default language | |
| self._speech_config.output_format = speechsdk.OutputFormat.Detailed | |
| # Enable detailed results for word timestamps | |
| self._speech_config.request_word_level_timestamps() | |
| # Configure neural voice models if available | |
| if credentials_info.get("use_neural_models", True): | |
| # Neural models provide better accuracy but cost more | |
| pass # Neural models are enabled by default in newer SDK versions | |
| self._client_initialized = True | |
| logger.info("Azure Speech client initialized successfully") | |
| except Exception as e: | |
| logger.error(f"Failed to initialize Azure Speech client: {e}") | |
| raise ProviderAuthenticationError( | |
| self.name, | |
| f"Failed to initialize client: {str(e)}" | |
| ) | |
| async def transcribe_audio( | |
| self, | |
| audio_data: bytes, | |
| format: str, | |
| language: str = "en-US", | |
| **kwargs | |
| ) -> TranscriptionResult: | |
| """ | |
| Transcribe audio data using Azure Speech Services. | |
| Args: | |
| audio_data: Raw audio bytes | |
| format: Audio format (wav, flac, mp3, etc.) | |
| language: Language code for transcription | |
| **kwargs: Additional options (model, enable_word_timestamps, etc.) | |
| Returns: | |
| TranscriptionResult with transcribed text and metadata | |
| Raises: | |
| ProviderUnavailableError: If Azure Speech API is unavailable | |
| UnsupportedFormatError: If audio format is not supported | |
| UnsupportedLanguageError: If language is not supported | |
| QuotaExceededError: If quota limits are exceeded | |
| TranscriptionError: If transcription fails | |
| """ | |
| start_time = datetime.now(timezone.utc) | |
| # Ensure client is initialized | |
| if not self._client_initialized: | |
| await self._initialize_client() | |
| # Validate format and language | |
| if not self.supports_format(format): | |
| raise UnsupportedFormatError(self.name, format, self.SUPPORTED_FORMATS) | |
| if not self.supports_language(language): | |
| raise UnsupportedLanguageError(self.name, language, self.SUPPORTED_LANGUAGES) | |
| # Estimate audio duration and check quota | |
| audio_duration = kwargs.get('audio_duration', self._estimate_audio_duration(audio_data, format)) | |
| await self._check_quota(audio_duration) | |
| try: | |
| # Configure speech recognition for this request | |
| speech_config = self._create_speech_config(language, **kwargs) | |
| # Create audio config from bytes | |
| audio_config = self._create_audio_config_from_bytes(audio_data, format) | |
| # Create recognizer | |
| recognizer = SpeechRecognizer( | |
| speech_config=speech_config, | |
| audio_config=audio_config | |
| ) | |
| logger.debug(f"Starting Azure Speech transcription for {audio_duration:.2f}s audio") | |
| # Perform recognition | |
| result = await asyncio.get_event_loop().run_in_executor( | |
| None, | |
| lambda: recognizer.recognize_once() | |
| ) | |
| # Process results | |
| transcription_result = self._process_recognition_result(result, start_time, audio_duration, language) | |
| # Update usage statistics | |
| await self._update_usage_stats(audio_duration, transcription_result.processing_time) | |
| logger.info( | |
| f"Azure Speech transcription completed: {len(transcription_result.text)} chars, " | |
| f"confidence: {transcription_result.confidence:.2f}, time: {transcription_result.processing_time:.2f}s" | |
| ) | |
| return transcription_result | |
| except Exception as e: | |
| await self._handle_azure_error(e) | |
| async def transcribe_streaming( | |
| self, | |
| audio_stream: AsyncIterator[bytes], | |
| format: str, | |
| language: str = "en-US", | |
| **kwargs | |
| ) -> AsyncIterator[TranscriptionResult]: | |
| """ | |
| Transcribe streaming audio data using Azure Speech Services. | |
| Args: | |
| audio_stream: Async iterator of audio chunks | |
| format: Audio format | |
| language: Language code for transcription | |
| **kwargs: Additional options | |
| Yields: | |
| TranscriptionResult for each processed chunk | |
| """ | |
| # Ensure client is initialized | |
| if not self._client_initialized: | |
| await self._initialize_client() | |
| # Validate format and language | |
| if not self.supports_format(format): | |
| raise UnsupportedFormatError(self.name, format, self.SUPPORTED_FORMATS) | |
| if not self.supports_language(language): | |
| raise UnsupportedLanguageError(self.name, language, self.SUPPORTED_LANGUAGES) | |
| session_id = kwargs.get('session_id', f"azure_stream_{int(datetime.now().timestamp())}") | |
| try: | |
| # Initialize streaming session | |
| self._active_streams[session_id] = { | |
| "start_time": datetime.now(timezone.utc), | |
| "language": language, | |
| "format": format, | |
| "chunk_count": 0, | |
| "total_duration": 0.0 | |
| } | |
| logger.info(f"Started Azure Speech streaming session: {session_id}") | |
| # Configure speech recognition for streaming | |
| speech_config = self._create_speech_config(language, **kwargs) | |
| # Create push audio input stream | |
| push_stream = speechsdk.audio.PushAudioInputStream() | |
| audio_config = speechsdk.audio.AudioConfig(stream=push_stream) | |
| # Create recognizer | |
| recognizer = SpeechRecognizer( | |
| speech_config=speech_config, | |
| audio_config=audio_config | |
| ) | |
| # Set up event handlers for streaming results | |
| results_queue = asyncio.Queue() | |
| def recognized_handler(evt): | |
| """Handle recognized speech events.""" | |
| if evt.result.reason == ResultReason.RecognizedSpeech: | |
| asyncio.create_task(results_queue.put(evt.result)) | |
| def recognizing_handler(evt): | |
| """Handle interim recognition results.""" | |
| if evt.result.reason == ResultReason.RecognizingSpeech: | |
| asyncio.create_task(results_queue.put(evt.result)) | |
| recognizer.recognized.connect(recognized_handler) | |
| recognizer.recognizing.connect(recognizing_handler) | |
| # Start continuous recognition | |
| recognizer.start_continuous_recognition() | |
| # Process audio chunks | |
| async for audio_chunk in audio_stream: | |
| try: | |
| # Estimate chunk duration | |
| chunk_duration = self._estimate_audio_duration(audio_chunk, format) | |
| # Check quota for this chunk | |
| await self._check_quota(chunk_duration) | |
| # Push audio data to stream | |
| push_stream.write(audio_chunk) | |
| # Update session stats | |
| session = self._active_streams[session_id] | |
| session["chunk_count"] += 1 | |
| session["total_duration"] += chunk_duration | |
| # Check for results (non-blocking) | |
| try: | |
| while True: | |
| result = results_queue.get_nowait() | |
| transcription_result = self._process_streaming_result( | |
| result, session_id, language | |
| ) | |
| if transcription_result: | |
| yield transcription_result | |
| except asyncio.QueueEmpty: | |
| pass | |
| except Exception as e: | |
| logger.error(f"Error processing streaming chunk: {e}") | |
| continue | |
| # Close the stream and stop recognition | |
| push_stream.close() | |
| recognizer.stop_continuous_recognition() | |
| # Process any remaining results | |
| await asyncio.sleep(0.5) # Allow time for final results | |
| try: | |
| while True: | |
| result = results_queue.get_nowait() | |
| transcription_result = self._process_streaming_result( | |
| result, session_id, language | |
| ) | |
| if transcription_result: | |
| yield transcription_result | |
| except asyncio.QueueEmpty: | |
| pass | |
| except Exception as e: | |
| await self._handle_azure_error(e) | |
| finally: | |
| # Clean up session | |
| if session_id in self._active_streams: | |
| session = self._active_streams.pop(session_id) | |
| total_duration = session["total_duration"] | |
| processing_time = (datetime.now(timezone.utc) - session["start_time"]).total_seconds() | |
| await self._update_usage_stats(total_duration, processing_time) | |
| logger.info(f"Completed Azure Speech streaming session: {session_id}, duration: {total_duration:.2f}s") | |
| async def check_health(self) -> bool: | |
| """ | |
| Check if the Azure Speech Services are available and healthy. | |
| Returns: | |
| True if provider is healthy, False otherwise | |
| """ | |
| try: | |
| if not self._client_initialized: | |
| await self._initialize_client() | |
| # Perform a simple health check with minimal audio | |
| test_audio = b'\x00' * 1000 # Silent audio | |
| # Create a simple speech config for health check | |
| speech_config = SpeechConfig( | |
| subscription=self.config.api_credentials["subscription_key"], | |
| region=self.config.api_credentials["region"] | |
| ) | |
| speech_config.speech_recognition_language = "en-US" | |
| # Create audio config from test data | |
| audio_config = self._create_audio_config_from_bytes(test_audio, "wav") | |
| # Create recognizer and test | |
| recognizer = SpeechRecognizer( | |
| speech_config=speech_config, | |
| audio_config=audio_config | |
| ) | |
| # This should complete quickly even if it doesn't recognize anything | |
| result = await asyncio.get_event_loop().run_in_executor( | |
| None, | |
| lambda: recognizer.recognize_once() | |
| ) | |
| # Any result (including no speech) indicates the service is working | |
| return True | |
| except Exception as e: | |
| logger.error(f"Azure Speech health check failed: {e}") | |
| return False | |
| async def get_quota_status(self) -> Dict[str, QuotaStatus]: | |
| """ | |
| Get current quota usage status for Azure Speech Services. | |
| Returns: | |
| Dictionary mapping quota types to their status | |
| """ | |
| await self._reset_counters_if_needed() | |
| now = datetime.now(timezone.utc) | |
| return { | |
| "requests_per_minute": QuotaStatus( | |
| provider=self.name, | |
| quota_type=QuotaType.REQUESTS_PER_MINUTE, | |
| current_usage=self._usage_stats["requests_this_minute"], | |
| limit=self.FREE_TIER_LIMITS["requests_per_minute"], | |
| remaining=max(0, self.FREE_TIER_LIMITS["requests_per_minute"] - self._usage_stats["requests_this_minute"]), | |
| reset_time=now.replace(second=0, microsecond=0) + timedelta(minutes=1), | |
| percentage_used=min(1.0, self._usage_stats["requests_this_minute"] / self.FREE_TIER_LIMITS["requests_per_minute"]) | |
| ), | |
| "requests_per_day": QuotaStatus( | |
| provider=self.name, | |
| quota_type=QuotaType.REQUESTS_PER_DAY, | |
| current_usage=self._usage_stats["requests_today"], | |
| limit=self.FREE_TIER_LIMITS["requests_per_day"], | |
| remaining=max(0, self.FREE_TIER_LIMITS["requests_per_day"] - self._usage_stats["requests_today"]), | |
| reset_time=now.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1), | |
| percentage_used=min(1.0, self._usage_stats["requests_today"] / self.FREE_TIER_LIMITS["requests_per_day"]) | |
| ), | |
| "audio_hours_per_month": QuotaStatus( | |
| provider=self.name, | |
| quota_type=QuotaType.AUDIO_MINUTES_PER_MONTH, # Using minutes enum for hours | |
| current_usage=self._usage_stats["audio_hours_this_month"], | |
| limit=self.FREE_TIER_LIMITS["audio_hours_per_month"], | |
| remaining=max(0, self.FREE_TIER_LIMITS["audio_hours_per_month"] - self._usage_stats["audio_hours_this_month"]), | |
| reset_time=self._get_next_month_start(), | |
| percentage_used=min(1.0, self._usage_stats["audio_hours_this_month"] / self.FREE_TIER_LIMITS["audio_hours_per_month"]) | |
| ) | |
| } | |
| 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 | |
| """ | |
| return format.lower() in [f.lower() for f in self.SUPPORTED_FORMATS] | |
| 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 | |
| """ | |
| return language in self.SUPPORTED_LANGUAGES | |
| 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 | |
| """ | |
| hours = audio_duration / 3600.0 | |
| # Check if within free tier | |
| current_usage = self._usage_stats["audio_hours_this_month"] | |
| free_remaining = max(0, self.FREE_TIER_LIMITS["audio_hours_per_month"] - current_usage) | |
| if hours <= free_remaining: | |
| return 0.0 # Within free tier | |
| # Calculate cost for paid usage | |
| paid_hours = hours - free_remaining | |
| model_type = "neural" # Default to neural pricing (higher quality) | |
| return paid_hours * self.PRICING[model_type] | |
| # Private methods | |
| def _create_speech_config(self, language: str, **kwargs) -> 'SpeechConfig': | |
| """Create speech configuration for recognition.""" | |
| # Clone the base config | |
| speech_config = SpeechConfig( | |
| subscription=self.config.api_credentials["subscription_key"], | |
| region=self.config.api_credentials["region"] | |
| ) | |
| # Set language | |
| speech_config.speech_recognition_language = language | |
| # Configure output format for detailed results | |
| speech_config.output_format = speechsdk.OutputFormat.Detailed | |
| # Enable word-level timestamps if requested | |
| if kwargs.get('enable_word_timestamps', True): | |
| speech_config.request_word_level_timestamps() | |
| # Configure profanity filter | |
| if kwargs.get('profanity_filter', False): | |
| speech_config.set_profanity(speechsdk.ProfanityOption.Masked) | |
| else: | |
| speech_config.set_profanity(speechsdk.ProfanityOption.Raw) | |
| # Configure custom models if specified | |
| if 'custom_model_id' in kwargs: | |
| speech_config.endpoint_id = kwargs['custom_model_id'] | |
| return speech_config | |
| def _create_audio_config_from_bytes(self, audio_data: bytes, format: str) -> 'AudioConfig': | |
| """Create audio configuration from audio bytes.""" | |
| # Create a stream from the audio data | |
| stream = speechsdk.audio.PushAudioInputStream() | |
| # Write the audio data to the stream | |
| stream.write(audio_data) | |
| stream.close() | |
| # Create audio config from the stream | |
| audio_config = speechsdk.audio.AudioConfig(stream=stream) | |
| return audio_config | |
| def _process_recognition_result( | |
| self, | |
| result, | |
| start_time: datetime, | |
| audio_duration: float, | |
| language: str | |
| ) -> TranscriptionResult: | |
| """Process batch recognition result.""" | |
| processing_time = (datetime.now(timezone.utc) - start_time).total_seconds() | |
| if result.reason == ResultReason.RecognizedSpeech: | |
| # Parse detailed results if available | |
| detailed_result = json.loads(result.json) if hasattr(result, 'json') and result.json else {} | |
| # Extract confidence score | |
| confidence = 0.0 | |
| if 'NBest' in detailed_result and detailed_result['NBest']: | |
| confidence = detailed_result['NBest'][0].get('Confidence', 0.0) | |
| # Extract word timestamps | |
| word_timestamps = self._extract_word_timestamps(detailed_result) | |
| # Extract alternatives | |
| alternatives = [] | |
| if 'NBest' in detailed_result and len(detailed_result['NBest']) > 1: | |
| alternatives = [item.get('Display', '') for item in detailed_result['NBest'][1:]] | |
| return TranscriptionResult( | |
| text=result.text, | |
| confidence=confidence, | |
| provider=self.name, | |
| processing_time=processing_time, | |
| audio_duration=audio_duration, | |
| language=language, | |
| alternatives=alternatives, | |
| word_timestamps=word_timestamps, | |
| is_final=True | |
| ) | |
| elif result.reason == ResultReason.NoMatch: | |
| return TranscriptionResult( | |
| text="", | |
| confidence=0.0, | |
| provider=self.name, | |
| processing_time=processing_time, | |
| audio_duration=audio_duration, | |
| language=language, | |
| alternatives=[], | |
| word_timestamps=None, | |
| is_final=True | |
| ) | |
| else: | |
| # Handle cancellation or error | |
| error_details = result.cancellation_details if hasattr(result, 'cancellation_details') else None | |
| error_msg = f"Recognition failed: {error_details.reason if error_details else 'Unknown error'}" | |
| if error_details and error_details.reason == CancellationReason.Error: | |
| error_msg += f" - {error_details.error_details}" | |
| raise TranscriptionError(error_msg) | |
| def _process_streaming_result( | |
| self, | |
| result, | |
| session_id: str, | |
| language: str | |
| ) -> Optional[TranscriptionResult]: | |
| """Process streaming recognition result.""" | |
| if result.reason in [ResultReason.RecognizedSpeech, ResultReason.RecognizingSpeech]: | |
| is_final = result.reason == ResultReason.RecognizedSpeech | |
| # Parse detailed results if available | |
| detailed_result = json.loads(result.json) if hasattr(result, 'json') and result.json else {} | |
| # Extract confidence score | |
| confidence = 0.0 | |
| if 'NBest' in detailed_result and detailed_result['NBest']: | |
| confidence = detailed_result['NBest'][0].get('Confidence', 0.0) | |
| # For interim results, confidence is typically lower | |
| if not is_final: | |
| confidence *= 0.8 # Reduce confidence for interim results | |
| return TranscriptionResult( | |
| text=result.text, | |
| confidence=confidence, | |
| provider=self.name, | |
| processing_time=0.1, # Streaming has minimal processing time | |
| audio_duration=0.0, # Will be updated by session tracking | |
| language=language, | |
| alternatives=[], | |
| word_timestamps=self._extract_word_timestamps(detailed_result) if is_final else None, | |
| is_final=is_final, | |
| session_id=session_id | |
| ) | |
| return None | |
| def _extract_word_timestamps(self, detailed_result: Dict[str, Any]) -> List[WordTimestamp]: | |
| """Extract word timestamps from detailed recognition result.""" | |
| if not detailed_result or 'NBest' not in detailed_result or not detailed_result['NBest']: | |
| return [] | |
| best_result = detailed_result['NBest'][0] | |
| if 'Words' not in best_result: | |
| return [] | |
| timestamps = [] | |
| try: | |
| for word_info in best_result['Words']: | |
| # Azure returns timestamps in 100-nanosecond units | |
| start_time = word_info.get('Offset', 0) / 10_000_000.0 # Convert to seconds | |
| duration = word_info.get('Duration', 0) / 10_000_000.0 # Convert to seconds | |
| end_time = start_time + duration | |
| timestamps.append(WordTimestamp( | |
| word=word_info.get('Word', ''), | |
| start_time=start_time, | |
| end_time=end_time, | |
| confidence=word_info.get('Confidence', 0.0) | |
| )) | |
| except (TypeError, KeyError, ValueError) as e: | |
| logger.warning(f"Error extracting word timestamps: {e}") | |
| return [] | |
| return timestamps | |
| def _estimate_audio_duration(self, audio_data: bytes, format: str) -> float: | |
| """Estimate audio duration from data size and format.""" | |
| # This is a rough estimation - in production, you'd want more accurate duration detection | |
| if format.lower() in ["wav", "flac"]: | |
| # Assume 16-bit, 16kHz mono for estimation | |
| return len(audio_data) / (16000 * 2) | |
| elif format.lower() in ["mp3", "ogg", "webm"]: | |
| # Compressed formats - rough estimation | |
| return len(audio_data) / 8000 # Assume ~64kbps compression | |
| else: | |
| # Default estimation | |
| return len(audio_data) / 16000 | |
| async def _check_quota(self, audio_duration: float) -> None: | |
| """Check if request would exceed quota limits.""" | |
| await self._reset_counters_if_needed() | |
| # Check requests per minute | |
| if self._usage_stats["requests_this_minute"] >= self.FREE_TIER_LIMITS["requests_per_minute"]: | |
| raise RateLimitExceededError( | |
| self.name, | |
| "requests_per_minute", | |
| retry_after=60.0 | |
| ) | |
| # Check requests per day | |
| if self._usage_stats["requests_today"] >= self.FREE_TIER_LIMITS["requests_per_day"]: | |
| raise RateLimitExceededError( | |
| self.name, | |
| "requests_per_day", | |
| retry_after=86400.0 # 24 hours | |
| ) | |
| # Check audio hours per month | |
| audio_hours = audio_duration / 3600.0 | |
| if self._usage_stats["audio_hours_this_month"] + audio_hours > self.FREE_TIER_LIMITS["audio_hours_per_month"]: | |
| raise QuotaExceededError( | |
| self.name, | |
| "audio_hours_per_month", | |
| self._usage_stats["audio_hours_this_month"] + audio_hours, | |
| self.FREE_TIER_LIMITS["audio_hours_per_month"] | |
| ) | |
| async def _update_usage_stats(self, audio_duration: float, processing_time: float) -> None: | |
| """Update usage statistics after successful request.""" | |
| await self._reset_counters_if_needed() | |
| self._usage_stats["requests_this_minute"] += 1 | |
| self._usage_stats["requests_today"] += 1 | |
| self._usage_stats["audio_hours_this_month"] += audio_duration / 3600.0 | |
| logger.debug( | |
| f"Updated Azure Speech usage: {self._usage_stats['requests_today']} requests today, " | |
| f"{self._usage_stats['audio_hours_this_month']:.2f} hours this month" | |
| ) | |
| async def _reset_counters_if_needed(self) -> None: | |
| """Reset usage counters based on time windows.""" | |
| now = datetime.now(timezone.utc) | |
| # Reset minute counter | |
| current_minute = now.replace(second=0, microsecond=0) | |
| if current_minute > self._usage_stats["last_minute_reset"]: | |
| self._usage_stats["requests_this_minute"] = 0 | |
| self._usage_stats["last_minute_reset"] = current_minute | |
| logger.debug("Reset Azure Speech minute counter") | |
| # Reset daily counter | |
| current_date = now.date() | |
| if current_date > self._usage_stats["last_daily_reset"]: | |
| self._usage_stats["requests_today"] = 0 | |
| self._usage_stats["last_daily_reset"] = current_date | |
| logger.info("Reset Azure Speech daily counter") | |
| # Reset monthly counter | |
| current_month_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0) | |
| if current_month_start > self._usage_stats["last_monthly_reset"]: | |
| self._usage_stats["audio_hours_this_month"] = 0.0 | |
| self._usage_stats["last_monthly_reset"] = current_month_start | |
| logger.info("Reset Azure Speech monthly counter") | |
| def _get_next_month_start(self) -> datetime: | |
| """Get the start of next month.""" | |
| now = datetime.now(timezone.utc) | |
| if now.month == 12: | |
| return now.replace(year=now.year + 1, month=1, day=1, hour=0, minute=0, second=0, microsecond=0) | |
| else: | |
| return now.replace(month=now.month + 1, day=1, hour=0, minute=0, second=0, microsecond=0) | |
| async def _handle_azure_error(self, error: Exception) -> None: | |
| """Handle Azure Speech Services specific errors.""" | |
| error_str = str(error).lower() | |
| if "unauthorized" in error_str or "authentication" in error_str: | |
| raise ProviderAuthenticationError( | |
| self.name, | |
| f"Authentication failed: {str(error)}" | |
| ) | |
| elif "quota" in error_str or "rate limit" in error_str or "throttl" in error_str: | |
| raise RateLimitExceededError( | |
| self.name, | |
| retry_after=60.0 | |
| ) | |
| elif "timeout" in error_str or "timed out" in error_str: | |
| raise ProviderTimeoutError( | |
| self.name, | |
| f"Request timeout: {str(error)}" | |
| ) | |
| elif "unavailable" in error_str or "service" in error_str: | |
| raise ProviderUnavailableError( | |
| self.name, | |
| f"Service unavailable: {str(error)}" | |
| ) | |
| else: | |
| # Generic provider error | |
| logger.error(f"Azure Speech error: {error}") | |
| raise TranscriptionError(f"Azure Speech transcription failed: {str(error)}") | |
| def create_azure_speech_provider( | |
| name: str = "azure_speech", | |
| priority: int = 3, | |
| **config_overrides | |
| ) -> AzureSpeechProvider: | |
| """ | |
| Factory function to create an AzureSpeechProvider with default configuration. | |
| Args: | |
| name: Provider name | |
| priority: Provider priority (lower = higher priority) | |
| **config_overrides: Configuration overrides | |
| Returns: | |
| Configured AzureSpeechProvider instance | |
| """ | |
| default_config = { | |
| "name": name, | |
| "provider_type": ProviderType.AZURE_SPEECH, | |
| "enabled": True, | |
| "priority": priority, | |
| "free_tier_limits": AzureSpeechProvider.FREE_TIER_LIMITS, | |
| "rate_limits": { | |
| "requests_per_minute": AzureSpeechProvider.FREE_TIER_LIMITS["requests_per_minute"], | |
| "requests_per_day": AzureSpeechProvider.FREE_TIER_LIMITS["requests_per_day"] | |
| }, | |
| "supported_formats": AzureSpeechProvider.SUPPORTED_FORMATS, | |
| "supported_languages": AzureSpeechProvider.SUPPORTED_LANGUAGES, | |
| "cost_per_minute": AzureSpeechProvider.PRICING["neural"] / 60.0, # Convert hourly to per-minute | |
| "api_credentials": {}, # Must be provided by user | |
| "endpoint_url": None, # Uses default Azure endpoint | |
| "timeout_seconds": 60, | |
| "max_retries": 3 | |
| } | |
| # Apply overrides | |
| default_config.update(config_overrides) | |
| # Create configuration object | |
| config = ProviderConfig(**default_config) | |
| return AzureSpeechProvider(config) |