fix(voice_worker): even out speaker loudness and stop transcribing noise into words

- Loudness equalisation replaces peak normalisation: rumble below 60 Hz removed, level measured on
  the VAD-voiced windows only, brought to -20 dBFS (gain -20..+40 dB), soft limiter below 0.98.
- Only clearly voiced windows (VAD >= 0.5) count towards the 250 ms needed before an utterance
  reaches the model, so noise the VAD half-believes never calls Whisper.
- Hallucination gate: mean token log-probability >= -0.7 (the old len/(len+1) correction let short
  hallucinations through), compression ratio <= 2.4; no_speech_prob dropped (always 0.0 on turbo).
- With hotwords, the plain decode of the same encoder pass decides; the hint may fix a wake word's
  spelling but cannot add or drop one (it wrote the wake word on laughter and after real sentences).
- Opt-in real-model evals: voice-like babble with the hint, speech over babble, quiet and clipped
  speakers, and a JARVIS_NOISE_DIR folder of real noise recordings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-11 10:27:38 +09:00
parent a7685e9078
commit 590cd07268
11 changed files with 460 additions and 54 deletions

View File

@@ -5,7 +5,7 @@ from __future__ import annotations
import numpy as np
import pytest
from voice_worker.audio import InputConverter, peak_normalise
from voice_worker.audio import InputConverter, loudness_equalise
from voice_worker.protocol import (KIND_AUDIO, KIND_TTS, ProtocolError, decode_audio_frame, encode_audio_frame,
encode_tts_frame, decode_tts_frame)
@@ -104,19 +104,70 @@ def test_odd_byte_counts_are_carried_to_the_next_frame():
assert len(a) + len(b) == 10
def _db(x: np.ndarray) -> float:
return 20 * np.log10(np.sqrt(np.mean(np.asarray(x, dtype=np.float64) ** 2)) + 1e-12)
def _voice(seconds: float, db: float) -> np.ndarray:
"""A stand-in for a voice: a 220 Hz tone with harmonics, at ``db`` dBFS RMS."""
t = np.arange(int(16000 * seconds)) / 16000
x = sum(np.sin(2 * np.pi * 220 * k * t) / k for k in (1, 2, 3, 4))
return (x * 10 ** (db / 20) / np.sqrt(np.mean(x ** 2))).astype(np.float32)
def _mask(n_samples: int, voiced: slice) -> np.ndarray:
m = np.zeros(-(-n_samples // 512), dtype=bool)
m[voiced] = True
return m
@pytest.mark.unit
def test_quiet_clip_is_raised_to_the_target_peak():
x = np.full(100, 0.2, dtype=np.float32)
assert np.isclose(np.max(np.abs(peak_normalise(x))), 0.9)
@pytest.mark.parametrize("db", [-60, -45, -30, -10, -3])
def test_every_speaker_level_comes_out_at_the_same_loudness(db):
x = _voice(2.0, db)
y = loudness_equalise(x)
assert y.dtype == np.float32 and len(y) == len(x)
assert abs(_db(y) - (-20)) < 1.0
@pytest.mark.unit
def test_loudness_is_measured_on_the_voice_not_the_silence_around_it():
x = np.concatenate([np.zeros(16000, dtype=np.float32), _voice(1.0, -40)])
y = loudness_equalise(x, _mask(len(x), slice(32, None)))
assert abs(_db(y[16000:]) - (-20)) < 1.0
@pytest.mark.unit
def test_a_loud_click_neither_keeps_a_quiet_voice_quiet_nor_clips():
x = _voice(2.0, -50)
burst = np.random.default_rng(3).normal(0, 1, 200) * np.exp(-np.arange(200) / 30)
x[8000:8200] += (0.95 * burst / np.max(np.abs(burst))).astype(np.float32) # a mouse click, far louder
voiced = _mask(len(x), slice(None))
voiced[8000 // 512] = False
y = loudness_equalise(x, voiced)
assert abs(_db(y[:7000]) - (-20)) < 1.0
assert np.max(np.abs(y)) < 1.0
@pytest.mark.unit
def test_clipped_shouting_is_brought_down_without_new_clipping():
x = np.clip(_voice(2.0, -3) * 4, -1, 1)
y = loudness_equalise(x)
assert abs(_db(y) - (-20)) < 1.5
assert np.max(np.abs(y)) < 1.0
@pytest.mark.unit
def test_near_silence_is_not_boosted_past_the_gain_cap():
x = np.full(100, 0.001, dtype=np.float32)
assert np.isclose(np.max(np.abs(peak_normalise(x))), 0.01)
x = _voice(1.0, -90)
assert abs(_db(loudness_equalise(x)) - (-90 + 40)) < 1.0
@pytest.mark.unit
def test_loud_clip_is_brought_down_to_the_target_peak():
x = np.array([0.0, 1.0, -0.5], dtype=np.float32)
assert np.isclose(np.max(np.abs(peak_normalise(x))), 0.9)
def test_low_rumble_is_removed_before_levelling():
t = np.arange(32000) / 16000
rumble = (0.3 * np.sin(2 * np.pi * 30 * t)).astype(np.float32)
y = loudness_equalise(_voice(2.0, -40) + rumble)
spec = np.abs(np.fft.rfft(y))
freqs = np.fft.rfftfreq(len(y), 1 / 16000)
assert spec[np.argmin(np.abs(freqs - 30))] < 0.01 * spec[np.argmin(np.abs(freqs - 220))]

View File

@@ -0,0 +1,80 @@
"""Voice worker: which Whisper transcripts are kept (the hallucination gate), model-free."""
from __future__ import annotations
import pytest
from voice_worker.stt_whisper import MIN_MEAN_LOGPROB, choose_with_hint, compression_ratio, keep_transcript
@pytest.mark.unit
def test_a_confident_transcript_is_kept():
assert keep_transcript("자비스, 오늘 서울 날씨 어때?", -0.05)
@pytest.mark.unit
def test_low_confidence_is_rejected_even_for_a_short_output():
# A three-token hallucination on laughter scored a mean of -0.73 per token; the length
# correction used before (len / (len + 1)) lifted it to -0.55 and let it through.
assert not keep_transcript("자비스", MIN_MEAN_LOGPROB - 0.03)
assert keep_transcript("자비스", MIN_MEAN_LOGPROB + 0.03)
@pytest.mark.unit
def test_empty_and_punctuation_only_outputs_are_rejected():
assert not keep_transcript("", -0.01)
assert not keep_transcript(" . . ", -0.01)
@pytest.mark.unit
def test_a_repetition_loop_is_rejected():
loop = "자막 제공 및 " * 12
assert compression_ratio(loop) > 2.4
assert not keep_transcript(loop, -0.1)
assert compression_ratio("오늘 회의는 오후 세 시에 시작해서 다섯 시쯤 끝날 것 같아요.") < 2.4
HINT = ("자비스",)
ASK = "지금 두 번째 모니터에 뭐 떠 있는지 알려줄래?"
@pytest.mark.unit
def test_voice_like_noise_that_the_hint_turns_into_the_wake_word_gives_nothing():
# Laughter, decoded with the wake word as a hint and without it.
assert choose_with_hint("자비스", -0.4, "감사합니다.", -1.4, HINT) == ""
assert choose_with_hint("자비스", -0.4, "", -0.1, HINT) == ""
@pytest.mark.unit
def test_a_wake_word_the_hint_adds_to_real_speech_is_dropped():
assert choose_with_hint(ASK + " 자비스", -0.1, ASK, -0.1, HINT) == ASK
@pytest.mark.unit
def test_the_hint_may_fix_how_a_spoken_wake_word_is_spelt():
fixed = "자비스, 오늘 서울 날씨 어때?"
assert choose_with_hint(fixed, -0.1, "자비수, 오늘 서울 날씨 어때?", -0.2, HINT) == fixed
@pytest.mark.unit
def test_a_wake_word_the_hint_loses_is_kept_from_the_plain_decode():
plain = "자비스, 오늘 서울 날씨 어때?"
assert choose_with_hint("오늘 서울 날씨 어때?", -0.2, plain, -0.07, HINT) == plain
@pytest.mark.unit
def test_an_unsure_hint_decode_falls_back_to_the_plain_one():
assert choose_with_hint(ASK, MIN_MEAN_LOGPROB - 0.2, ASK, -0.1, HINT) == ASK
assert choose_with_hint("zzz", -0.1, ASK, -0.1, HINT) == ASK
@pytest.mark.unit
def test_wake_word_matching_ignores_case_spacing_and_punctuation():
assert choose_with_hint("Hey Jarvis, lights off.", -0.1, "hey jarvis lights off", -0.1, ("jarvis",)) \
== "Hey Jarvis, lights off."
@pytest.mark.unit
def test_spacing_and_punctuation_differences_do_not_change_the_choice():
assert choose_with_hint("자비스 오늘 서울 날씨 어때", -0.1, "자비스, 오늘 서울 날씨 어때?", -0.1, HINT) \
== "자비스 오늘 서울 날씨 어때"

View File

@@ -171,7 +171,10 @@ def test_tts_reply_comes_back_as_the_same_words(engines):
if engines[2] is None:
pytest.skip("set JARVIS_MELO_PYTHON to the MeloTTS venv python")
from voice_worker.protocol import decode_tts_frame, encode_audio_frame
text = "오늘 서울은 맑고 기온은 이십삼 도예요. 우산은 필요 없어요."
# MeloTTS samples its voice differently each time and blurs some words ("기온은 이십삼" came back
# as "비오는 이시찬" in raw, peak-normalised and equalised audio alike), so the sentence is one it
# says clearly; this checks the worker's plumbing, not MeloTTS's diction.
text = "오늘 서울은 맑고 따뜻해요. 우산은 집에 두고 가셔도 돼요."
async def body(ws):
await ws.send(json.dumps({"type": "config", "partials": False}))
@@ -207,3 +210,106 @@ def test_tts_reply_comes_back_as_the_same_words(engines):
print(f"tts chunks={len(chunks)} first_chunk_s={first:.2f} heard={heard}")
assert [c[1] for c in chunks] == [0, 1]
assert cer(text, heard) <= 0.2
def _stream_clip_16k(engines, clip: np.ndarray, stt: dict) -> list[dict]:
"""Stream one 16 kHz mono clip as a single speaker (as fast as the socket takes it), end it,
and return every final the worker sends."""
from voice_worker.protocol import encode_audio_frame
pcm = (np.clip(to_48k_stereo(clip), -1, 1) * 32767).astype("<i2").tobytes()
step = 48000 * FRAME_MS // 1000 * 2 * 2
async def body(ws):
await ws.send(json.dumps({"type": "config", **stt}))
for k in range(0, len(pcm), step):
await ws.send(encode_audio_frame("s", pcm[k:k + step]))
await ws.send(json.dumps({"type": "speaking_end", "speaker": "s"}))
finals = []
while True:
try:
msg = json.loads(await asyncio.wait_for(ws.recv(), 3))
except asyncio.TimeoutError:
return finals
if msg["type"] == "final":
finals.append(msg)
return asyncio.run(with_worker(engines, body))
def _babble(seconds: float, rng) -> np.ndarray:
"""Speech-like noise: the kit's Korean clips played backwards and overlaid (voice-like, no words)."""
n = int(16000 * seconds)
x = np.zeros(n, dtype=np.float32)
for name in ("ko_01.wav", "ko_03.wav", "ko_05.wav", "ko_07.wav"):
c = load(name)[::-1]
x += np.roll(np.tile(c, n // len(c) + 1)[:n], int(rng.integers(0, n)))
return x
def _at_db(x: np.ndarray, db: float) -> np.ndarray:
return (x * 10 ** (db / 20) / (np.sqrt(np.mean(x.astype(np.float64) ** 2)) + 1e-12)).astype(np.float32)
@pytest.mark.parametrize("level_db", [-40, -25])
def test_voice_like_noise_with_the_wake_word_hint_produces_no_text(engines, level_db):
"""Backwards babble passes the VAD. Given the wake word as a hint, Whisper used to write the wake
word (a phantom call to the bot); without words in the audio no final may carry text."""
rng = np.random.default_rng(level_db + 100)
finals = _stream_clip_16k(engines, _at_db(_babble(6.0, rng), level_db),
{"hotwords": ["자비스"], "partials": False})
print(level_db, [(m["text"], m["end_reason"]) for m in finals])
assert all(m["text"] == "" for m in finals)
@pytest.mark.parametrize("snr_db", [20, 10])
def test_speech_over_voice_like_noise_keeps_the_words(engines, snr_db):
rng = np.random.default_rng(snr_db)
refs = json.loads((SAMPLES / "refs.json").read_text(encoding="utf-8"))["samples"]
errs = []
for r in refs[:4]:
speech = np.concatenate([np.zeros(8000, np.float32), _at_db(load(r["file"]), -25), np.zeros(8000, np.float32)])
noisy = speech + _at_db(_babble(len(speech) / 16000, rng), -25 - snr_db)
finals = _stream_clip_16k(engines, noisy, {"hotwords": ["자비스"], "partials": False})
text = " ".join(m["text"] for m in finals).strip()
errs.append(cer(r["text"], text))
print(snr_db, r["file"], round(errs[-1], 2), text)
assert np.mean(errs) <= 0.15
@pytest.mark.parametrize("level_db", [-60, -45, -10])
def test_quiet_and_loud_speakers_are_both_understood(engines, level_db):
refs = json.loads((SAMPLES / "refs.json").read_text(encoding="utf-8"))["samples"]
errs = []
for r in refs[:4]:
x = np.concatenate([np.zeros(8000, np.float32), _at_db(load(r["file"]), level_db), np.zeros(8000, np.float32)])
if level_db == -10:
x = np.clip(x * 4, -1, 1) # shouting into a hot mic: clipped
finals = _stream_clip_16k(engines, x, {"partials": False})
errs.append(cer(r["text"], " ".join(m["text"] for m in finals)))
print(level_db, [round(e, 2) for e in errs])
assert np.mean(errs) <= 0.15
def test_real_noise_recordings_produce_no_text(engines):
"""Optional: point JARVIS_NOISE_DIR at noise-only recordings (16 kHz or 44.1 kHz mono/stereo WAV,
e.g. ESC-50 keyboard, mouse, breathing, coughing, laughing). None may produce text."""
folder = os.environ.get("JARVIS_NOISE_DIR")
if not folder:
pytest.skip("set JARVIS_NOISE_DIR to a folder of noise-only WAV files")
from scipy.signal import resample_poly
texts = []
for path in sorted(Path(folder).glob("*.wav")):
with wave.open(str(path), "rb") as w:
x = np.frombuffer(w.readframes(w.getnframes()), dtype="<i2").astype(np.float32) / 32768.0
if w.getnchannels() == 2:
x = x.reshape(-1, 2).mean(axis=1)
rate = w.getframerate()
if rate != 16000:
from math import gcd
g = gcd(rate, 16000)
x = resample_poly(x, 16000 // g, rate // g).astype(np.float32)
for m in _stream_clip_16k(engines, x, {"hotwords": ["자비스"], "partials": False}):
if m["text"]:
texts.append((path.name, m["text"]))
print(texts)
assert texts == []

View File

@@ -102,6 +102,30 @@ def test_hysteresis_keeps_speech_going_but_never_starts_it():
assert len(f.of(Final)) == 1
@pytest.mark.unit
def test_weak_speech_like_noise_never_builds_up_to_an_utterance():
"""A breath of real speech probability followed by a long stretch of 'maybe speech' (fans,
keyboard, background rumble that the VAD scores around 0.4) is not enough to call the model."""
f = Feeder()
for _ in range(3):
f.feed(0.9, 40)
f.feed(0.4, 1000)
f.feed(0.0, 500)
assert f.events == []
@pytest.mark.unit
def test_finals_mark_which_windows_were_voiced():
f = Feeder()
f.feed(0.0, 500)
f.feed(0.9, 640)
f.feed(0.0, 500)
fin = f.of(Final)[0]
assert len(fin.voiced) == -(-len(fin.audio) // 512)
assert 20 <= fin.voiced.sum() <= 21 # 640 ms of 32 ms windows, not aligned to the frames
assert not fin.voiced[0] and not fin.voiced[-1] # pre-roll and tail are not voiced
@pytest.mark.unit
def test_speaking_end_closes_the_utterance_at_once():
f = Feeder()

View File

@@ -1,7 +1,8 @@
"""Voice worker end to end over a real local WebSocket, with fake STT/VAD/TTS engines.
The fake VAD reads speech probability off the amplitude and the fake transcriber names a clip by its
peak level, so each speaker's text tells which speaker's audio reached the model.
"level": each speaker sends a tone whose amplitude is the level (what the fake VAD reads) and whose
pitch is level x 1000 Hz (what the fake transcriber reads, since the worker evens out loudness).
"""
from __future__ import annotations
@@ -33,7 +34,7 @@ class LevelTranscriber:
def transcribe(self, clips, opts):
self.calls.append((opts, len(clips)))
return [f"level {np.median(np.abs(c)):.1f}" for c in clips]
return [f"level {np.argmax(np.abs(np.fft.rfft(c))) * 16000 / len(c) / 1000:.1f}" for c in clips]
class FakeTts:
@@ -54,7 +55,9 @@ class FakeTts:
def pcm(level: float, ms: int, rate=16000, channels=1) -> bytes:
n = rate * ms // 1000
return (np.full(n * channels, level) * 32767).astype("<i2").tobytes()
# 20 ms frames hold whole cycles at these pitches, so frames join without a click.
x = level * np.sin(2 * np.pi * level * 1000 * np.arange(n) / rate)
return (np.repeat(x, channels) * 32767).astype("<i2").tobytes()
async def with_worker(body, transcriber=None, tts=None, **kw):