Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(wake): multi-model vosk KWS - listen on every installed language model
Ruben Lütkee532bf1e229a
diff --git a/jarvis/plugins/wake/vosk_kws_provider.py b/jarvis/plugins/wake/vosk_kws_provider.pyindex f512582d39..4f9101114b 100644--- a/jarvis/plugins/wake/vosk_kws_provider.py+++ b/jarvis/plugins/wake/vosk_kws_provider.py@@ -56,7 +56,7 @@ import jsonimport loggingimport timefrom collections import deque-from collections.abc import AsyncIterator, Awaitable, Callable+from collections.abc import AsyncIterator, Awaitable, Callable, Sequencefrom concurrent.futures import ThreadPoolExecutorfrom difflib import SequenceMatcherfrom typing import Any@@ -150,6 +150,13 @@ class VoskKwsProvider:phrase: str,model_path: str,*,+ # ALL model dirs to listen on (primary first). None/empty = just+ # model_path. A phrase and the speaker language routinely diverge+ # ("Hey Jarvis": English name, German speaker — live forensic+ # 2026-07-11: the de model re-heard 'hey [unk]' and ate real wakes),+ # so every installed language model streams its own grammar and the+ # candidate is verified against the model that heard it.+ model_paths: Sequence[str] | None = None,keyword: str | None = None,sample_rate: int = 16_000,min_final_conf: float = _MIN_FINAL_CONF,@@ -170,6 +177,10 @@ class VoskKwsProvider:self._phrase = phrase.strip()self._keyword = keyword or "_".join(normalize_phrase_for_match(phrase)) or "wake"self._model_path = model_path+ paths = [p for p in (model_paths or ()) if p]+ if model_path and model_path not in paths:+ paths.insert(0, model_path)+ self._model_paths: list[str] = paths or [model_path]self._sample_rate = sample_rateself._min_final_conf = float(min_final_conf)self._confirm_ratio = float(confirm_ratio)@@ -189,7 +200,7 @@ class VoskKwsProvider:self._confirm_ratio = max(self._confirm_ratio, 0.62)self._target_peak = float(target_peak)self._max_gain = float(max_gain)- self._model: Any = None+ self._models: dict[str, Any] = {}self._grammar_words = [w for w in self._phrase.lower().split() if w]# Duck-typing parity with OpenWakeWordProvider: the pipeline's ready# log reads ``_keywords`` and ``_threshold`` off whatever detector is@@ -220,28 +231,45 @@ class VoskKwsProvider:# -- lifecycle ------------------------------------------------------------ def _ensure_model(self) -> Any:- if self._model is None:+ def _ensure_model(self, path: str | None = None) -> Any:+ key = path or self._model_path+ model = self._models.get(key)+ if model is None:from vosk import Model, SetLogLevel # lazy: keep base import lightSetLogLevel(-1)t0 = time.perf_counter()- self._model = Model(self._model_path)+ model = Model(key)+ self._models[key] = modellog.info("vosk-kws: model loaded in %.1f s (%s)",time.perf_counter() - t0,- self._model_path,+ key,)- return self._model+ return model- def _new_grammar_rec(self) -> Any:+ def _new_grammar_rec(self, path: str | None = None) -> Any:from vosk import KaldiRecognizergrammar = json.dumps([self._phrase.lower(), "[unk]"])- rec = KaldiRecognizer(self._ensure_model(), self._sample_rate, grammar)+ rec = KaldiRecognizer(self._ensure_model(path), self._sample_rate, grammar)rec.SetWords(True)return rec+ def _fresh_recs(self) -> dict[str, Any]:+ """One streaming grammar recognizer per LOADABLE model path.++ A corrupt/missing model dir must never brick the working ones —+ it is skipped with a warning and detection continues on the rest.+ """+ recs: dict[str, Any] = {}+ for path in self._model_paths:+ try:+ recs[path] = self._new_grammar_rec(path)+ except Exception as exc: # noqa: BLE001 — isolate a broken model+ log.warning("vosk-kws: model %s unusable (%s) — skipped.", path, exc)+ return recs+def _warmup_decode(self) -> None:"""Run ONE throwaway grammar + free decode pass so the FIRST realcandidate's verify does not also pay Kaldi's cold-start cost@@ -253,24 +281,32 @@ class VoskKwsProvider:real detect loop still builds fresh recognizers on the first genuinecandidate regardless of whether this succeeded."""- try:- from vosk import KaldiRecognizer-- silence = np.zeros(int(0.3 * self._sample_rate), dtype=np.int16).tobytes()- g = self._new_grammar_rec()- g.AcceptWaveform(silence)- g.FinalResult()- f = KaldiRecognizer(self._ensure_model(), self._sample_rate)- f.SetWords(True)- f.AcceptWaveform(silence)- f.FinalResult()- except Exception as exc: # noqa: BLE001 — warm-up must never break boot- log.debug("vosk-kws warm-up decode skipped: %s", exc)+ for path in self._model_paths:+ try:+ from vosk import KaldiRecognizer++ silence = np.zeros(+ int(0.3 * self._sample_rate), dtype=np.int16+ ).tobytes()+ g = self._new_grammar_rec(path)+ g.AcceptWaveform(silence)+ g.FinalResult()+ f = KaldiRecognizer(self._ensure_model(path), self._sample_rate)+ f.SetWords(True)+ f.AcceptWaveform(silence)+ f.FinalResult()+ except Exception as exc: # noqa: BLE001 — warm-up must never break boot+ log.debug("vosk-kws warm-up decode skipped (%s): %s", path, exc)async def start(self) -> None:- """Pre-load AND warm the model — moves Kaldi's cold-start decode cost- off the first real wake candidate and onto boot warm-up instead."""- await asyncio.to_thread(self._ensure_model)+ """Pre-load AND warm every model — moves Kaldi's cold-start decode+ cost off the first real wake candidate and onto boot warm-up instead."""+ for path in self._model_paths:+ try:+ await asyncio.to_thread(self._ensure_model, path)+ except Exception as exc: # noqa: BLE001 — a broken model must not+ # brick the working ones; _fresh_recs skips it too.+ log.warning("vosk-kws: model %s failed to load (%s).", path, exc)await asyncio.to_thread(self._warmup_decode)async def stop(self) -> None:@@ -281,7 +317,7 @@ class VoskKwsProvider:self._early_task.cancel()self._early_task = Noneawait self._notify_early(False)- self._model = None+ self._models.clear()self._ring.clear()self._ring_len = 0@@ -337,11 +373,13 @@ class VoskKwsProvider:# never break wake detection.log.debug("early-candidate listener failed: %s", exc)- async def _run_early_check(self, window: np.ndarray, gen: int) -> None:+ async def _run_early_check(+ self, window: np.ndarray, gen: int, model_path: str | None = None+ ) -> None:"""Mini-verify the truncated ring; show the candidate only if thepending candidate that spawned this check is still unresolved."""try:- ok = await asyncio.to_thread(self._early_check, window)+ ok = await asyncio.to_thread(self._early_check, window, model_path)except Exception as exc: # noqa: BLE001 — visual-only, never disruptlog.debug("early-candidate check errored: %s", exc)return@@ -385,19 +423,35 @@ class VoskKwsProvider:return (False, 1.0) # partials carry no conf; the confirm decidesreturn None- def _verify_candidate(self, window: np.ndarray) -> bool:- """Authoritative confirm — fails OPEN (never eat a real wake)."""- return self._verify_window(window, fail_open=True)+ def _verify_candidate(+ self, window: np.ndarray, model_path: str | None = None+ ) -> bool:+ """Authoritative confirm — fails OPEN (never eat a real wake).- def _early_check(self, window: np.ndarray) -> bool:+ ``model_path`` selects the model that HEARD the candidate; the verify+ must use the same acoustics that produced the hit, never a sibling.+ """+ return self._verify_window(window, fail_open=True, model_path=model_path)++ def _early_check(+ self, window: np.ndarray, model_path: str | None = None+ ) -> bool:"""Visual-only mini-verify on the truncated ring — fails CLOSED(never flash the bar on a broken verifier)."""try:- return self._verify_window(window, fail_open=False)+ return self._verify_window(+ window, fail_open=False, model_path=model_path+ )except Exception: # noqa: BLE001 — belt and braces for the UI pathreturn False- def _verify_window(self, window: np.ndarray, *, fail_open: bool) -> bool:+ def _verify_window(+ self,+ window: np.ndarray,+ *,+ fail_open: bool,+ model_path: str | None = None,+ ) -> bool:"""Three checks over the given window; ALL must pass before a fire.Why this shape (live forensic 2026-07-06, "Hey Ruben" fired on plain@@ -460,12 +514,14 @@ class VoskKwsProvider:# matrix 3 -> 7 with a last-1.8 s retry), because the grammar# happily forces any short speech snippet onto the phrase.def _grammar_pass() -> dict:- g = self._new_grammar_rec()+ g = self._new_grammar_rec(model_path)g.AcceptWaveform(pcm)return json.loads(g.FinalResult())def _free_pass() -> dict:- f = KaldiRecognizer(self._ensure_model(), self._sample_rate)+ f = KaldiRecognizer(+ self._ensure_model(model_path), self._sample_rate+ )f.SetWords(True)f.AcceptWaveform(pcm)return json.loads(f.FinalResult())@@ -550,14 +606,23 @@ class VoskKwsProvider:Only the keyword yielded after the full verify pass may cross into thepipeline or become visible in the overlay."""- await asyncio.to_thread(self._ensure_model)- rec = self._new_grammar_rec()+ for path in self._model_paths:+ try:+ await asyncio.to_thread(self._ensure_model, path)+ except Exception as exc: # noqa: BLE001 — skip a broken model+ log.warning("vosk-kws: model %s failed to load (%s).", path, exc)+ # One streaming grammar per installed model — a phrase whose language+ # differs from the speaker's still has a model that can spell it+ # (union recall measured +38% on the fixture corpus, 2026-07-11).+ recs = self._fresh_recs()last_fire_t = 0.0# Pending candidate: a PARTIAL hit waits for ``confirm_tail_s`` more# audio before the confirm pass so the free decoder sees the WHOLE# phrase, not a truncated one (E2E-measured recall trap). Finals skip- # the wait — their endpoint already passed.- pending: tuple[bool, float] | None = None+ # the wait — their endpoint already passed. ``hit_path`` pins the+ # model that heard the candidate: verify and early check must use the+ # same acoustics, never a sibling model.+ pending: tuple[bool, float, str] | None = Nonepending_tail = 0async for chunk in chunks:self._stat_chunks += 1@@ -565,26 +630,36 @@ class VoskKwsProvider:self._ring_push(pcm)if pending is not None:pending_tail += len(pcm)+ # Keep every model's stream fed during the tail wait so their+ # decode state stays aligned with the ring.+ for r in recs.values():+ self._grammar_hit(r, pcm)if pending_tail < self._confirm_tail_bytes:continue- is_final, conf = pending+ is_final, conf, hit_path = pendingpending = Noneelse:- hit = self._grammar_hit(rec, pcm)+ # Feed EVERY model; first hit wins the candidate slot.+ hit: tuple[bool, float] | None = None+ hit_path = ""+ for path, r in recs.items():+ h = self._grammar_hit(r, pcm)+ if h is not None and hit is None:+ hit, hit_path = h, pathif hit is None:continueis_final, conf = hitnow = time.time()if now - last_fire_t < self._cooldown_s:self._stat_suppressed_cooldown += 1- rec = self._new_grammar_rec()+ recs = self._fresh_recs()continueself._stat_candidates += 1if is_final and conf < self._min_final_conf:- rec = self._new_grammar_rec()+ recs = self._fresh_recs()continueif not is_final and self._confirm_tail_bytes > 0:- pending = (is_final, conf)+ pending = (is_final, conf, hit_path)pending_tail = 0# Visual-only early candidate: mini-verify the audio heard# SO FAR in a worker thread while the confirm tail keeps@@ -594,13 +669,31 @@ class VoskKwsProvider:self._pending_gen += 1self._early_task = asyncio.create_task(self._run_early_check(- self._ring_window(), self._pending_gen+ self._ring_window(), self._pending_gen, hit_path))continuenow = time.time()window = self._ring_window()- confirmed = await asyncio.to_thread(self._verify_candidate, window)+ confirmed = await asyncio.to_thread(+ self._verify_candidate, window, hit_path+ )+ fired_path = hit_path+ if not confirmed:+ # Sibling rescue: the model that HEARD the candidate could not+ # verify it, but the ring still holds the phrase — let every+ # other model try (union recall, measured +38%: 'Hey Jarvis'+ # de-spoken garbles on the de model yet verifies on en).+ # Fail-CLOSED via _early_check: an opportunistic rescue must+ # never fire off a broken sibling (the fail-open contract+ # protects only the primary confirm).+ for other in self._model_paths:+ if other == hit_path or other not in recs:+ continue+ if await asyncio.to_thread(self._early_check, window, other):+ confirmed = True+ fired_path = other+ breakif not confirmed:self._stat_suppressed_confirm += 1# Resolve the pending candidate: invalidate any in-flight@@ -611,7 +704,7 @@ class VoskKwsProvider:await self._early_taskself._early_task = Noneawait self._notify_early(False)- rec = self._new_grammar_rec()+ recs = self._fresh_recs()continue# Confirmed: let a still-running early check finish first (in# production it completed long ago — the tail wait dwarfs it) so@@ -626,12 +719,13 @@ class VoskKwsProvider:self._stat_fired += 1last_fire_t = nowlog.info(- "vosk-kws: WAKE fired for %r (%s candidate)",+ "vosk-kws: WAKE fired for %r (%s candidate, model %s)",self._phrase,"final" if is_final else "partial",+ fired_path,)yield self._keyword- rec = self._new_grammar_rec()+ recs = self._fresh_recs()def vosk_model_supports_phrase(model_path: str, phrase: str) -> bool:diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 72b9c3750a..89b831f2db 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -1140,6 +1140,7 @@ class SpeechPipeline:self._wake = VoskKwsProvider(phrase=wake_plan.phrase,model_path=wake_plan.vosk_model_path or "",+ model_paths=getattr(wake_plan, "vosk_model_paths", ()),keyword=wake_plan.oww_keyword,early_candidate_listener=self._vosk_early_candidate_listener,)@@ -1857,6 +1858,7 @@ class SpeechPipeline:self._wake = VoskKwsProvider(phrase=plan.phrase,model_path=getattr(plan, "vosk_model_path", None) or "",+ model_paths=getattr(plan, "vosk_model_paths", ()),keyword=plan.oww_keyword,early_candidate_listener=self._vosk_early_candidate_listener,)diff --git a/jarvis/speech/wake_constants.py b/jarvis/speech/wake_constants.pyindex e46b351825..821f6e80c6 100644--- a/jarvis/speech/wake_constants.py+++ b/jarvis/speech/wake_constants.py@@ -184,29 +184,32 @@ def _vosk_models_root() -> Path:return Path(base) / "wake_models" / "vosk"+def _vosk_model_dir(cand: Path) -> Path | None:+ """The extracted model dir inside a language folder, or None.++ A folder counts as a model when it carries Vosk's ``am/`` subdir or a+ ``conf/model.conf`` (top-level or one level down, so both an extracted+ ``vosk-model-small-de-0.15/`` inside the lang folder and a flattened+ layout resolve).+ """+ if (cand / "am").is_dir() or (cand / "conf" / "model.conf").is_file():+ return cand+ for sub in sorted(p for p in cand.iterdir() if p.is_dir()):+ if (sub / "am").is_dir() or (sub / "conf" / "model.conf").is_file():+ return sub+ return None++def resolve_vosk_model_path(language: str | None) -> str | None:"""Absolute path to an extracted Vosk model dir for ``language``, or None.``language`` is a BCP-47-ish code ("de", "de-DE", "auto", None). Aconcrete language looks up its own folder; ``auto``/None falls back tothe FIRST language folder present (a single-language install just works).- A folder counts as a model when it carries Vosk's ``am/`` subdir or a- ``conf/model.conf`` (top-level or one level down, so both an extracted- ``vosk-model-small-de-0.15/`` inside the lang folder and a flattened- layout resolve)."""root = _vosk_models_root()if not root.is_dir():return None-- def _model_dir(cand: Path) -> Path | None:- if (cand / "am").is_dir() or (cand / "conf" / "model.conf").is_file():- return cand- for sub in sorted(p for p in cand.iterdir() if p.is_dir()):- if (sub / "am").is_dir() or (sub / "conf" / "model.conf").is_file():- return sub- return None-lang = (language or "").strip().lower().split("-")[0]candidates: list[Path] = []if lang and lang != "auto":@@ -215,12 +218,38 @@ def resolve_vosk_model_path(language: str | None) -> str | None:candidates.extend(sorted(p for p in root.iterdir() if p.is_dir()))for cand in candidates:if cand.is_dir():- found = _model_dir(cand)+ found = _vosk_model_dir(cand)if found is not None:return str(found)return None+def resolve_vosk_model_paths(primary_language: str | None = None) -> list[str]:+ """Every installed Vosk model dir, primary language (if any) first.++ Why ALL models (live forensic 2026-07-11): a wake phrase and the speaker+ language routinely diverge — "Hey Jarvis" is an ENGLISH name spoken by a+ GERMAN speaker, so the language-matched de model garbles the name+ ("hey [unk]", real wakes eaten) while the installed en model spells it+ natively. Running the grammar over every installed model and letting+ whichever confirms fire covers both sides; the per-model verify keeps its+ calibrated precision gates. Order matters only for tie-breaking/logs —+ the primary (speaker-language) model leads.+ """+ root = _vosk_models_root()+ if not root.is_dir():+ return []+ out: list[str] = []+ primary = resolve_vosk_model_path(primary_language)+ if primary is not None:+ out.append(primary)+ for lang_dir in sorted(p for p in root.iterdir() if p.is_dir()):+ found = _vosk_model_dir(lang_dir)+ if found is not None and str(found) not in out:+ out.append(str(found))+ return out++__all__ = ["WAKE_ENGINES","DEFAULT_WAKE_PHRASE",@@ -232,4 +261,5 @@ __all__ = ["phrase_core_for_match","sound_fold","resolve_vosk_model_path",+ "resolve_vosk_model_paths",]diff --git a/jarvis/speech/wake_phrase.py b/jarvis/speech/wake_phrase.pyindex 42cb1f37c4..10e9f07526 100644--- a/jarvis/speech/wake_phrase.py+++ b/jarvis/speech/wake_phrase.py@@ -36,6 +36,7 @@ from jarvis.speech.wake_constants import (phrase_core,phrase_core_for_match,resolve_vosk_model_path,+ resolve_vosk_model_paths,sound_fold,)@@ -288,6 +289,13 @@ class WakeWordPlan:wake_available: bool = True# Extracted Vosk model directory for the vosk_kws engine (None otherwise).vosk_model_path: str | None = None+ # ALL installed Vosk model dirs, primary language first (vosk_kws only).+ # The provider streams a grammar per model and fires on whichever model's+ # verify confirms — a phrase and the speaker language routinely diverge+ # ("Hey Jarvis": English name, German speaker; live forensic 2026-07-11),+ # and the single language-matched model eats genuine wakes it cannot+ # spell. Empty tuple = fall back to the single vosk_model_path.+ vosk_model_paths: tuple[str, ...] = ()def _read(cfg: Any, name: str, default: Any) -> Any:@@ -443,6 +451,15 @@ def resolve_wake_plan(),verify_prefix=False, # the provider's sound confirm is built invosk_model_path=vosk_model,+ # Every installed model, primary first: the provider listens+ # on all of them so a phrase whose language differs from the+ # speaker's ("Hey Jarvis" de-spoken) still has a model that+ # can spell it. Verified per model — precision gates intact.+ vosk_model_paths=tuple(+ resolve_vosk_model_paths(+ lang_norm if lang_is_concrete else language+ )+ ),)# 3. Arbitrary phrase via local-Whisper transcript match.diff --git a/tests/unit/plugins/wake/test_vosk_kws_provider.py b/tests/unit/plugins/wake/test_vosk_kws_provider.pyindex 3869567802..5b87a9af58 100644--- a/tests/unit/plugins/wake/test_vosk_kws_provider.py+++ b/tests/unit/plugins/wake/test_vosk_kws_provider.py@@ -120,10 +120,13 @@ class _FakeModel:@pytest.fixture()def fake_vosk(monkeypatch):mod = types.ModuleType("vosk")- state = {"model": None}+ # "model" = the most recently built model (single-model tests);+ # "models" = every model by path (multi-model tests).+ state = {"model": None, "models": {}}def _model_factory(path): # noqa: ANN001state["model"] = _FakeModel(path)+ state["models"][path] = state["model"]return state["model"]mod.Model = _model_factory@@ -277,7 +280,7 @@ async def test_early_candidate_retracts_when_confirm_rejects("Hey Nova", model_path="fake", keyword="nova",early_candidate_listener=_listener,)- monkeypatch.setattr(p, "_early_check", lambda window: True)+ monkeypatch.setattr(p, "_early_check", lambda window, model_path=None: True)p._ensure_model()fake_vosk["model"].free_text = "das ist etwas ganz anderes" # i18n-allow: utterance under testfired = await _run_detect(p, [_chunk() for _ in range(12)])@@ -337,6 +340,48 @@ def test_free_words_outside_the_span_cannot_confirm(fake_vosk) -> None:assert p._verify_candidate(np.full(48000, 0.2, dtype=np.float32)) is False+async def test_multi_model_second_model_fires_when_first_is_deaf(fake_vosk) -> None:+ """Union recall (measured +38% on the fixture corpus, 2026-07-11): a+ phrase the primary language model cannot hear ("Hey Jarvis" on the de+ model → 'hey [unk]') must still fire through a sibling model that can.+ The verify runs against the model that HEARD the candidate.+ """+ p = VoskKwsProvider(+ "Hey Nova",+ model_path="deaf-model",+ model_paths=["deaf-model", "hearing-model"],+ keyword="nova",+ )+ p._ensure_model("deaf-model")+ p._ensure_model("hearing-model")+ fake_vosk["models"]["deaf-model"].fire_after = 10**9 # never hears+ fired = await _run_detect(p, [_chunk() for _ in range(12)])+ assert fired == ["nova"]+ assert p.stats()["fired"] == 1+++async def test_sibling_rescue_fires_when_primary_verify_rejects(fake_vosk) -> None:+ """First-hit-wins must not eat the union: when the model that heard the+ candidate cannot VERIFY it, the other models get to try over the same+ ring audio before the candidate is suppressed."""+ p = VoskKwsProvider(+ "Hey Nova",+ model_path="primary",+ model_paths=["primary", "sibling"],+ keyword="nova",+ )+ p._ensure_model("primary")+ p._ensure_model("sibling")+ # The primary hears the candidate but its free ear contradicts it; the+ # sibling's free ear confirms the phrase.+ fake_vosk["models"]["primary"].free_text = "das ist ganz anders" # i18n-allow: test utterance+ fake_vosk["models"]["sibling"].fire_after = 10**9 # never stage-1-hits+ fired = await _run_detect(p, [_chunk() for _ in range(12)])+ assert fired == ["nova"]+ assert p.stats()["fired"] == 1+ assert p.stats()["suppressed_confirm"] == 0++async def test_cooldown_suppresses_immediate_refire(fake_vosk) -> None:p = VoskKwsProvider("Hey Nova", model_path="fake", keyword="nova", cooldown_s=60.0)fired = await _run_detect(p, [_chunk() for _ in range(24)])