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): clean an OpenRouter transcript before it leaves the provider
Ruben Lütke244f167fc735
diff --git a/jarvis/plugins/stt/openrouter_stt.py b/jarvis/plugins/stt/openrouter_stt.pyindex 3a698ed030..8108a7d57c 100644--- a/jarvis/plugins/stt/openrouter_stt.py+++ b/jarvis/plugins/stt/openrouter_stt.py@@ -102,6 +102,13 @@ class Transcript:Plugin code must not import from ``jarvis.*``; structural compatibility issufficient because ``STTProvider`` is a ``runtime_checkable`` Protocol andconsumers access the fields by name.++ ``raw_text`` is additive and optional: it carries what the gateway returned+ BEFORE the cleanup filter ran. Consumers that want the cleaned sentence keep+ reading ``text`` and never notice it; the one caller that must not get a+ cleaned string — the dictation lane, whose whole promise is "these are my+ words" and which owns a user switch for filler removal — reads it through a+ ``getattr`` default, so every other provider stays unchanged."""text: str@@ -109,6 +116,7 @@ class Transcript:confidence: floatis_partial: bool = Falsesegments: tuple[dict[str, Any], ...] = field(default_factory=tuple)+ raw_text: str = ""class OpenRouterSTT:@@ -434,15 +442,33 @@ def _payload_to_transcript(payload: dict[str, Any]) -> Transcript:no per-segment timings or confidence, so confidence is a plain presencesignal (1.0 when non-empty text, else 0.0) and segments stay empty — thesame convention the Groq plugin uses when segments are absent.++ The text is run through :func:`jarvis.plugins.stt.transcript_filter.clean_stt_text`+ on the way in, which is the last point where the gateway's own artifacts —+ a decoder repetition loop, a hesitation sound, a stutter, an outer quote+ pair, NFD umlauts — can be removed before every consumer downstream starts+ reading the string. The untouched payload text stays on ``raw_text``.++ Confidence is computed from the RAW text, not the cleaned one. The two only+ diverge when cleanup emptied the string, and that is a cleanup defect, not+ a silent utterance — reporting 0.0 there would hand the pipeline a "nothing+ was said" verdict about audio that contained speech."""- text = str(payload.get("text", "")).strip()+ raw = str(payload.get("text", "")).strip()language = str(payload.get("language", "") or "unknown") or "unknown"+ # Local import: the module top must stay ``jarvis.*``-free (entry-point+ # purity), the same lazy seam the credential lookup and the error mapper+ # already use.+ from jarvis.plugins.stt.transcript_filter import clean_stt_text++ text = clean_stt_text(raw, language=language)return Transcript(text=text,language=language,- confidence=1.0 if text else 0.0,+ confidence=1.0 if raw else 0.0,is_partial=False,segments=(),+ raw_text=raw,)diff --git a/jarvis/plugins/stt/transcript_filter.py b/jarvis/plugins/stt/transcript_filter.pynew file mode 100644index 0000000000..fbeb5d6571--- /dev/null+++ b/jarvis/plugins/stt/transcript_filter.py@@ -0,0 +1,373 @@+"""Transcript cleanup for cloud STT payloads — artifacts, loops, filler, format.++What this is for+----------------+A cloud transcription model returns what it heard, artifacts included: a+repetition loop that repeats one phrase forty times, a hesitation sound, a+stutter, a stray quote pair the model wrapped around its own answer, and+whatever spacing the segmenting produced. Everything downstream — the intent+router, the command gates, the readbacks — reads that string. This module is+the one place where it is turned into the sentence the user actually spoke,+before a provider wraps it in a ``Transcript``.++What it deliberately does NOT do+--------------------------------+* **No LLM call, ever.** Same discipline as ``scrub_for_voice`` (AP-11) and+ ``jarvis.dictation.cleanup``: a second model pass can rewrite and "improve",+ and the user has no way to tell. Regex only — wrong in a way you can read.+* **No content gate.** Nothing here inspects the transcript for a specific+ phrase in order to reject it. A wake word is never verified on transcript+ CONTENT (AP-27), and a cleanup that deletes a sentence because of what it+ says would be that defect wearing a different hat. Every rule below either+ repairs a mechanical artifact or removes a token from a curated list.+* **No second filler table.** The hesitation-sound lists and the punctuation+ repair live in :mod:`jarvis.dictation.cleanup` and are reused from there.+ A copy would drift from the original the first time either is touched, and+ those tables carry hard-won exclusions (see its ``FILLER_WORDS`` docstring:+ English "er" is a top-frequency GERMAN pronoun, and one wrong language tag+ turned that into silent deletion of content words).++Order matters+-------------+1. **Character normalisation.** NFC, because a provider that answers in NFD+ spells an umlaut as two codepoints and every umlaut-bearing filler rule+ then silently misses. Zero-width and control characters go; NBSP becomes a+ normal space.+2. **Wrapping quotes.** One matched outer pair, nothing else.+3. **Repetition loops.** The best-known failure mode of the Whisper family:+ the decoder latches onto a phrase and emits it until the segment ends.+4. **Hyphen stutters.** "w- was" is one word spoken twice, not two words.+5. **Phonetic fixes.** A short, language-tagged table with a strict admission+ rule — see :data:`PHONETIC_FIXES`.+6. **Filler removal**, delegated, with its destruction ceiling intact.+7. **Punctuation repair**, delegated, and idempotent.++Fail-open everywhere: any rule that raises returns the text it was given. A+cleanup that eats an utterance is worse than an utterance that reads slightly+rough.+"""+from __future__ import annotations++import logging+import re+import unicodedata++log = logging.getLogger(__name__)++# ---------------------------------------------------------------------------+# Character normalisation+# ---------------------------------------------------------------------------++#: Zero-width and byte-order marks. They survive a ``strip()``, break word+#: boundaries in every rule below, and are invisible in a bug report — which is+#: why they are spelled as escapes here and never as the characters themselves.+_ZERO_WIDTH_RE = re.compile("[\u200b-\u200f\u2060\ufeff]")+#: Non-breaking / narrow / figure spaces — a space everywhere except to a regex.+_NBSP_RE = re.compile("[\u00a0\u2007\u202f]")+#: C0/C1 controls except the newline and tab we handle explicitly.+_CONTROL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]")+#: Horizontal whitespace runs (never touches a newline — a provider that+#: returns paragraphs keeps them).+_HORIZONTAL_WS_RE = re.compile(r"[^\S\n]+")++#: Quote characters a generative transcription model wraps its answer in.+#: Only a MATCHED outer pair is removed, so a quotation the speaker actually+#: dictated survives.+_QUOTE_PAIRS: tuple[tuple[str, str], ...] = (+ ('"', '"'),+ ("'", "'"),+ ("“", "”"), # “ ”+ ("„", "“"), # „ “ (German book quotes)+ ("«", "»"), # « »+ ("‘", "’"), # ‘ ’+)++# ---------------------------------------------------------------------------+# Repetition loops and stutters+# ---------------------------------------------------------------------------++#: One spoken word: a letter-initial token that may carry an apostrophe or an+#: internal hyphen ("don't", "e-mail"). Digits are excluded on purpose — a+#: repeated number ("zwei zwei zwei") is usually dictated data, not a loop.+#:+#: The trailing group admits an INTERNAL dot that a letter immediately follows+#: ("Amara.org", "z.B."). It is load-bearing rather than cosmetic: the single+#: most common decoder loop in this repo's history is a subtitle credit ending+#: in a domain name, and without this the phrase never matched itself, so the+#: rule quietly did nothing on the exact case it exists for. A dot that+#: whitespace follows is still a sentence end and stays outside the token.+_WORD_PATTERN = r"[^\W\d_][\w'’\-]*(?:\.[^\W\d_][\w'’\-]*)*"+#: What separates two repetitions: whitespace, optionally with the punctuation+#: the model emitted between them ("das, das, das", "Danke. Danke. Danke.").+_REPEAT_SEP = r"[ \t]*[,;:.!?]{0,2}[ \t]+"+#: Word boundaries spelled out — ``\b`` misbehaves next to non-ASCII letters.+_NOT_WORD_BEFORE = r"(?<![^\W\d_])"+_NOT_WORD_AFTER = r"(?![^\W\d_])"++#: Inside a MULTI-word phrase a pure number counts as one of the words. On its+#: own it does not (see :data:`_WORD_LOOP_RE`): a repeated bare number is often+#: dictated data — a phone number, a house number said twice for clarity —+#: while a whole phrase that happens to contain a year is never anything but a+#: loop. The one this repo has actually seen, verbatim:+#: "Untertitelung des ZDF für funk, 2017" # i18n-allow: STT boilerplate+_PHRASE_PATTERN = rf"(?:{_WORD_PATTERN}|\d+(?:[.,:]\d+)*)"++#: A phrase of 2–8 words repeated at least three times in a row. Three, not+#: two: a doubled word is ordinary speech in every language this ships in+#: (English "had had"; German "dass das das") # i18n-allow: quoted input+#: while the same span three times over is always a decoder loop.+#:+#: The upper span is set by the artifact, not by taste: the subtitle credits+#: Whisper falls into run six to eight words, so a shorter window would leave+#: the most common loop in the wild unmatched. Cost measured at ~2 ms on 4 KB+#: of text that contains no repetition at all, which is noise next to the+#: network call that produced the transcript.+_PHRASE_LOOP_RE = re.compile(+ _NOT_WORD_BEFORE+ + rf"((?:{_PHRASE_PATTERN}{_REPEAT_SEP}){{1,7}}{_PHRASE_PATTERN})"+ + rf"(?:{_REPEAT_SEP}\1){{2,}}"+ + _NOT_WORD_AFTER,+ re.IGNORECASE | re.UNICODE,+)+#: The same rule for a single word ("ja ja ja ja"), letters only.+_WORD_LOOP_RE = re.compile(+ _NOT_WORD_BEFORE + rf"({_WORD_PATTERN})(?:{_REPEAT_SEP}\1){{2,}}" + _NOT_WORD_AFTER,+ re.IGNORECASE | re.UNICODE,+)++#: An aborted syllable in front of the word it was aborted for: "w- was",+#: "ge- gehen". The fragment is capped at four characters, which is what keeps+#: the rule off a German suspended hyphen ("Vor- und Nachteile" is safe because+#: "und" does not start with "Vor"; "Software- und ..." is safe because the+#: fragment is too long to qualify at all). # i18n-allow: quoted German example+_HYPHEN_STUTTER_RE = re.compile(+ _NOT_WORD_BEFORE + r"([^\W\d_]{1,4})[-–][ \t]+(?=\1)",+ re.IGNORECASE | re.UNICODE,+)++_WORD_RE = re.compile(r"\w+", re.UNICODE)++# ---------------------------------------------------------------------------+# Phonetic fixes+# ---------------------------------------------------------------------------++# i18n-allow: the table below is speech-recognition vocabulary — the literal+# tokens a matcher must contain to recognise a mis-transcription. Matching+# data, not prose (CLAUDE.md §1, category 3).++#: Known mis-transcriptions, per language. Replacement is whole-word and+#: case-insensitive; the replacement inherits nothing from the source casing.+#:+#: ADMISSION RULE, and it is strict: an entry qualifies ONLY if the source is+#: **not a word in any language this project serves**. The language tag comes+#: from the provider and is regularly wrong — a cloud Whisper endpoint answering+#: "English" for German speech is a documented defect in this repo — so a source+#: token that means something somewhere will eventually be replaced inside a+#: sentence that was perfectly correct, and nothing will report it. That rules+#: out the obvious candidates: "auffliegen" is real German (to be found out),+#: "Gitter" is real German (a grid), so neither belongs here even though both+#: are documented mis-hearings of something else. "aufflegen" (doubled "f")+#: is a word in no language and is only ever the command "auflegen"+#: mis-transcribed on a low-confidence utterance (live 2026-06-09, see+#: ``jarvis/speech/hangup.py``).+#:+#: This table stays SHORT by design. The scalable path for "the recognizer keeps+#: getting MY word wrong" is the user's own STT dictionary+#: (``jarvis.speech.stt_dictionary``), which is editable in the app, applies to+#: every provider, and cannot poison anyone else's transcripts.+PHONETIC_FIXES: dict[str, tuple[tuple[str, str], ...]] = {+ "de": (+ ("aufflegen", "auflegen"),+ ("auffleg", "aufleg"),+ ),+ "en": (),+ "es": (),+}+++def _compile_phonetic(language: str) -> tuple[tuple[re.Pattern[str], str], ...]:+ """Whole-word patterns for one language, longest source first."""+ pairs = sorted(PHONETIC_FIXES[language], key=lambda p: len(p[0]), reverse=True)+ return tuple(+ (+ re.compile(+ _NOT_WORD_BEFORE + re.escape(source) + _NOT_WORD_AFTER,+ re.IGNORECASE | re.UNICODE,+ ),+ target,+ )+ for source, target in pairs+ )+++_PHONETIC_CACHE: dict[str, tuple[tuple[re.Pattern[str], str], ...]] = {+ lang: _compile_phonetic(lang) for lang in PHONETIC_FIXES+}+++# ---------------------------------------------------------------------------+# Steps+# ---------------------------------------------------------------------------+++def normalize_characters(text: str) -> str:+ """NFC, no invisibles, plain spaces. The precondition for every other rule.++ Composed form matters more than it looks: a provider answering in NFD+ spells an umlaut as a plain letter plus a combining mark, so a German+ filler rule matching the composed spelling finds nothing and reports a+ clean no-op.+ """+ out = unicodedata.normalize("NFC", text)+ out = _ZERO_WIDTH_RE.sub("", out)+ out = _NBSP_RE.sub(" ", out)+ out = _CONTROL_RE.sub("", out)+ out = out.replace("\r\n", "\n").replace("\r", "\n")+ out = _HORIZONTAL_WS_RE.sub(" ", out)+ return out.strip()+++def strip_wrapping_quotes(text: str) -> str:+ """Remove ONE matched pair of quotes the model wrapped the answer in.++ Word-agnostic (AP-27): it looks at the first and last character and never+ at what is between them. Only one pair, so a transcript that legitimately+ begins and ends on a quoted phrase keeps its inner quotes.+ """+ out = text.strip()+ if len(out) < 2:+ return out+ for opening, closing in _QUOTE_PAIRS:+ if out[0] == opening and out[-1] == closing:+ return out[1:-1].strip()+ return out+++def collapse_repetitions(text: str) -> str:+ """Collapse a decoder loop: 3+ identical repetitions in a row become one.++ Phrases first, then single words, so a looping phrase is not shredded into+ per-word decisions.++ No destruction ceiling here, and that is deliberate: a real loop IS the+ majority of the string it appears in ("Untertitel von Amara.org" forty+ times over), so a ceiling would refuse exactly the case the rule exists+ for. The safety comes from the threshold instead — three identical+ repetitions with nothing between them do not occur in dictated speech.+ """+ out = _PHRASE_LOOP_RE.sub(r"\1", text)+ return _WORD_LOOP_RE.sub(r"\1", out)+++def repair_stutters(text: str) -> str:+ """Drop an aborted syllable that the completed word follows ("w- was")."""+ return _HYPHEN_STUTTER_RE.sub("", text)+++def apply_phonetic_fixes(text: str, language: str | None) -> str:+ """Apply the curated mis-transcription table for ``language``.++ An unresolved or unlisted language is a no-op — the same discipline the+ filler tables use, and for the same reason: applying one language's rules+ to another's speech is how a correct sentence gets damaged.+ """+ if not language:+ return text+ rules = _PHONETIC_CACHE.get(language)+ if not rules:+ return text+ out = text+ for pattern, target in rules:+ out = pattern.sub(target, out)+ return out+++def _delegated_cleanup(+ text: str, *, language: str | None, remove_fillers: bool+) -> tuple[str, str]:+ """Filler removal + punctuation repair from :mod:`jarvis.dictation.cleanup`.++ Returns ``(text, reason)`` where ``reason`` is the cleanup module's own+ verdict (``""`` when it applied, ``no_rules`` / ``ceiling`` / ``disabled``+ otherwise), so a caller can log WHY nothing was removed.++ The import is local, not module-level: this file is reached from an+ entry-point plugin, which must stay ``jarvis.*``-free at import time, and+ nothing here may land on the boot critical path (AP-26). ``cleanup`` itself+ imports only ``re`` and ``dataclasses``, so the call is cheap.+ """+ try:+ from jarvis.dictation.cleanup import clean_transcript, tidy_transcript+ except Exception as exc: # noqa: BLE001 — a missing table is not a lost turn+ log.debug("Transcript cleanup tables unavailable (%s); skipping.", exc)+ return text, "unavailable"++ outcome = clean_transcript(+ text, language=language, remove_fillers=remove_fillers+ )+ return tidy_transcript(outcome.text), outcome.reason+++def clean_stt_text(+ text: str,+ *,+ language: str | None = None,+ remove_fillers: bool = True,+) -> str:+ """Turn a raw STT payload string into the sentence that was spoken.++ ``language`` is whatever the provider reported; both an ISO code and the+ English language name are understood, and an unknown one simply narrows the+ work to the language-independent repairs. Never raises: on any failure the+ input is returned unchanged.+ """+ raw = text or ""+ if not raw.strip():+ return raw++ try:+ out = normalize_characters(raw)+ out = strip_wrapping_quotes(out)+ out = collapse_repetitions(out)+ out = repair_stutters(out)++ # One resolved language for the two rule sets that need one, taken from+ # the cleanup module so "German" / "de-DE" / "de" mean the same thing+ # here as they do there.+ lang: str | None = None+ try:+ from jarvis.dictation.cleanup import normalize_language++ lang = normalize_language(language)+ except Exception as exc: # noqa: BLE001 — degrade to the neutral rules+ log.debug("Language normalisation unavailable (%s).", exc)++ out = apply_phonetic_fixes(out, lang)+ out, reason = _delegated_cleanup(+ out, language=lang, remove_fillers=remove_fillers+ )++ # A cleanup that leaves no words behind is a bug in the rules, never a+ # valid result — hand back what the provider said.+ if not _WORD_RE.search(out) and _WORD_RE.search(raw):+ log.warning(+ "Transcript cleanup emptied a non-empty transcript; using the raw text."+ )+ return raw.strip()+ if reason not in ("", "unavailable"):+ log.debug("Filler removal skipped (%s).", reason)+ return out+ except Exception: # noqa: BLE001 — never lose an utterance to a cleanup bug+ log.warning("Transcript cleanup failed; using the raw text.", exc_info=True)+ return raw.strip()+++__all__ = [+ "PHONETIC_FIXES",+ "apply_phonetic_fixes",+ "clean_stt_text",+ "collapse_repetitions",+ "normalize_characters",+ "repair_stutters",+ "strip_wrapping_quotes",+]diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 8d9d7275a2..208432caaf 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -9115,7 +9115,21 @@ class SpeechPipeline:inference_active.clear()stt_error = Nonestt_error_detail = ""- text = (getattr(transcript, "text", "") or "").strip()+ # ``raw_text`` when the provider offers it, ``text`` otherwise. A+ # provider may now clean its own transcript (filler sounds, decoder+ # loops, stutters) before handing it over, which is right for a+ # voice command and wrong here: this lane owns a user switch for+ # filler removal, runs its own cleanup right after with the+ # language the USER pinned, and stores the untouched string in the+ # dictation history so a person can see what was changed. Reading+ # the cleaned string would make that switch a no-op nobody could+ # observe (AP-31) and would put an already-edited sentence in the+ # column labelled "raw". Providers without the field are unchanged.+ text = (+ getattr(transcript, "raw_text", "")+ or getattr(transcript, "text", "")+ or ""+ ).strip()lang = str(getattr(transcript, "language", "") or "")return text, lang, True, Nonediff --git a/jarvis/speech/stt_dictionary.py b/jarvis/speech/stt_dictionary.pyindex 38c5842da5..4471701548 100644--- a/jarvis/speech/stt_dictionary.py+++ b/jarvis/speech/stt_dictionary.py@@ -501,13 +501,27 @@ class DictionaryCorrectingSTT:text = getattr(transcript, "text", None)if not text:return transcript- corrected = get_corrector(self._store).correct(text)- if corrected == text:+ corrector = get_corrector(self._store)+ corrected = corrector.correct(text)+ # A provider may also carry the pre-cleanup string on ``raw_text``,+ # and the dictation lane transcribes from THAT. The user's spelling+ # corrections are not part of the cleanup they opted out of — they+ # are words a person registered by name — so they have to reach both+ # fields or dictation silently stops honouring the dictionary.+ raw = getattr(transcript, "raw_text", "") or ""+ corrected_raw = corrector.correct(raw) if raw else raw+ if corrected == text and corrected_raw == raw:return transcriptlog.debug("STT dictionary corrected: %r -> %r", text, corrected)+ updates: dict[str, Any] = {"text": corrected}+ # Only when the provider actually has the field: passing it to a+ # provider that does not would raise instead of correcting.+ if raw:+ updates["raw_text"] = corrected_rawif dataclasses.is_dataclass(transcript):- return dataclasses.replace(transcript, text=corrected)- transcript.text = corrected # duck-typed fakes in tests+ return dataclasses.replace(transcript, **updates)+ for name, value in updates.items(): # duck-typed fakes in tests+ setattr(transcript, name, value)return transcriptexcept Exception as exc: # noqa: BLE001 — corrections must never break STTlog.warning("STT dictionary correction failed (%s); using raw text.", exc)diff --git a/tests/unit/dictation/test_delivery_and_bar.py b/tests/unit/dictation/test_delivery_and_bar.pyindex d9189a2078..162be74319 100644--- a/tests/unit/dictation/test_delivery_and_bar.py+++ b/tests/unit/dictation/test_delivery_and_bar.py@@ -529,6 +529,75 @@ async def test_auto_asks_the_provider_to_detect_instead_of_staying_silent(assert seen == [{"language": "auto"}]+async def test_a_provider_that_cleans_its_own_text_cannot_override_the_filler_switch(+ monkeypatch: pytest.MonkeyPatch, audio_spy+) -> None:+ """A cleaned ``text`` is right for a voice command and wrong for dictation.++ Cloud providers may now filter their own transcript — hesitation sounds,+ decoder loops, stutters — before handing it over. This lane must keep+ transcribing from ``raw_text``: it owns the user's filler switch, runs its+ own cleanup in the language the USER pinned, and writes the untouched+ string to the history. Reading the pre-cleaned one would turn "keep my+ filler words" into a setting with no effect and nothing to observe.+ """+ import jarvis.speech.pipeline as pipeline_mod++ class _CleaningSTT:+ async def transcribe_pcm(self, pcm: bytes, **_kw):+ return SimpleNamespace(+ text="Das ist gut.", # i18n-allow: German fixture under test (§1 list #4)+ raw_text="Ähm, das ist gut.", # i18n-allow: German fixture (§1 list #4)+ language="de",+ )++ monkeypatch.setattr(+ pipeline_mod, "MicrophoneCapture", lambda **_kw: _FakeMic(b"\x00\x01" * 16_000)+ )+ pipe, events = _session_pipeline(+ _CleaningSTT(),+ DictationConfig(+ language="de", partial_interval_s=0.0, remove_fillers=False+ ),+ )+ await pipe._dictation_session()++ final = [+ e for e in events if isinstance(e, DictationTranscript) and e.is_final+ ][-1]+ assert final.text == "Ähm, das ist gut." # i18n-allow: German fixture (§1 list #4)+++async def test_a_provider_without_a_raw_text_field_is_unaffected(+ monkeypatch: pytest.MonkeyPatch, audio_spy+) -> None:+ """Every other provider keeps its single ``text`` field and behaves as before."""+ import jarvis.speech.pipeline as pipeline_mod++ class _PlainSTT:+ async def transcribe_pcm(self, pcm: bytes, **_kw):+ return SimpleNamespace(+ text="Ähm, das ist gut.", # i18n-allow: German fixture (§1 list #4)+ language="de",+ )++ monkeypatch.setattr(+ pipeline_mod, "MicrophoneCapture", lambda **_kw: _FakeMic(b"\x00\x01" * 16_000)+ )+ pipe, events = _session_pipeline(+ _PlainSTT(),+ DictationConfig(language="de", partial_interval_s=0.0, remove_fillers=True),+ )+ await pipe._dictation_session()++ final = [+ e for e in events if isinstance(e, DictationTranscript) and e.is_final+ ][-1]+ assert final.text == "Das ist gut." # i18n-allow: German fixture (§1 list #4)++@pytest.mark.asyncioasync def test_a_provider_without_the_language_keyword_still_transcribes(monkeypatch: pytest.MonkeyPatch, audio_spydiff --git a/tests/unit/plugins/stt/test_openrouter_stt.py b/tests/unit/plugins/stt/test_openrouter_stt.pyindex 2fd553b710..95a7a1fd53 100644--- a/tests/unit/plugins/stt/test_openrouter_stt.py+++ b/tests/unit/plugins/stt/test_openrouter_stt.py@@ -179,6 +179,57 @@ async def test_response_text_is_parsed_into_transcript() -> None:assert result.segments == ()+async def test_gateway_artifacts_are_cleaned_and_the_raw_text_is_kept() -> None:+ """The payload text is filtered on the way into the Transcript.++ One response carries all three artifact classes the filter exists for: an+ outer quote pair the model added, a hesitation sound, and a decoder loop.+ ``raw_text`` keeps the gateway's own string so the dictation lane — which+ owns a user switch for filler removal — still transcribes from it.+ """+ payload = {+ "text": '"Um, turn on the light. Thank you. Thank you. Thank you."',+ "language": "English",+ }++ async def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json=payload)++ stt = OpenRouterSTT(api_key="k", http_client=_mock_client(handler))+ try:+ result = await stt.transcribe_pcm(_silent_pcm())+ finally:+ await stt.aclose()++ assert result.text == "Turn on the light. Thank you."+ assert result.raw_text == payload["text"]+ assert result.confidence == 1.0+++async def test_cleanup_never_reports_silence_for_audio_that_had_speech(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Confidence follows the RAW text: a filter bug must not read as silence."""+ monkeypatch.setattr(+ "jarvis.plugins.stt.transcript_filter.clean_stt_text",+ lambda *_a, **_k: "",+ )++ async def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json=_JSON_OK)++ stt = OpenRouterSTT(api_key="k", http_client=_mock_client(handler))+ try:+ result = await stt.transcribe_pcm(_silent_pcm())+ finally:+ await stt.aclose()++ assert result.confidence == 1.0+ assert result.raw_text == "hello world"++@pytest.mark.asyncioasync def test_empty_pcm_returns_empty_transcript_without_calling_api() -> None:called = {"n": 0}diff --git a/tests/unit/plugins/stt/test_transcript_filter.py b/tests/unit/plugins/stt/test_transcript_filter.pynew file mode 100644index 0000000000..cfb6a401dc--- /dev/null+++ b/tests/unit/plugins/stt/test_transcript_filter.py@@ -0,0 +1,209 @@+"""Transcript cleanup filter — ``jarvis.plugins.stt.transcript_filter``.++The German and Spanish strings in this file are the speech under test: a filter+that removes German hesitation sounds cannot be tested in English (CLAUDE.md §1,+allowed category 4).+"""+from __future__ import annotations++import unicodedata++import pytest++from jarvis.plugins.stt.transcript_filter import (+ PHONETIC_FIXES,+ apply_phonetic_fixes,+ clean_stt_text,+ collapse_repetitions,+ normalize_characters,+ repair_stutters,+ strip_wrapping_quotes,+)++# ----------------------------------------------------------------------+# Character normalisation+# ----------------------------------------------------------------------+++def test_decomposed_umlauts_are_composed() -> None:+ """A provider answering in NFD must not blind the umlaut-bearing rules."""+ decomposed = unicodedata.normalize("NFD", "ähnlich") # i18n-allow: input+ assert decomposed != "ähnlich" # i18n-allow: guards the fixture itself+ assert normalize_characters(decomposed) == "ähnlich" # i18n-allow: input+++def test_invisible_characters_and_nbsp_are_removed() -> None:+ text = "Mach das Licht an" # i18n-allow: input under test+ assert normalize_characters(text) == "Mach das Licht an" # i18n-allow: input+++def test_newlines_survive_but_horizontal_runs_collapse() -> None:+ assert normalize_characters("one two\n\nthree\t four") == "one two\n\nthree four"+++def test_decomposed_umlaut_filler_is_still_removed() -> None:+ """The reason NFC runs first: the filler tables are composed spellings."""+ decomposed = "Äh, mach das Licht an." # i18n-allow: German speech under test+ assert clean_stt_text(decomposed, language="de") == "Mach das Licht an."+++# ----------------------------------------------------------------------+# Wrapping quotes+# ----------------------------------------------------------------------+++ "wrapped",+ ['"turn on the light"', "'turn on the light'", "“turn on the light”"],+)+def test_one_matched_quote_pair_is_stripped(wrapped: str) -> None:+ assert strip_wrapping_quotes(wrapped) == "turn on the light"+++def test_unmatched_and_inner_quotes_survive() -> None:+ assert strip_wrapping_quotes('he said "hello" to me') == 'he said "hello" to me'+ assert strip_wrapping_quotes('"unbalanced') == '"unbalanced'+++# ----------------------------------------------------------------------+# Repetition loops+# ----------------------------------------------------------------------+++def test_word_loop_collapses_to_one() -> None:+ assert collapse_repetitions("ja ja ja ja das passt") == "ja das passt"+++def test_phrase_loop_with_punctuation_collapses() -> None:+ text = "Thank you for watching. Thank you for watching. Thank you for watching."+ assert collapse_repetitions(text) == "Thank you for watching."+++def test_phrase_loop_containing_a_year_collapses() -> None:+ """The subtitle credit this repo has actually seen in the wild."""+ # i18n-allow: German STT boilerplate is the artifact under test (§1 list #4)+ one = "Untertitelung des ZDF für funk, 2017" # i18n-allow: STT boilerplate+ assert collapse_repetitions(f"{one}. {one}. {one}. Mach das Licht an") == (+ f"{one}. Mach das Licht an"+ )+++def test_a_doubled_word_is_left_alone() -> None:+ """Two, not three: ordinary speech in every language this ships in."""+ # i18n-allow: German sentence whose legitimate doubling is under test+ german = "Ich weiß, dass das das Problem ist" # i18n-allow: input under test+ assert collapse_repetitions(german) == german+ assert collapse_repetitions("We had had enough") == "We had had enough"+++def test_a_repeated_bare_number_is_left_alone() -> None:+ """A repeated number is dictated data far more often than a decoder loop."""+ spoken = "Die Nummer ist 5 5 5" # i18n-allow: German speech under test+ assert collapse_repetitions(spoken) == spoken+++def test_distinct_words_in_a_row_are_left_alone() -> None:+ text = "Wir treffen uns Montag, Dienstag und Mittwoch." # i18n-allow: input+ assert collapse_repetitions(text) == text+++# ----------------------------------------------------------------------+# Stutters+# ----------------------------------------------------------------------+++def test_hyphen_stutter_is_dropped() -> None:+ assert repair_stutters("w- was ist das") == "was ist das" # i18n-allow: input+++def test_suspended_hyphen_survives() -> None:+ """German writes "Vor- und Nachteile"; that hyphen is not a stutter."""+ text = "Vor- und Nachteile" # i18n-allow: German construction under test+ assert repair_stutters(text) == text+++def test_long_fragment_before_a_hyphen_is_not_a_stutter() -> None:+ text = "Software- und Softwareentwicklung" # i18n-allow: input under test+ assert repair_stutters(text) == text+++# ----------------------------------------------------------------------+# Phonetic fixes+# ----------------------------------------------------------------------+++def test_known_misrecognition_is_repaired_for_its_language() -> None:+ # i18n-allow: the mis-transcription and its target are the data under test+ assert apply_phonetic_fixes("Bitte aufflegen", "de") == "Bitte auflegen"+++def test_phonetic_fixes_do_not_run_without_a_language() -> None:+ text = "Bitte aufflegen" # i18n-allow: input vocabulary under test+ assert apply_phonetic_fixes(text, None) == text+ assert apply_phonetic_fixes(text, "fr") == text+++def test_no_phonetic_source_is_a_real_word_elsewhere() -> None:+ """The admission rule, pinned: a source token that means something in+ another supported language would be replaced inside correct sentences the+ first time a provider reports the wrong language tag — and providers do."""+ from jarvis.dictation.cleanup import FILLER_WORDS++ every_filler = {word for words in FILLER_WORDS.values() for word in words}+ for language, pairs in PHONETIC_FIXES.items():+ for source, target in pairs:+ assert source.casefold() != target.casefold()+ assert source.casefold() not in every_filler, (language, source)+++# ----------------------------------------------------------------------+# End to end+# ----------------------------------------------------------------------+++def test_english_filler_and_quotes_in_one_pass() -> None:+ raw = '"Uh, I think we should um ship it."'+ assert clean_stt_text(raw, language="en") == "I think we should ship it."+++def test_german_filler_needs_the_german_tag() -> None:+ raw = "Ähm, kannst du äh das Licht anmachen?" # i18n-allow: speech under test+ assert clean_stt_text(raw, language="de") == "Kannst du das Licht anmachen?"+++def test_the_english_language_name_is_understood() -> None:+ """Cloud Whisper endpoints answer with the NAME, not the ISO code."""+ assert clean_stt_text("Uh, ship it.", language="English") == "Ship it."+++def test_an_unknown_language_still_gets_the_neutral_repairs() -> None:+ """No filler table for French, but a loop is a loop in every language."""+ out = clean_stt_text("bonjour bonjour bonjour Marie", language="fr")+ assert out == "bonjour Marie"+++def test_filler_removal_can_be_switched_off() -> None:+ raw = "Uh, ship it."+ assert clean_stt_text(raw, language="en", remove_fillers=False) == raw+++def test_empty_and_blank_input_is_returned_unchanged() -> None:+ assert clean_stt_text("") == ""+ assert clean_stt_text(" ") == " "+++def test_a_transcript_of_only_filler_survives_the_destruction_ceiling() -> None:+ """The delegated ceiling: rules that leave nothing behind are a defect."""+ assert clean_stt_text("um uh umm", language="en") == "um uh umm"+++def test_cleanup_never_raises_on_a_broken_rule(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def _boom(*_args: object, **_kwargs: object) -> str:+ raise RuntimeError("rule exploded")++ monkeypatch.setattr(+ "jarvis.plugins.stt.transcript_filter.collapse_repetitions", _boom+ )+ assert clean_stt_text("turn on the light", language="en") == "turn on the light"