| 1 | #!/usr/bin/env python3 |
| 2 | # -*- coding: utf-8 -*- |
| 3 | |
| 4 | """ |
| 5 | Online-Translator Application Core |
| 6 | --------------------------------- |
| 7 | Main application module that coordinates all components and handles the core |
| 8 | functionality of the Online-Translator application. |
| 9 | |
| 10 | Copyright (c) 2025 Kiko Cisneros |
| 11 | Licensed under the MIT License (see LICENSE file for details) |
| 12 | """ |
| 13 | |
| 14 | import threading |
| 15 | import queue |
| 16 | import time |
| 17 | import tkinter as tk |
| 18 | from tkinter import ttk, simpledialog, messagebox |
| 19 | import sys |
| 20 | import signal |
| 21 | import atexit |
| 22 | from collections import deque |
| 23 | import numpy as np |
| 24 | |
| 25 | # Import configuration |
| 26 | try: |
| 27 | from . import config |
| 28 | except ImportError: |
| 29 | print("Warning: config.py not found, using default settings") |
| 30 | sys.exit(1) |
| 31 | |
| 32 | # Import our modules |
| 33 | from .history_manager import TranscriptionHistory |
| 34 | from .audio_transcriber import RealTimeTranscriber |
| 35 | from .translator import TextTranslator |
| 36 | from .ui_components import HistoryWindow, create_modern_button, create_audio_device_selector |
| 37 | |
| 38 | # MLX imports |
| 39 | try: |
| 40 | import mlx.core as mx |
| 41 | except ImportError as e: |
| 42 | print(f"Error importing MLX: {e}") |
| 43 | print("Please install MLX dependencies: pip install mlx mlx-whisper mlx-lm") |
| 44 | sys.exit(1) |
| 45 | |
| 46 | |
| 47 | class FloatingSubtitles: |
| 48 | """Main application class for Online-Translator floating subtitles""" |
| 49 | |
| 50 | def __init__(self): |
| 51 | self.root = tk.Tk() |
| 52 | |
| 53 | # Language settings - Initialize before UI setup |
| 54 | self.source_language = tk.StringVar(value=config.DEFAULT_SOURCE_LANGUAGE) |
| 55 | self.target_language = tk.StringVar(value=config.DEFAULT_TARGET_LANGUAGE) |
| 56 | |
| 57 | print("🔧 Initializing Online-Translator components...") |
| 58 | |
| 59 | # Initialize components |
| 60 | self.history_manager = TranscriptionHistory() |
| 61 | print("✅ History manager initialized") |
| 62 | |
| 63 | self.history_window = HistoryWindow(self.history_manager) |
| 64 | print("✅ History window initialized") |
| 65 | |
| 66 | self.translator = TextTranslator() |
| 67 | print("✅ Translator initialized") |
| 68 | |
| 69 | # Initialize real-time transcriber with integrated LLM validation |
| 70 | print("🎤 Initializing real-time transcriber with LLM validation...") |
| 71 | print("⚡ Fast startup mode - LLM will load on first transcription") |
| 72 | try: |
| 73 | self.transcriber = RealTimeTranscriber( |
| 74 | sentence_callback=self.on_sentence_complete, |
| 75 | accumulated_text_callback=self.on_accumulated_text_update, |
| 76 | preload_llm=False |
| 77 | ) |
| 78 | print("✅ Real-time transcriber initialized - ready to start!") |
| 79 | except Exception as e: |
| 80 | print(f"❌ Error initializing real-time transcriber: {e}") |
| 81 | import traceback |
| 82 | traceback.print_exc() |
| 83 | return |
| 84 | |
| 85 | # Variables para mantener historial reciente en pantalla |
| 86 | self.recent_transcriptions = [] # Últimas 3-4 transcripciones |
| 87 | self.recent_translations = [] # Últimas 3-4 traducciones |
| 88 | self.max_recent_items = 3 # Máximo de elementos recientes a mostrar |
| 89 | self.current_accumulated_text = "" # Current text being accumulated |
| 90 | |
| 91 | # Workflow timing statistics |
| 92 | self.workflow_times = deque(maxlen=20) # End-to-end times |
| 93 | self.workflow_start_times = {} # Track start times for each text |
| 94 | self.total_workflows = 0 |
| 95 | |
| 96 | print("🖼️ Setting up window...") |
| 97 | self.setup_window() |
| 98 | print("✅ Window setup complete") |
| 99 | |
| 100 | print("🎨 Setting up UI...") |
| 101 | self.setup_ui() |
| 102 | print("✅ UI setup complete") |
| 103 | |
| 104 | # Transcription variables |
| 105 | self.is_running = False |
| 106 | |
| 107 | print("🚀 Online-Translator initialization complete!") |
| 108 | |
| 109 | # Auto-start transcription after UI is ready |
| 110 | self.root.after(100, self.start_transcription) |
| 111 | |
| 112 | def setup_window(self): |
| 113 | """Configure the floating window""" |
| 114 | self.root.title("Online-Translator - Live") |
| 115 | self.root.attributes('-topmost', True) # Always on top |
| 116 | self.root.attributes('-alpha', config.WINDOW_OPACITY) # Semi-transparent |
| 117 | |
| 118 | # Remove window decorations for a cleaner look |
| 119 | self.root.overrideredirect(True) |
| 120 | |
| 121 | # Position at bottom of screen |
| 122 | screen_width = self.root.winfo_screenwidth() |
| 123 | screen_height = self.root.winfo_screenheight() |
| 124 | |
| 125 | window_width = int(screen_width * config.WINDOW_WIDTH_RATIO) |
| 126 | window_height = config.WINDOW_HEIGHT |
| 127 | x = (screen_width - window_width) // 2 |
| 128 | y = screen_height - window_height - config.WINDOW_POSITION_Y_OFFSET |
| 129 | |
| 130 | self.root.geometry(f"{window_width}x{window_height}+{x}+{y}") |
| 131 | self.root.configure(bg=config.BACKGROUND_COLOR) |
| 132 | |
| 133 | def setup_ui(self): |
| 134 | """Setup the user interface""" |
| 135 | print(" 📱 Creating main frame...") |
| 136 | # Main frame |
| 137 | main_frame = tk.Frame(self.root, bg=config.BACKGROUND_COLOR) |
| 138 | main_frame.pack(fill=tk.BOTH, expand=True) |
| 139 | |
| 140 | print(" 📺 Creating subtitle frame...") |
| 141 | # Subtitle display en la parte superior |
| 142 | subtitle_frame = tk.Frame(main_frame, bg=config.BACKGROUND_COLOR) |
| 143 | subtitle_frame.pack(fill=tk.BOTH, expand=True, padx=8, pady=(8,2)) |
| 144 | |
| 145 | # Audio level meter (hidden by default) |
| 146 | self.meter_frame = tk.Frame(subtitle_frame, bg=config.BACKGROUND_COLOR) |
| 147 | self.audio_meter_visible = False # Hidden by default |
| 148 | |
| 149 | tk.Label(self.meter_frame, text="Audio Level:", fg=config.LABEL_COLOR, bg=config.BACKGROUND_COLOR, |
| 150 | font=config.LABEL_FONT).pack(side=tk.LEFT) |
| 151 | |
| 152 | # Volume meter canvas |
| 153 | self.volume_canvas = tk.Canvas(self.meter_frame, height=20, bg='black', highlightthickness=1, |
| 154 | highlightbackground='gray') |
| 155 | self.volume_canvas.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(10,0)) |
| 156 | |
| 157 | # Volume level text |
| 158 | self.volume_text = tk.Label(self.meter_frame, text="0.0%", fg=config.LABEL_COLOR, bg=config.BACKGROUND_COLOR, |
| 159 | font=config.LABEL_FONT, width=6) |
| 160 | self.volume_text.pack(side=tk.LEFT, padx=(5,0)) |
| 161 | |
| 162 | # Crear contenedor de dos columnas para subtítulos |
| 163 | columns_frame = tk.Frame(subtitle_frame, bg=config.BACKGROUND_COLOR) |
| 164 | columns_frame.pack(fill=tk.BOTH, expand=True, pady=(5,0)) |
| 165 | |
| 166 | # Calcular ancho disponible para las columnas |
| 167 | screen_width = self.root.winfo_screenwidth() |
| 168 | window_width = int(screen_width * config.WINDOW_WIDTH_RATIO) |
| 169 | available_width = window_width - 24 |
| 170 | column_width = available_width // 2 |
| 171 | |
| 172 | # Columna izquierda - Solo texto transcrito |
| 173 | left_column = tk.Frame(columns_frame, bg=config.BACKGROUND_COLOR, relief=tk.SOLID, bd=1, width=column_width) |
| 174 | left_column.pack(side=tk.LEFT, fill=tk.Y, padx=(0,2)) |
| 175 | left_column.pack_propagate(False) |
| 176 | |
| 177 | # Texto transcrito actual |
| 178 | self.original_text = tk.Label(left_column, text="", fg=config.ORIGINAL_TEXT_COLOR, bg=config.BACKGROUND_COLOR, |
| 179 | font=config.ORIGINAL_TEXT_FONT, wraplength=column_width-16, justify=tk.LEFT, anchor='nw') |
| 180 | self.original_text.pack(fill=tk.BOTH, expand=True, padx=2, pady=(0,2), anchor='w') |
| 181 | |
| 182 | # Columna derecha - Solo texto traducido |
| 183 | right_column = tk.Frame(columns_frame, bg=config.BACKGROUND_COLOR, relief=tk.SOLID, bd=1, width=column_width) |
| 184 | right_column.pack(side=tk.LEFT, fill=tk.Y, padx=(2,0)) |
| 185 | right_column.pack_propagate(False) |
| 186 | |
| 187 | # Texto traducido actual |
| 188 | self.translated_text = tk.Label(right_column, text="", fg=config.TRANSLATED_TEXT_COLOR, bg=config.BACKGROUND_COLOR, |
| 189 | font=config.TRANSLATED_TEXT_FONT, wraplength=column_width-16, justify=tk.LEFT, anchor='nw') |
| 190 | self.translated_text.pack(fill=tk.BOTH, expand=True, padx=2, pady=(0,2), anchor='w') |
| 191 | |
| 192 | print(" 🎛️ Creating footer control bar...") |
| 193 | # Barra de footer más estrecha |
| 194 | footer_frame = tk.Frame(main_frame, bg='#2b2b2b', relief=tk.RAISED, bd=1, height=35) |
| 195 | footer_frame.pack(fill=tk.X, side=tk.BOTTOM, padx=0, pady=0) |
| 196 | footer_frame.pack_propagate(False) |
| 197 | |
| 198 | # Contenedor interior con padding reducido |
| 199 | footer_content = tk.Frame(footer_frame, bg='#2b2b2b') |
| 200 | footer_content.pack(fill=tk.X, padx=6, pady=3) |
| 201 | |
| 202 | print(" 🎤 Creating audio device selector...") |
| 203 | # Audio device selector |
| 204 | try: |
| 205 | self.audio_device_frame, self.device_var, self.refresh_devices = create_audio_device_selector( |
| 206 | footer_content, self.transcriber, on_device_change=self.on_audio_device_change |
| 207 | ) |
| 208 | self.audio_device_frame.pack(side=tk.LEFT, padx=(0, 8)) |
| 209 | print(" ✅ Audio device selector created") |
| 210 | except Exception as e: |
| 211 | print(f" ❌ Error creating audio device selector: {e}") |
| 212 | import traceback |
| 213 | traceback.print_exc() |
| 214 | raise |
| 215 | |
| 216 | print(" 🌐 Creating language selection...") |
| 217 | # Language selection |
| 218 | lang_frame = tk.Frame(footer_content, bg='#2b2b2b') |
| 219 | lang_frame.pack(side=tk.LEFT, padx=(0, 8)) |
| 220 | |
| 221 | # Crear listas de nombres de idiomas para mostrar en UI |
| 222 | source_language_names = [config.LANGUAGE_NAMES.get(code, code) for code in config.SUPPORTED_SOURCE_LANGUAGES] |
| 223 | target_language_names = ["Desactivado"] + [config.LANGUAGE_NAMES.get(code, code) for code in config.SUPPORTED_TARGET_LANGUAGES] |
| 224 | |
| 225 | tk.Label(lang_frame, text="🎤", fg=config.LABEL_COLOR, bg='#2b2b2b', font=config.LABEL_FONT).pack(side=tk.LEFT) |
| 226 | self.source_combo = ttk.Combobox(lang_frame, values=source_language_names, width=8, state="readonly") |
| 227 | initial_source_name = config.LANGUAGE_NAMES.get(config.DEFAULT_SOURCE_LANGUAGE, config.DEFAULT_SOURCE_LANGUAGE) |
| 228 | self.source_combo.set(initial_source_name) |
| 229 | self.source_combo.pack(side=tk.LEFT, padx=(2,5)) |
| 230 | |
| 231 | tk.Label(lang_frame, text="🌐", fg=config.LABEL_COLOR, bg='#2b2b2b', font=config.LABEL_FONT).pack(side=tk.LEFT) |
| 232 | self.target_combo = ttk.Combobox(lang_frame, values=target_language_names, width=8, state="readonly") |
| 233 | initial_target_name = config.LANGUAGE_NAMES.get(config.DEFAULT_TARGET_LANGUAGE, config.DEFAULT_TARGET_LANGUAGE) |
| 234 | self.target_combo.set(initial_target_name) |
| 235 | self.target_combo.pack(side=tk.LEFT, padx=(2,0)) |
| 236 | |
| 237 | # Bind de eventos para actualizar variables internas cuando cambian los combos |
| 238 | self.source_combo.bind('<<ComboboxSelected>>', self.on_source_language_change) |
| 239 | self.target_combo.bind('<<ComboboxSelected>>', self.on_target_language_change) |
| 240 | |
| 241 | # Spacer para centrar botones principales |
| 242 | spacer = tk.Frame(footer_content, bg='#2b2b2b') |
| 243 | spacer.pack(side=tk.LEFT, fill=tk.X, expand=True) |
| 244 | |
| 245 | print(" 🎛️ Creating main control buttons...") |
| 246 | # Botones principales centrados |
| 247 | main_controls_frame = tk.Frame(footer_content, bg='#2b2b2b') |
| 248 | main_controls_frame.pack(side=tk.LEFT) |
| 249 | |
| 250 | try: |
| 251 | self.play_pause_button = create_modern_button(main_controls_frame, "⏸️", self.toggle_transcription, bg='#66BB6A', fg='black') |
| 252 | self.play_pause_button.pack(side=tk.LEFT, padx=2) |
| 253 | print(" ✅ Play/pause button created") |
| 254 | |
| 255 | create_modern_button(main_controls_frame, "📋", self.show_history, bg='#BA68C8', fg='white').pack(side=tk.LEFT, padx=2) |
| 256 | print(" ✅ History button created") |
| 257 | |
| 258 | # Audio meter toggle button |
| 259 | self.audio_meter_button = create_modern_button(main_controls_frame, "📊", self.toggle_audio_meter, bg='#90A4AE', fg='black') |
| 260 | self.audio_meter_button.pack(side=tk.LEFT, padx=2) |
| 261 | print(" ✅ Audio meter button created") |
| 262 | |
| 263 | except Exception as e: |
| 264 | print(f" ❌ Error creating main control buttons: {e}") |
| 265 | import traceback |
| 266 | traceback.print_exc() |
| 267 | raise |
| 268 | |
| 269 | # Spacer para empujar botones de utilidad a la derecha |
| 270 | spacer2 = tk.Frame(footer_content, bg='#2b2b2b') |
| 271 | spacer2.pack(side=tk.LEFT, fill=tk.X, expand=True) |
| 272 | |
| 273 | print(" 🔧 Creating utility buttons...") |
| 274 | # Botones de utilidad a la derecha |
| 275 | utility_controls_frame = tk.Frame(footer_content, bg='#2b2b2b') |
| 276 | utility_controls_frame.pack(side=tk.RIGHT) |
| 277 | |
| 278 | try: |
| 279 | create_modern_button(utility_controls_frame, "👁️", self.toggle_controls, bg='#B0BEC5', fg='black').pack(side=tk.LEFT, padx=2) |
| 280 | print(" ✅ Toggle controls button created") |
| 281 | |
| 282 | create_modern_button(utility_controls_frame, "❌", self.quit_app, bg='#757575', fg='white').pack(side=tk.LEFT, padx=2) |
| 283 | print(" ✅ Quit button created") |
| 284 | |
| 285 | except Exception as e: |
| 286 | print(f" ❌ Error creating utility buttons: {e}") |
| 287 | import traceback |
| 288 | traceback.print_exc() |
| 289 | raise |
| 290 | |
| 291 | # Control frame reference para toggle |
| 292 | self.control_frame = footer_frame |
| 293 | self.controls_visible = True |
| 294 | |
| 295 | print("🖱️ Binding events...") |
| 296 | # Bind events |
| 297 | self.root.bind('<Double-Button-1>', lambda e: self.toggle_controls()) |
| 298 | self.root.bind('<Button-1>', self.start_drag) |
| 299 | self.root.bind('<B1-Motion>', self.drag_window) |
| 300 | |
| 301 | print(" ✅ UI setup complete - all components created") |
| 302 | |
| 303 | def on_audio_device_change(self, device_name): |
| 304 | """Handle audio device change""" |
| 305 | # Restart recording if currently active |
| 306 | if self.is_running: |
| 307 | self.stop_transcription() |
| 308 | self.root.after(500, self.start_transcription) # Small delay before restart |
| 309 | |
| 310 | print(f"🔄 Audio device changed to: {device_name}") |
| 311 | |
| 312 | def toggle_audio_meter(self): |
| 313 | """Toggle audio meter visibility""" |
| 314 | if self.audio_meter_visible: |
| 315 | self.meter_frame.pack_forget() |
| 316 | self.audio_meter_button.config(text="📊") |
| 317 | else: |
| 318 | # Buscar el subtitle_frame para insertar el meter |
| 319 | subtitle_frame = self.original_text.master.master.master # columna -> columns_frame -> subtitle_frame |
| 320 | self.meter_frame.pack(fill=tk.X, pady=(0,10), in_=subtitle_frame, before=subtitle_frame.winfo_children()[1]) |
| 321 | self.audio_meter_button.config(text="📊 Hide") |
| 322 | self.audio_meter_visible = not self.audio_meter_visible |
| 323 | |
| 324 | def show_history(self): |
| 325 | """Show the transcription history window""" |
| 326 | self.history_window.show() |
| 327 | |
| 328 | def start_drag(self, event): |
| 329 | """Start dragging the window""" |
| 330 | self.drag_start_x = event.x |
| 331 | self.drag_start_y = event.y |
| 332 | |
| 333 | def drag_window(self, event): |
| 334 | """Drag the window""" |
| 335 | x = self.root.winfo_x() + event.x - self.drag_start_x |
| 336 | y = self.root.winfo_y() + event.y - self.drag_start_y |
| 337 | self.root.geometry(f"+{x}+{y}") |
| 338 | |
| 339 | def toggle_controls(self): |
| 340 | """Toggle control panel visibility""" |
| 341 | if self.controls_visible: |
| 342 | self.control_frame.pack_forget() |
| 343 | # Ajustar altura cuando se ocultan los controles (menos la altura del footer estrecho) |
| 344 | self.root.geometry(f"{self.root.winfo_width()}x{config.WINDOW_HEIGHT - 35}") |
| 345 | else: |
| 346 | self.control_frame.pack(fill=tk.X, side=tk.BOTTOM, padx=0, pady=0) |
| 347 | # Restaurar altura completa |
| 348 | self.root.geometry(f"{self.root.winfo_width()}x{config.WINDOW_HEIGHT}") |
| 349 | self.controls_visible = not self.controls_visible |
| 350 | |
| 351 | def toggle_transcription(self): |
| 352 | """Toggle between start and stop transcription""" |
| 353 | if self.is_running: |
| 354 | self.stop_transcription() |
| 355 | else: |
| 356 | self.start_transcription() |
| 357 | |
| 358 | def start_transcription(self): |
| 359 | """Start real-time transcription with continuous buffer processing""" |
| 360 | print("🎯 Starting real-time transcription with LLM validation...") |
| 361 | |
| 362 | if not self.is_running: |
| 363 | self.is_running = True |
| 364 | |
| 365 | try: |
| 366 | # Start new continuous transcription system |
| 367 | print("🧵 Starting continuous transcription (LLM will load on first use)...") |
| 368 | self.transcriber.start_continuous_transcription() |
| 369 | print("✅ Continuous transcription started - ready to process audio!") |
| 370 | |
| 371 | # Start volume meter updates (using the new transcriber's audio buffer) |
| 372 | self.root.after(100, self.update_volume_meter) |
| 373 | |
| 374 | # Update button to show pause icon |
| 375 | self.play_pause_button.config(text="⏸️", bg='#FF6B6B') |
| 376 | |
| 377 | print("🎉 Real-time transcription active! First LLM validation may take a few seconds.") |
| 378 | |
| 379 | except Exception as e: |
| 380 | print(f"❌ Error during transcription startup: {e}") |
| 381 | import traceback |
| 382 | traceback.print_exc() |
| 383 | self.is_running = False |
| 384 | |
| 385 | def on_sentence_complete(self, complete_sentence): |
| 386 | """Callback when a complete sentence is ready (after LLM validation)""" |
| 387 | # Record workflow start time |
| 388 | workflow_start_time = time.time() |
| 389 | self.workflow_start_times[complete_sentence] = workflow_start_time |
| 390 | |
| 391 | print(f"✅ LLM-validated sentence received: '{complete_sentence[:30]}...'") |
| 392 | |
| 393 | # Clear the current accumulated text since it's now a complete sentence |
| 394 | self.current_accumulated_text = "" |
| 395 | |
| 396 | # Add new transcription to recent history |
| 397 | self.recent_transcriptions.append(complete_sentence) |
| 398 | if len(self.recent_transcriptions) > self.max_recent_items: |
| 399 | self.recent_transcriptions.pop(0) |
| 400 | |
| 401 | # Update transcription area (left) |
| 402 | def update_original(): |
| 403 | try: |
| 404 | if hasattr(self, 'original_text') and self.original_text.winfo_exists(): |
| 405 | display_text = "\n\n".join(self.recent_transcriptions) |
| 406 | self.original_text.config(text=display_text) |
| 407 | except tk.TclError: |
| 408 | pass |
| 409 | |
| 410 | self.root.after(0, update_original) |
| 411 | |
| 412 | # Translation mode |
| 413 | target_lang = self.target_language.get() |
| 414 | |
| 415 | if target_lang == "Desactivate": |
| 416 | # Translation disabled |
| 417 | processed_text = "[Translation disabled]" |
| 418 | target_lang_code = "disabled" |
| 419 | else: |
| 420 | # Get previous message as context if available |
| 421 | previous_transcription = None |
| 422 | if len(self.recent_transcriptions) > 1: |
| 423 | previous_transcription = self.recent_transcriptions[-2] |
| 424 | print(f"🔗 Using context from previous message: '{previous_transcription[:20]}...'") |
| 425 | |
| 426 | # Perform translation with context |
| 427 | processed_text = self.translator.translate_text( |
| 428 | complete_sentence, |
| 429 | target_lang, |
| 430 | previous_text=previous_transcription |
| 431 | ) |
| 432 | target_lang_code = target_lang |
| 433 | |
| 434 | print(f"✅ Translation: '{complete_sentence[:30]}...' -> '{processed_text[:30]}...'") |
| 435 | |
| 436 | # Save to history |
| 437 | self.history_manager.add_entry( |
| 438 | original_text=complete_sentence, |
| 439 | translated_text=processed_text, |
| 440 | source_lang=self.source_language.get(), |
| 441 | target_lang=target_lang_code |
| 442 | ) |
| 443 | |
| 444 | # Add processed text to recent translations |
| 445 | self.recent_translations.append(processed_text) |
| 446 | if len(self.recent_translations) > self.max_recent_items: |
| 447 | self.recent_translations.pop(0) |
| 448 | |
| 449 | # Update translation area |
| 450 | def update_translation(): |
| 451 | try: |
| 452 | if hasattr(self, 'translated_text') and self.translated_text.winfo_exists(): |
| 453 | display_text = "\n\n".join(self.recent_translations) |
| 454 | self.translated_text.config(text=display_text) |
| 455 | except tk.TclError: |
| 456 | pass |
| 457 | |
| 458 | self.root.after(0, update_translation) |
| 459 | |
| 460 | # Calculate workflow timing |
| 461 | if complete_sentence in self.workflow_start_times: |
| 462 | workflow_time = time.time() - self.workflow_start_times[complete_sentence] |
| 463 | self.workflow_times.append(workflow_time) |
| 464 | self.total_workflows += 1 |
| 465 | avg_workflow_time = sum(self.workflow_times) / len(self.workflow_times) |
| 466 | |
| 467 | print(f"⏱️ Translation workflow time: {workflow_time:.2f}s | Avg: {avg_workflow_time:.2f}s | Total: {self.total_workflows}") |
| 468 | |
| 469 | # Clean up timing record |
| 470 | del self.workflow_start_times[complete_sentence] |
| 471 | |
| 472 | def stop_transcription(self): |
| 473 | """Stop transcription service - MEJORADO""" |
| 474 | try: |
| 475 | if config.ENABLE_DEBUG_LOGGING: |
| 476 | print("Stopping transcription service...") |
| 477 | |
| 478 | # Stop the transcriber |
| 479 | if hasattr(self, 'transcriber'): |
| 480 | # Si estamos cerrando la app, usar método rápido |
| 481 | if hasattr(self, '_quitting') and self._quitting: |
| 482 | print("🛑 Quick shutdown mode") |
| 483 | self.transcriber._shutdown_requested = True |
| 484 | |
| 485 | self.transcriber.stop_continuous_transcription() |
| 486 | |
| 487 | if config.ENABLE_DEBUG_LOGGING: |
| 488 | print("Transcription service stopped successfully") |
| 489 | |
| 490 | except Exception as e: |
| 491 | if config.ENABLE_DEBUG_LOGGING: |
| 492 | print(f"Error stopping transcription: {e}") |
| 493 | |
| 494 | def run(self): |
| 495 | """Run the application with proper cleanup handlers""" |
| 496 | try: |
| 497 | # Register signal handlers for clean shutdown |
| 498 | signal.signal(signal.SIGINT, self.signal_handler) |
| 499 | signal.signal(signal.SIGTERM, self.signal_handler) |
| 500 | |
| 501 | # Register cleanup function to run on exit |
| 502 | atexit.register(self.cleanup_all_resources) |
| 503 | |
| 504 | # Set window close protocol |
| 505 | try: |
| 506 | self.root.protocol("WM_DELETE_WINDOW", self.quit_app) |
| 507 | except tk.TclError: |
| 508 | # For windows without decorations, bind to window events |
| 509 | self.root.bind('<Destroy>', lambda e: self.quit_app() if e.widget == self.root else None) |
| 510 | |
| 511 | if config.ENABLE_DEBUG_LOGGING: |
| 512 | print("Online-Translator is now running...") |
| 513 | else: |
| 514 | print("🚀 Online-Translator is ready!") |
| 515 | print("💡 Double-click to show/hide controls") |
| 516 | print("🖱️ Drag to move the window") |
| 517 | print("🎯 Audio source will be auto-detected") |
| 518 | |
| 519 | # Start the main loop |
| 520 | self.root.mainloop() |
| 521 | |
| 522 | except KeyboardInterrupt: |
| 523 | if config.ENABLE_DEBUG_LOGGING: |
| 524 | print("\nReceived keyboard interrupt") |
| 525 | self.quit_app() |
| 526 | except Exception as e: |
| 527 | if config.ENABLE_DEBUG_LOGGING: |
| 528 | print(f"Unexpected error in main loop: {e}") |
| 529 | self.quit_app() |
| 530 | finally: |
| 531 | # Ensure cleanup happens |
| 532 | try: |
| 533 | self.cleanup_all_resources() |
| 534 | except Exception as e: |
| 535 | if config.ENABLE_DEBUG_LOGGING: |
| 536 | print(f"Error in final cleanup: {e}") |
| 537 | |
| 538 | def signal_handler(self, signum, frame): |
| 539 | """Handle system signals for clean shutdown""" |
| 540 | try: |
| 541 | if config.ENABLE_DEBUG_LOGGING: |
| 542 | print(f"Received signal {signum}, shutting down...") |
| 543 | self.quit_app() |
| 544 | except Exception as e: |
| 545 | if config.ENABLE_DEBUG_LOGGING: |
| 546 | print(f"Error in signal handler: {e}") |
| 547 | finally: |
| 548 | sys.exit(0) |
| 549 | |
| 550 | def quit_app(self): |
| 551 | """Quit the application with proper cleanup - MEJORADO""" |
| 552 | # Prevenir múltiples llamadas |
| 553 | if hasattr(self, '_quitting') and self._quitting: |
| 554 | return |
| 555 | self._quitting = True |
| 556 | |
| 557 | try: |
| 558 | if config.ENABLE_DEBUG_LOGGING: |
| 559 | print("Starting application shutdown...") |
| 560 | else: |
| 561 | print("👋 Goodbye from Online-Translator!") |
| 562 | |
| 563 | # Detener flag de ejecución |
| 564 | self.is_running = False |
| 565 | |
| 566 | # Stop transcription and translation gracefully |
| 567 | self.stop_transcription() |
| 568 | |
| 569 | # Clean up semaphores and queues |
| 570 | self.cleanup_all_resources() |
| 571 | |
| 572 | if config.ENABLE_DEBUG_LOGGING: |
| 573 | print("Application shutdown complete") |
| 574 | |
| 575 | except Exception as e: |
| 576 | if config.ENABLE_DEBUG_LOGGING: |
| 577 | print(f"Error during shutdown: {e}") |
| 578 | finally: |
| 579 | try: |
| 580 | # Verificar si la ventana aún existe antes de destruir |
| 581 | if hasattr(self, 'root') and self.root.winfo_exists(): |
| 582 | self.root.quit() # Salir del mainloop primero |
| 583 | self.root.destroy() # Después destruir la ventana |
| 584 | except (tk.TclError, AttributeError): |
| 585 | pass # Ignorar errores si la ventana ya fue destruida |
| 586 | |
| 587 | def cleanup_all_resources(self): |
| 588 | """Comprehensive cleanup of all resources and semaphores""" |
| 589 | try: |
| 590 | # Clean up transcriber resources |
| 591 | if hasattr(self, 'transcriber'): |
| 592 | try: |
| 593 | self.transcriber.cleanup_all() |
| 594 | except Exception as e: |
| 595 | if config.ENABLE_DEBUG_LOGGING: |
| 596 | print(f"Error cleaning transcriber: {e}") |
| 597 | |
| 598 | # Clean up MLX cache |
| 599 | try: |
| 600 | mx.clear_cache() |
| 601 | except Exception as e: |
| 602 | if config.ENABLE_DEBUG_LOGGING: |
| 603 | print(f"Error clearing MLX cache: {e}") |
| 604 | |
| 605 | except Exception as e: |
| 606 | if config.ENABLE_DEBUG_LOGGING: |
| 607 | print(f"Error in cleanup_all_resources: {e}") |
| 608 | |
| 609 | def update_volume_meter(self): |
| 610 | """Update the visual volume meter""" |
| 611 | try: |
| 612 | if not hasattr(self, 'volume_canvas') or not self.volume_canvas.winfo_exists(): |
| 613 | return |
| 614 | |
| 615 | # Get current volume level from continuous buffer |
| 616 | volume = 0.0 |
| 617 | if hasattr(self.transcriber, 'continuous_buffer') and self.transcriber.continuous_buffer: |
| 618 | # Calculate RMS from the most recent audio in buffer |
| 619 | with self.transcriber.continuous_buffer.lock: |
| 620 | if len(self.transcriber.continuous_buffer.buffer) > 0: |
| 621 | # Get the most recent 1 second of audio for volume calculation |
| 622 | recent_samples = min(self.transcriber.sample_rate, len(self.transcriber.continuous_buffer.buffer)) |
| 623 | recent_audio = self.transcriber.continuous_buffer.buffer[-recent_samples:] |
| 624 | volume = float(np.sqrt(np.mean(recent_audio.astype(np.float64)**2))) if len(recent_audio) > 0 else 0.0 |
| 625 | |
| 626 | # Convert to percentage (0-100) |
| 627 | volume_percent = min(volume * 1000, 100) # Scale factor for visibility |
| 628 | |
| 629 | # Update text |
| 630 | if hasattr(self, 'volume_text') and self.volume_text.winfo_exists(): |
| 631 | self.volume_text.config(text=f"{volume_percent:.1f}%") |
| 632 | |
| 633 | # Only update visual meter if it's visible |
| 634 | if self.audio_meter_visible: |
| 635 | # Clear canvas |
| 636 | self.volume_canvas.delete("all") |
| 637 | |
| 638 | # Get canvas dimensions |
| 639 | canvas_width = self.volume_canvas.winfo_width() |
| 640 | canvas_height = self.volume_canvas.winfo_height() |
| 641 | |
| 642 | if canvas_width <= 1: # Canvas not ready yet |
| 643 | self.root.after(100, self.update_volume_meter) |
| 644 | return |
| 645 | |
| 646 | # Draw volume bar |
| 647 | bar_width = int((volume_percent / 100) * canvas_width) |
| 648 | |
| 649 | # Color based on volume level |
| 650 | if volume_percent < 10: |
| 651 | color = '#404040' # Dark gray for low volume |
| 652 | elif volume_percent < 30: |
| 653 | color = '#00ff00' # Green for good volume |
| 654 | elif volume_percent < 70: |
| 655 | color = '#ffff00' # Yellow for high volume |
| 656 | else: |
| 657 | color = '#ff0000' # Red for very high volume |
| 658 | |
| 659 | # Draw the volume bar |
| 660 | if bar_width > 0: |
| 661 | self.volume_canvas.create_rectangle(0, 0, bar_width, canvas_height, |
| 662 | fill=color, outline=color) |
| 663 | |
| 664 | # Simplified volume visualization - removed complex history bars |
| 665 | # The continuous buffer provides real-time data without needing separate history |
| 666 | |
| 667 | # Schedule next update |
| 668 | if self.is_running: |
| 669 | self.root.after(50, self.update_volume_meter) # Update every 50ms |
| 670 | |
| 671 | except Exception as e: |
| 672 | if config.ENABLE_DEBUG_LOGGING: |
| 673 | print(f"Volume meter update error: {e}") |
| 674 | # Retry after a short delay |
| 675 | self.root.after(100, self.update_volume_meter) |
| 676 | |
| 677 | def on_source_language_change(self, event): |
| 678 | """Handle change in source language""" |
| 679 | selected_name = self.source_combo.get() |
| 680 | if selected_name: |
| 681 | # Buscar el código correspondiente al nombre seleccionado |
| 682 | for code in config.SUPPORTED_SOURCE_LANGUAGES: |
| 683 | if config.LANGUAGE_NAMES.get(code, code) == selected_name: |
| 684 | self.source_language.set(code) |
| 685 | print(f"🎤 Source language changed to: {selected_name} ({code})") |
| 686 | break |
| 687 | |
| 688 | def on_target_language_change(self, event): |
| 689 | """Handle change in target language""" |
| 690 | selected_name = self.target_combo.get() |
| 691 | if selected_name: |
| 692 | if selected_name == "Desactivado": |
| 693 | self.target_language.set("Desactivate") |
| 694 | print(f"🌐 Target language disabled") |
| 695 | else: |
| 696 | # Buscar el código correspondiente al nombre seleccionado |
| 697 | for code in config.SUPPORTED_TARGET_LANGUAGES: |
| 698 | if config.LANGUAGE_NAMES.get(code, code) == selected_name: |
| 699 | self.target_language.set(code) |
| 700 | print(f"🌐 Target language changed to: {selected_name} ({code})") |
| 701 | break |
| 702 | |
| 703 | def on_accumulated_text_update(self, accumulated_text): |
| 704 | """Callback for real-time accumulated text updates (before LLM validation)""" |
| 705 | self.current_accumulated_text = accumulated_text |
| 706 | |
| 707 | # Update the UI to show the current accumulated text in real-time |
| 708 | def update_live_text(): |
| 709 | try: |
| 710 | if hasattr(self, 'original_text') and self.original_text.winfo_exists(): |
| 711 | # Show recent completed transcriptions + current accumulated text |
| 712 | display_parts = [] |
| 713 | |
| 714 | # Add recent completed transcriptions |
| 715 | if self.recent_transcriptions: |
| 716 | display_parts.extend(self.recent_transcriptions) |
| 717 | |
| 718 | # Add current accumulated text (in progress) |
| 719 | if accumulated_text: |
| 720 | display_parts.append(f"⏳ {accumulated_text}") |
| 721 | |
| 722 | # Join with double line breaks for better readability |
| 723 | display_text = "\n\n".join(display_parts) if display_parts else "" |
| 724 | self.original_text.config(text=display_text) |
| 725 | except tk.TclError: |
| 726 | pass # Widget was destroyed |
| 727 | |
| 728 | self.root.after(0, update_live_text) |
| 729 | |
| 730 | |
| 731 | def main(): |
| 732 | """Main function to run Online-Translator with comprehensive error handling""" |
| 733 | app = None |
| 734 | try: |
| 735 | print("🎬 Starting Online-Translator - Live Assistant") |
| 736 | print("❤️ Created with love by Kiko Cisneros for his children") |
| 737 | print("🎤 Audio transcription and translation powered by MLX + ffmpeg") |
| 738 | print("=" * 60) |
| 739 | |
| 740 | # Create and run the application |
| 741 | app = FloatingSubtitles() |
| 742 | |
| 743 | # Set up exception handler for uncaught exceptions |
| 744 | def handle_exception(exc_type, exc_value, exc_traceback): |
| 745 | try: |
| 746 | if config.ENABLE_DEBUG_LOGGING: |
| 747 | print(f"Uncaught exception: {exc_type.__name__}: {exc_value}") |
| 748 | if app: |
| 749 | app.cleanup_all_resources() |
| 750 | except Exception as cleanup_error: |
| 751 | if config.ENABLE_DEBUG_LOGGING: |
| 752 | print(f"Error during exception cleanup: {cleanup_error}") |
| 753 | finally: |
| 754 | sys.exit(1) |
| 755 | |
| 756 | sys.excepthook = handle_exception |
| 757 | |
| 758 | # Run the application |
| 759 | app.run() |
| 760 | |
| 761 | except KeyboardInterrupt: |
| 762 | if config.ENABLE_DEBUG_LOGGING: |
| 763 | print("\nOnline-Translator interrupted by user") |
| 764 | if app: |
| 765 | try: |
| 766 | app.quit_app() |
| 767 | except: |
| 768 | pass |
| 769 | except Exception as e: |
| 770 | if config.ENABLE_DEBUG_LOGGING: |
| 771 | print(f"Unexpected error in Online-Translator main: {e}") |
| 772 | if app: |
| 773 | try: |
| 774 | app.cleanup_all_resources() |
| 775 | except: |
| 776 | pass |
| 777 | finally: |
| 778 | # Final cleanup attempt |
| 779 | if app: |
| 780 | try: |
| 781 | app.cleanup_all_resources() |
| 782 | except Exception as e: |
| 783 | if config.ENABLE_DEBUG_LOGGING: |
| 784 | print(f"Error in final cleanup: {e}") |
| 785 | |
| 786 | # Force cleanup of any remaining MLX resources |
| 787 | try: |
| 788 | mx.clear_cache() |
| 789 | except: |
| 790 | pass |
| 791 | |
| 792 | if config.ENABLE_DEBUG_LOGGING: |
| 793 | print("Online-Translator terminated cleanly") |
| 794 | print("👋 Goodbye from Online-Translator!") |
| 795 | |
| 796 | |
| 797 | if __name__ == "__main__": |
| 798 | main() |