Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
858 lines (745 loc) · 28.1 KB
/
Copy pathapp.py
File metadata and controls
858 lines (745 loc) · 28.1 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
"""Desktop recording UI for VSRS."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
import os
from pathlib import Path
from threading import Lock, Thread
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from typing import Any, Callable, Optional
import numpy as np
import soundfile as sf
# Allow the desktop UI process to coexist with mixed native OpenMP runtimes
# loaded by the Torch/SpeechBrain and FAISS stacks on some macOS setups.
os.environ.setdefault("KMP_DUPLICATE_LIB_OK", "TRUE")
try:
import sounddevice as sd
except ImportError as exc: # pragma: no cover - environment dependent
sd = None
SOUNDDEVICE_IMPORT_ERROR: Optional[ImportError] = exc
else:
SOUNDDEVICE_IMPORT_ERROR = None
from database import SpeakerDatabase, load_db, save_db
APP_TITLE = "VSRS Desktop Recorder"
TARGET_SAMPLE_RATE = 16_000
MIN_ENROLLMENT_CLIPS = 3
_INFERENCE_IMPORTS: Optional[tuple[Any, Callable[..., np.ndarray], Callable[..., Any]]] = None
def _load_inference_dependencies() -> tuple[Any, Callable[..., np.ndarray], Callable[..., Any]]:
"""Import Torch, embedding extraction, and identification lazily."""
global _INFERENCE_IMPORTS
if _INFERENCE_IMPORTS is None:
import torch
from embedding import extract_embedding_from_waveform
from identify import identify
_INFERENCE_IMPORTS = (
torch,
extract_embedding_from_waveform,
identify,
)
return _INFERENCE_IMPORTS
@dataclass
class AudioClip:
"""In-memory recording."""
label: str
samples: np.ndarray
sample_rate: int
@property
def duration_seconds(self) -> float:
if self.sample_rate <= 0:
return 0.0
return float(self.samples.shape[0] / self.sample_rate)
class RecorderController:
"""Thin wrapper around sounddevice for mono float32 capture."""
def __init__(self, sample_rate: int = TARGET_SAMPLE_RATE) -> None:
self.sample_rate = sample_rate
self.channels = 1
self.dtype = "float32"
self.input_device: Optional[int] = None
self._stream: Optional[sd.InputStream] = None if sd else None
self._chunks: list[np.ndarray] = []
self._lock = Lock()
self._level = 0.0
self._recording = False
self._elapsed_frames = 0
def ensure_available(self) -> None:
if sd is None:
raise RuntimeError(
"sounddevice is not installed. Install requirements first."
) from SOUNDDEVICE_IMPORT_ERROR
def list_input_devices(self) -> list[dict[str, object]]:
self.ensure_available()
devices = sd.query_devices()
results: list[dict[str, object]] = []
for index, device in enumerate(devices):
channels = int(device.get("max_input_channels", 0))
if channels > 0:
results.append(
{
"index": index,
"name": str(device.get("name", f"Input {index}")),
}
)
return results
def set_input_device(self, device_index: Optional[int]) -> None:
self.input_device = device_index
def start_recording(self) -> None:
self.ensure_available()
if self._recording:
raise RuntimeError("Recording is already in progress.")
self._chunks = []
self._level = 0.0
self._elapsed_frames = 0
def callback(
indata: np.ndarray,
frames: int,
time_info: object,
status: object,
) -> None:
del time_info, status
chunk = np.copy(indata).reshape(-1)
with self._lock:
self._chunks.append(chunk)
self._elapsed_frames += frames
if chunk.size:
self._level = float(np.max(np.abs(chunk)))
self._stream = sd.InputStream(
samplerate=self.sample_rate,
channels=self.channels,
dtype=self.dtype,
device=self.input_device,
callback=callback,
)
self._stream.start()
self._recording = True
def stop_recording(self) -> AudioClip:
if not self._recording or self._stream is None:
raise RuntimeError("No recording is currently in progress.")
self._stream.stop()
self._stream.close()
self._stream = None
self._recording = False
with self._lock:
if self._chunks:
samples = np.concatenate(self._chunks, axis=0).astype(np.float32)
else:
samples = np.zeros(0, dtype=np.float32)
self._chunks = []
self._level = 0.0
label = datetime.now().strftime("clip-%H%M%S")
return AudioClip(
label=label,
samples=samples,
sample_rate=self.sample_rate,
)
def play(self, clip: AudioClip) -> None:
self.ensure_available()
if clip.samples.size == 0:
raise RuntimeError("Clip is empty.")
sd.stop()
sd.play(clip.samples, clip.sample_rate, blocking=False)
def save_wav(self, clip: AudioClip, path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
sf.write(path, clip.samples, clip.sample_rate)
@property
def recording(self) -> bool:
return self._recording
@property
def level(self) -> float:
return self._level
@property
def elapsed_seconds(self) -> float:
if self.sample_rate <= 0:
return 0.0
return float(self._elapsed_frames / self.sample_rate)
class RecordingPanel(ttk.LabelFrame):
"""Reusable record / stop / play controls."""
def __init__(
self,
master: tk.Misc,
controller: RecorderController,
title: str,
on_clip_ready: Optional[Callable[[AudioClip], None]] = None,
allow_save: bool = False,
) -> None:
super().__init__(master, text=title, padding=12)
self.controller = controller
self.on_clip_ready = on_clip_ready
self.allow_save = allow_save
self.current_clip: Optional[AudioClip] = None
self._owns_recording = False
self.status_var = tk.StringVar(
value="Ready. Record in a quiet room and speak naturally."
)
self.timer_var = tk.StringVar(value="00.0s")
self.clip_var = tk.StringVar(value="No recording yet.")
self.level_var = tk.IntVar(value=0)
ttk.Label(
self,
text="Use normal speaking volume and stay the same distance from the mic.",
wraplength=520,
).grid(row=0, column=0, columnspan=5, sticky="w")
ttk.Label(self, text="Timer").grid(row=1, column=0, sticky="w", pady=(10, 0))
ttk.Label(self, textvariable=self.timer_var).grid(
row=1,
column=1,
sticky="w",
pady=(10, 0),
)
ttk.Label(self, text="Input level").grid(
row=2,
column=0,
sticky="w",
pady=(8, 0),
)
ttk.Progressbar(
self,
mode="determinate",
maximum=100,
variable=self.level_var,
length=220,
).grid(row=2, column=1, columnspan=2, sticky="we", pady=(8, 0))
self.record_button = ttk.Button(
self,
text="Start Recording",
command=self.start_recording,
)
self.record_button.grid(row=3, column=0, pady=(12, 0), sticky="we")
self.stop_button = ttk.Button(
self,
text="Stop",
command=self.stop_recording,
state="disabled",
)
self.stop_button.grid(row=3, column=1, pady=(12, 0), sticky="we", padx=6)
self.play_button = ttk.Button(
self,
text="Play",
command=self.play_clip,
state="disabled",
)
self.play_button.grid(row=3, column=2, pady=(12, 0), sticky="we")
self.clear_button = ttk.Button(
self,
text="Clear",
command=self.clear_clip,
state="disabled",
)
self.clear_button.grid(row=3, column=3, pady=(12, 0), sticky="we", padx=6)
if self.allow_save:
self.save_button = ttk.Button(
self,
text="Save WAV",
command=self.save_clip,
state="disabled",
)
self.save_button.grid(row=3, column=4, pady=(12, 0), sticky="we")
else:
self.save_button = None
ttk.Label(self, textvariable=self.clip_var).grid(
row=4,
column=0,
columnspan=5,
sticky="w",
pady=(10, 0),
)
ttk.Label(self, textvariable=self.status_var, wraplength=520).grid(
row=5,
column=0,
columnspan=5,
sticky="w",
pady=(6, 0),
)
self.columnconfigure(2, weight=1)
def start_recording(self) -> None:
try:
self.controller.start_recording()
except Exception as err: # noqa: BLE001
messagebox.showerror(APP_TITLE, str(err))
return
self._owns_recording = True
self.current_clip = None
self.record_button.config(state="disabled")
self.stop_button.config(state="normal")
self.play_button.config(state="disabled")
self.clear_button.config(state="disabled")
if self.save_button is not None:
self.save_button.config(state="disabled")
self.status_var.set("Recording... speak naturally for a few seconds.")
self.clip_var.set("Recording in progress.")
self._poll_level()
def _poll_level(self) -> None:
if not self._owns_recording:
return
self.level_var.set(int(max(0.0, min(1.0, self.controller.level)) * 100))
self.timer_var.set(f"{self.controller.elapsed_seconds:0.1f}s")
self.after(100, self._poll_level)
def stop_recording(self) -> None:
try:
clip = self.controller.stop_recording()
except Exception as err: # noqa: BLE001
messagebox.showerror(APP_TITLE, str(err))
return
self._owns_recording = False
self.current_clip = clip
self.level_var.set(0)
self.timer_var.set(f"{clip.duration_seconds:0.1f}s")
self.record_button.config(state="normal")
self.stop_button.config(state="disabled")
self.play_button.config(state="normal")
self.clear_button.config(state="normal")
if self.save_button is not None:
self.save_button.config(state="normal")
self.clip_var.set(
f"Captured {clip.label} ({clip.duration_seconds:0.1f}s)."
)
self.status_var.set("Clip ready. Keep it, re-record, or use it below.")
if self.on_clip_ready is not None:
self.on_clip_ready(clip)
def play_clip(self) -> None:
if self.current_clip is None:
return
try:
self.controller.play(self.current_clip)
except Exception as err: # noqa: BLE001
messagebox.showerror(APP_TITLE, str(err))
def clear_clip(self) -> None:
self.current_clip = None
self.level_var.set(0)
self.timer_var.set("00.0s")
self.clip_var.set("No recording yet.")
self.status_var.set("Ready. Record in a quiet room and speak naturally.")
self.play_button.config(state="disabled")
self.clear_button.config(state="disabled")
if self.save_button is not None:
self.save_button.config(state="disabled")
def save_clip(self) -> None:
if self.current_clip is None:
return
file_path = filedialog.asksaveasfilename(
title="Save recording",
defaultextension=".wav",
filetypes=[("WAV audio", "*.wav")],
)
if not file_path:
return
try:
self.controller.save_wav(self.current_clip, Path(file_path))
except Exception as err: # noqa: BLE001
messagebox.showerror(APP_TITLE, str(err))
return
self.status_var.set(f"Saved recording to {file_path}")
class VoiceRecognitionApp(tk.Tk):
"""Main VSRS desktop window."""
def __init__(self) -> None:
super().__init__()
self.title(APP_TITLE)
self.geometry("760x760")
self.minsize(720, 680)
self.controller = RecorderController()
self.status_var = tk.StringVar(
value="Ready. Select a microphone, then record clips."
)
self.device_var = tk.StringVar()
self.threshold_var = tk.StringVar(value="0.25")
self.enroll_name_var = tk.StringVar()
self.enroll_count_var = tk.StringVar(value="0 clips collected")
self.identify_result_var = tk.StringVar(
value="Record a clip, then run identification."
)
self.enrollment_clips: list[AudioClip] = []
self.identify_clip: Optional[AudioClip] = None
self._build_layout()
self.refresh_input_devices()
def _build_layout(self) -> None:
container = ttk.Frame(self, padding=16)
container.pack(fill="both", expand=True)
device_frame = ttk.LabelFrame(container, text="Microphone", padding=12)
device_frame.pack(fill="x")
ttk.Label(device_frame, text="Input device").grid(row=0, column=0, sticky="w")
self.device_combo = ttk.Combobox(
device_frame,
textvariable=self.device_var,
state="readonly",
width=50,
)
self.device_combo.grid(row=0, column=1, sticky="we", padx=8)
self.device_combo.bind("<<ComboboxSelected>>", self._on_device_selected)
ttk.Button(
device_frame,
text="Refresh",
command=self.refresh_input_devices,
).grid(row=0, column=2, sticky="e")
device_frame.columnconfigure(1, weight=1)
notebook = ttk.Notebook(container)
notebook.pack(fill="both", expand=True, pady=(12, 0))
self.record_tab = ttk.Frame(notebook, padding=12)
self.enroll_tab = ttk.Frame(notebook, padding=12)
self.identify_tab = ttk.Frame(notebook, padding=12)
self.speakers_tab = ttk.Frame(notebook, padding=12)
notebook.add(self.record_tab, text="Record")
notebook.add(self.enroll_tab, text="Enroll")
notebook.add(self.identify_tab, text="Identify")
notebook.add(self.speakers_tab, text="Speakers")
self._build_record_tab()
self._build_enroll_tab()
self._build_identify_tab()
self._build_speakers_tab()
ttk.Label(
container,
textvariable=self.status_var,
wraplength=700,
).pack(fill="x", pady=(12, 0))
def _build_record_tab(self) -> None:
panel = RecordingPanel(
self.record_tab,
controller=self.controller,
title="Quick recorder",
allow_save=True,
)
panel.pack(fill="x")
ttk.Label(
self.record_tab,
text=(
"Use this tab when you just want to capture and save a WAV file. "
"For enrollment, switch to the Enroll tab and collect at least "
f"{MIN_ENROLLMENT_CLIPS} natural takes."
),
wraplength=650,
).pack(anchor="w", pady=(16, 0))
def _build_enroll_tab(self) -> None:
top = ttk.Frame(self.enroll_tab)
top.pack(fill="x")
ttk.Label(top, text="Speaker name").grid(row=0, column=0, sticky="w")
ttk.Entry(top, textvariable=self.enroll_name_var, width=28).grid(
row=0,
column=1,
sticky="w",
padx=(8, 0),
)
ttk.Label(
top,
text=(
f"Capture at least {MIN_ENROLLMENT_CLIPS} clips in the same room "
"and at the same distance from the microphone."
),
wraplength=420,
).grid(row=1, column=0, columnspan=2, sticky="w", pady=(10, 0))
self.enroll_panel = RecordingPanel(
self.enroll_tab,
controller=self.controller,
title="Enrollment recorder",
)
self.enroll_panel.pack(fill="x", pady=(12, 0))
actions = ttk.Frame(self.enroll_tab)
actions.pack(fill="x", pady=(12, 0))
ttk.Button(
actions,
text="Add Current Clip",
command=self.add_enrollment_clip,
).pack(side="left")
ttk.Button(
actions,
text="Remove Selected Clip",
command=self.remove_enrollment_clip,
).pack(side="left", padx=8)
ttk.Button(
actions,
text="Clear Clips",
command=self.clear_enrollment_clips,
).pack(side="left")
ttk.Button(
actions,
text="Enroll Speaker",
command=self.enroll_speaker,
).pack(side="right")
ttk.Label(
self.enroll_tab,
textvariable=self.enroll_count_var,
).pack(anchor="w", pady=(10, 0))
self.enroll_listbox = tk.Listbox(self.enroll_tab, height=8)
self.enroll_listbox.pack(fill="both", expand=True, pady=(8, 0))
def _build_identify_tab(self) -> None:
ttk.Label(
self.identify_tab,
text=(
"Record one query clip, then compare it against the enrolled "
"speaker database."
),
wraplength=650,
).pack(anchor="w")
threshold_row = ttk.Frame(self.identify_tab)
threshold_row.pack(fill="x", pady=(12, 0))
ttk.Label(threshold_row, text="Threshold").pack(side="left")
ttk.Entry(
threshold_row,
textvariable=self.threshold_var,
width=8,
).pack(side="left", padx=(8, 0))
ttk.Label(
threshold_row,
text="Default is 0.25. Raise it for stricter matching.",
).pack(side="left", padx=(12, 0))
self.identify_panel = RecordingPanel(
self.identify_tab,
controller=self.controller,
title="Identification recorder",
on_clip_ready=self._set_identify_clip,
)
self.identify_panel.pack(fill="x", pady=(12, 0))
ttk.Button(
self.identify_tab,
text="Identify Speaker",
command=self.identify_speaker,
).pack(anchor="e", pady=(12, 0))
ttk.Label(
self.identify_tab,
textvariable=self.identify_result_var,
wraplength=650,
justify="left",
).pack(anchor="w", pady=(12, 0))
def _build_speakers_tab(self) -> None:
ttk.Label(
self.speakers_tab,
text="Refresh to inspect the local speaker database.",
wraplength=650,
).pack(anchor="w")
actions = ttk.Frame(self.speakers_tab)
actions.pack(fill="x", pady=(12, 0))
ttk.Button(
actions,
text="Refresh Speakers",
command=self.refresh_speakers,
).pack(side="left")
ttk.Button(
actions,
text="Delete Selected Speaker",
command=self.delete_selected_speaker,
).pack(side="left", padx=8)
self.speakers_listbox = tk.Listbox(self.speakers_tab, height=12)
self.speakers_listbox.pack(fill="both", expand=True, pady=(8, 0))
def refresh_input_devices(self) -> None:
try:
devices = self.controller.list_input_devices()
except Exception as err: # noqa: BLE001
self.status_var.set(f"Microphone unavailable: {err}")
self.device_combo["values"] = ()
return
self._devices = devices
labels = [f"{item['index']}: {item['name']}" for item in devices]
self.device_combo["values"] = labels
if labels:
self.device_combo.current(0)
self._on_device_selected()
self.status_var.set("Microphone ready.")
else:
self.status_var.set("No input devices found.")
def _on_device_selected(self, event: Optional[object] = None) -> None:
del event
index = self.device_combo.current()
if index < 0:
return
device_info = self._devices[index]
self.controller.set_input_device(int(device_info["index"]))
self.status_var.set(f"Using microphone: {device_info['name']}")
def add_enrollment_clip(self) -> None:
clip = self.enroll_panel.current_clip
if clip is None:
messagebox.showinfo(APP_TITLE, "Record a clip first.")
return
copied_clip = AudioClip(
label=f"sample-{len(self.enrollment_clips) + 1}",
samples=np.copy(clip.samples),
sample_rate=clip.sample_rate,
)
self.enrollment_clips.append(copied_clip)
self.enroll_listbox.insert(
tk.END,
f"{copied_clip.label} - {copied_clip.duration_seconds:0.1f}s",
)
self.enroll_count_var.set(f"{len(self.enrollment_clips)} clips collected")
self.enroll_panel.clear_clip()
def remove_enrollment_clip(self) -> None:
selection = self.enroll_listbox.curselection()
if not selection:
return
index = int(selection[0])
self.enroll_listbox.delete(index)
del self.enrollment_clips[index]
self.enroll_count_var.set(f"{len(self.enrollment_clips)} clips collected")
def clear_enrollment_clips(self) -> None:
self.enrollment_clips = []
self.enroll_listbox.delete(0, tk.END)
self.enroll_count_var.set("0 clips collected")
def _set_identify_clip(self, clip: AudioClip) -> None:
self.identify_clip = AudioClip(
label=clip.label,
samples=np.copy(clip.samples),
sample_rate=clip.sample_rate,
)
self.identify_result_var.set(
f"Clip ready ({clip.duration_seconds:0.1f}s). Click Identify Speaker."
)
def _run_in_background(
self,
worker: Callable[[], object],
on_success: Callable[[object], None],
task_label: str,
) -> None:
self.status_var.set(task_label)
def target() -> None:
try:
result = worker()
except Exception as err: # noqa: BLE001
self.after(
0,
lambda: messagebox.showerror(APP_TITLE, str(err)),
)
self.after(
0,
lambda: self.status_var.set(f"{task_label} failed."),
)
return
self.after(0, lambda: on_success(result))
Thread(target=target, daemon=True).start()
def enroll_speaker(self) -> None:
speaker_name = self.enroll_name_var.get().strip()
if not speaker_name:
messagebox.showinfo(APP_TITLE, "Enter a speaker name first.")
return
if len(self.enrollment_clips) < MIN_ENROLLMENT_CLIPS:
messagebox.showinfo(
APP_TITLE,
f"Collect at least {MIN_ENROLLMENT_CLIPS} clips before enrolling.",
)
return
clips = [
AudioClip(
label=clip.label,
samples=np.copy(clip.samples),
sample_rate=clip.sample_rate,
)
for clip in self.enrollment_clips
]
def worker() -> tuple[str, int]:
torch, extract_embedding_from_waveform, _identify = (
_load_inference_dependencies()
)
embeddings: list[np.ndarray] = []
for clip in clips:
waveform = torch.from_numpy(clip.samples).unsqueeze(0)
embedding = extract_embedding_from_waveform(
waveform,
clip.sample_rate,
)
embeddings.append(embedding)
stacked = np.stack(embeddings, axis=0).astype(np.float32)
centroid = np.mean(stacked, axis=0)
centroid = centroid / max(np.linalg.norm(centroid), 1e-12)
db = load_db()
if speaker_name in db.labels:
db.replace_speaker(speaker_name, centroid.astype(np.float32))
else:
db.add_speaker(speaker_name, centroid.astype(np.float32))
save_db(db)
return speaker_name, len(clips)
def on_success(result: object) -> None:
enrolled_name, clip_count = result # type: ignore[misc]
self.clear_enrollment_clips()
self.enroll_name_var.set("")
self.status_var.set(
f"Enrolled {enrolled_name} using {clip_count} clips."
)
self.refresh_speakers()
self._run_in_background(
worker=worker,
on_success=on_success,
task_label="Enrolling speaker...",
)
def identify_speaker(self) -> None:
clip = self.identify_clip
if clip is None:
messagebox.showinfo(APP_TITLE, "Record a clip first.")
return
try:
threshold = float(self.threshold_var.get())
except ValueError:
messagebox.showerror(APP_TITLE, "Threshold must be a number.")
return
query_clip = AudioClip(
label=clip.label,
samples=np.copy(clip.samples),
sample_rate=clip.sample_rate,
)
def worker() -> object:
torch, extract_embedding_from_waveform, identify = (
_load_inference_dependencies()
)
waveform = torch.from_numpy(query_clip.samples).unsqueeze(0)
embedding = extract_embedding_from_waveform(
waveform,
query_clip.sample_rate,
)
db = load_db()
if db.is_empty():
raise RuntimeError("Speaker database is empty. Enroll someone first.")
return identify(embedding, db=db, threshold=threshold)
def on_success(result: object) -> None:
match = result
if match.speaker_name is None or not match.accepted:
candidate = "No candidate"
if match.speaker_name is not None:
candidate = (
f"Best candidate: {match.speaker_name} "
f"(similarity={match.similarity:.4f})"
)
self.identify_result_var.set(
"Unknown speaker.\n"
f"{candidate}\n"
f"Threshold: {threshold:.2f}"
)
self.status_var.set("Identification complete. No confident match.")
return
self.identify_result_var.set(
f"Identified: {match.speaker_name}\n"
f"Similarity: {match.similarity:.4f}\n"
f"Threshold: {threshold:.2f}"
)
self.status_var.set("Identification complete.")
self._run_in_background(
worker=worker,
on_success=on_success,
task_label="Identifying speaker...",
)
def refresh_speakers(self) -> None:
db = load_db()
self.speakers_listbox.delete(0, tk.END)
if not db.labels:
self.speakers_listbox.insert(tk.END, "(no enrolled speakers)")
return
for label in db.labels:
self.speakers_listbox.insert(tk.END, label)
def delete_selected_speaker(self) -> None:
selection = self.speakers_listbox.curselection()
if not selection:
return
label = self.speakers_listbox.get(selection[0])
if label == "(no enrolled speakers)":
return
confirmed = messagebox.askyesno(
APP_TITLE,
f"Delete the speaker profile '{label}'?",
)
if not confirmed:
return
db = load_db()
deleted = db.delete_speaker(label)
if deleted:
save_db(db)
self.status_var.set(f"Deleted speaker profile '{label}'.")
self.refresh_speakers()
def main() -> None:
app = VoiceRecognitionApp()
app.mainloop()
if __name__ == "__main__":
main()