voice-hold-engine 0.6.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. voice_hold_engine/__init__.py +7 -0
  2. voice_hold_engine/__main__.py +6 -0
  3. voice_hold_engine/asr.py +137 -0
  4. voice_hold_engine/audio.py +183 -0
  5. voice_hold_engine/cli.py +266 -0
  6. voice_hold_engine/commands/__init__.py +7 -0
  7. voice_hold_engine/commands/apps.py +71 -0
  8. voice_hold_engine/commands/cloud.py +435 -0
  9. voice_hold_engine/commands/history.py +82 -0
  10. voice_hold_engine/commands/interpreter.py +123 -0
  11. voice_hold_engine/commands/jobs.py +171 -0
  12. voice_hold_engine/commands/llm.py +174 -0
  13. voice_hold_engine/commands/probes.py +263 -0
  14. voice_hold_engine/commands/quick.py +44 -0
  15. voice_hold_engine/commands/rules.py +256 -0
  16. voice_hold_engine/commands/safety.py +220 -0
  17. voice_hold_engine/commands/service.py +253 -0
  18. voice_hold_engine/corrections.py +163 -0
  19. voice_hold_engine/lists.py +84 -0
  20. voice_hold_engine/llamacpp.py +235 -0
  21. voice_hold_engine/memory.py +36 -0
  22. voice_hold_engine/models.py +327 -0
  23. voice_hold_engine/polish.py +136 -0
  24. voice_hold_engine/rewrite.py +87 -0
  25. voice_hold_engine/segmenter.py +150 -0
  26. voice_hold_engine/service.py +923 -0
  27. voice_hold_engine/sources.py +58 -0
  28. voice_hold_engine/text.py +151 -0
  29. voice_hold_engine/tts.py +127 -0
  30. voice_hold_engine/vocab.py +134 -0
  31. voice_hold_engine/wake.py +258 -0
  32. voice_hold_engine/wakeword.py +217 -0
  33. voice_hold_engine-0.6.0.dist-info/METADATA +92 -0
  34. voice_hold_engine-0.6.0.dist-info/RECORD +37 -0
  35. voice_hold_engine-0.6.0.dist-info/WHEEL +4 -0
  36. voice_hold_engine-0.6.0.dist-info/entry_points.txt +2 -0
  37. voice_hold_engine-0.6.0.dist-info/licenses/LICENSE +338 -0
@@ -0,0 +1,7 @@
1
+ """Voice Hold engine: local speech-to-text behind a session D-Bus service."""
2
+
3
+ __version__ = "0.6.0"
4
+
5
+ BUS_NAME = "org.griffit.VoiceHold"
6
+ OBJECT_PATH = "/org/griffit/VoiceHold"
7
+ INTERFACE = "org.griffit.VoiceHold"
@@ -0,0 +1,6 @@
1
+ """`python -m voice_hold_engine`: what the D-Bus service file runs."""
2
+ import sys
3
+
4
+ from .cli import main
5
+
6
+ sys.exit(main())
@@ -0,0 +1,137 @@
1
+ """Speech recognition (Parakeet TDT 0.6B int8) and voice activity detection
2
+ (Silero), both through sherpa-onnx."""
3
+ import ctypes
4
+ import os
5
+ import time
6
+
7
+ import numpy as np
8
+
9
+ from . import models
10
+
11
+ SAMPLE_RATE = 16000
12
+
13
+
14
+ class Recognizer:
15
+ """Loads lazily, can be unloaded to give the memory back."""
16
+
17
+ def __init__(self, threads=None, base=None):
18
+ self._threads = threads or min(4, os.cpu_count() or 2)
19
+ self._base = base
20
+ self._rec = None
21
+ self.load_seconds = 0.0
22
+
23
+ @property
24
+ def loaded(self):
25
+ return self._rec is not None
26
+
27
+ def load(self):
28
+ if self._rec is not None:
29
+ return
30
+ import sherpa_onnx
31
+ p = models.asr_paths(self._base)
32
+ t0 = time.perf_counter()
33
+ self._rec = sherpa_onnx.OfflineRecognizer.from_transducer(
34
+ tokens=p['tokens'], encoder=p['encoder'], decoder=p['decoder'],
35
+ joiner=p['joiner'], num_threads=self._threads, sample_rate=SAMPLE_RATE,
36
+ feature_dim=80, model_type='nemo_transducer', decoding_method='greedy_search')
37
+ self.load_seconds = time.perf_counter() - t0
38
+
39
+ def unload(self):
40
+ self._rec = None
41
+
42
+ def transcribe(self, samples, context=None):
43
+ """Text of `samples`. With `context` (the audio just before them),
44
+ the model hears it first and only the words that start after it are
45
+ kept: the first words of a block are then recognised, punctuated and
46
+ capitalised as the rest of the sentence they belong to."""
47
+ self.load()
48
+ samples = np.asarray(samples, dtype=np.float32)
49
+ if samples.size < SAMPLE_RATE // 10:
50
+ return ''
51
+ ctx = np.asarray(context, dtype=np.float32) if context is not None else np.zeros(0, np.float32)
52
+ s = self._rec.create_stream()
53
+ s.accept_waveform(SAMPLE_RATE, np.concatenate([ctx, samples]) if ctx.size else samples)
54
+ self._rec.decode_stream(s)
55
+ if not ctx.size:
56
+ return s.result.text.strip()
57
+ return words_after(list(s.result.tokens), list(s.result.timestamps), ctx.size / SAMPLE_RATE)
58
+
59
+
60
+ # A token that starts this little before the boundary still belongs to the
61
+ # block: the model stamps a word slightly before its sound.
62
+ BOUNDARY_SLACK_S = 0.08
63
+
64
+
65
+ def words_after(tokens, times, t0):
66
+ """The text of the tokens from the first word that starts at or after t0
67
+ seconds (a word starts with a token beginning with a space or '▁')."""
68
+ for i, (tok, t) in enumerate(zip(tokens, times)):
69
+ if t >= t0 - BOUNDARY_SLACK_S and tok[:1] in (' ', '▁'):
70
+ return ''.join(tokens[i:]).replace('▁', ' ').strip()
71
+ return ''
72
+
73
+
74
+ def release_memory():
75
+ """Give freed heap back to the kernel. Dropping the recogniser frees the
76
+ weights but glibc keeps ~600 MB of them resident until asked; without
77
+ this the promise "the model leaves memory after 5 minutes" is false."""
78
+ try:
79
+ libc = ctypes.CDLL('libc.so.6')
80
+ libc.malloc_trim(0)
81
+ except (OSError, AttributeError):
82
+ pass
83
+
84
+
85
+ class SileroVad:
86
+ """Adapter with the interface segmenter.Segmenter expects."""
87
+
88
+ WINDOW = 512 # samples per Silero frame at 16 kHz
89
+
90
+ # Blocks are cut at pauses of min_silence_s; without a pause, at
91
+ # max_speech_s (a long block costs max_speech_s × RTF to decode, so keep
92
+ # it short enough to feel live).
93
+ def __init__(self, base=None, threshold=0.5, min_silence_s=0.3,
94
+ min_speech_s=0.25, max_speech_s=8.0):
95
+ import sherpa_onnx
96
+ self.max_speech_s = max_speech_s
97
+ cfg = sherpa_onnx.VadModelConfig()
98
+ cfg.silero_vad.model = models.vad_path(base)
99
+ cfg.silero_vad.threshold = threshold
100
+ cfg.silero_vad.min_silence_duration = min_silence_s
101
+ cfg.silero_vad.min_speech_duration = min_speech_s
102
+ cfg.silero_vad.max_speech_duration = max_speech_s
103
+ cfg.sample_rate = SAMPLE_RATE
104
+ cfg.num_threads = 1
105
+ self._vad = sherpa_onnx.VoiceActivityDetector(cfg, buffer_size_in_seconds=max_speech_s + 5)
106
+ self._pending = np.zeros(0, dtype=np.float32)
107
+ self.in_speech = False
108
+
109
+ def _drain(self):
110
+ """(start sample, samples) of each finished segment, the start
111
+ counted from the last reset()."""
112
+ out = []
113
+ while not self._vad.empty():
114
+ seg = self._vad.front
115
+ out.append((int(seg.start), np.asarray(seg.samples, dtype=np.float32)))
116
+ self._vad.pop()
117
+ return out
118
+
119
+ def accept(self, chunk):
120
+ buf = np.concatenate([self._pending, np.asarray(chunk, dtype=np.float32)])
121
+ n = (len(buf) // self.WINDOW) * self.WINDOW
122
+ for i in range(0, n, self.WINDOW):
123
+ self._vad.accept_waveform(buf[i:i + self.WINDOW])
124
+ self._pending = buf[n:]
125
+ self.in_speech = self._vad.is_speech_detected()
126
+ return self._drain()
127
+
128
+ def flush(self):
129
+ self._vad.flush()
130
+ self.in_speech = False
131
+ self._pending = np.zeros(0, dtype=np.float32)
132
+ return self._drain()
133
+
134
+ def reset(self):
135
+ self._vad.reset()
136
+ self.in_speech = False
137
+ self._pending = np.zeros(0, dtype=np.float32)
@@ -0,0 +1,183 @@
1
+ """Audio sources: the microphone through PipeWire, or a WAV file replayed at
2
+ real speed (tests, demo). Both deliver float32 chunks at 16 kHz on a callback
3
+ called from a background thread; `None` means end of stream. When the stream
4
+ ended because the capture process died, `failure` holds a message before the
5
+ final `None` is delivered."""
6
+ import subprocess
7
+ import tempfile
8
+ import threading
9
+ import time
10
+ import wave
11
+
12
+ import numpy as np
13
+
14
+ SAMPLE_RATE = 16000
15
+ CHUNK = 512 # 32 ms
16
+
17
+ # After SIGTERM, how long pw-record gets before SIGKILL.
18
+ KILL_AFTER_S = 1.0
19
+ STDERR_TAIL = 300
20
+
21
+
22
+ class MicSource:
23
+ # Named, so that the extension can tell our streams from another
24
+ # application's recording (a call: the wake word pauses meanwhile).
25
+ CMD = ['pw-record', '--rate', str(SAMPLE_RATE), '--channels', '1',
26
+ '--format', 's16', '--latency', '20ms',
27
+ '-P', '{ application.name = "Voice Hold" application.id = "org.griffit.VoiceHold" }', '-']
28
+
29
+ def __init__(self, on_chunk, target=''):
30
+ self._on_chunk = on_chunk
31
+ self._target = target # PipeWire node name; '' = default source
32
+ self._proc = None
33
+ self._thread = None
34
+ self._stderr = None
35
+ self._stopped = False
36
+ self.failure = None
37
+ self.returncode = None
38
+
39
+ def start(self):
40
+ cmd = list(self.CMD)
41
+ if self._target:
42
+ cmd[1:1] = ['--target', self._target]
43
+ # stderr goes to a temporary file (never a pipe: a chatty process
44
+ # would block on a full pipe) and its tail is reported on failure.
45
+ self._stderr = tempfile.TemporaryFile()
46
+ try:
47
+ self._proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=self._stderr)
48
+ except FileNotFoundError as e:
49
+ self._stderr.close()
50
+ self._stderr = None
51
+ raise RuntimeError(f'{cmd[0]} not found: PipeWire is required') from e
52
+ self._thread = threading.Thread(target=self._pump, daemon=True, name='pw-record')
53
+ self._thread.start()
54
+
55
+ def _pump(self):
56
+ proc = self._proc
57
+ nbytes = CHUNK * 2
58
+ try:
59
+ while True:
60
+ data = proc.stdout.read(nbytes)
61
+ if not data:
62
+ break
63
+ samples = np.frombuffer(data, dtype=np.int16).astype(np.float32) / 32768.0
64
+ self._on_chunk(samples)
65
+ finally:
66
+ rc, tail = self._reap(proc)
67
+ self.returncode = rc
68
+ if not self._stopped:
69
+ msg = f'pw-record exited with status {rc}'
70
+ if tail:
71
+ msg += f': {tail}'
72
+ self.failure = msg
73
+ self._on_chunk(None)
74
+
75
+ # Wait for the process (it is exiting: EOF on stdout), close the pipes,
76
+ # return (exit code, tail of stderr). Runs on the pump thread, never on
77
+ # the event loop.
78
+ def _reap(self, proc):
79
+ try:
80
+ rc = proc.wait(timeout=KILL_AFTER_S + 1)
81
+ except subprocess.TimeoutExpired:
82
+ proc.kill()
83
+ rc = proc.wait()
84
+ try:
85
+ proc.stdout.close()
86
+ except Exception:
87
+ pass
88
+ tail = ''
89
+ if self._stderr is not None:
90
+ try:
91
+ self._stderr.seek(0)
92
+ tail = self._stderr.read()[-STDERR_TAIL:].decode(errors='replace').strip()
93
+ except Exception:
94
+ pass
95
+ try:
96
+ self._stderr.close()
97
+ except Exception:
98
+ pass
99
+ self._stderr = None
100
+ return rc, tail
101
+
102
+ def stop(self):
103
+ """Ask pw-record to exit. Never blocks: the pump thread reaps it when
104
+ its stdout closes; a timer sends SIGKILL if SIGTERM is ignored."""
105
+ self._stopped = True
106
+ proc, self._proc = self._proc, None
107
+ if proc is None:
108
+ return
109
+ if proc.poll() is None:
110
+ try:
111
+ proc.terminate()
112
+ except ProcessLookupError:
113
+ pass
114
+ timer = threading.Timer(KILL_AFTER_S, _kill_if_alive, args=(proc,))
115
+ timer.daemon = True
116
+ timer.start()
117
+
118
+
119
+ def _kill_if_alive(proc):
120
+ try:
121
+ if proc.poll() is None:
122
+ proc.kill()
123
+ except Exception:
124
+ pass
125
+
126
+
127
+ class FileSource:
128
+ def __init__(self, path, on_chunk, realtime=True):
129
+ self._path = path
130
+ self._on_chunk = on_chunk
131
+ self._realtime = realtime
132
+ self._stop = threading.Event()
133
+ self._thread = None
134
+ self.failure = None
135
+
136
+ @staticmethod
137
+ def read(path):
138
+ with wave.open(path, 'rb') as w:
139
+ rate, ch, width = w.getframerate(), w.getnchannels(), w.getsampwidth()
140
+ raw = w.readframes(w.getnframes())
141
+ if width != 2:
142
+ raise RuntimeError('only 16-bit PCM WAV is supported')
143
+ a = np.frombuffer(raw, dtype=np.int16).astype(np.float32) / 32768.0
144
+ if ch > 1:
145
+ a = a.reshape(-1, ch).mean(axis=1)
146
+ if rate != SAMPLE_RATE:
147
+ n = int(len(a) * SAMPLE_RATE / rate)
148
+ a = np.interp(np.linspace(0, len(a), n, endpoint=False), np.arange(len(a)), a).astype(np.float32)
149
+ return a
150
+
151
+ @property
152
+ def stopped(self):
153
+ return self._stop.is_set()
154
+
155
+ def start(self):
156
+ audio = self.read(self._path)
157
+ self._thread = threading.Thread(target=self._pump, args=(audio,), daemon=True)
158
+ self._thread.start()
159
+
160
+ def _pump(self, audio):
161
+ t0 = time.perf_counter()
162
+ try:
163
+ for i in range(0, len(audio), CHUNK):
164
+ if self._stop.is_set():
165
+ return
166
+ self._on_chunk(audio[i:i + CHUNK])
167
+ if self._realtime:
168
+ due = t0 + (i + CHUNK) / SAMPLE_RATE
169
+ delay = due - time.perf_counter()
170
+ if delay > 0:
171
+ time.sleep(delay)
172
+ # A little silence so the VAD closes the last segment on its own.
173
+ for _ in range(0, int(0.6 * SAMPLE_RATE), CHUNK):
174
+ if self._stop.is_set():
175
+ return
176
+ self._on_chunk(np.zeros(CHUNK, dtype=np.float32))
177
+ if self._realtime:
178
+ time.sleep(CHUNK / SAMPLE_RATE)
179
+ finally:
180
+ self._on_chunk(None)
181
+
182
+ def stop(self):
183
+ self._stop.set()
@@ -0,0 +1,266 @@
1
+ """Command line: `voice-hold-engine [serve|setup [--tts [LANG…]|--commands|--wake]|status [--verify]|transcribe FILE|speak TEXT|interpret TEXT|apps|commands-serve|install-service|uninstall [--models]]`."""
2
+ import argparse
3
+ import asyncio
4
+ import os
5
+ import shutil
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from . import BUS_NAME, __version__, models
10
+ from .commands import BUS_NAME as COMMANDS_BUS_NAME
11
+
12
+ SERVICE_FILE = f'{BUS_NAME}.service'
13
+ COMMANDS_SERVICE_FILE = f'{COMMANDS_BUS_NAME}.service'
14
+
15
+
16
+ def service_dir():
17
+ data = Path(os.environ.get('XDG_DATA_HOME', Path.home() / '.local' / 'share'))
18
+ return data / 'dbus-1' / 'services'
19
+
20
+
21
+ def service_exec():
22
+ """The interpreter running `setup`, not whichever voice-hold-engine is
23
+ first in PATH: with pipx or uv that is the venv's python, and
24
+ `pipx reinstall` keeps the same path. Never resolve() it: a venv's
25
+ python is a symlink to the system interpreter, which cannot import us."""
26
+ return f'{launcher()} -m voice_hold_engine serve'
27
+
28
+
29
+ def launcher():
30
+ """How to start this install's Python from a D-Bus service file. The
31
+ extension's Installation page unpacks the engine beside the system
32
+ Python and runs it through PYTHONPATH: a service file written from such
33
+ a run must carry it, or the service could not import us."""
34
+ path = os.environ.get('PYTHONPATH', '')
35
+ if path and all(c not in path for c in ' \t\n"\'\\'):
36
+ return f'/usr/bin/env PYTHONPATH={path} {sys.executable}'
37
+ return sys.executable
38
+
39
+
40
+ def install_service(log=print):
41
+ d = service_dir()
42
+ d.mkdir(parents=True, exist_ok=True)
43
+ path = d / SERVICE_FILE
44
+ path.write_text(f'[D-BUS Service]\nName={BUS_NAME}\nExec={service_exec()}\n')
45
+ log(f'D-Bus service installed: {path}')
46
+ return path
47
+
48
+
49
+ def install_commands_service(log=print):
50
+ """The helper behind the optional voice commands: its own bus name, so
51
+ it starts only when the commands are used."""
52
+ d = service_dir()
53
+ d.mkdir(parents=True, exist_ok=True)
54
+ path = d / COMMANDS_SERVICE_FILE
55
+ path.write_text(f'[D-BUS Service]\nName={COMMANDS_BUS_NAME}\n'
56
+ f'Exec={launcher()} -m voice_hold_engine commands-serve\n')
57
+ log(f'D-Bus service installed: {path}')
58
+ return path
59
+
60
+
61
+ def cmd_setup(args):
62
+ log = lambda s: (sys.stderr.write(s), sys.stderr.flush())
63
+ base = models.models_dir()
64
+ print(f'Models directory: {base}')
65
+ if args.tts is not None:
66
+ # `setup --tts`: only the voices, for an install that already works.
67
+ langs = args.tts or list(models.VOICES)
68
+ for lang in langs:
69
+ if lang not in models.VOICES:
70
+ print(f'No voice for {lang!r}: choose from {", ".join(models.VOICES)}', file=sys.stderr)
71
+ return 2
72
+ ok = models.setup_voice(lang, base, log)
73
+ print(f'Voice {lang}: {"ready" if ok else "FAILED"}')
74
+ if not shutil.which('pw-play'):
75
+ print('pw-play not found: install pipewire-audio-client-libraries (Ubuntu) or pipewire-utils', file=sys.stderr)
76
+ return 0
77
+ if getattr(args, 'wake', False):
78
+ # `setup --wake`: only the wake word model, for an install that already works.
79
+ miss = models.setup_wake(base, log)
80
+ if miss:
81
+ print('Still missing: ' + ', '.join(miss), file=sys.stderr)
82
+ return 1
83
+ print('Wake word model ready. Switch the wake word on in the Voice Hold preferences.')
84
+ return 0
85
+ if args.commands:
86
+ # `setup --commands`: the local LLM (llama.cpp and its model) and
87
+ # the helper's D-Bus service, for an install that already works.
88
+ from . import llamacpp
89
+ print(f'LLM directory: {llamacpp.llm_dir()}')
90
+ miss = llamacpp.setup(log=log)
91
+ if miss:
92
+ print('Still missing: ' + ', '.join(miss), file=sys.stderr)
93
+ return 1
94
+ install_commands_service()
95
+ print('Voice commands ready. Switch them on in the Voice Hold preferences.')
96
+ return 0
97
+ miss = models.setup(base, log)
98
+ if miss:
99
+ print('Still missing: ' + ', '.join(miss), file=sys.stderr)
100
+ return 1
101
+ print('Models ready.')
102
+ install_service()
103
+ install_commands_service()
104
+ print('Done. Enable the Voice Hold extension and hold Ctrl+Space in a text field.')
105
+ print('Optional voices (text to speech): voice-hold-engine setup --tts')
106
+ return 0
107
+
108
+
109
+ def cmd_status(args):
110
+ base = models.models_dir()
111
+ miss = models.missing(base)
112
+ print(f'voice-hold-engine {__version__}')
113
+ print(f'models: {base} ({"ready" if not miss else "missing: " + ", ".join(miss)})')
114
+ if args.verify and not miss:
115
+ bad = models.verify(base)
116
+ print(f'checksums: {"all match" if not bad else "MISMATCH: " + ", ".join(bad)}')
117
+ miss = miss or bad
118
+ svc = service_dir() / SERVICE_FILE
119
+ print(f'D-Bus service file: {svc} ({"present" if svc.exists() else "absent"})')
120
+ print(f'pw-record: {shutil.which("pw-record") or "NOT FOUND"}')
121
+ voices = models.voices_ready(base)
122
+ print(f'voices: {", ".join(voices) if voices else "none (voice-hold-engine setup --tts)"}; '
123
+ f'pw-play: {shutil.which("pw-play") or "NOT FOUND"}')
124
+ wake_miss = models.wake_missing(base)
125
+ wake_state = 'ready' if not wake_miss else 'not installed (voice-hold-engine setup --wake)'
126
+ if args.verify and not wake_miss:
127
+ bad = models.wake_verify(base)
128
+ wake_state = 'ready, checksums match' if not bad else 'CHECKSUM MISMATCH: ' + ', '.join(bad)
129
+ print(f'wake word: {models.WAKE_NAME} {wake_state}')
130
+ from . import llamacpp
131
+ from .commands import jobs
132
+ lm = llamacpp.missing()
133
+ term = jobs.find_terminal()
134
+ print(f'voice commands: LLM {llamacpp.MODEL_NAME} '
135
+ f'{"ready" if not lm else "not installed (voice-hold-engine setup --commands)"}'
136
+ f'{", server running" if llamacpp.healthy(0.3) else ""}; '
137
+ f'terminal: {term[0] if term else "NOT FOUND"}')
138
+ if models.upgrade_available(base) and not miss:
139
+ print(f'a better speech model is available ({models.ASR_NAME}): voice-hold-engine setup')
140
+ return 0 if not miss and svc.exists() else 1
141
+
142
+
143
+ def cmd_interpret(args):
144
+ import json
145
+ from .commands.interpreter import Interpreter
146
+ it = Interpreter(use_llm=not args.no_llm)
147
+ if it.use_llm:
148
+ from . import llamacpp
149
+ llamacpp.ensure()
150
+ print(json.dumps(it.interpret(' '.join(args.text)), ensure_ascii=False, indent=1))
151
+ return 0
152
+
153
+
154
+ def cmd_apps(args):
155
+ from .commands.apps import list_apps
156
+ for a in list_apps(force=True):
157
+ print(f"{a['id']:40} {a['name']}" + (f" ({a['name_fr']})" if a['name_fr'] else ''))
158
+ return 0
159
+
160
+
161
+ def cmd_commands_serve(args):
162
+ from .commands.service import serve
163
+ try:
164
+ asyncio.run(serve())
165
+ except KeyboardInterrupt:
166
+ pass
167
+ return 0
168
+
169
+
170
+ def cmd_transcribe(args):
171
+ from .asr import Recognizer
172
+ from .audio import FileSource
173
+ rec = Recognizer()
174
+ audio = FileSource.read(args.file)
175
+ rec.load()
176
+ print(f'[loaded in {rec.load_seconds:.1f}s]', file=sys.stderr)
177
+ import time
178
+ t0 = time.perf_counter()
179
+ print(rec.transcribe(audio))
180
+ dur = len(audio) / 16000
181
+ print(f'[{dur:.1f}s audio decoded in {time.perf_counter() - t0:.2f}s]', file=sys.stderr)
182
+ return 0
183
+
184
+
185
+ def cmd_speak(args):
186
+ from .tts import Speaker
187
+ import time
188
+ lang = args.lang
189
+ if not models.voice_ready(lang):
190
+ print(f'No {lang} voice installed: voice-hold-engine setup --tts {lang}', file=sys.stderr)
191
+ return 1
192
+ sp = Speaker()
193
+ t0 = time.perf_counter()
194
+ proc = sp.speak(' '.join(args.text), lang, args.speed)
195
+ print(f'[voice loaded in {sp.load_seconds:.1f}s, synthesized in {time.perf_counter() - t0 - sp.load_seconds:.2f}s]', file=sys.stderr)
196
+ if proc is not None:
197
+ proc.wait()
198
+ sp.finished()
199
+ return 0
200
+
201
+
202
+ def cmd_serve(args):
203
+ from .service import serve
204
+ try:
205
+ asyncio.run(serve())
206
+ except KeyboardInterrupt:
207
+ pass
208
+ return 0
209
+
210
+
211
+ def cmd_uninstall(args):
212
+ from . import llamacpp
213
+ llamacpp.stop()
214
+ for name in (SERVICE_FILE, COMMANDS_SERVICE_FILE):
215
+ svc = service_dir() / name
216
+ if svc.exists():
217
+ svc.unlink()
218
+ print(f'Removed {svc}')
219
+ if args.models:
220
+ for base in (models.models_dir(), llamacpp.llm_dir()):
221
+ if base.exists():
222
+ shutil.rmtree(base)
223
+ print(f'Removed {base}')
224
+ print('Now run: pipx uninstall voice-hold-engine (or: uv tool uninstall voice-hold-engine)')
225
+ return 0
226
+
227
+
228
+ def main(argv=None):
229
+ p = argparse.ArgumentParser(prog='voice-hold-engine', description=__doc__)
230
+ p.add_argument('--version', action='version', version=__version__)
231
+ sub = p.add_subparsers(dest='cmd')
232
+ sub.add_parser('serve', help='run the D-Bus service (default)').set_defaults(fn=cmd_serve)
233
+ se = sub.add_parser('setup', help='download the models and install the D-Bus service')
234
+ se.add_argument('--tts', nargs='*', metavar='LANG', help='download the voices for spoken answers (fr, en; all when none given)')
235
+ se.add_argument('--commands', action='store_true', help='download the local LLM for the voice commands (llama.cpp, ~1.3 GB)')
236
+ se.add_argument('--wake', action='store_true', help='download the wake word model (Kroko fr, ~55 MB)')
237
+ se.set_defaults(fn=cmd_setup)
238
+ st = sub.add_parser('status', help='check models and service')
239
+ st.add_argument('--verify', action='store_true', help='also check the SHA-256 of every model file')
240
+ st.set_defaults(fn=cmd_status)
241
+ sub.add_parser('install-service', help='(re)write the D-Bus service files').set_defaults(
242
+ fn=lambda a: (install_service(), install_commands_service(), 0)[2])
243
+ sub.add_parser('commands-serve', help='run the voice-command D-Bus service').set_defaults(fn=cmd_commands_serve)
244
+ i = sub.add_parser('interpret', help='print what a spoken command would do, without doing it')
245
+ i.add_argument('--no-llm', action='store_true')
246
+ i.add_argument('text', nargs='+')
247
+ i.set_defaults(fn=cmd_interpret)
248
+ sub.add_parser('apps', help='list the applications the voice commands know').set_defaults(fn=cmd_apps)
249
+ t = sub.add_parser('transcribe', help='transcribe a WAV file (debug)')
250
+ t.add_argument('file')
251
+ t.set_defaults(fn=cmd_transcribe)
252
+ sp = sub.add_parser('speak', help='say a sentence aloud (debug of the voices)')
253
+ sp.add_argument('--lang', default='fr', choices=sorted(models.VOICES))
254
+ sp.add_argument('--speed', type=float, default=1.0)
255
+ sp.add_argument('text', nargs='+')
256
+ sp.set_defaults(fn=cmd_speak)
257
+ u = sub.add_parser('uninstall', help='remove the D-Bus service files (and models with --models)')
258
+ u.add_argument('--models', action='store_true')
259
+ u.set_defaults(fn=cmd_uninstall)
260
+ args = p.parse_args(argv)
261
+ fn = getattr(args, 'fn', cmd_serve)
262
+ return fn(args)
263
+
264
+
265
+ if __name__ == '__main__':
266
+ sys.exit(main())
@@ -0,0 +1,7 @@
1
+ """Voice commands (optional): intent rules, a small local LLM served by
2
+ llama.cpp for what the rules leave, guard rails and shell jobs, behind a
3
+ second session D-Bus service."""
4
+
5
+ BUS_NAME = 'org.griffit.VoiceHold.Commands'
6
+ OBJECT_PATH = '/org/griffit/VoiceHold/Commands'
7
+ INTERFACE = 'org.griffit.VoiceHold.Commands'
@@ -0,0 +1,71 @@
1
+ """Installed applications, read from .desktop files (no PyGObject needed).
2
+
3
+ Each app: {id, name, name_fr, generic, generic_fr, keywords, exec}. The list
4
+ is cached for a minute: a voice command must not pay a directory walk."""
5
+ import configparser
6
+ import glob
7
+ import os
8
+ import time
9
+ from pathlib import Path
10
+
11
+ DIRS = [
12
+ Path.home() / '.local/share/applications',
13
+ Path('/usr/share/applications'),
14
+ Path('/usr/local/share/applications'),
15
+ Path('/var/lib/flatpak/exports/share/applications'),
16
+ Path.home() / '.local/share/flatpak/exports/share/applications',
17
+ Path('/var/lib/snapd/desktop/applications'),
18
+ ]
19
+ CACHE_S = 60.0
20
+
21
+ _cache = {'at': 0.0, 'apps': []}
22
+
23
+
24
+ def _split(v):
25
+ return [k for k in (v or '').split(';') if k]
26
+
27
+
28
+ def read_desktop(path):
29
+ cp = configparser.RawConfigParser(strict=False, interpolation=None)
30
+ try:
31
+ cp.read(path, encoding='utf-8')
32
+ e = cp['Desktop Entry']
33
+ except Exception:
34
+ return None
35
+ if e.get('Type', 'Application') != 'Application':
36
+ return None
37
+ if e.get('NoDisplay', 'false').lower() == 'true' or e.get('Hidden', 'false').lower() == 'true':
38
+ return None
39
+ if 'OnlyShowIn' in e and 'GNOME' not in _split(e.get('OnlyShowIn')):
40
+ return None
41
+ if 'GNOME' in _split(e.get('NotShowIn')):
42
+ return None
43
+ exe = (e.get('Exec') or '').split(' ')[0].split('/')[-1]
44
+ return {
45
+ 'id': os.path.basename(path),
46
+ 'name': e.get('Name', ''),
47
+ 'name_fr': e.get('Name[fr]', ''),
48
+ 'generic': e.get('GenericName', ''),
49
+ 'generic_fr': e.get('GenericName[fr]', ''),
50
+ 'keywords': _split(e.get('Keywords')) + _split(e.get('Keywords[fr]')),
51
+ 'exec': exe,
52
+ }
53
+
54
+
55
+ def list_apps(dirs=None, force=False):
56
+ now = time.monotonic()
57
+ if not force and dirs is None and _cache['apps'] and now - _cache['at'] < CACHE_S:
58
+ return _cache['apps']
59
+ seen, apps = set(), []
60
+ for d in dirs or DIRS:
61
+ for f in sorted(glob.glob(str(d / '*.desktop'))):
62
+ did = os.path.basename(f)
63
+ if did in seen:
64
+ continue
65
+ seen.add(did)
66
+ app = read_desktop(f)
67
+ if app:
68
+ apps.append(app)
69
+ if dirs is None:
70
+ _cache.update(at=now, apps=apps)
71
+ return apps