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): preserve pauses and measure recognition fidelity (#440)

Ruben Lütke991d9fab0800
diff --git a/jarvis/dictation/cleanup.py b/jarvis/dictation/cleanup.py
index 9226136837..87f5729879 100644
--- a/jarvis/dictation/cleanup.py
+++ b/jarvis/dictation/cleanup.py
@@ -328,29 +328,12 @@ def clean_transcript(
# Punctuation repair at the segment joins
# ---------------------------------------------------------------------------
-#: What a recognizer emits at a pause: a run of two or more dots, or the single
-#: "…" glyph. Both spellings occur, sometimes in the same transcript.
-_ELLIPSIS = r"(?:\.{2,}|…)"
-
-#: A sentence terminator with a recognizer ellipsis glued to it, either directly
-#: ("gesprochen...") or across the space a segment join left ("gesprochen. ...").
-#: The ``(?<=\w)`` lookbehind is load-bearing: it demands a WORD before the
-#: terminator, so the first dot of a free-standing " ... " can never be mistaken
-#: for the terminator and the speaker's own ellipsis survives the rule.
-_JOINED_ELLIPSIS_RE = re.compile(r"(?<=\w)([.!?])[ \t]*" + _ELLIPSIS)
-
-#: The same artifact spelled with the "…" glyph, which carries no terminator to
-#: keep: "gesprochen… ist". Only repaired when text follows — a trailing "…"
-#: ends nothing and may well be what the speaker meant.
-_ATTACHED_GLYPH_RE = re.compile(r"(?<=\w)…(?=[ \t]+\S)")
-
-#: A free-standing ellipsis between two segments. Whether it is an artifact or
-#: the speaker's own pause is undecidable from the text alone, so the decision
-#: is made in :func:`_repair_standalone_ellipsis` on the ONE signal that exists:
-#: the recognizer capitalises the start of every segment.
-_STANDALONE_ELLIPSIS_RE = re.compile(
- r"(?<=\w)[ \t]+" + _ELLIPSIS + r"[ \t]+(?=(?P<next>\w))"
-)
+#: Only collapse an ellipsis after a SEPARATE sentence terminator. Without the
+#: mandatory space, the first dot of an ordinary hesitation was mistaken for
+#: a full stop and the continuation was capitalized into a different sentence.
+#: Attached ellipses, Unicode ellipses and pauses before capitalized words are
+#: ambiguous: capitalization can mark a noun or a technical name, not a seam.
+_JOINED_ELLIPSIS_RE = re.compile(r"(?<=\w)([.!?])[ \t]+(?:\.{3,}|…)")
#: EXACTLY two dots, not part of a longer run. ".." is always a join artifact;
#: "..." is an ellipsis and must not be reduced to it one dot at a time.
@@ -377,68 +360,28 @@ _DOUBLE_SPACE_RE = re.compile(r"[ \t]{2,}")
_SENTENCE_START_RE = re.compile(r"(?<=\w\w)([.!?])([ \t]+)([^\W\d_])")
-def _repair_standalone_ellipsis(match: re.Match[str]) -> str:
- """A free-standing ellipsis is only a join artifact when a segment follows.
-
- The recognizer capitalises the first word of every segment it produces, so
- an upper-case continuation after " ... " means a new segment began there and
- the ellipsis is ours to remove. A lower-case continuation is the speaker
- trailing off mid-sentence, and that stays exactly as dictated.
- """
- if not match.group("next").isupper():
- return match.group(0)
- return ". "
-
-
def _upper_sentence_start(match: re.Match[str]) -> str:
return match.group(1) + match.group(2) + match.group(3).upper()
def tidy_transcript(text: str) -> str:
- """Repair the punctuation a SEGMENTED transcription leaves behind. Never raises.
-
- This runs on every dictation, not only on one a filler was removed from.
- The damage is not made here: the lane transcribes in ~8 s segments, the
- recognizer punctuates and capitalises each one as if it were the whole
- utterance, emits its own trailing "..." wherever a segment cut a sentence in
- half, and the pieces are then joined with a bare space. So a transcript no
- rule in this module ever touched still arrives with a stray "..." parked
- between two sentences and the next one starting lower-case — which is why
- gating the repair on "a filler was removed" left the common case broken.
-
- Four repairs, in this order:
-
- 1. an ellipsis glued to a sentence terminator collapses into that terminator;
- 2. a free-standing ellipsis before a capitalised word becomes a full stop;
- 3. adjacent terminal marks ("..", ".,", "., ") de-duplicate, stronger wins;
- 4. a lower-case word after a sentence terminator gets its capital back.
-
- THE TRADE-OFF, stated plainly
- -----------------------------
- Nothing in the text says whether an ellipsis came from the recognizer or
- from the speaker, so the split is drawn where it is cheapest to be wrong:
-
- * an **attached** ellipsis ("gesprochen... ist") is treated as an artifact
- and collapsed — a speaker who dictated a trailing pause there loses it;
- * a **free-standing** ellipsis ("das war ... schwierig") is kept, unless the
- next word is capitalised, which only a segment boundary produces.
-
- Rule 4 has a matching cost: it capitalises after an abbreviation that ends
- in a period and is at least two letters long ("etc. and" -> "etc. And").
- Both errors are cosmetic and visible; the errors they prevent — a doubled
- "...." in the middle of a sentence, a paragraph of lower-case sentence
- starts — are the ones users actually report.
-
- Returns the text unchanged on anything unexpected: a repair that eats a
- dictation is worse than a transcript that reads slightly wrong.
+ """Repair duplicate punctuation without treating a hesitation as a sentence.
+
+ A pause may be written as attached dots, spaced dots or a Unicode ellipsis.
+ Preserve each spelling, even before a capitalized word: text alone cannot
+ establish that the speaker finished a sentence there. Only a separately
+ written terminator licenses removing a following redundant ellipsis.
+
+ Existing duplicate-mark, whitespace and sentence-capitalization repairs
+ still run. Capitalization after multi-letter abbreviations remains a
+ limitation of the sentence rule; this pass does not infer their meaning.
+ Returns the original text on an unexpected failure.
"""
original = text or ""
if not original.strip():
return original
try:
out = _JOINED_ELLIPSIS_RE.sub(r"\1", original)
- out = _ATTACHED_GLYPH_RE.sub(".", out)
- out = _STANDALONE_ELLIPSIS_RE.sub(_repair_standalone_ellipsis, out)
out = _DOUBLE_DOT_RE.sub(".", out)
out = _TERMINATOR_THEN_WEAK_RE.sub(r"\1", out)
out = _WEAK_THEN_MARK_RE.sub(r"\1", out)
diff --git a/jarvis/speech/stt_eval/__main__.py b/jarvis/speech/stt_eval/__main__.py
index 6a15e5738c..f8e2642ce6 100644
--- a/jarvis/speech/stt_eval/__main__.py
+++ b/jarvis/speech/stt_eval/__main__.py
@@ -198,7 +198,7 @@ def main(argv: list[str] | None = None) -> int:
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(
json.dumps(
- {"schema_version": 2, "contenders": [asdict(report) for report in reports]},
+ {"schema_version": 3, "contenders": [asdict(report) for report in reports]},
ensure_ascii=False,
indent=2,
),
@@ -221,8 +221,12 @@ def main(argv: list[str] | None = None) -> int:
else f"estimated_cost=${report.estimated_cost_usd:.4f}"
)
print(
- f"{report.label}: WER={report.wer:.3f}, switch={switch}, "
+ f"{report.label}: macro_WER={report.wer:.3f}, "
+ f"speech_WER={report.quality.word_weighted_wer}, switch={switch}, "
f"repeatability={repeatability}, latency={report.median_latency_ms:.0f} ms, "
+ f"p95={report.quality.p95_latency_ms:.0f} ms, "
+ f"silence_hallucinations={report.quality.silence_hallucination_rate}, "
+ f"failed_attempts={report.quality.failed_attempts}, "
f"{cost}"
)
print(f"Report written to {out}")
diff --git a/jarvis/speech/stt_eval/corpus.py b/jarvis/speech/stt_eval/corpus.py
index b998ffb6a4..2a8036074d 100644
--- a/jarvis/speech/stt_eval/corpus.py
+++ b/jarvis/speech/stt_eval/corpus.py
@@ -43,11 +43,13 @@ def load_corpus(path: Path | str) -> tuple[STTEvalItem, ...]:
) from exc
item_id = str(row.get("id", "")).strip()
audio = str(row.get("audio", "")).strip()
- reference = str(row.get("reference", "")).strip()
- if not item_id or not audio or not reference:
+ reference = row.get("reference")
+ if not item_id or not audio or not isinstance(reference, str):
raise ValueError(
- f"Corpus line {line_number} requires id, audio, and reference."
+ f"Corpus line {line_number} requires id, audio, and a string reference "
+ "(use an explicit empty string for silence)."
)
+ reference = reference.strip()
if item_id in seen:
raise ValueError(f"Duplicate corpus id {item_id!r}.")
seen.add(item_id)
diff --git a/jarvis/speech/stt_eval/harness.py b/jarvis/speech/stt_eval/harness.py
index e6c78ff287..5cf6485a8c 100644
--- a/jarvis/speech/stt_eval/harness.py
+++ b/jarvis/speech/stt_eval/harness.py
@@ -2,15 +2,18 @@
from __future__ import annotations
+import math
import statistics
from collections.abc import Awaitable, Callable, Sequence
from dataclasses import dataclass
from jarvis.speech.stt_eval.corpus import STTEvalItem, read_pcm16
from jarvis.speech.stt_eval.metrics import (
+ WordErrors,
repeatability_error_rate,
switch_error_rate,
word_error_rate,
+ word_errors,
)
@@ -25,6 +28,25 @@ class Recognition:
error: str = ""
+@dataclass(frozen=True, slots=True)
+class QualitySummary:
+ """Counts span all attempts; speech WER excludes empty-reference cases.
+
+ Silence is measured separately so a large quiet corpus cannot dilute speech
+ errors. Failed quiet attempts never count as successful silence suppression.
+ Latency includes failed attempts, which remain visible in failed_attempts.
+ """
+
+ attempts: int
+ failed_attempts: int
+ speech_errors: WordErrors
+ word_weighted_wer: float | None
+ silence_evaluated: int
+ silence_hallucinations: int
+ silence_hallucination_rate: float | None
+ p95_latency_ms: float
+
+
@dataclass(frozen=True, slots=True)
class ItemReport:
id: str
@@ -33,6 +55,8 @@ class ItemReport:
repeatability_error_rate: float | None
median_latency_ms: float
errors: tuple[str, ...]
+ tags: tuple[str, ...]
+ quality: QualitySummary
@dataclass(frozen=True, slots=True)
@@ -48,6 +72,8 @@ class ContenderReport:
measured_cost_usd: float | None
estimated_cost_usd: float
items: tuple[ItemReport, ...]
+ quality: QualitySummary
+ by_tag: dict[str, QualitySummary]
@dataclass(frozen=True, slots=True)
@@ -63,6 +89,33 @@ def _mean_optional(values: Sequence[float | None]) -> float | None:
return statistics.fmean(present) if present else None
+def _quality(
+ scores: Sequence[QualitySummary], latencies: Sequence[float],
+) -> QualitySummary:
+ counts = WordErrors(
+ **{
+ field: sum(getattr(score.speech_errors, field) for score in scores)
+ for field in ("reference_words", "substitutions", "deletions", "insertions")
+ }
+ )
+ silence_evaluated = sum(score.silence_evaluated for score in scores)
+ hallucinations = sum(score.silence_hallucinations for score in scores)
+ ordered = sorted(latencies)
+ return QualitySummary(
+ attempts=sum(score.attempts for score in scores),
+ failed_attempts=sum(score.failed_attempts for score in scores),
+ speech_errors=counts,
+ word_weighted_wer=counts.total / counts.reference_words if counts.reference_words else None,
+ silence_evaluated=silence_evaluated,
+ silence_hallucinations=hallucinations,
+ silence_hallucination_rate=(
+ hallucinations / silence_evaluated if silence_evaluated else None
+ ),
+ # Nearest-rank percentile, including small corpora without extrapolation.
+ p95_latency_ms=ordered[math.ceil(0.95 * len(ordered)) - 1] if ordered else 0.0,
+ )
+
+
async def evaluate_contender(
recognize: RecognizeFn,
items: Sequence[STTEvalItem],
@@ -73,13 +126,20 @@ async def evaluate_contender(
repeats: int = 3,
price_per_minute_usd: float = 0.0,
) -> ContenderReport:
- """Measure WER, switch loss, latency, cost, and run-to-run variance."""
+ """Measure speech errors, silence, language switches, latency and cost.
+
+ ``wer`` retains its historical per-item mean. ``quality.word_weighted_wer``
+ is the speech-only corpus rate; category summaries use manifest tags.
+ """
+ if not items:
+ raise ValueError("The STT evaluation corpus is empty.")
repeats = max(1, int(repeats))
item_reports: list[ItemReport] = []
all_latencies: list[float] = []
measured_costs: list[float] = []
measured_cost_complete = True
total_audio_s = 0.0
+ tag_latencies: dict[str, list[float]] = {}
for item in items:
pcm, duration_s = read_pcm16(item)
total_audio_s += duration_s * repeats
@@ -94,6 +154,28 @@ async def evaluate_contender(
measured_costs.append(max(0.0, float(answer.cost_usd)))
wers = [word_error_rate(item.reference, text) for text in texts]
switch_rates = [switch_error_rate(item.switch_anchors, text) for text in texts]
+ scores: list[QualitySummary] = []
+ for text, answer in zip(texts, answers, strict=True):
+ counts = word_errors(item.reference, text)
+ silence_ok = counts.reference_words == 0 and not answer.error
+ hallucination = silence_ok and bool(text.strip())
+ scores.append(
+ QualitySummary(
+ attempts=1,
+ failed_attempts=int(bool(answer.error)),
+ speech_errors=counts if counts.reference_words else WordErrors(0),
+ word_weighted_wer=(
+ counts.total / counts.reference_words if counts.reference_words else None
+ ),
+ silence_evaluated=int(silence_ok),
+ silence_hallucinations=int(hallucination),
+ silence_hallucination_rate=float(hallucination) if silence_ok else None,
+ p95_latency_ms=max(0.0, answer.latency_ms),
+ )
+ )
+ tags = tuple(dict.fromkeys(item.tags))
+ for tag in tags:
+ tag_latencies.setdefault(tag, []).extend(latencies)
item_reports.append(
ItemReport(
id=item.id,
@@ -104,6 +186,8 @@ async def evaluate_contender(
errors=tuple(
dict.fromkeys(answer.error for answer in answers if answer.error)
),
+ tags=tags,
+ quality=_quality(scores, latencies),
)
)
return ContenderReport(
@@ -124,6 +208,13 @@ async def evaluate_contender(
),
estimated_cost_usd=(total_audio_s / 60.0) * max(0.0, price_per_minute_usd),
items=tuple(item_reports),
+ quality=_quality([item.quality for item in item_reports], all_latencies),
+ by_tag={
+ tag: _quality(
+ [item.quality for item in item_reports if tag in item.tags], latencies,
+ )
+ for tag, latencies in tag_latencies.items()
+ },
)
@@ -132,5 +223,6 @@ __all__ = [
"EvaluationReport",
"ItemReport",
"Recognition",
+ "QualitySummary",
"evaluate_contender",
]
diff --git a/jarvis/speech/stt_eval/metrics.py b/jarvis/speech/stt_eval/metrics.py
index ab01ee7d99..89387bfbf7 100644
--- a/jarvis/speech/stt_eval/metrics.py
+++ b/jarvis/speech/stt_eval/metrics.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import re
import unicodedata
from collections.abc import Sequence
+from dataclasses import dataclass
_NON_WORD = re.compile(r"[^\w]+", flags=re.UNICODE)
_WER_WORD = re.compile(r"[^\w']+", flags=re.UNICODE)
@@ -20,27 +21,54 @@ def _wer_words(text: str) -> list[str]:
return [word for word in _WER_WORD.split((text or "").lower()) if word]
-def word_error_rate(reference: str, hypothesis: str) -> float:
- """Return deterministic word-level Levenshtein error for STT output."""
+@dataclass(frozen=True, slots=True)
+class WordErrors:
+ """Edit counts; reference_words is the denominator for speech WER."""
+
+ reference_words: int
+ substitutions: int = 0
+ deletions: int = 0
+ insertions: int = 0
+
+ @property
+ def total(self) -> int:
+ return self.substitutions + self.deletions + self.insertions
+
+
+def word_errors(reference: str, hypothesis: str) -> WordErrors:
+ """Count a minimum edit alignment, preferring substitutions on equal cost."""
expected = _wer_words(reference)
actual = _wer_words(hypothesis)
- if not expected:
- return 0.0 if not actual else 1.0
-
- previous = list(range(len(actual) + 1))
+ # Each cell stores substitutions, deletions and insertions. Only the
+ # previous row is retained, so long recordings do not require a full matrix.
+ previous = [(0, 0, column) for column in range(len(actual) + 1)]
for row, expected_word in enumerate(expected, start=1):
- current = [row]
+ current = [(0, row, 0)]
for column, actual_word in enumerate(actual, start=1):
- substitution = 0 if expected_word == actual_word else 1
- current.append(
- min(
- previous[column] + 1,
- current[column - 1] + 1,
- previous[column - 1] + substitution,
+ if expected_word == actual_word:
+ current.append(previous[column - 1])
+ else:
+ sub, delete, insert = previous[column - 1]
+ above = previous[column]
+ left = current[column - 1]
+ current.append(
+ min(
+ (sub + 1, delete, insert),
+ (above[0], above[1] + 1, above[2]),
+ (left[0], left[1], left[2] + 1),
+ key=sum,
+ )
)
- )
previous = current
- return previous[-1] / len(expected)
+ return WordErrors(len(expected), *previous[-1])
+
+
+def word_error_rate(reference: str, hypothesis: str) -> float:
+ """Return WER, retaining the historical binary score for an empty reference."""
+ counts = word_errors(reference, hypothesis)
+ if not counts.reference_words:
+ return float(bool(counts.total))
+ return counts.total / counts.reference_words
def switch_error_rate(anchors: Sequence[str], hypothesis: str) -> float | None:
@@ -71,4 +99,7 @@ def repeatability_error_rate(hypotheses: Sequence[str]) -> float | None:
)
-__all__ = ["repeatability_error_rate", "switch_error_rate", "word_error_rate"]
+__all__ = [
+ "WordErrors", "repeatability_error_rate", "switch_error_rate",
+ "word_error_rate", "word_errors",
+]
diff --git a/tests/unit/dictation/test_polish_hook.py b/tests/unit/dictation/test_polish_hook.py
index e4e27ff68a..b7fbe7480b 100644
--- a/tests/unit/dictation/test_polish_hook.py
+++ b/tests/unit/dictation/test_polish_hook.py
@@ -124,6 +124,37 @@ async def test_punctuation_is_repaired_in_a_language_with_no_filler_rules() -> N
assert "..." not in text
[email protected]("target", ["chat", "insert"])
[email protected]("remove_fillers", [False, True])
+ ("raw", "language"),
+ [
+ ("was ich... hier eingesprochen habe.", "de"), # i18n-allow: regression
+ ("Please do… not delete these files.", "en"),
+ ("Das sind ... Namen und Zahlen.", "de"), # i18n-allow: German nouns
+ ],
+)
+async def test_hesitation_is_preserved_through_final_delivery(
+ raw: str, language: str, target: str, remove_fillers: bool,
+) -> None:
+ pipe, events, inserted = _pipeline(
+ DictationConfig(
+ history_enabled=False, polish=False, remove_fillers=remove_fillers,
+ )
+ )
+
+ text = await pipe._finish_dictation(
+ raw_text=raw, language=language, duration_s=6.0,
+ target=target, hung_up=False,
+ )
+
+ assert text == raw
+ assert _final_transcript(events).text == raw
+ assert _completed(events).raw_text == raw
+ assert inserted == ([raw] if target == "insert" else [])
+
+
# --------------------------------------------------------------------------
# The polish pass — the happy path and everything the composer sees
# --------------------------------------------------------------------------
diff --git a/tests/unit/dictation/test_tidy_transcript.py b/tests/unit/dictation/test_tidy_transcript.py
index 9cbdc545f6..f5478ec758 100644
--- a/tests/unit/dictation/test_tidy_transcript.py
+++ b/tests/unit/dictation/test_tidy_transcript.py
@@ -1,10 +1,8 @@
"""Punctuation repair at the segment joins — ``cleanup.tidy_transcript``.
-The dictation lane transcribes in ~8 s segments and joins them with a bare
-space, while the recognizer punctuates and capitalises every segment as if it
-were the whole utterance. Everything tested here is damage that arrangement
-manufactures: a doubled "....", a lower-case sentence start, a stray ellipsis
-where a segment cut a sentence in half.
+The recognizer can emit an ellipsis for a pause inside a sentence. A text-only
+cleanup cannot distinguish that hesitation from a window boundary. Preserve
+ambiguous punctuation while repairing separately written duplicate marks.
The negative tests carry the same weight as the positive ones. A repair that
deletes an ellipsis the speaker actually dictated is worse than the artifact it
@@ -103,17 +101,10 @@ def test_blank_input_is_returned_as_is(text: str) -> None:
# The German fixtures below are the vocabulary under test (§1 #4).
# Terminator plus a free-standing ellipsis: the join artifact proper.
("gesprochen. ... ist das gut", "gesprochen. Ist das gut"), # i18n-allow
- # The already-glued form, in case an older transcript carries it.
- ("gesprochen.... ist das gut", "gesprochen. Ist das gut"), # i18n-allow
- # A word-attached ellipsis: the recognizer's mid-sentence cut.
- ("gesprochen... ist das gut", "gesprochen. Ist das gut"), # i18n-allow
- # The single-glyph spelling of the same thing.
- ("gesprochen… ist das gut", "gesprochen. Ist das gut"), # i18n-allow
- # Free-standing, but the next segment starts on a capital.
- ("gesprochen ... Ist das gut", "gesprochen. Ist das gut"), # i18n-allow
+ ("Finished. … next item", "Finished. Next item"),
],
)
-def test_a_segment_join_ellipsis_becomes_one_terminator(
+def test_an_ellipsis_after_a_separate_terminator_is_redundant(
text: str, expected: str
) -> None:
assert tidy_transcript(text) == expected
@@ -129,11 +120,28 @@ def test_a_segment_join_ellipsis_becomes_one_terminator(
# Same, after a comma — the comma must not swallow the dots either.
"wir gehen, ... aber nicht heute", # i18n-allow
"I waited ... and nothing happened",
+ "I think... we should wait.",
+ "I think… we should wait.",
+ "I think.... we should wait.",
+ "I asked ... Alice to wait.",
+ "I asked… Alice to wait.",
+ "Please do... not delete the file.",
+ "Use version... 3.5 for the release.",
+ "Waiting...",
+ "Waiting…",
+ "Waiting ...",
+ "Waiting …",
+ "was ich... hier eingesprochen habe.", # i18n-allow: reported dictation
+ "gesprochen ... Ist das gut", # i18n-allow: ambiguous boundary
+ "Das sind ... Namen und Zahlen.", # i18n-allow: German nouns
+ "Bitte den... Pull Request nicht schließen.", # i18n-allow: mixed speech
+ "Creo… que debemos esperar.", # i18n-allow: Spanish pause
],
)
def test_an_intentional_mid_sentence_ellipsis_survives(text: str) -> None:
"""The failure direction that matters: never delete what was dictated."""
assert tidy_transcript(text) == text
+ assert tidy_transcript(tidy_transcript(text)) == text
# --------------------------------------------------------------------------
diff --git a/tests/unit/speech/stt_eval/test_harness.py b/tests/unit/speech/stt_eval/test_harness.py
index c3455b2e7d..c44e9a0775 100644
--- a/tests/unit/speech/stt_eval/test_harness.py
+++ b/tests/unit/speech/stt_eval/test_harness.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import json
import wave
from pathlib import Path
@@ -90,3 +91,155 @@ async def test_provider_error_counts_as_a_failed_transcript(tmp_path: Path) -> N
assert report.wer == 1.0
assert report.measured_cost_usd is None
assert report.items[0].errors == ("rate_limited",)
+ assert report.quality.failed_attempts == 3
+ assert report.quality.speech_errors.deletions == 6
+
+
+def test_manifest_accepts_an_explicit_empty_silence_reference(tmp_path: Path) -> None:
+ manifest = tmp_path / "corpus.jsonl"
+ manifest.write_text(
+ '{"id":"quiet","audio":"quiet.wav","reference":"","tags":["silence"]}\n',
+ encoding="utf-8",
+ )
+ assert load_corpus(manifest)[0].reference == ""
+
+
[email protected]("reference", [None, 7, False, []])
+def test_manifest_does_not_turn_invalid_references_into_silence(
+ tmp_path: Path, reference: object,
+) -> None:
+ manifest = tmp_path / "corpus.jsonl"
+ manifest.write_text(
+ json.dumps({"id": "bad", "audio": "bad.wav", "reference": reference}),
+ encoding="utf-8",
+ )
+ with pytest.raises(ValueError, match="string reference"):
+ load_corpus(manifest)
+
+
+def test_manifest_requires_the_reference_field_even_for_silence(tmp_path: Path) -> None:
+ manifest = tmp_path / "corpus.jsonl"
+ manifest.write_text('{"id":"bad","audio":"bad.wav"}', encoding="utf-8")
+ with pytest.raises(ValueError, match="string reference"):
+ load_corpus(manifest)
+
+
+async def test_word_weighting_silence_categories_and_tail_latency(tmp_path: Path) -> None:
+ audio = tmp_path / "sample.wav"
+ _wav(audio)
+ items = (
+ STTEvalItem("short", audio, "one two", tags=("speech", "short", "short")),
+ STTEvalItem("long", audio, "one two three four five six seven eight", tags=("speech",)),
+ STTEvalItem("quiet", audio, "", tags=("silence",)),
+ )
+ responses = iter(
+ (
+ Recognition("one wrong", 10.0),
+ Recognition("one two three four five six seven eight", 20.0),
+ Recognition("invented words", 100.0),
+ )
+ )
+
+ async def recognize(_pcm: bytes) -> Recognition:
+ return next(responses)
+
+ report = await evaluate_contender(
+ recognize, items, label="test", provider="fake", model="fake", repeats=1,
+ )
+
+ assert report.wer == 0.5 # Legacy per-item mean, including the silence failure.
+ assert report.quality.word_weighted_wer == 0.1
+ assert report.quality.speech_errors.reference_words == 10
+ assert report.quality.speech_errors.substitutions == 1
+ assert report.quality.speech_errors.insertions == 0
+ assert report.quality.silence_hallucination_rate == 1.0
+ assert report.quality.p95_latency_ms == 100.0
+ assert report.by_tag["speech"].word_weighted_wer == 0.1
+ assert report.by_tag["speech"].p95_latency_ms == 20.0
+ assert report.by_tag["short"].attempts == 1
+ assert report.by_tag["silence"].word_weighted_wer is None
+
+
+async def test_silence_errors_never_count_as_successful_suppression(tmp_path: Path) -> None:
+ audio = tmp_path / "quiet.wav"
+ _wav(audio)
+ responses = iter(
+ (Recognition("", 10, error="timeout"), Recognition("", 20), Recognition("...", 30))
+ )
+
+ async def recognize(_pcm: bytes) -> Recognition:
+ return next(responses)
+
+ report = await evaluate_contender(
+ recognize, (STTEvalItem("quiet", audio, ""),),
+ label="test", provider="fake", model="fake", repeats=3,
+ )
+
+ assert report.quality.attempts == 3
+ assert report.quality.failed_attempts == 1
+ assert report.quality.silence_evaluated == 2
+ assert report.quality.silence_hallucinations == 1
+ assert report.quality.silence_hallucination_rate == 0.5
+ assert report.quality.word_weighted_wer is None
+
+
+async def test_all_failed_silence_has_no_accuracy_measurement(tmp_path: Path) -> None:
+ audio = tmp_path / "quiet.wav"
+ _wav(audio)
+
+ async def recognize(_pcm: bytes) -> Recognition:
+ return Recognition("", 10, error="timeout")
+
+ report = await evaluate_contender(
+ recognize, (STTEvalItem("quiet", audio, ""),),
+ label="test", provider="fake", model="fake", repeats=1,
+ )
+ assert report.quality.failed_attempts == 1
+ assert report.quality.silence_hallucination_rate is None
+
+
+async def test_empty_corpus_fails_before_any_recognizer_call() -> None:
+ async def recognize(_pcm: bytes) -> Recognition:
+ pytest.fail("An empty corpus must not reach the provider")
+
+ with pytest.raises(ValueError, match="corpus is empty"):
+ await evaluate_contender(recognize, (), label="test", provider="fake", model="fake")
+
+
+def test_cli_writes_versioned_metrics_without_private_transcripts(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str],
+) -> None:
+ from jarvis.speech.stt_eval import __main__ as cli
+
+ audio = tmp_path / "private.wav"
+ _wav(audio)
+ private_text = "private dictation content"
+
+ async def recognize(_pcm: bytes) -> Recognition:
+ return Recognition(private_text, 42.0)
+
+ async def run(_args: object):
+ return (
+ await evaluate_contender(
+ recognize, (STTEvalItem("sample", audio, private_text, tags=("quiet",)),),
+ label="test", provider="fake", model="fake", repeats=1,
+ ),
+ )
+
+ monkeypatch.setattr(cli, "_run", run)
+ output = tmp_path / "report.json"
+ assert cli.main([
+ "--corpus", "unused.jsonl", "--contender", "test|fake|fake|0", "--out", str(output),
+ ]) == 0
+ serialized = output.read_text(encoding="utf-8")
+ report = json.loads(serialized)
+ assert report["schema_version"] == 3
+ assert report["contenders"][0]["quality"]["word_weighted_wer"] == 0.0
+ assert report["contenders"][0]["by_tag"]["quiet"]["p95_latency_ms"] == 42.0
+ assert private_text not in serialized
+ assert str(audio) not in serialized
+ assert private_text not in capsys.readouterr().out
diff --git a/tests/unit/speech/stt_eval/test_metrics.py b/tests/unit/speech/stt_eval/test_metrics.py
index d90b9564bc..3de0b5d271 100644
--- a/tests/unit/speech/stt_eval/test_metrics.py
+++ b/tests/unit/speech/stt_eval/test_metrics.py
@@ -7,9 +7,11 @@ import pytest
from jarvis.speech.stt_eval import metrics as metrics_module
from jarvis.speech.stt_eval.metrics import (
+ WordErrors,
repeatability_error_rate,
switch_error_rate,
word_error_rate,
+ word_errors,
)
@@ -27,6 +29,23 @@ def test_word_error_rate_preserves_legacy_contraction_tokenization() -> None:
assert word_error_rate("can't stop", "can t stop") == 1.0
+ ("reference", "hypothesis", "expected"),
+ [
+ ("one two three", "one wrong three plus", WordErrors(3, 1, 0, 1)),
+ ("one two three", "one three", WordErrors(3, 0, 1, 0)),
+ ("one two", "", WordErrors(2, 0, 2, 0)),
+ ("", "invented words", WordErrors(0, 0, 0, 2)),
+ ("", "", WordErrors(0)),
+ ("Don't delete 35 files", "Don't delete 35 files.", WordErrors(4)),
+ ],
+)
+def test_word_errors_distinguishes_substitution_deletion_and_insertion(
+ reference: str, hypothesis: str, expected: WordErrors,
+) -> None:
+ assert word_errors(reference, hypothesis) == expected
+
+
def test_metrics_import_without_private_tts_eval(
monkeypatch: pytest.MonkeyPatch,
) -> None: