From ec39a990e4335f158fb9d5c8e1100c99585341f4 Mon Sep 17 00:00:00 2001 From: Gabby Morgan Date: Fri, 9 Oct 2026 08:19:36 +0000 Subject: [PATCH] voice: default wake word to "Hey Computer", capture command after a pause openWakeWord ships no "computer" model, so pin a community openWakeWord-compatible ONNX (Apache-2.0, sha256 in pins.json `wake_word`) and fetch it into .runtime/voice/wake from scripts/voice-models.py. Its scores run lower than the official models (~0.26-0.82 on the phrase, <0.02 on negatives), so the seeded wake.threshold is 0.2 (the official models score ~0.99 at 0.5). Also fix command capture: after the wake word the daemon now waits listen_timeout_s (default 3s) for the command's speech to begin instead of assuming it is glued to the wake word, so a natural pause while the cue beep plays no longer truncates the command. --- README.md | 21 ++++++-- config.example.json | 8 +-- pins.json | 8 +++ scripts/bootstrap.sh | 6 +-- scripts/voice-models.py | 67 +++++++++++++++++++++---- semif_agent/voice_transport.py | 47 ++++++++++++++---- tests/test_voice_gateway.py | 90 ++++++++++++++++++++++++++++++++++ 7 files changed, 218 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index f6cbac4..6ab5a76 100644 --- a/README.md +++ b/README.md @@ -667,18 +667,29 @@ python -m semif_agent.cli gateway --platform voice PortAudio has no volume control — use `alsamixer`/`amixer` (then `sudo alsactl store`) to unmute and set the mic/speaker levels. - **Models.** `gateway.voice.wake.model` is an openWakeWord model (default - `hey_mycroft`), `stt.model` a faster-whisper size (default `base.en`), and + `hey_computer`, spoken phrase "Hey Computer"), `stt.model` a faster-whisper + size (default `base.en`), and `tts.voice` a Piper voice (default `en_US-lessac-medium`). Bootstrap downloads - the openWakeWord models into the venv's package dir (under `.runtime/venv`) - and the Piper voice into `.runtime/voice/tts`; the faster-whisper model lands - in the `.runtime/hf` cache. + the official openWakeWord models into the venv's package dir (under + `.runtime/venv`) and the Piper voice into `.runtime/voice/tts`; the + faster-whisper model lands in the `.runtime/hf` cache. openWakeWord ships no + "computer" model, so the default is a **pinned community model** + (openWakeWord-compatible, sha256-checked in `pins.json`) that + `scripts/voice-models.py` fetches into `.runtime/voice/wake`, where the + detector resolves it via `wake.model_dir`. Set `wake.model` to an official + name (e.g. `alexa`) or a path to switch. Because the community model's scores + run lower than the official models, the seeded `wake.threshold` is `0.2` (the + official models score ~0.99 and use `0.5`). - **Behavior.** Half-duplex — capture is discarded while a reply is speaking, so the agent never transcribes itself (no barge-in yet). A short beep plays when the wake word fires (`gateway.voice.cue`), so you know you're being heard; set `cue.submit_frequency > 0` for a second beep once the utterance is transcribed. After a reply, the next utterance is accepted **without** the wake word for `follow_up_window_s`, so - answering a question is conversational. `max_speak_chars` truncates long + answering a question is conversational. After the wake word, capture waits + `listen_timeout_s` for the command to begin, so a pause before speaking + (e.g. while the cue beep plays) does not truncate it. `max_speak_chars` + truncates long replies before speaking. `result_only` (default true for voice) speaks only the skill's result line — scheduler bookkeeping is dropped and the `: ok —` wrapper is stripped — so the spoken output is the answer, not diff --git a/config.example.json b/config.example.json index 9e87fde..a4fd41a 100644 --- a/config.example.json +++ b/config.example.json @@ -217,7 +217,7 @@ "text_batch_delay": 0.8 }, "voice": { - "_comment": "Voice command adapter: a local microphone front end with wake word + speech-to-text + text-to-speech. Requires the optional voice stack (requirements/voice.txt; sounddevice + openwakeword + faster-whisper + piper-tts + onnxruntime; the system needs libportaudio2). Lazy-imported; the gateway refuses to start with an install hint. Runs best in the user's audio session (foreground `gateway --platform voice`), not a headless systemd user service. Audio is 16 kHz mono int16; capture/playback run at the device's native rate and are resampled to/from 16 kHz (capture_sample_rate/output_sample_rate override it; 0 = the device default). wake.model is an openWakeWord model name or path (bootstrap downloads models into the venv, where they resolve by name; model_dir is an optional local dir for a custom model file); stt.model is a faster-whisper size/path (cached under .runtime/hf); tts.voice is a Piper voice id or path (bootstrap downloads it under .runtime/voice/tts). After each reply the next utterance is accepted without the wake word for follow_up_window_s. result_only speaks just the skill's result line (dropping queue/urgency bookkeeping and the `: ok —` wrapper) instead of the full scheduler output; set false for the complete text. max_speak_chars truncates long replies before speaking. chat_id identifies the single local session; home_channel defaults to it so timers/repair offers are spoken too.", + "_comment": "Voice command adapter: a local microphone front end with wake word + speech-to-text + text-to-speech. Requires the optional voice stack (requirements/voice.txt; sounddevice + openwakeword + faster-whisper + piper-tts + onnxruntime; the system needs libportaudio2). Lazy-imported; the gateway refuses to start with an install hint. Runs best in the user's audio session (foreground `gateway --platform voice`), not a headless systemd user service. Audio is 16 kHz mono int16; capture/playback run at the device's native rate and are resampled to/from 16 kHz (capture_sample_rate/output_sample_rate override it; 0 = the device default). wake.model is an openWakeWord model name or path (official models download into the venv and resolve by name; a pinned community model such as the default 'hey_computer' is fetched into model_dir, .runtime/voice/wake); stt.model is a faster-whisper size/path (cached under .runtime/hf); tts.voice is a Piper voice id or path (bootstrap downloads it under .runtime/voice/tts). After each reply the next utterance is accepted without the wake word for follow_up_window_s. After the wake word, listen_timeout_s is how long to wait for the command to start before giving up, so a pause before speaking does not truncate it. result_only speaks just the skill's result line (dropping queue/urgency bookkeeping and the `: ok —` wrapper) instead of the full scheduler output; set false for the complete text. max_speak_chars truncates long replies before speaking. chat_id identifies the single local session; home_channel defaults to it so timers/repair offers are spoken too.", "enabled": false, "chat_id": "voice", "display_name": "voice", @@ -226,6 +226,7 @@ "result_only": true, "max_speak_chars": 600, "follow_up_window_s": 5.0, + "listen_timeout_s": 3.0, "cue": { "_comment": "Audible feedback. A short sine beep plays when the wake word fires so you know you're being heard; set submit_frequency > 0 for a second beep once the utterance is transcribed. volume is 0..1.", "enabled": true, @@ -236,8 +237,9 @@ "submit_duration_ms": 100 }, "wake": { - "model": "hey_mycroft", - "threshold": 0.5, + "_comment": "model is an openWakeWord name/path. The default 'hey_computer' is a pinned community model whose scores run lower than the official models (measured ~0.26-0.82 on the phrase, <0.02 on negatives), so threshold 0.2 is tuned for it; the official models (e.g. hey_mycroft) score ~0.99 and are fine at 0.5.", + "model": "hey_computer", + "threshold": 0.2, "inference_framework": "onnx", "model_dir": "" }, diff --git a/pins.json b/pins.json index 759e264..62a76e9 100644 --- a/pins.json +++ b/pins.json @@ -19,5 +19,13 @@ "piper_train_ref": "efffbfb226bfb511ebbcf55d0cecd8b35a89743d", "base_checkpoint_url": "https://huggingface.co/datasets/rhasspy/piper-checkpoints/resolve/main/en/en_US/lessac/medium/epoch=2164-step=1355540.ckpt", "base_checkpoint_sha256": "ab7e5b8dab40f834b7cc58ae4ad7b7009c954b901e4ddbb784bbe11ce379a1cd" + }, + "wake_word": { + "_comment": "openWakeWord-compatible wake-word model refs fetched by scripts/voice-models.py into .runtime/voice/wake (deployment-independent, code-owned like the other pins). openWakeWord ships no 'computer' model, so this community-trained ONNX (Apache-2.0, same mel/embedding feature models) is pinned by sha256. 'phrase' is the spoken wake phrase.", + "hey_computer": { + "url": "https://huggingface.co/Soulcreek2/speechkit-wakeword-models/resolve/main/hey_computer.onnx", + "sha256": "3acbd9ffff04beba2d16ebdfd0d4c734d65fecdd22446f25f4d0afa6e5d7606b", + "phrase": "Hey Computer" + } } } diff --git a/scripts/bootstrap.sh b/scripts/bootstrap.sh index 9089b1a..d368e7b 100755 --- a/scripts/bootstrap.sh +++ b/scripts/bootstrap.sh @@ -642,9 +642,9 @@ Voice command gateway (wake word + speech-to-text + text-to-speech): Enable it in config.json with gateway.voice.enabled = true, then run it in the foreground (it needs your audio session; it is NOT a systemd unit): HF_HOME="$HF_CACHE" "$PYTHON" -m semif_agent.cli gateway --platform voice - - Say the wake word (gateway.voice.wake.model, default 'hey_mycroft') and - speak; the reply is spoken back. After each reply the next utterance needs - no wake word for gateway.voice.follow_up_window_s. + - Say the wake word (gateway.voice.wake.model, default 'hey_computer' — phrase + "Hey Computer") and speak; the reply is spoken back. After each reply the + next utterance needs no wake word for gateway.voice.follow_up_window_s. - If the mic or speaker is silent/quiet, set the ALSA mixer (PortAudio has no volume control) and persist it: alsamixer # or: amixer -c sset 'Speaker' unmute diff --git a/scripts/voice-models.py b/scripts/voice-models.py index 148dbc1..ae0c403 100644 --- a/scripts/voice-models.py +++ b/scripts/voice-models.py @@ -6,9 +6,12 @@ Run after installing `requirements/voice.txt` (bootstrap does this with `gateway.voice` from config.json so the downloaded models match the configured names, or take explicit flags. -- **Wake word** (openWakeWord): downloaded by `openwakeword.utils.download_models` - into the venv's package resources dir (inside `.runtime/venv/`, so still - contained in the checkout). The detector resolves the model by name there. +- **Wake word** (openWakeWord): official models are downloaded by + `openwakeword.utils.download_models` into the venv's package resources dir + (inside `.runtime/venv/`, so still contained in the checkout); the detector + resolves the model by name there. A **pinned community model** (openWakeWord + ships no "computer" model) is fetched from `pins.json` `wake_word` into the + configured `model_dir` (`.runtime/voice/wake`) and verified by sha256. - **TTS** (Piper): the voice `.onnx` + `.onnx.json` are fetched from the `rhasspy/piper-voices` HF repo into `.runtime/voice/tts/`. - **STT** (faster-whisper): instantiating the model warms it into the HF cache @@ -18,12 +21,15 @@ names, or take explicit flags. from __future__ import annotations import argparse +import hashlib import json import shutil +import urllib.request from pathlib import Path REPO_ROOT = Path(__file__).resolve().parent.parent RUNTIME = REPO_ROOT / ".runtime" / "voice" +PINS = REPO_ROOT / "pins.json" PIPER_REPO = "rhasspy/piper-voices" @@ -42,15 +48,56 @@ def piper_hf_path(voice: str) -> str: return f"{lang}/{locale}/{name}/{quality}/{voice}.onnx" -def download_wake(name: str) -> None: +def pinned_wake_models() -> dict: + """Return the code-owned wake-word refs from `pins.json` (`name` -> ref).""" + try: + pins = json.loads(PINS.read_text()) + except Exception: + return {} + block = pins.get("wake_word", {}) or {} + return { + name: ref + for name, ref in block.items() + if isinstance(ref, dict) and ref.get("url") + } + + +def _sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def download_wake_file(name: str, ref: dict, target_dir: Path) -> None: + """Fetch a pinned community wake model into `target_dir`, verifying sha256.""" + url = str(ref["url"]) + expected = str(ref.get("sha256", "") or "") + target_dir.mkdir(parents=True, exist_ok=True) + dest = target_dir / f"{name}.onnx" + if dest.is_file() and (not expected or _sha256(dest) == expected): + print(f"== wake word: {dest.name} (present)") + return + print(f"== wake word: {url} -> {dest}") + with urllib.request.urlopen(url) as resp: # pinned https URL from pins.json + data = resp.read() + if expected and hashlib.sha256(data).hexdigest() != expected: + raise SystemExit(f"sha256 mismatch for {name}: refusing to write {dest}") + dest.write_bytes(data) + + +def download_wake(name: str, target_dir: Path) -> None: import openwakeword.utils as utils print(f"== wake word model: {name}") - # Default target: the venv's package resources dir (inside .runtime/venv). - # openWakeWord resolves the model (and its shared mel/embedding models) by - # name from there. + # Always fetch the shared feature (mel/embedding) + VAD models, and for an + # official name the phrase model itself, into the venv's package resources + # dir (inside .runtime/venv). An unknown name is skipped here. utils.download_models(model_names=[name]) + # A pinned community model (openWakeWord ships no "computer" model) is + # fetched into the configured model_dir so the detector resolves it by path. + ref = pinned_wake_models().get(name) + if ref: + download_wake_file(name, ref, target_dir) + def download_voice(voice: str, target: Path) -> None: from huggingface_hub import hf_hub_download @@ -86,6 +133,8 @@ def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--config", default=str(REPO_ROOT / "config.json")) parser.add_argument("--wake", default=None, help="openWakeWord model name") + parser.add_argument("--wake-dir", default=str(RUNTIME / "wake"), + help="target dir for a pinned community wake model") parser.add_argument("--stt", default=None, help="faster-whisper model size/path") parser.add_argument("--tts", default=None, help="Piper voice id") parser.add_argument("--tts-dir", default=str(RUNTIME / "tts")) @@ -95,12 +144,12 @@ def main(argv: list[str] | None = None) -> int: args = parser.parse_args(argv) voice_cfg = _config_voice(Path(args.config)) - wake = args.wake or (voice_cfg.get("wake", {}) or {}).get("model") or "hey_mycroft" + wake = args.wake or (voice_cfg.get("wake", {}) or {}).get("model") or "hey_computer" stt = args.stt or (voice_cfg.get("stt", {}) or {}).get("model") or "base.en" tts = args.tts or (voice_cfg.get("tts", {}) or {}).get("voice") or "en_US-lessac-medium" if not args.skip_wake: - download_wake(wake) + download_wake(wake, Path(args.wake_dir)) if not args.skip_tts: download_voice(tts, Path(args.tts_dir)) if not args.skip_stt: diff --git a/semif_agent/voice_transport.py b/semif_agent/voice_transport.py index afc2498..13463f8 100644 --- a/semif_agent/voice_transport.py +++ b/semif_agent/voice_transport.py @@ -543,7 +543,7 @@ def build_engines(cfg: dict, trace=None) -> VoiceEngines: audio_cfg = cfg.get("audio", {}) or {} wake_model = resolve_model_path( - str(wake_cfg.get("model", "hey_mycroft") or ""), + str(wake_cfg.get("model", "hey_computer") or ""), str(wake_cfg.get("model_dir", "") or ""), (".onnx", ".tflite"), ) @@ -555,7 +555,7 @@ def build_engines(cfg: dict, trace=None) -> VoiceEngines: return VoiceEngines( wake=OpenWakeWordDetector( wake_model, - threshold=float(wake_cfg.get("threshold", 0.5)), + threshold=float(wake_cfg.get("threshold", 0.2)), inference_framework=str(wake_cfg.get("inference_framework", "onnx")), ), vad=_build_vad(cfg), @@ -601,7 +601,11 @@ class VoiceDaemon: self.config = cfg self.trace = trace self.name = name - self.wake_threshold = float((cfg.get("wake", {}) or {}).get("threshold", 0.5)) + self.wake_threshold = float((cfg.get("wake", {}) or {}).get("threshold", 0.2)) + #: After the wake word, how long to wait for the command's speech to + #: begin before giving up (a natural pause after "hey " — e.g. + #: waiting for the cue beep — must not truncate the command). + self.listen_timeout_ms = int(float(cfg.get("listen_timeout_s", 3.0) or 0) * 1000) audio_cfg = cfg.get("audio", {}) or {} self.sample_rate = int(audio_cfg.get("sample_rate", SAMPLE_RATE) or SAMPLE_RATE) self.frame_ms = int(audio_cfg.get("frame_ms", 80) or 80) @@ -700,6 +704,7 @@ class VoiceDaemon: if self._speaking.is_set(): continue armed = time.time() < self._follow_until + wait_for_speech_ms = 0 if not armed: score = engines.wake.score(pcm) if score < self.wake_threshold: @@ -710,8 +715,12 @@ class VoiceDaemon: except Exception: pass self._cue(self.cue_frequency, self.cue_duration_ms) + # Wait for the command to start rather than assuming it is + # glued to the wake word (the wake frame + a natural pause are + # discarded so the command is not truncated). + wait_for_speech_ms = self.listen_timeout_ms self._follow_until = 0.0 - utterance = self._collect(engines, pcm) + utterance = self._collect(engines, pcm, wait_for_speech_ms=wait_for_speech_ms) if not utterance: continue try: @@ -728,15 +737,27 @@ class VoiceDaemon: if self._on_utterance is not None: self._on_utterance(text) - def _collect(self, engines: VoiceEngines, first_frame: bytes) -> bytes: - """Accumulate frames from the wake word until trailing silence.""" - frames = [first_frame] - speech_ms = self.frame_ms + def _collect(self, engines: VoiceEngines, first_frame: bytes, wait_for_speech_ms: int = 0) -> bytes: + """Accumulate frames from the wake word until trailing silence. + + With `wait_for_speech_ms > 0`, `first_frame` (the wake-word frame) and + any leading silence are discarded and capture starts only once the + command's speech begins — so a natural pause after the wake word does + not truncate the command. Gives up after that many milliseconds with no + speech (traced `voice_no_command`). + """ + frames: list[bytes] = [] + speech_ms = 0 silence_ms = 0 started = time.time() #: Wall-clock of the most recent frame the VAD called speech — the #: "last word spoken" boundary the latency breakdown measures from. last_speech_ts = started + waiting = wait_for_speech_ms > 0 + wait_started = started + if not waiting: + frames.append(first_frame) + speech_ms = self.frame_ms while not self._stop.is_set(): if self._speaking.is_set(): break # a reply started; stop capturing so we don't transcribe it @@ -745,8 +766,16 @@ class VoiceDaemon: pcm = engines.audio.read() if pcm is None: break + is_speech = engines.vad.is_speech(pcm, self.sample_rate) + if waiting: + if not is_speech: + if (time.time() - wait_started) * 1000.0 >= wait_for_speech_ms: + self._event("voice_no_command", waited_ms=wait_for_speech_ms) + return b"" + continue + waiting = False frames.append(pcm) - if engines.vad.is_speech(pcm, self.sample_rate): + if is_speech: speech_ms += self.frame_ms silence_ms = 0 last_speech_ts = time.time() diff --git a/tests/test_voice_gateway.py b/tests/test_voice_gateway.py index a5aa921..9f5e497 100644 --- a/tests/test_voice_gateway.py +++ b/tests/test_voice_gateway.py @@ -170,6 +170,33 @@ def test_min_speech_rejects_short_utterance(): assert engines.stt.calls == [] +def test_command_after_pause_is_captured(): + # A pause between the wake word and the command (e.g. waiting for the cue + # beep) must not truncate the command: capture waits for speech to begin. + daemon, engines = make_daemon( + [b"WAKE", b"SIL", b"SIL", b"SIL", b"command", b"SIL", b"SIL"] + ) + heard = [] + daemon.run(heard.append) + assert heard == ["hello"] + assert engines.stt.calls == [b"command" + b"SIL" * 2] + + +def test_wake_without_command_times_out(monkeypatch): + # Wake fires but the user never speaks a command: no utterance is produced + # (traced `voice_no_command`) instead of capturing the wake frame as one. + import semif_agent.voice_transport as vt + + ticks = iter([0.0, 0.0, 3000.0]) + monkeypatch.setattr(vt.time, "time", lambda: next(ticks)) + daemon, engines = make_daemon([b"SIL", b"SIL"]) + events = [] + daemon._event = lambda kind, **kw: events.append(kind) + utterance = daemon._collect(engines, b"WAKE", wait_for_speech_ms=3000) + assert utterance == b"" + assert "voice_no_command" in events + + # ---- half-duplex / speaking ------------------------------------------------ @@ -313,3 +340,66 @@ def test_resample_pcm16(): assert len(_resample_pcm16(pcm, 44100, 16000)) // 2 == 160 assert _resample_pcm16(pcm, 44100, 44100) == pcm assert _resample_pcm16(b"", 44100, 16000) == b"" + + +# ---- wake-word model pinning (community model, no network) ------------------ + + +def _load_voice_models(): + import importlib.util + from pathlib import Path + + path = Path(__file__).resolve().parent.parent / "scripts" / "voice-models.py" + spec = importlib.util.spec_from_file_location("voice_models_script", path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def test_wake_word_pin_resolves_from_model_dir(tmp_path): + import hashlib + + from semif_agent.voice_transport import resolve_model_path + + module = _load_voice_models() + pins = module.pinned_wake_models() + assert "hey_computer" in pins + ref = pins["hey_computer"] + assert ref["url"].endswith("/hey_computer.onnx") + assert len(ref["sha256"]) == len(hashlib.sha256(b"").hexdigest()) + + stub = tmp_path / "hey_computer.onnx" + stub.write_bytes(b"stub") + assert resolve_model_path("hey_computer", str(tmp_path), (".onnx", ".tflite")) == str(stub) + + +def test_download_wake_file_verifies_and_skips_existing(tmp_path): + import hashlib + + module = _load_voice_models() + data = b"fake-openwakeword-model" + source = tmp_path / "src.onnx" + source.write_bytes(data) + ref = {"url": source.as_uri(), "sha256": hashlib.sha256(data).hexdigest()} + + wake_dir = tmp_path / "wake" + module.download_wake_file("hey_computer", ref, wake_dir) + dest = wake_dir / "hey_computer.onnx" + assert dest.read_bytes() == data + # Idempotent: a present, matching file is not re-fetched. + module.download_wake_file("hey_computer", ref, wake_dir) + assert dest.read_bytes() == data + + +def test_download_wake_file_rejects_sha_mismatch(tmp_path): + import pytest + + module = _load_voice_models() + source = tmp_path / "src.onnx" + source.write_bytes(b"tampered") + ref = {"url": source.as_uri(), "sha256": "0" * 64} + + wake_dir = tmp_path / "wake" + with pytest.raises(SystemExit): + module.download_wake_file("hey_computer", ref, wake_dir) + assert not (wake_dir / "hey_computer.onnx").exists()