Elffuss BraidHub

kikocis/online-translator public

main ยท 21.6 KiBRawPermalink
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3
4"""
5UI Components Module
6-------------------
7User interface components and widgets for the Online-Translator application.
8Includes floating subtitle window, controls, and settings interface.
9
10Copyright (c) 2025 Kiko Cisneros
11Licensed under the MIT License (see LICENSE file for details)
12"""
13
14import tkinter as tk
15from tkinter import ttk, messagebox
16from datetime import datetime
17from . import config
18
19
20class HistoryWindow:
21 """Separate window for viewing transcription history"""
22
23 def __init__(self, history_manager):
24 self.history_manager = history_manager
25 self.window = None
26 self.last_entry_count = 0
27 self.auto_refresh_active = False
28
29 def show(self):
30 """Show the history window"""
31 if self.window and self.window.winfo_exists():
32 self.window.lift()
33 self.window.focus()
34 return
35
36 self.window = tk.Toplevel()
37 self.window.title("Transcription History")
38 self.window.geometry("1000x600")
39 self.window.configure(bg='white')
40
41 # Set window close handler
42 self.window.protocol("WM_DELETE_WINDOW", self.on_window_close)
43
44 # Toolbar
45 toolbar = tk.Frame(self.window, bg='lightgray', relief=tk.RAISED, bd=1)
46 toolbar.pack(fill=tk.X, pady=(0,5))
47
48 # Export buttons
49 self.create_modern_button(toolbar, "๐Ÿ“„ Export TXT", self.export_txt,
50 bg="#4CAF50", fg="black").pack(side=tk.LEFT, padx=2, pady=2)
51 self.create_modern_button(toolbar, "๐Ÿ“Š Export CSV", self.export_csv,
52 bg="#2196F3", fg="black").pack(side=tk.LEFT, padx=2, pady=2)
53 self.create_modern_button(toolbar, "๐Ÿ”— Export JSON", self.export_json,
54 bg="#FF9800", fg="black").pack(side=tk.LEFT, padx=2, pady=2)
55
56 tk.Frame(toolbar, width=20, bg='lightgray').pack(side=tk.LEFT) # Spacer
57
58 self.create_modern_button(toolbar, "๐Ÿ”„ Refresh", self.refresh_history,
59 bg="#607D8B", fg="black").pack(side=tk.LEFT, padx=2, pady=2)
60 self.create_modern_button(toolbar, "๐Ÿ—‘๏ธ Clear All", self.clear_history,
61 bg="#F44336", fg="black").pack(side=tk.LEFT, padx=2, pady=2)
62
63 # Auto-refresh toggle
64 self.auto_refresh_var = tk.BooleanVar(value=True)
65 auto_refresh_check = tk.Checkbutton(toolbar, text="Auto-refresh", variable=self.auto_refresh_var,
66 bg='lightgray', fg='black', font=('Arial', 9))
67 auto_refresh_check.pack(side=tk.LEFT, padx=10)
68
69 # Stats
70 stats_frame = tk.Frame(toolbar, bg='lightgray')
71 stats_frame.pack(side=tk.RIGHT, padx=10)
72
73 self.stats_label = tk.Label(stats_frame, bg='lightgray', fg='black', font=('Arial', 9))
74 self.stats_label.pack()
75
76 # Create notebook for different views
77 self.notebook = ttk.Notebook(self.window)
78 self.notebook.pack(fill=tk.BOTH, expand=True, padx=5, pady=2)
79
80 # Tab 1: Two-column table view
81 self.table_frame = tk.Frame(self.notebook)
82 self.notebook.add(self.table_frame, text="๐Ÿ“Š Table View")
83
84 # Tab 2: Transcriptions only
85 self.transcription_frame = tk.Frame(self.notebook)
86 self.notebook.add(self.transcription_frame, text="๐ŸŽค Transcriptions")
87
88 # Tab 3: Translations only
89 self.translation_frame = tk.Frame(self.notebook)
90 self.notebook.add(self.translation_frame, text="๐ŸŒ Translations")
91
92 self.setup_table_view()
93 self.setup_transcription_view()
94 self.setup_translation_view()
95
96 self.refresh_history()
97 self.start_auto_refresh()
98
99 def setup_table_view(self):
100 """Setup the two-column table view"""
101 # Create Treeview for two-column display
102 columns = ('time', 'languages', 'transcription', 'translation')
103 self.tree = ttk.Treeview(self.table_frame, columns=columns, show='headings', height=20)
104
105 # Define column headings
106 self.tree.heading('time', text='Time')
107 self.tree.heading('languages', text='Languages')
108 self.tree.heading('transcription', text='Original Text')
109 self.tree.heading('translation', text='Translation')
110
111 # Configure column widths and alignment
112 self.tree.column('time', width=70, minwidth=70, anchor='center')
113 self.tree.column('languages', width=90, minwidth=80, anchor='center')
114 self.tree.column('transcription', width=350, minwidth=250, anchor='w')
115 self.tree.column('translation', width=350, minwidth=250, anchor='w')
116
117 # Scrollbars for table
118 v_scrollbar_table = ttk.Scrollbar(self.table_frame, orient=tk.VERTICAL, command=self.tree.yview)
119 h_scrollbar_table = ttk.Scrollbar(self.table_frame, orient=tk.HORIZONTAL, command=self.tree.xview)
120 self.tree.configure(yscrollcommand=v_scrollbar_table.set, xscrollcommand=h_scrollbar_table.set)
121
122 # Pack treeview and scrollbars
123 self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
124 v_scrollbar_table.pack(side=tk.RIGHT, fill=tk.Y)
125 h_scrollbar_table.pack(side=tk.BOTTOM, fill=tk.X)
126
127 # Style the treeview with larger row height to accommodate longer text
128 style = ttk.Style()
129 style.configure("Treeview", font=('Arial', 10), rowheight=60) # Increased row height
130 style.configure("Treeview.Heading", font=('Arial', 10, 'bold'))
131
132 # Alternating row colors
133 self.tree.tag_configure('oddrow', background='#f0f0f0')
134 self.tree.tag_configure('evenrow', background='white')
135
136 # Add tooltip functionality for long text
137 self.create_tooltip_bindings()
138
139 def create_tooltip_bindings(self):
140 """Add tooltip functionality to show full text on hover"""
141 def show_tooltip(event):
142 # Get the item under cursor
143 item = self.tree.identify('item', event.x, event.y)
144 if item:
145 # Get the column
146 column = self.tree.identify('column', event.x, event.y)
147 if column in ['#3', '#4']: # transcription or translation columns
148 values = self.tree.item(item, 'values')
149 if column == '#3' and len(values) > 2:
150 text = values[2] # transcription
151 elif column == '#4' and len(values) > 3:
152 text = values[3] # translation
153 else:
154 return
155
156 # Show tooltip if text is long
157 if len(text) > 50:
158 self.create_tooltip(event.x_root, event.y_root, text)
159
160 def hide_tooltip(event):
161 if hasattr(self, 'tooltip_window') and self.tooltip_window:
162 self.tooltip_window.destroy()
163 self.tooltip_window = None
164
165 self.tree.bind('<Motion>', show_tooltip)
166 self.tree.bind('<Leave>', hide_tooltip)
167 self.tooltip_window = None
168
169 def create_tooltip(self, x, y, text):
170 """Create a tooltip window with the full text"""
171 if hasattr(self, 'tooltip_window') and self.tooltip_window:
172 self.tooltip_window.destroy()
173
174 self.tooltip_window = tk.Toplevel(self.window)
175 self.tooltip_window.wm_overrideredirect(True)
176 self.tooltip_window.wm_geometry(f"+{x+10}+{y+10}")
177
178 # Create wrapped text label
179 label = tk.Label(self.tooltip_window, text=text, justify='left',
180 background='#ffffe0', relief='solid', borderwidth=1,
181 font=('Arial', 9), wraplength=400, padx=5, pady=3)
182 label.pack()
183
184 # Auto-hide after 3 seconds
185 self.window.after(3000, lambda: self.hide_tooltip_delayed())
186
187 def hide_tooltip_delayed(self):
188 """Hide tooltip after delay"""
189 if hasattr(self, 'tooltip_window') and self.tooltip_window:
190 self.tooltip_window.destroy()
191 self.tooltip_window = None
192
193 def setup_transcription_view(self):
194 """Setup the transcriptions-only text view"""
195 self.transcription_text = tk.Text(self.transcription_frame, wrap=tk.WORD, font=('Arial', 11))
196 transcription_scrollbar = ttk.Scrollbar(self.transcription_frame, orient=tk.VERTICAL,
197 command=self.transcription_text.yview)
198 self.transcription_text.configure(yscrollcommand=transcription_scrollbar.set)
199
200 self.transcription_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
201 transcription_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
202
203 # Configure text tags for styling
204 self.transcription_text.tag_configure("timestamp", foreground="#666666", font=('Arial', 9))
205 self.transcription_text.tag_configure("transcription", foreground="#000000", font=('Arial', 11))
206 self.transcription_text.tag_configure("separator", foreground="#CCCCCC")
207
208 def setup_translation_view(self):
209 """Setup the translations-only text view"""
210 self.translation_text = tk.Text(self.translation_frame, wrap=tk.WORD, font=('Arial', 11))
211 translation_scrollbar = ttk.Scrollbar(self.translation_frame, orient=tk.VERTICAL,
212 command=self.translation_text.yview)
213 self.translation_text.configure(yscrollcommand=translation_scrollbar.set)
214
215 self.translation_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
216 translation_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
217
218 # Configure text tags for styling
219 self.translation_text.tag_configure("timestamp", foreground="#666666", font=('Arial', 9))
220 self.translation_text.tag_configure("translation", foreground="#0066CC", font=('Arial', 11, 'bold'))
221 self.translation_text.tag_configure("separator", foreground="#CCCCCC")
222
223 def start_auto_refresh(self):
224 """Start auto-refresh timer"""
225 self.auto_refresh_active = True
226 self.check_for_updates()
227
228 def check_for_updates(self):
229 """Check for new entries and refresh if needed"""
230 if self.window and self.window.winfo_exists() and self.auto_refresh_active:
231 current_count = len(self.history_manager.entries)
232 if current_count != self.last_entry_count and self.auto_refresh_var.get():
233 self.refresh_history()
234 self.last_entry_count = current_count
235
236 # Schedule next check
237 self.window.after(1000, self.check_for_updates) # Check every second
238
239 def on_window_close(self):
240 """Handle window close event"""
241 self.auto_refresh_active = False
242 self.window.destroy()
243
244 def refresh_history(self):
245 """Refresh the history display in all views"""
246 # Clear existing entries from all views
247 for item in self.tree.get_children():
248 self.tree.delete(item)
249 self.transcription_text.delete(1.0, tk.END)
250 self.translation_text.delete(1.0, tk.END)
251
252 if not self.history_manager.entries:
253 # Empty state for all views
254 self.tree.insert('', 'end', values=("", "", "No transcriptions yet.", "Start recording to see your transcriptions here!"))
255 self.transcription_text.insert(tk.END, "No transcriptions yet.\nStart recording to see your transcriptions here!")
256 self.translation_text.insert(tk.END, "No translations yet.\nStart recording to see your translations here!")
257 self.stats_label.config(text="0 entries")
258 return
259
260 # Update stats
261 total_entries = len(self.history_manager.entries)
262 total_words = sum(len(entry['original_text'].split()) + len(entry['translated_text'].split())
263 for entry in self.history_manager.entries)
264 self.stats_label.config(text=f"{total_entries} entries โ€ข {total_words} words")
265
266 # Populate all views
267 for i, entry in enumerate(self.history_manager.entries, 1):
268 timestamp = datetime.fromisoformat(entry['timestamp']).strftime('%H:%M:%S')
269 lang_info = f"{entry['source_language']} โ†’ {entry['target_language']}"
270
271 # Table view (now shows full text without truncation)
272 original_text = entry['original_text']
273 translated_text = entry['translated_text']
274
275 # Apply text wrapping for better display in table cells
276 original_text = self.wrap_text_for_table(original_text, 45)
277 translated_text = self.wrap_text_for_table(translated_text, 45)
278
279 tag = 'evenrow' if i % 2 == 0 else 'oddrow'
280 self.tree.insert('', 'end', values=(timestamp, lang_info, original_text, translated_text), tags=(tag,))
281
282 # Transcriptions-only view
283 self.transcription_text.insert(tk.END, f"#{i} - {timestamp} ({lang_info})\n", "timestamp")
284 self.transcription_text.insert(tk.END, f"{entry['original_text']}\n", "transcription")
285 self.transcription_text.insert(tk.END, "โ”€" * 60 + "\n\n", "separator")
286
287 # Translations-only view
288 self.translation_text.insert(tk.END, f"#{i} - {timestamp} ({lang_info})\n", "timestamp")
289 self.translation_text.insert(tk.END, f"{entry['translated_text']}\n", "translation")
290 self.translation_text.insert(tk.END, "โ”€" * 60 + "\n\n", "separator")
291
292 # Auto-scroll all views to bottom (most recent)
293 if self.tree.get_children():
294 last_item = self.tree.get_children()[-1]
295 self.tree.see(last_item)
296
297 self.transcription_text.see(tk.END)
298 self.translation_text.see(tk.END)
299
300 self.last_entry_count = len(self.history_manager.entries)
301
302 def create_modern_button(self, parent, text, command, bg="#4CAF50", fg="black", width=None):
303 """Create a modern-styled button"""
304 button = tk.Button(
305 parent,
306 text=text,
307 command=command,
308 bg=bg,
309 fg=fg,
310 font=('Arial', 9, 'bold'),
311 relief=tk.FLAT,
312 cursor="hand2",
313 pady=4,
314 padx=8,
315 borderwidth=0
316 )
317 if width:
318 button.config(width=width)
319
320 # Hover effects
321 def on_enter(e):
322 button.config(bg=self.lighten_color(bg))
323 def on_leave(e):
324 button.config(bg=bg)
325
326 button.bind("<Enter>", on_enter)
327 button.bind("<Leave>", on_leave)
328
329 return button
330
331 def lighten_color(self, color):
332 """Lighten a hex color for hover effect"""
333 if color.startswith('#'):
334 color_map = {
335 "#66BB6A": "#81C784", # Light Green
336 "#FF6B6B": "#FF8A80", # Light Red
337 "#4FC3F7": "#81D4FA", # Light Blue
338 "#BA68C8": "#CE93D8", # Light Purple
339 "#90A4AE": "#B0BEC5", # Light Blue Grey
340 "#B0BEC5": "#CFD8DC", # Lighter Grey
341 "#757575": "#9E9E9E", # Light Grey
342 "#4CAF50": "#66BB6A", # Green (original)
343 "#2196F3": "#42A5F5", # Blue (original)
344 "#FF9800": "#FFB74D", # Orange (original)
345 "#607D8B": "#78909C", # Blue Grey (original)
346 "#F44336": "#EF5350" # Red (original)
347 }
348 return color_map.get(color, color)
349 return color
350
351 def export_txt(self):
352 self.history_manager.export_txt()
353 self.refresh_history()
354
355 def export_csv(self):
356 self.history_manager.export_csv()
357 self.refresh_history()
358
359 def export_json(self):
360 self.history_manager.export_json()
361 self.refresh_history()
362
363 def clear_history(self):
364 if messagebox.askyesno("Clear History", "Are you sure you want to clear all transcription history?"):
365 self.history_manager.clear_history()
366 self.refresh_history()
367
368 def wrap_text_for_table(self, text, max_length):
369 """Wrap text to fit within a specified maximum length"""
370 words = text.split()
371 wrapped_text = []
372 current_line = ""
373
374 for word in words:
375 if len(current_line) + len(word) + 1 > max_length:
376 wrapped_text.append(current_line.strip())
377 current_line = word
378 else:
379 if current_line:
380 current_line += " " + word
381 else:
382 current_line = word
383
384 if current_line:
385 wrapped_text.append(current_line.strip())
386
387 return "\n".join(wrapped_text)
388
389
390def create_modern_button(parent, text, command, bg="#4CAF50", fg="black", width=None):
391 """Create a modern-styled button with hover effects"""
392
393 def lighten_color(color):
394 """Lighten a hex color"""
395 color = color.lstrip('#')
396 rgb = tuple(int(color[i:i+2], 16) for i in (0, 2, 4))
397 lightened = tuple(min(255, int(c * 1.2)) for c in rgb)
398 return f"#{lightened[0]:02x}{lightened[1]:02x}{lightened[2]:02x}"
399
400 button = tk.Button(
401 parent,
402 text=text,
403 command=command,
404 bg=bg,
405 fg=fg,
406 activebackground=lighten_color(bg),
407 activeforeground=fg,
408 relief=tk.FLAT,
409 font=('Arial', 9, 'bold'),
410 cursor='hand2',
411 bd=0,
412 padx=10,
413 pady=5
414 )
415
416 if width:
417 button.config(width=width)
418
419 def on_enter(e):
420 button.config(bg=lighten_color(bg))
421
422 def on_leave(e):
423 button.config(bg=bg)
424
425 button.bind("<Enter>", on_enter)
426 button.bind("<Leave>", on_leave)
427
428 return button
429
430
431def create_audio_device_selector(parent, audio_transcriber, on_device_change=None):
432 """Create an audio device selection dropdown (compact version)"""
433 frame = tk.Frame(parent, bg=parent.cget('bg'))
434
435 # Compact label
436 label = tk.Label(frame, text="๐ŸŽค",
437 bg=frame.cget('bg'), fg='black',
438 font=('Arial', 9, 'bold'))
439 label.pack(side=tk.LEFT, padx=(0, 2))
440
441 # Get available devices
442 devices = audio_transcriber.get_audio_devices()
443 device_names = [device['name'] for device in devices]
444
445 # Create device type indicators (more compact)
446 device_display_names = []
447 for device in devices:
448 if device['is_microphone']:
449 device_display_names.append(f"๐ŸŽค {device['name'][:15]}...") # Truncate long names
450 elif device['is_system_audio']:
451 device_display_names.append(f"๐Ÿ”Š {device['name'][:15]}...")
452 else:
453 device_display_names.append(f"๐ŸŽง {device['name'][:15]}...")
454
455 # Compact dropdown
456 device_var = tk.StringVar()
457
458 # Set current selection
459 current_device = audio_transcriber.selected_device
460 if current_device in device_names:
461 idx = device_names.index(current_device)
462 device_var.set(device_display_names[idx])
463 elif device_display_names:
464 device_var.set(device_display_names[0])
465
466 device_dropdown = ttk.Combobox(frame, textvariable=device_var,
467 values=device_display_names,
468 state="readonly", width=20, # More compact width
469 font=('Arial', 8))
470 device_dropdown.pack(side=tk.LEFT, padx=(0, 5))
471
472 def on_device_selected(event=None):
473 """Handle device selection"""
474 selected_display = device_var.get()
475
476 # Find the actual device name
477 for i, display_name in enumerate(device_display_names):
478 if display_name == selected_display:
479 actual_device_name = device_names[i]
480 audio_transcriber.set_audio_device(actual_device_name)
481
482 if on_device_change:
483 on_device_change(actual_device_name)
484 break
485
486 device_dropdown.bind('<<ComboboxSelected>>', on_device_selected)
487
488 # Compact refresh button
489 def refresh_devices():
490 """Refresh the device list"""
491 nonlocal devices, device_names, device_display_names
492
493 devices = audio_transcriber.get_audio_devices()
494 device_names = [device['name'] for device in devices]
495
496 device_display_names = []
497 for device in devices:
498 if device['is_microphone']:
499 device_display_names.append(f"๐ŸŽค {device['name'][:15]}...")
500 elif device['is_system_audio']:
501 device_display_names.append(f"๐Ÿ”Š {device['name'][:15]}...")
502 else:
503 device_display_names.append(f"๐ŸŽง {device['name'][:15]}...")
504
505 device_dropdown['values'] = device_display_names
506
507 # Try to maintain current selection or select first device
508 current_device = audio_transcriber.selected_device
509 if current_device in device_names:
510 idx = device_names.index(current_device)
511 device_var.set(device_display_names[idx])
512 elif device_display_names:
513 device_var.set(device_display_names[0])
514 on_device_selected() # Auto-select first device
515
516 refresh_btn = tk.Button(frame, text="๐Ÿ”„", command=refresh_devices,
517 bg="#607D8B", fg="white", relief=tk.FLAT,
518 font=('Arial', 7, 'bold'), cursor='hand2',
519 bd=0, padx=3, pady=1) # More compact
520 refresh_btn.pack(side=tk.LEFT)
521
522 return frame, device_var, refresh_devices