-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbolo.py
More file actions
2259 lines (2008 loc) · 92.7 KB
/
bolo.py
File metadata and controls
2259 lines (2008 loc) · 92.7 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
#!/usr/bin/env python3
"""
Bolo — Telnyx voice dictation menubar app.
Hold Right Option anywhere to dictate. Release to transcribe and inject.
"""
import concurrent.futures
import datetime
import io
import json
import logging
import os
import re
import signal
import subprocess
import threading
import time
import traceback
import wave
import collections
import numpy as np
import requests
import rumps
import sounddevice as sd
from commands import parse_command
from corrections import CorrectionStore
from overlay_controller import RecordingOverlay
from stt import SilenceDetector, TelnyxStreamingSTT
from transcript_state import TranscriptState, longest_common_prefix, merge_transcript
from vocabulary import VocabularyStore
from AppKit import (
NSEvent,
NSEventMaskFlagsChanged,
NSPasteboard,
NSPasteboardTypeString,
NSWorkspace,
)
from Quartz import (
CGEventCreateKeyboardEvent,
CGEventKeyboardSetUnicodeString,
CGEventPost,
CGEventSetFlags,
CGEventSourceFlagsState,
CGEventTapCreate,
CGEventTapEnable,
CGEventTapIsEnabled,
CFMachPortCreateRunLoopSource,
CFRunLoopAddSource,
CFRunLoopGetCurrent,
CFRunLoopRun,
CGEventGetFlags,
CGEventMaskBit,
kCGEventTapOptionListenOnly,
kCGHeadInsertEventTap,
kCGSessionEventTap,
kCGHIDEventTap,
kCGEventSourceStateCombinedSessionState,
kCGEventFlagsChanged,
)
from CoreFoundation import kCFRunLoopDefaultMode
import HIServices
# ── Logging ───────────────────────────────────────────────────────────────────
_LOG_FILE = "/tmp/bolo.log"
_log_handler = logging.FileHandler(_LOG_FILE, encoding="utf-8")
_log_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s", datefmt="%Y-%m-%dT%H:%M:%S"))
_console_handler = logging.StreamHandler()
_console_handler.setFormatter(logging.Formatter("%(message)s"))
_logger = logging.getLogger("bolo")
_logger.setLevel(logging.DEBUG)
_logger.addHandler(_log_handler)
_logger.addHandler(_console_handler)
_logger.propagate = False
# ── Config ────────────────────────────────────────────────────────────────────
def _load_env_value(name: str) -> str:
"""Load a config value.
Priority (highest first):
1. ~/.codex/.env — authoritative on-disk source; always wins so that
stale shell env vars (from a previous session) cannot shadow the key.
2. os.environ — useful for CI/test overrides when .codex/.env is absent.
3. ~/.zshrc — last-resort fallback.
"""
env_file = os.path.expanduser("~/.codex/.env")
if os.path.exists(env_file):
try:
with open(env_file, "r", encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, raw = line.split("=", 1)
if key.strip() == name:
val = raw.strip().strip("\"'")
if val:
return val
except OSError:
pass
value = os.environ.get(name, "").strip()
if value:
return value
shell_file = os.path.expanduser("~/.zshrc")
if os.path.exists(shell_file):
try:
with open(shell_file, "r", encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line.startswith(f"export {name}="):
continue
return line.split("=", 1)[1].strip().strip("\"'")
except OSError:
pass
return ""
TELNYX_API_KEY = _load_env_value("TELNYX_API_KEY")
_LITELLM_BASE = _load_env_value("LITELLM_BASE") or ""
_LITELLM_KEY = _load_env_value("LITELLM_KEY") or ""
STT_ENDPOINT = "https://api.telnyx.com/v2/ai/audio/transcriptions"
_TELNYX_LLM_ENDPOINT = "https://api.telnyx.com/v2/ai/chat/completions"
def _llm_endpoint() -> str:
"""Return the LLM chat-completions URL. Prefer LiteLLM proxy when available."""
if _LITELLM_BASE:
base = _LITELLM_BASE.rstrip("/")
if not base.endswith("/v1"):
base = base + "/v1"
return f"{base}/chat/completions"
return _TELNYX_LLM_ENDPOINT
def _llm_headers() -> dict:
"""Return Authorization headers for the active LLM backend."""
if _LITELLM_BASE and _LITELLM_KEY:
return {"Authorization": f"Bearer {_LITELLM_KEY}", "Content-Type": "application/json"}
return {"Authorization": f"Bearer {TELNYX_API_KEY}", "Content-Type": "application/json"}
def _llm_model() -> str:
"""Return model ID appropriate for the active backend."""
if _LITELLM_BASE:
return "MiniMax-M2.5-drop"
return "Qwen/Qwen3-235B-A22B"
SAMPLE_RATE = 16000
CHANNELS = 1
CORRECTION_WINDOW_SECONDS = 3.0
STREAM_DRAIN_SECONDS = 0.35
_SILENCE_PADDING = bytes(int(16000 * 0.35 * 2)) # 350ms of silence at 16kHz mono 16-bit
LLM_CLEANUP_MODE = _load_env_value("BOLO_LLM_CLEANUP").strip().lower() or "auto"
DELETE_KEYCODE = 51
RATE_LIMIT_BACKOFF_SECONDS = 45.0
MAX_RECORDING_SECONDS = 90.0 # force-stop if stuck recording longer than this
AUTO_SILENCE_SECONDS = 5.0 # stop after this many seconds of silence
AUTO_SILENCE_MAX_SECONDS = 5.0 # flat threshold — no extension logic
AUTO_SILENCE_EXTEND_STEP = 2.0 # unused, kept for reference
AUTO_SILENCE_MIN_SPEAKING = 2.0 # only trigger auto-stop after user has been speaking this long
BOLO_PREFS_FILE = os.path.expanduser("~/.bolo_prefs.json")
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ICON_IDLE = os.path.join(BASE_DIR, "icon_idle.png")
ICON_REC = os.path.join(BASE_DIR, "icon_recording.png")
CORRECTIONS_FILE = os.path.expanduser("~/.bolo_corrections.json")
BUILT_IN_VOCAB_FILE = os.path.join(BASE_DIR, "vocabulary.json")
USER_VOCAB_FILE = os.path.expanduser("~/.bolo_vocabulary.json")
BOLO_METRICS_FILE = os.path.expanduser("~/.bolo/metrics.jsonl")
CORRECTION_STORE = CorrectionStore(CORRECTIONS_FILE)
VOCAB_STORE = VocabularyStore(BUILT_IN_VOCAB_FILE, USER_VOCAB_FILE)
CODE_APPS = {
"Code",
"Visual Studio Code",
"Cursor",
"Xcode",
"Terminal",
"iTerm2",
"Warp",
}
# STT prompt limit: Whisper uses a 224-token window; 4 chars/token is a safe approximation.
_STT_PROMPT_MAX_CHARS = 224 * 4
def build_stt_prompt(vocab_terms: list, context_text: str = "") -> str:
"""
Build a short STT hint string for the Telnyx/Whisper `prompt` parameter.
Proper nouns and domain terms are listed first (highest leverage), followed
by a tail of the active text-field context so the model continues in the
right register. The result is capped at _STT_PROMPT_MAX_CHARS to stay
within Whisper's 224-token prompt window.
Returns an empty string when there is nothing useful to inject.
"""
parts = []
if vocab_terms:
# Comma-separated list of recognised terms
parts.append(", ".join(vocab_terms))
if context_text:
# Append the last 120 chars of the active field — enough for register
# continuity without blowing the token budget.
tail = context_text.strip()[-120:]
if tail:
parts.append(tail)
prompt = ". ".join(parts) if parts else ""
return prompt[:_STT_PROMPT_MAX_CHARS]
SYSTEM_PROMPT = (
"You are a transcription formatter. "
"Your only job is to apply minimal capitalization and punctuation fixes to a raw speech transcript. "
"Do not rewrite meaning. Do not summarize. Do not add or remove claims. "
"If the input is already good, return it unchanged. "
"Remove filler words and verbal tics that add no meaning: "
"'um', 'uh', 'hmm', 'like' when used as filler (not as a meaningful word), "
"'you know', 'I mean', 'sort of', 'kind of', 'basically', 'literally' when used as filler, "
"'and all', 'and everything', 'right?' at end of sentences when rhetorical. "
"Be conservative: only remove when the word is clearly filler with no semantic value. "
"Do not remove 'like' when it means 'similar to' or has real meaning. "
"Also fix these known brand name and term misrecognitions when context makes them obvious: "
"'whisper flow', 'wisper flow', 'Voisei', or 'Voisey' -> 'Wispr Flow'; "
"'telnyx' or close variants -> 'Telnyx'; "
"'bolo' -> 'Bolo'; "
"'remotion', 'emotion', 'emotions' (when referring to a framework) -> 'Remotion'; "
"'nova three' or 'nova 3' (when referring to a model) -> 'nova-3'; "
"'Quen', 'Queue When', or 'Kyuen' (when referring to the AI model) -> 'Qwen'. "
"Output only the cleaned transcript."
)
_CLEANUP_PROMPT_SLACK = (
"You are a transcription formatter for a casual chat message. "
"Fix obvious errors, remove filler words (um, uh, you know, like), and apply light punctuation. "
"Keep contractions (don't, I'm, it's). Do NOT add formal punctuation or restructure sentences. "
"Keep the tone casual and conversational. Output only the cleaned text."
)
_CLEANUP_PROMPT_MAIL = (
"You are a transcription formatter for an email message. "
"Fix grammar, apply proper sentence punctuation, remove filler words (um, uh, you know, kind of, sort of). "
"Use full sentences with correct capitalization. Maintain a professional but natural tone. "
"Do not add or remove content. Output only the cleaned text."
)
_CLEANUP_PROMPT_NOTES = (
"You are a transcription formatter for a notes or document app. "
"Fix grammar and punctuation. Remove filler words. "
"If the text appears to be a list or contains bullet-point structure, preserve that structure. "
"Apply light formatting improvements without changing meaning. Output only the cleaned text."
)
def _build_cleanup_prompt(app_name: str) -> str:
"""Return the system prompt variant appropriate for the given app."""
name = (app_name or "").lower()
if any(k in name for k in ("slack", "messages", "discord", "whatsapp", "telegram")):
return _CLEANUP_PROMPT_SLACK
if any(k in name for k in ("mail", "gmail", "outlook", "spark")):
return _CLEANUP_PROMPT_MAIL
if any(k in name for k in ("notes", "notion", "obsidian", "bear", "craft", "docs", "word")):
return _CLEANUP_PROMPT_NOTES
return SYSTEM_PROMPT
RECONCILE_PROMPT = (
"You reconcile two speech transcripts of the same utterance. "
"Choose the more accurate wording or combine them conservatively. "
"Do not add facts that are not present in either transcript. "
"Prefer the more complete ending, better grammar only when clearly supported, and preserve the speaker's meaning. "
"Output only the final transcript."
)
KNOWN_TERM_PATTERNS = (
(re.compile(r"\bwhisper flow\b|\bwhisper of four\b|\bwisper flow\b|\bvoisei\b|\bvoisey\b", re.IGNORECASE), "Wispr Flow"),
(re.compile(r"\btelnyx\b|\btelenix\b|\btennis\b|\btennix\b", re.IGNORECASE), "Telnyx"),
(re.compile(r"\bbolo\b|\bbollo\b", re.IGNORECASE), "Bolo"),
(re.compile(r"\bremotion\b|\bemotion\b|\bemotions\b|\bmotion\b", re.IGNORECASE), "Remotion"),
(re.compile(r"\bgrokwise\b|\bcrocawise\b|\bgrok wise\b|\bcroca wise\b", re.IGNORECASE), "Grokwise"),
(re.compile(r"\bnova[ -]three\b|\bnova 3\b", re.IGNORECASE), "nova-3"),
(re.compile(r"\bquen\b|\bqueue when\b|\bkyuen\b|\bkwan\b", re.IGNORECASE), "Qwen"),
(re.compile(r"\bsonne\b|\bsonet\b|\bsonnet\b", re.IGNORECASE), "Sonnet"),
(re.compile(r"\bkimi\s*k\s*2\.?5\b|\bkimi\s*k2\.?5\b", re.IGNORECASE), "Kimi K2.5"),
(re.compile(r"\bclaude\s+sony\b|\bclaude\s+sonne\b|\bclaude\s+sonet\b", re.IGNORECASE), "Claude Sonnet"),
)
# Filler patterns applied as a pre-LLM cleanup pass.
# Ordered from most to least greedy. Each entry: (compiled regex, replacement).
FILLER_PATTERNS = [
# Standalone hesitation sounds at the start, middle, or end of a phrase
(re.compile(r'\b(um+|uh+|hmm+|mhm)\b[,.]?\s*', re.IGNORECASE), ''),
# "you know" as filler
(re.compile(r'\byou know[,.]?\s*', re.IGNORECASE), ''),
# "and all" only at end of phrase (not "and all of ...")
(re.compile(r'\band all\b(?!\s+of)\b[,.]?\s*$', re.IGNORECASE), ''),
# trailing rhetorical "right?" or ", right?"
(re.compile(r',?\s*\bright\??\s*$', re.IGNORECASE), ''),
]
# ── Bolo app ──────────────────────────────────────────────────────────────────
class BoloApp(rumps.App):
def __init__(self):
super().__init__("Bolo", icon=ICON_IDLE, title="⌥", template=True, quit_button=None)
self.recording = False
self.audio_frames = []
self.lock = threading.Lock()
self.last_error = None
self.last_pipeline = 0.0
self.menu = [
rumps.MenuItem("Bolo — Voice Dictation", callback=None),
None,
rumps.MenuItem("Hold Right Option to dictate", callback=None),
None,
rumps.MenuItem("Last transcript", callback=self._copy_last),
rumps.MenuItem("History", callback=None),
None,
rumps.MenuItem("Auto-stop on silence", callback=self._toggle_auto_silence),
rumps.MenuItem("Clipboard paste mode", callback=self._toggle_clipboard_mode),
None,
rumps.MenuItem("Quit Bolo", callback=self.quit_app),
]
self.menu["Bolo — Voice Dictation"].set_callback(None)
self.menu["Hold Right Option to dictate"].set_callback(None)
self.menu["History"].set_callback(None)
self.last_result = None
self.last_raw = None
self.last_paste_time = 0.0
self._rate_limit_backoff_until = 0.0
self.correction_window_until = 0.0
self.correction_mode = False
self.session_history = collections.deque(maxlen=10)
self.overlay = RecordingOverlay(BASE_DIR)
self._overlay_hide_timer = None
self._session_seq = 0
self._active_session_id = 0
self._session_phase = "idle"
# Auto-silence feature (Wispr Flow parity)
prefs = self._load_prefs()
self._auto_silence_enabled = prefs.get("auto_silence_enabled", True)
self._clipboard_mode_enabled = prefs.get("clipboard_mode_enabled", False)
self._update_auto_silence_menu()
self._update_clipboard_mode_menu()
# Streaming STT state
self._stt = None
self._transcript_state = None
self._transcript_lock = threading.Lock()
self._warm_stt = None
self._warm_stt_lock = threading.Lock()
self._warm_stt_connecting = False
self._warm_stt_connected_at: float = 0.0
self._stream_auth_failed = False # set on first 401; blocks all warm retries
self._silence = SilenceDetector()
self._silence_event = threading.Event()
self._chunk_time = time.time()
self._record_started_at = 0.0
self._stream_connected_at = None
self._last_overlay_preview_at = 0.0
self._overlay_stall_notice_shown = False
self.stream = None # opened only during recording
self._current_context = ""
self._context_aware = True
self._ropt_held = False
self._ns_monitor = None # deprecated: using CGEventTap now
self._key_event = None # "press" or "release" set by handler
self._last_press_at = 0.0
self._last_key_recovery_check = 0.0
# CGEventTap state
self._cg_tap = None
self._cg_tap_thread = None
self._cg_tap_enabled = False
# Panic reset: triple-tap Right Option to force reset
self._panic_presses = []
self._PANIC_WINDOW = 1.0 # 1 second to triple-tap
# Start CGEventTap hotkey listener (more reliable than NSEvent)
self._start_cgevent_tap()
# Poll key events and watchdogs on main thread
rumps.Timer(self._process_key_events, 0.02).start()
rumps.Timer(self._watchdog_cg_tap, 2).start() # Restart tap if disabled
rumps.Timer(self._watchdog_overlay_health, 1.0).start() # Monitor overlay
rumps.Timer(self._watchdog_overlay_preview, 0.5).start()
rumps.Timer(self._watchdog_recording, 5).start()
self._ensure_warm_stream()
# ── Prefs ─────────────────────────────────────────────────────────────────
def _load_prefs(self):
try:
with open(BOLO_PREFS_FILE, "r", encoding="utf-8") as fh:
return json.load(fh)
except (OSError, json.JSONDecodeError):
return {}
def _save_prefs(self, prefs):
try:
with open(BOLO_PREFS_FILE, "w", encoding="utf-8") as fh:
json.dump(prefs, fh, indent=2)
except OSError as e:
self._log(f"[prefs] failed to save: {e}")
def _update_auto_silence_menu(self):
label = "Auto-stop on silence " + ("✓" if self._auto_silence_enabled else "")
self.menu["Auto-stop on silence"].title = label.strip()
def _toggle_auto_silence(self, _):
self._auto_silence_enabled = not self._auto_silence_enabled
self._update_auto_silence_menu()
prefs = self._load_prefs()
prefs["auto_silence_enabled"] = self._auto_silence_enabled
self._save_prefs(prefs)
self._log(f"[silence] auto-stop {'enabled' if self._auto_silence_enabled else 'disabled'}")
def _update_clipboard_mode_menu(self):
label = "Clipboard paste mode " + ("✓" if self._clipboard_mode_enabled else "")
self.menu["Clipboard paste mode"].title = label.strip()
def _toggle_clipboard_mode(self, _):
self._clipboard_mode_enabled = not self._clipboard_mode_enabled
self._update_clipboard_mode_menu()
prefs = self._load_prefs()
prefs["clipboard_mode_enabled"] = self._clipboard_mode_enabled
self._save_prefs(prefs)
self._log(f"[clipboard] paste mode {'enabled' if self._clipboard_mode_enabled else 'disabled'}")
def _begin_session(self):
self._session_seq += 1
self._active_session_id = self._session_seq
self._session_phase = "recording"
return self._active_session_id
def _is_current_session(self, session_id):
return session_id == self._active_session_id
def _set_session_phase(self, phase, session_id=None):
if session_id is not None and not self._is_current_session(session_id):
return False
self._session_phase = phase
return True
def _normalize_transcript_text(self, text):
text = (text or "").strip()
if not text:
return ""
text = re.sub(r"([.!?])([A-Za-z])", r"\1 \2", text)
text = re.sub(r"([,;:])([A-Za-z])", r"\1 \2", text)
text = re.sub(r"([a-z])([A-Z])", r"\1 \2", text)
text = re.sub(r"\s+", " ", text)
return text.strip()
def _canonicalize_known_terms(self, text):
text = (text or "").strip()
if not text:
return ""
for pattern, replacement in KNOWN_TERM_PATTERNS:
text = pattern.sub(replacement, text)
return text
def _remove_fillers(self, text):
"""Strip isolated filler words/sounds that add no semantic value."""
text = (text or "").strip()
if not text:
return ""
for pattern, replacement in FILLER_PATTERNS:
text = pattern.sub(replacement, text)
# Clean up whitespace and punctuation artifacts left by removals
text = re.sub(r' +', ' ', text) # collapse double spaces
text = re.sub(r'^\s*[,;]\s*', '', text) # leading comma/semicolon
text = re.sub(r'\s+([.,!?;:])', r'\1', text) # space before punctuation
return text.strip()
# ── Context awareness ─────────────────────────────────────────────────────
def _get_focused_text_context(self) -> str:
"""Read the last 500 chars of the currently focused text field via accessibility API."""
try:
focused_system = HIServices.AXUIElementCreateSystemWide()
err, focused_el = HIServices.AXUIElementCopyAttributeValue(
focused_system, "AXFocusedUIElement", None
)
if err != 0 or focused_el is None:
return ""
err, value = HIServices.AXUIElementCopyAttributeValue(
focused_el, "AXValue", None
)
if err != 0 or not value:
return ""
text = str(value)
return text[-500:].strip() if len(text) > 500 else text.strip()
except Exception:
return ""
def _apply_context_capitalization(self, text: str, context: str) -> str:
"""Lower the first character of text if the context indicates we are mid-sentence."""
if not text or not context:
return text
context_stripped = context.rstrip()
if not context_stripped:
return text
last_char = context_stripped[-1]
# Mid-sentence indicators: comma, colon, semicolon, or no ending punctuation at all
sentence_enders = {".", "!", "?"}
if last_char not in sentence_enders:
# We are mid-sentence: do not capitalize the first word
return text[0].lower() + text[1:]
return text
# ── Audio ─────────────────────────────────────────────────────────────────
def _audio_callback(self, indata, frames, time_info, status):
if not self.recording:
return
self.audio_frames.append(indata.copy())
pcm = indata.tobytes()
# Stream to WebSocket
if self._stt:
try:
self._stt.send_audio(pcm)
except Exception:
pass
# Silence detection
now = time.time()
elapsed = now - self._chunk_time
self._chunk_time = now
result = self._silence.process(pcm, elapsed)
if result == "end_of_utterance":
self._silence_event.set()
def _to_wav_bytes(self, audio):
buf = io.BytesIO()
with wave.open(buf, "wb") as wf:
wf.setnchannels(CHANNELS)
wf.setsampwidth(2)
wf.setframerate(SAMPLE_RATE)
wf.writeframes(audio.tobytes())
return buf.getvalue()
# ── Hotkey (NSEvent global monitor) ───────────────────────────────────
# Right Option = NX_DEVICERALTKEYMASK (bit 6 of device-dep flags)
_NX_DEVICERALTKEYMASK = 0x00000040
def _is_right_option_down(self):
try:
flags = CGEventSourceFlagsState(kCGEventSourceStateCombinedSessionState)
except Exception:
return self._ropt_held
return bool(flags & self._NX_DEVICERALTKEYMASK)
def _stream_ends_at_sentence_boundary(self) -> bool:
"""Check if the latest stream transcript ends with sentence-terminal punctuation."""
state = self._transcript_state
if not state:
return True # no transcript state, allow stop
text = state.display_text().strip()
if not text:
return True # nothing transcribed, allow stop
return text[-1] in ".?!"
def _process_key_events(self, _):
# Silence auto-stop
if self._silence_event.is_set():
self._silence_event.clear()
if self.recording:
elapsed_recording = time.time() - self._record_started_at
if elapsed_recording >= AUTO_SILENCE_MIN_SPEAKING:
self._log(
f"[silence] end of utterance after {elapsed_recording:.1f}s -- stopping"
)
self._stop_recording()
else:
# Too early: reset so it can fire again once the user has spoken long enough
self._log(
f"[silence] ignored early trigger ({elapsed_recording:.1f}s < "
f"{AUTO_SILENCE_MIN_SPEAKING}s min)"
)
self._silence.reset()
threshold = AUTO_SILENCE_SECONDS if self._auto_silence_enabled else 9999.0
self._silence.set_silence_threshold(threshold)
return
# AGGRESSIVE RECOVERY: Check actual key state every tick
is_down = self._is_right_option_down()
# Case 1: We think key is held, but it's actually up -> force release
if self._ropt_held and not is_down:
self._ropt_held = False
if self._key_event != "release":
self._log("[key] RECOVERY: synthesized release (missed event)")
self._key_event = "release"
# Case 2: We think key is up, but it's actually held -> might be stuck from previous session
# Only recover if not currently recording (avoid double-trigger while active)
elif not self._ropt_held and is_down and not self.recording:
# Check if we've been stuck for a while (key held but we missed the press)
if time.time() - self._last_key_recovery_check > 2.0:
self._ropt_held = True
self._last_press_at = time.time()
self._log("[key] RECOVERY: synthesized press (missed event)")
self._key_event = "press"
self._last_key_recovery_check = time.time()
event = self._key_event
if event is None:
return
self._key_event = None
if event == "press":
self.correction_mode = False
self._last_press_at = time.time()
self._log("[key] Right Option pressed")
self._start_recording()
elif event == "release":
self._log("[key] Right Option released")
if self.recording:
self._stop_recording()
def _watchdog_tap(self, _):
# NSEvent monitors are never disabled by macOS — just log if monitor was lost.
if self._ns_monitor is None:
self._log("[tap] NSEvent monitor is None — re-registering")
self._start_nsevent_monitor()
def _start_nsevent_monitor(self):
"""Register an NSEvent global monitor for flagsChanged events.
NSEvent monitors are never disabled by macOS (unlike CGEventTap),
so no watchdog re-enable loop is needed.
"""
if not HIServices.AXIsProcessTrusted():
self._log(
"[accessibility] NOT TRUSTED. Open System Settings > "
"Privacy & Security > Accessibility and add this app."
)
HIServices.AXIsProcessTrustedWithOptions(
{HIServices.kAXTrustedCheckOptionPrompt: True}
)
self._ns_monitor = NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(
NSEventMaskFlagsChanged,
self._nsevent_flags_handler,
)
if self._ns_monitor is None:
self._log("[tap] NSEvent monitor creation failed — Accessibility not granted?")
else:
self._log("[tap] NSEvent global monitor active, listening for Right Option")
def _nsevent_flags_handler(self, event):
"""Called on every modifier flag change via NSEvent global monitor."""
flags = event.modifierFlags()
ropt_down = bool(flags & self._NX_DEVICERALTKEYMASK)
if ropt_down and not self._ropt_held:
if self.recording:
# Spurious key-down while already recording — ignore to prevent state reset
self._log("[key] spurious Right Option down while recording — ignored")
self._ropt_held = True # still track so release is recognized
return
self._ropt_held = True
self._last_press_at = time.time()
self._key_event = "press"
elif not ropt_down and self._ropt_held:
self._ropt_held = False
self._key_event = "release"
# ── CGEventTap Hotkey Listener (Primary) ───────────────────────────────
def _cgevent_callback(self, proxy, event_type, event, refcon):
"""Callback for CGEventTap - called on every event in the tap.
More reliable than NSEvent global monitor because it runs at lower level
and can be re-enabled if macOS disables it.
Also implements panic reset: triple-tap Right Option to force reset.
"""
if event_type == kCGEventFlagsChanged:
flags = CGEventGetFlags(event)
ropt_down = bool(flags & self._NX_DEVICERALTKEYMASK)
# Panic reset detection: track press releases in a 1-second window
if ropt_down:
now = time.time()
self._panic_presses.append(now)
# Keep only presses in the last second
self._panic_presses = [t for t in self._panic_presses if now - t < self._PANIC_WINDOW]
# Triple-tap detected
if len(self._panic_presses) >= 3:
self._log("[panic] triple-tap Right Option detected — forcing reset")
self._panic_reset()
self._panic_presses = []
if ropt_down and not self._ropt_held:
if self.recording:
# Spurious key-down while already recording — ignore
self._log("[tap] spurious Right Option down while recording — ignored")
self._ropt_held = True
else:
self._ropt_held = True
self._last_press_at = time.time()
self._key_event = "press"
self._log("[tap] Right Option pressed (CGEventTap)")
elif not ropt_down and self._ropt_held:
self._ropt_held = False
self._key_event = "release"
self._log("[tap] Right Option released (CGEventTap)")
return event
def _panic_reset(self):
"""Force reset all state — emergency recovery for wedged hotkey."""
self._log("[panic] executing force reset")
# Force stop recording if active
if self.recording:
self._log("[panic] forcing recording stop")
try:
self._stop_recording()
except Exception as e:
self._log(f"[panic] error stopping recording: {e}")
# Reset key state
self._ropt_held = False
self._key_event = None
# Force kill overlay
try:
self.overlay.force_kill()
except Exception as e:
self._log(f"[panic] error killing overlay: {e}")
# Play error sound so user knows reset happened
try:
self._play("Basso")
except Exception:
pass
self._log("[panic] force reset complete")
def _start_cgevent_tap(self):
"""Create and enable a CGEventTap for modifier key events.
CGEventTap is lower-level than NSEvent and more reliable, but can be
disabled by macOS if the process stalls. We watchdog-re-enable it.
"""
def tap_thread():
# Create the event tap for flags changed events
self._cg_tap = CGEventTapCreate(
kCGSessionEventTap, # Session scope (not HID - works without root)
kCGHeadInsertEventTap, # Insert at head of event stream
kCGEventTapOptionListenOnly, # Don't intercept, just observe
CGEventMaskBit(kCGEventFlagsChanged), # Only modifier key events
self._cgevent_callback,
None
)
if self._cg_tap is None:
self._log("[tap] CGEventTap creation failed — need Accessibility permission")
# Fall back to NSEvent
self._start_nsevent_monitor()
return
# Get the runloop source
run_loop_source = CFMachPortCreateRunLoopSource(None, self._cg_tap, 0)
# Add to current runloop (default mode)
from CoreFoundation import kCFRunLoopDefaultMode
CFRunLoopAddSource(CFRunLoopGetCurrent(), run_loop_source, kCFRunLoopDefaultMode)
# Enable the tap
CGEventTapEnable(self._cg_tap, True)
self._cg_tap_enabled = True
self._log("[tap] CGEventTap active (with watchdog)")
# Run the loop
CFRunLoopRun()
# Start in a daemon thread
self._cg_tap_thread = threading.Thread(target=tap_thread, daemon=True)
self._cg_tap_thread.start()
def _watchdog_cg_tap(self, _):
"""Watchdog: re-enable CGEventTap if macOS disabled it."""
if self._cg_tap is None:
return # Fall back mode
if not CGEventTapIsEnabled(self._cg_tap):
self._log("[tap] CGEventTap was disabled by macOS — re-enabling")
CGEventTapEnable(self._cg_tap, True)
def _watchdog_overlay_health(self, _):
"""Watchdog: monitor overlay process and restart if dead while showing."""
# If overlay died while supposed to be showing, force hide to clean state
if self.overlay._is_showing and not self.overlay.is_alive():
self._log("[overlay] died while showing — forcing hide to reset")
self.overlay._proc = None
self.overlay._is_showing = False
# If we're recording, stop to avoid stuck state
if self.recording:
self._log("[overlay] overlay died during recording — stopping")
self._stop_recording()
# ── Record ────────────────────────────────────────────────────────────────
def _play(self, sound):
subprocess.Popen(["afplay", f"/System/Library/Sounds/{sound}.aiff"])
def _ensure_warm_stream(self):
if self._stream_auth_failed:
return # API key is bad — don't hammer the endpoint
with self._warm_stt_lock:
if self.recording or self._stt or self._warm_stt or self._warm_stt_connecting:
return
self._warm_stt_connecting = True
threading.Thread(target=self._warm_stream_worker, daemon=True).start()
def _warm_stream_worker(self):
stt = TelnyxStreamingSTT()
try:
stt.connect(TELNYX_API_KEY, keywords=VOCAB_STORE.terms())
except Exception as e:
err_msg = str(e)
self._log(f"[stream] warm connect failed: {e}")
if "401" in err_msg or "Unauthorized" in err_msg or "auth" in err_msg.lower():
self._stream_auth_failed = True
self._rate_limit_backoff_until = time.time() + 86400.0
self._log("[stream] 401 auth failure — disabling stream. Fix API key and restart.")
self._show_error("Invalid API key — check ~/.codex/.env")
with self._warm_stt_lock:
self._warm_stt_connecting = False
return
with self._warm_stt_lock:
if self.recording or self._stt or self._warm_stt:
self._warm_stt_connecting = False
try:
stt.close()
except Exception:
pass
return
self._warm_stt = stt
self._warm_stt_connected_at = time.time()
self._warm_stt_connecting = False
self._log("[stream] warm connection ready")
def _claim_warm_stream(self):
with self._warm_stt_lock:
stt = self._warm_stt
age = time.time() - self._warm_stt_connected_at
if stt is not None and age > 45.0:
self._log(f"[stream] warm stream stale ({age:.1f}s), discarding")
try:
stt.close()
except Exception:
pass
stt = None
self._warm_stt = None
self._warm_stt_connecting = False
return stt
def _start_recording(self):
if self._overlay_hide_timer is not None:
self._overlay_hide_timer.cancel()
self._overlay_hide_timer = None
# Backoff / auth-failure check — give user feedback instead of silently ignoring
backoff_remaining = self._rate_limit_backoff_until - time.time()
if backoff_remaining > 0:
self._play("Basso")
self.overlay.show()
if self._stream_auth_failed:
self.overlay.update("error", "Invalid API key — restart required")
else:
wait_sec = int(backoff_remaining) + 1
self.overlay.update("error", f"Rate limited - wait {wait_sec}s")
self._hide_overlay_after_delay(1.5)
return
with self.lock:
if self.recording:
return
if time.time() - self.last_pipeline < 1.5:
return
self.audio_frames = []
self.recording = True
session_id = self._begin_session()
self._record_started_at = time.time()
self._stream_connected_at = None
self._last_overlay_preview_at = self._record_started_at
self._overlay_stall_notice_shown = False
self.icon = ICON_REC
self.title = "⌥"
self._silence.reset()
if self._context_aware:
self._current_context = self._get_focused_text_context()
if self._current_context:
self._log(f"[context] captured {len(self._current_context)} chars from focused field")
else:
self._current_context = ""
threshold = AUTO_SILENCE_SECONDS if self._auto_silence_enabled else 9999.0
self._silence.set_silence_threshold(threshold)
self._silence_event.clear()
self._chunk_time = time.time()
self._transcript_state = TranscriptState()
# IMMEDIATELY give user feedback — don't wait for stream/context
self._play("Tink")
self.overlay.show()
self.overlay.update("listening", "")
self._set_session_phase("recording", session_id)
self._stt = self._claim_warm_stream()
if self._stt is not None:
self._stream_connected_at = time.time()
threading.Thread(target=self._drain_stream_transcripts, daemon=True).start()
else:
threading.Thread(target=self._connect_stream_async, daemon=True).start()
for attempt in range(3):
try:
self.stream = sd.InputStream(
samplerate=SAMPLE_RATE, channels=CHANNELS,
dtype="int16", callback=self._audio_callback)
self.stream.start()
break
except Exception as e:
self._log(f"[mic] error opening stream (attempt {attempt+1}): {e}")
time.sleep(0.5)
else:
self._log("[mic] failed to open after 3 attempts — skipping")
if self._stt:
self._stt.close()
self._stt = None
with self.lock:
self.recording = False
self._ensure_warm_stream()
return
def _connect_stream_async(self) -> None:
"""Connect a fresh STT WebSocket in background; catch up with buffered audio."""
stt = TelnyxStreamingSTT()
try:
stt.connect(TELNYX_API_KEY, keywords=VOCAB_STORE.terms())
except Exception as e:
err_msg = str(e)
self._log(f"[stream] async connect failed: {e}")
if "401" in err_msg or "Unauthorized" in err_msg or "auth" in err_msg.lower():
self._stream_auth_failed = True
self._rate_limit_backoff_until = time.time() + 86400.0
self._log("[stream] 401 auth failure — disabling stream. Fix API key and restart.")
self._show_error("Invalid API key — check ~/.codex/.env")
return
if not self.recording:
# Recording ended before we connected — discard
try:
stt.close()
except Exception:
pass
return
# Catch up: send audio frames already captured before stream was ready
with self.lock:
buffered = list(self.audio_frames)
if buffered:
try:
pcm = np.concatenate(buffered, axis=0).tobytes()
stt.send_audio(pcm) # First call prepends WAV header automatically
except Exception:
pass
with self.lock:
self._stt = stt
self._stream_connected_at = time.time()
self._log(f"[stream] async connected at +{int((time.time() - self._record_started_at)*1000)}ms")
threading.Thread(target=self._drain_stream_transcripts, daemon=True).start()
def _watchdog_overlay_preview(self, _):
if not self.recording:
return
if not self._last_overlay_preview_at:
return
since_last_partial = time.time() - self._last_overlay_preview_at
if since_last_partial < 2.0:
return
# No stream partial received in 2s: show a live word-count estimate