Elffuss BraidHub

kikocis/online-translator public

main · 51.5 KiBRawPermalink
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3
4"""
5Audio Transcription Module
6-------------------------
7Handles audio capture, processing, and transcription using the Whisper model
8via MLX. Manages real-time audio streaming and transcription.
9
10Copyright (c) 2025 Kiko Cisneros
11Licensed under the MIT License (see LICENSE file for details)
12"""
13
14import threading
15import queue
16import time
17import subprocess
18import numpy as np
19from collections import deque
20import mlx_whisper
21import re
22import tempfile
23import os
24import signal
25from pathlib import Path
26import json
27
28# Handle imports for both module and standalone usage
29try:
30 from . import config
31 from .lightweight_llm import LightweightLLM
32 from .continuous_buffer import ContinuousBuffer
33except ImportError:
34 import config
35 from lightweight_llm import LightweightLLM
36 from continuous_buffer import ContinuousBuffer
37
38
39class RealTimeTranscriber:
40 """Real-time audio transcriber with enhanced text processing"""
41
42 def __init__(self, sentence_callback=None, accumulated_text_callback=None, preload_llm=False):
43 # Audio configuration
44 self.sample_rate = config.AUDIO_SAMPLE_RATE
45 self.chunk_duration = config.AUDIO_CHUNK_DURATION
46 self.chunk_size = int(self.sample_rate * self.chunk_duration)
47
48 # ✅ MEJORAR MANEJO DE SEÑALES PARA CIERRE LIMPIO
49 self._shutdown_requested = False
50 signal.signal(signal.SIGINT, self._signal_handler)
51 signal.signal(signal.SIGTERM, self._signal_handler)
52
53 print("🔐 Verificando permisos (una sola vez)...")
54 # Check permissions first - MEJORADO PARA NO PEDIR SIEMPRE
55 self.has_audio_permissions = check_audio_permissions()
56 self.has_screen_permissions = check_screen_capture_permissions()
57
58 if not self.has_audio_permissions:
59 print("⚠️ Permisos de micrófono requeridos")
60 request_permissions()
61 else:
62 print("✅ Permisos verificados correctamente")
63
64 print("📊 Initializing enhanced continuous buffer...")
65 # Continuous buffer
66 self.continuous_buffer = ContinuousBuffer(self.sample_rate)
67
68 print("🧠 Initializing enhanced LLM for semantic validation...")
69 # Enhanced text processing
70 self.llm = LightweightLLM()
71
72 # ✅ Optional model preloading - only if requested
73 if preload_llm:
74 print("⏳ Pre-loading LLM model (this may take 10-15 seconds)...")
75 try:
76 self._preload_llm_model()
77 print("✅ LLM model pre-loaded and ready!")
78 except Exception as e:
79 print(f"⚠️ LLM preload failed: {e}")
80 print("🔄 Model will load on first use")
81 else:
82 print("⚡ LLM will load on first use (may cause brief delay on first transcription)")
83
84 self.accumulated_text = ""
85 self.sentence_callback = sentence_callback
86 self.accumulated_text_callback = accumulated_text_callback
87 self.text_lock = threading.Lock()
88
89 print("🎵 Setting up audio system...")
90 # ffmpeg audio capture
91 self.ffmpeg_process = None
92 self.is_recording = False
93 self.audio_thread = None
94 self.transcription_thread = None
95 self.processing_active = False
96
97 # Audio device management (after permissions are set)
98 self.audio_devices = self.get_audio_devices()
99 self.selected_device = self.select_best_audio_device()
100
101 # Whisper model
102 self.whisper_model_name = config.WHISPER_MODEL
103 print("🔄 Pre-loading Whisper model...")
104 self.whisper_model_preloaded = False
105 try:
106 start_preload_time = time.time()
107 self._preload_whisper_model()
108 preload_time = time.time() - start_preload_time
109 self.whisper_model_preloaded = True
110 print(f"✅ Whisper model pre-loaded and ready! ({preload_time:.1f}s)")
111 except Exception as e:
112 print(f"⚠️ Whisper preload failed: {e}")
113 print("🔄 Model will load on first use (may cause 15-20s delay)")
114 self.whisper_model_preloaded = False
115
116 # Timing and statistics
117 self.transcription_times = deque(maxlen=20)
118 self.total_transcriptions = 0
119
120 # Enhanced phrase filtering
121 self.phrases_to_ignore = [
122 "gracias", "thank you", "thanks", "thank", "you", "thank's", "thank's you",
123 "gracias.", "thank you.", "thanks.", "thank.", "you.", "thank's.", "thank's you."
124 ]
125 self.recent_transcribed_texts = deque(maxlen=5) # Keep track of recent transcriptions
126
127 print("🚀 Enhanced real-time transcriber initialized and ready")
128
129
130 def _process_transcribed_text(self, new_text):
131 """Enhanced text processing with improved concatenation logic"""
132 with self.text_lock:
133 # ✅ PREVENT repetitive transcription loops
134 if new_text and new_text.strip():
135 # Check if this text is too similar to recent transcriptions
136 new_text_clean = new_text.strip()
137 for recent_text in self.recent_transcribed_texts:
138 if new_text_clean.lower() == recent_text.lower():
139 print(f"🔄 Skipping duplicate transcription: '{new_text_clean[:30]}...'")
140 return # Skip processing duplicate text
141
142 # ✅ FILTER OUT COMMON PHRASES like "Gracias" and "Thank you"
143 if new_text_clean.lower() in self.phrases_to_ignore:
144 print(f"🔇 Ignoring common phrase: '{new_text_clean}'")
145 return # Skip processing ignored phrases
146
147 # Add to recent transcriptions list
148 self.recent_transcribed_texts.append(new_text_clean)
149
150 # ✅ ENHANCED CONCATENATION LOGIC
151 if new_text and new_text.strip():
152 new_text_clean = new_text.strip()
153
154 # 🚫 DETECT WHISPER REPETITIVE LOOPS (known bug)
155 if self.llm._detect_repetitive_transcription(new_text_clean):
156 print(f"🚫 Skipping repetitive Whisper transcription: '{new_text_clean[:50]}...'")
157 return # Skip this transcription entirely
158
159 # 🧮 USE ENHANCED CONCATENATION WITH IMPROVED OVERLAP DETECTION
160 merged_text, is_complete, reason = self.llm.smart_concatenate_with_mahalanobis(
161 self.accumulated_text, new_text_clean
162 )
163
164 # Update accumulated text with the merged result
165 self.accumulated_text = merged_text
166
167 print(f"🔄 Enhanced Merged Text: '{self.accumulated_text}' ({len(self.accumulated_text)} chars) - {reason}")
168
169 # ✅ Real-time UI update with the merged text
170 if self.accumulated_text_callback and self.accumulated_text:
171 self.accumulated_text_callback(self.accumulated_text)
172
173 # 🧮 If system determined the text is complete, process it as a sentence
174 if is_complete:
175 # ✂️ REMOVE "GRACIAS" AND EQUIVALENTS AT END OF SENTENCE
176 final_text = self._remove_thanks_at_end(self.accumulated_text)
177 if final_text != self.accumulated_text:
178 print(f"✂️ Removed 'thanks' at end: '{self.accumulated_text}' -> '{final_text}'")
179 self.accumulated_text = final_text
180
181 print(f"✅ Enhanced Smart Completion: {self.accumulated_text}")
182 if self.sentence_callback:
183 self.sentence_callback(self.accumulated_text.strip())
184 self.accumulated_text = ""
185 # Clear accumulated text in UI when sentence is complete
186 if self.accumulated_text_callback:
187 self.accumulated_text_callback("")
188 return
189 else:
190 print(f"🔇 Empty transcription - keeping current buffer: '{self.accumulated_text}' ({len(self.accumulated_text)} chars)")
191
192 # ✅ ENHANCED SAFETY CHECK: Prevent overly long accumulated text
193 if len(self.accumulated_text) > 400: # Increased from 300 to 400
194 print(f"⚠️ Accumulated text too long ({len(self.accumulated_text)} chars), force processing...")
195
196 final_text = self._remove_thanks_at_end(self.accumulated_text)
197 if final_text != self.accumulated_text:
198 print(f"✂️ Removed 'thanks' at end: '{self.accumulated_text}' -> '{final_text}'")
199 self.accumulated_text = final_text
200
201
202 if self.accumulated_text.strip():
203 print(f"✅ Forced processing: {self.accumulated_text}")
204 if self.sentence_callback:
205 self.sentence_callback(self.accumulated_text.strip())
206 else:
207 print(f"❌ Force processing failed, clearing buffer")
208
209 self.accumulated_text = ""
210 # Clear accumulated text in UI
211 if self.accumulated_text_callback:
212 self.accumulated_text_callback("")
213
214 def _remove_thanks_at_end(self, text):
215 """Remove 'thanks' and equivalents in multiple languages at end of sentence"""
216 if not text:
217 return text
218
219 # List of thanks expressions in multiple languages
220 thanks_expressions = [
221 # Spanish
222 r'(?i)(gracias)\.?$', r'(?i)(muchas gracias)\.?$', r'(?i)(mil gracias)\.?$',
223 # English
224 r'(?i)(thank you)\.?$', r'(?i)(thanks)\.?$', r'(?i)(thank you very much)\.?$',
225 # Italian
226 r'(?i)(grazie)\.?$', r'(?i)(grazie mille)\.?$', r'(?i)(tante grazie)\.?$',
227 # French
228 r'(?i)(merci)\.?$', r'(?i)(merci beaucoup)\.?$',
229 # Portuguese
230 r'(?i)(obrigado)\.?$', r'(?i)(obrigada)\.?$', r'(?i)(muito obrigado)\.?$',
231 # German
232 r'(?i)(danke)\.?$', r'(?i)(vielen dank)\.?$',
233 # Japanese
234 r'(?i)(arigato)\.?$', r'(?i)(arigatou)\.?$', r'(?i)(ありがとう)\.?$',
235 r'(?i)(どうもありがとう)\.?$', r'(?i)(ありがとうございました)\.?$',
236 # Generic for other languages: short expressions at end
237 r'(?i)( (thanks|gracias|grazie|merci|danke|obrigado|arigato))\.?$'
238 ]
239
240 cleaned_text = text
241
242 for pattern in thanks_expressions:
243 # Check if sentence ends with this expression
244 match = re.search(pattern, cleaned_text)
245 if match:
246 # Remove expression from end
247 cleaned_text = cleaned_text[:match.start()].rstrip()
248 break # If we found a pattern, don't keep searching
249
250 return cleaned_text
251
252 def start_continuous_transcription(self):
253 """Start continuous real-time transcription"""
254 if self.is_recording:
255 return
256
257 print("🎵 Starting enhanced continuous transcription...")
258
259 # Start audio recording
260 self.start_recording()
261
262 # Start transcription processing
263 self.processing_active = True
264 self.transcription_thread = threading.Thread(target=self._continuous_transcription_worker, daemon=True)
265 self.transcription_thread.start()
266
267 print("✅ Enhanced continuous transcription active")
268
269 def stop_continuous_transcription(self):
270 """Stop continuous transcription - MEJORADO"""
271 if not self.processing_active:
272 return
273
274 print("🛑 Deteniendo transcripción continua...")
275
276 self.processing_active = False
277
278 # Si es shutdown rápido, no esperar tanto
279 if self._shutdown_requested:
280 timeout = 0.3
281 else:
282 timeout = 1.0
283 self.stop_recording()
284
285 # Wait for transcription thread to finish - TIMEOUT DINÁMICO
286 if self.transcription_thread and self.transcription_thread.is_alive():
287 self.transcription_thread.join(timeout=timeout)
288 if self.transcription_thread.is_alive() and not self._shutdown_requested:
289 print("⚠️ Thread de transcripción no terminó a tiempo")
290
291 # Process any remaining text - SOLO SI NO ES SHUTDOWN
292 if not self._shutdown_requested:
293 self._flush_remaining_text()
294
295 print("✅ Transcripción continua detenida")
296
297 def _continuous_transcription_worker(self):
298 """Enhanced worker thread for continuous transcription processing"""
299 min_audio_duration = 0.4 # ✅ OPTIMIZED: Balanced for quality and responsiveness
300 max_wait_time = 0.6 # ✅ OPTIMIZED: Slightly longer for better sentence formation
301 last_transcription_time = time.time()
302
303 # ✅ ENHANCED: Better initial processing
304 initial_processing_mode = True
305 initial_min_duration = 0.8 # ✅ BALANCED: Better first chunk for quality
306
307 # Enhanced silence detection
308 silence_threshold = 0.01 # ✅ RELAXED: Higher threshold to capture more audio
309 silence_duration_threshold = 0.4 # ✅ RELAXED: Longer silence needed
310 end_of_sentence_silence = 0.8 # ✅ RELAXED: Longer silence for end of sentence
311 is_silence_mode = False
312 silence_start_time = 0
313 buffer_overlap = 0.2 # ✅ RELAXED: Balanced overlap
314 small_buffer = np.array([], dtype=np.float32)
315
316 # Word boundary detection
317 word_boundary_threshold = 0.005 # ✅ RELAXED: Higher threshold
318 min_word_duration = 0.08 # ✅ RELAXED: Shorter minimum word duration
319 word_boundary_buffer = 0.1 # ✅ RELAXED: More buffer around words
320
321 # End of sentence detection
322 end_of_sentence_detected = False
323 end_of_sentence_start_time = 0
324
325 while self.processing_active and not self._shutdown_requested:
326 try:
327 # ✅ VERIFICAR SHUTDOWN REQUEST MÁS FRECUENTEMENTE
328 if self._shutdown_requested or not self.processing_active:
329 print("🛑 Worker thread detectó shutdown request")
330 break
331
332 current_time = time.time()
333
334 # Get new audio for transcription
335 new_audio = self.continuous_buffer.get_new_audio_for_transcription()
336
337 if len(new_audio) == 0:
338 time.sleep(0.05) # ✅ OPTIMIZED: Balanced polling
339 continue
340
341 # Calculate duration and audio level
342 audio_duration = len(new_audio) / self.sample_rate
343
344 # ✅ ENHANCED: Safer RMS calculation
345 try:
346 new_audio_safe = np.clip(new_audio, -1.0, 1.0)
347 audio_rms = np.sqrt(np.mean(new_audio_safe.astype(np.float64)**2))
348
349 if not np.isfinite(audio_rms):
350 audio_rms = 0.0
351
352 except (OverflowError, RuntimeWarning):
353 audio_rms = 0.0
354
355 time_since_last = current_time - last_transcription_time
356
357 # ✅ ENHANCED: Special handling for first transcription
358 if initial_processing_mode and self.total_transcriptions == 0:
359 if audio_duration >= initial_min_duration or time_since_last >= 3.0:
360 print(f"🚀 Processing FIRST audio chunk: {audio_duration:.1f}s")
361 transcribed_text = self._transcribe_audio_chunk(new_audio)
362 self._process_transcribed_text(transcribed_text)
363 last_transcription_time = current_time
364 initial_processing_mode = False
365 print("✅ First transcription complete - switching to enhanced real-time mode")
366 continue
367 else:
368 time.sleep(0.1)
369 continue
370
371 # Enhanced silence detection with word boundary awareness
372 is_silence = audio_rms < silence_threshold
373 is_word_boundary = silence_threshold > audio_rms > word_boundary_threshold
374
375 # ✅ ENHANCED: End of sentence detection
376 if is_silence and not end_of_sentence_detected:
377 if end_of_sentence_start_time == 0:
378 end_of_sentence_start_time = current_time
379 elif current_time - end_of_sentence_start_time >= end_of_sentence_silence:
380 end_of_sentence_detected = True
381 print(f"🔚 End of sentence detected ({audio_rms:.4f}) - processing final chunk")
382 # Process the accumulated audio as a complete sentence
383 if len(new_audio) > 0:
384 transcribed_text = self._transcribe_audio_chunk(new_audio)
385 self._process_transcribed_text(transcribed_text)
386 last_transcription_time = current_time
387 end_of_sentence_detected = False
388 end_of_sentence_start_time = 0
389 continue
390 elif not is_silence:
391 end_of_sentence_detected = False
392 end_of_sentence_start_time = 0
393
394 if not is_silence_mode and (is_silence or is_word_boundary):
395 if silence_start_time == 0:
396 silence_start_time = current_time
397 # Keep more context for word boundaries
398 if is_word_boundary:
399 small_buffer = new_audio[-int((buffer_overlap + word_boundary_buffer) * self.sample_rate):]
400 else:
401 small_buffer = new_audio[-int(buffer_overlap * self.sample_rate):]
402 elif current_time - silence_start_time >= silence_duration_threshold:
403 is_silence_mode = True
404 print(f"🔇 Enhanced silence detected ({audio_rms:.4f}) - pausing active transcription")
405
406 elif is_silence_mode and not is_silence:
407 is_silence_mode = False
408 silence_start_time = 0
409 print(f"🔊 Sound detected ({audio_rms:.4f}) - resuming enhanced transcription")
410
411 if len(small_buffer) > 0:
412 # Add extra context for word boundaries
413 if is_word_boundary:
414 new_audio = np.concatenate([small_buffer, new_audio])
415 small_buffer = np.array([], dtype=np.float32)
416 else:
417 new_audio = np.concatenate([small_buffer, new_audio])
418 small_buffer = np.array([], dtype=np.float32)
419
420 if not is_silence_mode and not is_silence:
421 # Keep more context for word boundaries
422 if is_word_boundary:
423 small_buffer = new_audio[-int((buffer_overlap + word_boundary_buffer) * self.sample_rate):]
424 else:
425 small_buffer = new_audio[-int(buffer_overlap * self.sample_rate):]
426
427 # Enhanced decision logic for processing
428 should_transcribe = False
429
430 if is_silence_mode:
431 should_transcribe = time_since_last >= 1.5 and audio_rms > silence_threshold * 0.5
432 else:
433 should_transcribe = (
434 audio_duration >= min_audio_duration or
435 (audio_duration >= 0.2 and time_since_last >= max_wait_time)
436 )
437
438 if should_transcribe and len(new_audio) > 0:
439 status = "🔄" if not is_silence_mode else "🔈"
440 print(f"{status} Enhanced processing {audio_duration:.1f}s (RMS: {audio_rms:.4f}, gap: {time_since_last:.1f}s)")
441
442 # ✅ ENHANCED: Better chunk size management
443 max_chunk_duration = 6.0 # Increased from 5.0
444 if audio_duration > max_chunk_duration:
445 max_samples = int(max_chunk_duration * self.sample_rate)
446 new_audio = new_audio[-max_samples:]
447 print(f"⚠️ Audio chunk too long, trimmed to {max_chunk_duration}s")
448
449 # Transcribe with enhanced processing
450 transcribed_text = self._transcribe_audio_chunk(new_audio)
451
452 if transcribed_text or transcribed_text == "":
453 self._process_transcribed_text(transcribed_text)
454 last_transcription_time = current_time
455
456 # ✅ ENHANCED: Smarter buffer cleanup
457 if audio_duration > 10.0: # Only clean when buffer is very large
458 overlap_keep_samples = self.continuous_buffer.overlap_samples * 3 # More overlap
459 self.continuous_buffer.clear_transcribed_audio(keep_samples=overlap_keep_samples)
460 print(f"🧹 Enhanced buffer cleanup, kept {overlap_keep_samples/self.sample_rate:.1f}s overlap")
461
462 # ✅ ENHANCED: More responsive sleep
463 time.sleep(0.05) # Balanced polling
464
465 except Exception as e:
466 print(f"❌ Enhanced transcription worker error: {e}")
467 time.sleep(0.5)
468
469 def _validate_transcription_length(self, text, audio_duration):
470 """Validate if the transcription length is reasonable for the audio duration"""
471 if not text:
472 return True
473
474 # Average speaking rate (words per minute)
475 avg_words_per_minute = 150 # Typical speaking rate
476 max_words_per_minute = 350 # ✅ RELAXED: Higher maximum rate
477
478 # Calculate expected word count based on audio duration
479 expected_words = (audio_duration / 60) * avg_words_per_minute
480 max_expected_words = (audio_duration / 60) * max_words_per_minute
481
482 # Count actual words in transcription
483 actual_words = len(text.split())
484
485 # If actual words are significantly more than expected, it's suspicious
486 if actual_words > max_expected_words * 1.5: # ✅ RELAXED: Allow 50% margin
487 print(f"⚠️ Suspicious transcription length: {actual_words} words for {audio_duration:.1f}s audio")
488 print(f" Expected max: {max_expected_words:.1f} words, got {actual_words}")
489 return False
490
491 return True
492
493 def _transcribe_audio_chunk(self, audio_data):
494 """Enhanced audio transcription with better validation"""
495 if len(audio_data) < self.sample_rate * 0.6: # Increased minimum duration
496 return ""
497
498 try:
499 start_time = time.time()
500 audio_duration = len(audio_data) / self.sample_rate
501
502 # ✅ ENHANCED: Better audio validation
503 if not np.isfinite(audio_data).all():
504 print("🚫 Corrupted audio detected, skipping")
505 return ""
506
507 audio_data = np.clip(audio_data, -1.0, 1.0)
508
509 try:
510 audio_rms = np.sqrt(np.mean(audio_data.astype(np.float64)**2))
511 if not np.isfinite(audio_rms):
512 audio_rms = 0.0
513 except (OverflowError, RuntimeWarning):
514 audio_rms = 0.0
515
516 print(f"🎵 Enhanced processing: {audio_duration:.1f}s, RMS: {audio_rms:.4f}")
517
518 # ✅ ENHANCED: More permissive threshold for quiet audio
519 if audio_rms < 0.0008: # Slightly higher but still permissive
520 print("🔇 Audio too quiet for enhanced processing")
521 return ""
522
523 if not hasattr(self, 'whisper_model_preloaded') or not self.whisper_model_preloaded:
524 if self.total_transcriptions == 0:
525 print("⏳ First enhanced transcription - loading Whisper model...")
526
527 # ✅ ENHANCED: Better transcription parameters
528 result = mlx_whisper.transcribe(
529 audio_data,
530 path_or_hf_repo=f"mlx-community/whisper-{self.whisper_model_name}-mlx",
531 language=None, # Auto-detect
532 word_timestamps=True, # Enable word timestamps for better word boundary detection
533 no_speech_threshold=0.6, # ✅ RELAXED: Less sensitive to speech
534 logprob_threshold=-1.2, # ✅ RELAXED: More permissive quality threshold
535 compression_ratio_threshold=2.8, # ✅ RELAXED: More permissive repetition detection
536 condition_on_previous_text=True, # Better context
537 initial_prompt="This is a transcription of speech. Please transcribe accurately." # Help with context
538 )
539
540 text = result.get("text", "").strip()
541
542 # ✅ IMMEDIATE FILTER: Remove CastingWords signature as soon as we get the text
543 text = text.replace("Transcription by CastingWords", "").strip()
544
545 # ✅ ENHANCED: Validate transcription length against audio duration
546 if not self._validate_transcription_length(text, audio_duration):
547 print("🚫 Rejecting transcription due to suspicious length")
548 return ""
549
550 # ✅ ENHANCED: Better word boundary handling
551 if result.get("words"):
552 words = result["words"]
553 if len(words) > 0:
554 # Check if first word is likely incomplete
555 first_word = words[0]
556 if first_word.get("start", 0) < 0.1: # Word starts very early
557 text = text[text.find(" ") + 1:] if " " in text else ""
558
559 # Check if last word is likely incomplete
560 last_word = words[-1]
561 if last_word.get("end", 0) > len(audio_data)/self.sample_rate - 0.1: # Word ends very late
562 text = text.rsplit(" ", 1)[0] if " " in text else ""
563
564 # ✅ ENHANCED: Better corruption detection
565 if self._is_corrupted_transcription_enhanced(text):
566 print(f"🚫 Enhanced corruption detection: skipping '{text[:30]}...'")
567 return ""
568
569 # Record timing
570 transcription_time = time.time() - start_time
571 self.transcription_times.append(transcription_time)
572 self.total_transcriptions += 1
573
574 if text:
575 avg_time = sum(self.transcription_times) / len(self.transcription_times)
576 print(f"🎯 Enhanced transcription ({audio_duration:.1f}s): '{text[:50]}{'...' if len(text) > 50 else ''}'")
577 print(f"⏱️ Enhanced timing: {transcription_time:.2f}s | Avg: {avg_time:.2f}s")
578 else:
579 print(f"🔇 Empty enhanced transcription for {audio_duration:.1f}s audio")
580
581 return text
582
583 except Exception as e:
584 print(f"❌ Enhanced transcription error: {e}")
585 return ""
586
587 def _is_corrupted_transcription_enhanced(self, text):
588 """Enhanced corruption detection for transcriptions"""
589 if not text or len(text.strip()) == 0:
590 return False
591
592 text_clean = text.strip()
593
594 # ✅ ENHANCED CHECK 1: Only punctuation/symbols
595 if len(text_clean) > 3:
596 non_alpha_count = sum(1 for c in text_clean if not c.isalpha() and not c.isspace())
597 alpha_count = sum(1 for c in text_clean if c.isalpha())
598
599 if alpha_count == 0 or (non_alpha_count / len(text_clean)) > 0.75: # More permissive
600 return True
601
602 # ✅ ENHANCED CHECK 2: Excessive character repetition
603 if len(text_clean) > 8:
604 for char in '!?.,;:-_=+':
605 if text_clean.count(char) > len(text_clean) * 0.6: # More permissive
606 return True
607
608 # ✅ ENHANCED CHECK 3: Better corruption patterns
609 corruption_patterns = [
610 r'^[!?.,;:\-_=+\s]+$', # Only punctuation
611 r'(.{1,2})\1{15,}', # Same 1-2 chars repeated 15+ times (more permissive)
612 r'^[0-9!@#$%^&*()_+\-=\[\]{};:\'",.<>?/`~\s]+$' # Only numbers and symbols
613 ]
614
615 for pattern in corruption_patterns:
616 if re.search(pattern, text_clean):
617 return True
618
619 return False
620
621 def _flush_remaining_text(self):
622 """Flush any remaining accumulated text"""
623 with self.text_lock:
624 if self.accumulated_text.strip() and self.sentence_callback:
625 print(f"🔄 Enhanced flushing remaining: {self.accumulated_text}")
626 self.sentence_callback(self.accumulated_text.strip())
627 self.accumulated_text = ""
628
629 def force_preload_models(self):
630 """Force preload all models"""
631 print("🔄 Force pre-loading enhanced models...")
632
633 if not getattr(self, 'whisper_model_preloaded', False):
634 print("📥 Force loading Whisper model...")
635 try:
636 start_time = time.time()
637 self._preload_whisper_model()
638 preload_time = time.time() - start_time
639 self.whisper_model_preloaded = True
640 print(f"✅ Whisper model force-loaded! ({preload_time:.1f}s)")
641 except Exception as e:
642 print(f"❌ Whisper force preload failed: {e}")
643 self.whisper_model_preloaded = False
644 else:
645 print("✅ Whisper model already loaded")
646
647 if not self.llm.model_loaded:
648 print("📥 Force loading enhanced LLM model...")
649 try:
650 self._preload_llm_model()
651 print("✅ Enhanced LLM model force-loaded!")
652 except Exception as e:
653 print(f"⚠️ Enhanced LLM force preload failed: {e}")
654 else:
655 print("✅ Enhanced LLM model already loaded")
656
657 def get_performance_info(self):
658 """Get enhanced performance information"""
659 buffer_info = self.continuous_buffer.get_buffer_info()
660
661 info = {
662 "whisper_model_preloaded": getattr(self, 'whisper_model_preloaded', False),
663 "llm_model_loaded": self.llm.model_loaded,
664 "total_transcriptions": self.total_transcriptions,
665 "is_recording": self.is_recording,
666 "processing_active": self.processing_active,
667 "buffer_info": buffer_info,
668 "avg_transcription_time": sum(self.transcription_times) / len(self.transcription_times) if self.transcription_times else 0,
669 "recent_transcription_times": list(self.transcription_times) if self.transcription_times else []
670 }
671
672 print("📊 Enhanced Performance Information:")
673 print(f" Buffer: {buffer_info['total_duration']:.1f}s / {buffer_info['max_duration']:.1f}s")
674 print(f" Transcriptions: {info['total_transcriptions']}")
675 print(f" Avg time: {info['avg_transcription_time']:.2f}s")
676 print(f" Models loaded: Whisper={info['whisper_model_preloaded']}, LLM={info['llm_model_loaded']}")
677
678 return info
679
680 def _preload_llm_model(self):
681 """Pre-load the LLM model"""
682 try:
683 if self.llm.model_loaded:
684 print(f"🧪 Enhanced LLM model already loaded and ready")
685 return
686
687 print("🔄 Testing enhanced LLM...")
688 import mlx_lm
689
690 simple_prompt = "Hello"
691 response = mlx_lm.generate(
692 self.llm.model,
693 self.llm.tokenizer,
694 prompt=simple_prompt,
695 max_tokens=5,
696 verbose=False
697 )
698
699 print(f"🧪 Enhanced LLM preload successful")
700
701 except Exception as e:
702 print(f"⚠️ Enhanced LLM preload failed: {e}")
703
704 def _preload_whisper_model(self):
705 """Pre-load the Whisper model"""
706 try:
707 print("📥 Loading enhanced Whisper model...")
708
709 test_audio = np.zeros(int(self.sample_rate * 0.5), dtype=np.float32)
710
711 result = mlx_whisper.transcribe(
712 test_audio,
713 path_or_hf_repo=f"mlx-community/whisper-{self.whisper_model_name}-mlx",
714 language="en",
715 word_timestamps=False,
716 no_speech_threshold=0.9,
717 logprob_threshold=-2.0,
718 compression_ratio_threshold=10.0,
719 condition_on_previous_text=False
720 )
721
722 print("🧪 Enhanced Whisper model loaded successfully")
723
724 except Exception as e:
725 print(f"❌ Enhanced Whisper preload failed: {e}")
726 raise
727
728 def start_recording(self):
729 """Start audio recording using ffmpeg"""
730 if self.is_recording:
731 return
732
733 request_permissions()
734
735 if not self.check_ffmpeg_installation():
736 print("❌ ffmpeg not installed. Installing...")
737 if not self.install_ffmpeg():
738 print("❌ Failed to install ffmpeg")
739 return
740
741 ffmpeg_input = self.get_device_ffmpeg_input(self.selected_device)
742
743 cmd = [
744 "ffmpeg", "-y",
745 "-f", "avfoundation",
746 "-i", ffmpeg_input,
747 "-ar", str(self.sample_rate),
748 "-ac", "1",
749 "-acodec", "pcm_f32le",
750 "-f", "wav",
751 "pipe:1"
752 ]
753
754 try:
755 print(f"🎵 Starting enhanced audio capture: {self.selected_device}")
756
757 self.ffmpeg_process = subprocess.Popen(
758 cmd,
759 stdout=subprocess.PIPE,
760 stderr=subprocess.PIPE,
761 preexec_fn=os.setsid
762 )
763
764 self.is_recording = True
765
766 self.audio_thread = threading.Thread(target=self._audio_capture_worker, daemon=True)
767 self.audio_thread.start()
768
769 print("✅ Enhanced audio recording started")
770
771 except Exception as e:
772 print(f"❌ Error starting enhanced audio recording: {e}")
773 self.is_recording = False
774
775 def _audio_capture_worker(self):
776 """Worker thread for capturing audio from ffmpeg"""
777 chunk_size = self.chunk_size * 4
778
779 while self.is_recording and self.ffmpeg_process:
780 try:
781 data = self.ffmpeg_process.stdout.read(chunk_size)
782 if not data:
783 break
784
785 audio_chunk = np.frombuffer(data, dtype=np.float32)
786
787 if len(audio_chunk) > 0:
788 self.continuous_buffer.add_audio(audio_chunk)
789
790 except Exception as e:
791 if self.is_recording:
792 print(f"Enhanced audio capture error: {e}")
793 break
794
795 def stop_recording(self):
796 """Stop audio recording - MEJORADO"""
797 if not self.is_recording:
798 return
799
800 print("🛑 Deteniendo grabación de audio...")
801 self.is_recording = False
802
803 # Si es shutdown rápido, no esperar tanto
804 if self._shutdown_requested:
805 timeout = 0.2
806 else:
807 timeout = 2.0
808
809 if self.ffmpeg_process:
810 try:
811 # Intentar terminación suave primero
812 os.killpg(os.getpgid(self.ffmpeg_process.pid), signal.SIGINT)
813 try:
814 self.ffmpeg_process.wait(timeout=timeout)
815 except subprocess.TimeoutExpired:
816 if not self._shutdown_requested:
817 print("⚠️ FFmpeg no terminó suavemente, forzando...")
818 os.killpg(os.getpgid(self.ffmpeg_process.pid), signal.SIGKILL)
819 self.ffmpeg_process.wait(timeout=0.5)
820 except Exception as e:
821 if not self._shutdown_requested:
822 print(f"⚠️ Error deteniendo ffmpeg: {e}")
823
824 self.ffmpeg_process = None
825
826 # Wait for audio thread - TIMEOUT DINÁMICO
827 if self.audio_thread and self.audio_thread.is_alive():
828 thread_timeout = 0.2 if self._shutdown_requested else 1.0
829 self.audio_thread.join(timeout=thread_timeout)
830 if self.audio_thread.is_alive() and not self._shutdown_requested:
831 print("⚠️ Thread de audio no terminó a tiempo")
832
833 print("✅ Grabación de audio detenida")
834
835 def get_audio_devices(self):
836 """Get available audio input devices using ffmpeg"""
837 devices = []
838 try:
839 result = subprocess.run([
840 "ffmpeg", "-f", "avfoundation", "-list_devices", "true", "-i", ""
841 ], capture_output=True, text=True)
842
843 lines = result.stderr.split('\n')
844 in_audio_devices = False
845 in_video_devices = False
846
847 for line in lines:
848 if '[AVFoundation indev @' in line and 'AVFoundation audio devices:' in line:
849 in_audio_devices = True
850 in_video_devices = False
851 continue
852 elif '[AVFoundation indev @' in line and 'AVFoundation video devices:' in line:
853 in_audio_devices = False
854 in_video_devices = True
855 continue
856
857 if in_audio_devices and '[AVFoundation indev @' in line and '] [' in line and '] ' in line:
858 try:
859 parts = line.split('] [', 1)
860 if len(parts) < 2:
861 continue
862
863 index_and_name = parts[1]
864 index_end = index_and_name.find('] ')
865 if index_end == -1:
866 continue
867
868 device_index_str = index_and_name[:index_end]
869 device_name = index_and_name[index_end + 2:].strip()
870
871 try:
872 device_index = int(device_index_str)
873 except ValueError:
874 continue
875
876 if 'blackhole' in device_name.lower():
877 continue
878
879 device_info = {
880 'name': device_name,
881 'index': device_index,
882 'is_system_audio': self.is_system_audio_device(device_name),
883 'is_microphone': self.is_microphone_device(device_name),
884 'device_type': 'audio'
885 }
886 devices.append(device_info)
887
888 except Exception as e:
889 print(f"Warning: Could not parse audio device line: {line} - {e}")
890 continue
891
892 except Exception as e:
893 print(f"Error getting audio devices: {e}")
894 devices = [
895 {'name': 'Built-in Microphone', 'index': 0, 'is_system_audio': False, 'is_microphone': True, 'device_type': 'audio'}
896 ]
897
898 if hasattr(self, 'has_screen_permissions') and self.has_screen_permissions:
899 native_system_audio = {
900 'name': 'macOS System Audio (Native)',
901 'index': 1,
902 'is_system_audio': True,
903 'is_microphone': False,
904 'device_type': 'native_system_audio'
905 }
906 devices.insert(0, native_system_audio)
907
908 return devices
909
910 def is_system_audio_device(self, device_name):
911 """Check if device is likely a system audio capture device"""
912 system_indicators = [
913 'capture screen', 'pantalla', 'screen capture', 'system audio'
914 ]
915 device_lower = device_name.lower()
916 if 'blackhole' in device_lower:
917 return False
918 return any(indicator in device_lower for indicator in system_indicators)
919
920 def is_microphone_device(self, device_name):
921 """Check if device is likely a microphone"""
922 mic_indicators = ['microphone', 'mic', 'built-in', 'internal', 'usb', 'bluetooth', 'airpods', 'headset', 'micrófono']
923 device_lower = device_name.lower()
924 return any(indicator in device_lower for indicator in mic_indicators)
925
926 def get_device_ffmpeg_input(self, device_name):
927 """Get the correct ffmpeg input format for the device"""
928 device_info = None
929 for device in self.audio_devices:
930 if device['name'] == device_name:
931 device_info = device
932 break
933
934 if device_info and device_info['index'] is not None:
935 if device_info.get('device_type') == 'native_system_audio':
936 return f"none:{device_info['index']}"
937 elif device_info['is_microphone']:
938 return f":{device_info['index']}"
939 else:
940 return f":{device_info['index']}"
941 else:
942 return ":0"
943
944 def check_ffmpeg_installation(self):
945 """Check if ffmpeg is installed"""
946 try:
947 result = subprocess.run(["ffmpeg", "-version"], capture_output=True, text=True)
948 return result.returncode == 0
949 except FileNotFoundError:
950 return False
951
952 def install_ffmpeg(self):
953 """Install ffmpeg using Homebrew"""
954 try:
955 print("📦 Installing ffmpeg using Homebrew...")
956 result = subprocess.run(["brew", "install", "ffmpeg"], capture_output=True, text=True)
957 if result.returncode == 0:
958 print("✅ ffmpeg installed successfully!")
959 return True
960 else:
961 print(f"❌ Error installing ffmpeg: {result.stderr}")
962 return False
963 except Exception as e:
964 print(f"❌ Error installing ffmpeg: {e}")
965 return False
966
967 def select_best_audio_device(self):
968 """Automatically select the best available audio device - MEJORADO"""
969 if not self.audio_devices:
970 print("❌ No audio input devices found!")
971 return "Built-in Microphone"
972
973 print("🔍 Available audio devices:")
974 for i, device in enumerate(self.audio_devices):
975 device_type = "🖥️ Screen" if device.get('device_type') == 'screen_capture' else \
976 "🎵 System Audio" if device.get('device_type') == 'native_system_audio' else \
977 "🔊 System Audio" if device['is_system_audio'] else \
978 "🎤 Microphone" if device['is_microphone'] else "🎧 Audio"
979 print(f" {i}: {device_type} - {device['name']}")
980
981 # ✅ LÓGICA MEJORADA: Priorizar micrófonos para transcripción de voz
982 # 1. Primero buscar micrófonos integrados
983 builtin_mics = [d for d in self.audio_devices if 'built-in' in d['name'].lower() or 'interno' in d['name'].lower() or 'micrófono' in d['name'].lower()]
984 if builtin_mics:
985 device_name = builtin_mics[0]['name']
986 print(f"🎤 Auto-selected built-in microphone: {device_name}")
987 return device_name
988
989 # 2. Después buscar otros micrófonos
990 mic_devices = [d for d in self.audio_devices if d['is_microphone']]
991 if mic_devices:
992 device_name = mic_devices[0]['name']
993 print(f"🎤 Auto-selected microphone: {device_name}")
994 return device_name
995
996 # 3. Solo como última opción, usar audio del sistema (si hay permisos reales)
997 # Verificar si realmente tenemos permisos de screen capture con una prueba más estricta
998 real_screen_permissions = self._test_real_screen_permissions()
999 if real_screen_permissions:
1000 native_audio_devices = [d for d in self.audio_devices if d.get('device_type') == 'native_system_audio']
1001 if native_audio_devices:
1002 device_name = native_audio_devices[0]['name']
1003 print(f"🎵 Auto-selected native system audio: {device_name}")
1004 return device_name
1005
1006 system_audio_devices = [d for d in self.audio_devices if d['is_system_audio'] and d.get('device_type') != 'screen_capture']
1007 if system_audio_devices:
1008 device_name = system_audio_devices[0]['name']
1009 print(f"🔊 Auto-selected system audio: {device_name}")
1010 return device_name
1011
1012 # 4. Fallback a cualquier dispositivo que no sea BlackHole
1013 non_blackhole_devices = [d for d in self.audio_devices if 'blackhole' not in d['name'].lower()]
1014 if non_blackhole_devices:
1015 device_name = non_blackhole_devices[0]['name']
1016 print(f"🎧 Auto-selected fallback audio device: {device_name}")
1017 return device_name
1018
1019 return "Built-in Microphone"
1020
1021 def _test_real_screen_permissions(self):
1022 """Test if we really have screen capture permissions (more strict)"""
1023 try:
1024 # Intentar una operación que realmente requiere screen capture
1025 result = subprocess.run([
1026 "osascript", "-e",
1027 'tell application "System Events" to tell process "Finder" to get name'
1028 ], capture_output=True, text=True, timeout=2)
1029
1030 return result.returncode == 0 and "Finder" in result.stdout
1031 except Exception:
1032 return False
1033
1034 def set_audio_device(self, device_name):
1035 """Set the audio device and restart recording if active"""
1036 print(f"🔄 Cambiando dispositivo de audio a: {device_name}")
1037
1038 # Verificar que el dispositivo existe
1039 device_found = False
1040 for device in self.audio_devices:
1041 if device['name'] == device_name:
1042 device_found = True
1043 break
1044
1045 if not device_found:
1046 print(f"⚠️ Dispositivo '{device_name}' no encontrado")
1047 return False
1048
1049 # Guardar estado de grabación actual
1050 was_recording = self.is_recording
1051
1052 # Detener grabación si está activa
1053 if self.is_recording:
1054 self.stop_recording()
1055
1056 # Actualizar dispositivo seleccionado
1057 self.selected_device = device_name
1058 print(f"✅ Dispositivo de audio actualizado: {device_name}")
1059
1060 # Reiniciar grabación si estaba activa
1061 if was_recording:
1062 self.start_recording()
1063 print(f"🎵 Grabación reiniciada con nuevo dispositivo")
1064
1065 return True
1066
1067 def get_current_audio_device(self):
1068 """Get the currently selected audio device"""
1069 return self.selected_device
1070
1071 def _signal_handler(self, signum, frame):
1072 """Manejo mejorado de señales para cierre limpio"""
1073 if not self._shutdown_requested:
1074 print(f"\n🛑 Recibida señal {signum}, cerrando limpiamente...")
1075 self._shutdown_requested = True
1076
1077 # Detener transcripción primero (más rápido)
1078 if self.processing_active:
1079 print("🛑 Deteniendo transcripción...")
1080 self.processing_active = False
1081
1082 # Detener grabación después
1083 if self.is_recording:
1084 print("🛑 Deteniendo grabación...")
1085 self.is_recording = False
1086
1087 # Dar tiempo mínimo para que los threads vean las señales
1088 time.sleep(0.5)
1089
1090 # Forzar terminación de ffmpeg si sigue corriendo
1091 if self.ffmpeg_process:
1092 try:
1093 os.killpg(os.getpgid(self.ffmpeg_process.pid), signal.SIGTERM)
1094 except:
1095 pass
1096
1097 print("✅ Cierre limpio completado")
1098 # No llamar exit() directamente, dejar que la UI maneje el cierre
1099 return
1100 else:
1101 print("🛑 Forzando cierre...")
1102 exit(1)
1103
1104
1105# ✅ Compatibility aliases
1106AudioTranscriber = RealTimeTranscriber
1107SentenceAccumulator = LightweightLLM
1108
1109
1110def check_audio_permissions():
1111 """Check if the app has microphone permissions - MEJORADO"""
1112 try:
1113 # Método más simple: intentar listar dispositivos de audio
1114 result = subprocess.run([
1115 "ffmpeg", "-f", "avfoundation", "-list_devices", "true", "-i", ""
1116 ], capture_output=True, text=True, timeout=3)
1117
1118 # Si podemos listar dispositivos, probablemente tenemos permisos
1119 if "AVFoundation audio devices:" in result.stderr:
1120 return True
1121
1122 # Fallback: intentar captura muy corta
1123 result = subprocess.run([
1124 "ffmpeg", "-f", "avfoundation", "-i", ":0", "-t", "0.1", "-f", "null", "-"
1125 ], capture_output=True, text=True, timeout=2)
1126
1127 if "Operation not permitted" in result.stderr or "Error opening input device" in result.stderr:
1128 return False
1129 return True
1130 except subprocess.TimeoutExpired:
1131 # Si no hay timeout, probablemente tenemos permisos
1132 return True
1133 except Exception:
1134 # En caso de error, asumir que tenemos permisos (conservador)
1135 return True
1136
1137def check_screen_capture_permissions():
1138 """Check if the app has screen recording permissions - MEJORADO"""
1139 try:
1140 # Método más permisivo - simplemente verificar si el comando existe
1141 result = subprocess.run([
1142 "osascript", "-e", "tell application \"System Events\" to get name"
1143 ], capture_output=True, text=True, timeout=2)
1144
1145 # Si osascript funciona, asumir que tenemos los permisos básicos
1146 return True
1147
1148 except Exception:
1149 # En caso de error, asumir que tenemos permisos (conservador)
1150 return True
1151
1152def request_permissions():
1153 """Request permissions only if really needed - MEJORADO"""
1154 print("🔐 Verificando permisos de macOS...")
1155
1156 # Solo pedir permisos si realmente no los tenemos
1157 if not check_audio_permissions():
1158 print("🎤 Solicitando permisos de micrófono (requerido)...")
1159 subprocess.run([
1160 "osascript", "-e",
1161 'display notification "Online-Translator necesita acceso al micrófono para la transcripción de audio." with title "Permisos requeridos"'
1162 ], capture_output=True)
1163 else:
1164 print("✅ Permisos de micrófono verificados")
1165
1166 if not check_screen_capture_permissions():
1167 print("📺 Permisos de grabación de pantalla no detectados (opcional para audio del sistema)")
1168 else:
1169 print("✅ Permisos de sistema verificados")