-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTTSPython.py
More file actions
2577 lines (2262 loc) · 108 KB
/
Copy pathTTSPython.py
File metadata and controls
2577 lines (2262 loc) · 108 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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import threading
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
from tkinter import font as tkfont
import os
import json
import re
import time
import gc
import shutil
import subprocess
import tempfile
import wave
import sys
import warnings
from datetime import datetime
# Reduce noisy Hugging Face warnings for local/offline use.
os.environ.setdefault("HF_HUB_DISABLE_SYMLINKS_WARNING", "1")
warnings.filterwarnings("ignore", message="You are sending unauthenticated requests to the HF Hub.*")
__version__ = "4.1.0"
IS_WINDOWS = sys.platform.startswith("win")
IS_LINUX = sys.platform.startswith("linux")
IS_DARWIN = sys.platform == "darwin"
try:
import pyttsx3
except ImportError:
pyttsx3 = None # type: ignore[assignment]
try:
import pythoncom as _pythoncom # type: ignore[import-not-found]
except ImportError:
_pythoncom = None
def _init_tts_engine():
"""Create a pyttsx3 engine using the best driver for this OS.
Windows: SAPI5 (default). Linux/macOS: espeak (espeak-ng compatible).
"""
if pyttsx3 is None:
raise RuntimeError(
"pyttsx3 is not installed. Install dependencies "
"(see requirements.txt or dependencies.sh / dependencies.bat)."
)
if IS_WINDOWS:
return pyttsx3.init()
# Prefer espeak explicitly so Linux does not try a missing nsss/sapi driver.
try:
return pyttsx3.init("espeak")
except Exception:
return pyttsx3.init()
def _ui_font_family():
"""Pick a UI font that exists on the current platform."""
if IS_WINDOWS:
return "Segoe UI"
if IS_DARWIN:
return "Helvetica Neue"
# Linux: prefer widely packaged sans fonts.
for family in ("Noto Sans", "DejaVu Sans", "Liberation Sans", "FreeSans", "Sans"):
try:
if family in tkfont.families():
return family
except Exception:
pass
return "Sans"
def _open_uri(uri_or_path):
"""Open a settings URI or file with the platform default handler."""
if IS_WINDOWS:
os.startfile(uri_or_path) # type: ignore[attr-defined]
return
opener = "open" if IS_DARWIN else "xdg-open"
subprocess.Popen(
[opener, uri_or_path],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
def _com_init_thread():
"""Initialize COM for a worker thread (Windows / pywin32). Returns True if CoUninitialize is needed."""
if _pythoncom is None:
return False
try:
_pythoncom.CoInitialize()
return True
except Exception:
try:
_pythoncom.CoInitializeEx(_pythoncom.COINIT_MULTITHREADED)
return True
except Exception:
return False
def _com_deinit_thread(com_initialized):
if not com_initialized or _pythoncom is None:
return
try:
_pythoncom.CoUninitialize()
except Exception:
pass
# --- Color emoji rendering -------------------------------------------------
# Tk paints color-emoji fonts as monochrome outline glyphs on Windows, so we
# render emoji to color bitmaps with Pillow and place them as tk.PhotoImage.
# Any failure (Pillow missing, no usable font) returns None so callers fall
# back to text-only. The cache keeps PhotoImage objects alive — Tk blanks a
# widget when its image is garbage-collected.
def _find_emoji_font():
"""Return a path or family name for a color-emoji font, or None."""
candidates = []
system_root = os.environ.get("SystemRoot", r"C:\Windows")
if sys.platform.startswith("win"):
candidates.append(os.path.join(system_root, "Fonts", "seguiemj.ttf"))
if os.environ.get("NOTO_COLOR_EMOJI"):
candidates.append(os.environ["NOTO_COLOR_EMOJI"])
candidates += [
"/usr/share/fonts/truetype/noto/NotoColorEmoji.ttf",
"/usr/share/fonts/opentype/noto/NotoColorEmoji.ttf",
"/usr/share/fonts/noto/NotoColorEmoji.ttf",
"/System/Library/Fonts/Apple Color Emoji.ttf",
r"C:\Windows\Fonts\seguiemj.ttf",
]
for path in candidates:
if path and os.path.exists(path):
return path
# Fall back to family names Pillow can resolve.
for name in ("Segoe UI Emoji", "Noto Color Emoji", "Symbola"):
try:
from PIL import ImageFont
ImageFont.truetype(name, 16)
return name
except Exception:
pass
return None
_EMOJI_IMAGES = {}
_EMOJI_FONT = None
def emoji_icon(char, size=16):
"""Render a single emoji as a color ``tk.PhotoImage`` (cached).
Returns ``None`` if rendering is unavailable so callers can fall back to
text-only labels.
"""
global _EMOJI_FONT
# Strip emoji variation selectors (U+FE0F emoji / U+FE0E text). On Segoe UI
# Emoji these render a stray mark that shifts the glyph left/right and gets
# clipped; the color glyph still renders without them.
clean_char = char.replace("\ufe0f", "").replace("\ufe0e", "")
cache_key = (clean_char, size, _EMOJI_FONT is not None)
if cache_key in _EMOJI_IMAGES:
return _EMOJI_IMAGES[cache_key]
image = None
try:
from PIL import Image, ImageDraw, ImageFont, ImageTk
if _EMOJI_FONT is None:
_EMOJI_FONT = _find_emoji_font()
if _EMOJI_FONT is not None:
# Render larger than the target so the glyph fits with margin, then
# center it on the canvas. Emoji ink boxes are larger than the font
# size and often drift off-center, so drawing at (0,0) clips them.
# Crop to the actual ink and recenter before scaling down so glyphs
# (e.g. ▶ ⏹ ⬆) are centered and not clipped.
render = size * 3
font = ImageFont.truetype(_EMOJI_FONT, int(render * 0.85))
img = Image.new("RGBA", (render, render), (0, 0, 0, 0))
ImageDraw.Draw(img).text(
(render / 2, render / 2), clean_char, font=font,
embedded_color=True, anchor="mm"
)
bbox = img.getbbox()
if bbox:
glyph = img.crop(bbox)
img = Image.new("RGBA", (render, render), (0, 0, 0, 0))
img.paste(glyph, ((render - glyph.width) // 2, (render - glyph.height) // 2), glyph)
img = img.resize((size, size), Image.LANCZOS)
image = ImageTk.PhotoImage(img)
except Exception:
image = None
_EMOJI_IMAGES[cache_key] = image
return image
# --- Color helpers (used by the theme/design system and the gradient header) ---
def _clamp_channel(value):
return max(0, min(255, int(round(value))))
def _hex_to_rgb(color):
color = str(color).lstrip("#")
if len(color) == 3:
color = "".join(ch * 2 for ch in color)
try:
return (int(color[0:2], 16), int(color[2:4], 16), int(color[4:6], 16))
except (ValueError, IndexError):
return (30, 30, 30)
def _rgb_to_hex(rgb):
return "#%02x%02x%02x" % (_clamp_channel(rgb[0]), _clamp_channel(rgb[1]), _clamp_channel(rgb[2]))
def _mix(color_a, color_b, t):
"""Linear blend from color_a (t=0) to color_b (t=1)."""
t = max(0.0, min(1.0, t))
ra, ga, ba = _hex_to_rgb(color_a)
rb, gb, bb = _hex_to_rgb(color_b)
return _rgb_to_hex((ra + (rb - ra) * t, ga + (gb - ga) * t, ba + (bb - ba) * t))
def _lighten(color, t=0.12):
return _mix(color, "#ffffff", t)
def _darken(color, t=0.12):
return _mix(color, "#000000", t)
def _relative_luminance(color):
r, g, b = (c / 255.0 for c in _hex_to_rgb(color))
return 0.2126 * r + 0.7152 * g + 0.0722 * b
def _is_dark(color):
return _relative_luminance(color) < 0.5
def _contrast_text(bg, light="#ffffff", dark="#111111"):
return dark if _relative_luminance(bg) > 0.55 else light
def _normalize_theme(theme):
"""Return a theme dict with every design-system key present.
Old/custom presets that only define the original 8 keys still load: any
missing key is derived from the base colors so the UI stays cohesive.
"""
t = dict(theme or {})
bg = t.setdefault("bg", "#1e1e1e")
dark = _is_dark(bg)
bg_elev = t.setdefault("bg_elev", _lighten(bg, 0.06) if dark else _darken(bg, 0.03))
text = t.setdefault("text", "#d4d4d4" if dark else "#111827")
accent = t.setdefault("accent", "#3b82f6")
t.setdefault("border", _lighten(bg, 0.22) if dark else _darken(bg, 0.16))
t.setdefault("muted", _mix(text, bg, 0.4))
t.setdefault("danger", "#f87171")
t.setdefault("name", "Custom")
# Gradient header
t.setdefault("header", _mix(bg_elev, accent, 0.22 if dark else 0.14))
t.setdefault("header2", _mix(bg, accent, 0.06))
t.setdefault("header_text", _contrast_text(t["header"], _lighten(text, 0.2), _darken(text, 0.1)))
# Buttons
t.setdefault("button", _lighten(bg_elev, 0.05) if dark else _darken(bg_elev, 0.02))
t.setdefault("button_text", text)
t.setdefault("button_hover", _mix(t["button"], accent, 0.34))
t.setdefault("button_active", accent)
# Fields (entries, combos, text areas)
t.setdefault("field", bg_elev)
t.setdefault("field_text", text)
t.setdefault("field_border", t["border"])
# States and misc
t.setdefault("disabled", _mix(bg_elev, bg, 0.5))
t.setdefault("disabled_text", _mix(t["muted"], bg, 0.35))
t.setdefault("on_accent", _contrast_text(accent))
return t
THEME_PRESETS = {
"dark": {
"bg": "#1e1e1e", "bg_elev": "#252526", "border": "#3c3c3c", "text": "#d4d4d4",
"muted": "#9d9d9d", "accent": "#3b82f6", "danger": "#f87171", "name": "Dark"
},
"twilight": {
"bg": "#171a21", "bg_elev": "#1b2838", "border": "#2a475e", "text": "#c7d5e0",
"muted": "#8f98a0", "accent": "#66c0f4", "danger": "#ff6b6b", "name": "Twilight"
},
"light": {
"bg": "#f3f4f6", "bg_elev": "#ffffff", "border": "#d1d5db", "text": "#111827",
"muted": "#4b5563", "accent": "#2563eb", "danger": "#dc2626", "name": "Light"
},
"contrast": {
"bg": "#000000", "bg_elev": "#0a0a0a", "border": "#ffffff", "text": "#ffffff",
"muted": "#e5e5e5", "accent": "#ffff00", "danger": "#ff4444", "name": "High Contrast"
},
"forest": {
"bg": "#141c16", "bg_elev": "#1c281f", "border": "#2d4a32", "text": "#dce8de",
"muted": "#7a9a80", "accent": "#4ade80", "danger": "#f87171", "name": "Forest"
},
"newvegas": {
"bg": "#0a100c", "bg_elev": "#101a14", "border": "#1f4d32", "text": "#5dff9a",
"muted": "#3a8f5c", "accent": "#8cffb4", "danger": "#ff7a45", "name": "New Vegas"
},
"spiral": {
"bg": "#0a0a0a", "bg_elev": "#131814", "border": "#2a4528", "text": "#dceadd",
"muted": "#6b8568", "accent": "#9fd12a", "danger": "#ff5533", "name": "Spiral"
},
"poly": {
"bg": "#080a12", "bg_elev": "#0f1422", "border": "#2a3f62", "text": "#e6edf7",
"muted": "#6b82a8", "accent": "#1f8fff", "danger": "#ff5c8a", "name": "Poly"
},
"sunset": {
"bg": "#1c1418", "bg_elev": "#261c22", "border": "#4a3040", "text": "#f3e8ef",
"muted": "#b8a0b0", "accent": "#fb923c", "danger": "#f87171", "name": "Sunset"
},
"paper": {
"bg": "#f2efe8", "bg_elev": "#faf8f4", "border": "#d4cec3", "text": "#2c2824",
"muted": "#6b6560", "accent": "#8b6914", "danger": "#b45309", "name": "Paper"
},
"graphite": {
"bg": "#2a2d32", "bg_elev": "#34383e", "border": "#4a5058", "text": "#e8eaed",
"muted": "#9aa0a8", "accent": "#7dd3fc", "danger": "#f87171", "name": "Graphite"
},
}
# Fill in derived design-system keys so every preset is complete and cohesive.
THEME_PRESETS = {key: _normalize_theme(value) for key, value in THEME_PRESETS.items()}
DEFAULT_SETTINGS = {
"theme_preset": "twilight",
"clipboard_monitor": False,
"clipboard_auto_queue": False,
"clipboard_action": "speak",
"performance_mode": True,
"mode": "tts",
"stt_engine": "faster-whisper",
"stt_whisper_model": "small",
"stt_input_device": "",
"tts_output_device": "",
"stt_unload_model_when_idle": False,
"stt_auto_unload_enabled": True,
"stt_auto_unload_minutes": 3,
}
class GradientHeader(tk.Canvas):
"""A canvas header that paints a horizontal gradient behind a title and,
optionally, a small cluster of ttk controls docked to the right edge.
The gradient is redrawn on ``<Configure>`` (resize) — no timers involved.
"""
_title_font = None
_subtitle_font = None
@classmethod
def _shared_fonts(cls):
# Lazily create shared fonts once (requires a live Tk root) so opening
# dialogs repeatedly does not accumulate new Font objects.
if cls._title_font is None:
family = _ui_font_family()
cls._title_font = tkfont.Font(family=family, size=15, weight="bold")
cls._subtitle_font = tkfont.Font(family=family, size=8)
return cls._title_font, cls._subtitle_font
def __init__(self, master, title="", subtitle="", height=60, **kwargs):
super().__init__(master, height=height, highlightthickness=0, bd=0, **kwargs)
self._title = title
self._subtitle = subtitle
self._c1 = "#2b2f3a"
self._c2 = "#1f2330"
self._title_color = "#ffffff"
self._subtitle_color = "#c8c8c8"
self._title_font, self._subtitle_font = self._shared_fonts()
# A frame docked to the right for interactive controls (buttons, combos).
self.controls = ttk.Frame(self, style="Header.TFrame")
self._controls_item = self.create_window(0, 0, window=self.controls, anchor="e")
self.bind("<Configure>", lambda _e: self.redraw())
def apply_colors(self, c1, c2, title_color, subtitle_color):
self._c1 = c1
self._c2 = c2
self._title_color = title_color
self._subtitle_color = subtitle_color
self.configure(bg=c1)
self.redraw()
def redraw(self):
self.delete("grad")
w = self.winfo_width()
h = self.winfo_height()
if w <= 1:
return
steps = 60
for i in range(steps):
t = i / (steps - 1)
color = _mix(self._c1, self._c2, t)
x0 = int(w * i / steps)
x1 = int(w * (i + 1) / steps) + 1
self.create_rectangle(x0, 0, x1, h, outline=color, fill=color, tags="grad")
if self._title:
ty = (h // 2 - 8) if self._subtitle else (h // 2)
self.create_text(18, ty, text=self._title, anchor="w",
fill=self._title_color, font=self._title_font, tags="grad")
if self._subtitle:
self.create_text(19, h // 2 + 11, text=self._subtitle, anchor="w",
fill=self._subtitle_color, font=self._subtitle_font, tags="grad")
# Keep the gradient/text under the docked control widgets.
self.tag_lower("grad")
self.coords(self._controls_item, w - 14, h // 2)
class ReaderApp:
def __init__(self, root):
self.root = root
self.style = ttk.Style(root)
self.root.title("TTSPython")
self.speaking = False
self.speak_thread = None
self.current_engine = None
self.stop_requested = False
self.global_stop_requested = False # Global stop flag for all TTS operations
self.all_engines = [] # Track all active TTS engines
self.current_file = None
# Store settings in the script directory, not AppData
script_dir = os.path.dirname(os.path.abspath(__file__))
self.settings_file = os.path.join(script_dir, "tts_settings.json")
self.theme_preset = DEFAULT_SETTINGS["theme_preset"]
self.performance_mode = DEFAULT_SETTINGS["performance_mode"]
self.clipboard_monitor_enabled = False
self.last_clipboard = ""
self.highlight_tag = "highlight"
self.current_word_indices = []
self.clipboard_auto_queue = False # Auto-queue clipboard items when speaking
self.clipboard_action_mode = 'speak' # Default clipboard action mode (will be overridden by load_settings)
self.current_mode = DEFAULT_SETTINGS["mode"]
self.stt_engine = "faster-whisper"
self.stt_whisper_model = DEFAULT_SETTINGS["stt_whisper_model"]
self.stt_input_device = DEFAULT_SETTINGS["stt_input_device"]
self.tts_output_device = DEFAULT_SETTINGS["tts_output_device"]
self.stt_unload_model_when_idle = DEFAULT_SETTINGS["stt_unload_model_when_idle"]
self.stt_auto_unload_enabled = DEFAULT_SETTINGS["stt_auto_unload_enabled"]
self.stt_auto_unload_minutes = DEFAULT_SETTINGS["stt_auto_unload_minutes"]
self.recording = False
self.recording_sample_rate = 16000
self.recording_stream = None
self.recording_wav_path = None
self.recording_wav_writer = None
self.recording_frame_count = 0
self.stt_idle_unload_timer_id = None
self.stt_processing = False
self.stt_backends = {}
self.last_highlight_update = 0.0
# Speech Queue System
self.speech_queue = []
self.queue_playing = False
self.current_queue_index = -1
# Load settings
self.load_settings()
# Initialize engine just to get default settings and voices
try:
temp_engine = _init_tts_engine()
self.default_rate = temp_engine.getProperty("rate")
self.default_volume = temp_engine.getProperty("volume")
self.voices = temp_engine.getProperty("voices")
temp_engine.stop() # Clean up temp engine
except Exception as e:
# Fallback if engine initialization fails
hint = (
"Please ensure pyttsx3 and pywin32 are installed."
if IS_WINDOWS
else "Please ensure pyttsx3 is installed and espeak-ng (+ alsa-utils/aplay) are available."
)
messagebox.showerror(
"TTS Engine Error",
f"Failed to initialize TTS engine: {str(e)}\n\n"
f"The app may not work correctly.\n{hint}",
)
self.default_rate = 150
self.default_volume = 1.0
self.voices = []
# --- UI ---
self.ui_font_family = _ui_font_family()
self.base_font = tkfont.Font(family=self.ui_font_family, size=10)
self.text_font = tkfont.Font(family=self.ui_font_family, size=11)
# Theme option lookups (used by the header switcher and the Settings dialog).
self.theme_options = [THEME_PRESETS[k]["name"] for k in THEME_PRESETS]
self.theme_id_by_name = {THEME_PRESETS[k]["name"]: k for k in THEME_PRESETS}
self.theme_name_var = tk.StringVar(
value=THEME_PRESETS[self.theme_preset]["name"] if self.theme_preset in THEME_PRESETS else "Twilight"
)
# Gradient header bar: title/version on the left, quick controls on the right.
self.header = GradientHeader(
root,
title=f"TTSPython {__version__}",
subtitle="",
height=60,
)
self.header.pack(fill="x", side="top")
self.mode_var = tk.StringVar(value=self.current_mode)
self.mode_toggle = ttk.Button(
self.header.controls, text="Mode: TTS", command=self.toggle_mode, style="Header.TButton"
)
self.mode_toggle.pack(side="left")
# Text editor area with scrollbar (wrapped so they align cleanly).
text_frame = ttk.Frame(root)
self.text_frame = text_frame
text_frame.pack(fill="both", expand=True, padx=10, pady=(10, 6))
self.txt = tk.Text(text_frame, wrap="word", height=16, undo=True, font=self.text_font)
scrollbar = ttk.Scrollbar(text_frame, orient="vertical", command=self.txt.yview)
scrollbar.pack(side="right", fill="y")
self.txt.pack(side="left", fill="both", expand=True)
self.txt.configure(yscrollcommand=scrollbar.set)
# Configure highlight tag
self.txt.tag_config(self.highlight_tag, background="yellow", foreground="black")
controls = ttk.Frame(root)
self.controls_frame = controls
controls.pack(fill="x", padx=10, pady=(0,10))
self.speak_btn = ttk.Button(controls, text="Speak All", image=emoji_icon("▶️"), compound=tk.LEFT, command=self.on_speak, style="Accent.TButton")
self.speak_selected_btn = ttk.Button(controls, text="Speak Selected", image=emoji_icon("🗣️"), compound=tk.LEFT, command=self.on_speak_selected)
self.stop_btn = ttk.Button(controls, text="Stop", image=emoji_icon("⏹️"), compound=tk.LEFT, command=self.on_stop)
paste_btn = ttk.Button(controls, text="Paste", image=emoji_icon("📋"), compound=tk.LEFT, command=self.on_paste)
clear_btn = ttk.Button(controls, text="Clear", image=emoji_icon("🧹"), compound=tk.LEFT, command=self.on_clear)
self.speak_btn.grid(row=0, column=0, padx=(0,6))
self.speak_selected_btn.grid(row=0, column=1, padx=(0,6))
self.stop_btn.grid(row=0, column=2, padx=(0,6))
paste_btn.grid(row=0, column=3, padx=(0,6))
clear_btn.grid(row=0, column=4, padx=(0,12))
# Rate
ttk.Label(controls, text="Rate").grid(row=0, column=6, padx=(16,4))
self.rate = tk.IntVar(value=self.default_rate)
self.rate_scale = ttk.Scale(controls, from_=100, to=250, orient="horizontal",
command=self._on_rate_change)
self.rate_scale.set(self.rate.get())
self.rate_scale.grid(row=0, column=7, sticky="ew", padx=(0,8))
# Volume
ttk.Label(controls, text="Volume").grid(row=0, column=8, padx=(8,4))
self.vol = tk.DoubleVar(value=self.default_volume)
self.vol_scale = ttk.Scale(controls, from_=0.1, to=1.0, orient="horizontal",
command=self._on_volume_change)
self.vol_scale.set(self.vol.get())
self.vol_scale.grid(row=0, column=9, sticky="ew", padx=(0,8))
# Voice selector
ttk.Label(controls, text="Voice").grid(row=0, column=10, padx=(8,4))
self.voice_map = { (v.name or f"Voice {i}"): v.id for i, v in enumerate(self.voices) }
self.voice_combo = ttk.Combobox(controls, values=list(self.voice_map.keys()), width=34, state="readonly")
# Pick a default female/neutral if available
if self.voice_map:
default_name = next((n for n in self.voice_map if "female" in n.lower() or "zira" in n.lower()), list(self.voice_map.keys())[0])
self.voice_combo.set(default_name)
self.selected_voice = self.voice_map[default_name] # Store selected voice
else:
self.voice_combo.set("No voices available")
self.selected_voice = None
self.voice_combo.bind("<<ComboboxSelected>>", self.on_voice_change)
self.voice_combo.grid(row=0, column=11, padx=(0,4))
# Refresh voices button
refresh_voices_btn = ttk.Button(controls, text="🔄 Refresh", command=self.refresh_voices)
refresh_voices_btn.grid(row=0, column=12, padx=(0,0))
voices_settings_btn = ttk.Button(controls, text="🎙️ Voices", command=self.open_voice_settings)
voices_settings_btn.grid(row=0, column=13, padx=(6,0))
controls.columnconfigure(7, weight=1)
controls.columnconfigure(9, weight=1)
# File operations and additional features
file_frame = ttk.Frame(root)
self.file_frame = file_frame
file_frame.pack(fill="x", padx=10, pady=(0,5))
open_btn = ttk.Button(file_frame, text="Open", image=emoji_icon("📂"), compound=tk.LEFT, command=self.on_open)
save_btn = ttk.Button(file_frame, text="Save", image=emoji_icon("💾"), compound=tk.LEFT, command=self.on_save)
save_as_btn = ttk.Button(file_frame, text="Save As", image=emoji_icon("💾"), compound=tk.LEFT, command=self.on_save_as)
self.export_audio_btn = ttk.Button(file_frame, text="Export Audio", image=emoji_icon("🎵"), compound=tk.LEFT, command=self.on_export_audio)
search_btn = ttk.Button(file_frame, text="Find/Replace", image=emoji_icon("🔍"), compound=tk.LEFT, command=self.on_search)
settings_btn = ttk.Button(file_frame, text="Settings", image=emoji_icon("⚙️"), compound=tk.LEFT, command=self.on_settings)
open_btn.pack(side="left", padx=(0,6))
save_btn.pack(side="left", padx=(0,6))
save_as_btn.pack(side="left", padx=(0,6))
self.export_audio_btn.pack(side="left", padx=(0,6))
search_btn.pack(side="left", padx=(0,6))
settings_btn.pack(side="left", padx=(0,6))
# Clipboard monitor controls
clipboard_frame = ttk.Frame(file_frame)
self.clipboard_frame = clipboard_frame
clipboard_frame.pack(side="right", padx=(6,0))
self.clipboard_var = tk.BooleanVar(value=self.clipboard_monitor_enabled)
clipboard_check = ttk.Checkbutton(clipboard_frame, text="Monitor Clipboard:", image=emoji_icon("📎"),
compound=tk.LEFT,
variable=self.clipboard_var, command=self.toggle_clipboard_monitor)
clipboard_check.pack(side="left")
# Clipboard action mode (speak or queue) - use loaded setting
self.clipboard_action = tk.StringVar(value=self.clipboard_action_mode)
clipboard_speak_radio = ttk.Radiobutton(clipboard_frame, text="Speak",
variable=self.clipboard_action, value="speak")
clipboard_queue_radio = ttk.Radiobutton(clipboard_frame, text="Queue",
variable=self.clipboard_action, value="queue")
clipboard_speak_radio.pack(side="left", padx=(5,0))
clipboard_queue_radio.pack(side="left")
# Auto-queue option for speak mode
self.auto_queue_var = tk.BooleanVar(value=self.clipboard_auto_queue)
auto_queue_check = ttk.Checkbutton(clipboard_frame, text="Auto-Queue",
variable=self.auto_queue_var, command=self.toggle_auto_queue)
auto_queue_check.pack(side="left", padx=(10,0))
self.performance_var = tk.BooleanVar(value=self.performance_mode)
performance_check = ttk.Checkbutton(
clipboard_frame,
text="Performance Mode",
variable=self.performance_var,
command=self.toggle_performance_mode
)
performance_check.pack(side="left", padx=(10, 0))
# Speech Queue Panel
queue_frame = ttk.LabelFrame(root, text="Speech Queue", padding=5)
self.queue_frame = queue_frame
queue_frame.pack(fill="both", expand=False, padx=10, pady=(0,5))
# Queue listbox with scrollbar
queue_list_frame = ttk.Frame(queue_frame)
self.queue_list_frame = queue_list_frame
queue_list_frame.pack(side="left", fill="both", expand=True)
queue_scrollbar = ttk.Scrollbar(queue_list_frame, orient="vertical")
self.queue_tree = ttk.Treeview(
queue_list_frame, height=4, selectmode="browse",
columns=("name",), show="tree headings",
yscrollcommand=queue_scrollbar.set,
)
self.queue_tree.heading("#0", text="")
self.queue_tree.column("#0", width=24, stretch=False, anchor="center")
self.queue_tree.heading("name", text="Speech Queue")
self.queue_tree.column("name", stretch=True)
queue_scrollbar.config(command=self.queue_tree.yview)
queue_scrollbar.pack(side="right", fill="y")
self.queue_tree.pack(side="left", fill="both", expand=True)
self.queue_tree.bind("<Delete>", lambda _e: self.remove_from_queue())
self.queue_tree.bind("<Double-1>", lambda _e: self.play_queue())
# Speech-queue playback state
self.queue_loop = tk.BooleanVar(value=False)
# Queue control buttons
queue_controls = ttk.Frame(queue_frame)
self.queue_controls_frame = queue_controls
queue_controls.pack(side="right", fill="y", padx=(5,0))
ttk.Button(queue_controls, text="Add Current Text", image=emoji_icon("➕"), compound=tk.LEFT,
command=self.add_current_to_queue).pack(fill="x", pady=2)
ttk.Button(queue_controls, text="Add File(s)", image=emoji_icon("📄"), compound=tk.LEFT,
command=self.add_files_to_queue).pack(fill="x", pady=2)
ttk.Button(queue_controls, text="Play Queue", image=emoji_icon("▶️"), compound=tk.LEFT, style="Accent.TButton",
command=self.play_queue).pack(fill="x", pady=2)
ttk.Button(queue_controls, text="Remove Selected", image=emoji_icon("➖"), compound=tk.LEFT,
command=self.remove_from_queue).pack(fill="x", pady=2)
ttk.Button(queue_controls, text="Clear Queue", image=emoji_icon("🗑️"), compound=tk.LEFT,
command=self.clear_queue).pack(fill="x", pady=2)
ttk.Button(queue_controls, text="Move Up", image=emoji_icon("⬆️"), compound=tk.LEFT,
command=self.move_queue_up).pack(fill="x", pady=2)
ttk.Button(queue_controls, text="Move Down", image=emoji_icon("⬇️"), compound=tk.LEFT,
command=self.move_queue_down).pack(fill="x", pady=2)
ttk.Checkbutton(queue_controls, text="Loop queue", variable=self.queue_loop).pack(fill="x", pady=(6, 2))
# STT panel (minimal UI, shown only in STT mode)
self.stt_frame = ttk.Frame(root)
ttk.Label(self.stt_frame, text="STT: faster-whisper", style="Section.TLabel").pack(side="left", padx=(0, 8))
self.stt_record_btn = ttk.Button(self.stt_frame, text="Start Recording", image=emoji_icon("⏺️"), compound=tk.LEFT, command=self.on_stt_record_toggle)
self.stt_record_btn.pack(side="left", padx=(0, 8))
self.stt_status = ttk.Label(self.stt_frame, text="Offline STT ready")
self.stt_status.pack(side="left")
# Status bar
self.status_var = tk.StringVar(value="Ready")
status_bar = ttk.Label(root, textvariable=self.status_var, relief="sunken", anchor="w")
status_bar.pack(side="bottom", fill="x")
self.status_bar = status_bar
# Apply theme
self.apply_theme()
self.refresh_mode_ui()
# Bind keyboard shortcuts
self.bind_shortcuts()
self.root.protocol("WM_DELETE_WINDOW", self.on_close)
# Window geometry: restore last size/position, else center on screen.
if getattr(self, "window_geometry", ""):
try:
self.root.geometry(self.window_geometry)
except Exception:
self._center_window()
else:
self._center_window()
# Start clipboard monitoring if enabled
if self.clipboard_monitor_enabled:
# Prime baseline so current clipboard does not auto-trigger on startup.
try:
self.last_clipboard = self.root.clipboard_get()
except Exception:
self.last_clipboard = ""
self.monitor_clipboard()
def _center_window(self):
"""Center the window within the screen, preserving its size."""
self.root.update_idletasks()
w = self.root.winfo_width()
h = self.root.winfo_height()
if w < 2 or h < 2:
w, h = 800, 600
sw = self.root.winfo_screenwidth()
sh = self.root.winfo_screenheight()
x = max(0, (sw - w) // 2)
y = max(0, (sh - h) // 2)
self.root.geometry(f"{w}x{h}+{x}+{y}")
def load_settings(self):
"""Load settings from JSON file with corruption recovery."""
loaded = {}
try:
if os.path.exists(self.settings_file):
with open(self.settings_file, "r", encoding="utf-8") as f:
loaded = json.load(f)
except Exception as e:
try:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
broken_file = os.path.join(os.path.dirname(self.settings_file), f"tts_settings.broken.{timestamp}.json")
if os.path.exists(self.settings_file):
shutil.copy2(self.settings_file, broken_file)
except Exception:
pass
print(f"Failed to load settings. Using defaults: {e}")
loaded = {}
self.theme_preset = loaded.get("theme_preset", DEFAULT_SETTINGS["theme_preset"])
if not isinstance(self.theme_preset, str) or self.theme_preset not in THEME_PRESETS:
if loaded.get("dark_mode") is True:
self.theme_preset = "dark"
elif loaded.get("dark_mode") is False:
self.theme_preset = "light"
else:
self.theme_preset = DEFAULT_SETTINGS["theme_preset"]
self.clipboard_monitor_enabled = bool(loaded.get("clipboard_monitor", DEFAULT_SETTINGS["clipboard_monitor"]))
self.clipboard_auto_queue = bool(loaded.get("clipboard_auto_queue", DEFAULT_SETTINGS["clipboard_auto_queue"]))
self.clipboard_action_mode = loaded.get("clipboard_action", DEFAULT_SETTINGS["clipboard_action"])
if self.clipboard_action_mode not in ("speak", "queue"):
self.clipboard_action_mode = "speak"
self.performance_mode = bool(loaded.get("performance_mode", DEFAULT_SETTINGS["performance_mode"]))
self.current_mode = loaded.get("mode", DEFAULT_SETTINGS["mode"])
if self.current_mode not in ("tts", "stt"):
self.current_mode = "tts"
self.stt_engine = "faster-whisper"
self.stt_whisper_model = loaded.get("stt_whisper_model", DEFAULT_SETTINGS["stt_whisper_model"])
self.stt_input_device = loaded.get("stt_input_device", DEFAULT_SETTINGS["stt_input_device"])
self.tts_output_device = loaded.get("tts_output_device", DEFAULT_SETTINGS["tts_output_device"])
self.stt_unload_model_when_idle = bool(
loaded.get("stt_unload_model_when_idle", DEFAULT_SETTINGS["stt_unload_model_when_idle"])
)
self.stt_auto_unload_enabled = bool(
loaded.get("stt_auto_unload_enabled", DEFAULT_SETTINGS["stt_auto_unload_enabled"])
)
loaded_minutes = loaded.get("stt_auto_unload_minutes", DEFAULT_SETTINGS["stt_auto_unload_minutes"])
try:
self.stt_auto_unload_minutes = max(1, min(60, int(loaded_minutes)))
except (TypeError, ValueError):
self.stt_auto_unload_minutes = DEFAULT_SETTINGS["stt_auto_unload_minutes"]
self.hotkeys = loaded.get("hotkeys", self.get_default_hotkeys())
self.window_geometry = loaded.get("geometry", "")
def save_settings(self):
"""Save settings to JSON file"""
# Capture current window geometry so we can restore it next launch.
try:
self.window_geometry = self.root.geometry()
except Exception:
pass
try:
settings = {
'theme_preset': self.theme_preset,
'clipboard_monitor': self.clipboard_monitor_enabled,
'clipboard_auto_queue': self.clipboard_auto_queue,
'clipboard_action': self.clipboard_action.get() if hasattr(self, 'clipboard_action') else 'speak',
'performance_mode': self.performance_mode,
'mode': self.current_mode,
'stt_engine': "faster-whisper",
'stt_whisper_model': self.stt_whisper_model,
'stt_input_device': self.stt_input_device,
'tts_output_device': self.tts_output_device,
'stt_unload_model_when_idle': self.stt_unload_model_when_idle,
'stt_auto_unload_enabled': self.stt_auto_unload_enabled,
'stt_auto_unload_minutes': self.stt_auto_unload_minutes,
'hotkeys': self.hotkeys,
'geometry': self.window_geometry
}
# Write atomically to avoid partial/corrupt JSON on interruption.
temp_settings_file = self.settings_file + ".tmp"
with open(temp_settings_file, 'w', encoding="utf-8") as f:
json.dump(settings, f, indent=2)
f.flush()
os.fsync(f.fileno())
self._atomic_replace(temp_settings_file, self.settings_file)
except Exception as e:
print(f"Failed to save settings: {e}")
def _atomic_replace(self, src, dst):
"""Replace dst with src, tolerating Windows lock/read-only issues.
On Windows, ``os.replace`` fails with WinError 5 when the destination
is held open by another process (e.g. an editor) or marked read-only.
We clear the read-only bit and retry, then fall back to a non-atomic
copy so settings still persist.
"""
try:
os.replace(src, dst)
return
except OSError:
pass
# Clear read-only attribute and retry the rename.
try:
os.chmod(dst, 0o666)
except OSError:
pass
try:
os.replace(src, dst)
return
except OSError:
pass
# Destination may be open (locked): overwrite its contents directly.
try:
shutil.copyfile(src, dst)
except OSError as e:
print(f"Failed to save settings (fallback): {e}")
finally:
try:
os.remove(src)
except OSError:
pass
def get_default_hotkeys(self):
"""Return default hotkey mappings"""
return {
'speak_all': '<Control-Return>',
'speak_selected': '<Control-Shift-Return>',
'stop': '<Escape>',
'open': '<Control-o>',
'save': '<Control-s>',
'save_as': '<Control-Shift-S>',
'paste': '<Control-v>',
'clear': '<Control-l>',
'find': '<Control-f>',
'export': '<Control-e>'
}
def bind_shortcuts(self):
"""Bind keyboard shortcuts"""
# Unbind all existing shortcuts first
for action, key in self.hotkeys.items():
try:
self.root.unbind(key)
except tk.TclError:
pass
# Bind shortcuts
self.root.bind(self.hotkeys['speak_all'], lambda e: self.on_speak())
self.root.bind(self.hotkeys['speak_selected'], lambda e: self.on_speak_selected())
self.root.bind(self.hotkeys['stop'], lambda e: self.on_stop())
self.root.bind(self.hotkeys['open'], lambda e: self.on_open())
self.root.bind(self.hotkeys['save'], lambda e: self.on_save())
self.root.bind(self.hotkeys['save_as'], lambda e: self.on_save_as())
self.root.bind(self.hotkeys['paste'], lambda e: self.on_paste())
self.root.bind(self.hotkeys['clear'], lambda e: self.on_clear())
self.root.bind(self.hotkeys['find'], lambda e: self.on_search())
self.root.bind(self.hotkeys['export'], lambda e: self.on_export_audio())
def toggle_mode(self):
if self.current_mode == "stt" and self.stt_unload_model_when_idle:
self._release_stt_model()
elif self.current_mode == "stt":
self._schedule_stt_idle_unload()
self.current_mode = "stt" if self.current_mode == "tts" else "tts"
self.refresh_mode_ui()
self.save_settings()
def refresh_mode_ui(self):
if self.current_mode == "stt":
self.mode_toggle.configure(text="Mode: STT")
self.stt_frame.pack(fill="x", padx=10, pady=(0, 5))
self.speak_btn.state(["disabled"])
self.speak_selected_btn.state(["disabled"])
self.status_var.set("STT mode ready (offline)")
else:
if self.recording:
self.stop_stt_recording()
self.mode_toggle.configure(text="Mode: TTS")
self.stt_frame.pack_forget()
self.speak_btn.state(["!disabled"])
self.speak_selected_btn.state(["!disabled"])
self.status_var.set("TTS mode ready")
def get_audio_devices(self):
"""Return available input/output audio devices for settings UI."""
try:
import sounddevice as sd
devices = sd.query_devices()
except Exception:
return {"inputs": [], "outputs": []}
inputs = []
outputs = []
for idx, dev in enumerate(devices):
name = dev.get("name", f"Device {idx}")
if dev.get("max_input_channels", 0) > 0:
inputs.append((str(idx), f"{idx}: {name}"))
if dev.get("max_output_channels", 0) > 0:
outputs.append((str(idx), f"{idx}: {name}"))
return {"inputs": inputs, "outputs": outputs}
def on_stt_record_toggle(self):
if self.current_mode != "stt":
messagebox.showinfo("Mode", "Switch to STT mode first.")
return
if self.stt_processing:
self.stt_status.configure(text="Still processing previous transcription...")
return
if self.recording:
self.stop_stt_recording()
else:
self.start_stt_recording()
def start_stt_recording(self):
try:
import sounddevice as sd
except Exception as exc:
messagebox.showerror("STT dependency missing", f"Please install STT dependencies.\n\n{exc}")
return
temp_fd, wav_path = tempfile.mkstemp(prefix="stt_recording_", suffix=".wav")
os.close(temp_fd)
wav_writer = None
try:
wav_writer = wave.open(wav_path, "wb")
wav_writer.setnchannels(1)
wav_writer.setsampwidth(2)
wav_writer.setframerate(self.recording_sample_rate)
except Exception:
if wav_writer:
wav_writer.close()
if os.path.exists(wav_path):
os.remove(wav_path)
messagebox.showerror("STT Error", "Could not prepare recording file.")
return
self.recording_wav_path = wav_path
self.recording_wav_writer = wav_writer
self.recording_frame_count = 0
self._cancel_stt_idle_unload()
self.recording = True
self.stt_record_btn.configure(text="Stop Recording", image=emoji_icon("⏹️"))
self.stt_status.configure(text="Recording... (faster-whisper)")
selected_input = self.stt_input_device.strip()
device_arg = None
if selected_input:
try:
device_arg = int(selected_input)
except ValueError:
device_arg = selected_input
def _audio_callback(indata, frames, callback_time, status):
writer = self.recording_wav_writer
if writer:
writer.writeframes(indata.tobytes())
self.recording_frame_count += frames
try:
self.recording_stream = sd.InputStream(