-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcodec_dictate.py
More file actions
663 lines (595 loc) · 25.8 KB
/
codec_dictate.py
File metadata and controls
663 lines (595 loc) · 25.8 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
#!/usr/bin/env python3
"""
CODEC Dictate — Hold-to-Speak + Live Typing
Hold ⌘R → speak → release → text pasted at cursor
L → live typing mode (words appear in real-time wherever cursor is)
Requirements: pynput, pyautogui, faster-whisper, Pillow, requests
"""
import threading
import tempfile
import subprocess
import sys
import os
import time
import pyautogui
import pyperclip
from pynput import keyboard
from faster_whisper import WhisperModel
# ── CONFIG ──────────────────────────────────────────────────────────────────
WHISPER_MODEL_SIZE = "base" # tiny / base / small — base is best balance
WHISPER_DEVICE = "cpu" # mac uses cpu for faster-whisper
WHISPER_COMPUTE = "int8"
SAMPLE_RATE = 16000
CHANNELS = 1
CHUNK_DURATION_MS = 30 # ms per audio chunk
# ── STATE ────────────────────────────────────────────────────────────────────
recording = False
audio_frames = []
cmd_held = False
overlay_proc = None
model = None
model_loaded = threading.Event()
# ── HANDS-FREE LIVE DICTATION STATE ─────────────────────────────────────────
live_active = False
live_overlay = None
live_thread = None
live_stop_event = threading.Event()
live_text_file = os.path.join(tempfile.gettempdir(), "codec_live_dictate.txt")
# Live dictation triggered by F5 key
# ── WHISPER HALLUCINATION FILTER ──────────────────────────────────────────────
WHISPER_HALLUCINATIONS = {
"you", "thank you", "thank you.", "thanks.", "thanks for watching.",
"thank you for watching.", "please subscribe.", "bye.", "the end.",
"thanks for watching!", "like and subscribe.", "see you next time.",
"subscribe to the channel.", "please like and subscribe.",
"subtitles by the amara.org community", "...", "",
}
def is_hallucination(text):
"""Check if transcribed text is a known Whisper hallucination."""
t = text.strip().lower()
if not t or len(t) <= 1:
return True
if t in WHISPER_HALLUCINATIONS:
return True
# Repetitive gibberish (same word 5+ times)
words = t.split()
if len(words) >= 5 and len(set(words)) == 1:
return True
return False
# ── LOAD WHISPER ─────────────────────────────────────────────────────────────
def load_model():
global model
print("[DICTATE] Loading Whisper model...")
model = WhisperModel(WHISPER_MODEL_SIZE, device=WHISPER_DEVICE, compute_type=WHISPER_COMPUTE)
model_loaded.set()
print("[DICTATE] Whisper ready.")
# ── OVERLAY (tiny floating window) ───────────────────────────────────────────
def show_overlay():
global overlay_proc
try:
script = """
import tkinter as tk
root = tk.Tk()
root.overrideredirect(True)
root.attributes('-topmost', True)
root.attributes('-alpha', 0.95)
root.configure(bg='#111111')
sw = root.winfo_screenwidth()
sh = root.winfo_screenheight()
w, h = 680, 88
x = (sw - w) // 2
y = sh - 120
root.geometry(f'{w}x{h}+{x}+{y}')
c = tk.Canvas(root, bg='#111111', highlightthickness=0, width=w, height=h)
c.pack()
c.create_rectangle(2, 2, w-2, h-2, outline='#E8711A', width=2)
dot = c.create_oval(24, 30, 40, 46, fill='#ff3b3b', outline='')
c.create_text(w//2+10, 28, text='Listening \\u2014 release \\u2318 to transcribe', fill='#ffffff', font=('SF Pro Display', 16, 'bold'))
c.create_text(w//2+10, 58, text='Press F5 for hands-free live typing', fill='#777777', font=('SF Pro Display', 12))
def pulse():
cur = c.itemcget(dot,'fill')
c.itemconfig(dot, fill='#ff3b3b' if cur=='#440000' else '#440000')
root.after(500, pulse)
pulse()
root.mainloop()
"""
overlay_proc = subprocess.Popen(
[sys.executable, "-c", script],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
except Exception as e:
print(f"[DICTATE] Overlay error: {e}")
def hide_overlay():
global overlay_proc
if overlay_proc:
try:
overlay_proc.terminate()
overlay_proc = None
except:
pass
# ── SHOW PROCESSING OVERLAY ───────────────────────────────────────────────────
def show_processing():
try:
script = """
import tkinter as tk
import sys
root = tk.Tk()
root.overrideredirect(True)
root.attributes('-topmost', True)
root.attributes('-alpha', 0.93)
root.configure(bg='#0a0a0a')
sw = root.winfo_screenwidth()
sh = root.winfo_screenheight()
w, h = 520, 90
x = (sw - w) // 2
y = sh - 130
root.geometry(f'{w}x{h}+{x}+{y}')
c = tk.Canvas(root, bg='#0a0a0a', highlightthickness=0, width=w, height=h)
c.pack()
c.create_rectangle(1,1,w-1,h-1, outline='#00aaff', width=1)
c.create_text(w//2, h//2, text='\u26a1 Transcribing...', fill='#00aaff', font=('Helvetica', 13))
root.after(20000, root.destroy)
root.mainloop()
"""
p = subprocess.Popen(
[sys.executable, "-c", script],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
return p
except:
return None
# ── LIVE DICTATION (hands-free, double-tap Option) ──────────────────────────
WHISPER_SERVER = "http://localhost:8084/v1/audio/transcriptions"
SOX_PATH = "/opt/homebrew/bin/sox"
def _live_overlay_script_appkit_DISABLED():
"""AppKit NSPanel (non-activating) — kept but disabled because on some
macOS builds it renders nothing visible when launched from a pm2-managed
background process. Tkinter fallback below is used instead."""
return """
import os, sys, objc
from AppKit import (NSApplication, NSPanel, NSColor, NSTextField, NSFont,
NSView, NSMakeRect, NSScreen, NSBezierPath,
NSBorderlessWindowMask, NSNonactivatingPanelMask,
NSUtilityWindowMask, NSObject)
from Foundation import NSTimer
app = NSApplication.sharedApplication()
app.setActivationPolicy_(2)
screen = NSScreen.mainScreen()
sf = screen.frame()
w, h = 210, 34
x = sf.size.width - w - 20
y = sf.size.height - h - 40
panel = NSPanel.alloc().initWithContentRect_styleMask_backing_defer_(
NSMakeRect(x, y, w, h),
NSBorderlessWindowMask | NSNonactivatingPanelMask | NSUtilityWindowMask,
2, False
)
panel.setLevel_(25)
panel.setOpaque_(False)
panel.setHasShadow_(True)
panel.setAlphaValue_(0.95)
panel.setBackgroundColor_(NSColor.clearColor())
panel.setIgnoresMouseEvents_(True)
panel.setCollectionBehavior_(1 << 0 | 1 << 4)
class OverlayView(NSView):
def drawRect_(self, rect):
bg = NSColor.colorWithCalibratedRed_green_blue_alpha_(0.04, 0.04, 0.04, 0.95)
bg.setFill()
NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(rect, 8, 8).fill()
border = NSColor.colorWithCalibratedRed_green_blue_alpha_(1.0, 0.23, 0.23, 0.9)
border.setStroke()
inset = NSMakeRect(0.5, 0.5, rect.size.width - 1, rect.size.height - 1)
bp = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(inset, 8, 8)
bp.setLineWidth_(1.0)
bp.stroke()
view = OverlayView.alloc().initWithFrame_(NSMakeRect(0, 0, w, h))
panel.setContentView_(view)
# Pulsing red dot (custom view)
class DotView(NSView):
_bright = True
def drawRect_(self, rect):
if self._bright:
c = NSColor.colorWithCalibratedRed_green_blue_alpha_(1.0, 0.23, 0.23, 1.0)
else:
c = NSColor.colorWithCalibratedRed_green_blue_alpha_(0.4, 0.05, 0.05, 1.0)
c.setFill()
NSBezierPath.bezierPathWithOvalInRect_(rect).fill()
dot = DotView.alloc().initWithFrame_(NSMakeRect(12, 11, 12, 12))
view.addSubview_(dot)
label = NSTextField.alloc().initWithFrame_(NSMakeRect(30, 8, w - 36, 20))
label.setStringValue_('LIVE · press L to stop')
label.setFont_(NSFont.boldSystemFontOfSize_(12))
label.setTextColor_(NSColor.colorWithCalibratedRed_green_blue_alpha_(1.0, 0.35, 0.35, 1.0))
label.setBackgroundColor_(NSColor.clearColor())
label.setBezeled_(False)
label.setEditable_(False)
label.setSelectable_(False)
view.addSubview_(label)
class PulseDelegate(NSObject):
@objc.python_method
def setup(self, d):
self._d = d
def tick_(self, timer):
self._d._bright = not self._d._bright
self._d.setNeedsDisplay_(True)
pd = PulseDelegate.alloc().init()
pd.setup(dot)
NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
0.5, pd, b'tick:', None, True
)
panel.orderFrontRegardless()
app.run()
"""
def _live_overlay_script():
"""Visible tkinter pill: 'LIVE · press F5 to stop' top-center.
Focus is no longer a problem because live mode is now triggered by F5
(not ⌘+L, which Chrome intercepts as 'focus URL bar')."""
return """
import tkinter as tk
root = tk.Tk()
root.overrideredirect(True)
root.attributes('-topmost', True)
root.attributes('-alpha', 0.95)
root.configure(bg='#0a0a0a')
sw = root.winfo_screenwidth()
w, h = 260, 40
x = (sw - w) // 2
y = 14
root.geometry(f'{w}x{h}+{x}+{y}')
c = tk.Canvas(root, bg='#0a0a0a', highlightthickness=0, width=w, height=h)
c.pack()
c.create_rectangle(1, 1, w-1, h-1, outline='#ff3b3b', width=2, fill='#0a0a0a')
dot = c.create_oval(14, 13, 28, 27, fill='#ff3b3b', outline='')
c.create_text(w//2 + 10, h//2, text='LIVE \u00b7 press F5 to stop',
fill='#ff3b3b', font=('SF Pro Display', 13, 'bold'))
def pulse():
cur = c.itemcget(dot, 'fill')
c.itemconfig(dot, fill='#ff3b3b' if cur == '#3a0000' else '#3a0000')
root.after(500, pulse)
pulse()
root.mainloop()
"""
def _live_record_loop():
"""Pipelined recording + transcription so no audio is dropped between chunks.
Producer thread: continuously records 2s sox chunks back-to-back into a queue.
Consumer (this thread): pulls chunks, sends to Whisper, pastes at cursor.
Gemini-style: each chunk is pasted at the current cursor position. No reflow.
"""
import requests, queue
chunk_sec = 2
q = queue.Queue(maxsize=8)
def _producer():
while not live_stop_event.is_set():
tmp = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
tmp.close()
try:
subprocess.run(
[SOX_PATH, "-t", "coreaudio", "default", "-r", "16000", "-c", "1",
"-b", "16", "-e", "signed-integer", tmp.name, "trim", "0", str(chunk_sec)],
timeout=chunk_sec + 3, capture_output=True
)
if live_stop_event.is_set():
try: os.unlink(tmp.name)
except: pass
break
if os.path.exists(tmp.name) and os.path.getsize(tmp.name) >= 1000:
try:
q.put(tmp.name, timeout=1)
except queue.Full:
try: os.unlink(tmp.name)
except: pass
else:
try: os.unlink(tmp.name)
except: pass
except Exception as e:
print(f"[DICTATE] Producer error: {e}")
try: os.unlink(tmp.name)
except: pass
prod = threading.Thread(target=_producer, daemon=True)
prod.start()
full_text = ""
while not live_stop_event.is_set() or not q.empty():
try:
path = q.get(timeout=0.5)
except Exception:
continue
try:
# Energy check
try:
import wave as _wave, numpy as _np
wf = _wave.open(path, 'rb')
data = _np.frombuffer(wf.readframes(wf.getnframes()), dtype=_np.int16)
wf.close()
if _np.abs(data).mean() < 150:
continue
except:
pass
with open(path, "rb") as f:
r = requests.post(WHISPER_SERVER,
files={"file": ("chunk.wav", f, "audio/wav")},
data={"model": "mlx-community/whisper-large-v3-turbo",
"language": "en", "task": "transcribe"},
timeout=10)
if r.status_code == 200:
chunk_text = r.json().get("text", "").strip()
if chunk_text and not is_hallucination(chunk_text):
full_text += chunk_text + " "
paste_text = chunk_text + " "
pyperclip.copy(paste_text)
time.sleep(0.05)
# Use pyautogui (CGEventPost) instead of osascript — does NOT
# activate System Events / shift focus. Paste lands in the
# field the user has focused, not the URL bar.
pyautogui.hotkey('command', 'v')
print(f"[DICTATE] Live: '{chunk_text}'")
except Exception as e:
print(f"[DICTATE] Live chunk error: {e}")
finally:
try: os.unlink(path)
except: pass
prod.join(timeout=3)
return full_text.strip()
def start_live_dictation():
global live_active, live_overlay, live_thread, live_stop_event
if live_active:
return
live_active = True
live_stop_event.clear()
print("[DICTATE] \U0001f3a4 Live dictation started — double-tap Option to stop")
# Sound
threading.Thread(target=lambda: subprocess.run(
['afplay', '/System/Library/Sounds/Blow.aiff'],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL), daemon=True).start()
# Show overlay — log stderr to /tmp so we can diagnose if it fails to render
_ov_err = open("/tmp/codec_dictate_overlay.log", "w")
live_overlay = subprocess.Popen(
[sys.executable, "-c", _live_overlay_script()],
stdout=subprocess.DEVNULL, stderr=_ov_err
)
print(f"[DICTATE] Overlay subprocess pid={live_overlay.pid}")
# Start recording loop in thread
live_thread = threading.Thread(target=_live_record_loop, daemon=True)
live_thread.start()
def stop_live_dictation():
global live_active, live_overlay, live_thread
if not live_active:
return
live_active = False
live_stop_event.set()
print("[DICTATE] \u2705 Live dictation stopped")
# Sound
threading.Thread(target=lambda: subprocess.run(
['afplay', '/System/Library/Sounds/Funk.aiff'],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL), daemon=True).start()
# Kill overlay — tkinter mainloop sometimes ignores SIGTERM, so SIGKILL it
if live_overlay:
try: live_overlay.terminate()
except: pass
try: live_overlay.wait(timeout=0.5)
except Exception:
try: live_overlay.kill()
except: pass
live_overlay = None
# Wait for thread
if live_thread:
live_thread.join(timeout=5)
live_thread = None
# Text was already typed live at cursor — nothing to paste
print("[DICTATE] \u2705 Live dictation complete")
# ── AUDIO RECORDING ───────────────────────────────────────────────────────────
def record_audio():
"""Record audio using sox (built into macOS via brew or system)"""
global audio_frames
audio_frames = []
tmp = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
tmp_path = tmp.name
tmp.close()
# Use sox to record — comes with macOS or brew install sox
# Falls back to afrecord (built-in macOS)
proc = None
sox_cmd = SOX_PATH if os.path.exists(SOX_PATH) else "sox"
try:
proc = subprocess.Popen(
[sox_cmd, "-t", "coreaudio", "default", "-r", str(SAMPLE_RATE), "-c", "1", "-b", "16", tmp_path],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
except FileNotFoundError:
try:
proc = subprocess.Popen(
["rec", "-r", str(SAMPLE_RATE), "-c", "1", "-b", "16", tmp_path],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
except FileNotFoundError:
print("[DICTATE] sox/rec not found. Install: brew install sox")
return None
return proc, tmp_path
# ── TRANSCRIBE ────────────────────────────────────────────────────────────────
def transcribe_and_type(audio_path):
if not model_loaded.is_set():
print("[DICTATE] Model not loaded yet")
return
proc_overlay = show_processing()
try:
print(f"[DICTATE] Transcribing {audio_path}...")
segments, info = model.transcribe(
audio_path,
beam_size=5,
vad_filter=True,
vad_parameters=dict(min_silence_duration_ms=300)
)
text = " ".join([s.text.strip() for s in segments]).strip()
if proc_overlay:
try:
proc_overlay.terminate()
except:
pass
if not text or is_hallucination(text):
print(f"[DICTATE] No speech or hallucination: {text!r}")
return
print(f"[DICTATE] Transcribed: {text}")
# Draft mode: ONLY if dictation starts with "draft" — refine with Qwen
import re as _re
_lower = text.lower().strip()
_draft_match = _re.match(r'^draft[\s.,!;:]+', _lower)
if _draft_match:
body = text[_draft_match.end():].strip()
if body:
try:
import requests as _req
print("[DICTATE] Draft mode — refining with Qwen...")
r = _req.post("http://localhost:8081/v1/chat/completions",
json={"model": "mlx-community/Qwen3.5-35B-A3B-4bit",
"messages": [
{"role": "system", "content": "Rewrite the user message as a polished, professional message. Output ONLY the final text. No preamble, no explanation."},
{"role": "user", "content": body}
],
"max_tokens": 300, "temperature": 0.3,
"chat_template_kwargs": {"enable_thinking": False}},
timeout=15)
if r.status_code == 200:
refined = r.json()["choices"][0]["message"]["content"].strip()
if refined:
text = refined
print(f"[DICTATE] Refined: {text}")
else:
text = body
print("[DICTATE] Qwen returned empty, using raw body")
else:
text = body
print(f"[DICTATE] Qwen HTTP {r.status_code}, using raw body")
except Exception as qe:
text = body
print(f"[DICTATE] Qwen error: {qe}, using raw body")
# Copy to clipboard
pyperclip.copy(text)
# Small delay to ensure focus is back on target window
time.sleep(0.15)
# Paste via osascript — more reliable than pyautogui on macOS
subprocess.run(["osascript", "-e",
'tell application "System Events" to keystroke "v" using command down'],
capture_output=True, timeout=5)
print(f"[DICTATE] \u2705 Typed: {text}")
except Exception as e:
print(f"[DICTATE] Transcription error: {e}")
if proc_overlay:
try:
proc_overlay.terminate()
except:
pass
finally:
try:
os.unlink(audio_path)
except:
pass
# ── KEYBOARD LISTENER ─────────────────────────────────────────────────────────
recording_proc = None
recording_path = None
def on_press(key):
global cmd_held, recording_proc, recording_path
# ── F5: toggle live dictation. (Was ⌘+L, but Chrome intercepts ⌘+L to
# focus the URL bar — so typing landed there instead of the chat.) ──
if key == keyboard.Key.f5:
if live_active:
threading.Thread(target=stop_live_dictation, daemon=True).start()
return
# F5 works standalone OR while CMD held
if cmd_held:
# Stop current recording, switch to live mode
if recording_proc:
try:
recording_proc.terminate()
recording_proc.wait(timeout=2)
except: pass
recording_proc = None
recording_path = None
hide_overlay()
cmd_held = False
threading.Thread(target=start_live_dictation, daemon=True).start()
return
# ── Hold RIGHT CMD only → classic dictation ──
if key == keyboard.Key.cmd_r:
if not cmd_held and not live_active:
cmd_held = True
print("[DICTATE] CMD held — starting recording")
threading.Thread(target=lambda: subprocess.run(
['afplay', '/System/Library/Sounds/Blow.aiff'],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL), daemon=True).start()
show_overlay()
result = record_audio()
if result:
recording_proc, recording_path = result
def on_release(key):
global cmd_held, recording_proc, recording_path
if key == keyboard.Key.cmd_r:
if cmd_held:
cmd_held = False
threading.Thread(target=lambda: subprocess.run(
['afplay', '/System/Library/Sounds/Funk.aiff'],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL), daemon=True).start()
hide_overlay()
if recording_proc:
print("[DICTATE] CMD released — stopping recording")
recording_proc.terminate()
recording_proc.wait()
rp = recording_path
recording_proc = None
recording_path = None
# Transcribe in background thread
t = threading.Thread(target=transcribe_and_type, args=(rp,), daemon=True)
t.start()
# ── MAIN ──────────────────────────────────────────────────────────────────────
def main():
print("""
\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557
\u2551 CODEC Dictate v2.1.0 \u2551
\u2551 Hold-to-Speak + Live Typing \u2551
\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563
\u2551 Hold \u2318R (right CMD) \u2192 speak \u2192 release \u2551
\u2551 F5 \u2192 Hands-free live typing at cursor \u2551
\u2551 Words type live wherever cursor is \u2551
\u2551 Press F5 again to stop \u2551
\u2551 Text types into active window \u2551
\u2551 Press Ctrl+C to quit \u2551
\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d
""")
# Check for sox
if not os.path.exists(SOX_PATH) and subprocess.run(["which", "sox"], capture_output=True).returncode != 0:
print("[DICTATE] \u26a0\ufe0f sox not found \u2014 install with: brew install sox")
print("[DICTATE] sox is required for microphone recording")
sys.exit(1)
# Load whisper in background
t = threading.Thread(target=load_model, daemon=True)
t.start()
print("[DICTATE] Waiting for Whisper to load...")
model_loaded.wait()
print("[DICTATE] \U0001f7e2 Ready. Hold right CMD to record. F5 to toggle live dictation.")
# Cleanup on exit — kill sox, overlays, temp files
import atexit, glob as _glob
def _cleanup():
global recording_proc
if recording_proc:
try: recording_proc.terminate(); recording_proc.wait(timeout=2)
except: pass
recording_proc = None
hide_overlay()
if live_active:
stop_live_dictation()
for f in _glob.glob(os.path.join(tempfile.gettempdir(), "dictate_*.wav")):
try: os.unlink(f)
except: pass
atexit.register(_cleanup)
import signal
signal.signal(signal.SIGTERM, lambda *a: (print("[DICTATE] SIGTERM received"), _cleanup(), sys.exit(0)))
# Start keyboard listener
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
try:
listener.join()
except KeyboardInterrupt:
print("\n[DICTATE] Shutting down.")
_cleanup()
if __name__ == "__main__":
main()