Spaces:
Runtime error
Runtime error
Download voice_control/providers/web_speech_provider.py from nifty-coder/stemsplit-backend: direct link, hf CLI and curl.
- Browser
- Download file 21.3 kB
-
https://huggingface.co/spaces/nifty-coder/stemsplit-backend/resolve/main/voice_control/providers/web_speech_provider.py
- Command line
-
hf download hf://spaces/nifty-coder/stemsplit-backend/voice_control/providers/web_speech_provider.py
-
curl -L -o web_speech_provider.py https://huggingface.co/spaces/nifty-coder/stemsplit-backend/resolve/main/voice_control/providers/web_speech_provider.py
21.3 kB
| """ | |
| Web Speech API provider implementation. | |
| This module implements a proxy provider that integrates with the browser's | |
| Web Speech API for client-side speech recognition. Since the Web Speech API | |
| runs in the browser, this provider acts as a proxy that coordinates with | |
| frontend JavaScript code. | |
| """ | |
| import asyncio | |
| import json | |
| import logging | |
| from typing import Dict, List, Optional, AsyncIterator, Any | |
| from datetime import datetime, timezone | |
| from ..interfaces import STTProvider | |
| from ..models import ( | |
| ProviderConfig, | |
| TranscriptionResult, | |
| QuotaStatus, | |
| QuotaType, | |
| WordTimestamp, | |
| ProviderType | |
| ) | |
| from ..exceptions import ( | |
| ProviderError, | |
| ProviderUnavailableError, | |
| UnsupportedFormatError, | |
| UnsupportedLanguageError, | |
| QuotaExceededError, | |
| TranscriptionError | |
| ) | |
| logger = logging.getLogger(__name__) | |
| class WebSpeechProvider(STTProvider): | |
| """ | |
| Web Speech API provider implementation. | |
| This provider acts as a proxy to the browser's Web Speech API. Since the | |
| Web Speech API runs client-side, this provider coordinates with frontend | |
| JavaScript code through WebSocket messages and handles browser compatibility. | |
| Key features: | |
| - Browser compatibility detection | |
| - Real-time streaming support | |
| - Fallback handling for unsupported browsers | |
| - Client-side processing (no server costs) | |
| - Language detection and support | |
| """ | |
| # Supported audio formats (limited by browser capabilities) | |
| SUPPORTED_FORMATS = ["webm", "wav", "mp3", "ogg"] | |
| # Supported languages (common Web Speech API languages) | |
| 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" | |
| ] | |
| def __init__(self, config: ProviderConfig): | |
| """ | |
| Initialize the Web Speech API provider. | |
| Args: | |
| config: Provider configuration | |
| """ | |
| super().__init__(config) | |
| # Validate configuration | |
| if config.provider_type != ProviderType.WEB_SPEECH_API: | |
| raise ValueError(f"Invalid provider type: {config.provider_type}") | |
| # Web Speech API is free, so we track usage for monitoring only | |
| self._usage_stats = { | |
| "requests_today": 0, | |
| "audio_minutes_today": 0.0, | |
| "last_reset": datetime.now(timezone.utc).date() | |
| } | |
| # Browser compatibility status | |
| self._browser_compatible = None | |
| self._last_compatibility_check = None | |
| # Session management for streaming | |
| self._active_sessions = {} | |
| logger.info(f"Initialized WebSpeechProvider: {self.name}") | |
| async def transcribe_audio( | |
| self, | |
| audio_data: bytes, | |
| format: str, | |
| language: str = "en-US", | |
| **kwargs | |
| ) -> TranscriptionResult: | |
| """ | |
| Transcribe audio data using Web Speech API. | |
| Since Web Speech API runs in the browser, this method coordinates | |
| with frontend JavaScript to perform the transcription. | |
| Args: | |
| audio_data: Raw audio bytes | |
| format: Audio format | |
| language: Language code for transcription | |
| **kwargs: Additional options (session_id, timeout, etc.) | |
| Returns: | |
| TranscriptionResult with transcribed text | |
| Raises: | |
| ProviderUnavailableError: If browser doesn't support Web Speech API | |
| UnsupportedFormatError: If audio format is not supported | |
| UnsupportedLanguageError: If language is not supported | |
| TranscriptionError: If transcription fails | |
| """ | |
| start_time = datetime.now(timezone.utc) | |
| # Check browser compatibility | |
| await self._check_browser_compatibility() | |
| # 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) | |
| # Check quota (for monitoring purposes) | |
| audio_duration = kwargs.get('audio_duration', 0.0) | |
| await self._check_usage_quota(audio_duration) | |
| try: | |
| # Create transcription request | |
| session_id = kwargs.get('session_id', f"ws_{int(datetime.now().timestamp())}") | |
| timeout = kwargs.get('timeout', 30.0) | |
| # Prepare transcription parameters | |
| transcription_params = { | |
| "language": language, | |
| "continuous": kwargs.get('continuous', False), | |
| "interim_results": kwargs.get('interim_results', True), | |
| "max_alternatives": kwargs.get('max_alternatives', 1), | |
| "session_id": session_id | |
| } | |
| # Since this is a proxy provider, we simulate the transcription process | |
| # In a real implementation, this would coordinate with frontend JavaScript | |
| result = await self._perform_transcription( | |
| audio_data, | |
| format, | |
| transcription_params, | |
| timeout | |
| ) | |
| # Update usage statistics | |
| processing_time = (datetime.now(timezone.utc) - start_time).total_seconds() | |
| await self._update_usage_stats(audio_duration, processing_time) | |
| return result | |
| except Exception as e: | |
| logger.error(f"Web Speech API transcription failed: {e}") | |
| if isinstance(e, (ProviderError, TranscriptionError)): | |
| raise | |
| 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 Web Speech 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 | |
| """ | |
| # Check browser compatibility | |
| await self._check_browser_compatibility() | |
| # 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"ws_stream_{int(datetime.now().timestamp())}") | |
| try: | |
| # Initialize streaming session | |
| self._active_sessions[session_id] = { | |
| "start_time": datetime.now(timezone.utc), | |
| "language": language, | |
| "format": format, | |
| "chunk_count": 0, | |
| "total_duration": 0.0 | |
| } | |
| logger.info(f"Started streaming session: {session_id}") | |
| # Process audio chunks | |
| async for audio_chunk in audio_stream: | |
| try: | |
| # Estimate chunk duration (rough approximation) | |
| chunk_duration = len(audio_chunk) / (16000 * 2) # Assume 16kHz, 16-bit | |
| # Check quota for this chunk | |
| await self._check_usage_quota(chunk_duration) | |
| # Process the chunk | |
| result = await self._process_streaming_chunk( | |
| audio_chunk, | |
| session_id, | |
| language, | |
| format, | |
| **kwargs | |
| ) | |
| if result: | |
| # Update session stats | |
| session = self._active_sessions[session_id] | |
| session["chunk_count"] += 1 | |
| session["total_duration"] += chunk_duration | |
| yield result | |
| except Exception as e: | |
| logger.error(f"Error processing streaming chunk: {e}") | |
| # Continue processing other chunks | |
| continue | |
| finally: | |
| # Clean up session | |
| if session_id in self._active_sessions: | |
| session = self._active_sessions.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 streaming session: {session_id}, duration: {total_duration:.2f}s") | |
| async def check_health(self) -> bool: | |
| """ | |
| Check if the Web Speech API is available and healthy. | |
| Returns: | |
| True if provider is healthy, False otherwise | |
| """ | |
| try: | |
| await self._check_browser_compatibility() | |
| return self._browser_compatible | |
| except Exception as e: | |
| logger.error(f"Health check failed: {e}") | |
| return False | |
| async def get_quota_status(self) -> Dict[str, QuotaStatus]: | |
| """ | |
| Get current quota usage status. | |
| Web Speech API is free, so this returns monitoring information only. | |
| Returns: | |
| Dictionary mapping quota types to their status | |
| """ | |
| await self._reset_daily_stats_if_needed() | |
| # Web Speech API doesn't have hard limits, but we track usage for monitoring | |
| return { | |
| "requests_per_day": QuotaStatus( | |
| provider=self.name, | |
| quota_type=QuotaType.REQUESTS_PER_DAY, | |
| current_usage=self._usage_stats["requests_today"], | |
| limit=float('inf'), # No hard limit | |
| remaining=float('inf'), | |
| reset_time=datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0), | |
| percentage_used=0.0 | |
| ), | |
| "audio_minutes_per_day": QuotaStatus( | |
| provider=self.name, | |
| quota_type=QuotaType.AUDIO_MINUTES_PER_DAY, | |
| current_usage=self._usage_stats["audio_minutes_today"], | |
| limit=float('inf'), # No hard limit | |
| remaining=float('inf'), | |
| reset_time=datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0), | |
| percentage_used=0.0 | |
| ) | |
| } | |
| 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. | |
| Web Speech API is free, so this always returns 0.0. | |
| Args: | |
| audio_duration: Duration in seconds | |
| Returns: | |
| Estimated cost (always 0.0 for Web Speech API) | |
| """ | |
| return 0.0 | |
| # Private methods | |
| async def _check_browser_compatibility(self) -> None: | |
| """ | |
| Check if the browser supports Web Speech API. | |
| Raises: | |
| ProviderUnavailableError: If browser doesn't support Web Speech API | |
| """ | |
| # In a real implementation, this would check browser capabilities | |
| # For now, we simulate compatibility check | |
| current_time = datetime.now(timezone.utc) | |
| # Cache compatibility check for 5 minutes | |
| if (self._last_compatibility_check and | |
| (current_time - self._last_compatibility_check).total_seconds() < 300): | |
| if not self._browser_compatible: | |
| raise ProviderUnavailableError( | |
| self.name, | |
| "Browser does not support Web Speech API" | |
| ) | |
| return | |
| # Simulate compatibility check | |
| # In reality, this would be done on the frontend and communicated via WebSocket | |
| self._browser_compatible = True # Assume compatible for now | |
| self._last_compatibility_check = current_time | |
| if not self._browser_compatible: | |
| raise ProviderUnavailableError( | |
| self.name, | |
| "Browser does not support Web Speech API" | |
| ) | |
| async def _check_usage_quota(self, audio_duration: float) -> None: | |
| """ | |
| Check usage quota (for monitoring purposes). | |
| Args: | |
| audio_duration: Duration of audio to be processed | |
| """ | |
| await self._reset_daily_stats_if_needed() | |
| # Web Speech API is free, but we can implement soft limits for monitoring | |
| max_daily_requests = self.config.free_tier_limits.get("max_daily_requests", float('inf')) | |
| max_daily_minutes = self.config.free_tier_limits.get("max_daily_minutes", float('inf')) | |
| if self._usage_stats["requests_today"] >= max_daily_requests: | |
| raise QuotaExceededError( | |
| self.name, | |
| "requests_per_day", | |
| self._usage_stats["requests_today"], | |
| max_daily_requests | |
| ) | |
| if self._usage_stats["audio_minutes_today"] + (audio_duration / 60.0) > max_daily_minutes: | |
| raise QuotaExceededError( | |
| self.name, | |
| "audio_minutes_per_day", | |
| self._usage_stats["audio_minutes_today"] + (audio_duration / 60.0), | |
| max_daily_minutes | |
| ) | |
| async def _perform_transcription( | |
| self, | |
| audio_data: bytes, | |
| format: str, | |
| params: Dict[str, Any], | |
| timeout: float | |
| ) -> TranscriptionResult: | |
| """ | |
| Perform the actual transcription. | |
| In a real implementation, this would coordinate with frontend JavaScript | |
| to use the Web Speech API. For now, we simulate the process. | |
| Args: | |
| audio_data: Raw audio bytes | |
| format: Audio format | |
| params: Transcription parameters | |
| timeout: Request timeout | |
| Returns: | |
| TranscriptionResult | |
| """ | |
| start_time = datetime.now(timezone.utc) | |
| # Simulate transcription delay | |
| await asyncio.sleep(0.1) | |
| # Estimate audio duration | |
| audio_duration = len(audio_data) / (16000 * 2) # Assume 16kHz, 16-bit | |
| # Simulate transcription result | |
| # In reality, this would come from the browser's Web Speech API | |
| transcribed_text = "This is a simulated transcription from Web Speech API" | |
| confidence = 0.85 | |
| processing_time = (datetime.now(timezone.utc) - start_time).total_seconds() | |
| return TranscriptionResult( | |
| text=transcribed_text, | |
| confidence=confidence, | |
| provider=self.name, | |
| processing_time=processing_time, | |
| audio_duration=audio_duration, | |
| language=params["language"], | |
| alternatives=[], | |
| word_timestamps=None, | |
| is_final=True, | |
| session_id=params["session_id"] | |
| ) | |
| async def _process_streaming_chunk( | |
| self, | |
| audio_chunk: bytes, | |
| session_id: str, | |
| language: str, | |
| format: str, | |
| **kwargs | |
| ) -> Optional[TranscriptionResult]: | |
| """ | |
| Process a streaming audio chunk. | |
| Args: | |
| audio_chunk: Audio data chunk | |
| session_id: Streaming session ID | |
| language: Language code | |
| format: Audio format | |
| **kwargs: Additional options | |
| Returns: | |
| TranscriptionResult if chunk produced results, None otherwise | |
| """ | |
| start_time = datetime.now(timezone.utc) | |
| # Simulate processing delay | |
| await asyncio.sleep(0.05) | |
| # Estimate chunk duration | |
| chunk_duration = len(audio_chunk) / (16000 * 2) | |
| # Simulate interim results (not every chunk produces results) | |
| if len(audio_chunk) < 1000: # Skip very small chunks | |
| return None | |
| # Simulate transcription | |
| interim_results = kwargs.get('interim_results', True) | |
| is_final = len(audio_chunk) > 8000 # Larger chunks are more likely to be final | |
| if interim_results or is_final: | |
| text = f"Streaming chunk {session_id[-4:]}" | |
| confidence = 0.7 if not is_final else 0.85 | |
| processing_time = (datetime.now(timezone.utc) - start_time).total_seconds() | |
| return TranscriptionResult( | |
| text=text, | |
| confidence=confidence, | |
| provider=self.name, | |
| processing_time=processing_time, | |
| audio_duration=chunk_duration, | |
| language=language, | |
| alternatives=[], | |
| word_timestamps=None, | |
| is_final=is_final, | |
| session_id=session_id | |
| ) | |
| return None | |
| async def _update_usage_stats(self, audio_duration: float, processing_time: float) -> None: | |
| """ | |
| Update usage statistics. | |
| Args: | |
| audio_duration: Duration of processed audio | |
| processing_time: Time taken to process | |
| """ | |
| await self._reset_daily_stats_if_needed() | |
| self._usage_stats["requests_today"] += 1 | |
| self._usage_stats["audio_minutes_today"] += audio_duration / 60.0 | |
| logger.debug( | |
| f"Updated usage stats: {self._usage_stats['requests_today']} requests, " | |
| f"{self._usage_stats['audio_minutes_today']:.2f} minutes today" | |
| ) | |
| async def _reset_daily_stats_if_needed(self) -> None: | |
| """Reset daily statistics if a new day has started.""" | |
| current_date = datetime.now(timezone.utc).date() | |
| if current_date > self._usage_stats["last_reset"]: | |
| self._usage_stats["requests_today"] = 0 | |
| self._usage_stats["audio_minutes_today"] = 0.0 | |
| self._usage_stats["last_reset"] = current_date | |
| logger.info("Reset daily usage statistics") | |
| def create_web_speech_provider( | |
| name: str = "web_speech_api", | |
| priority: int = 1, | |
| **config_overrides | |
| ) -> WebSpeechProvider: | |
| """ | |
| Factory function to create a WebSpeechProvider with default configuration. | |
| Args: | |
| name: Provider name | |
| priority: Provider priority (lower = higher priority) | |
| **config_overrides: Configuration overrides | |
| Returns: | |
| Configured WebSpeechProvider instance | |
| """ | |
| default_config = { | |
| "name": name, | |
| "provider_type": ProviderType.WEB_SPEECH_API, | |
| "enabled": True, | |
| "priority": priority, | |
| "free_tier_limits": { | |
| "max_daily_requests": 1000, # Soft limit for monitoring | |
| "max_daily_minutes": 60.0 # Soft limit for monitoring | |
| }, | |
| "rate_limits": { | |
| "requests_per_minute": 60, | |
| "requests_per_hour": 1000 | |
| }, | |
| "supported_formats": WebSpeechProvider.SUPPORTED_FORMATS, | |
| "supported_languages": WebSpeechProvider.SUPPORTED_LANGUAGES, | |
| "cost_per_minute": 0.0, # Free | |
| "api_credentials": {}, # No credentials needed | |
| "endpoint_url": None, # Browser-based | |
| "timeout_seconds": 30, | |
| "max_retries": 2 | |
| } | |
| # Apply overrides | |
| default_config.update(config_overrides) | |
| # Create configuration object | |
| config = ProviderConfig(**default_config) | |
| return WebSpeechProvider(config) |