-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.py
More file actions
350 lines (289 loc) Β· 10.6 KB
/
main.py
File metadata and controls
350 lines (289 loc) Β· 10.6 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
import ctypes
import queue
import threading
import time
import tkinter as tk
# Fix DPI awareness before any window is created.
# CustomTkinter changes the DPI mode which shifts widget positioning.
try:
ctypes.windll.shcore.SetProcessDpiAwareness(1) # PROCESS_SYSTEM_DPI_AWARE
except Exception:
try:
ctypes.windll.user32.SetProcessDPIAware()
except Exception:
pass
_STOP = object() # sentinel to shut down pipeline workers
from logger import log
from recorder import Recorder
from transcriber import Transcriber
from injector import inject
from hotkey import HotkeyListener
from tray_icon import TrayIcon
from widget import RecordingWidget
import assistant
import config
import database as db
import locales
from notifier import ReminderScheduler
from notes_window import NotesWindow
from settings_window import SettingsWindow
_pipeline_queue = queue.Queue()
_assistant_queue = queue.Queue()
recorder = Recorder()
transcriber = None
tray = None
widget = None
root = None
notes_win = None
settings_win = None
scheduler = None
hotkey_listener = None
_rec_start = 0.0
_MIN_DURATION = 0.5
# Toggle-mode timeout timers
_dict_timeout_timer = None
_assist_timeout_timer = None
# ββ Load persisted settings into config at startup ββββββββββββββββββββββββ
def _load_settings():
"""Read settings from DB and apply them to config module."""
hold = db.get_setting("hold_to_record", "")
if hold != "":
config.HOLD_TO_RECORD = hold == "1"
max_sec = db.get_setting("max_record_seconds", "")
if max_sec != "":
try:
config.MAX_RECORD_SECONDS = int(max_sec)
except ValueError:
pass
# ββ Toggle-mode timeout helpers βββββββββββββββββββββββββββββββββββββββββββ
def _start_timeout(mode: str):
"""Start a safety timer that auto-stops recording in toggle mode."""
global _dict_timeout_timer, _assist_timeout_timer
if config.HOLD_TO_RECORD:
return
seconds = getattr(config, "MAX_RECORD_SECONDS", 120)
if seconds <= 0:
return
if mode == "dictation":
_dict_timeout_timer = threading.Timer(seconds, _timeout_dictation)
_dict_timeout_timer.daemon = True
_dict_timeout_timer.start()
elif mode == "assistant":
_assist_timeout_timer = threading.Timer(seconds, _timeout_assistant)
_assist_timeout_timer.daemon = True
_assist_timeout_timer.start()
def _cancel_timeout(mode: str):
global _dict_timeout_timer, _assist_timeout_timer
if mode == "dictation" and _dict_timeout_timer is not None:
_dict_timeout_timer.cancel()
_dict_timeout_timer = None
elif mode == "assistant" and _assist_timeout_timer is not None:
_assist_timeout_timer.cancel()
_assist_timeout_timer = None
def _timeout_dictation():
log.warning("Toggle-mode dictation timeout reached.")
if hotkey_listener:
hotkey_listener.force_stop_dictation()
def _timeout_assistant():
log.warning("Toggle-mode assistant timeout reached.")
if hotkey_listener:
hotkey_listener.force_stop_assistant()
# ββ Dictation callbacks (AltGr) ββββββββββββββββββββββββββββββββββββββββββ
def _on_hotkey_press():
global _rec_start
_rec_start = time.monotonic()
recorder.start()
if tray:
tray.set_recording(True)
if widget:
widget.show_recording()
_start_timeout("dictation")
log.info("Recording started (dictation).")
def _on_hotkey_release():
_cancel_timeout("dictation")
audio = recorder.stop()
duration = time.monotonic() - _rec_start
if tray:
tray.set_recording(False)
log.info("Recording stopped (%.2fs).", duration)
if audio is not None and len(audio) > 0 and duration >= _MIN_DURATION:
if widget:
widget.show_processing()
_pipeline_queue.put(audio)
else:
if widget:
widget.hide()
if duration < _MIN_DURATION:
log.info("Too short (%.2fs), skipping.", duration)
else:
log.info("Empty audio, skipping.")
# ββ Assistant callbacks (Ctrl+R) ββββββββββββββββββββββββββββββββββββββββββ
def _on_assist_press():
global _rec_start
_rec_start = time.monotonic()
recorder.start()
if tray:
tray.set_recording(True)
if widget:
widget.show_assistant()
widget.set_expression("listening")
_start_timeout("assistant")
log.info("Recording started (assistant).")
def _on_assist_release():
_cancel_timeout("assistant")
audio = recorder.stop()
duration = time.monotonic() - _rec_start
if tray:
tray.set_recording(False)
log.info("Assistant recording stopped (%.2fs).", duration)
if audio is not None and len(audio) > 0 and duration >= _MIN_DURATION:
if widget:
widget.show_processing()
widget.set_expression("thinking")
_assistant_queue.put(audio)
else:
if widget:
widget.hide()
# ββ Pipeline workers ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _dictation_worker():
"""Transcribe audio and paste the result into the active application."""
while True:
item = _pipeline_queue.get()
if item is _STOP:
break
try:
log.info("Transcribing (dictation)...")
text = transcriber.transcribe(item)
if text:
log.info("Transcribed: %r", text)
inject(text)
else:
log.info("No speech detected.")
except Exception as exc:
log.error("Dictation pipeline error: %s", exc)
finally:
if widget:
widget.hide()
def _assistant_worker():
"""Transcribe audio, send to Ollama, and execute the returned action."""
while True:
item = _assistant_queue.get()
if item is _STOP:
break
try:
log.info("Transcribing (assistant)...")
text = transcriber.transcribe(item)
if not text:
log.info("No speech detected.")
if widget:
widget.hide()
continue
log.info("Assistant heard: %r", text)
result = assistant.process(text)
log.info("Assistant result: %s", result)
# Handle special show commands
if result == "__show_notes__":
if notes_win:
root.after(0, lambda: notes_win.show("notes"))
if widget:
widget.set_expression("happy")
widget.show_message(locales.get("show_notes"), 2000)
elif result == "__show_appointments__":
if notes_win:
root.after(0, lambda: notes_win.show("appointments"))
if widget:
widget.set_expression("happy")
widget.show_message(locales.get("show_appointments"), 2000)
elif result == "__show_reminders__":
if notes_win:
root.after(0, lambda: notes_win.show("reminders"))
if widget:
widget.set_expression("happy")
widget.show_message(locales.get("show_reminders"), 2000)
elif result == locales.get("not_understood") or result.startswith(locales.get("error", detail="")):
if widget:
widget.set_expression("sad")
widget.show_message(result, 3000)
else:
if widget:
widget.set_expression("happy")
widget.show_message(result, 3000)
except Exception as exc:
log.error("Assistant pipeline error: %s", exc)
if widget:
widget.set_expression("error")
widget.show_message(locales.get("assistant_error"), 2000)
# ββ Quit & Main βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _show_notes():
"""Open notes window from tray menu."""
if notes_win:
root.after(0, lambda: notes_win.show("notes"))
def _show_settings():
"""Open settings window from tray menu."""
if settings_win:
root.after(0, lambda: settings_win.show())
def _quit():
log.info("Quitting...")
_cancel_timeout("dictation")
_cancel_timeout("assistant")
_pipeline_queue.put(_STOP)
_assistant_queue.put(_STOP)
if scheduler:
scheduler.stop()
if hotkey_listener:
try:
hotkey_listener.stop()
except Exception:
pass
if tray:
try:
tray.stop()
except Exception:
pass
try:
recorder.stop()
except Exception:
pass
if root:
try:
root.after(0, root.destroy)
except Exception:
pass
log.info("Shutdown complete.")
def main():
global transcriber, tray, widget, root, notes_win, settings_win, scheduler
global hotkey_listener
db.init()
_load_settings()
root = tk.Tk()
root.withdraw()
widget = RecordingWidget(root)
notes_win = NotesWindow(root)
settings_win = SettingsWindow(root)
recorder.on_level = lambda rms: widget.update_level(min(1.0, rms * 8))
recorder.on_mic_error = lambda msg: widget.show_message(msg, 4000)
tray = TrayIcon(on_quit=_quit, on_show_notes=_show_notes,
on_show_settings=_show_settings)
tray.start()
# Check Ollama connectivity at startup
if not assistant.ping_ollama():
log.warning("Ollama is not reachable at %s", config.OLLAMA_URL)
tray.set_tooltip(locales.get("tray_ollama_down"))
transcriber = Transcriber()
scheduler = ReminderScheduler()
scheduler.start()
t1 = threading.Thread(target=_dictation_worker, daemon=True)
t1.start()
t2 = threading.Thread(target=_assistant_worker, daemon=True)
t2.start()
hotkey_listener = HotkeyListener(
on_press_cb=_on_hotkey_press,
on_release_cb=_on_hotkey_release,
on_assist_press_cb=_on_assist_press,
on_assist_release_cb=_on_assist_release,
)
hotkey_listener.start()
log.info("Ready. AltGr=dictate, Ctrl+R=assistant.")
root.mainloop()
if __name__ == "__main__":
main()