Skip to content

The agent that grows with you

fix(wake): use one engine family and honor selected capture

ethernetfd605dcacfb5
diff --git a/tests/tools/test_wake_word.py b/tests/tools/test_wake_word.py
index 2d35e3cdf0b..b4773b732b2 100644
--- a/tests/tools/test_wake_word.py
+++ b/tests/tools/test_wake_word.py
@@ -92,6 +92,99 @@ def test_build_engine_dispatch(monkeypatch):
ww._build_engine({"provider": "bogus"})
+def test_engine_classes_are_owned_by_the_extracted_module():
+ """wake_word imports the extracted engines and must not shadow them with
+ copies — two class families carrying thresholds/model lookup/cleanup is
+ exactly the bug class where fixes to the apparent owner do nothing."""
+ from tools import wake_word_engines as engines
+
+ assert ww._Engine is engines._Engine
+ assert ww._OpenWakeWordEngine is engines._OpenWakeWordEngine
+ assert ww._SherpaKwsEngine is engines._SherpaKwsEngine
+ assert ww._PorcupineEngine is engines._PorcupineEngine
+
+
+def test_engine_construction_ensures_audio_io_only_for_local_capture(monkeypatch, tmp_path):
+ """Constructor-to-capture admission: an engine constructor ensures its own
+ wake-* extra always, but audio-io (sounddevice+numpy) ONLY when the resolved
+ capture mode is local. Client capture (desktop streams PCM via wake.feed)
+ must never trigger installation of local audio libraries.
+
+ Regression (Q033): the active engine constructors ensured only wake-*, so a
+ freshly installed per-engine extra without sounddevice/numpy failed at
+ capture; the extracted _ensure_dep fixed that but was dead code because
+ wake_word shadowed the extracted classes.
+ """
+ from tools import wake_word_engines as engines
+
+ ensured: list[str] = []
+
+ def _fake_ensure_import(feature, *a, **k):
+ ensured.append(feature)
+
+ monkeypatch.setattr(pm, "ensure_import", _fake_ensure_import)
+ monkeypatch.setattr(pm, "available", lambda feature: feature in ensured)
+
+ class _FakeModel:
+ id = "hey_hermes"
+
+ @staticmethod
+ def from_model(model_path, libtensorflowlite_c_path=None):
+ return _FakeModel()
+
+ def process_streaming(self, embeddings):
+ return iter(())
+
+ def reset(self):
+ pass
+
+ def close(self):
+ pass
+
+ class _FakeFeatures:
+ @staticmethod
+ def from_builtin(models_dir=None, libtensorflowlite_c_path=None):
+ return _FakeFeatures()
+
+ def process_streaming(self, audio_chunk):
+ return iter(())
+
+ def reset(self):
+ pass
+
+ def close(self):
+ pass
+
+ mod = types.ModuleType("pyopen_wakeword")
+ mod.OpenWakeWord = _FakeModel
+ mod.OpenWakeWordFeatures = _FakeFeatures
+ monkeypatch.setitem(sys.modules, "pyopen_wakeword", mod)
+
+ cfg = {"provider": "openwakeword"}
+
+ # Client capture: engine extra only, never audio-io.
+ engines._OpenWakeWordEngine({**cfg, "capture": "client"})
+ assert "wake-openwakeword" in ensured
+ assert "audio-io" not in ensured
+
+ # Local capture: engine extra plus the capture deps.
+ ensured.clear()
+ engines._OpenWakeWordEngine({**cfg, "capture": "local"})
+ assert "wake-openwakeword" in ensured
+ assert "audio-io" in ensured
+
+ # The caller has already selected client capture even when config says auto.
+ ensured.clear()
+ monkeypatch.setattr(ww, "_lock_path", lambda: tmp_path / "wake.lock")
+ owner = object()
+ try:
+ ww.start_listening(lambda: None, owner=owner, config=cfg, external_audio=True)
+ assert "wake-openwakeword" in ensured
+ assert "audio-io" not in ensured
+ finally:
+ ww.stop_listening(owner=owner)
+
+
# ── Requirements probe ───────────────────────────────────────────────────
diff --git a/tools/wake_word.py b/tools/wake_word.py
index 46c8a2f5ecb..6ce39bccae3 100644
--- a/tools/wake_word.py
+++ b/tools/wake_word.py
@@ -21,7 +21,13 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Dict, Optional
-from tools.wake_word_engines import _Engine, _PorcupineEngine, _SherpaKwsEngine, _sub
+from tools.wake_word_engines import (
+ _Engine,
+ _OpenWakeWordEngine,
+ _PorcupineEngine,
+ _SherpaKwsEngine,
+ _sub,
+)
logger = logging.getLogger(__name__)
@@ -268,314 +274,6 @@ def silent_audio_hint(details: Dict[str, Any]) -> str:
return f"Microphone delivers only silence from {label}. {fix}, then toggle the wake word."
-# ---------------------------------------------------------------------------
-# Engines
-# ---------------------------------------------------------------------------
-
-class _Engine:
- """Minimal hotword-engine contract: feed int16 frames, get a bool."""
-
- frame_length: int = 1280 # 80 ms at 16 kHz
-
- #: Optional (matched phrase, profile name) of the most recent fire.
- #: Multi-phrase engines (sherpa) set this for profile routing; the
- #: single-phrase engines leave it None (callers fall back to the
- #: configured phrase / active profile).
- last_match: Optional[tuple[str, str]] = None
-
- def process(self, frame) -> bool: # frame: 1-D int16 ndarray
- raise NotImplementedError
-
- def reset(self) -> None:
- """Clear any internal audio/feature buffer (called on every (re)start)."""
- pass
-
- def close(self) -> None:
- pass
-
-
-def _looks_like_path(value: str) -> bool:
- return (
- os.sep in value
- or value.endswith((".onnx", ".tflite", ".ppn"))
- or os.path.exists(value)
- )
-
-
-class _OpenWakeWordEngine(_Engine):
- """pyopen-wakeword — free, local hotword detection (TFLite via a bundled
- tensorflowlite_c lib; no runtime download, no framework choice). Scores one
- ~80 ms frame at a time; ``sensitivity`` IS the raw 0..1 threshold (higher =
- stricter). A real utterance holds the score high across frames while a stray
- phoneme spikes one, so ``confirmation_frames`` hits are required."""
-
- # pyopen-wakeword recommends 80 ms frames (1280 samples) for efficiency.
- frame_length = 1280
-
- def __init__(self, cfg: Dict[str, Any]):
- import pm
-
- pm.ensure_import("wake-openwakeword")
-
- from pyopen_wakeword import OpenWakeWord, OpenWakeWordFeatures
-
- sub = cfg.get("openwakeword") if isinstance(cfg.get("openwakeword"), dict) else {}
- model_ref = str(sub.get("model") or _BUNDLED_MODEL_NAME).strip()
- # Default (or explicit "hey_hermes") → the bundled model; a custom path
- # is used as-is. pyopen-wakeword bundles the shared feature models
- # (melspectrogram + embedding — byte-identical to the openWakeWord
- # v0.5.1 files) inside its wheel, so there is no download_models step.
- if model_ref.lower() in _BUNDLED_MODEL_ALIASES:
- model_ref = _bundled_wakeword_path()
- # pyopen-wakeword returns a 0..1 score per completed window; sensitivity
- # IS the raw threshold a score must clear. Higher = stricter (fewer
- # false fires). Default 0.6 sits above openWakeWord's permissive 0.5
- # baseline, which let near-misses like "hey hor" through.
- self._threshold = _sensitivity(cfg)
- self._confirm_needed = _confirmation_frames(cfg)
- self._confirm_streak = 0
- self._features = OpenWakeWordFeatures.from_builtin()
- self._model = OpenWakeWord.from_model(model_ref)
- self._labels = [self._model.id]
-
- def process(self, frame) -> bool:
- # frame is a 1-D int16 ndarray; the features pipeline consumes int16
- # bytes. process_streaming() yields embeddings as the window fills and
- # the model yields one 0..1 score per completed window.
- over = False
- for emb in self._features.process_streaming(frame.tobytes()):
- for score in self._model.process_streaming(emb):
- if score >= self._threshold:
- over = True
- # Require N consecutive over-threshold frames: a real phrase holds the
- # score high across frames, a stray ambient phoneme spikes just one.
- if over:
- self._confirm_streak += 1
- if self._confirm_streak >= self._confirm_needed:
- self._confirm_streak = 0
- return True
- return False
- self._confirm_streak = 0
- return False
-
- def reset(self) -> None:
- # Clears pyopen-wakeword's rolling feature/prediction buffer so stale
- # audio captured before a pause can't re-fire the moment we resume.
- self._confirm_streak = 0
- with suppress(Exception):
- self._features.reset()
- self._model.reset()
-
- def close(self) -> None:
- self.reset()
- with suppress(Exception):
- self._features.close()
- self._model.close()
-
-
-# sherpa-onnx open-vocabulary KWS model: a small streaming zipformer
-# transducer. English (GigaSpeech); one-time download, cached under
-# HERMES_HOME. Keywords are typed phrases tokenized at RUNTIME — no
-# training step, unlike openWakeWord/Porcupine custom models.
-_SHERPA_KWS_MODEL_URL = (
- "https://github.com/k2-fsa/sherpa-onnx/releases/download/kws-models/"
- "sherpa-onnx-kws-zipformer-gigaspeech-3.3M-2024-01-01.tar.bz2"
-)
-_SHERPA_KWS_MODEL_DIR = "sherpa-onnx-kws-zipformer-gigaspeech-3.3M-2024-01-01"
-
-
-def _sherpa_model_root() -> Path:
- from hermes_constants import get_hermes_home
-
- return get_hermes_home() / "cache" / "wakewords"
-
-
-def _ensure_sherpa_model(root: Optional[Path] = None) -> Path:
- """Download + unpack the sherpa KWS model once; return its directory."""
- root = root or _sherpa_model_root()
- target = root / _SHERPA_KWS_MODEL_DIR
- if (target / "tokens.txt").exists():
- return target
- import tarfile
- import urllib.request
-
- root.mkdir(parents=True, exist_ok=True)
- archive = root / f"{_SHERPA_KWS_MODEL_DIR}.tar.bz2"
- logger.info("wake word: downloading sherpa KWS model (one-time, ~13 MB)")
- urllib.request.urlretrieve(_SHERPA_KWS_MODEL_URL, archive) # noqa: S310
- with tarfile.open(archive, "r:bz2") as tf:
- tf.extractall(root, filter="data")
- archive.unlink(missing_ok=True)
- if not (target / "tokens.txt").exists():
- raise RuntimeError(f"sherpa KWS model unpack failed: {target}")
- return target
-
-
-class _SherpaKwsEngine(_Engine):
- """sherpa-onnx open-vocabulary keyword spotting — any typed phrase, zero training.
-
- The configured ``wake_word.phrase`` is BPE-tokenized at runtime against the
- model's vocabulary, so "hey hermes", "hey coder", or any other phrase works
- immediately. Here ``phrase`` is DETECTION config, not a cosmetic label.
- """
-
- # sherpa's streaming zipformer consumes arbitrary chunk sizes; 1280
- # samples (80 ms) matches the shared capture path.
- frame_length = 1280
-
- def __init__(self, cfg: Dict[str, Any]):
- import pm
-
- pm.ensure_import("wake-sherpa")
-
- import sherpa_onnx
- from sherpa_onnx import text2token
-
- sub = cfg.get("sherpa") if isinstance(cfg.get("sherpa"), dict) else {}
- model_dir = str(sub.get("model_dir") or "").strip()
- d = Path(model_dir) if model_dir else _ensure_sherpa_model()
- if not (d / "tokens.txt").exists():
- raise RuntimeError(f"sherpa KWS model not found at {d}")
-
- # Phrase set: this profile's own phrase, plus — when profile routing is
- # on — every other wake-enabled profile's phrase, so ONE listener can
- # wake any profile ("hey hermes" / "hey coder" / ...). display-name →
- # profile is kept for routing the match back.
- phrase = str(_get(cfg, "phrase") or "hey hermes").strip()
- own_profile = _active_profile_name()
- phrase_map: Dict[str, str] = {phrase: own_profile}
- if bool(cfg.get("profile_routing", True)):
- for prof, p in enrolled_profile_phrases().items():
- phrase_map.setdefault(p.strip(), prof)
-
- phrases = list(phrase_map)
- # Runtime tokenization of the arbitrary phrases — the open-vocab core.
- tokens = text2token(
- [p.upper() for p in phrases],
- tokens=str(d / "tokens.txt"),
- tokens_type="bpe",
- bpe_model=str(d / "bpe.model"),
- )
- import tempfile
-
- # sherpa keyword entries reject spaces in the @display-name; underscore
- # them and map display → profile for match routing.
- self._display_to_profile: Dict[str, str] = {}
- kw = tempfile.NamedTemporaryFile(
- mode="w", suffix=".txt", prefix="hermes-kws-", delete=False, encoding="utf-8"
- )
- for p, toks in zip(phrases, tokens):
- display = p.upper().replace(" ", "_")
- self._display_to_profile[display] = phrase_map[p]
- kw.write(" ".join(toks) + f" @{display}\n")
- kw.close()
- self._keywords_file = kw.name
- #: (phrase display name, profile) of the most recent fire, for routing.
- self.last_match: Optional[tuple[str, str]] = None
-
- # Map the shared 0..1 sensitivity onto sherpa's keywords_threshold.
- # 0.5 lands exactly on sherpa's recommended default (0.25); live TTS
- # matrix testing showed our previous stricter mapping (0.35) missed
- # ~12% of true positives while 0.25 held zero false fires.
- threshold = 0.05 + 0.4 * _sensitivity(cfg)
-
- def _model_file(pattern: str) -> str:
- hits = sorted(d.glob(pattern))
- if not hits:
- raise RuntimeError(f"sherpa KWS model file missing: {d}/{pattern}")
- return str(hits[0])
-
- self._spotter = sherpa_onnx.KeywordSpotter(
- tokens=str(d / "tokens.txt"),
- encoder=_model_file("encoder-*[!8].onnx"),
- decoder=_model_file("decoder-*[!8].onnx"),
- joiner=_model_file("joiner-*[!8].onnx"),
- keywords_file=self._keywords_file,
- keywords_threshold=threshold,
- num_threads=1,
- )
- self._stream = self._spotter.create_stream()
-
- def process(self, frame) -> bool:
- import numpy as np
-
- samples = np.asarray(frame, dtype=np.float32) / 32768.0
- self._stream.accept_waveform(SAMPLE_RATE, samples)
- fired = False
- while self._spotter.is_ready(self._stream):
- self._spotter.decode_stream(self._stream)
- result = self._spotter.get_result(self._stream)
- if result:
- fired = True
- display = str(result)
- self.last_match = (
- display.replace("_", " ").lower(),
- self._display_to_profile.get(display, ""),
- )
- # Reset decoder state so one utterance can't fire repeatedly.
- self._spotter.reset_stream(self._stream)
- return fired
-
- def reset(self) -> None:
- # Fresh stream drops all buffered audio/decoder state (pause → resume
- # must not re-fire on stale audio).
- try:
- self._stream = self._spotter.create_stream()
- except Exception:
- pass
-
- def close(self) -> None:
- try:
- os.unlink(self._keywords_file)
- except OSError:
- pass
-
-
-class _PorcupineEngine(_Engine):
- """Picovoice Porcupine — premium, on-device, needs an access key."""
-
- def __init__(self, cfg: Dict[str, Any]):
- import pm
-
- pm.ensure_import("wake-porcupine")
-
- import pvporcupine
-
- access_key = (os.getenv("PORCUPINE_ACCESS_KEY") or "").strip()
- if not access_key:
- raise RuntimeError(
- "Porcupine wake word requires PORCUPINE_ACCESS_KEY "
- "(get a free key at https://console.picovoice.ai)."
- )
-
- sub = cfg.get("porcupine") if isinstance(cfg.get("porcupine"), dict) else {}
- keyword = str(sub.get("keyword") or "jarvis").strip()
- # Porcupine's `sensitivities` runs the OPPOSITE way to our shared knob:
- # per Picovoice, higher = more true positives AND more false alarms
- # (looser). Our config contract is "higher = stricter" everywhere, so
- # invert it here to keep one consistent meaning across all engines.
- porcupine_sensitivity = 1.0 - _sensitivity(cfg)
-
- kwargs: Dict[str, Any] = {"access_key": access_key, "sensitivities": [porcupine_sensitivity]}
- if _looks_like_path(keyword):
- kwargs["keyword_paths"] = [keyword]
- else:
- kwargs["keywords"] = [keyword]
-
- self._porcupine = pvporcupine.create(**kwargs)
- self.frame_length = self._porcupine.frame_length
-
- def process(self, frame) -> bool:
- # pvporcupine wants a plain list/sequence of int16 samples.
- return self._porcupine.process(frame) >= 0
-
- def close(self) -> None:
- try:
- self._porcupine.delete()
- except Exception:
- pass
-
-
def _build_engine(cfg: Dict[str, Any]) -> _Engine:
provider = _provider(cfg)
if provider not in _PROVIDERS:
@@ -1047,7 +745,8 @@ def start_listening(on_wake: Callable[[], None], *, owner: object, config: Optio
_detector_file_lock = _acquire_machine_lock()
try:
cfg = config if config is not None else load_wake_word_config()
- _detector = WakeWordDetector(_build_engine(cfg), on_wake, on_failure=_detector_failed,
+ engine_cfg = {**cfg, "capture": "client" if external_audio else "local"}
+ _detector = WakeWordDetector(_build_engine(engine_cfg), on_wake, on_failure=_detector_failed,
input_device=_input_device(cfg), external_audio=external_audio)
_detector_owner = owner
_detector.start()
diff --git a/tools/wake_word_engines.py b/tools/wake_word_engines.py
index de2a759e3a6..b5ae7edd804 100644
--- a/tools/wake_word_engines.py
+++ b/tools/wake_word_engines.py
@@ -1,7 +1,15 @@
-"""Wake-word hotword engines (openWakeWord / sherpa-onnx KWS / Porcupine).
+"""Wake-word hotword engines (pyopen-wakeword / sherpa-onnx KWS / Porcupine).
All three run fully on-device. Config, platform probes and sensitivity accessors
live in :mod:`tools.wake_word`; engines read them lazily through that module (import cycle).
+This module is the SINGLE owner of the engine implementations — ``tools.wake_word``
+imports these classes and must not shadow them with copies.
+
+Dependency admission: constructing an engine ensures its ``wake-*`` extra. The
+``audio-io`` extra (sounddevice + numpy) is ensured only when the resolved
+capture mode is ``local`` — client capture (desktop/TUI streaming PCM via
+``wake.feed``) never needs, and must never trigger installation of, local
+audio libraries.
"""
from __future__ import annotations
@@ -20,14 +28,12 @@ def _ww():
return wake_word
-def _ensure_dep(feature: str) -> None:
- # The old lazy-deps specs bundled sounddevice + numpy with every engine;
- # the wake-* sub-extras deliberately don't (audio-io composes [voice]),
- # so ensure capture deps alongside the engine's own extra.
+def _ensure_dep(feature: str, cfg: Dict[str, Any]) -> None:
import pm
pm.ensure_import(feature)
- if not pm.available("audio-io"):
+ # Only local capture needs the microphone dependencies.
+ if _ww().resolve_capture_mode(cfg) == "local" and not pm.available("audio-io"):
pm.ensure_import("audio-io")
@@ -44,7 +50,7 @@ class _Engine:
last_match: Optional[tuple[str, str]] = None
def __init__(self, cfg: Dict[str, Any]):
- _ensure_dep(self.feature)
+ _ensure_dep(self.feature, cfg)
self._build(cfg, _sub(cfg, self.section), _ww())
def _build(self, cfg: Dict[str, Any], sub: Dict[str, Any], ww) -> None:
@@ -69,6 +75,71 @@ def _sub(cfg: Dict[str, Any], key: str) -> Dict[str, Any]:
return sub if isinstance(sub, dict) else {}
+class _OpenWakeWordEngine(_Engine):
+ """pyopen-wakeword — free, local hotword detection (TFLite via a bundled
+ tensorflowlite_c lib; no runtime download, no framework choice). Scores one
+ ~80 ms frame at a time; ``sensitivity`` IS the raw 0..1 threshold (higher =
+ stricter). A real utterance holds the score high across frames while a stray
+ phoneme spikes one, so ``confirmation_frames`` hits are required."""
+
+ feature, section = "wake-openwakeword", "openwakeword"
+
+ def _build(self, cfg, sub, ww) -> None:
+ from pyopen_wakeword import OpenWakeWord, OpenWakeWordFeatures
+
+ model_ref = str(sub.get("model") or ww._BUNDLED_MODEL_NAME).strip()
+ # Default (or explicit "hey_hermes") → the bundled model; a custom path
+ # is used as-is. pyopen-wakeword bundles the shared feature models
+ # (melspectrogram + embedding — byte-identical to the openWakeWord
+ # v0.5.1 files) inside its wheel, so there is no download_models step.
+ if model_ref.lower() in ww._BUNDLED_MODEL_ALIASES:
+ model_ref = ww._bundled_wakeword_path()
+ # pyopen-wakeword returns a 0..1 score per completed window; sensitivity
+ # IS the raw threshold a score must clear. Higher = stricter (fewer
+ # false fires). Default 0.6 sits above openWakeWord's permissive 0.5
+ # baseline, which let near-misses like "hey hor" through.
+ self._threshold = ww._sensitivity(cfg)
+ self._confirm_needed = ww._confirmation_frames(cfg)
+ self._confirm_streak = 0
+ self._features = OpenWakeWordFeatures.from_builtin()
+ self._model = OpenWakeWord.from_model(model_ref)
+ self._labels = [self._model.id]
+
+ def process(self, frame) -> bool:
+ # frame is a 1-D int16 ndarray; the features pipeline consumes int16
+ # bytes. process_streaming() yields embeddings as the window fills and
+ # the model yields one 0..1 score per completed window.
+ over = False
+ for emb in self._features.process_streaming(frame.tobytes()):
+ for score in self._model.process_streaming(emb):
+ if score >= self._threshold:
+ over = True
+ # Require N consecutive over-threshold frames: a real phrase holds the
+ # score high across frames, a stray ambient phoneme spikes just one.
+ if over:
+ self._confirm_streak += 1
+ if self._confirm_streak >= self._confirm_needed:
+ self._confirm_streak = 0
+ return True
+ return False
+ self._confirm_streak = 0
+ return False
+
+ def reset(self) -> None:
+ # Clears pyopen-wakeword's rolling feature/prediction buffer so stale
+ # audio captured before a pause can't re-fire the moment we resume.
+ self._confirm_streak = 0
+ with suppress(Exception):
+ self._features.reset()
+ self._model.reset()
+
+ def close(self) -> None:
+ self.reset()
+ with suppress(Exception):
+ self._features.close()
+ self._model.close()
+
+
# sherpa-onnx open-vocabulary KWS model: small streaming zipformer transducer (English,
# GigaSpeech), downloaded once under HERMES_HOME. Keywords are tokenized at RUNTIME.
_SHERPA_KWS_MODEL_URL = (