Spaces:
Building
Building
Update stt/stt_google.py
Browse files- stt/stt_google.py +364 -503
stt/stt_google.py
CHANGED
@@ -1,503 +1,364 @@
|
|
1 |
-
"""
|
2 |
-
Google Cloud Speech-to-Text Implementation
|
3 |
-
"""
|
4 |
-
import
|
5 |
-
import
|
6 |
-
from
|
7 |
-
import
|
8 |
-
|
9 |
-
import
|
10 |
-
import
|
11 |
-
import
|
12 |
-
import
|
13 |
-
import
|
14 |
-
from utils.logger import log_info, log_error, log_debug, log_warning
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
self.
|
37 |
-
self.
|
38 |
-
self.
|
39 |
-
self.
|
40 |
-
self.
|
41 |
-
|
42 |
-
|
43 |
-
self.session_id = 0
|
44 |
-
self.
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
self.
|
49 |
-
self.
|
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 |
-
microphone_distance=speech.RecognitionMetadata.MicrophoneDistance.NEARFIELD,
|
366 |
-
recording_device_type=speech.RecognitionMetadata.RecordingDeviceType.PC,
|
367 |
-
)
|
368 |
-
)
|
369 |
-
|
370 |
-
# Create streaming config with VAD
|
371 |
-
self.streaming_config = speech.StreamingRecognitionConfig(
|
372 |
-
config=recognition_config,
|
373 |
-
interim_results=True,
|
374 |
-
single_utterance=False,
|
375 |
-
enable_voice_activity_events=True # β
VAD events enabled
|
376 |
-
)
|
377 |
-
|
378 |
-
self.is_streaming = True
|
379 |
-
self.stop_event.clear()
|
380 |
-
|
381 |
-
# Thread baΕlatmadan ΓΆnce son kontrol
|
382 |
-
if self.stream_thread is not None:
|
383 |
-
log_error("β stream_thread should be None at this point!")
|
384 |
-
self.stream_thread = None
|
385 |
-
|
386 |
-
self.is_streaming = True
|
387 |
-
|
388 |
-
# Start streaming thread with unique ID
|
389 |
-
thread_id = f"GoogleSTT-Session-{self.session_id}-{int(time.time()*1000)}"
|
390 |
-
self.stream_thread = threading.Thread(
|
391 |
-
target=self._run_stream,
|
392 |
-
name=thread_id
|
393 |
-
)
|
394 |
-
self.stream_thread.daemon = True
|
395 |
-
|
396 |
-
log_info(f"π Starting thread: {thread_id}")
|
397 |
-
self.stream_thread.start()
|
398 |
-
|
399 |
-
log_info(f"β
Google STT streaming session #{self.session_id} started successfully")
|
400 |
-
|
401 |
-
except Exception as e:
|
402 |
-
log_error(f"β Failed to start Google STT streaming", error=str(e))
|
403 |
-
self.is_streaming = False
|
404 |
-
self.client = None
|
405 |
-
self._create_fresh_queues()
|
406 |
-
raise
|
407 |
-
|
408 |
-
def _run_stream(self):
|
409 |
-
"""Run the streaming recognition loop in a separate thread"""
|
410 |
-
try:
|
411 |
-
thread_id = threading.current_thread().ident
|
412 |
-
log_info(f"π€ Google STT stream thread started - Thread ID: {thread_id}, Session: {self.session_id}")
|
413 |
-
|
414 |
-
# Create request generator
|
415 |
-
requests = self._request_generator()
|
416 |
-
|
417 |
-
# Create streaming client
|
418 |
-
log_info(f"π€ Creating Google STT streaming client... Thread ID: {thread_id}")
|
419 |
-
|
420 |
-
# Get responses (no timeout parameter!)
|
421 |
-
responses = self.client.streaming_recognize(requests)
|
422 |
-
|
423 |
-
# Track responses
|
424 |
-
first_response_time = None
|
425 |
-
response_count = 0
|
426 |
-
|
427 |
-
# Process responses
|
428 |
-
for response in responses:
|
429 |
-
if self.should_stop:
|
430 |
-
log_info("π Stop flag detected, ending stream")
|
431 |
-
break
|
432 |
-
|
433 |
-
response_count += 1
|
434 |
-
|
435 |
-
if first_response_time is None:
|
436 |
-
first_response_time = time.time()
|
437 |
-
elapsed = first_response_time - self.stream_start_time
|
438 |
-
log_info(f"π FIRST RESPONSE from Google STT after {elapsed:.2f}s")
|
439 |
-
|
440 |
-
# Check for VAD events
|
441 |
-
if hasattr(response, 'speech_event_type') and response.speech_event_type:
|
442 |
-
event_type = response.speech_event_type
|
443 |
-
log_info(f"ποΈ VAD Event: {event_type}")
|
444 |
-
|
445 |
-
if event_type == speech.StreamingRecognizeResponse.SpeechEventType.END_OF_SINGLE_UTTERANCE:
|
446 |
-
log_info("π End of utterance detected by VAD")
|
447 |
-
|
448 |
-
# Log response
|
449 |
-
has_results = len(response.results) > 0 if hasattr(response, 'results') else False
|
450 |
-
log_info(f"π¨ Google STT Response #{response_count}: has_results={has_results}")
|
451 |
-
|
452 |
-
if not response.results:
|
453 |
-
continue
|
454 |
-
|
455 |
-
# Process results
|
456 |
-
for result_idx, result in enumerate(response.results):
|
457 |
-
# Check result type
|
458 |
-
result_type = "π INTERIM" if not result.is_final else "β
FINAL"
|
459 |
-
stability = getattr(result, 'stability', 0.0)
|
460 |
-
|
461 |
-
log_info(f"{result_type} Result #{result_idx}: "
|
462 |
-
f"alternatives={len(result.alternatives)}, "
|
463 |
-
f"stability={stability:.3f}")
|
464 |
-
|
465 |
-
if result.alternatives:
|
466 |
-
best_alternative = result.alternatives[0]
|
467 |
-
transcript = best_alternative.transcript
|
468 |
-
confidence = best_alternative.confidence if result.is_final else stability
|
469 |
-
|
470 |
-
# Log transcript
|
471 |
-
if result.is_final:
|
472 |
-
log_info(f"β
FINAL TRANSCRIPT: '{transcript}' "
|
473 |
-
f"(confidence: {confidence:.3f})")
|
474 |
-
else:
|
475 |
-
log_info(f"π INTERIM TRANSCRIPT: '{transcript[:100]}...' "
|
476 |
-
f"(stability: {stability:.3f})")
|
477 |
-
|
478 |
-
# Queue result
|
479 |
-
result_obj = TranscriptionResult(
|
480 |
-
text=transcript,
|
481 |
-
is_final=result.is_final,
|
482 |
-
confidence=confidence,
|
483 |
-
timestamp=datetime.utcnow()
|
484 |
-
)
|
485 |
-
|
486 |
-
self.responses_queue.put(result_obj)
|
487 |
-
log_info(f"π₯ {'FINAL' if result.is_final else 'INTERIM'} result queued")
|
488 |
-
|
489 |
-
# Log completion
|
490 |
-
if response_count == 0:
|
491 |
-
log_error("β Google STT stream ended without ANY responses!")
|
492 |
-
else:
|
493 |
-
log_info(f"β
Google STT stream ended normally after {response_count} responses")
|
494 |
-
|
495 |
-
except Exception as e:
|
496 |
-
log_error(f"β Google STT error: {e}")
|
497 |
-
if hasattr(e, 'details'):
|
498 |
-
log_error(f"Error details: {e.details}")
|
499 |
-
self.error_message = str(e)
|
500 |
-
finally:
|
501 |
-
log_info("π€ Google STT stream thread ended")
|
502 |
-
with self.lock:
|
503 |
-
self.is_streaming = False
|
|
|
1 |
+
"""
|
2 |
+
Google Cloud Speech-to-Text Implementation
|
3 |
+
"""
|
4 |
+
import asyncio
|
5 |
+
from typing import AsyncIterator, Optional, List, Any
|
6 |
+
from datetime import datetime
|
7 |
+
import queue
|
8 |
+
import threading
|
9 |
+
import traceback
|
10 |
+
import os
|
11 |
+
from google.cloud import speech
|
12 |
+
from google.cloud.speech import RecognitionConfig, StreamingRecognitionConfig
|
13 |
+
import google.auth
|
14 |
+
from utils.logger import log_info, log_error, log_debug, log_warning
|
15 |
+
from .stt_interface import STTInterface, STTConfig, TranscriptionResult
|
16 |
+
|
17 |
+
class GoogleSTT(STTInterface):
|
18 |
+
"""Google Cloud Speech-to-Text implementation"""
|
19 |
+
def __init__(self, credentials_path: Optional[str] = None):
|
20 |
+
"""
|
21 |
+
Initialize Google STT
|
22 |
+
Args:
|
23 |
+
credentials_path: Path to service account JSON file (optional if using default credentials)
|
24 |
+
"""
|
25 |
+
try:
|
26 |
+
# Initialize client
|
27 |
+
if credentials_path:
|
28 |
+
self.client = speech.SpeechClient.from_service_account_file(credentials_path)
|
29 |
+
log_info(f"β
Google STT initialized with service account: {credentials_path}")
|
30 |
+
else:
|
31 |
+
# Use default credentials (ADC)
|
32 |
+
self.client = speech.SpeechClient()
|
33 |
+
log_info("β
Google STT initialized with default credentials")
|
34 |
+
|
35 |
+
# Streaming state
|
36 |
+
self.is_streaming = False
|
37 |
+
self.audio_generator = None
|
38 |
+
self.responses_stream = None
|
39 |
+
self.audio_queue = queue.Queue()
|
40 |
+
self.results_queue = queue.Queue(maxsize=100)
|
41 |
+
|
42 |
+
# Session tracking
|
43 |
+
self.session_id = 0
|
44 |
+
self.total_audio_bytes = 0
|
45 |
+
self.total_chunks = 0
|
46 |
+
|
47 |
+
# Threading
|
48 |
+
self.stream_thread = None
|
49 |
+
self.stop_event = threading.Event()
|
50 |
+
|
51 |
+
except Exception as e:
|
52 |
+
log_error(f"β Failed to initialize Google STT: {str(e)}")
|
53 |
+
raise
|
54 |
+
|
55 |
+
def _map_language_code(self, language: str) -> str:
|
56 |
+
"""Map language codes to Google format"""
|
57 |
+
# Google uses BCP-47 language codes
|
58 |
+
language_map = {
|
59 |
+
"tr-TR": "tr-TR",
|
60 |
+
"en-US": "en-US",
|
61 |
+
"en-GB": "en-GB",
|
62 |
+
"de-DE": "de-DE",
|
63 |
+
"fr-FR": "fr-FR",
|
64 |
+
"es-ES": "es-ES",
|
65 |
+
"it-IT": "it-IT",
|
66 |
+
"pt-BR": "pt-BR",
|
67 |
+
"ru-RU": "ru-RU",
|
68 |
+
"ja-JP": "ja-JP",
|
69 |
+
"ko-KR": "ko-KR",
|
70 |
+
"zh-CN": "zh-CN",
|
71 |
+
"ar-SA": "ar-SA",
|
72 |
+
}
|
73 |
+
return language_map.get(language, language)
|
74 |
+
|
75 |
+
async def start_streaming(self, config: STTConfig) -> None:
|
76 |
+
"""Initialize streaming session"""
|
77 |
+
try:
|
78 |
+
# Stop any existing stream
|
79 |
+
if self.is_streaming:
|
80 |
+
log_warning("β οΈ Previous stream still active, stopping it first")
|
81 |
+
await self.stop_streaming()
|
82 |
+
await asyncio.sleep(0.5)
|
83 |
+
|
84 |
+
# Reset session data
|
85 |
+
self._reset_session_data()
|
86 |
+
|
87 |
+
log_info(f"π€ Starting Google STT - Session #{self.session_id}")
|
88 |
+
|
89 |
+
# Configure recognition settings
|
90 |
+
language_code = self._map_language_code(config.language)
|
91 |
+
|
92 |
+
# β
Google STT best practices for Turkish and single utterance
|
93 |
+
recognition_config = RecognitionConfig(
|
94 |
+
encoding=RecognitionConfig.AudioEncoding.LINEAR16,
|
95 |
+
sample_rate_hertz=16000,
|
96 |
+
language_code=language_code,
|
97 |
+
# β
Single utterance iΓ§in ideal ayarlar
|
98 |
+
enable_automatic_punctuation=True,
|
99 |
+
# Model selection - latest_long for better accuracy
|
100 |
+
model="latest_long",
|
101 |
+
# Use enhanced model if available (better for Turkish)
|
102 |
+
use_enhanced=True,
|
103 |
+
# Single channel audio
|
104 |
+
audio_channel_count=1,
|
105 |
+
# Boost adaptation for better Turkish recognition
|
106 |
+
speech_contexts=[
|
107 |
+
speech.SpeechContext(
|
108 |
+
phrases=[], # BoΕ bΔ±rakΔ±yoruz ama context var
|
109 |
+
boost=20.0
|
110 |
+
)
|
111 |
+
],
|
112 |
+
# Alternative transcripts for debugging
|
113 |
+
max_alternatives=1,
|
114 |
+
# Profanity filter disabled for accuracy
|
115 |
+
profanity_filter=False,
|
116 |
+
# Enable speaker diarization if needed
|
117 |
+
enable_speaker_diarization=False,
|
118 |
+
# Word level confidence
|
119 |
+
enable_word_confidence=False,
|
120 |
+
enable_spoken_punctuation=False,
|
121 |
+
enable_spoken_emojis=False,
|
122 |
+
)
|
123 |
+
|
124 |
+
# β
Streaming config - optimized for final results only
|
125 |
+
self.streaming_config = StreamingRecognitionConfig(
|
126 |
+
config=recognition_config,
|
127 |
+
# β
Single utterance mode - stops after detecting speech end
|
128 |
+
single_utterance=True,
|
129 |
+
# β
No interim results - only final
|
130 |
+
interim_results=False
|
131 |
+
)
|
132 |
+
|
133 |
+
log_info(f"π§ Google STT config: language={language_code}, "
|
134 |
+
f"model=latest_long, enhanced=True, "
|
135 |
+
f"single_utterance=True, interim_results=False")
|
136 |
+
|
137 |
+
# Start streaming in background thread
|
138 |
+
self.stop_event.clear()
|
139 |
+
self.stream_thread = threading.Thread(
|
140 |
+
target=self._stream_recognition,
|
141 |
+
daemon=True
|
142 |
+
)
|
143 |
+
self.stream_thread.start()
|
144 |
+
|
145 |
+
self.is_streaming = True
|
146 |
+
log_info(f"β
Google STT started - Ready for speech")
|
147 |
+
|
148 |
+
except Exception as e:
|
149 |
+
log_error(f"β Failed to start Google STT", error=str(e))
|
150 |
+
self.is_streaming = False
|
151 |
+
raise
|
152 |
+
|
153 |
+
def _stream_recognition(self):
|
154 |
+
"""Background thread for streaming recognition"""
|
155 |
+
try:
|
156 |
+
log_debug("ποΈ Starting recognition stream thread")
|
157 |
+
|
158 |
+
# Create audio generator
|
159 |
+
audio_generator = self._audio_generator()
|
160 |
+
|
161 |
+
# Start streaming recognition
|
162 |
+
responses = self.client.streaming_recognize(
|
163 |
+
self.streaming_config,
|
164 |
+
audio_generator
|
165 |
+
)
|
166 |
+
|
167 |
+
# Process responses
|
168 |
+
for response in responses:
|
169 |
+
if self.stop_event.is_set():
|
170 |
+
break
|
171 |
+
|
172 |
+
if not response.results:
|
173 |
+
continue
|
174 |
+
|
175 |
+
# Process each result
|
176 |
+
for result in response.results:
|
177 |
+
if not result.alternatives:
|
178 |
+
continue
|
179 |
+
|
180 |
+
# Get best alternative
|
181 |
+
alternative = result.alternatives[0]
|
182 |
+
|
183 |
+
# Only process if we have transcript
|
184 |
+
if alternative.transcript:
|
185 |
+
transcription_result = TranscriptionResult(
|
186 |
+
text=alternative.transcript,
|
187 |
+
is_final=result.is_final,
|
188 |
+
confidence=alternative.confidence,
|
189 |
+
timestamp=datetime.now().timestamp()
|
190 |
+
)
|
191 |
+
|
192 |
+
try:
|
193 |
+
self.results_queue.put(transcription_result)
|
194 |
+
|
195 |
+
if result.is_final:
|
196 |
+
log_info(f"π― FINAL TRANSCRIPT: '{alternative.transcript}' "
|
197 |
+
f"(confidence: {alternative.confidence:.2f})")
|
198 |
+
# Single utterance mode will end stream after this
|
199 |
+
break
|
200 |
+
else:
|
201 |
+
# This shouldn't happen with interim_results=False
|
202 |
+
log_debug(f"π Transcript: '{alternative.transcript}'")
|
203 |
+
|
204 |
+
except queue.Full:
|
205 |
+
log_warning("β οΈ Results queue full")
|
206 |
+
|
207 |
+
# Check if stream ended due to single_utterance
|
208 |
+
if hasattr(response, 'speech_event_type'):
|
209 |
+
if response.speech_event_type == speech.StreamingRecognizeResponse.SpeechEventType.END_OF_SINGLE_UTTERANCE:
|
210 |
+
log_info("π End of single utterance detected")
|
211 |
+
break
|
212 |
+
|
213 |
+
except Exception as e:
|
214 |
+
if not self.stop_event.is_set():
|
215 |
+
log_error(f"β Recognition stream error: {str(e)}")
|
216 |
+
# Put error in queue
|
217 |
+
error_result = TranscriptionResult(
|
218 |
+
text="",
|
219 |
+
is_final=True,
|
220 |
+
confidence=0.0,
|
221 |
+
timestamp=datetime.now().timestamp()
|
222 |
+
)
|
223 |
+
self.results_queue.put(error_result)
|
224 |
+
finally:
|
225 |
+
log_debug("ποΈ Recognition stream thread ended")
|
226 |
+
self.is_streaming = False
|
227 |
+
|
228 |
+
def _audio_generator(self):
|
229 |
+
"""Generator that yields audio chunks for streaming"""
|
230 |
+
while not self.stop_event.is_set():
|
231 |
+
try:
|
232 |
+
# Get audio chunk with timeout
|
233 |
+
chunk = self.audio_queue.get(timeout=0.1)
|
234 |
+
|
235 |
+
if chunk is None: # Sentinel value
|
236 |
+
break
|
237 |
+
|
238 |
+
yield chunk
|
239 |
+
|
240 |
+
except queue.Empty:
|
241 |
+
continue
|
242 |
+
except Exception as e:
|
243 |
+
log_error(f"β Audio generator error: {str(e)}")
|
244 |
+
break
|
245 |
+
|
246 |
+
async def stream_audio(self, audio_chunk: bytes) -> AsyncIterator[TranscriptionResult]:
|
247 |
+
"""Stream audio chunk and get transcription results"""
|
248 |
+
if not self.is_streaming:
|
249 |
+
raise RuntimeError("Streaming not started. Call start_streaming() first.")
|
250 |
+
|
251 |
+
try:
|
252 |
+
# Add audio to queue for background thread
|
253 |
+
self.audio_queue.put(audio_chunk)
|
254 |
+
|
255 |
+
self.total_chunks += 1
|
256 |
+
self.total_audio_bytes += len(audio_chunk)
|
257 |
+
|
258 |
+
# Log progress
|
259 |
+
if self.total_chunks % 50 == 0:
|
260 |
+
log_debug(f"π Processing... {self.total_chunks} chunks, {self.total_audio_bytes/1024:.1f}KB")
|
261 |
+
|
262 |
+
# Check for results
|
263 |
+
while True:
|
264 |
+
try:
|
265 |
+
result = self.results_queue.get_nowait()
|
266 |
+
|
267 |
+
# Log for debugging
|
268 |
+
log_debug(f"π― Yielding result: is_final={result.is_final}, text='{result.text}'")
|
269 |
+
|
270 |
+
yield result
|
271 |
+
|
272 |
+
# If final result, stream will end
|
273 |
+
if result.is_final:
|
274 |
+
self.is_streaming = False
|
275 |
+
|
276 |
+
except queue.Empty:
|
277 |
+
break
|
278 |
+
|
279 |
+
except Exception as e:
|
280 |
+
log_error(f"β Error streaming audio", error=str(e))
|
281 |
+
self.is_streaming = False
|
282 |
+
raise
|
283 |
+
|
284 |
+
async def stop_streaming(self) -> Optional[TranscriptionResult]:
|
285 |
+
"""Stop streaming and clean up"""
|
286 |
+
if not self.is_streaming:
|
287 |
+
log_debug("Already stopped, nothing to do")
|
288 |
+
return None
|
289 |
+
|
290 |
+
try:
|
291 |
+
log_info(f"π Stopping Google STT session #{self.session_id}")
|
292 |
+
|
293 |
+
self.is_streaming = False
|
294 |
+
|
295 |
+
# Signal stop
|
296 |
+
self.stop_event.set()
|
297 |
+
|
298 |
+
# Send sentinel to audio queue
|
299 |
+
self.audio_queue.put(None)
|
300 |
+
|
301 |
+
# Wait for thread to finish
|
302 |
+
if self.stream_thread and self.stream_thread.is_alive():
|
303 |
+
self.stream_thread.join(timeout=2.0)
|
304 |
+
|
305 |
+
# Get final result if any
|
306 |
+
final_result = None
|
307 |
+
while not self.results_queue.empty():
|
308 |
+
try:
|
309 |
+
result = self.results_queue.get_nowait()
|
310 |
+
if result.is_final and result.text:
|
311 |
+
final_result = result
|
312 |
+
except queue.Empty:
|
313 |
+
break
|
314 |
+
|
315 |
+
log_info(f"β
Google STT session #{self.session_id} stopped")
|
316 |
+
return final_result
|
317 |
+
|
318 |
+
except Exception as e:
|
319 |
+
log_error(f"β Error during stop_streaming", error=str(e))
|
320 |
+
self.is_streaming = False
|
321 |
+
return None
|
322 |
+
|
323 |
+
def _reset_session_data(self):
|
324 |
+
"""Reset session-specific data"""
|
325 |
+
# Clear queues
|
326 |
+
while not self.audio_queue.empty():
|
327 |
+
try:
|
328 |
+
self.audio_queue.get_nowait()
|
329 |
+
except:
|
330 |
+
pass
|
331 |
+
|
332 |
+
while not self.results_queue.empty():
|
333 |
+
try:
|
334 |
+
self.results_queue.get_nowait()
|
335 |
+
except:
|
336 |
+
pass
|
337 |
+
|
338 |
+
# Reset counters
|
339 |
+
self.total_audio_bytes = 0
|
340 |
+
self.total_chunks = 0
|
341 |
+
self.session_id += 1
|
342 |
+
|
343 |
+
log_debug(f"π Session data reset. New session ID: {self.session_id}")
|
344 |
+
|
345 |
+
def supports_realtime(self) -> bool:
|
346 |
+
"""Google STT supports real-time streaming"""
|
347 |
+
return True
|
348 |
+
|
349 |
+
def get_supported_languages(self) -> List[str]:
|
350 |
+
"""Get list of supported language codes"""
|
351 |
+
# Google Cloud Speech-to-Text supported languages (partial list)
|
352 |
+
# Full list: https://cloud.google.com/speech-to-text/docs/languages
|
353 |
+
return [
|
354 |
+
"tr-TR", "en-US", "en-GB", "en-AU", "en-CA", "en-IN",
|
355 |
+
"es-ES", "es-MX", "es-AR", "fr-FR", "fr-CA", "de-DE",
|
356 |
+
"it-IT", "pt-BR", "pt-PT", "ru-RU", "ja-JP", "ko-KR",
|
357 |
+
"zh-CN", "zh-TW", "ar-SA", "ar-EG", "hi-IN", "nl-NL",
|
358 |
+
"pl-PL", "sv-SE", "da-DK", "no-NO", "fi-FI", "el-GR",
|
359 |
+
"he-IL", "th-TH", "vi-VN", "id-ID", "ms-MY", "fil-PH"
|
360 |
+
]
|
361 |
+
|
362 |
+
def get_provider_name(self) -> str:
|
363 |
+
"""Get provider name"""
|
364 |
+
return "google"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|