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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
"""
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)