-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtranslatorApp.py
More file actions
746 lines (653 loc) · 28.4 KB
/
translatorApp.py
File metadata and controls
746 lines (653 loc) · 28.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
import tkinter as tk
from tkinter import ttk, scrolledtext
from googletrans import Translator, LANGUAGES
import threading
import speech_recognition as sr
import pyttsx3
import json
import os
from datetime import datetime
class TranslatorApp:
def __init__(self, root):
self.root = root
self.root.title("✨ Universal Translator")
# Configure window size and position
window_width = 1000
window_height = 700
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
center_x = int(screen_width/2 - window_width/2)
center_y = int(screen_height/2 - window_height/2)
self.root.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')
# Modern color scheme
self.colors = {
'bg_primary': "#1C2833", # Deep Navy
'bg_secondary': "#2C3E50", # Dark Blue Gray
'accent': "#5DADE2", # Sky Blue
'accent_2': "#F1C40F", # Lemon Yellow
'text_light': "#ECF0F1", # Light Gray
'text_dark': "#2C3E50" # Dark Blue Gray
}
self.root.configure(bg=self.colors['bg_primary'])
# Initialize translator
self.translator = Translator(service_urls=['translate.google.com'])
# Style configuration
self.style = ttk.Style()
self.style.configure('Custom.TCombobox',
background=self.colors['bg_secondary'],
fieldbackground=self.colors['bg_secondary'],
foreground=self.colors['text_light'],
arrowcolor=self.colors['accent_2'])
# Add padding at the top
top_padding = tk.Frame(root, height=40, bg=self.colors['bg_primary'])
top_padding.pack(fill=tk.X)
# Title with modern styling
title_frame = tk.Frame(root, bg=self.colors['bg_primary'])
title_frame.pack(fill=tk.X, pady=(0, 20))
title = tk.Label(title_frame,
text="🌐 Universal Translator 🌐",
font=("Montserrat", 32, "bold"),
bg=self.colors['bg_primary'],
fg=self.colors['accent_2'])
title.pack()
subtitle = tk.Label(title_frame,
text="Breaking Language Barriers",
font=("Montserrat", 14),
bg=self.colors['bg_primary'],
fg=self.colors['accent'])
subtitle.pack()
# Container frame
container = tk.Frame(root, bg=self.colors['bg_primary'], padx=40, pady=20)
container.pack(fill=tk.BOTH, expand=True)
# Language selection frame
lang_frame = tk.Frame(container, bg=self.colors['bg_primary'])
lang_frame.pack(fill=tk.X, pady=(0, 15))
# Add source_lang_var initialization
self.source_lang_var = tk.StringVar(value="Auto-Detect")
# From label and detection
self.detected_lang_label = tk.Label(lang_frame,
text="Detected Language: Auto",
bg=self.colors['bg_primary'],
fg=self.colors['accent'],
font=("Montserrat", 12))
self.detected_lang_label.pack(side=tk.LEFT)
# Swap button with hover effects
self.swap_btn = tk.Button(lang_frame,
text="🔄",
command=self.swap_languages,
bg=self.colors['bg_secondary'],
fg=self.colors['accent_2'],
font=("Montserrat", 14),
relief=tk.FLAT,
borderwidth=0,
padx=15,
pady=5)
self.swap_btn.pack(side=tk.LEFT, padx=20)
self._add_hover_effect(self.swap_btn)
# To label and combobox
to_label = tk.Label(lang_frame,
text="To:",
bg=self.colors['bg_primary'],
fg=self.colors['text_light'],
font=("Montserrat", 12))
to_label.pack(side=tk.LEFT, padx=(10, 5))
self.target_lang_var = tk.StringVar()
target_combo = ttk.Combobox(lang_frame,
textvariable=self.target_lang_var,
values=sorted(LANGUAGES.values()),
style='Custom.TCombobox',
width=20)
target_combo.pack(side=tk.LEFT)
# Text areas frame
text_frame = tk.Frame(container, bg=self.colors['bg_primary'])
text_frame.pack(fill=tk.BOTH, expand=True)
# Text areas with improved wrapping and spacing
# Source text area
self.source_text = scrolledtext.ScrolledText(
text_frame,
wrap=tk.WORD, # Ensure word wrapping (not character wrapping)
width=30,
height=10,
font=("Poppins", 13),
bg=self.colors['bg_secondary'],
fg=self.colors['text_light'],
insertbackground=self.colors['text_light'],
padx=25, # Increased horizontal padding
pady=20, # Increased vertical padding
relief=tk.FLAT,
borderwidth=0,
spacing1=5, # Space between lines
spacing2=2, # Space between paragraphs
spacing3=5 # Space before paragraphs
)
self.source_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0, 10))
self.source_text.insert("1.0", "\n") # Top margin
# Target text area
self.target_text = scrolledtext.ScrolledText(
text_frame,
wrap=tk.WORD, # Ensure word wrapping (not character wrapping)
width=30,
height=10,
font=("Poppins", 13),
bg=self.colors['bg_secondary'],
fg=self.colors['text_light'],
insertbackground=self.colors['text_light'],
padx=25, # Increased horizontal padding
pady=20, # Increased vertical padding
relief=tk.FLAT,
borderwidth=0,
spacing1=5, # Space between lines
spacing2=2, # Space between paragraphs
spacing3=5 # Space before paragraphs
)
self.target_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.target_text.insert("1.0", "\n") # Top margin
# Translate button frame
btn_frame = tk.Frame(container, bg=self.colors['bg_primary'])
btn_frame.pack(fill=tk.X, pady=(20, 0))
# Modern translate button
self.translate_btn = tk.Button(
btn_frame,
text="Translate ✨",
command=self.translate,
bg=self.colors['accent'],
fg=self.colors['text_light'],
font=("Montserrat", 14, "bold"),
relief=tk.FLAT,
borderwidth=0,
padx=30,
pady=10
)
self.translate_btn.pack()
self._add_hover_effect(self.translate_btn, is_translate_btn=True)
# Status label
self.status_label = tk.Label(
btn_frame,
text="Ready to translate",
bg=self.colors['bg_primary'],
fg=self.colors['accent'],
font=("Montserrat", 10)
)
self.status_label.pack(pady=(5, 0))
# Add history and favorites storage
self.history = []
self.favorites = set()
self.load_saved_data()
# Add character count label
self.char_count_source = tk.Label(
container,
text="Characters: 0/5000",
bg=self.colors['bg_primary'],
fg=self.colors['text_light'],
font=("Montserrat", 10)
)
self.char_count_source.pack(pady=(5, 0))
# Add loading animation label
self.loading_label = tk.Label(
btn_frame,
text="",
bg=self.colors['bg_primary'],
fg=self.colors['accent_2'],
font=("Montserrat", 12)
)
self.loading_label.pack()
# Modify keyboard shortcuts (remove copy shortcut)
self.root.bind('<Control-Return>', lambda e: self.translate())
self.root.bind('<Control-l>', lambda e: self.toggle_theme())
# Add theme toggle button
self.theme_btn = tk.Button(
title_frame,
text="🌙",
command=self.toggle_theme,
bg=self.colors['bg_primary'],
fg=self.colors['accent_2'],
font=("Montserrat", 12),
relief=tk.FLAT,
padx=10
)
self.theme_btn.pack(side=tk.RIGHT, padx=10)
# Bind text change events for character count
self.source_text.bind('<KeyRelease>', self.update_char_count)
# Initialize speech components
self.recognizer = sr.Recognizer()
self.engine = pyttsx3.init()
# Add voice control buttons frame
voice_frame = tk.Frame(container, bg=self.colors['bg_primary'])
voice_frame.pack(fill=tk.X, pady=5)
# Voice input button
self.voice_input_btn = tk.Button(
voice_frame,
text="🎤 Speak",
command=self.start_voice_input,
bg=self.colors['bg_secondary'],
fg=self.colors['accent_2'],
font=("Montserrat", 12),
relief=tk.FLAT,
padx=15
)
self.voice_input_btn.pack(side=tk.LEFT, padx=5)
# Text-to-Speech button
self.tts_btn = tk.Button(
voice_frame,
text="🔊 Listen",
command=self.speak_translation,
bg=self.colors['bg_secondary'],
fg=self.colors['accent_2'],
font=("Montserrat", 12),
relief=tk.FLAT,
padx=15
)
self.tts_btn.pack(side=tk.RIGHT, padx=5)
# Add hover effects to buttons
for btn in [self.voice_input_btn, self.tts_btn]:
self._add_hover_effect(btn)
# Add new features frame
features_frame = tk.Frame(container, bg=self.colors['bg_primary'])
features_frame.pack(fill=tk.X, pady=5)
# Auto-Language Detection Toggle
self.auto_detect_var = tk.BooleanVar(value=True)
self.auto_detect_btn = tk.Checkbutton(
features_frame,
text="🔄 Auto Detect",
variable=self.auto_detect_var,
command=self.toggle_auto_detect,
bg=self.colors['bg_primary'],
fg=self.colors['text_light'],
selectcolor=self.colors['bg_secondary'],
activebackground=self.colors['bg_primary'],
font=("Montserrat", 10)
)
self.auto_detect_btn.pack(side=tk.LEFT, padx=5)
# Always on Top Toggle
self.always_on_top_var = tk.BooleanVar(value=False)
self.always_on_top_btn = tk.Checkbutton(
features_frame,
text="📌 Always on Top",
variable=self.always_on_top_var,
command=self.toggle_always_on_top,
bg=self.colors['bg_primary'],
fg=self.colors['text_light'],
selectcolor=self.colors['bg_secondary'],
activebackground=self.colors['bg_primary'],
font=("Montserrat", 10)
)
self.always_on_top_btn.pack(side=tk.LEFT, padx=5)
# Mini Mode Toggle
self.mini_mode_btn = tk.Button(
features_frame,
text="🔍 Mini Mode",
command=self.toggle_mini_mode,
bg=self.colors['bg_secondary'],
fg=self.colors['accent_2'],
font=("Montserrat", 10),
relief=tk.FLAT
)
self.mini_mode_btn.pack(side=tk.RIGHT, padx=5)
# Pronunciation Guide Button
self.pronun_btn = tk.Button(
features_frame,
text="🗣️ Pronunciation",
command=self.show_pronunciation,
bg=self.colors['bg_secondary'],
fg=self.colors['accent_2'],
font=("Montserrat", 10),
relief=tk.FLAT
)
self.pronun_btn.pack(side=tk.RIGHT, padx=5)
# Add keyboard shortcuts
self.root.bind('<Control-m>', lambda e: self.toggle_mini_mode())
self.root.bind('<Control-t>', lambda e: self.toggle_always_on_top())
self.root.bind('<Control-p>', lambda e: self.show_pronunciation())
def _add_hover_effect(self, button, is_translate_btn=False):
"""Add hover effect to buttons"""
if is_translate_btn:
button.bind('<Enter>',
lambda e: button.config(
bg=self.colors['accent_2'],
fg=self.colors['text_dark']))
button.bind('<Leave>',
lambda e: button.config(
bg=self.colors['accent'],
fg=self.colors['text_light']))
else:
button.bind('<Enter>',
lambda e: button.config(
bg=self.colors['accent'],
fg=self.colors['text_light']))
button.bind('<Leave>',
lambda e: button.config(
bg=self.colors['bg_secondary'],
fg=self.colors['accent_2']))
def get_language_code(self, language_name):
"""Convert language name to language code"""
for code, name in LANGUAGES.items():
if name.lower() == language_name.lower():
return code
return None
def swap_languages(self):
"""Swap source and target languages"""
if self.source_lang_var.get() != "Auto-Detect":
source = self.source_lang_var.get()
target = self.target_lang_var.get()
self.source_lang_var.set(target)
self.target_lang_var.set(source)
# Also swap the text
source_text = self.source_text.get("1.0", tk.END).strip()
target_text = self.target_text.get("1.0", tk.END).strip()
self.source_text.delete("1.0", tk.END)
self.target_text.delete("1.0", tk.END)
self.source_text.insert("1.0", target_text)
self.target_text.insert("1.0", source_text)
def translate(self):
"""Override translate method to add new features"""
self.translate_btn.config(state=tk.DISABLED)
self.show_loading_animation()
self.play_sound("translate")
# Get all text including first line if it contains overflow
text = self.source_text.get("2.0", tk.END).strip()
# Check if there's any text in the first line (overflow)
first_line = self.source_text.get("1.0", "2.0").strip()
if first_line:
text = first_line + text
if not text:
self.status_label.config(text="Please enter some text to translate")
self.translate_btn.config(state=tk.NORMAL)
return
# Start translation in a separate thread
thread = threading.Thread(target=self._translate_thread, args=(text,))
thread.start()
def _translate_thread(self, text):
"""Handle the translation process"""
try:
source_lang = "auto" if self.source_lang_var.get() == "Auto-Detect" \
else self.get_language_code(self.source_lang_var.get())
target_lang = self.get_language_code(self.target_lang_var.get())
# Perform translation
result = self.translator.translate(text,
src=source_lang,
dest=target_lang)
# Update UI in the main thread
self.root.after(0, self._update_translation_result, result)
except Exception as e:
self.root.after(0, self._update_error, str(e))
finally:
self.root.after(0, self._enable_translate_button)
def _update_translation_result(self, result):
"""Update the translation result in the UI"""
self.target_text.delete("1.0", tk.END)
# Add initial newline for margin
self.target_text.insert("1.0", "\n")
# Insert translated text after the margin
self.target_text.insert("2.0", result.text)
if result.src != 'auto':
detected_lang = LANGUAGES.get(result.src, 'unknown').title()
self.status_label.config(text=f"Detected language: {detected_lang}")
else:
self.status_label.config(text="Translation complete!")
def _update_error(self, error_msg):
"""Update error message in the UI"""
self.status_label.config(text=f"Error: {error_msg}")
def _enable_translate_button(self):
"""Re-enable the translate button"""
self.translate_btn.config(state=tk.NORMAL)
def on_text_change(self, event=None):
"""Handle text changes and maintain the top margin"""
# Ensure first line is always empty for margin
first_line = self.source_text.get("1.0", "2.0").strip()
if not self.source_text.get("1.0", "2.0").startswith("\n"):
self.source_text.insert("1.0", "\n")
# Get text for language detection
text = self.source_text.get("1.0", tk.END).strip()
if text:
try:
detected = self.translator.detect(text)
detected_lang = LANGUAGES.get(detected.lang, 'unknown').title()
self.detected_lang_label.config(
text=f"Detected Language: {detected_lang}"
)
except:
pass
def load_saved_data(self):
"""Load translation history and favorites"""
try:
with open('translator_data.json', 'r') as f:
data = json.load(f)
self.history = data.get('history', [])
self.favorites = set(data.get('favorites', []))
except FileNotFoundError:
pass
def save_data(self):
"""Save translation history and favorites"""
with open('translator_data.json', 'w') as f:
json.dump({
'history': self.history[-10:], # Keep last 10 translations
'favorites': list(self.favorites)
}, f)
def update_char_count(self, event=None):
"""Update character count label"""
text = self.source_text.get("1.0", tk.END).strip()
count = len(text)
self.char_count_source.config(
text=f"Characters: {count}/5000",
fg=self.colors['accent'] if count <= 5000 else "red"
)
def toggle_theme(self):
"""Toggle between light and dark theme"""
if self.colors['bg_primary'] == "#1C2833": # Dark theme
self.colors.update({
'bg_primary': "#FFFFFF",
'bg_secondary': "#F5F5F5",
'text_light': "#2C3E50",
'text_dark': "#1C2833"
})
self.theme_btn.config(text="☀️")
else: # Light theme
self.colors.update({
'bg_primary': "#1C2833",
'bg_secondary': "#2C3E50",
'text_light': "#ECF0F1",
'text_dark': "#2C3E50"
})
self.theme_btn.config(text="🌙")
self.apply_theme()
def apply_theme(self):
"""Apply current theme to all widgets"""
# Update root and all main frames
self.root.configure(bg=self.colors['bg_primary'])
for widget in self.root.winfo_children():
if isinstance(widget, tk.Frame):
widget.configure(bg=self.colors['bg_primary'])
for child in widget.winfo_children():
if isinstance(child, tk.Frame):
child.configure(bg=self.colors['bg_primary'])
elif isinstance(child, tk.Label):
child.configure(
bg=self.colors['bg_primary'],
fg=self.colors['text_light']
)
elif isinstance(child, tk.Button):
if child != self.translate_btn:
child.configure(
bg=self.colors['bg_secondary'],
fg=self.colors['accent_2']
)
elif isinstance(child, scrolledtext.ScrolledText):
child.configure(
bg=self.colors['bg_secondary'],
fg=self.colors['text_light'],
insertbackground=self.colors['text_light']
)
# Update specific widgets
self.title_label.configure(
bg=self.colors['bg_primary'],
fg=self.colors['accent_2']
)
self.subtitle_label.configure(
bg=self.colors['bg_primary'],
fg=self.colors['accent']
)
def play_sound(self, action):
"""Play sound effects"""
sounds = {
'copy': 'sounds/copy.wav',
'translate': 'sounds/translate.wav',
'error': 'sounds/error.wav'
}
try:
if os.path.exists(sounds[action]):
threading.Thread(target=playsound, args=(sounds[action],)).start()
except:
pass
def show_loading_animation(self):
"""Show loading animation during translation"""
chars = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
def animate():
for char in chars:
if self.translate_btn['state'] == tk.DISABLED:
self.loading_label.config(text=f"Translating {char}")
self.root.after(100)
self.root.update()
else:
self.loading_label.config(text="")
break
threading.Thread(target=animate).start()
def start_voice_input(self):
"""Handle voice input"""
self.status_label.config(text="🎤 Listening... Speak now")
self.voice_input_btn.config(state=tk.DISABLED)
def listen():
try:
with sr.Microphone() as source:
self.recognizer.adjust_for_ambient_noise(source)
audio = self.recognizer.listen(source, timeout=5)
text = self.recognizer.recognize_google(audio)
# Update UI in main thread
self.root.after(0, self._update_voice_input, text)
except sr.WaitTimeoutError:
self.root.after(0, self.status_label.config,
{"text": "No speech detected. Please try again."})
except sr.RequestError:
self.root.after(0, self.status_label.config,
{"text": "Could not connect to speech service."})
except Exception as e:
self.root.after(0, self.status_label.config,
{"text": f"Error: {str(e)}"})
finally:
self.root.after(0, self.voice_input_btn.config, {"state": tk.NORMAL})
threading.Thread(target=listen).start()
def _update_voice_input(self, text):
"""Update the source text with voice input"""
self.source_text.delete("1.0", tk.END)
self.source_text.insert("1.0", "\n" + text)
self.status_label.config(text="✨ Voice input received!")
self.translate() # Auto-translate after voice input
def speak_translation(self):
"""Convert translation to speech"""
text = self.target_text.get("2.0", tk.END).strip()
if text:
self.status_label.config(text="🔊 Playing audio...")
self.tts_btn.config(state=tk.DISABLED)
def speak():
try:
self.engine.say(text)
self.engine.runAndWait()
self.root.after(0, self.status_label.config,
{"text": "Audio playback complete!"})
except Exception as e:
self.root.after(0, self.status_label.config,
{"text": f"Audio Error: {str(e)}"})
finally:
self.root.after(0, self.tts_btn.config, {"state": tk.NORMAL})
threading.Thread(target=speak).start()
def toggle_auto_detect(self):
"""Toggle automatic language detection"""
if self.auto_detect_var.get():
self.source_lang_var.set("Auto-Detect")
self.detected_lang_label.pack(side=tk.LEFT)
else:
self.detected_lang_label.pack_forget()
def toggle_always_on_top(self):
"""Toggle always on top mode"""
self.root.attributes('-topmost', self.always_on_top_var.get())
def toggle_mini_mode(self):
"""Toggle mini mode for quick translations"""
if hasattr(self, 'is_mini_mode') and self.is_mini_mode:
# Restore normal mode
self.root.geometry(self.original_geometry)
self.title_frame.pack(fill=tk.X, pady=(0, 20))
self.features_frame.pack(fill=tk.X, pady=5)
self.is_mini_mode = False
else:
# Switch to mini mode
self.original_geometry = self.root.geometry()
mini_width = 400
mini_height = 200
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
x = screen_width - mini_width - 10
y = screen_height - mini_height - 40
self.root.geometry(f"{mini_width}x{mini_height}+{x}+{y}")
self.title_frame.pack_forget()
self.features_frame.pack_forget()
self.is_mini_mode = True
def show_pronunciation(self):
"""Show pronunciation guide for translated text"""
text = self.target_text.get("2.0", tk.END).strip()
if not text:
return
popup = tk.Toplevel(self.root)
popup.title("Pronunciation Guide")
popup.geometry("300x200")
popup.configure(bg=self.colors['bg_primary'])
# Add phonetic pronunciation (simplified example)
phonetic_text = text.lower().replace('th', 'ð').replace('ch', 'tʃ')
label = tk.Label(popup,
text="Phonetic Pronunciation:",
font=("Montserrat", 12),
bg=self.colors['bg_primary'],
fg=self.colors['text_light'])
label.pack(pady=10)
pronun_text = scrolledtext.ScrolledText(
popup,
wrap=tk.WORD,
width=30,
height=5,
font=("Poppins", 12),
bg=self.colors['bg_secondary'],
fg=self.colors['text_light']
)
pronun_text.pack(padx=10, pady=5)
pronun_text.insert("1.0", phonetic_text)
pronun_text.configure(state='disabled')
# Add syllable breakdown
syllables = self._break_into_syllables(text)
tk.Label(popup,
text="Syllable Breakdown:",
font=("Montserrat", 12),
bg=self.colors['bg_primary'],
fg=self.colors['text_light']).pack(pady=5)
tk.Label(popup,
text=syllables,
font=("Poppins", 12),
bg=self.colors['bg_primary'],
fg=self.colors['accent_2']).pack()
def _break_into_syllables(self, text):
"""Simple syllable breakdown (example implementation)"""
# This is a simplified version - you might want to use a proper NLP library
vowels = 'aeiouAEIOU'
syllables = []
current = ""
for char in text:
current += char
if char in vowels:
syllables.append(current)
current = ""
if current:
syllables.append(current)
return " • ".join(syllables)
def main():
root = tk.Tk()
app = TranslatorApp(root)
root.mainloop()
if __name__ == "__main__":
main()