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(voice-engine): P0 measurement bench for the local live voice engine
rubenluetke10-beepdbcbd6d3c50e
diff --git a/jarvis/voice_engine/__init__.py b/jarvis/voice_engine/__init__.pynew file mode 100644index 0000000000..e625b55f21--- /dev/null+++ b/jarvis/voice_engine/__init__.py@@ -0,0 +1,13 @@+"""Jarvis-owned local voice engine (ADR-0037).++This package runs inside the engine's OWN Python environment, not the app's.+It therefore imports nothing from ``jarvis.*`` and only standard-library+modules at import time; every model runtime (onnxruntime, sherpa-onnx, torch,+mlx) is imported lazily by the module that needs it. The app talks to the+engine through a thin provider adapter (``docs/local-live-voice-rebuild.md``).++Phase P0 ships the measurement bench (``python -m jarvis.voice_engine.bench``)+on top of the same component modules the worker will use.+"""++ENGINE_VERSION = "0.1.0"diff --git a/jarvis/voice_engine/audio.py b/jarvis/voice_engine/audio.pynew file mode 100644index 0000000000..b0059b5fba--- /dev/null+++ b/jarvis/voice_engine/audio.py@@ -0,0 +1,89 @@+"""PCM helpers shared by every engine component.++Audio inside the engine is mono float32 in [-1, 1]. The wire format to the app+is PCM16 little-endian; conversion happens only at the edges.+"""++from __future__ import annotations++import wave+from pathlib import Path+from typing import Any++import numpy as np++STT_RATE = 16_000+OUTPUT_RATE = 24_000+++def to_float32(pcm16: bytes | np.ndarray) -> np.ndarray:+ data = np.frombuffer(pcm16, dtype="<i2") if isinstance(pcm16, bytes) else pcm16+ return data.astype(np.float32) / 32768.0+++def to_pcm16(samples: np.ndarray) -> bytes:+ clipped = np.clip(samples, -1.0, 1.0)+ return (clipped * 32767.0).astype("<i2").tobytes()+++def resample(samples: np.ndarray, rate_in: int, rate_out: int) -> np.ndarray:+ """High-quality resampling through soxr, with a band-limited numpy fallback.++ The fallback exists so pure-numpy environments (tests, a broken wheel) still+ work; it low-passes by averaging before linear interpolation, which is+ adequate for VAD and turn detection but not for listening.+ """+ samples = np.asarray(samples, dtype=np.float32)+ if rate_in == rate_out or samples.size == 0:+ return samples+ try:+ import soxr # noqa: PLC0415 - optional, lazily imported++ return soxr.resample(samples, rate_in, rate_out).astype(np.float32)+ except ImportError:+ # soxr is an optional speed/quality upgrade; the fallback below is exact+ # enough for detection models and keeps the engine importable without it.+ pass+ if rate_out < rate_in:+ width = max(1, int(round(rate_in / rate_out)))+ if width > 1:+ kernel = np.ones(width, dtype=np.float32) / width+ samples = np.convolve(samples, kernel, mode="same").astype(np.float32)+ duration = samples.size / rate_in+ count = max(1, int(round(duration * rate_out)))+ positions = np.linspace(0, samples.size - 1, count)+ return np.interp(positions, np.arange(samples.size), samples).astype(np.float32)+++def read_wav(path: Path) -> tuple[np.ndarray, int]:+ with wave.open(str(path), "rb") as handle:+ channels = handle.getnchannels()+ width = handle.getsampwidth()+ rate = handle.getframerate()+ raw = handle.readframes(handle.getnframes())+ if width != 2:+ raise ValueError(f"{path.name}: only 16-bit PCM WAV is supported, got {8 * width}-bit")+ samples = to_float32(raw)+ if channels > 1:+ samples = samples.reshape(-1, channels).mean(axis=1)+ return samples, rate+++def write_wav(path: Path, samples: np.ndarray, rate: int) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ with wave.open(str(path), "wb") as handle:+ handle.setnchannels(1)+ handle.setsampwidth(2)+ handle.setframerate(int(rate))+ handle.writeframes(to_pcm16(np.asarray(samples, dtype=np.float32)))+++def silence(seconds: float, rate: int) -> np.ndarray:+ return np.zeros(max(0, int(round(seconds * rate))), dtype=np.float32)+++def as_float_array(chunk: Any) -> np.ndarray:+ """Normalise a TTS chunk (numpy, list or torch tensor) to float32 numpy."""+ if hasattr(chunk, "detach"):+ chunk = chunk.detach().cpu().numpy()+ return np.asarray(chunk, dtype=np.float32).reshape(-1)diff --git a/jarvis/voice_engine/bench/__init__.py b/jarvis/voice_engine/bench/__init__.pynew file mode 100644index 0000000000..0854b9c10c--- /dev/null+++ b/jarvis/voice_engine/bench/__init__.py@@ -0,0 +1,14 @@+"""Phase P0 measurement bench for the local voice engine.++Run inside the engine's own environment, from a checkout::++ PYTHONPATH=<repo> PYTHONUTF8=1 python -m jarvis.voice_engine.bench env+ ... python -m jarvis.voice_engine.bench stt|tts|turn|llm|tools|e2e|memory+ ... python -m jarvis.voice_engine.bench summary++Every suite writes one JSON file to ``paths.results_dir()`` that records the+machine, the load on it, the configuration and every individual measurement.+Speech input is synthetic (rendered by the engine's own TTS), which makes+transcription accuracy optimistic and turn detection pessimistic; the report+says so next to each number.+"""diff --git a/jarvis/voice_engine/bench/__main__.py b/jarvis/voice_engine/bench/__main__.pynew file mode 100644index 0000000000..d816c688e0--- /dev/null+++ b/jarvis/voice_engine/bench/__main__.py@@ -0,0 +1,137 @@+"""Command line for the P0 bench: ``python -m jarvis.voice_engine.bench <suite>``."""++from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path+from typing import Any++from jarvis.voice_engine.bench import corpus+from jarvis.voice_engine.bench.env import describe, load_snapshot+from jarvis.voice_engine.llm import DEFAULT_BASE_URL+from jarvis.voice_engine.paths import results_dir+++def _languages(value: str) -> list[str]:+ languages = [v.strip() for v in value.split(",") if v.strip()]+ unknown = [v for v in languages if v not in corpus.LANGUAGES]+ if unknown:+ raise argparse.ArgumentTypeError(f"no corpus for {unknown}; have {corpus.LANGUAGES}")+ return languages+++def _list(value: str) -> list[str]:+ return [v.strip() for v in value.split(",") if v.strip()]+++def _options(pairs: list[str]) -> dict[str, Any]:+ options: dict[str, Any] = {}+ for pair in pairs:+ key, _, raw = pair.partition("=")+ try:+ options[key] = json.loads(raw)+ except json.JSONDecodeError:+ options[key] = raw+ return options+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(prog="python -m jarvis.voice_engine.bench")+ sub = parser.add_subparsers(dest="command", required=True)+ sub.add_parser("env", help="describe this machine")+ fetch = sub.add_parser("fetch", help="download the registry models")+ fetch.add_argument("--only", type=_list, default=None)++ def common(p: argparse.ArgumentParser, *, llm: bool = False) -> None:+ p.add_argument("--languages", type=_languages, default=list(corpus.LANGUAGES))+ if llm:+ p.add_argument("--model", required=True)+ p.add_argument("--base-url", default=DEFAULT_BASE_URL)+ p.add_argument("--num-gpu", type=int, default=None,+ help="0 forces the model onto the CPU")++ common(stt := sub.add_parser("stt", help="transcription speed and accuracy"))+ stt.add_argument("--voices", type=_list, default=["piper", "pocket"])+ common(tts := sub.add_parser("tts", help="speech synthesis speed and accuracy"))+ tts.add_argument("--engine", required=True, choices=["piper", "pocket", "qwen3"])+ tts.add_argument("--opt", action="append", default=[], help="backend option key=value")+ regrade = sub.add_parser("regrade", help="add ASR error rates to a TTS report")+ regrade.add_argument("report", type=Path)+ common(turn := sub.add_parser("turn", help="end-of-turn decisions on hesitations"))+ turn.add_argument("--voices", type=_list, default=["piper", "pocket"])+ common(llm := sub.add_parser("llm", help="LLM latency and prefix cache"), llm=True)+ llm.add_argument("--tools", action="store_true", help="declare the bench tool set")+ common(tools := sub.add_parser("tools", help="tool-call accuracy"), llm=True)+ tools.add_argument("--limit", type=int, default=None, help="cases per language")+ common(e2e := sub.add_parser("e2e", help="speech end to first audio"), llm=True)+ e2e.add_argument("--tts", default="pocket", choices=["piper", "pocket", "qwen3"])+ e2e.add_argument("--voice", default="piper", choices=["piper", "pocket"])+ e2e.add_argument("--opt", action="append", default=[], help="TTS option key=value")+ common(memory := sub.add_parser("memory", help="resident memory per component"))+ memory.add_argument("--tts", type=_list, default=["piper", "pocket"])+ sub.add_parser("summary", help="print the latest result of every suite")+ return parser+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ if args.command == "env":+ print(json.dumps(describe(), indent=2))+ return 0+ if args.command == "fetch":+ from jarvis.voice_engine import models # noqa: PLC0415++ for name in args.only or list(models.REGISTRY):+ path, digest = models.fetch(name, progress=_progress)+ print(f"{name}: {path} ({digest[:12]})")+ return 0+ if args.command == "summary":+ from jarvis.voice_engine.bench.report import print_summary # noqa: PLC0415++ print_summary(results_dir())+ return 0+ from jarvis.voice_engine.bench import suites # noqa: PLC0415++ before = load_snapshot()+ if args.command == "regrade":+ print(suites.regrade(args.report))+ return 0+ if args.command == "stt":+ payload = suites.run_stt(args.languages, args.voices)+ elif args.command == "tts":+ payload = suites.run_tts(args.engine, args.languages, _options(args.opt))+ elif args.command == "turn":+ payload = suites.run_turn(args.languages, args.voices)+ elif args.command == "llm":+ payload = suites.run_llm(args.model, args.languages, with_tools=args.tools,+ num_gpu=args.num_gpu, base_url=args.base_url)+ elif args.command == "tools":+ payload = suites.run_tools(args.model, args.languages, limit=args.limit,+ num_gpu=args.num_gpu, base_url=args.base_url)+ elif args.command == "e2e":+ payload = suites.run_e2e(args.model, args.tts, args.languages, voice_kind=args.voice,+ num_gpu=args.num_gpu, base_url=args.base_url,+ tts_options=_options(args.opt))+ elif args.command == "memory":+ payload = suites.run_memory(args.languages, args.tts)+ else: # pragma: no cover - argparse enforces the choices+ raise SystemExit(f"unknown command {args.command}")+ path = suites.write_report(args.command, payload, before)+ headline = {k: v for k, v in payload.items() if k in ("summary", "groups", "load_s")}+ print(json.dumps(headline, indent=2, ensure_ascii=False))+ print(f"report: {path}")+ return 0+++def _progress(name: str, done: int, total: int) -> None:+ percent = 100 * done / total if total else 0+ print(f"\r{name}: {done / 1e6:.0f} / {total / 1e6:.0f} MB ({percent:.0f} %)", end="",+ file=sys.stderr)+ if done >= total:+ print(file=sys.stderr)+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/jarvis/voice_engine/bench/corpus.py b/jarvis/voice_engine/bench/corpus.pynew file mode 100644index 0000000000..17104ed89e--- /dev/null+++ b/jarvis/voice_engine/bench/corpus.py@@ -0,0 +1,113 @@+"""The bench's German and English test material and the tool-call checks."""++from __future__ import annotations++import itertools+import json+from dataclasses import dataclass, field+from functools import cache, lru_cache+from pathlib import Path+from typing import Any++CORPUS_DIR = Path(__file__).with_name("corpus")+LANGUAGES = ("de", "en")+++@cache+def load(language: str) -> dict[str, Any]:+ return json.loads((CORPUS_DIR / f"{language}.json").read_text(encoding="utf-8"))+++@lru_cache(maxsize=1)+def tools() -> list[dict[str, Any]]:+ return json.loads((CORPUS_DIR / "tools.json").read_text(encoding="utf-8"))+++@dataclass(frozen=True, slots=True)+class ToolCase:+ language: str+ utterance: str+ tool: str | None # None: the model must answer without a tool+ accept: tuple[str, ...] = ()+ checks: dict[str, Any] = field(default_factory=dict)+++def _fill(value: Any, slots: dict[str, Any]) -> Any:+ if isinstance(value, str) and value.startswith("{") and value.endswith("}"):+ return slots.get(value[1:-1], value)+ return value+++def tool_cases(language: str) -> list[ToolCase]:+ corpus = load(language)+ cases: list[ToolCase] = []+ for spec in corpus["tool_cases"]:+ slot_names = list(spec.get("slots", {}))+ slot_values = [spec["slots"][name] for name in slot_names]+ combos = list(itertools.product(*slot_values)) if slot_names else [()]+ for template in spec["templates"]:+ for combo in combos:+ spoken = {name: pair[0] for name, pair in zip(slot_names, combo, strict=True)}+ expected = {name: pair[1] for name, pair in zip(slot_names, combo, strict=True)}+ checks = {+ arg: {kind: _fill(raw, expected) for kind, raw in rule.items()}+ for arg, rule in spec.get("check", {}).items()+ }+ cases.append(+ ToolCase(+ language=language,+ utterance=template.format(**spoken),+ tool=spec["tool"],+ accept=tuple(spec.get("accept", ())),+ checks=checks,+ )+ )+ cases.extend(+ ToolCase(language=language, utterance=text, tool=None) for text in corpus["no_tool"]+ )+ return cases+++def _matches(rule: dict[str, Any], actual: Any) -> bool:+ if "equals" in rule:+ expected = rule["equals"]+ try:+ return float(actual) == float(expected)+ except (TypeError, ValueError):+ return str(actual).strip().casefold() == str(expected).strip().casefold()+ if "contains" in rule:+ options = rule["contains"]+ options = options if isinstance(options, list) else [options]+ text = str(actual).casefold()+ return any(str(option).casefold() in text for option in options)+ return True+++def grade(case: ToolCase, calls: list[dict[str, Any]]) -> dict[str, Any]:+ """Score the model's first tool call against the case.++ Verdicts: ``correct`` (right tool, arguments pass), ``wrong_args``,+ ``wrong_tool``, ``missed`` (no call where one was needed) and+ ``unneeded`` (a call where a direct answer was expected).+ """+ if case.tool is None:+ return {"verdict": "correct" if not calls else "unneeded",+ "called": [c.get("name") for c in calls]}+ if not calls:+ return {"verdict": "missed", "called": []}+ first = calls[0]+ name = first.get("name")+ if name != case.tool and name not in case.accept:+ return {"verdict": "wrong_tool", "called": [c.get("name") for c in calls]}+ if name != case.tool:+ return {"verdict": "correct", "called": [name], "note": "accepted alternative"}+ args = first.get("arguments") or {}+ if isinstance(args, str):+ try:+ args = json.loads(args)+ except json.JSONDecodeError:+ return {"verdict": "wrong_args", "called": [name], "detail": "arguments not JSON"}+ failed = [arg for arg, rule in case.checks.items() if not _matches(rule, args.get(arg))]+ if failed:+ return {"verdict": "wrong_args", "called": [name], "failed": failed, "args": args}+ return {"verdict": "correct", "called": [name]}diff --git a/jarvis/voice_engine/bench/corpus/de.json b/jarvis/voice_engine/bench/corpus/de.jsonnew file mode 100644index 0000000000..0f1c9aa260--- /dev/null+++ b/jarvis/voice_engine/bench/corpus/de.json@@ -0,0 +1,92 @@+{+ "language": "de",+ "system_prompt": "Du bist Jarvis, ein Sprachassistent. Antworte auf Deutsch in ein bis zwei kurzen Sätzen. Nutze die Werkzeuge für Aktionen und aktuelle Informationen; behaupte nie, etwas getan zu haben, ohne das passende Werkzeug aufzurufen. Für Unterhaltung und Allgemeinwissen antworte direkt.",+ "roundtrip": [+ "Wie wird das Wetter morgen in München?",+ "Spiel bitte die Playlist Focus auf Spotify.",+ "Erinnere mich heute Abend daran, meine Mutter anzurufen.",+ "Was steht heute noch in meinem Kalender?",+ "Öffne Visual Studio Code und zeig mir das letzte Projekt.",+ "Mach das Licht im Wohnzimmer etwas dunkler.",+ "Schreib eine kurze Nachricht an Anna, dass ich später komme.",+ "Kannst du mir erklären, wie eine Wärmepumpe funktioniert?",+ "Such im Internet nach Rezepten für Linsensuppe.",+ "Wie lange brauche ich mit dem Zug von Berlin nach Hamburg?",+ "Stell den Wecker für morgen früh auf halb sieben.",+ "Was ist der Unterschied zwischen Wetter und Klima?",+ "Bitte fasse die wichtigsten Punkte aus dem Meeting zusammen.",+ "Gibt es in der Nähe ein Café, das jetzt noch geöffnet hat?",+ "Danke, das war sehr hilfreich."+ ],+ "dialog": [+ "Wie weit ist der Mond von der Erde entfernt?",+ "Erklär mir kurz, was ein Schwarzes Loch ist.",+ "Gib mir einen Tipp, wie ich besser einschlafe.",+ "Was ist die Hauptstadt von Australien?",+ "Warum ist der Himmel blau?",+ "Was kann ich heute Abend kochen, wenn ich Nudeln und Tomaten habe?",+ "Wie viele Tage hat ein Schaltjahr?",+ "Erzähl mir einen kurzen Witz.",+ "Was bedeutet das Wort Gemütlichkeit?",+ "Wer hat den Faust geschrieben?"+ ],+ "hesitations": [+ {"segments": ["Ich möchte", "einen Termin am Dienstag eintragen."], "pauses_ms": [700]},+ {"segments": ["Kannst du mir", "die Nummer von meinem Zahnarzt", "heraussuchen?"], "pauses_ms": [600, 900]},+ {"segments": ["Spiel mal", "etwas Entspanntes zum Arbeiten."], "pauses_ms": [800]},+ {"segments": ["Also", "ich brauche eine Erinnerung für morgen früh."], "pauses_ms": [900]},+ {"segments": ["Wie war noch mal", "der Name von dem Restaurant", "in dem wir letzte Woche waren?"], "pauses_ms": [700, 1000]},+ {"segments": ["Schreib Anna", "dass ich heute", "etwas später komme."], "pauses_ms": [600, 800]},+ {"segments": ["Mach das Licht", "im Schlafzimmer aus."], "pauses_ms": [500]},+ {"segments": ["Was meinst du", "soll ich heute laufen gehen oder lieber nicht?"], "pauses_ms": [1100]}+ ],+ "tool_cases": [+ {"tool": "set_timer", "accept": ["set_reminder"], "templates": ["Stell einen Timer auf {n} Minuten.", "Timer für {n} Minuten, bitte.", "Kannst du mir einen Timer von {n} Minuten stellen?", "Starte einen Countdown über {n} Minuten.", "Sag mir in {n} Minuten Bescheid."], "slots": {"n": [["fünf", 5], ["zehn", 10], ["zwanzig", 20], ["fünfundvierzig", 45]]}, "check": {"minutes": {"equals": "{n}"}}},+ {"tool": "set_reminder", "templates": ["Erinnere mich morgen früh daran, {task}.", "Erinnere mich heute Abend daran, {task}.", "Kannst du mich um sechs Uhr daran erinnern, {task}?", "Vergiss nicht, mich am Freitag daran zu erinnern, {task}."], "slots": {"task": [["den Müll rauszubringen", "müll"], ["meine Mutter anzurufen", "mutter"], ["die Rechnung zu bezahlen", "rechnung"], ["das Paket abzuholen", "paket"]]}, "check": {"text": {"contains": "{task}"}}},+ {"tool": "get_weather", "templates": ["Wie wird das Wetter morgen in {city}?", "Regnet es heute in {city}?", "Brauche ich in {city} heute einen Regenschirm?", "Wie warm ist es gerade in {city}?"], "slots": {"city": [["München", "münchen"], ["Hamburg", "hamburg"], ["Köln", "köln"], ["Wien", "wien"]]}, "check": {"location": {"contains": "{city}"}}},+ {"tool": "calendar_list_events", "templates": ["Was steht heute in meinem Kalender?", "Welche Termine habe ich morgen?", "Habe ich am Freitag etwas vor?", "Was ist mein nächster Termin?", "Zeig mir meine Termine für diese Woche.", "Bin ich morgen Nachmittag frei?", "Wann ist mein nächstes Meeting?", "Was habe ich am Montag geplant?"]},+ {"tool": "calendar_create_event", "templates": ["Trag {event} für morgen um zehn Uhr ein.", "Leg einen Termin {event} am Freitag um drei an.", "Plane {event} nächsten Dienstag um neun Uhr ein."], "slots": {"event": [["ein Meeting mit Anna", "anna"], ["den Zahnarzt", "zahnarzt"], ["ein Abendessen mit Tom", "tom"]]}, "check": {"title": {"contains": "{event}"}}},+ {"tool": "open_app", "templates": ["Öffne {app}.", "Starte bitte {app}.", "Mach mal {app} auf.", "Kannst du {app} öffnen?"], "slots": {"app": [["Spotify", "spotify"], ["Visual Studio Code", "code"], ["Excel", "excel"], ["den Taschenrechner", ["rechner", "calc"]], ["Google Chrome", "chrome"]]}, "check": {"name": {"contains": "{app}"}}},+ {"tool": "play_music", "templates": ["Spiel {q}.", "Spiel bitte {q} auf Spotify.", "Ich möchte {q} hören.", "Kannst du {q} abspielen?"], "slots": {"q": [["die Playlist Focus", "focus"], ["Bohemian Rhapsody", "bohemian"], ["etwas von Daft Punk", "daft punk"], ["entspannte Jazzmusik", "jazz"]]}, "check": {"query": {"contains": "{q}"}}},+ {"tool": "set_volume", "templates": ["Stell die Lautstärke auf {n} Prozent.", "Lautstärke auf {n}, bitte.", "Mach die Lautstärke auf {n}.", "Setz den Ton auf {n} Prozent."], "slots": {"n": [["dreißig", 30], ["fünfzig", 50], ["achtzig", 80], ["zehn", 10]]}, "check": {"level": {"equals": "{n}"}}},+ {"tool": "search_web", "templates": ["Such im Internet nach {q}.", "Google mal {q}.", "Finde aktuelle Infos zu {q}.", "Recherchiere bitte {q}."], "slots": {"q": [["dem Fusionsreaktor ITER", "iter"], ["den besten Laufschuhen", "lauf"], ["Rezepten für Linsensuppe", "linsen"], ["dem aktuellen Bitcoin-Kurs", "bitcoin"]]}, "check": {"query": {"contains": "{q}"}}},+ {"tool": "send_email", "templates": ["Schreib eine E-Mail an {who} mit dem Betreff Projektstand.", "Schick {who} eine Mail, dass das Meeting verschoben ist.", "Mail an {who}: Ich bin morgen im Homeoffice."], "slots": {"who": [["Anna", "anna"], ["Thomas", "thomas"], ["das Team", "team"]]}, "check": {"to": {"contains": "{who}"}}},+ {"tool": "home_control", "templates": ["Mach das Licht im {room} an.", "Schalte im {room} das Licht ein."], "slots": {"room": [["Wohnzimmer", "wohnzimmer"], ["Schlafzimmer", "schlafzimmer"], ["Büro", "büro"]]}, "check": {"device": {"contains": "{room}"}, "action": {"equals": "on"}}},+ {"tool": "home_control", "templates": ["Mach das Licht im {room} aus.", "Schalte die Lampe im {room} aus."], "slots": {"room": [["Wohnzimmer", "wohnzimmer"], ["Schlafzimmer", "schlafzimmer"], ["Büro", "büro"]]}, "check": {"device": {"contains": "{room}"}, "action": {"equals": "off"}}},+ {"tool": "home_control", "templates": ["Dimm das Licht im {room} auf dreißig Prozent."], "slots": {"room": [["Wohnzimmer", "wohnzimmer"], ["Schlafzimmer", "schlafzimmer"], ["Büro", "büro"]]}, "check": {"device": {"contains": "{room}"}, "action": {"equals": "dim"}, "level": {"equals": 30}}},+ {"tool": "take_appshot", "templates": ["Mach einen Screenshot von dem Fenster.", "Schau dir mal mein Fenster an.", "Nimm ein Appshot auf.", "Guck mal, was ich gerade offen habe.", "Kannst du dir den Fehler hier auf dem Bildschirm anschauen?", "Was siehst du auf meinem Bildschirm?"]},+ {"tool": "end_call", "templates": ["Tschüss Jarvis.", "Leg auf.", "Beende das Gespräch.", "Okay, das war's, bis später.", "Danke, du kannst jetzt auflegen."]}+ ],+ "no_tool": [+ "Wie geht's dir heute?",+ "Erzähl mir einen Witz.",+ "Was ist die Hauptstadt von Frankreich?",+ "Wie viele Tage hat ein Schaltjahr?",+ "Was bedeutet Photosynthese?",+ "Was ist größer, ein Elefant oder eine Maus?",+ "Kannst du mir das Wort Gemütlichkeit erklären?",+ "Was ist zwölf mal zwölf?",+ "Wer hat den Faust geschrieben?",+ "Gib mir einen Tipp zum Einschlafen.",+ "Was ist der Unterschied zwischen Wetter und Klima?",+ "Wie heißt der höchste Berg der Welt?",+ "Was reimt sich auf Haus?",+ "Wie schreibt man Rhythmus?",+ "Übersetze guten Morgen ins Englische.",+ "Was ist ein Haiku?",+ "Warum fallen im Herbst die Blätter?",+ "Wie viele Beine hat eine Spinne?",+ "Was ist die Wurzel aus einhundertvierundvierzig?",+ "Was ist ein Palindrom?",+ "Nenn mir drei Primzahlen.",+ "Wie lange kocht man ein weiches Ei?",+ "Was ist der Unterschied zwischen einem Virus und einem Bakterium?",+ "Wer hat die Relativitätstheorie entwickelt?",+ "Wie viele Kontinente gibt es?",+ "Was ist eine Metapher?",+ "Welche Farbe entsteht aus Blau und Gelb?",+ "Wie nennt man ein Baby-Känguru?",+ "Was ist schwerer, ein Kilo Federn oder ein Kilo Eisen?",+ "Hilf mir, ein Wort für sehr glücklich zu finden."+ ]+}diff --git a/jarvis/voice_engine/bench/corpus/en.json b/jarvis/voice_engine/bench/corpus/en.jsonnew file mode 100644index 0000000000..374228354e--- /dev/null+++ b/jarvis/voice_engine/bench/corpus/en.json@@ -0,0 +1,92 @@+{+ "language": "en",+ "system_prompt": "You are Jarvis, a voice assistant. Answer in English in one or two short sentences. Use the tools for actions and current information; never claim you did something without calling the matching tool. For conversation and general knowledge, answer directly.",+ "roundtrip": [+ "What will the weather be like tomorrow in Munich?",+ "Please play the Focus playlist on Spotify.",+ "Remind me tonight to call my mother.",+ "What else is on my calendar today?",+ "Open Visual Studio Code and show me the last project.",+ "Make the living room light a little darker.",+ "Send a short message to Anna that I will be late.",+ "Can you explain how a heat pump works?",+ "Search the web for lentil soup recipes.",+ "How long does the train take from Berlin to Hamburg?",+ "Set the alarm for half past six tomorrow morning.",+ "What is the difference between weather and climate?",+ "Please summarize the key points from the meeting.",+ "Is there a cafe nearby that is still open now?",+ "Thanks, that was really helpful."+ ],+ "dialog": [+ "How far is the moon from the earth?",+ "Briefly explain what a black hole is.",+ "Give me a tip for falling asleep faster.",+ "What is the capital of Australia?",+ "Why is the sky blue?",+ "What can I cook tonight if I have pasta and tomatoes?",+ "How many days does a leap year have?",+ "Tell me a short joke.",+ "What does the word serendipity mean?",+ "Who wrote Pride and Prejudice?"+ ],+ "hesitations": [+ {"segments": ["I would like to", "add an appointment on Tuesday."], "pauses_ms": [700]},+ {"segments": ["Can you", "find the number of my dentist", "for me?"], "pauses_ms": [600, 900]},+ {"segments": ["Play something", "relaxing for work."], "pauses_ms": [800]},+ {"segments": ["So", "I need a reminder for tomorrow morning."], "pauses_ms": [900]},+ {"segments": ["What was the name", "of the restaurant", "we went to last week?"], "pauses_ms": [700, 1000]},+ {"segments": ["Tell Anna", "that I will be", "a little late today."], "pauses_ms": [600, 800]},+ {"segments": ["Turn off the light", "in the bedroom."], "pauses_ms": [500]},+ {"segments": ["What do you think", "should I go for a run today or not?"], "pauses_ms": [1100]}+ ],+ "tool_cases": [+ {"tool": "set_timer", "accept": ["set_reminder"], "templates": ["Set a timer for {n} minutes.", "Timer for {n} minutes, please.", "Can you start a {n} minute timer?", "Start a countdown of {n} minutes.", "Let me know in {n} minutes."], "slots": {"n": [["five", 5], ["ten", 10], ["twenty", 20], ["forty-five", 45]]}, "check": {"minutes": {"equals": "{n}"}}},+ {"tool": "set_reminder", "templates": ["Remind me tomorrow morning to {task}.", "Remind me tonight to {task}.", "Can you remind me at six to {task}?", "Don't forget to remind me on Friday to {task}."], "slots": {"task": [["take out the trash", "trash"], ["call my mother", "mother"], ["pay the bill", "bill"], ["pick up the parcel", "parcel"]]}, "check": {"text": {"contains": "{task}"}}},+ {"tool": "get_weather", "templates": ["What will the weather be like tomorrow in {city}?", "Is it raining in {city} today?", "Do I need an umbrella in {city} today?", "How warm is it in {city} right now?"], "slots": {"city": [["Munich", "munich"], ["Hamburg", "hamburg"], ["London", "london"], ["Vienna", "vienna"]]}, "check": {"location": {"contains": "{city}"}}},+ {"tool": "calendar_list_events", "templates": ["What's on my calendar today?", "Which appointments do I have tomorrow?", "Do I have anything on Friday?", "What is my next appointment?", "Show me my events for this week.", "Am I free tomorrow afternoon?", "When is my next meeting?", "What do I have planned on Monday?"]},+ {"tool": "calendar_create_event", "templates": ["Add {event} for tomorrow at ten.", "Create an appointment {event} on Friday at three.", "Schedule {event} next Tuesday at nine."], "slots": {"event": [["a meeting with Anna", "anna"], ["the dentist", "dentist"], ["dinner with Tom", "tom"]]}, "check": {"title": {"contains": "{event}"}}},+ {"tool": "open_app", "templates": ["Open {app}.", "Please start {app}.", "Launch {app}.", "Can you open {app}?"], "slots": {"app": [["Spotify", "spotify"], ["Visual Studio Code", "code"], ["Excel", "excel"], ["the calculator", "calc"], ["Google Chrome", "chrome"]]}, "check": {"name": {"contains": "{app}"}}},+ {"tool": "play_music", "templates": ["Play {q}.", "Please play {q} on Spotify.", "I want to listen to {q}.", "Can you put on {q}?"], "slots": {"q": [["the Focus playlist", "focus"], ["Bohemian Rhapsody", "bohemian"], ["something by Daft Punk", "daft punk"], ["relaxing jazz", "jazz"]]}, "check": {"query": {"contains": "{q}"}}},+ {"tool": "set_volume", "templates": ["Set the volume to {n} percent.", "Volume {n}, please.", "Turn the volume to {n}.", "Put the sound at {n} percent."], "slots": {"n": [["thirty", 30], ["fifty", 50], ["eighty", 80], ["ten", 10]]}, "check": {"level": {"equals": "{n}"}}},+ {"tool": "search_web", "templates": ["Search the web for {q}.", "Google {q}.", "Find current information about {q}.", "Please look up {q}."], "slots": {"q": [["the ITER fusion reactor", "iter"], ["the best running shoes", "running"], ["lentil soup recipes", "lentil"], ["the current bitcoin price", "bitcoin"]]}, "check": {"query": {"contains": "{q}"}}},+ {"tool": "send_email", "templates": ["Write an email to {who} with the subject project status.", "Send {who} a mail that the meeting is postponed.", "Email {who}: I am working from home tomorrow."], "slots": {"who": [["Anna", "anna"], ["Thomas", "thomas"], ["the team", "team"]]}, "check": {"to": {"contains": "{who}"}}},+ {"tool": "home_control", "templates": ["Turn on the light in the {room}.", "Switch the {room} light on."], "slots": {"room": [["living room", "living"], ["bedroom", "bedroom"], ["office", "office"]]}, "check": {"device": {"contains": "{room}"}, "action": {"equals": "on"}}},+ {"tool": "home_control", "templates": ["Turn off the light in the {room}.", "Switch off the lamp in the {room}."], "slots": {"room": [["living room", "living"], ["bedroom", "bedroom"], ["office", "office"]]}, "check": {"device": {"contains": "{room}"}, "action": {"equals": "off"}}},+ {"tool": "home_control", "templates": ["Dim the light in the {room} to thirty percent."], "slots": {"room": [["living room", "living"], ["bedroom", "bedroom"], ["office", "office"]]}, "check": {"device": {"contains": "{room}"}, "action": {"equals": "dim"}, "level": {"equals": 30}}},+ {"tool": "take_appshot", "templates": ["Take a screenshot of this window.", "Have a look at my window.", "Take an appshot.", "Look at what I have open right now.", "Can you look at the error on my screen?", "What do you see on my screen?"]},+ {"tool": "end_call", "templates": ["Bye Jarvis.", "Hang up.", "End the call.", "Okay, that's it, talk later.", "Thanks, you can hang up now."]}+ ],+ "no_tool": [+ "How are you today?",+ "Tell me a joke.",+ "What is the capital of France?",+ "How many days does a leap year have?",+ "What does photosynthesis mean?",+ "Which is bigger, an elephant or a mouse?",+ "Can you explain the word serendipity?",+ "What is twelve times twelve?",+ "Who wrote Hamlet?",+ "Give me a tip for falling asleep.",+ "What is the difference between weather and climate?",+ "What is the highest mountain in the world?",+ "What rhymes with house?",+ "How do you spell rhythm?",+ "Translate good morning into German.",+ "What is a haiku?",+ "Why do leaves fall in autumn?",+ "How many legs does a spider have?",+ "What is the square root of one hundred forty-four?",+ "What is a palindrome?",+ "Name three prime numbers.",+ "How long do you boil a soft egg?",+ "What is the difference between a virus and a bacterium?",+ "Who developed the theory of relativity?",+ "How many continents are there?",+ "What is a metaphor?",+ "What color do blue and yellow make?",+ "What is a baby kangaroo called?",+ "Which is heavier, a kilo of feathers or a kilo of iron?",+ "Help me find a word for very happy."+ ]+}diff --git a/jarvis/voice_engine/bench/corpus/tools.json b/jarvis/voice_engine/bench/corpus/tools.jsonnew file mode 100644index 0000000000..0c144e6a59--- /dev/null+++ b/jarvis/voice_engine/bench/corpus/tools.json@@ -0,0 +1,15 @@+[+ {"type": "function", "function": {"name": "set_timer", "description": "Start a countdown timer.", "parameters": {"type": "object", "properties": {"minutes": {"type": "number", "description": "Duration in minutes"}, "label": {"type": "string"}}, "required": ["minutes"]}}},+ {"type": "function", "function": {"name": "set_reminder", "description": "Remind the user of something at a given time.", "parameters": {"type": "object", "properties": {"text": {"type": "string", "description": "What to remind the user of"}, "time": {"type": "string", "description": "When, as the user said it"}}, "required": ["text", "time"]}}},+ {"type": "function", "function": {"name": "get_weather", "description": "Current weather or forecast for a place.", "parameters": {"type": "object", "properties": {"location": {"type": "string"}, "day": {"type": "string", "description": "today, tomorrow or a weekday"}}, "required": ["location"]}}},+ {"type": "function", "function": {"name": "calendar_list_events", "description": "List the user's calendar events for a day or range.", "parameters": {"type": "object", "properties": {"day": {"type": "string", "description": "today, tomorrow, a weekday or 'this week'"}}, "required": []}}},+ {"type": "function", "function": {"name": "calendar_create_event", "description": "Create a calendar event.", "parameters": {"type": "object", "properties": {"title": {"type": "string"}, "start": {"type": "string", "description": "Start as the user said it"}, "duration_minutes": {"type": "number"}}, "required": ["title", "start"]}}},+ {"type": "function", "function": {"name": "open_app", "description": "Open an application on the user's computer.", "parameters": {"type": "object", "properties": {"name": {"type": "string", "description": "Application name"}}, "required": ["name"]}}},+ {"type": "function", "function": {"name": "play_music", "description": "Play music: a song, artist, playlist or genre.", "parameters": {"type": "object", "properties": {"query": {"type": "string"}, "service": {"type": "string", "description": "Optional streaming service"}}, "required": ["query"]}}},+ {"type": "function", "function": {"name": "set_volume", "description": "Set the system output volume in percent.", "parameters": {"type": "object", "properties": {"level": {"type": "integer", "minimum": 0, "maximum": 100}}, "required": ["level"]}}},+ {"type": "function", "function": {"name": "search_web", "description": "Search the web for current information.", "parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}}},+ {"type": "function", "function": {"name": "send_email", "description": "Send an email from the user's account.", "parameters": {"type": "object", "properties": {"to": {"type": "string"}, "subject": {"type": "string"}, "body": {"type": "string"}}, "required": ["to", "subject"]}}},+ {"type": "function", "function": {"name": "home_control", "description": "Switch or dim smart-home lights and devices.", "parameters": {"type": "object", "properties": {"device": {"type": "string", "description": "Device or room, e.g. 'living room light'"}, "action": {"type": "string", "enum": ["on", "off", "dim"]}, "level": {"type": "integer", "minimum": 0, "maximum": 100}}, "required": ["device", "action"]}}},+ {"type": "function", "function": {"name": "take_appshot", "description": "Capture the user's front window so you can look at it.", "parameters": {"type": "object", "properties": {}, "required": []}}},+ {"type": "function", "function": {"name": "end_call", "description": "End the voice conversation when the user says goodbye or asks to hang up.", "parameters": {"type": "object", "properties": {}, "required": []}}}+]diff --git a/jarvis/voice_engine/bench/env.py b/jarvis/voice_engine/bench/env.pynew file mode 100644index 0000000000..8227719b27--- /dev/null+++ b/jarvis/voice_engine/bench/env.py@@ -0,0 +1,102 @@+"""Describe the machine a bench run happened on, including how busy it was."""++from __future__ import annotations++import os+import platform+import shutil+import subprocess+import sys+from typing import Any++# Same flag as jarvis.core.process_utils.NO_WINDOW_CREATIONFLAGS (AP-1); the+# engine package cannot import jarvis.* because it runs in its own environment.+_NO_WINDOW = 0x08000000 if sys.platform == "win32" else 0+++def _run(argv: list[str], timeout: float = 10.0) -> str:+ try:+ completed = subprocess.run( # noqa: S603 - fixed argv, no shell+ argv,+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=timeout,+ creationflags=_NO_WINDOW,+ check=False,+ )+ except (OSError, subprocess.TimeoutExpired):+ # A missing or hung probe tool means "unknown", which the report shows.+ return ""+ return completed.stdout.strip()+++def cpu_name() -> str:+ if sys.platform == "darwin":+ return _run(["sysctl", "-n", "machdep.cpu.brand_string"]) or platform.processor()+ if sys.platform == "win32":+ out = _run(["powershell", "-NoProfile", "-Command",+ "(Get-CimInstance Win32_Processor | Select-Object -First 1).Name"])+ return out or platform.processor()+ try:+ with open("/proc/cpuinfo", encoding="utf-8") as handle:+ for line in handle:+ if line.lower().startswith("model name"):+ return line.split(":", 1)[1].strip()+ except OSError:+ # Not every Linux exposes cpuinfo (some containers); fall through.+ pass+ return platform.processor() or platform.machine()+++def gpus() -> list[dict[str, str]]:+ if not shutil.which("nvidia-smi"):+ return []+ out = _run(["nvidia-smi", "--query-gpu=name,memory.total,memory.used,driver_version",+ "--format=csv,noheader,nounits"])+ rows = []+ for line in out.splitlines():+ parts = [p.strip() for p in line.split(",")]+ if len(parts) == 4:+ rows.append({"name": parts[0], "memory_total_mib": parts[1],+ "memory_used_mib": parts[2], "driver": parts[3]})+ return rows+++def load_snapshot() -> dict[str, Any]:+ try:+ import psutil # noqa: PLC0415 - optional++ return {+ "cpu_percent": psutil.cpu_percent(interval=1.0),+ "ram_available_gb": round(psutil.virtual_memory().available / 1e9, 1),+ }+ except ImportError:+ return {}+++def describe() -> dict[str, Any]:+ info: dict[str, Any] = {+ "os": platform.platform(),+ "machine": platform.machine(),+ "python": sys.version.split()[0],+ "cpu": cpu_name(),+ "cpu_count": os.cpu_count(),+ "gpus": gpus(),+ }+ try:+ import psutil # noqa: PLC0415 - optional++ info["ram_total_gb"] = round(psutil.virtual_memory().total / 1e9, 1)+ except ImportError:+ # psutil is optional; RAM is simply not reported without it.+ pass+ for module in ("onnxruntime", "sherpa_onnx", "torch", "pocket_tts", "mlx", "soxr", "numpy"):+ try:+ imported = __import__(module)+ info[f"version_{module}"] = getattr(imported, "__version__", "?")+ except ImportError:+ info[f"version_{module}"] = None+ info["load"] = load_snapshot()+ return infodiff --git a/jarvis/voice_engine/bench/report.py b/jarvis/voice_engine/bench/report.pynew file mode 100644index 0000000000..6f386c2f9c--- /dev/null+++ b/jarvis/voice_engine/bench/report.py@@ -0,0 +1,55 @@+"""Print the newest result of every suite and configuration as Markdown."""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any+++def _key(report: dict[str, Any]) -> str:+ suite = report.get("suite", "?")+ parts = [suite]+ for field in ("model", "engine", "tts", "voice", "num_gpu", "with_tools"):+ value = report.get(field)+ if value not in (None, False, ""):+ parts.append(f"{field}={value}")+ return " ".join(parts)+++def latest_reports(root: Path) -> dict[str, dict[str, Any]]:+ newest: dict[str, dict[str, Any]] = {}+ for path in sorted(root.glob("*.json")):+ try:+ report = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ # A half-written or foreign file in the results folder is skipped,+ # not fatal: the summary still covers every readable report.+ continue+ report["_path"] = str(path)+ newest[_key(report)] = report+ return newest+++def _fmt(stats: Any) -> str:+ if isinstance(stats, dict) and "p50" in stats:+ p50, p95 = stats.get("p50"), stats.get("p95")+ if p50 is None:+ return "–"+ return f"{p50:.0f} / {p95:.0f}" if p95 is not None else f"{p50:.0f}"+ return "–" if stats is None else str(stats)+++def print_summary(root: Path) -> None:+ for key, report in sorted(latest_reports(root).items()):+ load = report.get("load_before", {})+ print(f"\n## {key}\n")+ print(f"_{report.get('created_utc')} · CPU load before {load.get('cpu_percent', '?')} %_\n")+ if "summary" in report:+ for name, stats in report["summary"].items():+ print(f"- {name}: {_fmt(stats)}")+ for group, values in (report.get("groups") or {}).items():+ cells = ", ".join(f"{k} {_fmt(v)}" for k, v in values.items())+ print(f"- {group}: {cells}")+ if report.get("load_s"):+ print(f"- load_s: {report['load_s']}")diff --git a/jarvis/voice_engine/bench/speech.py b/jarvis/voice_engine/bench/speech.pynew file mode 100644index 0000000000..202a267862--- /dev/null+++ b/jarvis/voice_engine/bench/speech.py@@ -0,0 +1,147 @@+"""Synthetic user speech and the lazily loaded speech components."""++from __future__ import annotations++import hashlib+import time+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++import numpy as np++from jarvis.voice_engine import models+from jarvis.voice_engine.audio import STT_RATE, read_wav, resample, silence, write_wav+from jarvis.voice_engine.paths import results_dir+++@dataclass+class Components:+ """Loads each component once and records how long loading took."""++ load_s: dict[str, float] = field(default_factory=dict)+ _cache: dict[str, Any] = field(default_factory=dict)++ def _load(self, key: str, factory: Any) -> Any:+ if key not in self._cache:+ started = time.perf_counter()+ self._cache[key] = factory()+ self.load_s[key] = round(time.perf_counter() - started, 3)+ return self._cache[key]++ def stt(self) -> Any:+ from jarvis.voice_engine.stt import ParakeetStt # noqa: PLC0415++ return self._load(+ "stt", lambda: ParakeetStt(models.model_path("parakeet-tdt-0.6b-v3-int8"))+ )++ def vad(self) -> Any:+ from jarvis.voice_engine.vad import SileroVad # noqa: PLC0415++ return self._load("vad", lambda: SileroVad(models.model_path("silero-vad-v6")))++ def turn(self) -> Any:+ from jarvis.voice_engine.turn import SmartTurn # noqa: PLC0415++ return self._load("turn", lambda: SmartTurn(models.model_path("smart-turn-v3.2")))++ def tts(self, kind: str, language: str, **options: Any) -> Any:+ from jarvis.voice_engine.tts import load_tts # noqa: PLC0415++ key = f"tts:{kind}:{language}:{sorted(options.items())}"+ return self._load(key, lambda: load_tts(kind, language, **options))+++class UserVoice:+ """Renders corpus text as 16 kHz 'user' speech, cached on disk."""++ def __init__(self, components: Components, kind: str = "piper") -> None:+ self._components = components+ self.kind = kind+ self._root = results_dir() / "speech-cache" / kind++ def render(self, text: str, language: str, *, pad_s: float = 0.2) -> np.ndarray:+ """Speech for ``text`` with ``pad_s`` of silence on both sides.++ The padding stands in for the VAD pre-roll and the trailing pause a+ real microphone segment has.+ """+ digest = hashlib.sha256(f"{language}|{text}".encode()).hexdigest()[:16]+ path = self._root / language / f"{digest}.wav"+ if path.exists():+ audio, rate = read_wav(path)+ audio16 = resample(audio, rate, STT_RATE)+ else:+ tts = self._components.tts(self.kind, language)+ audio = np.concatenate(list(tts.stream(text)))+ audio16 = resample(audio, tts.sample_rate, STT_RATE)+ write_wav(path, audio16, STT_RATE)+ if pad_s <= 0:+ return audio16+ pad = silence(pad_s, STT_RATE)+ return np.concatenate([pad, audio16, pad])++ def render_with_pauses(+ self, segments: list[str], pauses_ms: list[int], language: str, tail_s: float = 1.2+ ) -> tuple[np.ndarray, list[float]]:+ """One continuous utterance with silence inserted at the segment borders.++ Rendering each segment separately gives every piece a sentence-final+ melody, and the turn detector then (rightly) hears a finished sentence+ at every pause. Rendering the whole sentence once and splicing silence+ in at the quietest point near each border keeps the mid-sentence+ melody a hesitating speaker has. Returns the audio and the end time of+ every segment.+ """+ audio = trim_silence(self.render(" ".join(segments), language, pad_s=0.0))+ total_chars = sum(len(s) + 1 for s in segments)+ cuts: list[int] = []+ consumed = 0+ for segment in segments[:-1]:+ consumed += len(segment) + 1+ cuts.append(_quietest_near(audio, int(audio.size * consumed / total_chars)))+ lead = silence(0.3, STT_RATE)+ parts: list[np.ndarray] = [lead]+ ends: list[float] = []+ elapsed = lead.size / STT_RATE+ start = 0+ for index, cut in enumerate([*cuts, audio.size]):+ piece = audio[start:cut]+ parts.append(piece)+ elapsed += piece.size / STT_RATE+ ends.append(elapsed)+ if index < len(pauses_ms):+ pause = silence(pauses_ms[index] / 1000.0, STT_RATE)+ parts.append(pause)+ elapsed += pause.size / STT_RATE+ start = cut+ parts.append(silence(tail_s, STT_RATE))+ return np.concatenate(parts), ends+++def _quietest_near(audio: np.ndarray, center: int, window_s: float = 0.15) -> int:+ """Sample index of the lowest-energy 10 ms frame within ``window_s`` of ``center``."""+ frame = int(0.01 * STT_RATE)+ low = max(0, center - int(window_s * STT_RATE))+ high = min(audio.size - frame, center + int(window_s * STT_RATE))+ if high <= low:+ return center+ starts = np.arange(low, high, frame // 2)+ energy = [float(np.mean(audio[s : s + frame] ** 2)) for s in starts]+ return int(starts[int(np.argmin(energy))] + frame // 2)+++def trim_silence(audio: np.ndarray, threshold: float = 0.01) -> np.ndarray:+ voiced = np.flatnonzero(np.abs(audio) > threshold)+ if voiced.size == 0:+ return audio+ start = max(0, voiced[0] - int(0.02 * STT_RATE))+ end = min(audio.size, voiced[-1] + int(0.05 * STT_RATE))+ return audio[start:end]+++def save_sample(name: str, audio: np.ndarray, rate: int) -> Path:+ path = results_dir() / "samples" / f"{name}.wav"+ write_wav(path, audio, rate)+ return pathdiff --git a/jarvis/voice_engine/bench/stats.py b/jarvis/voice_engine/bench/stats.pynew file mode 100644index 0000000000..6facae2811--- /dev/null+++ b/jarvis/voice_engine/bench/stats.py@@ -0,0 +1,62 @@+"""Small, dependency-free statistics for bench reports."""++from __future__ import annotations++import math+import re+import unicodedata+from collections.abc import Iterable, Sequence++_PUNCT = re.compile(r"[^\w\s]", re.UNICODE)+++def percentile(values: Iterable[float], q: float) -> float | None:+ data = sorted(v for v in values if v is not None and not math.isnan(v))+ if not data:+ return None+ if len(data) == 1:+ return data[0]+ rank = (len(data) - 1) * q / 100.0+ low = math.floor(rank)+ high = math.ceil(rank)+ if low == high:+ return data[low]+ return data[low] + (data[high] - data[low]) * (rank - low)+++def summary(values: Iterable[float]) -> dict[str, float | int | None]:+ data = [v for v in values if v is not None]+ return {+ "n": len(data),+ "p50": percentile(data, 50),+ "p95": percentile(data, 95),+ "max": max(data) if data else None,+ }+++def normalize_text(text: str) -> str:+ text = unicodedata.normalize("NFC", text).casefold()+ text = _PUNCT.sub(" ", text)+ return " ".join(text.split())+++def _edit_distance(a: Sequence[str], b: Sequence[str]) -> int:+ previous = list(range(len(b) + 1))+ for i, left in enumerate(a, 1):+ current = [i]+ for j, right in enumerate(b, 1):+ substitution = previous[j - 1] + (left != right)+ current.append(min(previous[j] + 1, current[j - 1] + 1, substitution))+ previous = current+ return previous[-1]+++def error_rates(reference: str, hypothesis: str) -> tuple[float, float]:+ """(character error rate, word error rate) after normalisation."""+ ref = normalize_text(reference)+ hyp = normalize_text(hypothesis)+ ref_chars = ref.replace(" ", "")+ hyp_chars = hyp.replace(" ", "")+ cer = _edit_distance(ref_chars, hyp_chars) / max(1, len(ref_chars))+ wer = _edit_distance(ref.split(), hyp.split()) / max(1, len(ref.split()))+ return cer, werdiff --git a/jarvis/voice_engine/bench/suites.py b/jarvis/voice_engine/bench/suites.pynew file mode 100644index 0000000000..45bf940001--- /dev/null+++ b/jarvis/voice_engine/bench/suites.py@@ -0,0 +1,494 @@+"""Bench suites for the measurements in section 8 of the rebuild plan.++Each suite returns a JSON-serialisable payload; ``write_report`` stores it+together with the machine description and the load before and after the run.+"""++from __future__ import annotations++import concurrent.futures as cf+import json+import threading+import time+from collections.abc import Callable+from datetime import UTC, datetime+from pathlib import Path+from typing import Any++import numpy as np++from jarvis.voice_engine.audio import STT_RATE, resample, silence+from jarvis.voice_engine.bench import corpus+from jarvis.voice_engine.bench.env import describe, gpus, load_snapshot+from jarvis.voice_engine.bench.speech import Components, UserVoice, save_sample+from jarvis.voice_engine.bench.stats import error_rates, summary+from jarvis.voice_engine.llm import OllamaChat+from jarvis.voice_engine.paths import results_dir+from jarvis.voice_engine.vad import FRAME_SAMPLES, Endpointer++SILENCE_MS = 200+INCOMPLETE_WAIT_MS = 1000+COMPLETE_THRESHOLD = 0.5+++def write_report(suite: str, payload: dict[str, Any], load_before: dict[str, Any]) -> Path:+ stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")+ path = results_dir() / f"{suite}-{stamp}.json"+ path.parent.mkdir(parents=True, exist_ok=True)+ report = {+ "suite": suite,+ "created_utc": stamp,+ "machine": describe(),+ "load_before": load_before,+ **payload,+ }+ path.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")+ return path+++def _timed(fn: Callable[..., Any], *args: Any) -> tuple[Any, float]:+ started = time.perf_counter()+ value = fn(*args)+ return value, (time.perf_counter() - started) * 1000.0+++def _ms(seconds: float | None) -> float | None:+ return None if seconds is None else round(seconds * 1000.0, 1)+++# ── STT ──────────────────────────────────────────────────────────────────────+++def run_stt(languages: list[str], voices: list[str], repeats: int = 2) -> dict[str, Any]:+ components = Components()+ stt = components.stt()+ items: list[dict[str, Any]] = []+ for kind in voices:+ voice = UserVoice(components, kind)+ for language in languages:+ texts = corpus.load(language)["roundtrip"]+ stt.transcribe(voice.render(texts[0], language)) # warm-up, not recorded+ for text in texts:+ audio = voice.render(text, language)+ times = []+ hypothesis = ""+ for _ in range(repeats):+ hypothesis, elapsed = _timed(stt.transcribe, audio)+ times.append(elapsed)+ cer, wer = error_rates(text, hypothesis)+ items.append({+ "voice": kind, "language": language, "text": text,+ "hypothesis": hypothesis, "audio_s": round(audio.size / STT_RATE, 2),+ "stt_ms": round(min(times), 1), "cer": round(cer, 4), "wer": round(wer, 4),+ })+ groups: dict[str, Any] = {}+ for kind in voices:+ for language in languages:+ rows = [i for i in items if i["voice"] == kind and i["language"] == language]+ groups[f"{kind}/{language}"] = {+ "stt_ms": summary(r["stt_ms"] for r in rows),+ "rtfx_p50": round(+ float(np.median([r["audio_s"] * 1000 / r["stt_ms"] for r in rows])), 1+ ),+ "cer_mean": round(float(np.mean([r["cer"] for r in rows])), 4),+ "wer_mean": round(float(np.mean([r["wer"] for r in rows])), 4),+ }+ return {"config": {"voices": voices, "repeats": repeats}, "load_s": components.load_s,+ "groups": groups, "items": items}+++# ── TTS ──────────────────────────────────────────────────────────────────────+++def run_tts(engine: str, languages: list[str], options: dict[str, Any]) -> dict[str, Any]:+ components = Components()+ items: list[dict[str, Any]] = []+ gpu_before = gpus()+ gpu_after_load: dict[str, Any] = {}+ for language in languages:+ tts = components.tts(engine, language, **options)+ gpu_after_load[language] = gpus()+ warm = getattr(tts, "warmup", None)+ if callable(warm):+ warm()+ list(tts.stream("Hallo." if language == "de" else "Hello.")) # warm-up, not recorded+ for index, text in enumerate(corpus.load(language)["roundtrip"]):+ started = time.perf_counter()+ first: float | None = None+ chunks = []+ for chunk in tts.stream(text):+ if first is None:+ first = time.perf_counter() - started+ chunks.append(chunk)+ total = time.perf_counter() - started+ audio = np.concatenate(chunks) if chunks else np.zeros(0, dtype=np.float32)+ duration = audio.size / tts.sample_rate+ sample = save_sample(f"{tts.name}/{language}/{index:02d}", audio, tts.sample_rate)+ items.append({+ "language": language, "text": text, "sample": str(sample),+ "ttfa_ms": _ms(first), "synth_s": round(total, 3),+ "audio_s": round(duration, 2),+ "speed_x_realtime": round(duration / total, 2) if total > 0 else None,+ })+ try:+ _regrade_items(items, components)+ except ImportError:+ # This environment has no transcription runtime (e.g. a CUDA-only TTS+ # venv); ``bench regrade`` fills the error rates in from the CPU venv.+ pass+ return {"engine": engine, "options": options, "load_s": components.load_s,+ "gpu_before": gpu_before, "gpu_after_load": gpu_after_load,+ "torch_cuda_peak_mb": _torch_cuda_peak_mb(),+ "groups": _tts_groups(items, languages), "items": items}+++def _torch_cuda_peak_mb() -> float | None:+ import sys # noqa: PLC0415++ torch = sys.modules.get("torch")+ if torch is None or not torch.cuda.is_available():+ return None+ return round(torch.cuda.max_memory_reserved() / 1e6, 1)+++def _regrade_items(items: list[dict[str, Any]], components: Components) -> None:+ from jarvis.voice_engine.audio import read_wav # noqa: PLC0415++ stt = components.stt()+ pad = silence(0.2, STT_RATE)+ for item in items:+ audio, rate = read_wav(Path(item["sample"]))+ # The live engine hands the recogniser a VAD segment with pre-roll and+ # trailing silence; raw TTS output starts on the first phoneme, which+ # makes Parakeet drop or clip the first word.+ hypothesis = stt.transcribe(np.concatenate([pad, resample(audio, rate, STT_RATE), pad]))+ cer, wer = error_rates(item["text"], hypothesis)+ item.update({"asr": hypothesis, "cer": round(cer, 4), "wer": round(wer, 4)})+++def _tts_groups(items: list[dict[str, Any]], languages: list[str]) -> dict[str, Any]:+ groups = {}+ for language in languages:+ rows = [i for i in items if i["language"] == language]+ graded = [r["cer"] for r in rows if r.get("cer") is not None]+ groups[language] = {+ "ttfa_ms": summary(r["ttfa_ms"] for r in rows),+ "speed_x_realtime_p50": float(np.median([r["speed_x_realtime"] for r in rows])),+ "cer_mean": round(float(np.mean(graded)), 4) if graded else None,+ }+ return groups+++def regrade(report_path: Path) -> Path:+ report = json.loads(report_path.read_text(encoding="utf-8"))+ components = Components()+ _regrade_items(report["items"], components)+ languages = sorted({i["language"] for i in report["items"]})+ report["groups"] = _tts_groups(report["items"], languages)+ report_path.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")+ return report_path+++# ── Turn-taking ──────────────────────────────────────────────────────────────+++def _silence_events(vad: Any, audio: np.ndarray) -> list[tuple[float, float]]:+ """(silence_start time, last voiced time) for every pause the endpointer reports."""+ vad.reset()+ endpointer = Endpointer(silence_ms=SILENCE_MS)+ last_voiced = 0.0+ events = []+ for start in range(0, audio.size - FRAME_SAMPLES + 1, FRAME_SAMPLES):+ probability = vad(audio[start : start + FRAME_SAMPLES])+ now = (start + FRAME_SAMPLES) / STT_RATE+ if probability >= endpointer.on_threshold:+ last_voiced = now+ event = endpointer.feed(probability)+ if event is not None and event.kind == "silence_start":+ events.append((now, last_voiced))+ return events+++def run_turn(languages: list[str], voices: list[str]) -> dict[str, Any]:+ components = Components()+ vad = components.vad()+ turn = components.turn()+ items: list[dict[str, Any]] = []+ for kind in voices:+ voice = UserVoice(components, kind)+ for language in languages:+ for case in corpus.load(language)["hesitations"]:+ audio, ends = voice.render_with_pauses(+ case["segments"], case["pauses_ms"], language+ )+ for at, last_voiced in _silence_events(vad, audio):+ probability, elapsed = _timed(turn.probability, audio[: int(at * STT_RATE)])+ items.append({+ "voice": kind, "language": language,+ "utterance": " … ".join(case["segments"]),+ "at_s": round(at, 3), "final": last_voiced >= ends[-1] - 0.05,+ "p_complete": round(probability, 3), "turn_ms": round(elapsed, 1),+ })+ groups = {}+ for kind in voices:+ for language in languages:+ rows = [i for i in items if i["voice"] == kind and i["language"] == language]+ inner = [r for r in rows if not r["final"]]+ final = [r for r in rows if r["final"]]+ groups[f"{kind}/{language}"] = {+ "pause_events": len(inner),+ "cut_rate": round(+ sum(r["p_complete"] >= COMPLETE_THRESHOLD for r in inner) / len(inner), 3+ ) if inner else None,+ "end_events": len(final),+ "end_complete_rate": round(+ sum(r["p_complete"] >= COMPLETE_THRESHOLD for r in final) / len(final), 3+ ) if final else None,+ "turn_ms": summary(r["turn_ms"] for r in rows),+ }+ return {"config": {"silence_ms": SILENCE_MS, "threshold": COMPLETE_THRESHOLD},+ "load_s": components.load_s, "groups": groups, "items": items}+++# ── LLM ──────────────────────────────────────────────────────────────────────++_FOLLOW_UP = {+ "de": "Und das bitte noch kürzer.", # i18n-allow: German speech-input fixture+ "en": "Say that even shorter, please.",+}+++def run_llm(model: str, languages: list[str], *, with_tools: bool, num_gpu: int | None,+ base_url: str) -> dict[str, Any]:+ llm = OllamaChat(model, base_url=base_url, num_gpu=num_gpu)+ llm.unload()+ cold_load_s = llm.warm()+ tools = corpus.tools() if with_tools else None+ items: list[dict[str, Any]] = []+ for language in languages:+ system = {"role": "system", "content": corpus.load(language)["system_prompt"]}+ for question in corpus.load(language)["dialog"]:+ first = llm.chat([system, {"role": "user", "content": question}], tools=tools)+ history = [system, {"role": "user", "content": question},+ {"role": "assistant", "content": first.text},+ {"role": "user", "content": _FOLLOW_UP[language]}]+ second = llm.chat(history, tools=tools)+ items.append({+ "language": language, "question": question, "answer": first.text,+ "error": first.error or second.error,+ "ttft_ms": _ms(first.t_first_token), "first_clause_ms": _ms(first.t_first_clause),+ "done_ms": _ms(first.t_done), "prompt_tokens": first.prompt_tokens,+ "prefill_tps": round(first.prefill_tps), "gen_tps": round(first.generation_tps),+ "turn2_ttft_ms": _ms(second.t_first_token),+ "turn2_first_clause_ms": _ms(second.t_first_clause),+ "turn2_prompt_tokens": second.prompt_tokens,+ "turn2_cached_tokens": second.prompt_cached_tokens,+ "tool_calls": first.tool_calls,+ })+ return {+ "model": model, "with_tools": with_tools, "num_gpu": num_gpu,+ "cold_load_s": round(cold_load_s, 2),+ "ollama_ps": llm.loaded_models(),+ "summary": {+ "ttft_ms": summary(i["ttft_ms"] for i in items),+ "first_clause_ms": summary(i["first_clause_ms"] for i in items),+ "turn2_first_clause_ms": summary(i["turn2_first_clause_ms"] for i in items),+ "gen_tps_p50": float(np.median([i["gen_tps"] for i in items])),+ "prefill_tps_p50": float(np.median([i["prefill_tps"] for i in items])),+ },+ "items": items,+ }+++# ── Tool calls ───────────────────────────────────────────────────────────────+++def run_tools(model: str, languages: list[str], *, limit: int | None, num_gpu: int | None,+ base_url: str) -> dict[str, Any]:+ llm = OllamaChat(model, base_url=base_url, num_gpu=num_gpu, temperature=0.0)+ llm.warm()+ tools = corpus.tools()+ items: list[dict[str, Any]] = []+ for language in languages:+ system = {"role": "system", "content": corpus.load(language)["system_prompt"]}+ cases = corpus.tool_cases(language)+ if limit:+ step = max(1, len(cases) // limit)+ cases = cases[::step][:limit]+ for case in cases:+ result = llm.chat([system, {"role": "user", "content": case.utterance}], tools=tools)+ verdict = corpus.grade(case, result.tool_calls)+ items.append({+ "language": language, "utterance": case.utterance, "expected": case.tool,+ "calls": result.tool_calls, "text": result.text[:200], "error": result.error,+ "decision_ms": _ms(result.t_done), **verdict,+ })+ groups = {}+ for language in languages:+ rows = [i for i in items if i["language"] == language]+ needed = [r for r in rows if r["expected"] is not None]+ direct = [r for r in rows if r["expected"] is None]+ groups[language] = {+ "cases": len(rows),+ "accuracy": round(sum(r["verdict"] == "correct" for r in rows) / len(rows), 3),+ "tool_accuracy": round(+ sum(r["verdict"] == "correct" for r in needed) / len(needed), 3+ ) if needed else None,+ "missed": sum(r["verdict"] == "missed" for r in rows),+ "wrong_tool": sum(r["verdict"] == "wrong_tool" for r in rows),+ "wrong_args": sum(r["verdict"] == "wrong_args" for r in rows),+ "unneeded": sum(r["verdict"] == "unneeded" for r in direct),+ "decision_ms": summary(r["decision_ms"] for r in rows),+ }+ return {"model": model, "num_gpu": num_gpu, "groups": groups, "items": items}+++# ── End to end ───────────────────────────────────────────────────────────────++_FAKE_RESULTS = {+ "set_timer": {"success": True, "output": "Timer started."},+ "set_reminder": {"success": True, "output": "Reminder saved."},+ "get_weather": {"success": True, "output": {"condition": "light rain", "temp_c": 14}},+ "calendar_list_events": {"success": True, "output": [{"title": "Team sync", "start": "10:00"}]},+ "calendar_create_event": {"success": True, "output": "Event created."},+ "open_app": {"success": True, "output": "Opened."},+ "play_music": {"success": True, "output": "Playing."},+ "set_volume": {"success": True, "output": "Volume set."},+ "search_web": {"success": True, "output": "ITER is scheduled to start operation in the 2030s."},+ "send_email": {"success": True, "output": "Sent."},+ "home_control": {"success": True, "output": "Done."},+ "take_appshot": {"success": True, "output": "A code editor showing a Python file."},+ "end_call": {"success": True, "output": "Ending."},+}+++def _first_audio(tts: Any, text: str) -> float:+ stop = threading.Event()+ started = time.perf_counter()+ stream = tts.stream(text, stop=stop)+ try:+ next(stream)+ except StopIteration:+ # The engine produced no audio for this clause; time to "nothing" is+ # still the honest latency of the attempt.+ pass+ elapsed = (time.perf_counter() - started) * 1000.0+ stop.set()+ for _ in stream:+ pass+ return elapsed+++def run_e2e(model: str, tts_kind: str, languages: list[str], *, voice_kind: str,+ num_gpu: int | None, base_url: str, tts_options: dict[str, Any]) -> dict[str, Any]:+ components = Components()+ vad, turn, stt = components.vad(), components.turn(), components.stt()+ llm = OllamaChat(model, base_url=base_url, num_gpu=num_gpu)+ llm.warm()+ tools = corpus.tools()+ voice = UserVoice(components, voice_kind)+ pool = cf.ThreadPoolExecutor(max_workers=2)+ items: list[dict[str, Any]] = []+ for language in languages:+ tts = components.tts(tts_kind, language, **tts_options)+ list(tts.stream("Hallo." if language == "de" else "Hello.")) # warm-up+ system = {"role": "system", "content": corpus.load(language)["system_prompt"]}+ texts = [(t, "dialog") for t in corpus.load(language)["dialog"]]+ seen: set[str] = set()+ for case in corpus.tool_cases(language):+ if case.tool and case.tool not in seen:+ seen.add(case.tool)+ texts.append((case.utterance, "tool"))+ for text, kind in texts:+ audio = np.concatenate([voice.render(text, language), silence(1.0, STT_RATE)])+ events = _silence_events(vad, audio)+ if not events:+ items.append({"language": language, "text": text, "error": "no end of speech"})+ continue+ at, last_voiced = events[-1]+ turn_future = pool.submit(_timed, turn.probability, audio[: int(at * STT_RATE)])+ stt_future = pool.submit(+ _timed, stt.transcribe, audio[: int((last_voiced + 0.1) * STT_RATE)]+ )+ probability, turn_ms = turn_future.result()+ transcript, stt_ms = stt_future.result()+ wait_ms = (at - last_voiced) * 1000.0+ decision_ms = wait_ms + max(turn_ms, stt_ms)+ if probability < COMPLETE_THRESHOLD:+ decision_ms += INCOMPLETE_WAIT_MS+ messages = [system, {"role": "user", "content": transcript}]+ first = llm.chat(messages, tools=tools)+ tool_round_ms = 0.0+ reply = first+ if first.tool_calls:+ call = first.tool_calls[0]+ tool_round_ms = first.t_done * 1000.0+ messages += [+ {"role": "assistant", "content": first.text,+ "tool_calls": [{"function": {"name": call["name"],+ "arguments": call["arguments"]}}]},+ {"role": "tool", "tool_name": call["name"],+ "content": json.dumps(_FAKE_RESULTS.get(call["name"], {"success": True}))},+ ]+ reply = llm.chat(messages, tools=tools)+ clause = reply.clauses[0] if reply.clauses else reply.text.strip()+ reply_ms = tool_round_ms + 1000.0 * (reply.t_first_clause or reply.t_done)+ tts_ms = _first_audio(tts, clause) if clause else 0.0+ items.append({+ "language": language, "kind": kind, "text": text, "transcript": transcript,+ "tool_calls": [c["name"] for c in first.tool_calls], "first_clause": clause,+ "wait_ms": round(wait_ms, 1), "turn_ms": round(turn_ms, 1),+ "stt_ms": round(stt_ms, 1), "p_complete": round(probability, 3),+ "decision_ms": round(decision_ms, 1), "tool_round_ms": round(tool_round_ms, 1),+ "reply_first_clause_ms": round(reply_ms, 1), "tts_first_audio_ms": round(tts_ms, 1),+ "e2e_ms": round(decision_ms + reply_ms + tts_ms, 1),+ })+ pool.shutdown()+ done = [i for i in items if "e2e_ms" in i]+ return {+ "model": model, "tts": tts_kind, "tts_options": tts_options, "voice": voice_kind,+ "num_gpu": num_gpu, "load_s": components.load_s,+ "summary": {+ "e2e_ms_all": summary(i["e2e_ms"] for i in done),+ "e2e_ms_dialog": summary(i["e2e_ms"] for i in done if i["kind"] == "dialog"),+ "e2e_ms_tool": summary(i["e2e_ms"] for i in done if i["kind"] == "tool"),+ "decision_ms": summary(i["decision_ms"] for i in done),+ "stt_ms": summary(i["stt_ms"] for i in done),+ "turn_ms": summary(i["turn_ms"] for i in done),+ "reply_first_clause_ms": summary(i["reply_first_clause_ms"] for i in done),+ "tts_first_audio_ms": summary(i["tts_first_audio_ms"] for i in done),+ "incomplete_verdicts": sum(i["p_complete"] < COMPLETE_THRESHOLD for i in done),+ },+ "items": items,+ }+++# ── Memory ───────────────────────────────────────────────────────────────────+++def run_memory(languages: list[str], tts_kinds: list[str]) -> dict[str, Any]:+ import psutil # noqa: PLC0415 - bench-only dependency++ process = psutil.Process()+ components = Components()+ steps = []+ loaders: list[tuple[str, Callable[[], Any]]] = [+ ("vad", components.vad), ("turn", components.turn), ("stt", components.stt),+ ]+ for kind in tts_kinds:+ for language in languages:+ loaders.append((f"tts:{kind}:{language}",+ lambda k=kind, lang=language: components.tts(k, lang)))+ baseline = process.memory_info().rss+ for name, loader in loaders:+ before = process.memory_info().rss+ started = time.perf_counter()+ loader()+ steps.append({+ "component": name, "load_s": round(time.perf_counter() - started, 2),+ "rss_delta_mb": round((process.memory_info().rss - before) / 1e6, 1),+ })+ total_mb = round((process.memory_info().rss - baseline) / 1e6, 1)+ return {"languages": languages, "tts": tts_kinds, "steps": steps,+ "resident_total_mb": total_mb, "gpus": describe()["gpus"],+ "load_snapshot": load_snapshot()}diff --git a/jarvis/voice_engine/chunker.py b/jarvis/voice_engine/chunker.pynew file mode 100644index 0000000000..f767cb4911--- /dev/null+++ b/jarvis/voice_engine/chunker.py@@ -0,0 +1,82 @@+"""Cut a streaming LLM reply into speakable clauses.++The first clause leaves as early as possible (a comma is enough once a few+words arrived) so speech can start while the model is still writing; later+clauses prefer sentence ends. Abbreviations and ordinal numbers ("am 3.+Oktober", "z. B.", "e.g.") do not end a sentence.+"""++from __future__ import annotations++import re++_ABBREVIATIONS = frozenset(+ {+ # German+ "z", "b", "bzw", "usw", "ca", "dr", "nr", "str", "d", "h", "u", "a", "etc",+ "vgl", "inkl", "evtl", "ggf", "bspw", "sog", "zzgl", "abs", "st", "mio", "mrd",+ # English+ "e", "g", "i", "mr", "mrs", "ms", "vs", "approx", "no", "jr", "sr",+ }+)+_SENTENCE_END = re.compile(r"[.!?…]+[\"')\]]*(?=\s)")+_CLAUSE_END = re.compile(r"[,;:–—](?=\s)")+++class ClauseChunker:+ def __init__(self, *, first_min_chars: int = 12, min_chars: int = 40, max_chars: int = 220):+ self.first_min_chars = first_min_chars+ self.min_chars = min_chars+ self.max_chars = max_chars+ self._buffer = ""+ self._emitted = 0++ def feed(self, delta: str) -> list[str]:+ self._buffer += delta+ out: list[str] = []+ while True:+ cut = self._find_cut()+ if cut is None:+ break+ clause, self._buffer = self._buffer[:cut].strip(), self._buffer[cut:].lstrip()+ if clause:+ out.append(clause)+ self._emitted += 1+ return out++ def flush(self) -> list[str]:+ rest, self._buffer = self._buffer.strip(), ""+ if rest:+ self._emitted += 1+ return [rest]+ return []++ def _find_cut(self) -> int | None:+ text = self._buffer+ for match in _SENTENCE_END.finditer(text):+ if not self._is_abbreviation(text, match.start()):+ return match.end()+ threshold = self.first_min_chars if self._emitted == 0 else self.min_chars+ for match in _CLAUSE_END.finditer(text):+ if match.end() >= threshold:+ return match.end()+ if len(text) > self.max_chars:+ space = text.rfind(" ", 0, self.max_chars)+ return space if space > 0 else self.max_chars+ return None++ @staticmethod+ def _is_abbreviation(text: str, dot: int) -> bool:+ if text[dot] != ".":+ return False+ before = text[:dot]+ word = re.search(r"([A-Za-zÄÖÜäöüß]+|\d+)$", before) # i18n-allow: German letters+ if word is None:+ return False+ token = word.group(1)+ if token.isdigit():+ # German ordinals ("am 3. Oktober", "1. Platz") use a dot. Treating+ # every one- or two-digit number as an ordinal costs at most a+ # later cut when a sentence really ends on a small number.+ return len(token) <= 2+ return token.lower() in _ABBREVIATIONSdiff --git a/jarvis/voice_engine/llm.py b/jarvis/voice_engine/llm.pynew file mode 100644index 0000000000..ca45c598cd--- /dev/null+++ b/jarvis/voice_engine/llm.py@@ -0,0 +1,208 @@+"""Streaming chat against a local Ollama server, with tool calls and timings.++Ollama's native ``/api/chat`` is used because it accepts the voice profile+directly (``num_ctx``, ``think: false``, ``keep_alive``) and reports prompt and+generation counters that show whether the prefix cache hit. A portable+OpenAI-compatible client (llama-server, LM Studio) follows in phase P1.+"""++from __future__ import annotations++import http.client+import json+import threading+import time+from collections.abc import Callable+from dataclasses import dataclass, field+from typing import Any+from urllib.parse import urlsplit++from jarvis.voice_engine.chunker import ClauseChunker++DEFAULT_BASE_URL = "http://127.0.0.1:11434"+++@dataclass(slots=True)+class LlmResult:+ text: str = ""+ tool_calls: list[dict[str, Any]] = field(default_factory=list)+ clauses: list[str] = field(default_factory=list)+ t_first_token: float | None = None # seconds from request start+ t_first_clause: float | None = None+ t_done: float = 0.0+ prompt_tokens: int = 0+ prompt_cached_tokens: int = 0+ prompt_eval_s: float = 0.0+ eval_tokens: int = 0+ eval_s: float = 0.0+ load_s: float = 0.0+ error: str = ""++ @property+ def generation_tps(self) -> float:+ return self.eval_tokens / self.eval_s if self.eval_s > 0 else 0.0++ @property+ def prefill_tps(self) -> float:+ return self.prompt_tokens / self.prompt_eval_s if self.prompt_eval_s > 0 else 0.0+++class OllamaChat:+ def __init__(+ self,+ model: str,+ *,+ base_url: str = DEFAULT_BASE_URL,+ num_ctx: int = 8192,+ keep_alive: str = "30m",+ temperature: float = 0.2,+ num_gpu: int | None = None,+ timeout_s: float = 120.0,+ ) -> None:+ parts = urlsplit(base_url)+ if parts.scheme != "http" or not parts.hostname:+ raise ValueError(f"expected an http://host:port Ollama address, got {base_url!r}")+ self.model = model+ self._host = parts.hostname+ self._port = parts.port or 11434+ self._timeout = timeout_s+ self._keep_alive = keep_alive+ self._options: dict[str, Any] = {"num_ctx": num_ctx, "temperature": temperature}+ if num_gpu is not None:+ self._options["num_gpu"] = num_gpu+ self._think_supported = True++ def _post(self, path: str, payload: dict[str, Any]) -> http.client.HTTPResponse:+ connection = http.client.HTTPConnection(self._host, self._port, timeout=self._timeout)+ body = json.dumps(payload).encode("utf-8")+ connection.request("POST", path, body=body, headers={"Content-Type": "application/json"})+ return connection.getresponse()++ def unload(self) -> None:+ """Ask Ollama to drop the model now, so the next load is a cold one."""+ response = self._post("/api/generate", {"model": self.model, "keep_alive": 0})+ response.read()++ def loaded_models(self) -> list[dict[str, Any]]:+ """Ollama's view of resident models: size and how much sits in VRAM."""+ connection = http.client.HTTPConnection(self._host, self._port, timeout=self._timeout)+ connection.request("GET", "/api/ps")+ response = connection.getresponse()+ payload = json.loads(response.read() or b"{}")+ return [+ {+ "name": entry.get("name"),+ "size_gb": round(int(entry.get("size") or 0) / 1e9, 2),+ "size_vram_gb": round(int(entry.get("size_vram") or 0) / 1e9, 2),+ "context_length": entry.get("context_length"),+ }+ for entry in payload.get("models", [])+ ]++ def warm(self) -> float:+ """Load the model with the voice profile; returns seconds spent."""+ started = time.perf_counter()+ response = self._post(+ "/api/generate",+ {"model": self.model, "prompt": "", "keep_alive": self._keep_alive,+ "options": self._options},+ )+ response.read()+ if response.status != 200:+ raise RuntimeError(f"Ollama could not load {self.model}: HTTP {response.status}")+ return time.perf_counter() - started++ def chat(+ self,+ messages: list[dict[str, Any]],+ *,+ tools: list[dict[str, Any]] | None = None,+ chunker: ClauseChunker | None = None,+ on_clause: Callable[[str, float], None] | None = None,+ stop: threading.Event | None = None,+ ) -> LlmResult:+ payload: dict[str, Any] = {+ "model": self.model,+ "messages": messages,+ "stream": True,+ "keep_alive": self._keep_alive,+ "options": self._options,+ }+ if tools:+ payload["tools"] = tools+ if self._think_supported:+ payload["think"] = False+ started = time.perf_counter()+ response = self._post("/api/chat", payload)+ if response.status == 400 and self._think_supported:+ detail = response.read().decode("utf-8", "replace")+ if "think" in detail.lower():+ # Models without a reasoning mode reject the switch; they have+ # nothing to turn off, so retry once without it.+ self._think_supported = False+ return self.chat(messages, tools=tools, chunker=chunker, on_clause=on_clause,+ stop=stop)+ return LlmResult(+ error=f"HTTP 400: {detail[:300]}", t_done=time.perf_counter() - started+ )+ if response.status != 200:+ detail = response.read().decode("utf-8", "replace")+ return LlmResult(error=f"HTTP {response.status}: {detail[:300]}",+ t_done=time.perf_counter() - started)+ result = LlmResult()+ chunker = chunker or ClauseChunker()+ try:+ for raw in response:+ if stop is not None and stop.is_set():+ result.error = "cancelled"+ break+ line = raw.strip()+ if not line:+ continue+ event = json.loads(line)+ if event.get("error"):+ result.error = str(event["error"])+ break+ message = event.get("message") or {}+ delta = message.get("content") or ""+ now = time.perf_counter() - started+ if delta:+ if result.t_first_token is None:+ result.t_first_token = now+ result.text += delta+ for clause in chunker.feed(delta):+ self._clause(result, clause, now, on_clause)+ for call in message.get("tool_calls") or []:+ if result.t_first_token is None:+ result.t_first_token = now+ function = call.get("function") or {}+ result.tool_calls.append(+ {+ "name": function.get("name", ""),+ "arguments": function.get("arguments") or {},+ }+ )+ if event.get("done"):+ result.prompt_tokens = int(event.get("prompt_eval_count") or 0)+ result.prompt_cached_tokens = int(event.get("prompt_eval_cached_count") or 0)+ result.prompt_eval_s = int(event.get("prompt_eval_duration") or 0) / 1e9+ result.eval_tokens = int(event.get("eval_count") or 0)+ result.eval_s = int(event.get("eval_duration") or 0) / 1e9+ result.load_s = int(event.get("load_duration") or 0) / 1e9+ finally:+ response.close()+ end = time.perf_counter() - started+ for clause in chunker.flush():+ self._clause(result, clause, end, on_clause)+ result.t_done = end+ return result++ @staticmethod+ def _clause(+ result: LlmResult, clause: str, at: float, on_clause: Callable[[str, float], None] | None+ ) -> None:+ if result.t_first_clause is None:+ result.t_first_clause = at+ result.clauses.append(clause)+ if on_clause is not None:+ on_clause(clause, at)diff --git a/jarvis/voice_engine/models.py b/jarvis/voice_engine/models.pynew file mode 100644index 0000000000..1bfcf93f45--- /dev/null+++ b/jarvis/voice_engine/models.py@@ -0,0 +1,206 @@+"""The engine's model store: pinned sources, checksums, resumable downloads.++Every model the engine loads comes from this registry. Each entry pins an+immutable source (a release asset or a Hugging Face revision) and, once+verified, its SHA-256. Downloads resume after an interruption, are verified+before they become visible, and archives are unpacked with tarfile's data+filter. At runtime the engine only reads the store; it never touches the+network (``docs/local-live-voice-rebuild.md`` section 4.9).++Models that their own runtime package downloads (Pocket TTS, Qwen3-TTS) are not+listed here; the bench reports where those runtimes cache them.+"""++from __future__ import annotations++import hashlib+import os+import shutil+import tarfile+import time+import urllib.request+from collections.abc import Callable+from dataclasses import dataclass+from pathlib import Path++from jarvis.voice_engine.paths import models_dir++_CHUNK = 1 << 20+_USER_AGENT = "jarvis-voice-engine/0.1 (+https://github.com/PersonalJarvis/PersonalJarvis)"++ProgressFn = Callable[[str, int, int], None]+++@dataclass(frozen=True, slots=True)+class ModelSource:+ name: str+ url: str+ size: int+ sha256: str+ # For archives: the directory the archive unpacks to (relative to the store).+ unpacks_to: str = ""+ # For single files: the file name inside the model's own directory.+ filename: str = ""+ licence: str = ""++ @property+ def is_archive(self) -> bool:+ return self.url.endswith((".tar.bz2", ".tar.gz", ".tgz"))+++_GH_SHERPA = "https://github.com/k2-fsa/sherpa-onnx/releases/download"++REGISTRY: dict[str, ModelSource] = {+ source.name: source+ for source in (+ ModelSource(+ name="silero-vad-v6",+ url=(+ "https://raw.githubusercontent.com/snakers4/silero-vad/v6.2.3/"+ "src/silero_vad/data/silero_vad.onnx"+ ),+ size=2_327_524,+ sha256="1a153a22f4509e292a94e67d6f9b85e8deb25b4988682b7e174c65279d8788e3",+ filename="silero_vad.onnx",+ licence="MIT",+ ),+ ModelSource(+ name="smart-turn-v3.2",+ url=(+ "https://huggingface.co/pipecat-ai/smart-turn-v3/resolve/"+ "f766f81d3cfdf7737ac64aad813d91bbfd56bf93/smart-turn-v3.2-cpu.onnx"+ ),+ size=8_679_182,+ sha256="2bb026316b14a660486a75b1733cd3fbab8c2fd0314dc9af7be49f8cca967e4f",+ filename="smart-turn-v3.2-cpu.onnx",+ licence="BSD-2-Clause",+ ),+ ModelSource(+ name="parakeet-tdt-0.6b-v3-int8",+ url=f"{_GH_SHERPA}/asr-models/sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8.tar.bz2",+ size=487_170_055,+ sha256="5793d0fd397c5778d2cf2126994d58e9d56b1be7c04d13c7a15bb1b4eafb16bf",+ unpacks_to="sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8",+ licence="CC-BY-4.0",+ ),+ ModelSource(+ name="piper-de-thorsten-medium",+ url=f"{_GH_SHERPA}/tts-models/vits-piper-de_DE-thorsten-medium.tar.bz2",+ size=67_214_254,+ sha256="50487d9c95fdf2191f31d2588569381063ba1591dcd4c7d4bdd30f12b2191714",+ unpacks_to="vits-piper-de_DE-thorsten-medium",+ licence="CC0-1.0 voice; Apache-2.0 runtime",+ ),+ ModelSource(+ name="piper-en-ryan-medium",+ url=f"{_GH_SHERPA}/tts-models/vits-piper-en_US-ryan-medium.tar.bz2",+ size=67_213_100,+ sha256="c546af78b6395b4e7c4ce1ed899438b64426a362f5d4ec5fecd090ded9ad7505",+ unpacks_to="vits-piper-en_US-ryan-medium",+ licence="CC-BY-4.0 voice; Apache-2.0 runtime",+ ),+ )+}+++def model_path(name: str, root: Path | None = None) -> Path:+ """Where a registered model lives once fetched (directory or single file)."""+ source = REGISTRY[name]+ base = (root or models_dir())+ if source.is_archive:+ return base / source.unpacks_to+ return base / name / source.filename+++def is_present(name: str, root: Path | None = None) -> bool:+ path = model_path(name, root)+ return path.is_dir() and any(path.iterdir()) if REGISTRY[name].is_archive else path.is_file()+++def sha256_of(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as handle:+ for block in iter(lambda: handle.read(_CHUNK), b""):+ digest.update(block)+ return digest.hexdigest()+++def _download(url: str, target: Path, expected_size: int, progress: ProgressFn | None) -> None:+ if not url.startswith("https://"):+ raise ValueError(f"refusing a non-https model source: {url}")+ partial = target.with_name(target.name + ".part")+ done = partial.stat().st_size if partial.exists() else 0+ request = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT}) # noqa: S310 - https checked above+ if done:+ request.add_header("Range", f"bytes={done}-")+ with urllib.request.urlopen(request, timeout=60) as response: # noqa: S310 - https checked above+ if done and response.status != 206:+ # The server ignored the range request; start over rather than+ # appending a second copy to the partial file.+ done = 0+ partial.unlink(missing_ok=True)+ total = int(response.headers.get("Content-Length") or 0) + done+ total = total or expected_size+ with partial.open("ab" if done else "wb") as handle:+ last = 0.0+ while True:+ block = response.read(_CHUNK)+ if not block:+ break+ handle.write(block)+ done += len(block)+ now = time.monotonic()+ if progress is not None and now - last > 0.5:+ progress(target.name, done, total)+ last = now+ if progress is not None:+ progress(target.name, done, done)+ partial.replace(target)+++def fetch(+ name: str,+ root: Path | None = None,+ *,+ progress: ProgressFn | None = None,+ allow_unpinned: bool = False,+) -> tuple[Path, str]:+ """Download, verify and unpack one model. Returns (path, sha256).++ An entry without a pinned checksum is refused unless ``allow_unpinned`` is+ set (bench bootstrap only); the computed checksum is returned so it can be+ pinned in :data:`REGISTRY`.+ """+ source = REGISTRY[name]+ base = root or models_dir()+ final = model_path(name, base)+ if is_present(name, base):+ return final, source.sha256 or "present"+ if not source.sha256 and not allow_unpinned:+ raise RuntimeError(f"{name} has no pinned checksum; refusing to download it")+ staging = base / ".download"+ staging.mkdir(parents=True, exist_ok=True)+ blob = staging / source.url.rsplit("/", 1)[-1]+ if not blob.exists():+ _download(source.url, blob, source.size, progress)+ digest = sha256_of(blob)+ if source.sha256 and digest != source.sha256:+ blob.unlink(missing_ok=True)+ raise RuntimeError(f"{name}: checksum mismatch (got {digest}, pinned {source.sha256})")+ if source.is_archive:+ unpack_dir = staging / f"{name}.unpack"+ shutil.rmtree(unpack_dir, ignore_errors=True)+ unpack_dir.mkdir(parents=True)+ with tarfile.open(blob) as archive:+ archive.extractall(unpack_dir, filter="data")+ produced = unpack_dir / source.unpacks_to+ if not produced.is_dir():+ raise RuntimeError(f"{name}: archive did not contain {source.unpacks_to}/")+ final.parent.mkdir(parents=True, exist_ok=True)+ os.replace(produced, final)+ shutil.rmtree(unpack_dir, ignore_errors=True)+ else:+ final.parent.mkdir(parents=True, exist_ok=True)+ os.replace(blob, final)+ blob.unlink(missing_ok=True)+ return final, digestdiff --git a/jarvis/voice_engine/paths.py b/jarvis/voice_engine/paths.pynew file mode 100644index 0000000000..e76062a451--- /dev/null+++ b/jarvis/voice_engine/paths.py@@ -0,0 +1,38 @@+"""Where the engine keeps its environments, models and bench results.++The home lives in the per-user application-data folder of each OS, never next+to the code: a checkout can sit in a cloud-synced folder, and multi-gigabyte+model stores must not be uploaded. The app passes its own location through+``JARVIS_VOICE_ENGINE_HOME`` when it spawns the worker.+"""++from __future__ import annotations++import os+import sys+from pathlib import Path++ENV_HOME = "JARVIS_VOICE_ENGINE_HOME"+++def engine_home() -> Path:+ override = os.environ.get(ENV_HOME, "").strip()+ if override:+ return Path(override).expanduser().resolve()+ if sys.platform == "win32":+ base = os.environ.get("LOCALAPPDATA", "").strip()+ root = Path(base) if base else Path.home() / "AppData" / "Local"+ return root / "JarvisVoiceEngine"+ if sys.platform == "darwin":+ return Path.home() / "Library" / "Application Support" / "JarvisVoiceEngine"+ base = os.environ.get("XDG_DATA_HOME", "").strip()+ root = Path(base) if base else Path.home() / ".local" / "share"+ return root / "jarvis-voice-engine"+++def models_dir() -> Path:+ return engine_home() / "models"+++def results_dir() -> Path:+ return engine_home() / "bench-results"diff --git a/jarvis/voice_engine/stt.py b/jarvis/voice_engine/stt.pynew file mode 100644index 0000000000..9c663ef48b--- /dev/null+++ b/jarvis/voice_engine/stt.py@@ -0,0 +1,49 @@+"""Parakeet TDT 0.6B v3 transcription through sherpa-onnx (offline transducer).++Parakeet v3 decodes a whole utterance at once. The engine runs it+speculatively when the user falls silent, so by the time the turn detector+decides, the transcript is usually ready (``docs/local-live-voice-rebuild.md``+section 4.3).+"""++from __future__ import annotations++import os+from pathlib import Path++import numpy as np++from jarvis.voice_engine.audio import STT_RATE+++def default_threads() -> int:+ return max(1, min(4, (os.cpu_count() or 2) // 2))+++class ParakeetStt:+ def __init__(+ self, model_dir: Path, *, threads: int | None = None, provider: str = "cpu"+ ) -> None:+ import sherpa_onnx # noqa: PLC0415 - heavy runtime, imported on use++ def pick(stem: str) -> str:+ matches = sorted(model_dir.glob(f"{stem}*.onnx"))+ if not matches:+ raise FileNotFoundError(f"{model_dir.name}: no {stem}*.onnx")+ return str(matches[0])++ self._recognizer = sherpa_onnx.OfflineRecognizer.from_transducer(+ encoder=pick("encoder"),+ decoder=pick("decoder"),+ joiner=pick("joiner"),+ tokens=str(model_dir / "tokens.txt"),+ num_threads=threads or default_threads(),+ model_type="nemo_transducer",+ provider=provider,+ )++ def transcribe(self, audio: np.ndarray, rate: int = STT_RATE) -> str:+ stream = self._recognizer.create_stream()+ stream.accept_waveform(rate, np.asarray(audio, dtype=np.float32))+ self._recognizer.decode_stream(stream)+ return stream.result.text.strip()diff --git a/jarvis/voice_engine/tts/__init__.py b/jarvis/voice_engine/tts/__init__.pynew file mode 100644index 0000000000..f0e79658b3--- /dev/null+++ b/jarvis/voice_engine/tts/__init__.py@@ -0,0 +1,45 @@+"""Text-to-speech backends behind one streaming interface.++The ladder (``docs/local-live-voice-rebuild.md`` section 4.7): Piper is the+floor that runs everywhere, Pocket TTS the natural CPU voice, Qwen3-TTS the+premium GPU/MLX voice. Each backend is loaded for one language and yields+float32 chunks at its own ``sample_rate``.+"""++from __future__ import annotations++import threading+from collections.abc import Iterator+from typing import Protocol++import numpy as np+++class TtsEngine(Protocol):+ name: str+ sample_rate: int++ def stream(self, text: str, *, stop: threading.Event | None = None) -> Iterator[np.ndarray]:+ """Yield audio chunks for one clause; stop early when ``stop`` is set."""+ ...+++LANGUAGE_NAMES = {"de": "german", "en": "english", "es": "spanish", "fr": "french",+ "it": "italian", "pt": "portuguese", "nl": "dutch"}+++def load_tts(kind: str, language: str, **options: object) -> TtsEngine:+ """Build one backend by name; heavy imports happen inside the backend."""+ if kind == "piper":+ from jarvis.voice_engine.tts.piper import PiperTts # noqa: PLC0415++ return PiperTts.for_language(language, **options) # type: ignore[arg-type]+ if kind == "pocket":+ from jarvis.voice_engine.tts.pocket import PocketTts # noqa: PLC0415++ return PocketTts(language, **options) # type: ignore[arg-type]+ if kind == "qwen3":+ from jarvis.voice_engine.tts.qwen3 import Qwen3Tts # noqa: PLC0415++ return Qwen3Tts(language, **options) # type: ignore[arg-type]+ raise ValueError(f"unknown TTS backend {kind!r}")diff --git a/jarvis/voice_engine/tts/piper.py b/jarvis/voice_engine/tts/piper.pynew file mode 100644index 0000000000..6deb97921d--- /dev/null+++ b/jarvis/voice_engine/tts/piper.py@@ -0,0 +1,53 @@+"""Piper voices through sherpa-onnx: the TTS floor that runs on every CPU.++sherpa-onnx's Apache-2.0 runtime replaces the GPL ``piper1`` package; only the+voice files come from Piper.+"""++from __future__ import annotations++import os+import threading+from collections.abc import Iterator+from pathlib import Path++import numpy as np++from jarvis.voice_engine.models import is_present, model_path++VOICES = {"de": "piper-de-thorsten-medium", "en": "piper-en-ryan-medium"}+++class PiperTts:+ name = "piper"++ def __init__(self, voice_dir: Path, *, threads: int | None = None) -> None:+ import sherpa_onnx # noqa: PLC0415 - heavy runtime, imported on use++ onnx = next(p for p in sorted(voice_dir.glob("*.onnx")))+ config = sherpa_onnx.OfflineTtsConfig(+ model=sherpa_onnx.OfflineTtsModelConfig(+ vits=sherpa_onnx.OfflineTtsVitsModelConfig(+ model=str(onnx),+ tokens=str(voice_dir / "tokens.txt"),+ data_dir=str(voice_dir / "espeak-ng-data"),+ ),+ num_threads=threads or max(1, min(4, (os.cpu_count() or 2) // 2)),+ provider="cpu",+ ),+ )+ self._tts = sherpa_onnx.OfflineTts(config)+ self.sample_rate = int(self._tts.sample_rate)++ @classmethod+ def for_language(cls, language: str, *, threads: int | None = None) -> PiperTts:+ voice = VOICES.get(language)+ if voice is None or not is_present(voice):+ raise RuntimeError(f"no Piper voice installed for language {language!r}")+ return cls(model_path(voice), threads=threads)++ def stream(self, text: str, *, stop: threading.Event | None = None) -> Iterator[np.ndarray]:+ if stop is not None and stop.is_set():+ return+ audio = self._tts.generate(text, sid=0, speed=1.0)+ yield np.asarray(audio.samples, dtype=np.float32)diff --git a/jarvis/voice_engine/tts/pocket.py b/jarvis/voice_engine/tts/pocket.pynew file mode 100644index 0000000000..a6f5fd11b2--- /dev/null+++ b/jarvis/voice_engine/tts/pocket.py@@ -0,0 +1,51 @@+"""Kyutai Pocket TTS (100M parameters): the natural voice that runs on a CPU.++Weights come from the ungated ``kyutai/pocket-tts-without-voice-cloning``+repository through the package's own loader; voices are its predefined+embeddings, so no reference audio and no token are needed.+"""++from __future__ import annotations++import threading+from collections.abc import Iterator++import numpy as np++from jarvis.voice_engine.audio import as_float_array+from jarvis.voice_engine.tts import LANGUAGE_NAMES++DEFAULT_VOICES = {"de": "juergen", "en": "alba"}+++class PocketTts:+ name = "pocket"++ def __init__(+ self,+ language: str,+ *,+ voice: str | None = None,+ large: bool = False,+ threads: int | None = None,+ ) -> None:+ import torch # noqa: PLC0415 - heavy runtime, imported on use+ from pocket_tts import TTSModel # noqa: PLC0415++ if threads:+ torch.set_num_threads(int(threads))+ config = LANGUAGE_NAMES.get(language)+ if config is None:+ raise RuntimeError(f"Pocket TTS has no model for language {language!r}")+ if large and language != "en":+ config = f"{config}_24l"+ self._model = TTSModel.load_model(language=config)+ self._voice = self._model.get_state_for_audio_prompt(+ voice or DEFAULT_VOICES.get(language, "alba")+ )+ self.sample_rate = int(self._model.sample_rate)+ self.name = f"pocket-{config}"++ def stream(self, text: str, *, stop: threading.Event | None = None) -> Iterator[np.ndarray]:+ for chunk in self._model.generate_audio_stream(self._voice, text, stop=stop):+ yield as_float_array(chunk)diff --git a/jarvis/voice_engine/tts/qwen3.py b/jarvis/voice_engine/tts/qwen3.pynew file mode 100644index 0000000000..ea2e550630--- /dev/null+++ b/jarvis/voice_engine/tts/qwen3.py@@ -0,0 +1,56 @@+"""Qwen3-TTS through faster-qwen3-tts (CUDA graphs): the premium GPU voice.++Needs torch with CUDA; Apple Silicon uses mlx-audio instead (phase P4). The+CustomVoice checkpoints carry named speakers, so no reference audio is needed.+"""++from __future__ import annotations++import threading+from collections.abc import Iterator++import numpy as np++from jarvis.voice_engine.audio import as_float_array++QWEN_LANGUAGES = {"de": "German", "en": "English", "es": "Spanish", "fr": "French",+ "it": "Italian", "pt": "Portuguese"}+CHECKPOINTS = {+ "0.6b": "Qwen/Qwen3-TTS-12Hz-0.6B-CustomVoice",+ "1.7b": "Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice",+}+++class Qwen3Tts:+ def __init__(+ self,+ language: str,+ *,+ size: str = "0.6b",+ speaker: str = "Aiden",+ chunk_size: int = 4,+ device: str = "cuda",+ ) -> None:+ from faster_qwen3_tts import FasterQwen3TTS # noqa: PLC0415 - heavy runtime++ if language not in QWEN_LANGUAGES:+ raise RuntimeError(f"Qwen3-TTS has no language {language!r}")+ self._language = QWEN_LANGUAGES[language]+ self._speaker = speaker+ self._chunk = int(chunk_size)+ self._model = FasterQwen3TTS.from_pretrained(CHECKPOINTS[size], device=device)+ self.sample_rate = 24_000+ self.name = f"qwen3-{size}"++ def warmup(self) -> None:+ self._model.warmup()++ def stream(self, text: str, *, stop: threading.Event | None = None) -> Iterator[np.ndarray]:+ chunks = self._model.generate_custom_voice_streaming(+ text=text, speaker=self._speaker, language=self._language, chunk_size=self._chunk+ )+ for audio, rate, _timing in chunks:+ if stop is not None and stop.is_set():+ return+ self.sample_rate = int(rate)+ yield as_float_array(audio)diff --git a/jarvis/voice_engine/turn.py b/jarvis/voice_engine/turn.pynew file mode 100644index 0000000000..6c90dfa6a4--- /dev/null+++ b/jarvis/voice_engine/turn.py@@ -0,0 +1,106 @@+"""Smart Turn v3.2 end-of-turn detection on ONNX Runtime, without transformers.++The model scores whether the user finished speaking from the last 8 s of+audio. Its input is Whisper's 80-bin log-mel spectrogram; this module+reimplements ``WhisperFeatureExtractor(chunk_length=8)`` with+``do_normalize=True`` in numpy, matching the reference ``inference.py`` of+github.com/pipecat-ai/smart-turn: keep the last 8 s, zero-pad at the BEGINNING,+normalise to zero mean and unit variance, then log-mel.+"""++from __future__ import annotations++from functools import lru_cache+from pathlib import Path++import numpy as np++RATE = 16_000+WINDOW_SECONDS = 8+N_FFT = 400+HOP = 160+N_MELS = 80+++def _hertz_to_mel(freq: np.ndarray) -> np.ndarray:+ """Slaney mel scale, as transformers' ``hertz_to_mel(mel_scale="slaney")``."""+ freq = np.asarray(freq, dtype=np.float64)+ mels = 3.0 * freq / 200.0+ log_region = freq >= 1000.0+ mels[log_region] = 15.0 + np.log(freq[log_region] / 1000.0) * (27.0 / np.log(6.4))+ return mels+++def _mel_to_hertz(mels: np.ndarray) -> np.ndarray:+ mels = np.asarray(mels, dtype=np.float64)+ freq = 200.0 * mels / 3.0+ log_region = mels >= 15.0+ freq[log_region] = 1000.0 * np.exp((np.log(6.4) / 27.0) * (mels[log_region] - 15.0))+ return freq+++@lru_cache(maxsize=1)+def mel_filters() -> np.ndarray:+ """(201, 80) Slaney-normalised triangular filter bank for 0-8 kHz."""+ fft_freqs = np.linspace(0, RATE // 2, 1 + N_FFT // 2)+ low, high = _hertz_to_mel(np.array([0.0, 8000.0]))+ mel_points = np.linspace(low, high, N_MELS + 2)+ filter_freqs = _mel_to_hertz(mel_points)+ filter_diff = np.diff(filter_freqs)+ slopes = filter_freqs[None, :] - fft_freqs[:, None]+ down = -slopes[:, :-2] / filter_diff[:-1]+ up = slopes[:, 2:] / filter_diff[1:]+ filters = np.maximum(0.0, np.minimum(down, up))+ enorm = 2.0 / (filter_freqs[2 : N_MELS + 2] - filter_freqs[:N_MELS])+ return filters * enorm[None, :]+++@lru_cache(maxsize=1)+def _hann() -> np.ndarray:+ return np.hanning(N_FFT + 1)[:-1] # periodic Hann, as window_function(400, "hann")+++def prepare_window(audio: np.ndarray) -> np.ndarray:+ """Last 8 s of 16 kHz audio, zero-padded at the beginning."""+ target = WINDOW_SECONDS * RATE+ audio = np.asarray(audio, dtype=np.float32).reshape(-1)+ if audio.size >= target:+ return audio[-target:]+ return np.pad(audio, (target - audio.size, 0))+++def log_mel(audio: np.ndarray) -> np.ndarray:+ """Whisper-compatible (80, 800) log-mel features of an 8 s window."""+ x = prepare_window(audio).astype(np.float64)+ x = (x - x.mean()) / np.sqrt(x.var() + 1e-7)+ padded = np.pad(x, (N_FFT // 2, N_FFT // 2), mode="reflect")+ frames = 1 + (padded.size - N_FFT) // HOP+ strides = (padded.strides[0] * HOP, padded.strides[0])+ windows = np.lib.stride_tricks.as_strided(padded, shape=(frames, N_FFT), strides=strides)+ spectrum = np.fft.rfft(windows * _hann(), n=N_FFT, axis=1)+ power = (spectrum.real**2 + spectrum.imag**2).T # (201, frames)+ mel = mel_filters().T @ power # (80, frames)+ log_spec = np.log10(np.maximum(mel, 1e-10))[:, :-1]+ log_spec = np.maximum(log_spec, log_spec.max() - 8.0)+ return ((log_spec + 4.0) / 4.0).astype(np.float32)+++class SmartTurn:+ def __init__(self, model_path: Path, *, threads: int = 1) -> None:+ import onnxruntime as ort # noqa: PLC0415 - heavy runtime, imported on use++ options = ort.SessionOptions()+ options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL+ options.inter_op_num_threads = 1+ options.intra_op_num_threads = max(1, threads)+ options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL+ self._session = ort.InferenceSession(+ str(model_path), sess_options=options, providers=["CPUExecutionProvider"]+ )+ self._input = self._session.get_inputs()[0].name++ def probability(self, audio16k: np.ndarray) -> float:+ """Probability that the turn is complete (sigmoid output of the model)."""+ features = log_mel(audio16k)[None, :, :]+ (out,) = self._session.run(None, {self._input: features})+ return float(np.asarray(out).reshape(-1)[0])diff --git a/jarvis/voice_engine/vad.py b/jarvis/voice_engine/vad.pynew file mode 100644index 0000000000..9cc40e759b--- /dev/null+++ b/jarvis/voice_engine/vad.py@@ -0,0 +1,107 @@+"""Silero VAD v6 on ONNX Runtime, without torch.++Mirrors the official ``OnnxWrapper`` (silero-vad ``utils_vad.py``): 512-sample+frames at 16 kHz, each prefixed with the last 64 samples of the previous frame,+and a recurrent state of shape (2, 1, 128).+"""++from __future__ import annotations++from dataclasses import dataclass+from pathlib import Path++import numpy as np++FRAME_SAMPLES = 512+CONTEXT_SAMPLES = 64+RATE = 16_000+FRAME_MS = FRAME_SAMPLES * 1000 // RATE # 32 ms+++class SileroVad:+ def __init__(self, model_path: Path, *, threads: int = 1) -> None:+ import onnxruntime as ort # noqa: PLC0415 - heavy runtime, imported on use++ options = ort.SessionOptions()+ options.inter_op_num_threads = 1+ options.intra_op_num_threads = max(1, threads)+ self._session = ort.InferenceSession(+ str(model_path), sess_options=options, providers=["CPUExecutionProvider"]+ )+ self._rate = np.array(RATE, dtype=np.int64)+ self.reset()++ def reset(self) -> None:+ self._state = np.zeros((2, 1, 128), dtype=np.float32)+ self._context = np.zeros((1, CONTEXT_SAMPLES), dtype=np.float32)++ def __call__(self, frame: np.ndarray) -> float:+ """Speech probability of one 512-sample frame (float32, 16 kHz)."""+ if frame.shape[-1] != FRAME_SAMPLES:+ raise ValueError(f"Silero expects {FRAME_SAMPLES} samples, got {frame.shape[-1]}")+ chunk = np.concatenate([self._context, frame.reshape(1, -1).astype(np.float32)], axis=1)+ out, state = self._session.run(+ None, {"input": chunk, "state": self._state, "sr": self._rate}+ )+ self._state = state+ self._context = chunk[:, -CONTEXT_SAMPLES:]+ return float(out.reshape(-1)[0])+++@dataclass(slots=True)+class VadEvent:+ kind: str # "speech_start" | "silence_start" | "silence_end"+ at_ms: int+++class Endpointer:+ """Turns frame probabilities into speech/silence edges with hysteresis.++ ``speech_start`` fires after ``min_speech_ms`` of voiced frames;+ ``silence_start`` after ``silence_ms`` of unvoiced frames inside speech —+ the moment the turn detector and the speculative transcription start;+ ``silence_end`` when the user resumes before the turn was taken.+ """++ def __init__(+ self,+ *,+ on_threshold: float = 0.5,+ off_threshold: float = 0.35,+ min_speech_ms: int = 160,+ silence_ms: int = 200,+ ) -> None:+ self.on_threshold = on_threshold+ self.off_threshold = off_threshold+ self.min_speech_frames = max(1, min_speech_ms // FRAME_MS)+ self.silence_frames = max(1, silence_ms // FRAME_MS)+ self.reset()++ def reset(self) -> None:+ self.in_speech = False+ self.in_silence = False+ self._voiced = 0+ self._unvoiced = 0+ self._frame = 0++ def feed(self, probability: float) -> VadEvent | None:+ self._frame += 1+ now = self._frame * FRAME_MS+ if probability >= self.on_threshold:+ self._voiced += 1+ self._unvoiced = 0+ if not self.in_speech and self._voiced >= self.min_speech_frames:+ self.in_speech = True+ return VadEvent("speech_start", now)+ if self.in_silence:+ self.in_silence = False+ return VadEvent("silence_end", now)+ return None+ if probability < self.off_threshold:+ self._unvoiced += 1+ if not self.in_speech:+ self._voiced = 0+ elif not self.in_silence and self._unvoiced >= self.silence_frames:+ self.in_silence = True+ return VadEvent("silence_start", now)+ return Nonediff --git a/scripts/ci/german-allowlist.txt b/scripts/ci/german-allowlist.txtindex cacce18825..7fb3d84903 100644--- a/scripts/ci/german-allowlist.txt+++ b/scripts/ci/german-allowlist.txt@@ -471,3 +471,7 @@ tests/unit/memory/test_profile_capture.py# --- Agent society (2026-09-01): the focus alias table maps the words people# write in agent descriptions (de/en) onto capability ids ---jarvis/society/focus.py++# --- Local voice engine bench (2026-10-01): the German speech-input corpus the+# P0 bench renders, transcribes and sends to the local LLM (ADR-0037) ---+jarvis/voice_engine/bench/corpus/de.jsondiff --git a/tests/fakes/fake_ollama_chat_stream.py b/tests/fakes/fake_ollama_chat_stream.pynew file mode 100644index 0000000000..d3b0de5ef6--- /dev/null+++ b/tests/fakes/fake_ollama_chat_stream.py@@ -0,0 +1,78 @@+"""A loopback HTTP server that streams scripted Ollama ``/api/chat`` replies.++The voice engine talks to Ollama with the standard library's ``http.client``+(it runs in its own environment without httpx), so this fake is a real socket+server on 127.0.0.1 with an ephemeral port. Each POST to ``/api/chat`` pops the+next scripted reply and streams it as NDJSON; every request body is recorded.++Usage::++ with FakeOllamaChatStream() as fake:+ fake.script([{"message": {"content": "Hi."}, "done": False}, {"done": True}])+ chat = OllamaChat("m", base_url=fake.base_url)+"""++from __future__ import annotations++import json+import threading+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from typing import Any++__all__ = ["FakeOllamaChatStream"]+++class FakeOllamaChatStream:+ def __init__(self) -> None:+ self.requests: list[dict[str, Any]] = []+ self._replies: list[tuple[int, list[dict[str, Any]] | str]] = []+ self._lock = threading.Lock()+ fake = self++ class Handler(BaseHTTPRequestHandler):+ def log_message(self, format: str, *args: Any) -> None: # noqa: A002+ del format, args # keep test output quiet++ def do_POST(self) -> None: # noqa: N802 - http.server naming+ length = int(self.headers.get("Content-Length") or 0)+ body = json.loads(self.rfile.read(length) or b"{}")+ with fake._lock:+ fake.requests.append({"path": self.path, "body": body})+ status, reply = fake._replies.pop(0) if fake._replies else (200, [])+ if isinstance(reply, str):+ payload = reply.encode("utf-8")+ self.send_response(status)+ self.send_header("Content-Length", str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)+ return+ self.send_response(status)+ self.send_header("Content-Type", "application/x-ndjson")+ self.end_headers()+ for event in reply:+ self.wfile.write((json.dumps(event) + "\n").encode("utf-8"))+ self.wfile.flush()++ self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)++ @property+ def base_url(self) -> str:+ host, port = self._server.server_address[:2]+ return f"http://{host}:{port}"++ def script(self, events: list[dict[str, Any]], *, status: int = 200) -> None:+ """Queue one streamed reply."""+ self._replies.append((status, events))++ def script_error(self, status: int, body: str) -> None:+ """Queue one plain error reply (e.g. Ollama's 400 for an unsupported option)."""+ self._replies.append((status, body))++ def __enter__(self) -> FakeOllamaChatStream:+ self._thread.start()+ return self++ def __exit__(self, *exc: object) -> None:+ self._server.shutdown()+ self._server.server_close()diff --git a/tests/unit/voice_engine/__init__.py b/tests/unit/voice_engine/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/unit/voice_engine/test_bench_corpus.py b/tests/unit/voice_engine/test_bench_corpus.pynew file mode 100644index 0000000000..2317f9cfbc--- /dev/null+++ b/tests/unit/voice_engine/test_bench_corpus.py@@ -0,0 +1,74 @@+"""Bench corpus integrity and tool-call grading."""++from __future__ import annotations++import pytest++from jarvis.voice_engine.bench import corpus+from jarvis.voice_engine.bench.stats import error_rates, percentile, summary++[email protected]("language", corpus.LANGUAGES)+def test_each_language_has_at_least_200_tool_cases(language: str) -> None:+ cases = corpus.tool_cases(language)+ assert len(cases) >= 200+ assert sum(case.tool is None for case in cases) >= 25+ declared = {tool["function"]["name"] for tool in corpus.tools()}+ assert {case.tool for case in cases if case.tool} <= declared++[email protected]("language", corpus.LANGUAGES)+def test_corpus_sections_are_complete(language: str) -> None:+ data = corpus.load(language)+ assert data["language"] == language+ assert len(data["roundtrip"]) >= 15+ assert len(data["dialog"]) >= 10+ for item in data["hesitations"]:+ assert len(item["pauses_ms"]) == len(item["segments"]) - 1+++def _case(**overrides: object) -> corpus.ToolCase:+ base = {"language": "en", "utterance": "Set a timer for ten minutes.", "tool": "set_timer",+ "accept": ("set_reminder",), "checks": {"minutes": {"equals": 10}}}+ base.update(overrides)+ return corpus.ToolCase(**base) # type: ignore[arg-type]+++def test_grade_verdicts() -> None:+ case = _case()+ assert corpus.grade(case, [{"name": "set_timer", "arguments": {"minutes": 10}}])["verdict"] == (+ "correct"+ )+ assert corpus.grade(case, [{"name": "set_timer", "arguments": {"minutes": "10"}}])[+ "verdict"+ ] == "correct"+ assert corpus.grade(case, [{"name": "set_timer", "arguments": {"minutes": 5}}])["verdict"] == (+ "wrong_args"+ )+ assert corpus.grade(case, [{"name": "set_reminder", "arguments": {}}])["verdict"] == "correct"+ assert corpus.grade(case, [{"name": "open_app", "arguments": {}}])["verdict"] == "wrong_tool"+ assert corpus.grade(case, [])["verdict"] == "missed"+ direct = _case(tool=None, accept=(), checks={})+ assert corpus.grade(direct, [])["verdict"] == "correct"+ assert corpus.grade(direct, [{"name": "search_web", "arguments": {}}])["verdict"] == "unneeded"+++def test_contains_check_accepts_alternatives() -> None:+ case = _case(tool="open_app", accept=(), checks={"name": {"contains": ["rechner", "calc"]}})+ assert corpus.grade(case, [{"name": "open_app", "arguments": {"name": "Calculator"}}])[+ "verdict"+ ] == "correct"+++def test_error_rates_ignore_case_and_punctuation() -> None:+ assert error_rates("Wie wird das Wetter?", "wie wird das wetter") == (0.0, 0.0) # i18n-allow+ cer, wer = error_rates("one two three", "one too three")+ assert 0 < cer < 0.2+ assert wer == pytest.approx(1 / 3)+++def test_percentiles() -> None:+ assert percentile([], 50) is None+ assert percentile([5.0], 95) == 5.0+ assert percentile([1, 2, 3, 4], 50) == pytest.approx(2.5)+ assert summary([1, 2, 3])["n"] == 3diff --git a/tests/unit/voice_engine/test_chunker.py b/tests/unit/voice_engine/test_chunker.pynew file mode 100644index 0000000000..10b3991952--- /dev/null+++ b/tests/unit/voice_engine/test_chunker.py@@ -0,0 +1,43 @@+"""The clause chunker starts speech early without splitting abbreviations."""++from __future__ import annotations++from jarvis.voice_engine.chunker import ClauseChunker+++def _run(deltas: list[str], **kwargs: int) -> list[str]:+ chunker = ClauseChunker(**kwargs)+ out: list[str] = []+ for delta in deltas:+ out.extend(chunker.feed(delta))+ return out + chunker.flush()+++def test_sentence_end_cuts_once_whitespace_follows() -> None:+ chunker = ClauseChunker()+ assert chunker.feed("The moon is far away.") == [] # no whitespace yet: could be "away.com"+ assert chunker.feed(" It") == ["The moon is far away."]+ assert chunker.flush() == ["It"]+++def test_first_clause_leaves_at_a_comma_but_later_ones_wait() -> None:+ text = "Sure, a black hole is a region of space, from which nothing escapes, not even light."+ clauses = _run([text[i : i + 5] for i in range(0, len(text), 5)])+ assert clauses[0] == "Sure, a black hole is a region of space,"+ assert clauses[-1].endswith("not even light.")+++def test_short_first_fragment_is_not_cut() -> None:+ assert _run(["Ja, gern. Das geht."]) == ["Ja, gern.", "Das geht."]+++def test_abbreviations_and_ordinals_do_not_end_a_sentence() -> None:+ clauses = _run(["Das ist z. B. am 3. Oktober so. Danach nicht mehr."]) # i18n-allow+ assert clauses == ["Das ist z. B. am 3. Oktober so.", "Danach nicht mehr."] # i18n-allow+++def test_runaway_text_is_split_at_a_space() -> None:+ text = "word " * 80+ clauses = _run([text], max_chars=50)+ assert all(len(c) <= 50 for c in clauses)+ assert " ".join(clauses).split() == text.split()diff --git a/tests/unit/voice_engine/test_llm_stream.py b/tests/unit/voice_engine/test_llm_stream.pynew file mode 100644index 0000000000..9dddd09687--- /dev/null+++ b/tests/unit/voice_engine/test_llm_stream.py@@ -0,0 +1,64 @@+"""Streaming chat parsing against a scripted loopback Ollama."""++from __future__ import annotations++from jarvis.voice_engine.llm import OllamaChat+from tests.fakes.fake_ollama_chat_stream import FakeOllamaChatStream+++def _done(**counters: int) -> dict:+ return {"message": {"content": ""}, "done": True, **counters}+++def test_text_clauses_and_counters() -> None:+ with FakeOllamaChatStream() as fake:+ fake.script([+ {"message": {"content": "The moon is about "}, "done": False},+ {"message": {"content": "384,000 km away. "}, "done": False},+ {"message": {"content": "That is far."}, "done": False},+ _done(prompt_eval_count=120, prompt_eval_cached_count=100,+ prompt_eval_duration=50_000_000, eval_count=20, eval_duration=200_000_000),+ ])+ result = OllamaChat("m", base_url=fake.base_url).chat([{"role": "user", "content": "?"}])+ body = fake.requests[0]["body"]+ assert result.error == ""+ assert result.clauses == ["The moon is about 384,000 km away.", "That is far."]+ assert result.prompt_tokens == 120 and result.prompt_cached_tokens == 100+ assert result.generation_tps == 100.0+ assert result.t_first_token is not None and result.t_first_clause is not None+ assert body["think"] is False and body["options"]["num_ctx"] == 8192+ assert body["stream"] is True+++def test_tool_calls_are_collected() -> None:+ with FakeOllamaChatStream() as fake:+ fake.script([+ {"message": {"content": "", "tool_calls": [+ {"function": {"name": "set_timer", "arguments": {"minutes": 10}}}]}, "done": False},+ _done(),+ ])+ result = OllamaChat("m", base_url=fake.base_url).chat(+ [{"role": "user", "content": "timer"}], tools=[{"type": "function"}]+ )+ assert result.tool_calls == [{"name": "set_timer", "arguments": {"minutes": 10}}]+ assert result.text == ""+++def test_models_without_a_thinking_switch_are_retried_without_it() -> None:+ with FakeOllamaChatStream() as fake:+ fake.script_error(400, '{"error":"\\"m\\" does not support thinking"}')+ fake.script([{"message": {"content": "Hi."}, "done": False}, _done()])+ chat = OllamaChat("m", base_url=fake.base_url)+ result = chat.chat([{"role": "user", "content": "hi"}])+ second = chat.chat([{"role": "user", "content": "again"}])+ bodies = [r["body"] for r in fake.requests]+ assert result.text == "Hi."+ assert "think" in bodies[0] and "think" not in bodies[1] and "think" not in bodies[2]+ assert second.error == ""+++def test_server_errors_are_reported_not_raised() -> None:+ with FakeOllamaChatStream() as fake:+ fake.script_error(500, "boom")+ result = OllamaChat("m", base_url=fake.base_url).chat([{"role": "user", "content": "x"}])+ assert result.error.startswith("HTTP 500")diff --git a/tests/unit/voice_engine/test_package_contract.py b/tests/unit/voice_engine/test_package_contract.pynew file mode 100644index 0000000000..083de8859b--- /dev/null+++ b/tests/unit/voice_engine/test_package_contract.py@@ -0,0 +1,63 @@+"""The engine package stays installable into its own environment."""++from __future__ import annotations++import ast+import re+from pathlib import Path++import jarvis.voice_engine as engine+from jarvis.voice_engine import models++PACKAGE = Path(engine.__file__).parent+_HEAVY = {"onnxruntime", "sherpa_onnx", "torch", "pocket_tts", "faster_qwen3_tts", "mlx", "soxr",+ "psutil"}+++def _imports(path: Path) -> list[tuple[str, bool]]:+ """(module, imported at module scope) for every import in a file."""+ tree = ast.parse(path.read_text(encoding="utf-8"))+ top = {id(node) for node in tree.body}+ found = []+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ found += [(alias.name, id(node) in top) for alias in node.names]+ elif isinstance(node, ast.ImportFrom) and node.module:+ found.append((node.module, id(node) in top))+ return found+++def test_engine_imports_nothing_from_the_app() -> None:+ offenders = [+ (path.name, module)+ for path in PACKAGE.rglob("*.py")+ for module, _ in _imports(path)+ if module.startswith("jarvis.") and not module.startswith("jarvis.voice_engine")+ ]+ assert offenders == []+++def test_model_runtimes_are_imported_lazily() -> None:+ offenders = [+ (path.name, module)+ for path in PACKAGE.rglob("*.py")+ for module, at_top in _imports(path)+ if at_top and module.split(".")[0] in _HEAVY+ ]+ assert offenders == []+++def test_registry_sources_are_pinned() -> None:+ for source in models.REGISTRY.values():+ assert source.url.startswith("https://")+ assert re.fullmatch(r"[0-9a-f]{64}", source.sha256), source.name+ assert source.size > 0+ assert bool(source.unpacks_to) == source.is_archive+++def test_model_paths_live_under_the_given_root(tmp_path: Path) -> None:+ for name, source in models.REGISTRY.items():+ path = models.model_path(name, tmp_path)+ assert tmp_path in path.parents+ assert not models.is_present(name, tmp_path)+ assert path.name == (source.unpacks_to or source.filename)diff --git a/tests/unit/voice_engine/test_turn_and_vad.py b/tests/unit/voice_engine/test_turn_and_vad.pynew file mode 100644index 0000000000..ba3d8ef35d--- /dev/null+++ b/tests/unit/voice_engine/test_turn_and_vad.py@@ -0,0 +1,60 @@+"""Smart Turn features and the VAD endpointer, without any model runtime."""++from __future__ import annotations++import numpy as np++from jarvis.voice_engine.turn import log_mel, mel_filters, prepare_window+from jarvis.voice_engine.vad import FRAME_MS, Endpointer+++def test_window_keeps_the_end_and_pads_the_beginning() -> None:+ short = np.ones(16_000, dtype=np.float32)+ window = prepare_window(short)+ assert window.shape == (128_000,)+ assert window[:-16_000].sum() == 0 and window[-16_000:].sum() == 16_000+ long = np.arange(200_000, dtype=np.float32)+ assert prepare_window(long)[-1] == 199_999+++def test_log_mel_shape_and_gain_invariance() -> None:+ rng = np.random.default_rng(1)+ audio = (0.1 * rng.standard_normal(48_000)).astype(np.float32)+ features = log_mel(audio)+ assert features.shape == (80, 800)+ assert features.dtype == np.float32+ # Zero-mean/unit-variance normalisation makes the input level irrelevant,+ # which is what lets one threshold work for quiet and loud microphones.+ assert np.allclose(log_mel(audio * 7.0), features, atol=1e-4)+++def test_mel_bank_is_slaney_shaped() -> None:+ bank = mel_filters()+ assert bank.shape == (201, 80)+ assert (bank >= 0).all()+ assert np.count_nonzero(bank.sum(axis=0)) == 80+++def _feed(endpointer: Endpointer, probabilities: list[float]) -> list[tuple[str, int]]:+ events = []+ for p in probabilities:+ event = endpointer.feed(p)+ if event is not None:+ events.append((event.kind, event.at_ms))+ return events+++def test_endpointer_reports_start_pause_and_resume() -> None:+ endpointer = Endpointer(min_speech_ms=96, silence_ms=192)+ voiced, quiet = [0.9] * 10, [0.05] * 8+ events = _feed(endpointer, voiced + quiet + voiced)+ kinds = [kind for kind, _ in events]+ assert kinds == ["speech_start", "silence_start", "silence_end"]+ start, pause = events[0][1], events[1][1]+ assert start == 3 * FRAME_MS+ assert pause == (10 + 6) * FRAME_MS+++def test_endpointer_ignores_short_blips() -> None:+ endpointer = Endpointer(min_speech_ms=160, silence_ms=200)+ assert _feed(endpointer, [0.9, 0.9, 0.1, 0.9, 0.1] * 3) == []