""" Google Speech-to-Text provider implementation. This module implements a provider that integrates with Google Cloud Speech-to-Text API for high-quality speech recognition. It supports both streaming and batch transcription with comprehensive quota management for the free tier (60 minutes/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: from google.cloud import speech from google.cloud.speech import RecognitionConfig, StreamingRecognitionConfig from google.oauth2 import service_account from google.api_core import exceptions as google_exceptions GOOGLE_SPEECH_AVAILABLE = True except ImportError: logger.warning("Google Cloud Speech library not available. Install with: pip install google-cloud-speech") GOOGLE_SPEECH_AVAILABLE = False # Create mock classes for type hints speech = None RecognitionConfig = None StreamingRecognitionConfig = None service_account = None google_exceptions = None class GoogleSpeechProvider(STTProvider): """ Google Cloud Speech-to-Text provider implementation. This provider integrates with Google Cloud Speech-to-Text API to provide high-quality speech recognition with support for multiple languages, streaming transcription, and advanced features like word timestamps. Key features: - Streaming and batch transcription - Free tier quota management (60 minutes/month) - Multiple audio format support - Word-level timestamps - Confidence scoring - Language detection - Noise robustness """ # Supported audio formats for Google Speech-to-Text SUPPORTED_FORMATS = [ "wav", "flac", "mp3", "ogg", "webm", "amr", "amr-wb" ] # Supported languages (subset of Google's extensive language support) SUPPORTED_LANGUAGES = [ "en-US", "en-GB", "en-AU", "en-CA", "en-IN", "en-NZ", "en-ZA", "es-ES", "es-MX", "es-AR", "es-CO", "es-CL", "es-PE", "es-VE", "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", "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" ] # Free tier limits (as of 2024) FREE_TIER_LIMITS = { "audio_minutes_per_month": 60.0, "requests_per_minute": 1000, "requests_per_day": 50000 } # Pricing (per minute, in USD) PRICING = { "standard": 0.006, # $0.006 per minute for standard models "enhanced": 0.009 # $0.009 per minute for enhanced models } def __init__(self, config: ProviderConfig): """ Initialize the Google Speech-to-Text provider. Args: config: Provider configuration Raises: ImportError: If Google Cloud Speech library is not available ProviderAuthenticationError: If credentials are invalid """ super().__init__(config) if not GOOGLE_SPEECH_AVAILABLE: raise ImportError( "Google Cloud Speech library not available. " "Install with: pip install google-cloud-speech" ) # Validate configuration if config.provider_type != ProviderType.GOOGLE_SPEECH: raise ValueError(f"Invalid provider type: {config.provider_type}") # Initialize client self._client = None self._streaming_client = None self._credentials = None # Usage tracking for quota management self._usage_stats = { "requests_today": 0, "requests_this_minute": 0, "audio_minutes_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 GoogleSpeechProvider: {self.name}") async def _initialize_client(self) -> None: """Initialize the Google Speech client with credentials.""" try: # Get credentials from config credentials_info = self.config.api_credentials if "service_account_key" in credentials_info: # Use service account key (JSON string or file path) key_data = credentials_info["service_account_key"] if isinstance(key_data, str) and key_data.startswith("{"): # JSON string import json key_info = json.loads(key_data) self._credentials = service_account.Credentials.from_service_account_info(key_info) else: # File path self._credentials = service_account.Credentials.from_service_account_file(key_data) elif "api_key" in credentials_info: # Use API key (less secure, not recommended for production) logger.warning("Using API key authentication. Service account is recommended for production.") # For API key, we'll use default credentials and set the key in environment import os os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = credentials_info["api_key"] self._credentials = None else: # Use default credentials (from environment or metadata server) logger.info("Using default Google Cloud credentials") self._credentials = None # Create clients if self._credentials: self._client = speech.SpeechClient(credentials=self._credentials) self._streaming_client = speech.SpeechClient(credentials=self._credentials) else: self._client = speech.SpeechClient() self._streaming_client = speech.SpeechClient() self._client_initialized = True logger.info("Google Speech client initialized successfully") except Exception as e: logger.error(f"Failed to initialize Google 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 Google Speech-to-Text API. Args: audio_data: Raw audio bytes format: Audio format (wav, flac, mp3, etc.) language: Language code for transcription **kwargs: Additional options (model, enable_word_time_offsets, etc.) Returns: TranscriptionResult with transcribed text and metadata Raises: ProviderUnavailableError: If Google 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: # Prepare recognition config config = self._create_recognition_config(format, language, **kwargs) # Prepare audio audio = speech.RecognitionAudio(content=audio_data) # Perform transcription logger.debug(f"Starting Google Speech transcription for {audio_duration:.2f}s audio") response = await asyncio.get_event_loop().run_in_executor( None, lambda: self._client.recognize(config=config, audio=audio) ) # Process results result = self._process_recognition_response(response, start_time, audio_duration, language) # Update usage statistics await self._update_usage_stats(audio_duration, result.processing_time) logger.info( f"Google Speech transcription completed: {len(result.text)} chars, " f"confidence: {result.confidence:.2f}, time: {result.processing_time:.2f}s" ) return result except Exception as e: # Check if it's a Google API error by checking attributes if hasattr(e, 'code'): await self._handle_google_api_error(e) else: logger.error(f"Google Speech transcription failed: {e}") raise TranscriptionError(f"Transcription failed: {str(e)}") async def transcribe_streaming( self, audio_stream: AsyncIterator[bytes], format: str, language: str = "en-US", **kwargs ) -> AsyncIterator[TranscriptionResult]: """ Transcribe streaming audio data using Google Speech-to-Text API. 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"gs_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 Google Speech streaming session: {session_id}") # Create streaming config config = self._create_streaming_config(format, language, **kwargs) # Create streaming request generator requests = self._create_streaming_requests(audio_stream, config, session_id) # Start streaming recognition responses = await asyncio.get_event_loop().run_in_executor( None, lambda: self._streaming_client.streaming_recognize(requests) ) # Process streaming responses async for response in self._process_streaming_responses(responses, session_id): yield response except Exception as e: # Check if it's a Google API error by checking attributes if hasattr(e, 'code'): await self._handle_google_api_error(e) else: logger.error(f"Google Speech streaming failed: {e}") raise TranscriptionError(f"Streaming transcription failed: {str(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 Google Speech streaming session: {session_id}, duration: {total_duration:.2f}s") async def check_health(self) -> bool: """ Check if the Google Speech API is 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 config = speech.RecognitionConfig( encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16, sample_rate_hertz=16000, language_code="en-US" ) audio = speech.RecognitionAudio(content=test_audio) # This should complete quickly even if it doesn't recognize anything await asyncio.get_event_loop().run_in_executor( None, lambda: self._client.recognize(config=config, audio=audio) ) return True except Exception as e: logger.error(f"Google Speech health check failed: {e}") return False async def get_quota_status(self) -> Dict[str, QuotaStatus]: """ Get current quota usage status for Google Speech API. 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_minutes_per_month": QuotaStatus( provider=self.name, quota_type=QuotaType.AUDIO_MINUTES_PER_MONTH, current_usage=self._usage_stats["audio_minutes_this_month"], limit=self.FREE_TIER_LIMITS["audio_minutes_per_month"], remaining=max(0, self.FREE_TIER_LIMITS["audio_minutes_per_month"] - self._usage_stats["audio_minutes_this_month"]), reset_time=self._get_next_month_start(), percentage_used=min(1.0, self._usage_stats["audio_minutes_this_month"] / self.FREE_TIER_LIMITS["audio_minutes_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 """ minutes = audio_duration / 60.0 # Check if within free tier current_usage = self._usage_stats["audio_minutes_this_month"] free_remaining = max(0, self.FREE_TIER_LIMITS["audio_minutes_per_month"] - current_usage) if minutes <= free_remaining: return 0.0 # Within free tier # Calculate cost for paid usage paid_minutes = minutes - free_remaining model_type = "standard" # Default to standard pricing return paid_minutes * self.PRICING[model_type] # Private methods def _create_recognition_config(self, format: str, language: str, **kwargs) -> 'RecognitionConfig': """Create recognition configuration for batch transcription.""" # Map format to Google Speech encoding encoding_map = { "wav": speech.RecognitionConfig.AudioEncoding.LINEAR16, "flac": speech.RecognitionConfig.AudioEncoding.FLAC, "mp3": speech.RecognitionConfig.AudioEncoding.MP3, "ogg": speech.RecognitionConfig.AudioEncoding.OGG_OPUS, "webm": speech.RecognitionConfig.AudioEncoding.WEBM_OPUS, "amr": speech.RecognitionConfig.AudioEncoding.AMR, "amr-wb": speech.RecognitionConfig.AudioEncoding.AMR_WB } encoding = encoding_map.get(format.lower(), speech.RecognitionConfig.AudioEncoding.LINEAR16) config = speech.RecognitionConfig( encoding=encoding, sample_rate_hertz=kwargs.get('sample_rate', 16000), language_code=language, enable_word_time_offsets=kwargs.get('enable_word_time_offsets', True), enable_automatic_punctuation=kwargs.get('enable_automatic_punctuation', True), max_alternatives=kwargs.get('max_alternatives', 1), profanity_filter=kwargs.get('profanity_filter', False), speech_contexts=kwargs.get('speech_contexts', []), enable_speaker_diarization=kwargs.get('enable_speaker_diarization', False), diarization_speaker_count=kwargs.get('diarization_speaker_count', 2), model=kwargs.get('model', 'latest_long') ) return config def _create_streaming_config(self, format: str, language: str, **kwargs) -> 'StreamingRecognitionConfig': """Create streaming recognition configuration.""" recognition_config = self._create_recognition_config(format, language, **kwargs) streaming_config = speech.StreamingRecognitionConfig( config=recognition_config, interim_results=kwargs.get('interim_results', True), single_utterance=kwargs.get('single_utterance', False) ) return streaming_config async def _create_streaming_requests( self, audio_stream: AsyncIterator[bytes], config: 'StreamingRecognitionConfig', session_id: str ) -> AsyncIterator: """Create streaming requests from audio stream.""" # First request with config yield speech.StreamingRecognizeRequest(streaming_config=config) # Subsequent requests with audio data async for audio_chunk in audio_stream: if session_id in self._active_streams: session = self._active_streams[session_id] session["chunk_count"] += 1 # Estimate chunk duration chunk_duration = self._estimate_audio_duration(audio_chunk, session["format"]) session["total_duration"] += chunk_duration # Check quota for this chunk await self._check_quota(chunk_duration) yield speech.StreamingRecognizeRequest(audio_content=audio_chunk) async def _process_streaming_responses( self, responses, session_id: str ) -> AsyncIterator[TranscriptionResult]: """Process streaming recognition responses.""" for response in responses: if not response.results: continue for result in response.results: if not result.alternatives: continue alternative = result.alternatives[0] # Create transcription result transcription_result = TranscriptionResult( text=alternative.transcript, confidence=alternative.confidence if hasattr(alternative, 'confidence') else 0.0, provider=self.name, processing_time=0.1, # Streaming has minimal processing time audio_duration=0.0, # Will be updated by session tracking language=self._active_streams[session_id]["language"], alternatives=[alt.transcript for alt in result.alternatives[1:]] if len(result.alternatives) > 1 else [], word_timestamps=self._extract_word_timestamps(alternative) if hasattr(alternative, 'words') else None, is_final=result.is_final, session_id=session_id ) yield transcription_result def _process_recognition_response( self, response, start_time: datetime, audio_duration: float, language: str ) -> TranscriptionResult: """Process batch recognition response.""" processing_time = (datetime.now(timezone.utc) - start_time).total_seconds() if not hasattr(response, 'results') or not response.results: 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 ) # Get the best result result = response.results[0] if not hasattr(result, 'alternatives') or not result.alternatives: 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 ) best_alternative = result.alternatives[0] return TranscriptionResult( text=best_alternative.transcript, confidence=getattr(best_alternative, 'confidence', 0.0), provider=self.name, processing_time=processing_time, audio_duration=audio_duration, language=language, alternatives=[alt.transcript for alt in result.alternatives[1:]] if len(result.alternatives) > 1 else [], word_timestamps=self._extract_word_timestamps(best_alternative) if hasattr(best_alternative, 'words') else None, is_final=True ) def _extract_word_timestamps(self, alternative) -> List[WordTimestamp]: """Extract word timestamps from recognition alternative.""" if not hasattr(alternative, 'words') or not alternative.words: return [] timestamps = [] try: for word_info in alternative.words: start_time = word_info.start_time.total_seconds() if hasattr(word_info.start_time, 'total_seconds') else 0.0 end_time = word_info.end_time.total_seconds() if hasattr(word_info.end_time, 'total_seconds') else 0.0 timestamps.append(WordTimestamp( word=word_info.word, start_time=start_time, end_time=end_time, confidence=getattr(word_info, 'confidence', 0.0) )) except (TypeError, AttributeError): # Handle mock objects or malformed data 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 minutes per month audio_minutes = audio_duration / 60.0 if self._usage_stats["audio_minutes_this_month"] + audio_minutes > self.FREE_TIER_LIMITS["audio_minutes_per_month"]: raise QuotaExceededError( self.name, "audio_minutes_per_month", self._usage_stats["audio_minutes_this_month"] + audio_minutes, self.FREE_TIER_LIMITS["audio_minutes_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_minutes_this_month"] += audio_duration / 60.0 logger.debug( f"Updated Google Speech usage: {self._usage_stats['requests_today']} requests today, " f"{self._usage_stats['audio_minutes_this_month']:.2f} minutes 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 Google 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 Google 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_minutes_this_month"] = 0.0 self._usage_stats["last_monthly_reset"] = current_month_start logger.info("Reset Google 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_google_api_error(self, error: Exception) -> None: """Handle Google API specific errors.""" if hasattr(error, 'code'): if error.code == 401: raise ProviderAuthenticationError( self.name, f"Authentication failed: {str(error)}" ) elif error.code == 429: raise RateLimitExceededError( self.name, retry_after=60.0 ) elif error.code == 503: raise ProviderUnavailableError( self.name, f"Service unavailable: {str(error)}" ) elif error.code in [408, 504]: raise ProviderTimeoutError( self.name, f"Request timeout: {str(error)}" ) # Generic provider error raise ProviderError( self.name, f"Google API error: {str(error)}" ) def create_google_speech_provider( name: str = "google_speech", priority: int = 2, **config_overrides ) -> GoogleSpeechProvider: """ Factory function to create a GoogleSpeechProvider with default configuration. Args: name: Provider name priority: Provider priority (lower = higher priority) **config_overrides: Configuration overrides Returns: Configured GoogleSpeechProvider instance """ default_config = { "name": name, "provider_type": ProviderType.GOOGLE_SPEECH, "enabled": True, "priority": priority, "free_tier_limits": GoogleSpeechProvider.FREE_TIER_LIMITS, "rate_limits": { "requests_per_minute": GoogleSpeechProvider.FREE_TIER_LIMITS["requests_per_minute"], "requests_per_day": GoogleSpeechProvider.FREE_TIER_LIMITS["requests_per_day"] }, "supported_formats": GoogleSpeechProvider.SUPPORTED_FORMATS, "supported_languages": GoogleSpeechProvider.SUPPORTED_LANGUAGES, "cost_per_minute": GoogleSpeechProvider.PRICING["standard"], "api_credentials": {}, # Must be provided by user "endpoint_url": None, # Uses default Google Cloud endpoint "timeout_seconds": 60, "max_retries": 3 } # Apply overrides default_config.update(config_overrides) # Create configuration object config = ProviderConfig(**default_config) return GoogleSpeechProvider(config)