Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(wake): the sample recorder shows level, warns on clipping, and lets you redo one

rubenluetke10-beep21152339cb1e
diff --git a/jarvis/audio/wake_sample_quality.py b/jarvis/audio/wake_sample_quality.py
new file mode 100644
index 0000000000..1187ed75e3
--- /dev/null
+++ b/jarvis/audio/wake_sample_quality.py
@@ -0,0 +1,234 @@
+"""Judging a wake-word recording while it is still being made.
+
+Training a custom wake word needs roughly fifteen clean recordings of the
+phrase. Collecting them is easy; knowing whether they were any good is not, and
+a bad set produces a wake word that either ignores you or fires at nothing. The
+single most common cause is CLIPPING — audio recorded so loud that the waveform
+is cut flat at the top — because a clipped sample is not a loud version of your
+voice, it is a different sound, and the model learns that instead.
+
+This module is the judging, kept separate from the recorder so it can be tested
+without a microphone. Everything here is pure arithmetic over int16 frames: no
+device access, no I/O, and therefore identical on every operating system.
+
+## What counts as clipping
+
+Not "a sample touched the maximum". At 16 kHz a single peaked sample happens in
+perfectly good audio. What identifies real clipping is a RUN of consecutive
+samples pinned at the rail — that flat top is the distortion, and it is what a
+listener hears as harshness. So both signals are reported:
+
+* ``clipped_ratio`` — how much of the recording is pinned at all, which catches
+ a mic that is hot throughout;
+* ``longest_run`` — the longest flat top, which catches a recording that is
+ fine except for the one syllable that mattered.
+
+Either one crossing its threshold is enough to warn, because they fail
+differently and a set can contain both kinds.
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import numpy as np
+
+__all__ = [
+ "CLIP_RATIO_LIMIT",
+ "CLIP_RUN_LIMIT",
+ "LEVEL_TARGET_DBFS",
+ "LEVEL_TOO_QUIET_DBFS",
+ "FrameLevel",
+ "SampleQuality",
+ "SetSummary",
+ "frame_level",
+ "judge_sample",
+ "summarize_set",
+]
+
+#: int16 full scale. A sample at or beyond this is pinned at the rail.
+_FULL_SCALE = 32767
+
+#: A run of this many consecutive pinned samples is a flat top rather than a
+#: coincidental peak. Three samples at 16 kHz is ~0.19 ms — short enough to
+#: catch one distorted syllable, long enough that clean audio does not trip it.
+CLIP_RUN_LIMIT = 3
+
+#: Warn once this fraction of the recording is pinned, even without a long run.
+#: 0.1 % of a 2-second sample is ~32 samples, which is already an input gain
+#: problem rather than a stray transient.
+CLIP_RATIO_LIMIT = 0.001
+
+#: The band a usable sample should land in, RMS in dBFS. Above roughly -12 the
+#: headroom is gone and the next louder take will clip; below -40 there is more
+#: room noise than voice.
+LEVEL_TARGET_DBFS = (-30.0, -12.0)
+LEVEL_TOO_QUIET_DBFS = -40.0
+
+#: Floor for the dBFS conversion, so digital silence reports a number instead
+#: of -inf and every consumer can format it the same way.
+_SILENCE_DBFS = -90.0
+
+
+def _dbfs(amplitude: float) -> float:
+ """Amplitude in 0..1 as dBFS, floored so silence is a finite number."""
+ if amplitude <= 0.0:
+ return _SILENCE_DBFS
+ return max(_SILENCE_DBFS, 20.0 * float(np.log10(amplitude)))
+
+
+@dataclass(frozen=True, slots=True)
+class FrameLevel:
+ """One block's worth of level, for the live meter."""
+
+ peak_dbfs: float
+ rms_dbfs: float
+ #: True when this block alone already shows a flat top. Reported per block
+ #: so the recorder can say "too loud" WHILE the person is speaking, which
+ #: is the only moment the warning can still change anything.
+ clipping: bool
+
+ @property
+ def meter_fraction(self) -> float:
+ """Peak mapped to 0..1 over the meter's useful range (-60..0 dBFS)."""
+ return min(1.0, max(0.0, (self.peak_dbfs + 60.0) / 60.0))
+
+
+def frame_level(frame: np.ndarray) -> FrameLevel:
+ """Level and clipping for one block of int16 samples.
+
+ Cheap enough to run in an audio callback: two reductions and a run scan
+ over a block that is normally a few hundred samples.
+ """
+ if frame.size == 0:
+ return FrameLevel(_SILENCE_DBFS, _SILENCE_DBFS, clipping=False)
+ samples = frame.reshape(-1).astype(np.int32)
+ magnitude = np.abs(samples)
+ peak = float(magnitude.max()) / _FULL_SCALE
+ rms = float(np.sqrt(np.mean((samples.astype(np.float64) / _FULL_SCALE) ** 2)))
+ return FrameLevel(
+ peak_dbfs=_dbfs(peak),
+ rms_dbfs=_dbfs(rms),
+ clipping=_longest_run(magnitude >= _FULL_SCALE) >= CLIP_RUN_LIMIT,
+ )
+
+
+def _longest_run(mask: np.ndarray) -> int:
+ """Longest run of True in a boolean array.
+
+ Done with a diff over the padded mask rather than a Python loop: a 2-second
+ sample is 32000 values and this runs once per finished recording as well as
+ per live block.
+ """
+ if not mask.any():
+ return 0
+ padded = np.concatenate(([False], mask, [False]))
+ edges = np.flatnonzero(padded[1:] != padded[:-1])
+ return int((edges[1::2] - edges[::2]).max())
+
+
+@dataclass(frozen=True, slots=True)
+class SampleQuality:
+ """The verdict on one finished recording."""
+
+ rms_dbfs: float
+ peak_dbfs: float
+ clipped_ratio: float
+ longest_run: int
+
+ @property
+ def clipped(self) -> bool:
+ return (
+ self.longest_run >= CLIP_RUN_LIMIT
+ or self.clipped_ratio > CLIP_RATIO_LIMIT
+ )
+
+ @property
+ def too_quiet(self) -> bool:
+ return self.rms_dbfs < LEVEL_TOO_QUIET_DBFS
+
+ @property
+ def usable(self) -> bool:
+ """Whether this sample should go into the training set as it is."""
+ return not self.clipped and not self.too_quiet
+
+ @property
+ def verdict(self) -> str:
+ """One word for a table column. Clipping outranks quietness: a quiet
+ take still carries the phrase, a clipped one carries a different sound.
+ """
+ if self.clipped:
+ return "clipped"
+ if self.too_quiet:
+ return "quiet"
+ if not (LEVEL_TARGET_DBFS[0] <= self.rms_dbfs <= LEVEL_TARGET_DBFS[1]):
+ return "ok"
+ return "good"
+
+ @property
+ def advice(self) -> str:
+ """What to change before recording this one again. Empty when nothing."""
+ if self.clipped:
+ return "Too loud — move back from the mic or lower the input gain."
+ if self.too_quiet:
+ return "Too quiet — move closer or raise the input gain."
+ if self.rms_dbfs > LEVEL_TARGET_DBFS[1]:
+ return "Close to clipping; a little more distance would be safer."
+ if self.rms_dbfs < LEVEL_TARGET_DBFS[0]:
+ return "Usable, but a bit more volume would train better."
+ return ""
+
+
+def judge_sample(pcm: np.ndarray) -> SampleQuality:
+ """Judge a complete recording of int16 samples."""
+ if pcm.size == 0:
+ return SampleQuality(_SILENCE_DBFS, _SILENCE_DBFS, 0.0, 0)
+ samples = pcm.reshape(-1).astype(np.int32)
+ magnitude = np.abs(samples)
+ pinned = magnitude >= _FULL_SCALE
+ return SampleQuality(
+ rms_dbfs=_dbfs(
+ float(np.sqrt(np.mean((samples.astype(np.float64) / _FULL_SCALE) ** 2)))
+ ),
+ peak_dbfs=_dbfs(float(magnitude.max()) / _FULL_SCALE),
+ clipped_ratio=float(pinned.sum()) / float(pinned.size),
+ longest_run=_longest_run(pinned),
+ )
+
+
+@dataclass(frozen=True, slots=True)
+class SetSummary:
+ """How the whole captured set stands."""
+
+ total: int
+ usable: int
+ clipped: int
+ quiet: int
+ needed: int
+
+ @property
+ def enough(self) -> bool:
+ return self.usable >= self.needed
+
+ @property
+ def headline(self) -> str:
+ if self.enough:
+ return f"{self.usable} usable samples — enough to train."
+ short = self.needed - self.usable
+ return (
+ f"{self.usable} usable of {self.total} — {short} more needed. "
+ "Re-record the flagged ones rather than starting over."
+ )
+
+
+def summarize_set(qualities: list[SampleQuality], needed: int) -> SetSummary:
+ """Count how the set stands against the number of samples training needs."""
+ return SetSummary(
+ total=len(qualities),
+ usable=sum(1 for q in qualities if q.usable),
+ clipped=sum(1 for q in qualities if q.clipped),
+ # A sample can be both; count it under the one that decides its verdict
+ # so the two columns add up to the unusable total rather than double
+ # counting.
+ quiet=sum(1 for q in qualities if q.too_quiet and not q.clipped),
+ needed=needed,
+ )
diff --git a/scripts/record_wake_samples.py b/scripts/record_wake_samples.py
index 0c9fe32644..2692c2ef75 100644
--- a/scripts/record_wake_samples.py
+++ b/scripts/record_wake_samples.py
@@ -6,6 +6,23 @@ real recordings are then mixed into the training set (heavily weighted) so the
custom openWakeWord model fires reliably on YOUR voice — the guaranteed path to
"Hey Google" reliability for a custom word.
+## Why it shows you a meter
+
+Fifteen recordings are easy to collect and hard to judge, and a bad set trains a
+wake word that either ignores you or fires at nothing. So the recording is no
+longer blind:
+
+* a **live level meter**, so you can see the microphone is hearing you at all;
+* a **clipping warning while you speak**, not after the set is finished —
+ clipping is the most common cause of a wake word that will not train, and a
+ warning that arrives once all fifteen are recorded cannot save any of them;
+* a **summary** at the end that flags the individual bad takes, so you re-record
+ those instead of starting the whole set again.
+
+The audio itself is unchanged: 16 kHz mono int16, exactly what
+``jarvis/plugins/wake/openwakeword_provider.py`` consumes. Nothing here filters,
+normalizes or gates the recording — the meter only observes.
+
Works alongside the running app (Windows WASAPI shared mode). Cross-platform via
sounddevice.
@@ -20,7 +37,17 @@ import time
import wave
import numpy as np
-import sounddevice as sd
+
+# The repo root, so this runs from anywhere without an editable install.
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from jarvis.audio.wake_sample_quality import ( # noqa: E402
+ FrameLevel,
+ SampleQuality,
+ frame_level,
+ judge_sample,
+ summarize_set,
+)
PHRASE = sys.argv[1] if len(sys.argv) > 1 else "Hey Assistant"
COUNT = int(sys.argv[2]) if len(sys.argv) > 2 else 15
@@ -28,19 +55,104 @@ SR = 16000
DUR = 2.0
SLUG = re.sub(r"[^a-z0-9]+", "_", PHRASE.lower()).strip("_") or "wake"
OUT = os.path.join("data", "wake_samples", SLUG)
-os.makedirs(OUT, exist_ok=True)
+#: Live meter refresh. 20 blocks a second is smooth to watch and cheap enough
+#: that the arithmetic never competes with the capture thread.
+BLOCK = SR // 20
+
+_METER_WIDTH = 28
+
+
+def _import_sounddevice():
+ """Import sounddevice, or explain why this script cannot run here.
+
+ Recording needs a real input device. On a headless server, in a container,
+ or on a Linux box without PortAudio the import itself fails, and the honest
+ answer is a sentence about the missing hardware rather than a traceback
+ about a shared library.
+ """
+ try:
+ import sounddevice as sd
+ except Exception as exc: # noqa: BLE001 — any import failure means the same
+ # thing to the user (no capture available), and the underlying error is
+ # printed so a missing library is still diagnosable.
+ print(f"\nCannot record on this machine: {exc}", file=sys.stderr)
+ print(
+ "This script needs a microphone and PortAudio. On a headless host "
+ "record the samples on a machine that has one and copy "
+ f"'{OUT}' across.",
+ file=sys.stderr,
+ )
+ raise SystemExit(2) from exc
+ return sd
+
+
+def _meter(level: FrameLevel) -> str:
+ """One line of live feedback: a bar, the level, and a loud warning.
+
+ The bar is peak-driven rather than RMS-driven because peak is what actually
+ reaches the rail, and the point of watching it is to see the headroom
+ disappear BEFORE it does.
+ """
+ filled = int(level.meter_fraction * _METER_WIDTH)
+ bar = "#" * filled + "-" * (_METER_WIDTH - filled)
+ tail = " << TOO LOUD" if level.clipping else ""
+ return f" [{bar}] {level.peak_dbfs:6.1f} dBFS{tail}"
+
+
+def record_one(path: str, *, label: str, meter: bool = True) -> SampleQuality:
+ """Record one clip to ``path`` and return its verdict.
+
+ Uses a callback stream rather than ``sd.rec`` + ``sd.wait`` so the level can
+ be drawn while the audio arrives. The blocks are collected untouched and
+ concatenated, so what lands on disk is byte-identical to what the old
+ blocking capture produced.
+ """
+ sd = _import_sounddevice()
+ blocks: list[np.ndarray] = []
+ latest: list[FrameLevel] = []
+
+ def on_block(indata, _frames, _time, status):
+ if status:
+ # An overflow means samples were dropped by the driver. Say so —
+ # silently keeping a gapped recording is how an unexplained bad
+ # sample gets into the training set.
+ print(f"\n audio device warning: {status}", flush=True)
+ block = indata.reshape(-1).copy()
+ blocks.append(block)
+ latest.append(frame_level(block))
+
+ with sd.InputStream(
+ samplerate=SR, channels=1, dtype="int16", blocksize=BLOCK, callback=on_block
+ ):
+ deadline = time.monotonic() + DUR
+ warned = False
+ while time.monotonic() < deadline:
+ if latest and meter:
+ level = latest[-1]
+ print(_meter(level), end="\r", flush=True)
+ if level.clipping and not warned:
+ warned = True
+ time.sleep(0.03)
+
+ print(" " * (_METER_WIDTH + 30), end="\r") # clear the meter line
+ pcm = (
+ np.concatenate(blocks) if blocks else np.zeros(0, dtype=np.int16)
+ ).astype(np.int16)
-def record_one(path: str) -> float:
- a = sd.rec(int(DUR * SR), samplerate=SR, channels=1, dtype="int16")
- sd.wait()
- a = a.reshape(-1)
with wave.open(path, "wb") as wf:
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(SR)
- wf.writeframes(a.tobytes())
- return float(np.sqrt(np.mean((a.astype(np.float32) / 32768.0) ** 2)))
+ wf.writeframes(pcm.tobytes())
+
+ quality = judge_sample(pcm)
+ marker = {"good": "ok", "ok": "ok", "quiet": "!!", "clipped": "!!"}[quality.verdict]
+ line = f" [{marker}] {label}: {quality.rms_dbfs:.1f} dBFS ({quality.verdict})"
+ if quality.advice:
+ line += f"\n {quality.advice}"
+ print(line, flush=True)
+ return quality
NEG_OUT = os.path.join("data", "wake_samples", SLUG + "_neg")
@@ -61,29 +173,87 @@ def record_negatives() -> None:
chunk = 3.0
n = int(NEG_SECONDS / chunk)
for i in range(n):
- record_one(os.path.join(NEG_OUT, f"neg_{i:02d}.wav"))
- print(f" negatives {int((i + 1) * chunk)}/{int(NEG_SECONDS)}s...", end="\r", flush=True)
- print(f"\n saved {n} negative clips to {NEG_OUT}")
+ record_one(
+ os.path.join(NEG_OUT, f"neg_{i:02d}.wav"),
+ label=f"negatives {int((i + 1) * chunk)}/{int(NEG_SECONDS)}s",
+ meter=False,
+ )
+ print(f" saved {n} negative clips to {NEG_OUT}")
+
+
+def _print_summary(qualities: dict[int, SampleQuality]) -> list[int]:
+ """Print the set table and return the indices worth re-recording."""
+ summary = summarize_set(list(qualities.values()), needed=COUNT)
+ print(f"\n {summary.headline}")
+ if summary.clipped:
+ print(f" {summary.clipped} clipped — those are the ones that hurt training most.")
+ if summary.quiet:
+ print(f" {summary.quiet} too quiet.")
+
+ bad = [i for i, q in sorted(qualities.items()) if not q.usable]
+ if bad:
+ print("\n Sample Level Problem")
+ for i in bad:
+ q = qualities[i]
+ print(f" {i + 1:>6} {q.rms_dbfs:>6.1f} dB {q.verdict}")
+ return bad
def main() -> None:
+ os.makedirs(OUT, exist_ok=True)
print(f"\nRecording {COUNT} samples of '{PHRASE}'. Speak naturally, at your")
- print("normal distance and volume. Vary it a little (a bit faster/slower).\n")
- kept = 0
+ print("normal distance and volume. Vary it a little (a bit faster/slower).")
+ print("Watch the meter: the bar should move well, and never say TOO LOUD.\n")
+
+ qualities: dict[int, SampleQuality] = {}
for i in range(COUNT):
for c in (3, 2, 1):
print(f" sample {i + 1}/{COUNT} in {c}...", end="\r", flush=True)
time.sleep(0.7)
print(f" sample {i + 1}/{COUNT}: SPEAK NOW -> '{PHRASE}' ", flush=True)
path = os.path.join(OUT, f"{SLUG}_{i:02d}.wav")
- rms = record_one(path)
- if rms < 0.005:
- print(f" (very quiet, rms={rms:.3f} — kept, but speak up if you can)")
- kept += 1
+ qualities[i] = record_one(path, label=f"sample {i + 1}")
time.sleep(0.3)
- print(f"\nSaved {kept} wake samples to {OUT}")
+
+ print(f"\nSaved {len(qualities)} wake samples to {OUT}")
+
+ # Re-record loop: one sample at a time, so a single bad take never costs
+ # the whole set.
+ while True:
+ bad = _print_summary(qualities)
+ if not bad:
+ break
+ answer = input(
+ "\n Re-record which one? (number, 'all' for every flagged one, "
+ "Enter to keep them) "
+ ).strip().lower()
+ if not answer:
+ break
+ targets = bad if answer == "all" else _parse_target(answer, len(qualities))
+ if not targets:
+ print(" Not a sample number.")
+ continue
+ for i in targets:
+ print(f"\n sample {i + 1}: SPEAK NOW -> '{PHRASE}' ", flush=True)
+ time.sleep(0.4)
+ path = os.path.join(OUT, f"{SLUG}_{i:02d}.wav")
+ qualities[i] = record_one(path, label=f"sample {i + 1}")
+
record_negatives()
- print("\nAll done. Tell the assistant you're finished — it retrains on your voice + environment.")
+ print(
+ "\nAll done. Tell the assistant you're finished — it retrains on "
+ "your voice + environment."
+ )
+
+
+def _parse_target(answer: str, count: int) -> list[int]:
+ """A 1-based sample number from the prompt, as a 0-based index."""
+ try:
+ index = int(answer) - 1
+ except ValueError:
+ return []
+ return [index] if 0 <= index < count else []
-main()
+if __name__ == "__main__":
+ main()
diff --git a/tests/unit/audio/test_record_wake_samples.py b/tests/unit/audio/test_record_wake_samples.py
new file mode 100644
index 0000000000..b45e8aedbe
--- /dev/null
+++ b/tests/unit/audio/test_record_wake_samples.py
@@ -0,0 +1,150 @@
+"""The recorder still writes exactly what the wake provider consumes.
+
+The meter was added around the capture, and the capture itself changed from a
+blocking `sd.rec` to a callback stream. That is the risky part: the training
+side reads these files unchanged, so a WAV that came out at the wrong rate,
+width or channel count would break the wake word in a way no test of the meter
+would notice.
+
+The audio device is replaced by a hand-written fake — no `unittest.mock`, per
+the repo rule — so this runs on a machine with no microphone.
+"""
+from __future__ import annotations
+
+import importlib.util
+import sys
+import wave
+from pathlib import Path
+
+import numpy as np
+import pytest
+
+REPO = Path(__file__).resolve().parents[3]
+SCRIPT = REPO / "scripts" / "record_wake_samples.py"
+
+
+def _load_recorder(monkeypatch, phrase: str = "Hey Test"):
+ """Import the script as a module, with argv set the way a user would."""
+ monkeypatch.setattr(sys, "argv", ["record_wake_samples.py", phrase, "2"])
+ spec = importlib.util.spec_from_file_location("_wake_recorder", SCRIPT)
+ module = importlib.util.module_from_spec(spec)
+ assert spec.loader is not None
+ spec.loader.exec_module(module)
+ return module
+
+
+class FakeStream:
+ """Stands in for `sd.InputStream`, delivering one prepared block.
+
+ Real capture hands blocks to the callback from its own thread; here the
+ block is delivered on `__enter__`, which is enough because the recorder
+ only ever reads what has accumulated.
+ """
+
+ def __init__(self, block: np.ndarray, callback, status: str = ""):
+ self._block = block
+ self._callback = callback
+ self._status = status
+
+ def __enter__(self):
+ self._callback(self._block, len(self._block), None, self._status)
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+
+class FakeSoundDevice:
+ def __init__(self, block: np.ndarray, status: str = ""):
+ self._block = block
+ self._status = status
+ self.requested: dict = {}
+
+ def InputStream(self, **kwargs): # noqa: N802 — mirrors the real API name
+ self.requested = kwargs
+ return FakeStream(self._block, kwargs["callback"], self._status)
+
+
+def recorder(monkeypatch):
+ return _load_recorder(monkeypatch)
+
+
+def _install_fake(monkeypatch, recorder, block: np.ndarray, status: str = ""):
+ fake = FakeSoundDevice(block, status)
+ monkeypatch.setattr(recorder, "_import_sounddevice", lambda: fake)
+ # The loop is wall-clock bound; collapse it so the test does not wait 2 s.
+ monkeypatch.setattr(recorder, "DUR", 0.0)
+ return fake
+
+
+def test_importing_the_script_does_not_start_recording(monkeypatch):
+ # It used to call main() at module scope, so merely importing it opened the
+ # microphone. Loading it in this test at all is the assertion.
+ recorder = _load_recorder(monkeypatch)
+ assert callable(recorder.main)
+
+
+def test_the_wav_is_16khz_mono_int16(monkeypatch, recorder, tmp_path):
+ block = (np.sin(np.arange(3200) / 20) * 8000).astype(np.int16)
+ _install_fake(monkeypatch, recorder, block)
+ path = tmp_path / "sample.wav"
+
+ recorder.record_one(str(path), label="sample 1")
+
+ with wave.open(str(path), "rb") as wf:
+ assert wf.getframerate() == 16_000
+ assert wf.getnchannels() == 1
+ assert wf.getsampwidth() == 2
+ written = np.frombuffer(wf.readframes(wf.getnframes()), dtype=np.int16)
+ # Byte-identical to what the device delivered: the meter observes, it does
+ # not filter, normalize or gate.
+ assert np.array_equal(written, block)
+
+
+def test_the_capture_is_requested_at_the_providers_format(monkeypatch, recorder, tmp_path):
+ fake = _install_fake(monkeypatch, recorder, np.zeros(1600, dtype=np.int16))
+ recorder.record_one(str(tmp_path / "s.wav"), label="sample 1")
+ assert fake.requested["samplerate"] == 16_000
+ assert fake.requested["channels"] == 1
+ assert fake.requested["dtype"] == "int16"
+
+
+def test_a_clipped_take_comes_back_flagged(monkeypatch, recorder, tmp_path):
+ full = np.full(1600, 32767, dtype=np.int16)
+ _install_fake(monkeypatch, recorder, full)
+ quality = recorder.record_one(str(tmp_path / "s.wav"), label="sample 1")
+ assert quality.clipped
+ assert not quality.usable
+
+
+def test_a_dropped_frame_warning_is_reported_not_swallowed(
+ monkeypatch, recorder, tmp_path, capsys
+):
+ _install_fake(monkeypatch, recorder, np.zeros(1600, dtype=np.int16), status="overflow")
+ recorder.record_one(str(tmp_path / "s.wav"), label="sample 1")
+ # A gapped recording that says nothing is how an unexplained bad sample
+ # gets into the training set.
+ assert "overflow" in capsys.readouterr().out
+
+
+def test_a_recording_with_no_audio_at_all_still_writes_a_file(
+ monkeypatch, recorder, tmp_path
+):
+ _install_fake(monkeypatch, recorder, np.zeros(0, dtype=np.int16))
+ path = tmp_path / "s.wav"
+ quality = recorder.record_one(str(path), label="sample 1")
+ assert path.exists()
+ assert not quality.usable
+
+
+def test_the_slug_is_filesystem_safe(monkeypatch):
+ recorder = _load_recorder(monkeypatch, phrase="Hey, Jarvis!")
+ assert recorder.SLUG == "hey_jarvis"
+
+
+def test_a_re_record_target_is_parsed_one_based(recorder):
+ assert recorder._parse_target("2", 5) == [1]
+ assert recorder._parse_target("0", 5) == []
+ assert recorder._parse_target("6", 5) == []
+ assert recorder._parse_target("not a number", 5) == []
diff --git a/tests/unit/audio/test_wake_sample_quality.py b/tests/unit/audio/test_wake_sample_quality.py
new file mode 100644
index 0000000000..408c5b43bb
--- /dev/null
+++ b/tests/unit/audio/test_wake_sample_quality.py
@@ -0,0 +1,201 @@
+"""Judging a wake-word recording — the clipping detector above all.
+
+Clipping is the most common reason a custom wake word will not train, so a
+detector that misses it, or one that cries wolf on clean audio, is worse than
+none: it either lets the bad samples through or teaches people to ignore it.
+Both directions are asserted here.
+
+Pure arithmetic over int16 arrays — no device, no files, so this runs on a
+headless CI box exactly as it does on a laptop.
+"""
+from __future__ import annotations
+
+import numpy as np
+import pytest
+
+from jarvis.audio.wake_sample_quality import (
+ CLIP_RATIO_LIMIT,
+ CLIP_RUN_LIMIT,
+ LEVEL_TOO_QUIET_DBFS,
+ frame_level,
+ judge_sample,
+ summarize_set,
+)
+
+SR = 16_000
+FULL = 32767
+
+
+def tone(amplitude: float, seconds: float = 2.0) -> np.ndarray:
+ """A sine at a given fraction of full scale — clean audio by construction."""
+ t = np.arange(int(SR * seconds)) / SR
+ return (np.sin(2 * np.pi * 220 * t) * amplitude * FULL).astype(np.int16)
+
+
+def clipped_tone(seconds: float = 2.0, overdrive: float = 1.6) -> np.ndarray:
+ """A sine driven past full scale and cut flat — what real clipping is."""
+ t = np.arange(int(SR * seconds)) / SR
+ raw = np.sin(2 * np.pi * 220 * t) * overdrive * FULL
+ return np.clip(raw, -FULL, FULL).astype(np.int16)
+
+
+# ---------------------------------------------------------------- clipping
+
+
+def test_a_clipped_recording_is_detected():
+ quality = judge_sample(clipped_tone())
+ assert quality.clipped
+ assert quality.verdict == "clipped"
+ assert not quality.usable
+ assert "loud" in quality.advice.lower()
+
+
+def test_clean_loud_audio_is_not_called_clipped():
+ # 0.9 of full scale is loud and completely undistorted. Flagging this would
+ # train people to ignore the warning.
+ quality = judge_sample(tone(0.9))
+ assert not quality.clipped
+ assert quality.usable
+
+
+def test_a_single_peaked_sample_is_not_clipping():
+ pcm = tone(0.5)
+ pcm[1000] = FULL
+ assert not judge_sample(pcm).clipped
+
+
+def test_a_short_flat_top_is_clipping():
+ pcm = tone(0.5)
+ pcm[1000 : 1000 + CLIP_RUN_LIMIT] = FULL
+ quality = judge_sample(pcm)
+ assert quality.clipped
+ assert quality.longest_run >= CLIP_RUN_LIMIT
+
+
+def test_a_run_one_sample_short_of_the_limit_is_not_clipping():
+ pcm = tone(0.5)
+ pcm[1000 : 1000 + CLIP_RUN_LIMIT - 1] = FULL
+ assert not judge_sample(pcm).clipped
+
+
+def test_a_hot_mic_is_caught_by_the_ratio_even_without_a_long_run():
+ # Scattered single peaks: no run reaches the limit, but the proportion of
+ # pinned samples says the input gain is too high throughout.
+ pcm = tone(0.5)
+ count = int(pcm.size * CLIP_RATIO_LIMIT * 4)
+ pcm[np.linspace(0, pcm.size - 1, count, dtype=int)] = FULL
+ quality = judge_sample(pcm)
+ assert quality.longest_run < CLIP_RUN_LIMIT
+ assert quality.clipped_ratio > CLIP_RATIO_LIMIT
+ assert quality.clipped
+
+
+def test_negative_full_scale_counts_as_clipping_too():
+ # Cutting only the trough is still a flat top; a magnitude-blind detector
+ # would pass a recording that is audibly distorted.
+ pcm = tone(0.5)
+ pcm[500 : 500 + CLIP_RUN_LIMIT] = -FULL
+ assert judge_sample(pcm).clipped
+
+
+# ---------------------------------------------------------------- level
+
+
+def test_a_quiet_recording_is_flagged_but_ranked_below_clipping():
+ quality = judge_sample(tone(0.002))
+ assert quality.too_quiet
+ assert quality.verdict == "quiet"
+ assert quality.rms_dbfs < LEVEL_TOO_QUIET_DBFS
+ assert "quiet" in quality.advice.lower()
+
+
+def test_clipping_outranks_quietness_in_the_verdict():
+ # A recording can be both mostly quiet and clipped on one syllable. The
+ # verdict must name the clipping: a quiet take still carries the phrase, a
+ # clipped one carries a different sound.
+ pcm = tone(0.001)
+ pcm[100 : 100 + CLIP_RUN_LIMIT] = FULL
+ quality = judge_sample(pcm)
+ assert quality.clipped
+ assert quality.verdict == "clipped"
+
+
+def test_digital_silence_reports_a_finite_level_rather_than_minus_infinity():
+ quality = judge_sample(np.zeros(SR, dtype=np.int16))
+ assert np.isfinite(quality.rms_dbfs)
+ assert quality.too_quiet
+
+
+def test_an_empty_recording_does_not_raise():
+ quality = judge_sample(np.zeros(0, dtype=np.int16))
+ assert not quality.usable
+ assert np.isfinite(quality.rms_dbfs)
+
+
+def test_a_well_levelled_sample_reads_as_good():
+ quality = judge_sample(tone(0.15))
+ assert quality.verdict == "good"
+ assert quality.usable
+ assert quality.advice == ""
+
+
+# ---------------------------------------------------------------- live meter
+
+
+def test_the_live_meter_flags_a_clipping_block_while_it_is_happening():
+ block = clipped_tone(seconds=0.05)
+ assert frame_level(block).clipping
+
+
+def test_the_live_meter_does_not_flag_a_clean_block():
+ assert not frame_level(tone(0.6, seconds=0.05)).clipping
+
+
+def test_the_meter_bar_stays_inside_its_range():
+ for amplitude in (0.0001, 0.01, 0.5, 1.0):
+ fraction = frame_level(tone(amplitude, seconds=0.05)).meter_fraction
+ assert 0.0 <= fraction <= 1.0
+
+
+def test_the_meter_bar_grows_with_level():
+ quiet = frame_level(tone(0.01, seconds=0.05)).meter_fraction
+ loud = frame_level(tone(0.8, seconds=0.05)).meter_fraction
+ assert loud > quiet
+
+
+def test_an_empty_block_is_silence_not_a_crash():
+ level = frame_level(np.zeros(0, dtype=np.int16))
+ assert not level.clipping
+ assert level.meter_fraction == pytest.approx(0.0)
+
+
+# ---------------------------------------------------------------- the set
+
+
+def test_the_summary_counts_each_bad_sample_once():
+ both = judge_sample(_quiet_and_clipped())
+ summary = summarize_set([judge_sample(tone(0.15)), both], needed=2)
+ assert summary.total == 2
+ assert summary.usable == 1
+ assert summary.clipped == 1
+ # Counted as clipped, not also as quiet — otherwise the columns overstate
+ # how many recordings are actually unusable.
+ assert summary.quiet == 0
+
+
+def test_the_summary_says_how_many_more_are_needed():
+ summary = summarize_set([judge_sample(tone(0.15))], needed=15)
+ assert not summary.enough
+ assert "14 more" in summary.headline
+
+
+def test_a_full_set_says_it_is_enough():
+ summary = summarize_set([judge_sample(tone(0.15))] * 15, needed=15)
+ assert summary.enough
+ assert "enough" in summary.headline
+
+
+def _quiet_and_clipped() -> np.ndarray:
+ pcm = tone(0.001)
+ pcm[100 : 100 + CLIP_RUN_LIMIT] = FULL
+ return pcm