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.

@ fix(dictation): stop the guard rejecting a polish that REPAIRED a misheard word

Ruben Lütke9e617279970f
diff --git a/jarvis/dictation/polish_guards.py b/jarvis/dictation/polish_guards.py
index cb169d0875..03c0b3bd1c 100644
--- a/jarvis/dictation/polish_guards.py
+++ b/jarvis/dictation/polish_guards.py
@@ -93,6 +93,33 @@ TRANSLATE_DRIFT_REASONS: Final[tuple[str, ...]] = (
#: short tokens are dominated by inflections, particles and recognizer debris.
_RARE_MIN_CHARS = 4
+#: How different a replacement may be and still count as a REPAIR of the token
+#: it replaced, rather than its loss. Levenshtein distance over the longer of
+#: the two, so it is a share and not an absolute: at 0.5, half the characters
+#: may move.
+#:
+#: The number is set by the two mistakes it has to tell apart, measured on the
+#: live history:
+#:
+#: * repairs that MUST pass — ``deskto`` -> ``desktop`` (0.14),
+#: ``javas`` -> ``jarvis`` (0.33), ``haboogle`` -> ``hab google`` (0.11),
+#: ``promme`` -> ``prompts`` (0.43);
+#: * losses that MUST still fail — ``anushka`` -> ``her`` (1.0),
+#: ``kubernetes`` dropped entirely (no candidate at all).
+#:
+#: The gap between the two groups is wide, so the exact cut matters far less
+#: than being inside it. It sits nearer the repairs because the cost is not
+#: symmetric: a rejected repair hands the user a transcript they cannot use,
+#: while a wrongly accepted one is a word they can see and edit.
+_REPAIR_MAX_DISTANCE_SHARE = 0.5
+
+#: How many output tokens a single misheard token may have been split into.
+#: A recognizer that runs two words together (``hab Google`` -> ``haboogle``)
+#: is repaired by splitting them apart again, so the candidate has to be looked
+#: for across token boundaries as well. Two is what the observed failures need;
+#: more would start matching unrelated phrases by coincidence.
+_REPAIR_MAX_SPLIT = 2
+
#: Scripts that do not put spaces between words. A "word count" over these is
#: meaningless — a whole Chinese sentence counts as ONE token — so any
#: length-ratio check that spans one of them and a space-separated script is
@@ -365,6 +392,78 @@ def rare_tokens(text: str, *, language: str) -> frozenset[str]:
)
+def _edit_distance(a: str, b: str) -> int:
+ """Levenshtein distance between two short tokens.
+
+ Written out rather than pulled from a dependency because this module is on
+ the dictation path and must stay import-free (same discipline as
+ ``scrub_for_voice``, AP-11). Two rolling rows, so the cost is O(len(a) *
+ len(b)) time and O(len(b)) space over strings that are words.
+ """
+ if a == b:
+ return 0
+ if not a:
+ return len(b)
+ if not b:
+ return len(a)
+ previous = list(range(len(b) + 1))
+ for i, ch_a in enumerate(a, start=1):
+ current = [i]
+ for j, ch_b in enumerate(b, start=1):
+ current.append(
+ min(
+ previous[j] + 1, # deletion
+ current[j - 1] + 1, # insertion
+ previous[j - 1] + (ch_a != ch_b), # substitution
+ )
+ )
+ previous = current
+ return previous[-1]
+
+
+def _is_repair_of(lost: str, candidate: str) -> bool:
+ """Whether *candidate* is *lost* spelled correctly, rather than a new word."""
+ if not candidate:
+ return False
+ span = max(len(lost), len(candidate))
+ if not span:
+ return False
+ return _edit_distance(lost, candidate) / span <= _REPAIR_MAX_DISTANCE_SHARE
+
+
+def _was_repaired(lost: str, out_tokens: Sequence[str]) -> bool:
+ """Whether the output carries a corrected spelling of the token *lost*.
+
+ This is the difference between the two things a vanished rare token can
+ mean, and the guard is useless until it can tell them apart:
+
+ * the formatter **dropped** a word the speaker said — ``Anushka`` becoming
+ ``her``, a protected term deleted outright. Nothing in the answer stands
+ where it was, and the guard must reject.
+ * the formatter **repaired** what the recognizer misheard — ``deskto``
+ becoming ``desktop``, ``haboogle`` becoming ``hab Google``. The word is
+ still there; only its spelling changed, towards the one the speaker
+ actually said.
+
+ Treating the second as the first is not a conservative default, it is the
+ guard failing exactly where it is needed most: a misrecognized word is
+ ALWAYS rare — that is what being misrecognized makes it — so the rarity
+ filter protects the recognizer's mistakes in direct proportion to how badly
+ it mangled them. Measured on the live history, 30 of 71 polish runs (42 %)
+ were thrown away this way, and the worse the transcript, the likelier the
+ repair was refused.
+
+ Candidates are single output tokens plus runs of up to
+ :data:`_REPAIR_MAX_SPLIT`, because one misheard token is often two spoken
+ words run together.
+ """
+ for size in range(1, _REPAIR_MAX_SPLIT + 1):
+ for start in range(len(out_tokens) - size + 1):
+ if _is_repair_of(lost, "".join(out_tokens[start : start + size])):
+ return True
+ return False
+
+
def _digit_runs(text: str) -> frozenset[str]:
"""Every number in *text*, with grouping separators flattened away."""
return frozenset(_DIGIT_RUN_RE.findall(_DIGIT_SEPARATOR_RE.sub("", str(text or ""))))
@@ -462,8 +561,15 @@ def drift_reason(
# guard declining to compound it. `raw_language` is already computed above,
# so the correction costs nothing.
lookup = raw_language if raw_language != "unknown" else language
- if rare_tokens(raw, language=lookup) - rare_tokens(polished, language=lookup):
- return "lost_term"
+ vanished = rare_tokens(raw, language=lookup) - rare_tokens(polished, language=lookup)
+ if vanished:
+ # A vanished rare token is only a LOSS when nothing in the answer stands
+ # where it was. Where a corrected spelling does, it is the repair this
+ # pass exists to make — see ``_was_repaired`` for why conflating the two
+ # disarmed the guard on precisely the transcripts that needed it.
+ out_tokens = _compare_tokens(polished)
+ if any(not _was_repaired(token, out_tokens) for token in vanished):
+ return "lost_term"
return ""
diff --git a/jarvis/dictation/polish_prompt.py b/jarvis/dictation/polish_prompt.py
index a6327c751e..6bb2613488 100644
--- a/jarvis/dictation/polish_prompt.py
+++ b/jarvis/dictation/polish_prompt.py
@@ -38,7 +38,7 @@ from typing import Final
#: Bumped whenever the wording below changes in a way that could change model
#: behaviour. Stored alongside a polished transcript so a later quality
#: regression can be attributed to a prompt revision rather than a provider.
-POLISH_PROMPT_VERSION: Final[int] = 1
+POLISH_PROMPT_VERSION: Final[int] = 2
#: The delimiters that fence the untrusted transcript inside the user message.
#: Deliberately ugly and unlikely to be dictated by accident; deliberately
@@ -79,11 +79,20 @@ HARD RULES — a violation makes your answer unusable:
3. PRESERVE VERBATIM: proper names, place names, product names, brand names,
technical terms, code identifiers, file paths, URLs, e-mail addresses,
acronyms, and every number, quantity, date, time and currency amount.
- Never "correct" an unfamiliar word into a familiar one.
+ An unfamiliar word that IS a word stays exactly as written — you do not
+ know every name, and a word you have not met is not a mistake.
4. RETURN ONLY THE FORMATTED TEXT. No preamble, no quotes, no explanation,
no markdown fences, no "Here is".
WHAT YOU MAY DO:
+- Repair a word the recognizer clearly misheard, and ONLY under all three
+ conditions: what it wrote is not a word in the input language, the word the
+ speaker said is unambiguous from the surrounding sentence, and your repair
+ sounds like what was written. This covers a word cut short ("deskto" ->
+ "desktop") and two words run together ("haboogle Drive" -> "hab Google
+ Drive"). If more than one word would fit, or the result would only be more
+ plausible rather than clearly intended, leave it alone — a strange word the
+ reader can see beats a confident wrong one they cannot.
- Remove filler sounds and repeated words that carry no meaning.
- Remove false starts and self-corrections: keep the corrected version, drop
the abandoned one. ("at 2, actually 3" -> "at 3")
diff --git a/jarvis/plugins/stt/__init__.py b/jarvis/plugins/stt/__init__.py
index 9e738a0549..0546daece1 100644
--- a/jarvis/plugins/stt/__init__.py
+++ b/jarvis/plugins/stt/__init__.py
@@ -190,6 +190,50 @@ def provider_runs_on_device(provider_name: str) -> bool:
return bool(getattr(_load_provider_class(name), _ON_DEVICE_ATTR, False))
+#: Class attribute a recognizer plugin sets to declare what it was BUILT for —
+#: ``"latency"`` or ``"accuracy"``. Same shape and same reason as
+#: ``runs_on_device`` above: the capability is answered by the plugin, so no
+#: caller has to carry a list of engine names (AP-21).
+_OPTIMIZED_FOR_ATTR = "optimized_for"
+
+#: What a provider that declares nothing is taken to be. "accuracy" is the
+#: right default because it changes no behaviour: every consumer of this
+#: function is looking for a reason to AVOID an engine, so an undeclared
+#: provider — including every stranger's plugin — keeps being used exactly
+#: where it was used before.
+_DEFAULT_OPTIMIZED_FOR = "accuracy"
+
+
+@lru_cache(maxsize=32)
+def provider_optimized_for_latency(provider_name: str) -> bool:
+ """Whether ``provider_name`` trades accuracy for speed by design.
+
+ A streaming recognizer emits words before the sentence containing them
+ exists: it is decoding under a deadline, with only the audio that has
+ already arrived. That is the correct trade for a spoken command, where a
+ late word is worse than an imperfect one, and the wrong one for a dictation
+ — which is recorded first, transcribed afterwards, and then READ, so there
+ is no deadline to trade against and nothing to gain by guessing early.
+
+ Asked so that the dictation lane can prefer an accuracy-first engine
+ WITHOUT naming one. The alternative that AP-21 warns about — a list of
+ engine names here — would be wrong for the next streaming recognizer
+ somebody plugs in, and wrong again for the user who configured a cloud
+ provider this repo has never heard of.
+
+ Cached per name for the same reason as :func:`provider_runs_on_device`: the
+ answer cannot change while the process runs, and reading the attribute
+ imports the plugin module.
+ """
+ name = (provider_name or "").strip()
+ if not name:
+ return False
+ declared = getattr(
+ _load_provider_class(name), _OPTIMIZED_FOR_ATTR, _DEFAULT_OPTIMIZED_FOR
+ )
+ return str(declared or _DEFAULT_OPTIMIZED_FOR).strip().lower() == "latency"
+
+
def stt_family_id(provider_name: str) -> str:
"""The CREDENTIAL family a provider id belongs to.
diff --git a/jarvis/plugins/stt/nemotron_local.py b/jarvis/plugins/stt/nemotron_local.py
index d46fd1cc25..6063ccfeb7 100644
--- a/jarvis/plugins/stt/nemotron_local.py
+++ b/jarvis/plugins/stt/nemotron_local.py
@@ -76,6 +76,18 @@ class NemotronLocalSTT:
# which is a separate piece of pipeline work — claiming it before it exists
# would be the dead-config lie this repo keeps auditing for.
supports_streaming = False
+ # What this engine was BUILT to optimise, declared by the plugin for itself
+ # (AP-21) so no caller has to know the name "nemotron" to reason about it.
+ # A cache-aware streaming transducer buys its latency with future context it
+ # does not wait for, and this bundle can only decode greedily: sherpa-onnx
+ # rejects ``modified_beam_search`` for ``nemo_transducer``, which also means
+ # no hotwords and so no contextual biasing from the user's STT dictionary
+ # (k2-fsa/sherpa-onnx#3572). Both trades are right for a spoken command,
+ # where a word arriving late is worse than a word arriving imperfect, and
+ # wrong for a dictation, which is transcribed after the fact and read as
+ # text. Callers that transcribe a FINISHED recording read this and prefer an
+ # accuracy-first engine where the user has one.
+ optimized_for = "latency"
def __init__(
self,
diff --git a/tests/unit/dictation/test_polish_guards.py b/tests/unit/dictation/test_polish_guards.py
index 372439b910..5d482664f8 100644
--- a/tests/unit/dictation/test_polish_guards.py
+++ b/tests/unit/dictation/test_polish_guards.py
@@ -148,6 +148,43 @@ def test_a_dropped_proper_noun_is_rejected_even_without_a_dictionary_entry() ->
assert verdict(raw, polished) == "lost_term"
+def test_a_misheard_word_may_be_corrected_without_counting_as_a_loss() -> None:
+ """The guard's own worst failure: protecting the recognizer's mistakes.
+
+ A misheard word is ALWAYS rare — being misheard is what makes it rare — so
+ a rarity filter that treats "this token is gone" as "a word was lost"
+ refuses every repair, and refuses hardest on the transcripts that need one
+ most. Measured on the live history: 30 of 71 polish runs (42 %) were thrown
+ away this way. Each raw line below is a real one.
+ """
+ for raw, polished in (
+ # A word cut short by the recognizer.
+ ("Wieso legt die Javas Deskto App so extrem rum", # i18n-allow: real transcript under test
+ "Wieso laggt die Jarvis Desktop App so extrem rum?"), # i18n-allow
+ # Two spoken words run together into one non-word.
+ ("Ich haboogle Drive und so nicht mal offen", # i18n-allow
+ "Ich hab Google Drive und so nicht mal offen."), # i18n-allow
+ ("Ich hab die Promme nicht mal", "Ich hab die Prompts nicht mal."), # i18n-allow
+ ):
+ assert verdict(raw, polished, language="de") == "", (
+ f"a repair of {raw!r} must be delivered, not refused"
+ )
+
+
+def test_a_word_replaced_by_an_unrelated_one_is_still_a_loss() -> None:
+ """Letting repairs through must not let rewrites through with them.
+
+ The line between the two is whether anything in the answer stands where the
+ word did. ``Anushka`` -> ``Anuschka`` is a spelling; ``Anushka`` -> ``Sarah``
+ is a different person.
+ """
+ raw = "I met Anushka at the conference in Lisbon on Tuesday morning"
+ assert verdict(raw, "I met Sarah at the conference in Lisbon on Tuesday "
+ "morning.") == "lost_term"
+ assert verdict(raw, "I met Anuschka at the conference in Lisbon on Tuesday "
+ "morning.") == ""
+
+
def test_every_reason_this_module_can_return_is_a_declared_one() -> None:
"""A guard that invents a code the history and the UI never heard of is the
five-layer drift this repo has hit four times (AP-4)."""