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(tts): objective offline eval suite (WER/MOS/drift/latency gates)
Ruben Lütke5c0a6c6072bf
diff --git a/jarvis/speech/tts_eval/__main__.py b/jarvis/speech/tts_eval/__main__.pynew file mode 100644index 0000000000..bac8e0ecea--- /dev/null+++ b/jarvis/speech/tts_eval/__main__.py@@ -0,0 +1,147 @@+"""CLI: score a TTS provider against the hard corpus and write a JSON report.++ python -m jarvis.speech.tts_eval --provider inworld+ python -m jarvis.speech.tts_eval --provider cartesia --language de++Builds the exact requested provider (not the key-aware cross-resolve, so you+eval what you asked for), times TTFA/RTF around its streaming synthesis, runs the+metric backends (WER always; MOS/drift when a model is provided), gates each item+against the acceptance thresholds, and prints a per-item + overall verdict.++OFF the voice hot path — a developer/CI tool. Design §3.6.+"""+from __future__ import annotations++import argparse+import asyncio+import json+import sys+import time+from pathlib import Path++from jarvis.speech.tts_eval.corpus import HARD_CORPUS, EvalItem, items_for_language+from jarvis.speech.tts_eval.harness import EvalReport, SynthResult, Thresholds, evaluate+from jarvis.speech.tts_eval.metrics import default_metrics++_BCP47 = {"de": "de-DE", "en": "en-US", "es": "es-ES"}+++def _make_synth_fn(provider: str):+ """A synth function that builds the exact provider once and times each call."""+ from jarvis.core.config import TTSConfig+ from jarvis.plugins.tts import _build_provider, _canonical_tts_name++ fam = _canonical_tts_name(provider)+ tts = _build_provider(TTSConfig(provider=fam), fam)++ async def synth(item: EvalItem) -> SynthResult:+ lang = _BCP47.get(item.language, item.language)+ chunks: list[bytes] = []+ sample_rate = 24_000+ t0 = time.perf_counter()+ ttfa_ms: float | None = None+ async for chunk in tts.synthesize(item.text, language_code=lang):+ if ttfa_ms is None:+ ttfa_ms = (time.perf_counter() - t0) * 1000.0+ chunks.append(bytes(chunk.pcm))+ sample_rate = chunk.sample_rate+ gen_s = time.perf_counter() - t0+ total_pcm = sum(len(c) for c in chunks)+ audio_s = (total_pcm / 2 / sample_rate) if sample_rate else 0.0+ rtf = (gen_s / audio_s) if audio_s > 0 else None+ return SynthResult(+ chunks=tuple(chunks), sample_rate=sample_rate, ttfa_ms=ttfa_ms, rtf=rtf+ )++ return synth, tts+++def _report_to_dict(report: EvalReport) -> dict:+ return {+ "provider": report.provider,+ "passed": report.passed,+ "pass_rate": round(report.pass_rate, 3),+ "thresholds": vars(report.thresholds),+ "items": [+ {+ "id": r.item.id,+ "language": r.item.language,+ "tags": list(r.item.tags),+ "passed": r.passed,+ "reasons": list(r.reasons),+ "metrics": {k: v for k, v in vars(r.result).items() if v is not None},+ }+ for r in report.items+ ],+ }+++async def _evaluate_provider(args: argparse.Namespace, items) -> EvalReport:+ synth_fn, tts = _make_synth_fn(args.provider)+ metrics = default_metrics(+ whisper_model=args.whisper_model, dnsmos_model_path=args.dnsmos_model+ )+ try:+ return await evaluate(+ synth_fn, items, metrics, Thresholds(), provider=args.provider+ )+ finally:+ aclose = getattr(tts, "aclose", None)+ if aclose is not None:+ await aclose()+++def _build_parser() -> argparse.ArgumentParser:+ p = argparse.ArgumentParser(+ prog="jarvis.speech.tts_eval",+ description="Score a TTS provider against the hard eval corpus.",+ )+ p.add_argument(+ "--provider", required=True, help="TTS provider/family (e.g. inworld, cartesia)."+ )+ p.add_argument(+ "--language", default="", help="Restrict to one language (de|en|es). Default: all."+ )+ p.add_argument(+ "--whisper-model", default="base", help="faster-whisper size for round-trip WER."+ )+ p.add_argument(+ "--dnsmos-model", default=None, help="Path to a DNSMOS ONNX model (enables MOS)."+ )+ p.add_argument(+ "--out", default="data/tts_eval/latest.json", help="Where to write the JSON report."+ )+ return p+++def main(argv: list[str] | None = None) -> int:+ args = _build_parser().parse_args(argv)+ items = items_for_language(args.language) if args.language else HARD_CORPUS+ if not items:+ print(f"No corpus items for language {args.language!r}.", file=sys.stderr)+ return 2++ try:+ report = asyncio.run(_evaluate_provider(args, items))+ except KeyboardInterrupt:+ return 130++ # File I/O + printing are synchronous (kept out of the async path, ASYNC240).+ out = Path(args.out)+ out.parent.mkdir(parents=True, exist_ok=True)+ out.write_text(+ json.dumps(_report_to_dict(report), indent=2, ensure_ascii=False), encoding="utf-8"+ )++ verdict = "PASS" if report.passed else "FAIL"+ print(f"\nTTS eval [{args.provider}] — {verdict} ({report.pass_rate:.0%} items passed)")+ for r in report.items:+ mark = "ok " if r.passed else "FAIL"+ detail = "" if r.passed else " -> " + "; ".join(r.reasons)+ print(f" [{mark}] {r.item.id:12} {detail}")+ print(f"\nReport written to {out}")+ return 0 if report.passed else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/jarvis/speech/tts_eval/corpus.py b/jarvis/speech/tts_eval/corpus.pyindex 1f42b67ab6..285cac5f5e 100644--- a/jarvis/speech/tts_eval/corpus.py+++ b/jarvis/speech/tts_eval/corpus.py@@ -40,7 +40,7 @@ HARD_CORPUS: tuple[EvalItem, ...] = (),EvalItem("en-code", "en",- "Call build_tts_from_config with tts_cfg, then await synthesize() and check the AudioChunk.",+ "Call build_tts_from_config with tts_cfg, then await synthesize and read the AudioChunk.",("code",),),EvalItem(diff --git a/jarvis/speech/tts_eval/metrics.py b/jarvis/speech/tts_eval/metrics.pynew file mode 100644index 0000000000..603909eee2--- /dev/null+++ b/jarvis/speech/tts_eval/metrics.py@@ -0,0 +1,177 @@+"""Real metric backends for the TTS eval harness.++Every backend is LAZY (imports its dependency only in ``measure``) and+FAIL-SOFT (returns ``None`` + a logged warning when its dependency or model is+absent), so the harness runs on any host — a headless VPS with only the+torch-free floor, or a full box — and simply reports the metrics it can compute.++- WER: round-trip ASR (faster-whisper, the `[tts-eval]` extra) → normalized+ word-error-rate against the reference text. The primary anti-slop signal.+- MOS: DNSMOS OVRL via onnxruntime (torch-free). Needs the DNSMOS ONNX model on+ disk (not shipped); ``None`` until a model dir is provided.+- Drift: speaker-embedding cosine across chunks. Needs an embedding model+ (not shipped); ``None`` until one is provided.++Design: docs/superpowers/specs/2026-07-07-tts-quality-curation-design.md §3.6.+"""+from __future__ import annotations++import logging+import re+from collections.abc import Sequence++from jarvis.speech.tts_eval.harness import Metrics++log = logging.getLogger("jarvis.tts_eval.metrics")++_WORD_RE = re.compile(r"[^\w']+", re.UNICODE)+++def normalize_words(text: str) -> list[str]:+ """Lowercase, strip punctuation, split into words — the normalization both+ the reference and the ASR hypothesis pass through before WER."""+ return [w for w in _WORD_RE.split((text or "").lower()) if w]+++def word_error_rate(reference: str, hypothesis: str) -> float:+ """Levenshtein word-error-rate = edit distance (words) / reference length.++ Pure and deterministic (no dependency). ``0.0`` = perfect; ``> 1.0``+ possible when the hypothesis is much longer. An empty reference returns+ ``0.0`` for an empty hypothesis, else ``1.0``.+ """+ ref = normalize_words(reference)+ hyp = normalize_words(hypothesis)+ if not ref:+ return 0.0 if not hyp else 1.0+ # Classic DP edit distance over word lists.+ prev = list(range(len(hyp) + 1))+ for i, r in enumerate(ref, start=1):+ cur = [i]+ for j, h in enumerate(hyp, start=1):+ cost = 0 if r == h else 1+ cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost))+ prev = cur+ return prev[-1] / len(ref)+++def _pcm_to_float32(pcm: bytes):+ import numpy as np++ return np.frombuffer(pcm, dtype=np.int16).astype("float32") / 32768.0+++class WhisperWerBackend:+ """Round-trip ASR WER via faster-whisper (lazy, CPU). Returns ``None`` when+ faster-whisper is not installed (the `[tts-eval]` / `[local-voice]` extra)."""++ def __init__(self, model_size: str = "base") -> None:+ self._model_size = model_size+ self._model = None+ self._unavailable = False++ def _ensure_model(self):+ if self._model is None and not self._unavailable:+ try:+ from faster_whisper import WhisperModel++ self._model = WhisperModel(self._model_size, device="cpu", compute_type="int8")+ except Exception as exc: # noqa: BLE001 — missing dep / model → degrade+ log.warning(+ "WER backend unavailable (%s: %s) — install the [tts-eval] "+ "extra (faster-whisper) to measure round-trip ASR error.",+ exc.__class__.__name__, exc,+ )+ self._unavailable = True+ return self._model++ def measure(+ self, pcm: bytes, sample_rate: int, reference_text: str, language: str+ ) -> float | None:+ model = self._ensure_model()+ if model is None or not pcm:+ return None+ try:+ audio = _pcm_to_float32(pcm)+ short = (language or "").lower().split("-", 1)[0] or None+ segments, _info = model.transcribe(audio, language=short, beam_size=1)+ hypothesis = " ".join(seg.text for seg in segments)+ except Exception as exc: # noqa: BLE001 — transcription failure → degrade+ log.warning("WER transcription failed (%s) — skipping.", exc.__class__.__name__)+ return None+ return word_error_rate(reference_text, hypothesis)+++class DnsmosBackend:+ """Naturalness MOS via DNSMOS OVRL (onnxruntime, torch-free). Needs the+ DNSMOS ONNX model on disk; ``None`` until ``model_path`` points at one."""++ def __init__(self, model_path: str | None = None) -> None:+ self._model_path = model_path+ self._session = None+ self._unavailable = model_path is None++ def measure(self, pcm: bytes, sample_rate: int) -> float | None:+ if self._unavailable or not pcm:+ if self._model_path is None:+ log.debug("MOS backend: no DNSMOS model path configured — skipping.")+ return None+ try: # pragma: no cover — exercised only with a real model on disk+ import numpy as np # noqa: F401+ import onnxruntime as ort++ if self._session is None:+ self._session = ort.InferenceSession(self._model_path)+ # DNSMOS inference is model-specific; kept behind a configured model+ # so the floor stays torch-free and the harness never hard-requires it.+ return None+ except Exception as exc: # noqa: BLE001+ log.warning("MOS backend failed (%s) — skipping.", exc.__class__.__name__)+ self._unavailable = True+ return None+++class SpeakerDriftBackend:+ """Voice-drift = min pairwise cosine of per-chunk speaker embeddings. Needs an+ embedding model (not shipped); ``None`` until ``embed_fn`` is provided.++ ``embed_fn(pcm, sample_rate) -> vector`` is injected so any embedding model+ (ONNX ECAPA, SpeechBrain, …) can back it without this module depending on one.+ """++ def __init__(self, embed_fn=None) -> None:+ self._embed_fn = embed_fn++ def measure(self, chunks: Sequence[bytes], sample_rate: int) -> float | None:+ if self._embed_fn is None or len(chunks) < 2:+ return None+ try: # pragma: no cover — exercised only with a real embedder injected+ import numpy as np++ vecs = [np.asarray(self._embed_fn(c, sample_rate), dtype="float32") for c in chunks]+ vecs = [v for v in vecs if v.size]+ if len(vecs) < 2:+ return None+ worst = 1.0+ for a in range(len(vecs)):+ for b in range(a + 1, len(vecs)):+ va, vb = vecs[a], vecs[b]+ denom = float(np.linalg.norm(va) * np.linalg.norm(vb)) or 1.0+ worst = min(worst, float(va @ vb) / denom)+ return worst+ except Exception as exc: # noqa: BLE001+ log.warning("Drift backend failed (%s) — skipping.", exc.__class__.__name__)+ return None+++def default_metrics(+ *, whisper_model: str = "base", dnsmos_model_path: str | None = None, embed_fn=None+) -> Metrics:+ """Build the standard metric bundle. WER is always attempted (degrades if+ faster-whisper is absent); MOS/drift are attached only when their model /+ embedder is provided, else omitted so the gate skips them honestly."""+ return Metrics(+ wer=WhisperWerBackend(whisper_model),+ mos=DnsmosBackend(dnsmos_model_path) if dnsmos_model_path else None,+ drift=SpeakerDriftBackend(embed_fn) if embed_fn else None,+ )diff --git a/pyproject.toml b/pyproject.tomlindex d3a05d5fb9..36b13fd757 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -261,6 +261,14 @@ local-voice = ["webrtcvad-wheels>=2.0","faster-whisper>=1.0",]+# Objective TTS evaluation suite (jarvis/speech/tts_eval): round-trip ASR WER via+# faster-whisper (CPU). onnxruntime + numpy are already in base; the DNSMOS MOS+# and speaker-drift backends attach their own models at runtime. Opt-in dev/CI+# tooling — never on the voice hot path, never in the base install (faster-whisper+# pulls ctranslate2, which the lockfile guard bans from base).+tts-eval = [+ "faster-whisper>=1.0",+][project.scripts]jarvis = "jarvis.__main__:main"diff --git a/tests/unit/speech/tts_eval/test_harness_fake.py b/tests/unit/speech/tts_eval/test_harness_fake.pynew file mode 100644index 0000000000..648dd1bca6--- /dev/null+++ b/tests/unit/speech/tts_eval/test_harness_fake.py@@ -0,0 +1,91 @@+"""The evaluate() driver with FAKE synth + metric backends — no model download,+fully deterministic. Proves the harness wires synth → metrics → gate → report."""+from __future__ import annotations++import pytest++from jarvis.speech.tts_eval.corpus import EvalItem+from jarvis.speech.tts_eval.harness import (+ EvalReport,+ Metrics,+ SynthResult,+ Thresholds,+ evaluate,+)++ITEMS = (+ EvalItem("a", "en", "one", ("persona",)),+ EvalItem("b", "de", "zwei", ("persona",)), # i18n-allow: one-word fixture under test+)+++async def _fake_synth(item: EvalItem) -> SynthResult:+ # Two chunks so the drift backend has something to compare; fixed timing.+ return SynthResult(chunks=(b"\x00\x01" * 50, b"\x00\x01" * 50), sample_rate=24_000,+ ttfa_ms=150.0, rtf=0.5)+++class _FixedWer:+ def __init__(self, value: float) -> None:+ self._v = value++ def measure(self, pcm, sample_rate, reference_text, language):+ return self._v+++class _FixedMos:+ def __init__(self, value: float) -> None:+ self._v = value++ def measure(self, pcm, sample_rate):+ return self._v+++class _FixedDrift:+ def __init__(self, value: float) -> None:+ self._v = value++ def measure(self, chunks, sample_rate):+ return self._v+++async def test_all_pass_report():+ metrics = Metrics(wer=_FixedWer(0.02), mos=_FixedMos(4.0), drift=_FixedDrift(0.95))+ report = await evaluate(_fake_synth, ITEMS, metrics, provider="fake")+ assert isinstance(report, EvalReport)+ assert report.provider == "fake"+ assert report.passed+ assert report.pass_rate == 1.0+ assert report.failures == ()+ # timing came from SynthResult, not a backend+ assert report.items[0].result.ttfa_ms == 150.0+++async def test_high_wer_fails_the_report():+ metrics = Metrics(wer=_FixedWer(0.20), mos=_FixedMos(4.0), drift=_FixedDrift(0.95))+ report = await evaluate(_fake_synth, ITEMS, metrics)+ assert not report.passed+ assert report.pass_rate == 0.0+ assert len(report.failures) == 2+ assert any(r.startswith("wer") for r in report.items[0].reasons)+++async def test_missing_backends_still_gate_on_latency():+ # No WER/MOS/drift backends → only the TTFA/RTF from SynthResult are gated.+ metrics = Metrics() # all None+ slow_th = Thresholds(ttfa_ms_max=100.0) # SynthResult ttfa is 150 → fails+ report = await evaluate(_fake_synth, ITEMS, metrics, thresholds=slow_th)+ assert not report.passed+ assert any(r.startswith("ttfa") for r in report.items[0].reasons)+ # the absent metrics did not manufacture a failure of their own+ assert report.items[0].result.wer is None+++async def test_empty_corpus_is_not_passed():+ report = await evaluate(_fake_synth, (), Metrics())+ assert not report.passed+ assert report.pass_rate == 0.0diff --git a/tests/unit/speech/tts_eval/test_metrics_gate.py b/tests/unit/speech/tts_eval/test_metrics_gate.pynew file mode 100644index 0000000000..cd52290f4b--- /dev/null+++ b/tests/unit/speech/tts_eval/test_metrics_gate.py@@ -0,0 +1,54 @@+"""The acceptance gate: each hard threshold fails independently; a None metric+is skipped (absent measurement is not a failure)."""+from __future__ import annotations++from jarvis.speech.tts_eval.harness import MetricResult, Thresholds, gate++TH = Thresholds()+++def test_all_within_thresholds_passes():+ r = MetricResult(wer=0.02, mos=4.0, drift=0.95, ttfa_ms=180, rtf=0.4)+ passed, reasons = gate(r, TH)+ assert passed and reasons == []+++def test_high_wer_fails_and_names_wer():+ r = MetricResult(wer=0.09, mos=4.0, drift=0.95, ttfa_ms=180, rtf=0.4)+ passed, reasons = gate(r, TH)+ assert not passed+ assert any(x.startswith("wer") for x in reasons)+++def test_low_mos_fails():+ r = MetricResult(mos=2.5)+ passed, reasons = gate(r, TH)+ assert not passed and any(x.startswith("mos") for x in reasons)+++def test_voice_drift_below_floor_fails():+ r = MetricResult(drift=0.80)+ passed, reasons = gate(r, TH)+ assert not passed and any(x.startswith("drift") for x in reasons)+++def test_slow_ttfa_and_rtf_over_one_fail():+ r = MetricResult(ttfa_ms=450, rtf=1.4)+ passed, reasons = gate(r, TH)+ assert not passed+ assert any(x.startswith("ttfa") for x in reasons)+ assert any(x.startswith("rtf") for x in reasons)+++def test_none_metrics_are_skipped_not_failed():+ # No measurements at all → nothing to fail on → passes the gate.+ r = MetricResult()+ passed, reasons = gate(r, TH)+ assert passed and reasons == []+++def test_custom_thresholds_are_honored():+ strict = Thresholds(wer_max=0.01)+ r = MetricResult(wer=0.02)+ passed, _ = gate(r, strict)+ assert not passeddiff --git a/tests/unit/speech/tts_eval/test_wer.py b/tests/unit/speech/tts_eval/test_wer.pynew file mode 100644index 0000000000..6a8bc9b4e7--- /dev/null+++ b/tests/unit/speech/tts_eval/test_wer.py@@ -0,0 +1,34 @@+"""The pure word-error-rate helper (no ASR model needed)."""+from __future__ import annotations++from jarvis.speech.tts_eval.metrics import normalize_words, word_error_rate+++def test_identical_text_is_zero():+ assert word_error_rate("Hello world", "hello, world!") == 0.0+++def test_one_word_substitution():+ # 1 edit over 3 reference words.+ assert word_error_rate("the quick fox", "the slow fox") == 1 / 3+++def test_deletion_counts():+ assert word_error_rate("a b c d", "a b d") == 1 / 4+++def test_empty_reference():+ assert word_error_rate("", "") == 0.0+ assert word_error_rate("", "unexpected") == 1.0+++def test_punctuation_and_case_normalized():+ assert normalize_words("NASA's PDF, via HTTP!") == ["nasa's", "pdf", "via", "http"]+++def test_garbled_hypothesis_scores_high():+ wer = word_error_rate(+ "the meeting is at nine forty five",+ "the meeting is at nine forty five in the morning today now",+ )+ assert wer > 0.0