Skip to content

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.

revert: restore the custom-phrase wake to the pre-session state (0d141971)

Ruben Lütke9c78f59b6fbe
diff --git a/jarvis/plugins/stt/__init__.py b/jarvis/plugins/stt/__init__.py
index 737a26162e..f16162f06a 100644
--- a/jarvis/plugins/stt/__init__.py
+++ b/jarvis/plugins/stt/__init__.py
@@ -7,7 +7,6 @@ detector path keeps working when no cloud provider is registered.
"""
from __future__ import annotations
-from functools import lru_cache
from importlib import metadata as importlib_metadata
from typing import Any
@@ -122,30 +121,8 @@ def build_stt_from_config(stt_cfg: Any) -> Any:
)
-@lru_cache(maxsize=1)
-def _wake_cuda_available() -> bool:
- """True iff a CUDA device is usable by the CTranslate2 / faster-whisper backend.
-
- Cached — the device count is stable for the process lifetime. Any import or
- probe error is treated as "no CUDA", so a host without the GPU stack degrades
- to the cloud-first CPU default instead of raising. This is the capability
- probe behind the wake-Whisper GPU auto-upgrade (AP-21: gate on a capability,
- never on a provider/hardware name).
- """
- try:
- import ctranslate2
-
- return ctranslate2.get_cuda_device_count() > 0
- except Exception: # noqa: BLE001 - any failure means "treat as no GPU"
- return False
-
-
def build_wake_whisper(
- stt_cfg: Any,
- *,
- language: str | None = None,
- wake_phrase: str | None = None,
- cuda_available: bool | None = None,
+ stt_cfg: Any, *, language: str | None = None, wake_phrase: str | None = None
) -> Any:
"""Build the LOCAL wake-match / live-preview Whisper.
@@ -187,36 +164,11 @@ def build_wake_whisper(
"""
from jarvis.plugins.stt.fwhisper import FasterWhisperProvider
- model = getattr(stt_cfg, "wake_model", "base")
- device = getattr(stt_cfg, "wake_device", "cpu")
- compute = getattr(stt_cfg, "wake_compute_type", "int8")
-
- # Capability-gated GPU upgrade (forensic 2026-06-24). On the cloud-first CPU
- # defaults (base/cpu) AND a usable CUDA device, transcribe the wake on the GPU
- # with a fast MULTILINGUAL turbo model. Measured on the user's REAL "Hey Ruben"
- # clips: ~150 ms/window vs ~750 ms-1.4 s on base/cpu, AND it hears the German
- # proper noun reliably where base/cpu mis-hears it as "Ruhm"/"Tavis"/"Thomas"
- # (the strict matcher then never fires -> "the wake word doesn't work"). Only
- # the stt_match custom-phrase path on a GPU box is affected; the bundled
- # "Hey Jarvis"/openWakeWord path and every CPU/VPS host keep base/cpu. An
- # explicit wake_model/wake_device wins — only the untouched base/cpu pair
- # auto-upgrades. large-v3-turbo is MULTILINGUAL (NOT distil-large-v3, which is
- # English-only and would hallucinate German into "Thank you").
- if cuda_available is None:
- cuda_available = _wake_cuda_available()
- if model == "base" and device == "cpu" and cuda_available:
- model, device, compute = "large-v3-turbo", "cuda", "int8_float16"
- logger.info(
- "Wake-Whisper: CUDA device present -> GPU turbo "
- "(large-v3-turbo/cuda/int8_float16) for a fast multilingual "
- "custom-phrase wake (set wake_model explicitly to override)."
- )
-
bias = wake_phrase.strip() if wake_phrase and wake_phrase.strip() else None
return FasterWhisperProvider(
- model=model,
- device=device,
- compute_type=compute,
+ model=getattr(stt_cfg, "wake_model", "base"),
+ device=getattr(stt_cfg, "wake_device", "cpu"),
+ compute_type=getattr(stt_cfg, "wake_compute_type", "int8"),
language=language,
initial_prompt=bias,
)
diff --git a/jarvis/plugins/stt/fwhisper.py b/jarvis/plugins/stt/fwhisper.py
index ce49b21403..98328f5b48 100644
--- a/jarvis/plugins/stt/fwhisper.py
+++ b/jarvis/plugins/stt/fwhisper.py
@@ -134,40 +134,27 @@ class FasterWhisperProvider:
async def transcribe_pcm(
self, pcm_bytes: bytes, sample_rate: int = 16_000,
language: str | None = None,
- use_bias: bool = True,
) -> Transcript:
"""Direkter Weg für VAD-Output: int16-PCM-Bytes → Transcript.
`language` überschreibt per Call die Default-Sprache. Nützlich für den
Wake-Detector der auch bei STT-Default "auto" immer auf Deutsch hören soll.
-
- `use_bias=False` transcribes this ONE call WITHOUT the ``initial_prompt``
- bias, even on a biased instance. The wake backstop uses this for an
- unbiased confirmation pass: a strong biased model can hallucinate the
- primed wake phrase onto a different "Hey X", and the unbiased re-read
- reveals the actually-spoken phrase (forensic 2026-06-24).
"""
self._ensure_model()
audio_np = pcm_bytes_to_np(pcm_bytes)
- return await self._transcribe_np(
- audio_np, sample_rate, language=language, use_bias=use_bias
- )
+ return await self._transcribe_np(audio_np, sample_rate, language=language)
async def _transcribe_np(
self, audio_np: np.ndarray, sample_rate: int,
language: str | None = None,
- use_bias: bool = True,
) -> Transcript:
# faster-whisper ist synchron → in Thread shippen
import asyncio
- return await asyncio.to_thread(
- self._transcribe_sync, audio_np, sample_rate, language, use_bias
- )
+ return await asyncio.to_thread(self._transcribe_sync, audio_np, sample_rate, language)
def _transcribe_sync(
self, audio_np: np.ndarray, sample_rate: int,
language: str | None = None,
- use_bias: bool = True,
) -> Transcript:
assert self._model is not None
# faster-whisper akzeptiert np.ndarray float32 direkt wenn 16 kHz
@@ -177,9 +164,6 @@ class FasterWhisperProvider:
# Per-Call-Override hat Vorrang vor self._language
effective_lang = language if language is not None else self._language
- # Per-call bias override: an unbiased confirmation pass (use_bias=False)
- # drops the wake-phrase prompt so a hallucinated echo cannot survive it.
- effective_prompt = self._initial_prompt if use_bias else None
segments_iter, info = self._model.transcribe(
audio_np,
@@ -187,7 +171,7 @@ class FasterWhisperProvider:
beam_size=self._beam_size,
vad_filter=self._vad_filter,
condition_on_previous_text=False,
- initial_prompt=effective_prompt,
+ initial_prompt=self._initial_prompt,
no_speech_threshold=self._no_speech_threshold,
)
# segments_iter ist generator — durchiterieren materialisiert
diff --git a/jarvis/speech/rolling_whisper_wake.py b/jarvis/speech/rolling_whisper_wake.py
index 35f427def3..1bc82dca07 100644
--- a/jarvis/speech/rolling_whisper_wake.py
+++ b/jarvis/speech/rolling_whisper_wake.py
@@ -23,7 +23,6 @@ Parameter:
from __future__ import annotations
import asyncio
-import difflib
import logging
import os
import re
@@ -97,43 +96,6 @@ def _reliable_wake_transcript(
)
-def _wake_confirmed_unbiased(unbiased_text: str, name: str) -> bool:
- """Confirm a wake ONLY if an UNBIASED re-read POSITIVELY supports it.
-
- The ``initial_prompt="Hey Ruben"`` bias is needed for recall (a strong model
- still mishears the quiet proper noun without it) but makes that model
- hallucinate the primed phrase on two things: (1) quiet noise / silence, where
- Whisper's own artifact is "Vielen Dank."/"Ja." and the bias turns it into the
- wake; (2) a different spoken wake ("Hey Jarvis"). Forensic 2026-06-24: 14 of
- 16 live fires were such hallucinations — and an earlier "reject only on a
- competing name, else give the benefit of the doubt" rule let every silence
- artifact ("Vielen Dank", which names nothing) straight through.
-
- So require POSITIVE evidence in the unbiased read: a ``hey <name-ish>`` (or the
- name as a strong standalone token). A silence artifact has no "hey"; a
- competing wake has "hey" + the wrong name; pure garble has neither — all are
- rejected. Validated on the user's real fire WAVs: confirms 2/2 genuine
- "Hey Ruben"/"Hey Ruhm", rejects 14/14 hallucinations + "Hey Jarvis"/"Hey John".
- The 0.4 fuzzy floor admits the model's honest mishearings of the name
- ("Ruhm" 0.44, "Ruf" 0.5) but not jarvis(0.36)/john(0.18)/vielen(0.36).
- """
- u = unbiased_text.lower()
- name_l = name.lower().strip()
- # An unbiased "hey <name-ish>" -> a real wake. ``\W+`` (not just whitespace)
- # spans the comma Whisper often inserts: "Hey, Ruf." must still match.
- for mt in re.finditer(r"\b(?:hey|hi|hallo|ok|okay)\W+([a-zäöüß]{2,})", u):
- if difflib.SequenceMatcher(None, mt.group(1), name_l).ratio() >= 0.4:
- return True
- # Or the name as a strong standalone token (the unbiased read dropped "hey").
- if any(
- difflib.SequenceMatcher(None, t, name_l).ratio() >= 0.7
- for t in re.findall(r"[a-zäöüß]+", u)
- ):
- return True
- # No positive support (silence artifact / competing name / garble) -> reject.
- return False
-
-
class RollingWhisperWake:
"""Rolling-Window Wake-Detection per Whisper-Transkription."""
@@ -144,14 +106,7 @@ class RollingWhisperWake:
# ``.search(text)`` returning an object with ``.group(0)``.
pattern: Any = DEFAULT_PATTERN,
window_s: float = 1.8, # kürzer = weniger Stille-Anteil = höhere avg-RMS
- # 2026-06-24: the wake-reaction latency is dominated by the ~1.4s CPU
- # base-Whisper transcription itself (measured: beam_size has no effect —
- # the cost is the encoder pass over the ``window_s`` audio, not the
- # decoder). The poll interval is the only *artificial* idle gap on the
- # serialized ``sleep -> transcribe`` cadence, so keep it small. 0.3 -> 0.15
- # trims ~150ms off every cycle for free; it does not add load on a slow
- # box (there the transcription, not the sleep, paces the loop).
- poll_interval_s: float = 0.15, # schnellere Wake-Reaktion (transcribe-bound)
+ poll_interval_s: float = 0.3, # schnellere Wake-Reaktion
cooldown_s: float = 5.0, # längerer Cooldown → weniger Over-Triggering
sample_rate: int = 16_000,
# 2026-04-22 (3. Iteration): RMS/Peak-Gates zurueck auf niedrig. Die
@@ -177,15 +132,13 @@ class RollingWhisperWake:
# chunks: live, cleanly-heard custom-name wakes land at ~0.28-0.52 (real
# samples 2026-06-23: "Ruben." 0.318, "Hey Ruhm" 0.365, "Hey Ruben" 0.52).
# A 0.45 floor rejected EVERY genuine wake (142 rejects / 0 accepts in one
- # evening). That floor was built to suppress *prompt-bias* hallucinations.
- # The bias is ON again (2026-06-23: build_wake_whisper seeds the wake
- # phrase as ``initial_prompt`` — without it the base/cpu model heard "Hey
- # Ruben" as "Space"/"Ego" -> 2-13% recall, with it 83%). The hallucination
- # guard is therefore NOT the confidence floor but the strict pattern (a
- # random mis-hear does not match the specific adjacent "hey ruben") plus
- # the ``max_no_speech_prob``/RMS/peak gates. Keep only a low sanity floor
- # that still drops a near-zero-confidence transcript (regression: a
- # 0.2-confidence match must stay rejected).
+ # evening). That floor was built to suppress *prompt-bias* hallucinations,
+ # but the bias is now disabled (build_wake_whisper passes initial_prompt
+ # =None), so the pattern itself is the hallucination guard — a random
+ # mis-hear does not match the specific wake phrase — and the
+ # ``max_no_speech_prob`` gate below still rejects silence/noise. Keep only
+ # a low sanity floor that still drops a near-zero-confidence transcript
+ # (regression: a 0.2-confidence match must stay rejected).
min_wake_confidence: float = 0.28,
max_no_speech_prob: float = 0.6,
) -> None:
@@ -213,26 +166,6 @@ class RollingWhisperWake:
self._max_rms = 0.0
self._last_transcript = ""
self._last_heartbeat_t = time.time()
- # Windows dropped pre-Whisper by the rms/peak gate since the last
- # heartbeat. Surfaced in the heartbeat so a "wake never fires" report is
- # diagnosable: a high gated-out count means the mic is too quiet (the gate
- # eats real wakes), as opposed to a low count with many "rejected
- # unreliable" lines, which points at the model/confidence (forensic
- # 2026-06-24 — these quiet drops were previously a silent ``continue``).
- self._gated_out = 0
-
- def _should_confirm_unbiased(self) -> bool:
- """Run the unbiased hallucination-confirm pass for this STT instance?
-
- Only when (a) the STT is biased — no ``initial_prompt`` means nothing can
- hallucinate the primed phrase — AND (b) the re-read is cheap: a CUDA model
- re-transcribes a window in ~150 ms, whereas a CPU ``base`` model would add
- ~1 s to every wake fire. On the slow CPU path the weak recall also makes
- the bias hallucination rare, so the pass is not worth the latency there.
- """
- biased = bool(getattr(self._stt, "_initial_prompt", None))
- fast = getattr(self._stt, "_device", "cpu") == "cuda"
- return biased and fast
async def detect(
self, chunks: AsyncIterator[AudioChunk]
@@ -279,18 +212,16 @@ class RollingWhisperWake:
dbfs = 20.0 * np.log10(max(self._max_rms, 1e-12))
log.info(
"💓 wake-heartbeat: chunks=%d bytes=%dKB "
- "max-rms=%.4f (%.1f dBFS) gated-out=%d last-transcript=%r",
+ "max-rms=%.4f (%.1f dBFS) last-transcript=%r",
self._chunks_seen,
self._total_bytes // 1024,
self._max_rms,
dbfs,
- self._gated_out,
self._last_transcript[:80],
)
self._chunks_seen = 0
self._total_bytes = 0
self._max_rms = 0.0
- self._gated_out = 0
self._last_heartbeat_t = now_hb
# Ältere Samples rauswerfen wenn Buffer zu lang
@@ -334,14 +265,12 @@ class RollingWhisperWake:
# Lautstärke-Check (RMS) — kein Whisper-Call bei Stille
rms = float(np.sqrt(np.mean(audio_np * audio_np) + 1e-12))
if rms < self._min_rms:
- self._gated_out += 1 # observability (surfaced in heartbeat)
continue
# Peak-Gate: bei reinem Rauschen gar nicht erst Whisper bemühen
peak = float(np.max(np.abs(audio_np)))
if peak < self._min_peak:
# Kein Whisper-Call — zu leise für Sprache
- self._gated_out += 1 # observability (surfaced in heartbeat)
continue
# Whisper-Call mit Peak-Normalization (dynamischer Gain)
@@ -402,30 +331,6 @@ class RollingWhisperWake:
log.info("rolling-whisper: rms=%.4f text=%r", rms, text)
m = self._pattern.search(text)
if m:
- # Unbiased hallucination-confirm (forensic 2026-06-24): on the
- # fast GPU path a biased turbo can hallucinate the primed wake
- # phrase onto a different "Hey X" ("Hey Jarvis"/"Hey John" fired
- # as "Hey Ruben"). Re-read the SAME boosted window WITHOUT the
- # bias; drop the hit if the unbiased read names a different wake.
- if self._should_confirm_unbiased():
- try:
- unbiased = await self._stt.transcribe_pcm(
- pcm_bytes, language=self._language, use_bias=False
- )
- except Exception as exc: # noqa: BLE001
- log.warning("unbiased wake-confirm failed: %s", exc)
- unbiased = None
- if unbiased is not None:
- name = m.group(0).split()[-1] if m.group(0).split() else text
- if not _wake_confirmed_unbiased(
- (unbiased.text or "").strip(), name
- ):
- log.info(
- "rolling-whisper: rejected hallucinated wake — "
- "biased=%r unbiased=%r name=%r",
- text, (unbiased.text or "").strip(), name,
- )
- continue
last_trigger_t = now
yield m.group(0)
finally:
diff --git a/tests/unit/plugins/stt/test_wake_whisper_build.py b/tests/unit/plugins/stt/test_wake_whisper_build.py
index 1fa6655447..0ccc31cddd 100644
--- a/tests/unit/plugins/stt/test_wake_whisper_build.py
+++ b/tests/unit/plugins/stt/test_wake_whisper_build.py
@@ -32,9 +32,7 @@ def test_build_wake_whisper_uses_wake_fields_not_utterance_model() -> None:
wake_device="cpu",
wake_compute_type="int8",
)
- # cuda_available=False isolates this from the GPU auto-upgrade below — here we
- # only assert the wake instance does not inherit the heavy *utterance* fields.
- p = build_wake_whisper(cfg, cuda_available=False)
+ p = build_wake_whisper(cfg)
assert isinstance(p, FasterWhisperProvider)
# The wake instance must NOT inherit the heavy utterance model / cuda.
@@ -43,37 +41,8 @@ def test_build_wake_whisper_uses_wake_fields_not_utterance_model() -> None:
assert p._compute_type == "int8"
-def test_build_wake_whisper_upgrades_to_gpu_turbo_when_cuda_available() -> None:
- # Capability-gated speed+reliability upgrade (forensic 2026-06-24): on the
- # cloud-first CPU defaults (base/cpu) AND a CUDA device, the custom-phrase wake
- # transcribes on the GPU with a fast MULTILINGUAL turbo model. Measured on the
- # user's real "Hey Ruben" clips: ~150ms/window (vs ~750ms-1.4s on base/cpu) AND
- # it hears the German proper noun where base/cpu mis-hears it ("Ruhm"/"Tavis").
- p = build_wake_whisper(STTConfig(), cuda_available=True)
- assert p._model_name == "large-v3-turbo"
- assert p._device == "cuda"
- assert p._compute_type == "int8_float16"
-
-
-def test_build_wake_whisper_stays_cpu_base_without_cuda() -> None:
- # No GPU (VPS / fresh slim box): the cloud-first floor is untouched.
- p = build_wake_whisper(STTConfig(), cuda_available=False)
- assert p._model_name == "base"
- assert p._device == "cpu"
- assert p._compute_type == "int8"
-
-
-def test_build_wake_whisper_respects_explicit_non_default_over_gpu_auto() -> None:
- # An explicit wake_model wins over the auto-upgrade even on a CUDA box — the
- # upgrade only fires for the untouched base/cpu defaults.
- cfg = STTConfig(wake_model="small", wake_device="cpu", wake_compute_type="int8")
- p = build_wake_whisper(cfg, cuda_available=True)
- assert p._model_name == "small"
- assert p._device == "cpu"
-
-
def test_build_wake_whisper_passes_language() -> None:
- p = build_wake_whisper(STTConfig(), language="de", cuda_available=False)
+ p = build_wake_whisper(STTConfig(), language="de")
assert p._language == "de"
@@ -82,7 +51,7 @@ def test_build_wake_whisper_tolerates_missing_wake_fields() -> None:
class _Bare:
pass
- p = build_wake_whisper(_Bare(), cuda_available=False)
+ p = build_wake_whisper(_Bare())
assert p._model_name == "base"
assert p._device == "cpu"
assert p._compute_type == "int8"
@@ -99,17 +68,13 @@ def test_build_wake_whisper_biases_prompt_with_custom_phrase() -> None:
# no_speech_prob/RMS gates: false-wake stayed ~0% on real speech. So the bias
# is re-enabled on this path. It is scoped to the custom phrase only -- the
# OWW/"Hey Jarvis" paths pass no phrase and stay unbiased (test below).
- p = build_wake_whisper(
- STTConfig(), language="de", wake_phrase="Hey Ruben", cuda_available=False
- )
+ p = build_wake_whisper(STTConfig(), language="de", wake_phrase="Hey Ruben")
assert p._initial_prompt == "Hey Ruben"
def test_build_wake_whisper_default_has_no_prompt_bias() -> None:
- p = build_wake_whisper(STTConfig(), language="de", cuda_available=False)
+ p = build_wake_whisper(STTConfig(), language="de")
assert p._initial_prompt is None
- p_blank = build_wake_whisper(
- STTConfig(), language="de", wake_phrase=" ", cuda_available=False
- )
+ p_blank = build_wake_whisper(STTConfig(), language="de", wake_phrase=" ")
assert p_blank._initial_prompt is None
diff --git a/tests/unit/speech/test_rolling_whisper_wake.py b/tests/unit/speech/test_rolling_whisper_wake.py
index 5be9be71d4..c15ce70d2e 100644
--- a/tests/unit/speech/test_rolling_whisper_wake.py
+++ b/tests/unit/speech/test_rolling_whisper_wake.py
@@ -18,45 +18,7 @@ import asyncio
import numpy as np
from jarvis.core.protocols import AudioChunk, Transcript
-from jarvis.speech.rolling_whisper_wake import (
- RollingWhisperWake,
- _wake_confirmed_unbiased,
-)
-
-
-# --- unbiased hallucination-confirm (forensic 2026-06-24) ---------------------
-# A biased turbo can hallucinate the primed "Hey Ruben" onto a different "Hey X".
-# An unbiased re-read of the same window reveals the truth; reject only on a clear
-# competing wake-name so recall is preserved.
-
-
-def test_confirm_accepts_unbiased_read_that_still_says_the_name() -> None:
- assert _wake_confirmed_unbiased("Hey Ruben", "ruben") is True
-
-
-def test_confirm_accepts_mumbled_unbiased_near_name() -> None:
- # Real but quiet "Hey Ruben" the unbiased model heard as "Hey Ruf"/"Hey Ruhm"
- # (ratio 0.5 / 0.44 vs "ruben") must still confirm — hey + a name-ish token.
- assert _wake_confirmed_unbiased("Hey, Ruf.", "ruben") is True
- assert _wake_confirmed_unbiased("Hey Ruhm.", "ruben") is True
-
-
-def test_confirm_rejects_silence_artifact_hallucination() -> None:
- # The bias turns Whisper's quiet-audio artifact ("Vielen Dank."/"Ja.") into the
- # primed wake; the unbiased read positively supports nothing -> reject. This was
- # 14/16 of the live false fires the old benefit-of-the-doubt rule let through.
- assert _wake_confirmed_unbiased("Vielen Dank.", "ruben") is False
- assert _wake_confirmed_unbiased("Ja.", "ruben") is False
- assert _wake_confirmed_unbiased("Löffel.", "ruben") is False
- assert _wake_confirmed_unbiased("", "ruben") is False
-
-
-def test_confirm_rejects_unbiased_competing_hey_name() -> None:
- # "Hey Jarvis" / "Hey John" spoken -> biased hallucinates "Hey Ruben"; the
- # unbiased read names a different wake (wrong name after "hey") -> reject.
- assert _wake_confirmed_unbiased("Hey Jarvis", "ruben") is False
- assert _wake_confirmed_unbiased("Hey John.", "ruben") is False
- assert _wake_confirmed_unbiased("Hallo Computer", "ruben") is False
+from jarvis.speech.rolling_whisper_wake import RollingWhisperWake
def _loud_chunk(marker: int, n: int = 1600) -> AudioChunk:
@@ -122,31 +84,6 @@ class _PhraseSTT:
)
-class _BiasAwareSTT:
- """A biased CUDA wake-Whisper for the unbiased-confirm pass: returns
- ``biased_text`` on a normal (biased) call and ``unbiased_text`` when the
- detector re-reads with ``use_bias=False``."""
-
- def __init__(
- self, biased_text: str, unbiased_text: str, *, confidence: float = 0.9
- ) -> None:
- self._biased = biased_text
- self._unbiased = unbiased_text
- self._confidence = confidence
- self._initial_prompt = "Hey Ruben" # biased -> confirm is eligible
- self._device = "cuda" # fast -> confirm actually runs
-
- async def transcribe_pcm(
- self,
- pcm: bytes,
- sample_rate: int = 16000,
- language: str | None = None,
- use_bias: bool = True,
- ) -> Transcript:
- text = self._biased if use_bias else self._unbiased
- return Transcript(text=text, language="de", confidence=self._confidence)
-
-
async def _feed_until(src: asyncio.Queue, stop: asyncio.Event) -> None:
i = 0
while not stop.is_set():
@@ -393,179 +330,6 @@ async def test_detect_rejects_matching_high_no_speech_transcript() -> None:
pass
-async def test_detect_rejects_biased_hallucination_via_unbiased_confirm() -> None:
- """A biased turbo that prints 'hey ruben' for a spoken 'hey jarvis' is dropped.
-
- The unbiased re-read (use_bias=False) names the real wake -> reject. This is
- the false-wake the user hit (2026-06-24): "Hey Jarvis"/"Hey John" fired the
- "Hey Ruben" wake because the bias collapsed every "Hey X" onto the primed name.
- """
- import re
-
- wake = RollingWhisperWake(
- _BiasAwareSTT(biased_text="hey ruben", unbiased_text="hey jarvis"),
- pattern=re.compile(r"hey\W+ruben", re.IGNORECASE),
- poll_interval_s=0.01,
- cooldown_s=0.0,
- save_debug_wavs=False,
- min_rms=0.0,
- min_peak=0.0,
- )
-
- src: asyncio.Queue = asyncio.Queue()
- stop_feed = asyncio.Event()
-
- async def _iter():
- while True:
- chunk = await src.get()
- if chunk is None:
- return
- yield chunk
-
- async def _first_keyword() -> str:
- async for kw in wake.detect(_iter()):
- return kw
- return ""
-
- feeder = asyncio.create_task(_feed_until(src, stop_feed))
- try:
- try:
- kw = await asyncio.wait_for(_first_keyword(), timeout=0.7)
- except TimeoutError:
- kw = ""
- assert kw == "", f"hallucinated wake was not rejected: {kw!r}"
- finally:
- stop_feed.set()
- await src.put(None)
- feeder.cancel()
- try:
- await feeder
- except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
- pass
-
-
-async def test_detect_confirms_real_wake_when_unbiased_agrees() -> None:
- """A genuine 'hey ruben' the unbiased read also supports still fires."""
- import re
-
- wake = RollingWhisperWake(
- _BiasAwareSTT(biased_text="hey ruben", unbiased_text="hey ruben"),
- pattern=re.compile(r"hey\W+ruben", re.IGNORECASE),
- poll_interval_s=0.01,
- cooldown_s=0.0,
- save_debug_wavs=False,
- min_rms=0.0,
- min_peak=0.0,
- )
-
- src: asyncio.Queue = asyncio.Queue()
- stop_feed = asyncio.Event()
-
- async def _iter():
- while True:
- chunk = await src.get()
- if chunk is None:
- return
- yield chunk
-
- async def _first_keyword() -> str:
- async for kw in wake.detect(_iter()):
- return kw
- return ""
-
- feeder = asyncio.create_task(_feed_until(src, stop_feed))
- try:
- kw = await asyncio.wait_for(_first_keyword(), timeout=3.0)
- assert kw.lower() == "hey ruben"
- finally:
- stop_feed.set()
- await src.put(None)
- feeder.cancel()
- try:
- await feeder
- except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
- pass
-
-
-def test_default_poll_interval_is_responsive() -> None:
- """The poll cadence sets the idle gap before a fresh window is transcribed.
-
- Forensic 2026-06-24: the wake-reaction latency is dominated by the ~1.4s CPU
- base-Whisper transcription itself (beam_size has no measurable effect — the
- cost is the encoder pass over the window, not the decoder). The poll interval
- is the only *artificial* idle gap on the cadence, so keep it small. This locks
- in the faster default and guards against a regression back to the sluggish
- 0.3-0.5s cadence.
- """
- wake = RollingWhisperWake(_PhraseSTT("hi"), save_debug_wavs=False)
- assert wake._poll_interval_s <= 0.15
-
-
-async def test_gated_out_windows_are_counted_for_observability() -> None:
- """A too-quiet window is dropped *before* Whisper — and must be observable.
-
- Forensic 2026-06-24: the rms/peak gate skips the transcription with a bare
- ``continue`` and no log, so a user whose mic is too quiet sees "it never
- fires" with zero evidence in the log (both deep-dive passes flagged this as
- the blind spot). The drop must bump a counter the heartbeat can surface, so a
- future "doesn't fire" turn is diagnosable (high gated-out = mic too quiet vs.
- low gated-out + high rejects = model/confidence).
- """
- stt = _PhraseSTT("should not be called")
- wake = RollingWhisperWake(
- stt,
- pattern=_NeverMatch(),
- poll_interval_s=0.01,
- cooldown_s=0.0,
- save_debug_wavs=False,
- # Floors well above the (near-silent) quiet chunks below, so every poll
- # is gated out pre-Whisper.
- min_rms=0.5,
- min_peak=0.5,
- )
-
- src: asyncio.Queue = asyncio.Queue()
- stop_feed = asyncio.Event()
-
- async def _quiet_feeder() -> None:
- # ~ -60 dBFS noise: passes the >=1s buffer fill, fails the rms/peak gate.
- i = 0
- while not stop_feed.is_set():
- arr = np.full(1600, 30, dtype=np.int16) # tiny amplitude
- await src.put(
- AudioChunk(pcm=arr.tobytes(), sample_rate=16000, timestamp_ns=i)
- )
- i += 1
- await asyncio.sleep(0.002)
-
- async def _iter():
- while True:
- chunk = await src.get()
- if chunk is None:
- return
- yield chunk
-
- async def _drive() -> None:
- async for _kw in wake.detect(_iter()):
- pass
-
- feeder = asyncio.create_task(_quiet_feeder())
- detect_task = asyncio.create_task(_drive())
- try:
- await asyncio.sleep(0.4)
- assert wake._gated_out >= 1, "quiet windows were not counted as gated-out"
- finally:
- stop_feed.set()
- await src.put(None)
- feeder.cancel()
- detect_task.cancel()
- for t in (feeder, detect_task):
- try:
- await t
- except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
- pass
-
-
async def test_consumer_keeps_draining_while_transcription_is_in_flight() -> None:
stt = _GatedSTT()
wake = RollingWhisperWake(