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(speech): add pure mic-dBFS measurement + onboarding mic-level route
Ruben Lütke6e7bdf5d8362
diff --git a/jarvis/speech/diagnose.py b/jarvis/speech/diagnose.pyindex 7603c7eb0e..7d93961775 100644--- a/jarvis/speech/diagnose.py+++ b/jarvis/speech/diagnose.py@@ -22,6 +22,7 @@ import loggingimport osimport sysimport time+from collections.abc import Callablefrom pathlib import Pathimport numpy as np@@ -92,28 +93,51 @@ def step_devices() -> None:print(f" {marker} #{i:2d} {d['name']} (ch={d['max_output_channels']}, rate={int(d['default_samplerate'])})")+async def measure_mic_dbfs(+ duration_s: float = 3.0,+ *,+ on_frame: Callable[[float, float, int], None] | None = None,+) -> float:+ """Return the max dBFS heard over ``duration_s``; -120.0 if no samples / no+ device / any error. Pure measurement (no printing) — reused by the+ onboarding mic-level route (``GET /api/settings/wake-word/mic-level``) and+ by ``step_mic_level``'s CLI bars via the optional ``on_frame`` hook+ (called per chunk with ``(dbfs, running_max, n_samples)``). Never raises."""+ max_dbfs = -120.0+ try:+ async with MicrophoneCapture() as mic:+ t_end = time.time() + duration_s+ async for chunk in mic.stream():+ if time.time() >= t_end:+ break+ arr = pcm_bytes_to_np(chunk.pcm)+ rms = float(np.sqrt(np.mean(arr * arr)) + 1e-12)+ dbfs = 20.0 * float(np.log10(rms))+ max_dbfs = max(max_dbfs, dbfs)+ if on_frame is not None:+ on_frame(dbfs, max_dbfs, len(arr))+ except Exception: # noqa: BLE001 — headless / no device / any error → honest floor+ return -120.0+ return max_dbfs++async def step_mic_level(duration_s: float = 10.0) -> float:"""Measures the live mic level — the user should speak loudly, max dBFS is recorded."""_print_header(2, f"Mic level test ({int(duration_s)} seconds — SPEAK NOW!)")print("Speak loudly — count to ten or sing a bit.")print("Max level should be in the range -20 to -5 dBFS.")print()- max_dbfs = -120.0samples_seen = 0- t_end = time.time() + duration_s- async with MicrophoneCapture() as mic:- async for chunk in mic.stream():- if time.time() >= t_end:- break- arr = pcm_bytes_to_np(chunk.pcm)- rms = float(np.sqrt(np.mean(arr * arr)) + 1e-12)- dbfs = 20.0 * np.log10(rms)- max_dbfs = max(max_dbfs, dbfs)- samples_seen += len(arr)- bar_len = max(0, int((dbfs + 60) / 2)) # scales [-60 .. 0] → [0 .. 30]- bar = "█" * min(bar_len, 30)- sys.stdout.write(f"\r level: {dbfs:6.1f} dBFS {bar:<30s} (max: {max_dbfs:6.1f})")- sys.stdout.flush()++ def _render_bar(dbfs: float, running_max: float, n_samples: int) -> None:+ nonlocal samples_seen+ samples_seen += n_samples+ bar_len = max(0, int((dbfs + 60) / 2)) # scales [-60 .. 0] → [0 .. 30]+ bar = "█" * min(bar_len, 30)+ sys.stdout.write(f"\r level: {dbfs:6.1f} dBFS {bar:<30s} (max: {running_max:6.1f})")+ sys.stdout.flush()++ max_dbfs = await measure_mic_dbfs(duration_s=duration_s, on_frame=_render_bar)print()print(f"→ Samples received: {samples_seen} Max level: {max_dbfs:.1f} dBFS")if samples_seen == 0:diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.pyindex 8980276654..4e88c7a0f3 100644--- a/jarvis/ui/web/settings_routes.py+++ b/jarvis/ui/web/settings_routes.py@@ -693,6 +693,24 @@ async def download_wake_model(request: Request) -> dict[str, object]:}[email protected]("/wake-word/mic-level")+async def wake_mic_level() -> dict[str, object]:+ """Live mic dBFS for the onboarding wake step (Task 7: mic + spoken-word+ verification before ``acknowledgeWakeWord``). Never 500s — a headless/no-mic+ host reports ``no_device=True`` rather than raising. Warn threshold −40 dBFS+ matches ``jarvis.speech.diagnose`` (same measurement helper, so the CLI+ diagnostics and this route can never disagree on what "too quiet" means).+ """+ from jarvis.speech.diagnose import measure_mic_dbfs++ max_dbfs = await measure_mic_dbfs(duration_s=3.0)+ return {+ "max_dbfs": max_dbfs,+ "no_device": max_dbfs <= -119.9,+ "too_quiet": -119.9 < max_dbfs < -40.0,+ }++# ---------------------------------------------------------------------------# Push-to-talk hotkey (editable). GET current + safe suggestions; PUT to change.# Persisted to jarvis.toml [trigger].hotkey; applies on the next voice bootstrapdiff --git a/tests/unit/speech/test_mic_level_helper.py b/tests/unit/speech/test_mic_level_helper.pynew file mode 100644index 0000000000..050ceb41fc--- /dev/null+++ b/tests/unit/speech/test_mic_level_helper.py@@ -0,0 +1,100 @@+"""``measure_mic_dbfs`` is the pure mic-level measurement reused by the CLI+diagnostics (``step_mic_level``) and the onboarding mic-level route+(``GET /api/settings/wake-word/mic-level``). It must never raise -- a+headless host / missing device / any capture error degrades to the honest+floor -120.0 dBFS instead of bubbling up.+"""+import pytest++from jarvis.speech import diagnose+++async def test_measure_mic_dbfs_no_device_returns_floor(monkeypatch):+ class _NoMic:+ async def __aenter__(self):+ raise OSError("no device")++ async def __aexit__(self, *a):+ return False++ monkeypatch.setattr(diagnose, "MicrophoneCapture", lambda: _NoMic())+ val = await diagnose.measure_mic_dbfs(duration_s=0.1)+ assert val == -120.0 # honest floor, never raises+++async def test_measure_mic_dbfs_never_raises_on_unexpected_error(monkeypatch):+ """Any capture-time exception (not just "no device") still degrades honestly."""++ class _Boom:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *a):+ return False++ def stream(self):+ raise RuntimeError("PortAudio exploded")++ monkeypatch.setattr(diagnose, "MicrophoneCapture", lambda: _Boom())+ val = await diagnose.measure_mic_dbfs(duration_s=0.1)+ assert val == -120.0+++async def test_measure_mic_dbfs_reports_loud_signal(monkeypatch):+ """A real (mocked) mic stream yields a max dBFS well above the floor."""+ import numpy as np++ class _Chunk:+ def __init__(self, pcm: bytes) -> None:+ self.pcm = pcm++ class _LoudMic:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *a):+ return False++ async def stream(self):+ # A single loud full-scale int16 chunk.+ arr = np.full(160, 32767, dtype=np.int16)+ yield _Chunk(arr.tobytes())++ monkeypatch.setattr(diagnose, "MicrophoneCapture", lambda: _LoudMic())+ val = await diagnose.measure_mic_dbfs(duration_s=1.0)+ assert val > -1.0 # near 0 dBFS for a full-scale signal+++async def test_measure_mic_dbfs_invokes_on_frame_callback(monkeypatch):+ """The optional on_frame hook (used by step_mic_level's CLI bar) fires per+ chunk with (dbfs, running_max, n_samples) and never affects the return value."""+ import numpy as np++ class _Chunk:+ def __init__(self, pcm: bytes) -> None:+ self.pcm = pcm++ class _OneShotMic:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *a):+ return False++ async def stream(self):+ arr = np.full(160, 32767, dtype=np.int16)+ yield _Chunk(arr.tobytes())++ monkeypatch.setattr(diagnose, "MicrophoneCapture", lambda: _OneShotMic())+ calls = []+ val = await diagnose.measure_mic_dbfs(+ duration_s=1.0, on_frame=lambda dbfs, running_max, n: calls.append((dbfs, running_max, n))+ )+ assert len(calls) == 1+ dbfs, running_max, n = calls[0]+ assert running_max == val+ assert n == 160diff --git a/tests/unit/web/test_mic_level_route.py b/tests/unit/web/test_mic_level_route.pynew file mode 100644index 0000000000..26ae5ab58b--- /dev/null+++ b/tests/unit/web/test_mic_level_route.py@@ -0,0 +1,85 @@+"""GET /api/settings/wake-word/mic-level -- live mic dBFS for the onboarding+wake step (Task 7). Never 500s; reports too_quiet / no_device honestly.+"""+import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.ui.web.settings_routes import router+++def client(monkeypatch):+ import jarvis.speech.diagnose as d++ async def fake_measure(duration_s=3.0):+ return -45.0++ monkeypatch.setattr(d, "measure_mic_dbfs", fake_measure)+ app = FastAPI()+ app.include_router(router)+ return TestClient(app)+++def test_mic_level_reports_too_quiet(client):+ r = client.get("/api/settings/wake-word/mic-level")+ assert r.status_code == 200+ b = r.json()+ assert b["max_dbfs"] == -45.0+ assert b["too_quiet"] is True+ assert b["no_device"] is False+++def test_mic_level_reports_no_device(monkeypatch):+ import jarvis.speech.diagnose as d++ async def fake_measure(duration_s=3.0):+ return -120.0++ monkeypatch.setattr(d, "measure_mic_dbfs", fake_measure)+ app = FastAPI()+ app.include_router(router)+ client = TestClient(app)++ r = client.get("/api/settings/wake-word/mic-level")+ assert r.status_code == 200+ b = r.json()+ assert b["no_device"] is True+ assert b["too_quiet"] is False+++def test_mic_level_reports_good_level(monkeypatch):+ import jarvis.speech.diagnose as d++ async def fake_measure(duration_s=3.0):+ return -15.0++ monkeypatch.setattr(d, "measure_mic_dbfs", fake_measure)+ app = FastAPI()+ app.include_router(router)+ client = TestClient(app)++ r = client.get("/api/settings/wake-word/mic-level")+ assert r.status_code == 200+ b = r.json()+ assert b["max_dbfs"] == -15.0+ assert b["too_quiet"] is False+ assert b["no_device"] is False+++def test_mic_level_never_500s_on_helper_error(monkeypatch):+ """Even if the underlying measurement blows up, the route stays honest --+ though measure_mic_dbfs itself never raises, this guards the route+ contract independently in case that invariant is ever broken upstream."""+ import jarvis.speech.diagnose as d++ async def fake_measure(duration_s=3.0):+ return -120.0 # the real helper's own honest floor on any error++ monkeypatch.setattr(d, "measure_mic_dbfs", fake_measure)+ app = FastAPI()+ app.include_router(router)+ client = TestClient(app)++ r = client.get("/api/settings/wake-word/mic-level")+ assert r.status_code == 200