-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
2511 lines (2181 loc) · 102 KB
/
Copy pathapp.py
File metadata and controls
2511 lines (2181 loc) · 102 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
"""TinyReadAloud - Select text, press Ctrl+Alt+R, hear it read aloud."""
import asyncio
import ctypes
import ctypes.wintypes
import json
import os
import queue
import signal
import sys
import threading
import time
import tkinter as tk
from tkinter import messagebox, ttk
import urllib.error
import urllib.request
from version import __version__
# When frozen as a windowless app (console=False), stdout/stderr are None.
# Redirect to a log file so print() calls don't crash.
if getattr(sys, 'frozen', False) and sys.stdout is None:
_data_base = os.environ.get("LOCALAPPDATA",
os.path.expanduser("~\\AppData\\Local"))
_log_dir = os.path.join(_data_base, "TinyReadAloud")
os.makedirs(_log_dir, exist_ok=True)
sys.stdout = open(os.path.join(_log_dir, "tinyreadaloud.log"), "a", encoding="utf-8")
sys.stderr = sys.stdout
# Add pip-installed NVIDIA CUDA DLLs to PATH so onnxruntime can find them
try:
import nvidia
_nv_root = os.path.dirname(nvidia.__path__[0] if hasattr(nvidia.__path__, '__iter__') else nvidia.__path__)
for _subpkg in ("cublas", "cuda_runtime", "cudnn", "cufft", "nvjitlink"):
_bin = os.path.join(_nv_root, "nvidia", _subpkg, "bin")
if os.path.isdir(_bin):
os.add_dll_directory(_bin)
os.environ["PATH"] = _bin + os.pathsep + os.environ.get("PATH", "")
except ImportError:
pass
import keyboard
import numpy as np
import onnxruntime as ort
import pystray
import sounddevice as sd
from kokoro_onnx import Kokoro
from langdetect import detect as langdetect_detect
from PIL import Image, ImageDraw
# ── Constants ────────────────────────────────────────────────────────────────
HOTKEY = "ctrl+alt+r"
DICTATION_HOTKEY = "ctrl+alt+d"
GRAMMAR_HOTKEY = "ctrl+alt+g"
REPHRASE_HOTKEY = "ctrl+alt+p"
DEFAULT_VOICE_EN = "af_heart"
DEFAULT_VOICE_ES = "ef_dora"
DEFAULT_SPEED = 1.0
DEFAULT_GRAMMAR_MODE = "manual"
GRAMMAR_MODES = ["off", "manual", "after_dictation"]
DEFAULT_DICTATION_PROVIDER = "windows"
DEFAULT_GRAMMAR_PROVIDER = "anthropic"
DICTATION_PROVIDERS = ["windows"]
GRAMMAR_PROVIDERS = ["anthropic"]
REPHRASE_STYLES = ["Natural", "Formal", "Casual", "Concise", "Expanded", "Professional"]
DEFAULT_REPHRASE_STYLE = "Natural"
DEFAULT_STYLE_HOTKEYS = {s: "" for s in REPHRASE_STYLES}
RECALL_STYLE_HOTKEY = ""
DEFAULT_MIC_DEVICE = "" # empty = system default
COPY_WAIT_INTERVAL = 0.02
COPY_WAIT_TIMEOUT = 0.5
AUDIO_CHUNK_SECS = 0.05 # 50ms playback granularity for stop responsiveness
ANTHROPIC_API_URL = "https://api.anthropic.com/v1/messages"
ANTHROPIC_MODEL_DEFAULT = "claude-sonnet-4-6"
ANTHROPIC_VERSION = "2023-06-01"
def _get_app_dir():
"""Return the application directory (where the exe/script lives)."""
if getattr(sys, 'frozen', False):
return os.path.dirname(sys.executable)
return os.path.dirname(os.path.abspath(__file__))
def _get_data_dir():
"""Return %LOCALAPPDATA%/TinyReadAloud, creating it if needed."""
base = os.environ.get("LOCALAPPDATA",
os.path.expanduser("~\\AppData\\Local"))
d = os.path.join(base, "TinyReadAloud")
os.makedirs(d, exist_ok=True)
return d
APP_DIR = _get_app_dir()
DATA_DIR = _get_data_dir()
CONFIG_PATH = os.path.join(DATA_DIR, "config.json")
MODEL_PATH_FP16 = os.path.join(DATA_DIR, "kokoro-v1.0.fp16.onnx")
MODEL_PATH_INT8 = os.path.join(DATA_DIR, "kokoro-v1.0.int8.onnx")
VOICES_PATH = os.path.join(DATA_DIR, "voices-v1.0.bin")
MODEL_URL_FP16 = "https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files-v1.0/kokoro-v1.0.fp16.onnx"
MODEL_URL_INT8 = "https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files-v1.0/kokoro-v1.0.int8.onnx"
VOICES_URL = "https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files-v1.0/voices-v1.0.bin"
CF_UNICODETEXT = 13
GMEM_MOVEABLE = 0x0002
GMEM_ZEROINIT = 0x0040
user32 = ctypes.windll.user32
kernel32 = ctypes.windll.kernel32
user32.OpenClipboard.argtypes = [ctypes.wintypes.HWND]
user32.OpenClipboard.restype = ctypes.wintypes.BOOL
user32.CloseClipboard.argtypes = []
user32.CloseClipboard.restype = ctypes.wintypes.BOOL
user32.EmptyClipboard.argtypes = []
user32.EmptyClipboard.restype = ctypes.wintypes.BOOL
user32.GetClipboardData.argtypes = [ctypes.wintypes.UINT]
user32.GetClipboardData.restype = ctypes.c_void_p
user32.SetClipboardData.argtypes = [ctypes.wintypes.UINT, ctypes.c_void_p]
user32.SetClipboardData.restype = ctypes.c_void_p
user32.IsClipboardFormatAvailable.argtypes = [ctypes.wintypes.UINT]
user32.IsClipboardFormatAvailable.restype = ctypes.wintypes.BOOL
user32.GetForegroundWindow.argtypes = []
user32.GetForegroundWindow.restype = ctypes.wintypes.HWND
user32.SetForegroundWindow.argtypes = [ctypes.wintypes.HWND]
user32.SetForegroundWindow.restype = ctypes.wintypes.BOOL
kernel32.GlobalAlloc.argtypes = [ctypes.wintypes.UINT, ctypes.c_size_t]
kernel32.GlobalAlloc.restype = ctypes.c_void_p
kernel32.GlobalLock.argtypes = [ctypes.c_void_p]
kernel32.GlobalLock.restype = ctypes.c_void_p
kernel32.GlobalUnlock.argtypes = [ctypes.c_void_p]
kernel32.GlobalUnlock.restype = ctypes.wintypes.BOOL
kernel32.GlobalFree.argtypes = [ctypes.c_void_p]
kernel32.GlobalFree.restype = ctypes.c_void_p
# ── Win32 focus / caret detection ─────────────────────────────────────────────
class GUITHREADINFO(ctypes.Structure):
_fields_ = [
("cbSize", ctypes.wintypes.DWORD),
("flags", ctypes.wintypes.DWORD),
("hwndActive", ctypes.wintypes.HWND),
("hwndFocus", ctypes.wintypes.HWND),
("hwndCapture", ctypes.wintypes.HWND),
("hwndMenuOwner", ctypes.wintypes.HWND),
("hwndMoveSize", ctypes.wintypes.HWND),
("hwndCaret", ctypes.wintypes.HWND),
("rcCaret", ctypes.wintypes.RECT),
]
user32.GetGUIThreadInfo.argtypes = [ctypes.wintypes.DWORD, ctypes.POINTER(GUITHREADINFO)]
user32.GetGUIThreadInfo.restype = ctypes.wintypes.BOOL
user32.GetWindowThreadProcessId.argtypes = [ctypes.wintypes.HWND, ctypes.POINTER(ctypes.wintypes.DWORD)]
user32.GetWindowThreadProcessId.restype = ctypes.wintypes.DWORD
user32.GetClassNameW.argtypes = [ctypes.wintypes.HWND, ctypes.wintypes.LPWSTR, ctypes.c_int]
user32.GetClassNameW.restype = ctypes.c_int
_DESKTOP_CLASSES = frozenset({"Progman", "WorkerW", "Shell_TrayWnd", "Shell_SecondaryTrayWnd"})
def _is_textfield_focused():
"""Return True if the foreground window likely has a text field focused."""
hwnd = user32.GetForegroundWindow()
if not hwnd:
return False
# Check if the foreground window is the desktop / taskbar
buf = ctypes.create_unicode_buffer(256)
user32.GetClassNameW(hwnd, buf, 256)
if buf.value in _DESKTOP_CLASSES:
return False
# Get GUI thread info for the foreground window's thread
tid = user32.GetWindowThreadProcessId(hwnd, None)
gti = GUITHREADINFO()
gti.cbSize = ctypes.sizeof(GUITHREADINFO)
if user32.GetGUIThreadInfo(tid, ctypes.byref(gti)):
if not gti.hwndFocus:
return False
return True
# ── Win32 modifier key helpers ────────────────────────────────────────────────
_VK_CONTROL = 0x11
_VK_MENU = 0x12 # Alt
_VK_SHIFT = 0x10
_MODIFIER_VKS = (_VK_CONTROL, _VK_MENU, _VK_SHIFT)
user32.GetAsyncKeyState.argtypes = [ctypes.c_int]
user32.GetAsyncKeyState.restype = ctypes.c_short
def _wait_for_modifiers_released(timeout=2.0):
"""Spin until Ctrl, Alt, and Shift are all physically released.
With suppress=False hotkeys the physical keys are still held when the
callback fires. We must wait for the user to release them before
injecting keyboard.send('ctrl+a') etc., otherwise the target app
receives ctrl+alt+a instead of ctrl+a.
"""
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if not any(user32.GetAsyncKeyState(vk) & 0x8000 for vk in _MODIFIER_VKS):
return
time.sleep(0.02)
# Timed out — proceed anyway (user may be holding the key intentionally)
# ── Model Download ───────────────────────────────────────────────────────────
def _has_cuda():
"""Check if CUDA execution provider is available."""
try:
return "CUDAExecutionProvider" in ort.get_available_providers()
except Exception:
return False
USE_GPU = _has_cuda()
def ensure_models():
"""Download model files if they don't exist. Returns True if ready."""
model_path = MODEL_PATH_FP16 if USE_GPU else MODEL_PATH_INT8
model_url = MODEL_URL_FP16 if USE_GPU else MODEL_URL_INT8
# Remove the other model variant to save disk space
other = MODEL_PATH_INT8 if USE_GPU else MODEL_PATH_FP16
if os.path.exists(other):
os.remove(other)
for path, url in [(model_path, model_url), (VOICES_PATH, VOICES_URL)]:
if os.path.exists(path):
continue
name = os.path.basename(path)
print(f"Downloading {name} (first run only)...")
def reporthook(block, block_size, total):
done = block * block_size
pct = min(100, done * 100 // max(total, 1))
mb_done = done / 1048576
mb_total = total / 1048576
print(f"\r {pct}% ({mb_done:.1f} / {mb_total:.1f} MB)", end="", flush=True)
try:
urllib.request.urlretrieve(url, path, reporthook=reporthook)
print()
except Exception as e:
print(f"\nDownload failed: {e}", file=sys.stderr)
if os.path.exists(path):
os.remove(path)
return False
return True
SPEED_OPTIONS = [("Slow", 0.8), ("Normal", 1.0), ("Fast", 1.2), ("Very Fast", 1.5)]
SPEED_BY_LABEL = {label: spd for label, spd in SPEED_OPTIONS}
SPEED_BY_VALUE = {spd: label for label, spd in SPEED_OPTIONS}
# ── Config ──────────────────────────────────────────────────────────────────
def load_config():
"""Load settings from config.json, returning defaults for missing keys."""
defaults = {"hotkey": HOTKEY, "voice_en": DEFAULT_VOICE_EN,
"voice_es": DEFAULT_VOICE_ES, "speed": DEFAULT_SPEED,
"dictation_hotkey": DICTATION_HOTKEY,
"grammar_hotkey": GRAMMAR_HOTKEY,
"rephrase_hotkey": REPHRASE_HOTKEY,
"grammar_mode": DEFAULT_GRAMMAR_MODE,
"dictation_provider": DEFAULT_DICTATION_PROVIDER,
"grammar_provider": DEFAULT_GRAMMAR_PROVIDER,
"rephrase_style": DEFAULT_REPHRASE_STYLE,
"style_hotkeys": dict(DEFAULT_STYLE_HOTKEYS),
"recall_style_hotkey": RECALL_STYLE_HOTKEY,
"mic_device": DEFAULT_MIC_DEVICE,
"anthropic_api_key": "",
"anthropic_model": ANTHROPIC_MODEL_DEFAULT}
if not os.path.exists(CONFIG_PATH):
return defaults
try:
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
data = json.load(f)
# Migrate old single-voice config
if "voice" in data and "voice_en" not in data:
data["voice_en"] = data.pop("voice")
for k, v in defaults.items():
data.setdefault(k, v)
return data
except Exception:
return defaults
def save_config(cfg):
"""Save settings dict to config.json."""
with open(CONFIG_PATH, "w", encoding="utf-8") as f:
json.dump(cfg, f, indent=2)
def grammar_check_text_anthropic(text, api_key="", model=""):
"""Use Anthropic to correct grammar and return corrected plain text."""
api_key = (api_key or "").strip() or os.environ.get("ANTHROPIC_API_KEY", "").strip()
if not api_key:
raise RuntimeError("ANTHROPIC_API_KEY is not set")
model = (model or "").strip() or ANTHROPIC_MODEL_DEFAULT
prompt = (
"Correct grammar and punctuation for the text below. "
"Do not add commentary. Return only corrected text in the same language.\n\n"
f"{text}"
)
payload = {
"model": model,
"max_tokens": max(256, min(2048, len(text) * 3)),
"messages": [{"role": "user", "content": prompt}],
}
req = urllib.request.Request(
ANTHROPIC_API_URL,
data=json.dumps(payload).encode("utf-8"),
headers={
"Content-Type": "application/json",
"x-api-key": api_key,
"anthropic-version": ANTHROPIC_VERSION,
},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
data = json.loads(resp.read().decode("utf-8"))
except urllib.error.HTTPError as e:
body = ""
try:
body = e.read().decode("utf-8", errors="replace")
except Exception:
pass
raise RuntimeError(f"HTTP {e.code}: {body or e.reason}") from e
parts = []
for item in data.get("content", []):
if item.get("type") == "text":
parts.append(item.get("text", ""))
corrected = "".join(parts).strip()
if not corrected:
return text
return corrected
def grammar_check_text(text, provider, api_key="", model=""):
"""Dispatch grammar check to the selected provider."""
if provider == "anthropic":
return grammar_check_text_anthropic(text, api_key=api_key, model=model)
raise RuntimeError(f"Unsupported grammar provider: {provider}")
_REPHRASE_STYLE_PROMPTS = {
"Natural": (
"Rewrite the text below using different words and sentence structure. "
"Do NOT just fix grammar or punctuation — actively rephrase with new wording so the output "
"sounds noticeably different from the input while keeping the same meaning and language."
),
"Formal": (
"Rewrite the text below in a formal, professional tone using different vocabulary and sentence structure. "
"Do NOT just fix grammar — actively rephrase with elevated, polished wording. Keep the same meaning and language."
),
"Casual": (
"Rewrite the text below in a relaxed, conversational tone using different words and phrasing. "
"Do NOT just fix grammar — actively rephrase to sound friendly and informal. Keep the same meaning and language."
),
"Concise": (
"Rewrite the text below to be significantly shorter and more direct. "
"Cut unnecessary words, merge sentences where possible, and use tighter phrasing. "
"Keep the core meaning and language but make it noticeably more compact."
),
"Expanded": (
"Rewrite the text below to be longer and more detailed. "
"Add descriptive language, elaborate on ideas, and use fuller sentences. "
"Keep the same meaning and language but make the output noticeably richer and more developed."
),
"Professional": (
"Rewrite the text below in polished business language suitable for a workplace email or report. "
"Use different words and sentence structure — do NOT just fix grammar. "
"Keep the same meaning and language."
),
}
def rephrase_text_anthropic(text, api_key="", model="", style=""):
"""Use Anthropic to rephrase/reword text and return the result."""
api_key = (api_key or "").strip() or os.environ.get("ANTHROPIC_API_KEY", "").strip()
if not api_key:
raise RuntimeError("ANTHROPIC_API_KEY is not set")
model = (model or "").strip() or ANTHROPIC_MODEL_DEFAULT
style = (style or DEFAULT_REPHRASE_STYLE).strip()
style_instr = _REPHRASE_STYLE_PROMPTS.get(style, _REPHRASE_STYLE_PROMPTS[DEFAULT_REPHRASE_STYLE])
system_prompt = (
"You are a professional writing assistant. "
"Your sole task is to rewrite the text the user gives you according to the style instruction. "
"Output ONLY the rewritten text — no quotes, no labels, no commentary, no explanation."
)
user_message = f"{style_instr}\n\nText to rewrite:\n{text}"
payload = {
"model": model,
"max_tokens": max(256, min(2048, len(text) * 4)),
"system": system_prompt,
"messages": [{"role": "user", "content": user_message}],
}
req = urllib.request.Request(
ANTHROPIC_API_URL,
data=json.dumps(payload).encode("utf-8"),
headers={
"Content-Type": "application/json",
"x-api-key": api_key,
"anthropic-version": ANTHROPIC_VERSION,
},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=30) as resp:
data = json.loads(resp.read().decode("utf-8"))
except urllib.error.HTTPError as e:
body = ""
try:
body = e.read().decode("utf-8", errors="replace")
except Exception:
pass
raise RuntimeError(f"HTTP {e.code}: {body or e.reason}") from e
print(f"[Rephrase] Raw API response type={data.get('type')} stop_reason={data.get('stop_reason')}", flush=True)
# Anthropic sometimes returns a 200 with {"type": "error", ...}
if data.get("type") == "error":
err = data.get("error", {})
raise RuntimeError(f"{err.get('type', 'api_error')}: {err.get('message', str(data))}")
parts = []
for item in data.get("content", []):
if item.get("type") == "text":
parts.append(item.get("text", ""))
result = "".join(parts).strip()
print(f"[Rephrase] Extracted result ({len(result)} chars): {result[:120]!r}", flush=True)
if not result:
raise RuntimeError("API returned empty content — check model name and API key tier.")
return result
def rephrase_text(text, provider, api_key="", model="", style=""):
"""Dispatch rephrase to the selected provider."""
if provider == "anthropic":
return rephrase_text_anthropic(text, api_key=api_key, model=model, style=style)
raise RuntimeError(f"Unsupported rephrase provider: {provider}")
# ── Clipboard ────────────────────────────────────────────────────────────────
def _open_clipboard(retries=2):
for i in range(retries):
if user32.OpenClipboard(0):
return True
time.sleep(0.05)
return False
def clipboard_get_text():
if not _open_clipboard():
return ""
try:
if not user32.IsClipboardFormatAvailable(CF_UNICODETEXT):
return ""
handle = user32.GetClipboardData(CF_UNICODETEXT)
if not handle:
return ""
ptr = ctypes.c_wchar_p(handle)
return ptr.value or ""
finally:
user32.CloseClipboard()
def clipboard_set_text(text):
"""Write text to clipboard, retrying up to 10 times. Returns True on success."""
for attempt in range(10):
if _open_clipboard():
try:
user32.EmptyClipboard()
if not text:
return True
buf = (text + "\0").encode("utf-16-le")
hmem = kernel32.GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, len(buf))
if not hmem:
continue
ptr = kernel32.GlobalLock(hmem)
if not ptr:
kernel32.GlobalFree(hmem)
continue
ctypes.memmove(ptr, buf, len(buf))
kernel32.GlobalUnlock(hmem)
user32.SetClipboardData(CF_UNICODETEXT, hmem)
return True
finally:
user32.CloseClipboard()
time.sleep(0.05)
return False
def clipboard_clear():
if not _open_clipboard():
return
try:
user32.EmptyClipboard()
finally:
user32.CloseClipboard()
def capture_selected_text():
old = clipboard_get_text()
clipboard_clear()
keyboard.send("ctrl+c")
elapsed = 0.0
text = ""
while elapsed < COPY_WAIT_TIMEOUT:
time.sleep(COPY_WAIT_INTERVAL)
elapsed += COPY_WAIT_INTERVAL
text = clipboard_get_text()
if text:
break
if old:
clipboard_set_text(old)
else:
clipboard_clear()
return text.strip()
# ── Icon ─────────────────────────────────────────────────────────────────────
def create_tray_icon(size=64, speaking=False):
img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
bg = "#2ECC71" if speaking else "#E74C3C"
pad = 2
draw.ellipse([pad, pad, size - pad, size - pad], fill=bg)
cx, cy = size // 2, size // 2
# Speaker body
draw.rectangle([cx - 12, cy - 6, cx - 4, cy + 6], fill="white")
# Speaker cone
draw.polygon(
[(cx - 4, cy - 6), (cx + 6, cy - 14), (cx + 6, cy + 14), (cx - 4, cy + 6)],
fill="white",
)
if speaking:
draw.rectangle([cx + 12, cy - 7, cx + 17, cy + 7], fill="white")
draw.rectangle([cx + 20, cy - 7, cx + 25, cy + 7], fill="white")
else:
for r in [14, 21]:
bbox = [cx + 6 - r, cy - r, cx + 6 + r, cy + r]
draw.arc(bbox, start=-35, end=35, fill="white", width=2)
return img
# ── Voice Helpers ────────────────────────────────────────────────────────────
_LANG_NAMES = {"a": "American", "b": "British", "e": "Spanish", "f": "French",
"h": "Hindi", "i": "Italian", "j": "Japanese", "p": "Portuguese",
"z": "Chinese"}
_GENDER_NAMES = {"f": "Female", "m": "Male"}
def voice_display_name(code):
"""Convert 'af_heart' to 'Heart (American, Female)'."""
parts = code.split("_", 1)
if len(parts) != 2 or len(parts[0]) < 2:
return code
prefix, name = parts
lang = _LANG_NAMES.get(prefix[0], prefix[0].upper())
gender = _GENDER_NAMES.get(prefix[1], prefix[1].upper())
return f"{name.title()} ({lang}, {gender})"
def is_english_voice(code):
"""Voice codes starting with 'a' (American) or 'b' (British) are English."""
return len(code) >= 2 and code[0] in ("a", "b")
def is_spanish_voice(code):
"""Voice codes starting with 'e' are Spanish."""
return len(code) >= 2 and code[0] == "e"
# Kokoro lang parameter mapping
_KOKORO_LANG = {"en": "en-us", "es": "es"}
def detect_language(text):
"""Detect whether text is English or Spanish. Returns 'en' or 'es'."""
try:
lang = langdetect_detect(text)
if lang.startswith("es"):
return "es"
except Exception:
pass
return "en"
# ── Floating Status Bar ──────────────────────────────────────────────────────
_STATUSBAR_TRANSPARENT = "#010203"
class FloatingStatusBar:
"""Tiny draggable always-on-top bar: style switcher + live status + settings gear."""
BG = "#1a1a2e"
FG = "#e2e8f0"
DIM = "#8892a0"
ACCENT = "#a78bfa"
SEP = "#2d3748"
W, H = 300, 36
RADIUS = 10
_FONT = ("Segoe UI", 9)
_FONTB = ("Segoe UI", 9, "bold")
_instance_lock = threading.Lock()
_instance = None
# ── Singleton ────────────────────────────────────────────────────────────
@classmethod
def open(cls, app):
with cls._instance_lock:
if cls._instance is not None:
try:
cls._instance._root.lift()
return
except Exception:
pass
inst = cls(app)
cls._instance = inst
threading.Thread(target=inst._run, daemon=True).start()
@classmethod
def get(cls):
with cls._instance_lock:
return cls._instance
# ── Init ─────────────────────────────────────────────────────────────────
def __init__(self, app):
self._app = app
self._root = None
self._status_var = None
self._style_var = None
self._drag_x = self._drag_y = 0
self._own_hwnd = 0 # set once the Tk window is created
self._last_target_hwnd = 0 # last foreground HWND that isn't the status bar
try:
self._style_idx = REPHRASE_STYLES.index(app._rephrase_style)
except (ValueError, AttributeError):
self._style_idx = 0
# ── Thread-safe updates ───────────────────────────────────────────────────
def set_status(self, text):
if self._root and self._status_var:
try:
self._root.after(0, lambda t=text: self._status_var.set(t))
except Exception:
pass
def sync_style(self):
"""Called after Settings saves a new rephrase style."""
style = getattr(self._app, "_rephrase_style", REPHRASE_STYLES[0])
try:
self._style_idx = REPHRASE_STYLES.index(style)
except ValueError:
pass
if self._root and self._style_var:
try:
self._root.after(0, lambda s=style: self._style_var.set(s))
except Exception:
pass
# ── Canvas helper ─────────────────────────────────────────────────────────
@staticmethod
def _rounded_rect(canvas, x1, y1, x2, y2, r, **kw):
pts = [
x1 + r, y1, x2 - r, y1,
x2, y1, x2, y1 + r,
x2, y2 - r, x2, y2,
x2 - r, y2, x1 + r, y2,
x1, y2, x1, y2 - r,
x1, y1 + r, x1, y1,
]
canvas.create_polygon(pts, smooth=True, **kw)
# ── Drag ─────────────────────────────────────────────────────────────────
def _drag_start(self, event):
self._drag_x = event.x_root - self._root.winfo_x()
self._drag_y = event.y_root - self._root.winfo_y()
def _drag_move(self, event):
self._root.geometry(
f"+{event.x_root - self._drag_x}+{event.y_root - self._drag_y}"
)
# ── Style cycling ─────────────────────────────────────────────────────────
def _prev_style(self, _=None):
self._style_idx = (self._style_idx - 1) % len(REPHRASE_STYLES)
self._commit_style()
def _next_style(self, _=None):
self._style_idx = (self._style_idx + 1) % len(REPHRASE_STYLES)
self._commit_style()
def _commit_style(self):
style = REPHRASE_STYLES[self._style_idx]
if self._style_var:
self._style_var.set(style)
self._app._rephrase_style = style
try:
cfg = load_config()
cfg["rephrase_style"] = style
save_config(cfg)
except Exception:
pass
# ── Open settings / trigger rephrase ─────────────────────────────────────
def _open_settings(self, _=None):
SettingsWindow.open(self._app)
def _trigger_rephrase(self, _=None):
"""Triggered when the user clicks the style name — rephrases with current style."""
# Use the last tracked editor window, NOT GetForegroundWindow() which at
# click time returns the status bar's own HWND.
target_hwnd = self._last_target_hwnd or None
style = self._app._rephrase_style
target_hex = f"{target_hwnd:#010x}" if target_hwnd else "0"
print(f"[Rephrase] Status bar click. last_target_hwnd={target_hex} style={style!r}", flush=True)
threading.Thread(
target=self._app._run_rephrase_select_all,
args=(target_hwnd,),
daemon=True,
).start()
# ── Tk main loop ──────────────────────────────────────────────────────────
def _run(self):
T = _STATUSBAR_TRANSPARENT
W, H, R = self.W, self.H, self.RADIUS
ymid = H // 2
root = tk.Tk()
self._root = root
root.overrideredirect(True)
root.wm_attributes("-topmost", True)
root.wm_attributes("-alpha", 0.95)
root.wm_attributes("-transparentcolor", T)
root.configure(bg=T)
root.resizable(False, False)
sw = root.winfo_screenwidth()
root.geometry(f"{W}x{H}+{(sw - W) // 2}+48")
# Win11 rounded corners via DWM (safe no-op on Win10)
try:
root.update_idletasks()
ctypes.windll.dwmapi.DwmSetWindowAttribute(
root.winfo_id(), 33,
ctypes.byref(ctypes.c_int(2)), ctypes.sizeof(ctypes.c_int),
)
except Exception:
pass
# Prevent this window from ever stealing keyboard focus
GWL_EXSTYLE = -20
WS_EX_NOACTIVATE = 0x08000000
WS_EX_TOOLWINDOW = 0x00000080
SWP_NOMOVE = 0x0002
SWP_NOSIZE = 0x0001
SWP_NOZORDER = 0x0004
SWP_FRAMECHANGED = 0x0020
hwnd = root.winfo_id()
self._own_hwnd = hwnd
try:
cur = ctypes.windll.user32.GetWindowLongW(hwnd, GWL_EXSTYLE)
ctypes.windll.user32.SetWindowLongW(
hwnd, GWL_EXSTYLE,
cur | WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW,
)
# Force the extended-style change to take effect immediately
ctypes.windll.user32.SetWindowPos(
hwnd, 0, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED,
)
except Exception:
pass
# Background thread: track the last non-statusbar foreground window
def _fg_tracker():
while self._root is not None:
try:
fg = user32.GetForegroundWindow()
if fg and fg != self._own_hwnd:
self._last_target_hwnd = fg
except Exception:
pass
time.sleep(0.15)
threading.Thread(target=_fg_tracker, daemon=True).start()
# ── Canvas ───────────────────────────────────────────────────────────
canvas = tk.Canvas(root, width=W, height=H, bg=T, highlightthickness=0)
canvas.pack(fill="both", expand=True)
self._rounded_rect(canvas, 0, 0, W, H, R, fill=self.BG, outline=self.BG)
def _lbl(text="", textvariable=None, font=None, fg=None,
width=None, anchor="center", cursor="arrow"):
kw = dict(bg=self.BG, fg=fg or self.FG,
font=font or self._FONT, cursor=cursor)
if textvariable is not None:
kw["textvariable"] = textvariable
else:
kw["text"] = text
if width:
kw["width"] = width
if anchor:
kw["anchor"] = anchor
return tk.Label(root, **kw)
# ── ◀ left arrow ─────────────────────────────────────────────────────
btn_l = _lbl("◀", fg=self.ACCENT, cursor="hand2")
btn_l.bind("<Button-1>", self._prev_style)
btn_l.bind("<Enter>", lambda e: btn_l.config(fg="white"))
btn_l.bind("<Leave>", lambda e: btn_l.config(fg=self.ACCENT))
canvas.create_window(10, ymid, window=btn_l, anchor="w")
# ── style name (clickable — triggers rephrase) ───────────────────────────
self._style_var = tk.StringVar(value=REPHRASE_STYLES[self._style_idx])
lbl_style = _lbl(textvariable=self._style_var,
font=self._FONTB, width=13, anchor="center", cursor="hand2")
lbl_style.bind("<Button-1>", self._trigger_rephrase)
lbl_style.bind("<Enter>", lambda e: lbl_style.config(fg=self.ACCENT))
lbl_style.bind("<Leave>", lambda e: lbl_style.config(fg=self.FG))
canvas.create_window(26, ymid, window=lbl_style, anchor="w")
# ── ▶ right arrow ────────────────────────────────────────────────────
btn_r = _lbl("▶", fg=self.ACCENT, cursor="hand2")
btn_r.bind("<Button-1>", self._next_style)
btn_r.bind("<Enter>", lambda e: btn_r.config(fg="white"))
btn_r.bind("<Leave>", lambda e: btn_r.config(fg=self.ACCENT))
canvas.create_window(118, ymid, window=btn_r, anchor="w")
# ── separator ────────────────────────────────────────────────────────
canvas.create_line(134, 8, 134, H - 8, fill=self.SEP, width=1)
# ── status label ─────────────────────────────────────────────────────
self._status_var = tk.StringVar(value="Ready")
lbl_status = _lbl(textvariable=self._status_var,
fg=self.DIM, width=14, anchor="w")
canvas.create_window(140, ymid, window=lbl_status, anchor="w")
# ── gear ⚙ ───────────────────────────────────────────────────────────
btn_gear = _lbl("⚙", font=("Segoe UI", 11), fg=self.DIM, cursor="hand2")
btn_gear.bind("<Button-1>", self._open_settings)
btn_gear.bind("<Enter>", lambda e: btn_gear.config(fg=self.ACCENT))
btn_gear.bind("<Leave>", lambda e: btn_gear.config(fg=self.DIM))
canvas.create_window(W - 10, ymid, window=btn_gear, anchor="e")
# Prevent all widgets from grabbing keyboard focus when clicked
for w in (canvas, btn_l, btn_r, btn_gear, lbl_style, lbl_status):
try:
w.configure(takefocus=0)
except Exception:
pass
root.attributes("-topmost", True)
# drag on background + status label (NOT on style label — it triggers rephrase)
for w in (canvas, lbl_status):
w.bind("<ButtonPress-1>", self._drag_start)
w.bind("<B1-Motion>", self._drag_move)
root.protocol("WM_DELETE_WINDOW", lambda: None)
root.mainloop()
# ── Settings Window ─────────────────────────────────────────────────────────
class SettingsWindow:
"""Tkinter settings dialog — modern themed, grouped into sections."""
_instance_lock = threading.Lock()
_instance = None
# Dark theme colours
BG = "#1e1e2e"
BG2 = "#282840"
FG = "#cdd6f4"
DIM = "#6c7086"
ACCENT = "#a78bfa"
BORDER = "#45475a"
ENTRY_BG = "#313244"
BTN_BG = "#585b70"
BTN_FG = "#cdd6f4"
SAVE_BG = "#a78bfa"
SAVE_FG = "#1e1e2e"
@classmethod
def open(cls, app):
"""Open the settings window, or focus it if already open."""
with cls._instance_lock:
if cls._instance is not None:
try:
cls._instance._root.after(0, cls._instance._root.lift)
return
except Exception:
cls._instance = None
win = cls(app)
cls._instance = win
sb = FloatingStatusBar.get()
if sb and sb._root:
sb._root.after(0, win._run, sb._root)
else:
threading.Thread(target=win._run, daemon=True).start()
def __init__(self, app):
self._app = app
self._root = None
self._hotkey_var = None
self._dictation_hotkey_var = None
self._grammar_hotkey_var = None
self._grammar_mode_var = None
self._dictation_provider_var = None
self._grammar_provider_var = None
self._anthropic_api_key_var = None
self._anthropic_model_var = None
self._rephrase_style_var = None
self._recall_style_hotkey_var = None
self._voice_en_var = None
self._voice_es_var = None
self._speed_var = None
self._mic_device_var = None
self._recording = False
self._record_target = None
self._record_buttons = [] # all record buttons for disable/enable
self._en_codes = []
self._en_labels = []
self._es_codes = []
self._es_labels = []
self._style_hotkey_vars = {}
# ── Helpers ──────────────────────────────────────────────────────────────
def _make_section(self, parent, title):
"""Create a labelled section frame packed into parent. Returns body frame."""
wrapper = tk.Frame(parent, bg=self.BG)
wrapper.pack(fill="x", padx=8, pady=(6, 2))
# Section header
hdr = tk.Frame(wrapper, bg=self.BG)
hdr.pack(fill="x", pady=(0, 2))
tk.Label(hdr, text=title, font=("Segoe UI Semibold", 10),
bg=self.BG, fg=self.ACCENT).pack(side="left")
sep = tk.Frame(hdr, bg=self.BORDER, height=1)
sep.pack(side="left", fill="x", expand=True, padx=(8, 0), pady=1)
# Section body frame
body = tk.Frame(wrapper, bg=self.BG2, highlightbackground=self.BORDER,
highlightthickness=1)
body.pack(fill="x")
body.columnconfigure(1, weight=1)
return body
def _add_label(self, parent, text, row, col=0, **kw):
lbl = tk.Label(parent, text=text, font=("Segoe UI", 9),
bg=self.BG2, fg=self.FG, anchor="w")
lbl.grid(row=row, column=col, sticky="w", padx=(10, 4), pady=3, **kw)
return lbl
def _add_entry(self, parent, var, row, col=1, width=28, show=None, state="readonly"):
e = tk.Entry(parent, textvariable=var, width=width, font=("Segoe UI", 9),
bg=self.ENTRY_BG, fg=self.FG, insertbackground=self.FG,
relief="flat", highlightthickness=1,
highlightbackground=self.BORDER, highlightcolor=self.ACCENT)
if show:
e.config(show=show)
if state == "readonly":
e.config(state="readonly", readonlybackground=self.ENTRY_BG)
e.grid(row=row, column=col, sticky="ew", padx=4, pady=3)
return e
def _add_record_btn(self, parent, command, row, col=2):
b = tk.Button(parent, text="⏺", font=("Segoe UI", 8), width=3,
bg=self.BTN_BG, fg=self.BTN_FG, relief="flat",
activebackground=self.ACCENT, activeforeground=self.SAVE_FG,
cursor="hand2", command=command)