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:
@@ -50,9 +50,39 @@ class InputConverter:
|
||||
return out.astype(np.float32)
|
||||
|
||||
|
||||
def peak_normalise(x: np.ndarray, target: float = 0.9, max_gain: float = 10.0) -> np.ndarray:
|
||||
peak = float(np.max(np.abs(x))) if len(x) else 0.0
|
||||
if peak <= 0:
|
||||
return x.astype(np.float32)
|
||||
gain = min(target / peak, max_gain)
|
||||
return (x * gain).astype(np.float32)
|
||||
TARGET_DB = -20.0 # loudness every speaker is brought to, dBFS RMS over the voiced windows
|
||||
MAX_GAIN_DB = 40.0 # a whisper at -60 dBFS still reaches the target; pure hiss is not blown up
|
||||
MIN_GAIN_DB = -20.0
|
||||
HIGHPASS_HZ = 60.0 # mains hum and desk rumble carry no speech
|
||||
_KNEE = 0.8 # soft limiter: peaks above this bend smoothly towards the ceiling instead of clipping
|
||||
_CEILING = 0.98
|
||||
_WINDOW = 512
|
||||
|
||||
|
||||
def loudness_equalise(x: np.ndarray, voiced: np.ndarray | None = None) -> np.ndarray:
|
||||
"""Bring a clip to the same loudness whoever spoke it, without clipping.
|
||||
|
||||
``voiced`` marks the 512-sample windows the VAD heard as speech; the level is measured on them so
|
||||
silence, a click or a knock does not decide the gain. Without it the louder half of the windows is
|
||||
used. Low rumble is removed first and peaks are soft-limited after the gain.
|
||||
"""
|
||||
x = np.asarray(x, dtype=np.float32)
|
||||
if len(x) == 0:
|
||||
return x
|
||||
spec = np.fft.rfft(x.astype(np.float64))
|
||||
spec[np.fft.rfftfreq(len(x), 1 / TARGET_RATE) < HIGHPASS_HZ] = 0
|
||||
y = np.fft.irfft(spec, len(x))
|
||||
n_win = -(-len(y) // _WINDOW)
|
||||
frames = np.pad(y, (0, n_win * _WINDOW - len(y))).reshape(n_win, _WINDOW)
|
||||
energy = (frames ** 2).mean(axis=1)
|
||||
if voiced is not None and len(voiced) == n_win and voiced.any():
|
||||
sel = energy[voiced]
|
||||
else:
|
||||
sel = energy[energy >= np.median(energy)]
|
||||
level_db = 10 * np.log10(sel.mean() + 1e-20)
|
||||
gain_db = float(np.clip(TARGET_DB - level_db, MIN_GAIN_DB, MAX_GAIN_DB))
|
||||
y = y * 10 ** (gain_db / 20)
|
||||
over = np.abs(y) > _KNEE
|
||||
room = _CEILING - _KNEE
|
||||
y[over] = np.sign(y[over]) * (_KNEE + room * np.tanh((np.abs(y[over]) - _KNEE) / room))
|
||||
return y.astype(np.float32)
|
||||
|
||||
@@ -33,6 +33,7 @@ class SpeechStart:
|
||||
class Partial:
|
||||
utt: int
|
||||
audio: np.ndarray
|
||||
voiced: np.ndarray # one bool per 512-sample window: the VAD heard speech there
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -41,6 +42,7 @@ class Final:
|
||||
audio: np.ndarray
|
||||
reason: str # silence | speaking_end | idle | max_length
|
||||
decided_at: float
|
||||
voiced: np.ndarray
|
||||
|
||||
|
||||
def _windows(ms: float) -> int:
|
||||
@@ -60,7 +62,8 @@ class Segmenter:
|
||||
def _reset(self) -> None:
|
||||
self._active = False
|
||||
self._win: list[np.ndarray] = []
|
||||
self._speech = 0
|
||||
self._voiced: list[bool] = []
|
||||
self._speech = 0 # windows that clearly held speech (>= START_PROB)
|
||||
self._trailing = 0
|
||||
self._started = False
|
||||
self._last_partial_at = 0.0
|
||||
@@ -83,7 +86,7 @@ class Segmenter:
|
||||
and now - self._last_partial_at >= self.settings.partial_interval_ms / 1000:
|
||||
self._last_partial_at = now
|
||||
self._last_partial_len = len(self._win)
|
||||
events.append(Partial(self._utt_count, np.concatenate(self._win)))
|
||||
events.append(Partial(self._utt_count, np.concatenate(self._win), np.array(self._voiced)))
|
||||
return events
|
||||
|
||||
def _window(self, w: np.ndarray, now: float) -> list:
|
||||
@@ -92,6 +95,7 @@ class Segmenter:
|
||||
if p >= START_PROB:
|
||||
self._active = True
|
||||
self._win = self._pre + [w]
|
||||
self._voiced = [False] * len(self._pre) + [True]
|
||||
self._pre = []
|
||||
self._speech = 1
|
||||
self._trailing = 0
|
||||
@@ -100,8 +104,12 @@ class Segmenter:
|
||||
del self._pre[:-_windows(PRE_ROLL_MS)]
|
||||
return []
|
||||
self._win.append(w)
|
||||
if p >= KEEP_PROB:
|
||||
self._voiced.append(p >= START_PROB)
|
||||
# "Maybe speech" (between the two thresholds) keeps an utterance going but is not evidence
|
||||
# of a voice, so noise the VAD half-believes never adds up to a call to the model.
|
||||
if p >= START_PROB:
|
||||
self._speech += 1
|
||||
if p >= KEEP_PROB:
|
||||
self._trailing = 0
|
||||
else:
|
||||
self._trailing += 1
|
||||
@@ -121,8 +129,9 @@ class Segmenter:
|
||||
events: list = []
|
||||
if self._active and self._started:
|
||||
drop = max(0, self._trailing - _windows(TAIL_KEEP_MS))
|
||||
kept = self._win[:len(self._win) - drop]
|
||||
events.append(Final(self._utt_count, np.concatenate(kept), reason, now))
|
||||
keep = len(self._win) - drop
|
||||
events.append(Final(self._utt_count, np.concatenate(self._win[:keep]), reason, now,
|
||||
np.array(self._voiced[:keep])))
|
||||
self._reset()
|
||||
return events
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import numpy as np
|
||||
|
||||
from jarvis.debug import debug_log
|
||||
|
||||
from .audio import InputConverter
|
||||
from .audio import InputConverter, loudness_equalise
|
||||
from .protocol import KIND_AUDIO, ProtocolError, decode_audio_frame, encode_tts_frame
|
||||
from .scheduler import DecodeOptions, SttResult, SttScheduler, Transcriber
|
||||
from .segmenter import SR, Final, Partial, Segmenter, SpeechStart, VadStream
|
||||
@@ -211,7 +211,7 @@ class Session:
|
||||
self.send({"type": "speech_start", "speaker": speaker, "utt": ev.utt})
|
||||
elif isinstance(ev, Partial):
|
||||
if sched and self.settings.partials:
|
||||
sched.submit_partial((self.sid, speaker), ev.audio, self._opts(1),
|
||||
sched.submit_partial((self.sid, speaker), loudness_equalise(ev.audio, ev.voiced), self._opts(1),
|
||||
self._partial_cb(speaker, st, ev.utt))
|
||||
elif isinstance(ev, Final):
|
||||
debug_log(f"utterance end speaker={speaker} utt={ev.utt} reason={ev.reason} "
|
||||
@@ -219,7 +219,8 @@ class Session:
|
||||
if sched is None:
|
||||
self._send_final(speaker, ev, SttResult("", 0, "stt unavailable"))
|
||||
else:
|
||||
sched.submit_final((self.sid, speaker), ev.audio, self._opts(self.settings.final_beam),
|
||||
sched.submit_final((self.sid, speaker), loudness_equalise(ev.audio, ev.voiced),
|
||||
self._opts(self.settings.final_beam),
|
||||
lambda res, ev=ev: self._send_final(speaker, ev, res))
|
||||
|
||||
def _partial_cb(self, speaker: str, st: _Speaker, utt: int):
|
||||
|
||||
@@ -4,18 +4,83 @@ from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import zlib
|
||||
|
||||
import numpy as np
|
||||
|
||||
from jarvis.debug import debug_log
|
||||
|
||||
from .audio import peak_normalise
|
||||
from .scheduler import DecodeOptions
|
||||
|
||||
SR = 16000
|
||||
NO_SPEECH_THRESHOLD = 0.5 # same gate as v1 (whisper_no_speech_threshold)
|
||||
MIN_CONFIDENCE = 0.3 # avg_logprob + 1, same as v1 (whisper_min_confidence)
|
||||
# Mean log-probability per output token. Measured on real noise (coughs, laughter, crying) and speech
|
||||
# over it: every hallucination stayed below, real speech above except two short words in loud noise.
|
||||
# Whisper's no_speech_prob is not used: large-v3-turbo reports 0.0 for silence and noise alike.
|
||||
MIN_MEAN_LOGPROB = -0.7
|
||||
MAX_COMPRESSION_RATIO = 2.4 # repetition loops ("A B A B A B ...") compress far better than speech
|
||||
|
||||
|
||||
def _letters(text: str) -> str:
|
||||
"""Text without spacing, punctuation and case, so decodes compare by what was said."""
|
||||
return re.sub(r"[\W_]+", "", text).casefold()
|
||||
|
||||
|
||||
def compression_ratio(text: str) -> float:
|
||||
raw = text.encode("utf-8")
|
||||
return len(raw) / len(zlib.compress(raw)) if raw else 0.0
|
||||
|
||||
|
||||
def keep_transcript(text: str, mean_logprob: float) -> bool:
|
||||
return bool(_letters(text)) and mean_logprob >= MIN_MEAN_LOGPROB \
|
||||
and compression_ratio(text) <= MAX_COMPRESSION_RATIO
|
||||
|
||||
|
||||
def _edit_distance(a: str, b: str) -> int:
|
||||
prev = list(range(len(b) + 1))
|
||||
for i, ca in enumerate(a, 1):
|
||||
cur = [i]
|
||||
for j, cb in enumerate(b, 1):
|
||||
cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
|
||||
prev = cur
|
||||
return prev[-1]
|
||||
|
||||
|
||||
def _mentions(text: str, word: str) -> int:
|
||||
"""How many times ``word`` occurs in ``text``, allowing a near miss in spelling (자비수 for 자비스)."""
|
||||
t, w = _letters(text), _letters(word)
|
||||
if not w:
|
||||
return 0
|
||||
slack = max(1, len(w) // 3)
|
||||
count, i = 0, 0
|
||||
while i <= len(t) - max(1, len(w) - slack):
|
||||
hit = next((n for n in range(len(w) - slack, len(w) + slack + 1)
|
||||
if i + n <= len(t) and _edit_distance(t[i:i + n], w) <= slack), None)
|
||||
if hit:
|
||||
count += 1
|
||||
i += hit
|
||||
else:
|
||||
i += 1
|
||||
return count
|
||||
|
||||
|
||||
def choose_with_hint(hint_text: str, hint_lp: float, plain_text: str, plain_lp: float,
|
||||
hotwords: tuple[str, ...]) -> str:
|
||||
"""Pick between the decode that had the hotwords as a hint and the plain decode of the same audio.
|
||||
|
||||
The hint can make Whisper write a wake word that nobody said (on laughter, or tacked onto a real
|
||||
sentence), so the plain decode decides: no plain text means nothing was said, and the hint's text
|
||||
is used only when it stays close to the plain one and mentions every hotword as often (it may fix
|
||||
their spelling, not add or drop them).
|
||||
"""
|
||||
if not keep_transcript(plain_text, plain_lp):
|
||||
return ""
|
||||
close = _edit_distance(_letters(hint_text), _letters(plain_text)) <= len(_letters(plain_text)) // 2
|
||||
if close and keep_transcript(hint_text, hint_lp) and all(
|
||||
_mentions(hint_text, w) == _mentions(plain_text, w) for w in hotwords):
|
||||
return hint_text
|
||||
return plain_text
|
||||
|
||||
|
||||
def add_cuda_dll_dirs() -> None:
|
||||
@@ -50,11 +115,12 @@ class WhisperTranscriber:
|
||||
self.transcribe([np.zeros(SR, dtype=np.float32)], DecodeOptions(beam=1, language="en", hotwords=()))
|
||||
|
||||
def transcribe(self, clips: list[np.ndarray], opts: DecodeOptions) -> list[str]:
|
||||
"""Clips arrive loudness-equalised by the session."""
|
||||
m = self.model
|
||||
n_frames = m.feature_extractor.nb_max_frames
|
||||
feats = []
|
||||
for c in clips:
|
||||
a = peak_normalise(c[: SR * 30])
|
||||
a = np.asarray(c[: SR * 30], dtype=np.float32)
|
||||
a = np.pad(a, (0, SR * 30 - len(a)))
|
||||
feats.append(m.feature_extractor(a, padding=0)[:, :n_frames])
|
||||
enc = m.encode(np.stack(feats).astype(np.float32))
|
||||
@@ -62,17 +128,18 @@ class WhisperTranscriber:
|
||||
langs = [opts.language] * len(clips)
|
||||
else:
|
||||
langs = [r[0][0][2:-2] for r in m.model.detect_language(enc)]
|
||||
hot = " ".join(opts.hotwords) or None
|
||||
prompts = [m.get_prompt(self._tokenizer(lang), [], without_timestamps=True, hotwords=hot) for lang in langs]
|
||||
results = m.model.generate(enc, prompts, beam_size=opts.beam, max_length=224,
|
||||
suppress_blank=True, suppress_tokens=[-1], return_scores=True,
|
||||
return_no_speech_prob=True)
|
||||
texts = []
|
||||
for lang, r in zip(langs, results):
|
||||
tokens = r.sequences_ids[0]
|
||||
avg_logprob = r.scores[0] * len(tokens) / (len(tokens) + 1)
|
||||
if r.no_speech_prob >= NO_SPEECH_THRESHOLD or avg_logprob + 1 < MIN_CONFIDENCE:
|
||||
texts.append("")
|
||||
else:
|
||||
texts.append(self._tokenizer(lang).decode(tokens).strip())
|
||||
return texts
|
||||
plain = self._decode(enc, langs, opts.beam, None)
|
||||
if not opts.hotwords:
|
||||
return [text if keep_transcript(text, lp) else "" for text, lp in plain]
|
||||
hinted = self._decode(enc, langs, opts.beam, " ".join(opts.hotwords))
|
||||
return [choose_with_hint(ht, hlp, pt, plp, opts.hotwords) for (ht, hlp), (pt, plp) in zip(hinted, plain)]
|
||||
|
||||
def _decode(self, enc, langs: list[str], beam: int, hotwords: str | None) -> list[tuple[str, float]]:
|
||||
m = self.model
|
||||
prompts = [m.get_prompt(self._tokenizer(lang), [], without_timestamps=True, hotwords=hotwords)
|
||||
for lang in langs]
|
||||
results = m.model.generate(enc, prompts, beam_size=beam, max_length=224, suppress_blank=True,
|
||||
suppress_tokens=[-1], return_scores=True)
|
||||
# ``scores`` is the sequence log-probability divided by its length: the mean per token.
|
||||
return [(self._tokenizer(lang).decode(r.sequences_ids[0]).strip(), float(r.scores[0]))
|
||||
for lang, r in zip(langs, results)]
|
||||
|
||||
@@ -74,7 +74,7 @@ STT settings (all optional in `hello` and `config`):
|
||||
| `end_silence_ms` | 300 | Trailing VAD silence that ends an utterance. Range 100-2000. |
|
||||
| `final_beam` | 2 | Beam size for finals (partials always use 1). Range 1-5. |
|
||||
| `language` | `"ko"` | Whisper language code, or `null` to detect per utterance. |
|
||||
| `hotwords` | `[]` | Words (wake words, names) passed to Whisper as a hint. |
|
||||
| `hotwords` | `[]` | Words (wake words, names) passed to Whisper as a hint. The hint alone made Whisper write the wake word on laughter, so with hotwords every clip is also decoded without them and that plain decode decides (see Hallucination gate). |
|
||||
|
||||
### Utterance rules
|
||||
|
||||
@@ -82,10 +82,12 @@ Each speaker's audio is mixed to mono, resampled to 16 kHz with a streaming filt
|
||||
its own streaming Silero VAD (512-sample windows, state kept between frames).
|
||||
|
||||
- **Start**: the first window with speech probability at or above 0.5. The 200 ms before it are kept.
|
||||
- **speech_start** is sent once the utterance holds 250 ms of speech windows. An utterance that ends
|
||||
before that is dropped without any message (a click or a cough).
|
||||
- **speech_start** is sent once the utterance holds 250 ms of clearly voiced windows (probability at
|
||||
or above 0.5). An utterance that ends before that is dropped without any message and never reaches
|
||||
the model: a click, a cough, or noise.
|
||||
- **Speech continues** while windows stay at or above 0.35 (hysteresis); a quieter window counts as
|
||||
silence.
|
||||
silence. Windows between 0.35 and 0.5 keep an utterance open but are not evidence of a voice, so
|
||||
noise the VAD half-believes (fans, typing) never adds up to an utterance.
|
||||
- **End**, with `end_reason`:
|
||||
- `silence`: trailing silence reached `end_silence_ms`.
|
||||
- `speaking_end`: the app sent `speaking_end`. Discord stops sending packets when a user stops
|
||||
@@ -94,7 +96,12 @@ its own streaming Silero VAD (512-sample windows, state kept between frames).
|
||||
- `max_length`: the utterance reached 28 seconds (Whisper's window). The next audio starts a new
|
||||
utterance.
|
||||
- The final clip keeps at most 200 ms of trailing silence.
|
||||
- Before transcription the clip is peak-normalised to 0.9 with the gain capped at 10x.
|
||||
- **Loudness equalisation** before transcription (partials and finals), so a quiet and a loud speaker
|
||||
reach the model alike: rumble below 60 Hz is removed, the level is measured as the RMS of the voiced
|
||||
windows only (silence, a click or a knock do not set the gain), the clip is brought to -20 dBFS with
|
||||
the gain kept between -20 and +40 dB, and peaks above 0.8 are soft-limited below 0.98 instead of
|
||||
clipping. Measured: speech from -60 dBFS to clipped shouting was transcribed equally well, and quiet
|
||||
speech under loud clicks or knocks better than with peak normalisation.
|
||||
|
||||
### Scheduling
|
||||
|
||||
@@ -112,9 +119,35 @@ wait seconds behind it; two clips keep that wait to about one clip's time. With
|
||||
captions fall behind and only the newest audio per speaker is transcribed.
|
||||
|
||||
Batches are grouped by decode settings (beam, language, hotwords). A partial whose utterance has
|
||||
already ended, or that is older than the last partial sent, is dropped. Whisper output is rejected
|
||||
(empty text) when `no_speech_prob >= 0.5` or the confidence (`avg_logprob + 1`) is below 0.3, the
|
||||
same gate as v1.
|
||||
already ended, or that is older than the last partial sent, is dropped.
|
||||
|
||||
### Hallucination gate
|
||||
|
||||
Whisper writes text for voice-like sounds without words (coughs, laughter, a crying baby) and,
|
||||
prompted with a hint, the hint itself. A transcript is kept only when all of these hold, else the
|
||||
text is empty:
|
||||
|
||||
- It has letters or digits (not only punctuation).
|
||||
- Its mean log-probability per token is at least -0.7. This is the decoder's own per-token mean; the
|
||||
`avg_logprob` used by faster-whisper divides by one token more, which lifted a three-token
|
||||
hallucination from -0.73 to -0.55 and let it through.
|
||||
- Its compression ratio (UTF-8 bytes over zlib bytes) is at most 2.4, which catches repetition loops.
|
||||
- With hotwords: the clip is decoded once with them and once without, from the same encoder pass.
|
||||
The plain decode must pass the checks above, otherwise nothing was said. The hinted text is used
|
||||
only when it stays within half the plain text's letters of it and mentions every hotword as often
|
||||
as the plain one (a near miss in spelling counts as a mention), so the hint can fix how a spoken
|
||||
wake word is written but never add or drop one. Otherwise the plain text is used.
|
||||
|
||||
`no_speech_prob` is not used: large-v3-turbo reports 0.0 for silence and noise alike.
|
||||
|
||||
Measured (2026-11-11, RTX 5050) with 54 real noise recordings from ESC-50 (typing, mouse, breathing,
|
||||
coughing, laughing, crying, vacuum, ...), each at its own level and at -25 dBFS: of the 108 noise-only
|
||||
clips, 102 never reached the model (the VAD rule above) and the 6 that did (coughs, laughter, crying)
|
||||
all came out empty, with and without the wake word hint. Over 89 mixes of speech with that noise
|
||||
(SNR 20, 10 and 0 dB, plus clean) the mean character error rate was 4.8%. Left over: one
|
||||
"thank you" written for laughter just before a sentence (mean log-probability -0.70, right at the
|
||||
line), two short words lost in loud noise, and one word repeated three times at SNR 0. A stricter
|
||||
line (-0.6) would lose more real words than it saves.
|
||||
|
||||
### TTS
|
||||
|
||||
|
||||
Reference in New Issue
Block a user