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:
@@ -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 == []
|
||||
|
||||
Reference in New Issue
Block a user