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(stt): run the transcript filter on every provider, not just OpenRouter
Ruben Lütke594320b456b5
diff --git a/jarvis/core/protocols.py b/jarvis/core/protocols.pyindex 53f4be3998..6c8ca6b839 100644--- a/jarvis/core/protocols.py+++ b/jarvis/core/protocols.py@@ -45,12 +45,28 @@ class AudioDevice:@dataclass(frozen=True, slots=True)class Transcript:- """STT result, optionally including segments and language information."""+ """STT result, optionally including segments and language information.++ ``text`` is what a consumer should normally read: providers run their+ payload through ``jarvis.plugins.stt.transcript_filter.clean_stt_text``+ first, which removes the artifacts a recognizer manufactures (decoder+ repetition loops, hesitation sounds, stutters, an outer quote pair, NFD+ umlauts).++ ``raw_text`` is what the recognizer actually returned, and it exists for+ the two callers that must NOT read an edited string: the dictation lane,+ whose promise is "these are my words" and which owns the user's filler+ switch, and wake verification, which has to judge the recognizer's own+ output. It defaults to empty, so a provider that does not set it costs+ those callers nothing — they fall back to ``text``.+ """text: str- language: str # "de", "en", "auto-detected" oder konkret- confidence: float # 0.0–1.0+ language: str # "de", "en", "auto-detected", or a concrete code+ confidence: float # 0.0-1.0is_partial: bool = Falsesegments: tuple[dict[str, Any], ...] = field(default_factory=tuple)+ #: The pre-filter transcript; empty when the provider did not filter.+ raw_text: str = ""# ----------------------------------------------------------------------diff --git a/jarvis/plugins/stt/fwhisper.py b/jarvis/plugins/stt/fwhisper.pyindex c32b144f16..5ba4652e2a 100644--- a/jarvis/plugins/stt/fwhisper.py+++ b/jarvis/plugins/stt/fwhisper.py@@ -704,12 +704,27 @@ class FasterWhisperProvider:else:confidence = 0.0+ # The cleanup filter runs here, on the joined text only. Two things it+ # deliberately does NOT touch:+ #+ # * ``seg_dicts`` keeps every segment exactly as decoded. Those carry+ # timings and per-segment probabilities for the flight recorder, and+ # re-aligning them to an edited string is not possible without+ # guessing where the edits landed.+ # * ``raw_text`` keeps the joined string as decoded, because this ONE+ # instance is shared with the rolling-whisper wake poll loop and the+ # dictation lane. Wake verification has to judge what the recognizer+ # actually emitted, and dictation owns the user's filler switch —+ # both read ``raw_text`` and are unaffected by anything below.+ from jarvis.plugins.stt.transcript_filter import clean_stt_text+return Transcript(- text=text,+ text=clean_stt_text(text, language=info.language),language=info.language,confidence=confidence,is_partial=False,segments=seg_dicts,+ raw_text=text,)async def stream_transcribe(diff --git a/jarvis/plugins/stt/gemini_api.py b/jarvis/plugins/stt/gemini_api.pyindex d0cf204fb5..063bd176c2 100644--- a/jarvis/plugins/stt/gemini_api.py+++ b/jarvis/plugins/stt/gemini_api.py@@ -104,6 +104,10 @@ class Transcript:confidence: floatis_partial: bool = Falsesegments: tuple[dict[str, Any], ...] = field(default_factory=tuple)+ #: What the model returned BEFORE the cleanup filter ran. Read by the two+ #: callers that must not get an edited string - the dictation lane (which+ #: owns the user's filler switch) and wake verification.+ raw_text: str = ""class GeminiSTT:@@ -368,21 +372,6 @@ def _wrap_pcm_as_wav(pcm: bytes, *, sample_rate: int, channels: int) -> bytes:return buf.getvalue()-def _clean_transcript(text: str) -> str:- """Light cleanup of generative preamble artifacts — never a content filter.-- A generative model occasionally wraps the transcript in matched quotes even- when told not to. Strip ONE matched pair of surrounding quotes. This is- word-agnostic and never inspects the transcript for any specific phrase- (AP-27): it only removes an outer quote pair, so recognized speech is- preserved verbatim.- """- cleaned = text.strip()- if len(cleaned) >= 2 and cleaned[0] == cleaned[-1] and cleaned[0] in {'"', "'"}:- cleaned = cleaned[1:-1].strip()- return cleaned--def _response_to_transcript(response: Any, language: str | None) -> Transcript:"""Parse a google-genai response into a Transcript.@@ -390,14 +379,29 @@ def _response_to_transcript(response: Any, language: str | None) -> Transcript:timings or confidence, so confidence is a plain presence signal (1.0 fornon-empty text, else 0.0) and segments stay empty — the same convention theOpenRouter plugin uses when segments are absent.++ The text is filtered on the way in. This plugin used to carry its own+ two-line version of that (strip one matched quote pair, which a generative+ model adds even when told not to); the shared filter does the same and adds+ the artifacts every recognizer produces — repetition loops, hesitation+ sounds, stutters, NFD umlauts. It stays word-agnostic: nothing is rejected+ for what it says (AP-27). The untouched string stays on ``raw_text``."""- text = _clean_transcript(str(getattr(response, "text", None) or ""))+ raw = str(getattr(response, "text", None) or "").strip()+ tag = language or "unknown"+ # Local import so the module top stays ``jarvis.*``-free (entry-point+ # purity), the same seam the error mapper already uses.+ from jarvis.plugins.stt.transcript_filter import clean_stt_text+return Transcript(- text=text,- language=language or "unknown",- confidence=1.0 if text else 0.0,+ text=clean_stt_text(raw, language=tag),+ language=tag,+ # Presence on the RAW text: a cleanup that emptied the string is a+ # filter defect, not silence.+ confidence=1.0 if raw else 0.0,is_partial=False,segments=(),+ raw_text=raw,)diff --git a/jarvis/plugins/stt/groq_api.py b/jarvis/plugins/stt/groq_api.pyindex 86acde60f9..92af27859a 100644--- a/jarvis/plugins/stt/groq_api.py+++ b/jarvis/plugins/stt/groq_api.py@@ -82,6 +82,10 @@ class Transcript:confidence: floatis_partial: bool = Falsesegments: tuple[dict[str, Any], ...] = field(default_factory=tuple)+ #: What the vendor returned BEFORE the cleanup filter ran. Read by the two+ #: callers that must not get an edited string - the dictation lane (which+ #: owns the user's filler switch) and wake verification.+ raw_text: str = ""class GroqWhisperAPI:@@ -315,8 +319,16 @@ def _wrap_pcm_as_wav(pcm: bytes, *, sample_rate: int, channels: int) -> bytes:def _payload_to_transcript(payload: dict[str, Any]) -> Transcript:- """Parse Groq's OpenAI-shaped verbose_json response into a Transcript."""- text = str(payload.get("text", "")).strip()+ """Parse Groq's OpenAI-shaped verbose_json response into a Transcript.++ The text is filtered on the way in (see+ :func:`jarvis.plugins.stt.transcript_filter.clean_stt_text`), which is the+ last point where the recognizer's own artifacts can be removed before every+ consumer downstream reads the string. The untouched payload text stays on+ ``raw_text``, and the per-segment texts are left exactly as delivered: they+ carry the timings the flight recorder needs and are never read as prose.+ """+ raw = str(payload.get("text", "")).strip()language = str(payload.get("language", "unknown")) or "unknown"segments_raw = payload.get("segments") or ()@@ -339,14 +351,21 @@ def _payload_to_transcript(payload: dict[str, Any]) -> Transcript:except OverflowError:confidence = 0.0else:- confidence = 1.0 if text else 0.0+ # Presence is judged on the RAW text: a cleanup that emptied the string+ # is a filter defect, and reporting 0.0 would call it silence instead.+ confidence = 1.0 if raw else 0.0++ # Local import, like the credential lookup and the error mapper: the module+ # top stays ``jarvis.*``-free (entry-point purity).+ from jarvis.plugins.stt.transcript_filter import clean_stt_textreturn Transcript(- text=text,+ text=clean_stt_text(raw, language=language),language=language,confidence=min(1.0, max(0.0, confidence)),is_partial=False,segments=seg_tuple,+ raw_text=raw,)diff --git a/jarvis/plugins/stt/openai_api.py b/jarvis/plugins/stt/openai_api.pyindex be145436be..acb22dbd37 100644--- a/jarvis/plugins/stt/openai_api.py+++ b/jarvis/plugins/stt/openai_api.py@@ -106,6 +106,10 @@ class Transcript:confidence: floatis_partial: bool = Falsesegments: tuple[dict[str, Any], ...] = field(default_factory=tuple)+ #: What the vendor returned BEFORE the cleanup filter ran. Read by the two+ #: callers that must not get an edited string - the dictation lane (which+ #: owns the user's filler switch) and wake verification.+ raw_text: str = ""class OpenAIWhisperAPI:@@ -402,8 +406,13 @@ def _payload_to_transcript(payload: dict[str, Any]) -> Transcript:from the mean segment ``avg_logprob`` (``exp`` of the average); otherwise itis a plain presence signal (1.0 for non-empty text, else 0.0) — the sameconvention the Groq plugin uses.++ The text is filtered on the way in (see+ :func:`jarvis.plugins.stt.transcript_filter.clean_stt_text`) and the+ untouched payload text stays on ``raw_text``. Per-segment texts are left as+ delivered: they carry timings, and nothing reads them as prose."""- text = str(payload.get("text", "")).strip()+ raw = str(payload.get("text", "")).strip()language = str(payload.get("language", "unknown")) or "unknown"segments_raw = payload.get("segments") or ()@@ -424,14 +433,20 @@ def _payload_to_transcript(payload: dict[str, Any]) -> Transcript:except OverflowError:confidence = 0.0else:- confidence = 1.0 if text else 0.0+ # Presence is judged on the RAW text: a cleanup that emptied the string+ # is a filter defect, and reporting 0.0 would call it silence instead.+ confidence = 1.0 if raw else 0.0++ # Local import (entry-point purity), same seam as the error mapper.+ from jarvis.plugins.stt.transcript_filter import clean_stt_textreturn Transcript(- text=text,+ text=clean_stt_text(raw, language=language),language=language,confidence=min(1.0, max(0.0, confidence)),is_partial=False,segments=seg_tuple,+ raw_text=raw,)diff --git a/jarvis/speech/rolling_whisper_wake.py b/jarvis/speech/rolling_whisper_wake.pyindex a044e39683..9163c78dea 100644--- a/jarvis/speech/rolling_whisper_wake.py+++ b/jarvis/speech/rolling_whisper_wake.py@@ -487,7 +487,14 @@ class RollingWhisperWake:exc,)return False- unbiased = (transcript.text or "").strip()+ # ``raw_text`` first: providers now clean their transcript, and wake+ # verification must judge what the recognizer EMITTED, not an edited+ # version of it. A cleaned string would also break the pairing with the+ # word-agnostic audio checks (energy at the match site, candidate+ # shape), which are measured against the raw decode (AP-27).+ unbiased = (+ getattr(transcript, "raw_text", "") or transcript.text or ""+ ).strip()if unbiased and STT_HALLUCINATION_RE.search(unbiased) is None:log.info("echo-confirm: unprimed ear heard %r — genuine wake", unbiased[:60]@@ -885,7 +892,11 @@ class RollingWhisperWake:)continue- text = transcript.text.strip()+ # See the note at the echo-confirm pass: wake reads the+ # recognizer's own output, never the cleaned one.+ text = (+ getattr(transcript, "raw_text", "") or transcript.text or ""+ ).strip()self._last_transcript = text# Watchdog: save the WAV so the user/I can review the recordingdiff --git a/tests/unit/plugins/stt/test_transcript_filter_parity.py b/tests/unit/plugins/stt/test_transcript_filter_parity.pynew file mode 100644index 0000000000..151b74590c--- /dev/null+++ b/tests/unit/plugins/stt/test_transcript_filter_parity.py@@ -0,0 +1,118 @@+"""Every STT provider filters its transcript, and none of them loses the raw one.++Two failure modes this pins, both of which are invisible until a user reports+"it behaves differently since I switched providers":++1. **Coverage.** A provider that skips the filter hands hesitation sounds,+ decoder loops and stutters to the intent router while its neighbours do not,+ so command accuracy silently depends on which key someone happens to have —+ the exact provider-shaped divergence AP-21/22 exist to prevent.+2. **The raw string.** Dictation and wake verification must both read what the+ recognizer actually emitted. A provider that filters without keeping+ ``raw_text`` turns the user's filler switch into a no-op (AP-31) and makes+ wake judge an edited transcript (AP-27).++The German fixtures are the speech under test (CLAUDE.md §1, category 4).+"""+from __future__ import annotations++import dataclasses+from types import SimpleNamespace++import pytest++from jarvis.plugins.stt import (+ gemini_api,+ groq_api,+ openai_api,+ openrouter_stt,+)++#: One payload carrying three artifact classes at once: an outer quote pair the+#: model added, a hesitation sound, and a decoder repetition loop.+DIRTY_TEXT = '"Um, turn on the light. Thank you. Thank you. Thank you."'+CLEAN_TEXT = "Turn on the light. Thank you."++#: Every provider module that turns a vendor payload into a Transcript.+PAYLOAD_PROVIDERS = (openrouter_stt, groq_api, openai_api)++#: Every provider module at all, including the local engine.+ALL_PROVIDER_MODULES = (openrouter_stt, groq_api, openai_api, gemini_api)+++ "module", PAYLOAD_PROVIDERS, ids=lambda m: m.__name__.rsplit(".", 1)[-1]+)+def test_a_payload_provider_cleans_its_text_and_keeps_the_raw_one(module) -> None:+ transcript = module._payload_to_transcript(+ {"text": DIRTY_TEXT, "language": "English"}+ )+ assert transcript.text == CLEAN_TEXT+ assert transcript.raw_text == DIRTY_TEXT+ # A filter that removed words must never read as "nothing was said".+ assert transcript.confidence > 0.0+++def test_gemini_cleans_its_response_and_keeps_the_raw_one() -> None:+ transcript = gemini_api._response_to_transcript(+ SimpleNamespace(text=DIRTY_TEXT), "en"+ )+ assert transcript.text == CLEAN_TEXT+ assert transcript.raw_text == DIRTY_TEXT+ assert transcript.confidence == 1.0+++async def test_the_local_engine_cleans_its_joined_text_and_keeps_the_raw_one() -> None:+ """faster-whisper joins segment texts; the join is what gets filtered.++ The per-segment dicts stay exactly as decoded — they carry timings and+ probabilities, and re-aligning them to an edited string would mean guessing+ where the edits landed.+ """+ from jarvis.plugins.stt.fwhisper import FasterWhisperProvider++ # i18n-allow: German speech under test (§1 list #4)+ pieces = ("Ähm, mach ", "das Licht an. ", "Danke. Danke. Danke.") # i18n-allow++ class _SegmentedModel:+ def transcribe(self, audio, **_kwargs): # noqa: ANN001, ANN003+ segments = [+ SimpleNamespace(+ start=float(i), end=float(i + 1), text=piece, avg_logprob=-0.2+ )+ for i, piece in enumerate(pieces)+ ]+ return iter(segments), SimpleNamespace(language="de")++ prov = FasterWhisperProvider(device="cpu", compute_type="int8")+ prov._model = _SegmentedModel() # noqa: SLF001 — skip the real model load++ transcript = await prov.transcribe_pcm(b"\x00\x00" * 16_000)++ assert transcript.text == "Mach das Licht an. Danke." # i18n-allow: fixture (§1 list #4)+ assert transcript.raw_text == "".join(pieces).strip()+ assert tuple(s["text"] for s in transcript.segments) == pieces+ assert transcript.confidence > 0.0+++ "module", ALL_PROVIDER_MODULES, ids=lambda m: m.__name__.rsplit(".", 1)[-1]+)+def test_every_provider_transcript_carries_an_optional_raw_text(module) -> None:+ """A new provider cannot ship a Transcript without the field and stay green.++ The default has to be empty rather than required: consumers construct empty+ Transcripts on silence and on an aborted call, and a required field would+ turn every one of those into a TypeError at the worst possible moment.+ """+ fields = {f.name: f for f in dataclasses.fields(module.Transcript)}+ assert "raw_text" in fields, f"{module.__name__} lost the raw transcript"+ assert fields["raw_text"].default == ""+++def test_the_shared_protocol_transcript_carries_it_too() -> None:+ """The local engine returns the protocol type, not a plugin-local copy."""+ from jarvis.core.protocols import Transcript as ProtocolTranscript++ fields = {f.name: f for f in dataclasses.fields(ProtocolTranscript)}+ assert fields["raw_text"].default == ""