Elffuss BraidHub

kikocis/online-translator public

feat: improve audio transcription with relaxed thresholds and better word boundary detection
Changeset58b323d668552b1d01e4b9a2ff66231874920d802543a46205c6cd6e0dcae3c5
AuthorKikoCis <kikocisneros@gmail.com> · 2025-06-15 18:01 +02:00
CommitterKikoCis <kikocisneros@gmail.com> · 2025-06-15 18:01 +02:00
Parents276975768aeb

Browse the files at this changeset

12 files changed

modified .gitignore +1 −0
@@ -35,6 +35,7 @@
3535
3636 # Project specific
3737 transcriptions_history/
38+transcription_history/
3839 *.log
3940 *.bak
4041
modified LICENSE +1 −1
@@ -1,6 +1,6 @@
11 MIT License
22
3-Copyright (c) 2024 Online-Translator
3+Copyright (c) 2025 Online-Translator
44
55 Permission is hereby granted, free of charge, to any person obtaining a copy
66 of this software and associated documentation files (the "Software"), to deal
modified main.py +1 −1
@@ -7,7 +7,7 @@
77 The main application file for Online-Translator, handling the core functionality
88 of audio transcription and translation with MLX models.
99
10-Copyright (c) 2024 Kiko Cisneros
10+Copyright (c) 2025 Kiko Cisneros
1111 Licensed under the MIT License (see LICENSE file for details)
1212 """
1313
modified setup_mac_app.py +1 −1
@@ -6,7 +6,7 @@
66 It handles the creation of the .app structure, installation of dependencies,
77 and setup of MLX models.
88
9-Copyright (c) 2024 Kiko Cisneros
9+Copyright (c) 2025 Kiko Cisneros
1010 Licensed under the MIT License (see LICENSE file for details)
1111 """
1212
modified src/app.py +1 −1
@@ -7,7 +7,7 @@
77 Main application module that coordinates all components and handles the core
88 functionality of the Online-Translator application.
99
10-Copyright (c) 2024 Kiko Cisneros
10+Copyright (c) 2025 Kiko Cisneros
1111 Licensed under the MIT License (see LICENSE file for details)
1212 """
1313
modified src/audio_transcriber.py +111 −19
@@ -7,7 +7,7 @@
77 Handles audio capture, processing, and transcription using the Whisper model
88 via MLX. Manages real-time audio streaming and transcription.
99
10-Copyright (c) 2024 Kiko Cisneros
10+Copyright (c) 2025 Kiko Cisneros
1111 Licensed under the MIT License (see LICENSE file for details)
1212 """
1313
@@ -126,6 +126,7 @@
126126
127127 print("🚀 Enhanced real-time transcriber initialized and ready")
128128
129+
129130 def _process_transcribed_text(self, new_text):
130131 """Enhanced text processing with improved concatenation logic"""
131132 with self.text_lock:
@@ -197,6 +198,7 @@
197198 print(f"✂️ Removed 'thanks' at end: '{self.accumulated_text}' -> '{final_text}'")
198199 self.accumulated_text = final_text
199200
201+
200202 if self.accumulated_text.strip():
201203 print(f"✅ Forced processing: {self.accumulated_text}")
202204 if self.sentence_callback:
@@ -303,13 +305,23 @@
303305 initial_min_duration = 0.8 # ✅ BALANCED: Better first chunk for quality
304306
305307 # Enhanced silence detection
306- silence_threshold = 0.003 # ✅ OPTIMIZED: Slightly higher threshold
307- silence_duration_threshold = 0.5 # ✅ ENHANCED: Longer for better pause 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
308311 is_silence_mode = False
309312 silence_start_time = 0
310- buffer_overlap = 0.15 # ✅ ENHANCED: Longer overlap for better word continuity
313+ buffer_overlap = 0.2 # ✅ RELAXED: Balanced overlap
311314 small_buffer = np.array([], dtype=np.float32)
312315
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+
313325 while self.processing_active and not self._shutdown_requested:
314326 try:
315327 # ✅ VERIFICAR SHUTDOWN REQUEST MÁS FRECUENTEMENTE
@@ -356,13 +368,37 @@
356368 time.sleep(0.1)
357369 continue
358370
359- # Enhanced silence detection
371+ # Enhanced silence detection with word boundary awareness
360372 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
361393
362- if not is_silence_mode and is_silence:
394+ if not is_silence_mode and (is_silence or is_word_boundary):
363395 if silence_start_time == 0:
364396 silence_start_time = current_time
365- small_buffer = new_audio[-int(buffer_overlap * self.sample_rate):]
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):]
366402 elif current_time - silence_start_time >= silence_duration_threshold:
367403 is_silence_mode = True
368404 print(f"🔇 Enhanced silence detected ({audio_rms:.4f}) - pausing active transcription")
@@ -373,11 +409,20 @@
373409 print(f"🔊 Sound detected ({audio_rms:.4f}) - resuming enhanced transcription")
374410
375411 if len(small_buffer) > 0:
376- new_audio = np.concatenate([small_buffer, new_audio])
377- small_buffer = np.array([], dtype=np.float32)
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)
378419
379420 if not is_silence_mode and not is_silence:
380- small_buffer = new_audio[-int(buffer_overlap * self.sample_rate):]
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):]
381426
382427 # Enhanced decision logic for processing
383428 should_transcribe = False
@@ -421,6 +466,30 @@
421466 print(f"❌ Enhanced transcription worker error: {e}")
422467 time.sleep(0.5)
423468
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+
424493 def _transcribe_audio_chunk(self, audio_data):
425494 """Enhanced audio transcription with better validation"""
426495 if len(audio_data) < self.sample_rate * 0.6: # Increased minimum duration
@@ -428,6 +497,7 @@
428497
429498 try:
430499 start_time = time.time()
500+ audio_duration = len(audio_data) / self.sample_rate
431501
432502 # ✅ ENHANCED: Better audio validation
433503 if not np.isfinite(audio_data).all():
@@ -443,7 +513,7 @@
443513 except (OverflowError, RuntimeWarning):
444514 audio_rms = 0.0
445515
446- print(f"🎵 Enhanced processing: {len(audio_data)/self.sample_rate:.1f}s, RMS: {audio_rms:.4f}")
516+ print(f"🎵 Enhanced processing: {audio_duration:.1f}s, RMS: {audio_rms:.4f}")
447517
448518 # ✅ ENHANCED: More permissive threshold for quiet audio
449519 if audio_rms < 0.0008: # Slightly higher but still permissive
@@ -459,15 +529,38 @@
459529 audio_data,
460530 path_or_hf_repo=f"mlx-community/whisper-{self.whisper_model_name}-mlx",
461531 language=None, # Auto-detect
462- word_timestamps=False,
463- no_speech_threshold=0.5, # ✅ ENHANCED: More balanced
464- logprob_threshold=-1.2, # ✅ ENHANCED: Better quality balance
465- compression_ratio_threshold=2.8, # ✅ ENHANCED: Better repetition detection
466- condition_on_previous_text=True # Better context
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
467538 )
468539
469540 text = result.get("text", "").strip()
470541
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+
471564 # ✅ ENHANCED: Better corruption detection
472565 if self._is_corrupted_transcription_enhanced(text):
473566 print(f"🚫 Enhanced corruption detection: skipping '{text[:30]}...'")
@@ -480,11 +573,10 @@
480573
481574 if text:
482575 avg_time = sum(self.transcription_times) / len(self.transcription_times)
483- duration = len(audio_data) / self.sample_rate
484- print(f"🎯 Enhanced transcription ({duration:.1f}s): '{text[:50]}{'...' if len(text) > 50 else ''}'")
576+ print(f"🎯 Enhanced transcription ({audio_duration:.1f}s): '{text[:50]}{'...' if len(text) > 50 else ''}'")
485577 print(f"⏱️ Enhanced timing: {transcription_time:.2f}s | Avg: {avg_time:.2f}s")
486578 else:
487- print(f"🔇 Empty enhanced transcription for {len(audio_data)/self.sample_rate:.1f}s audio")
579+ print(f"🔇 Empty enhanced transcription for {audio_duration:.1f}s audio")
488580
489581 return text
490582
modified src/config.py +1 −1
@@ -7,7 +7,7 @@
77 Configuration settings and constants for the Online-Translator application.
88 Includes paths, model settings, and application parameters.
99
10-Copyright (c) 2024 Kiko Cisneros
10+Copyright (c) 2025 Kiko Cisneros
1111 Licensed under the MIT License (see LICENSE file for details)
1212 """
1313
modified src/continuous_buffer.py +7 −3
@@ -7,7 +7,7 @@
77 Manages continuous audio buffer processing for real-time transcription.
88 Handles audio data streaming and buffering for optimal performance.
99
10-Copyright (c) 2024 Kiko Cisneros
10+Copyright (c) 2025 Kiko Cisneros
1111 Licensed under the MIT License (see LICENSE file for details)
1212 """
1313
@@ -25,11 +25,15 @@
2525 self.lock = threading.Lock()
2626
2727 # Transcription overlap management
28- self.overlap_duration = 0.4 # 1 second overlap
28+ self.overlap_duration = 0.4 # ✅ RELAXED: Balanced overlap
2929 self.overlap_samples = int(self.overlap_duration * sample_rate)
3030 self.last_transcribed_position = 0
3131
32- print(f"📊 Continuous buffer initialized: {max_duration}s max, {self.overlap_duration}s overlap")
32+ # Word boundary context
33+ self.word_boundary_context = 0.15 # ✅ RELAXED: Less context needed
34+ self.word_boundary_samples = int(self.word_boundary_context * sample_rate)
35+
36+ print(f"📊 Continuous buffer initialized: {max_duration}s max, {self.overlap_duration}s overlap, {self.word_boundary_context}s word boundary context")
3337
3438 def add_audio(self, audio_chunk):
3539 """Add new audio to the continuous buffer"""
modified src/history_manager.py +1 −1
@@ -7,7 +7,7 @@
77 Manages transcription and translation history for the Online-Translator application.
88 Handles storage, retrieval, and export of historical data.
99
10-Copyright (c) 2024 Kiko Cisneros
10+Copyright (c) 2025 Kiko Cisneros
1111 Licensed under the MIT License (see LICENSE file for details)
1212 """
1313
modified src/lightweight_llm.py +1 −1
@@ -7,7 +7,7 @@
77 Provides lightweight language model functionality for semantic validation
88 and text processing in the Online-Translator application.
99
10-Copyright (c) 2024 Kiko Cisneros
10+Copyright (c) 2025 Kiko Cisneros
1111 Licensed under the MIT License (see LICENSE file for details)
1212 """
1313
modified src/translator.py +1 −1
@@ -7,7 +7,7 @@
77 Handles text translation functionality for the Online-Translator application.
88 Provides translation services using MLX models and manages translation context.
99
10-Copyright (c) 2024 Kiko Cisneros
10+Copyright (c) 2025 Kiko Cisneros
1111 Licensed under the MIT License (see LICENSE file for details)
1212 """
1313
modified src/ui_components.py +1 −1
@@ -7,7 +7,7 @@
77 User interface components and widgets for the Online-Translator application.
88 Includes floating subtitle window, controls, and settings interface.
99
10-Copyright (c) 2024 Kiko Cisneros
10+Copyright (c) 2025 Kiko Cisneros
1111 Licensed under the MIT License (see LICENSE file for details)
1212 """
1313