File size: 33,603 Bytes
8cbe6eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
"""
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)