From 1309525aa8825258b3649a666fe7a198e00663b3 Mon Sep 17 00:00:00 2001 From: javis-bot Date: Wed, 11 Nov 2026 10:40:42 +0900 Subject: [PATCH] fix(voice_worker): the wake word hint may never add, drop or create a wake word MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hotword occurrences were counted with fuzzy matching, which never counted a one-letter wake word (so a hinted "봇 ..." was accepted over a plain decode without it) and counted the real word "서비스" as "자비스" (so the hint could turn it into the wake word). Occurrences are now counted exactly (case, spacing and punctuation ignored); near misses are left as heard for call detection. The real-noise eval now plays each recording as recorded and at -25 dBFS and reports how many clips reached the model. Co-Authored-By: Claude Opus 5.5 --- docs/v2/voice-and-llm.md | 4 ++-- src/voice_worker/stt_whisper.py | 28 +++++++++------------------ src/voice_worker/voice_worker.spec.md | 13 ++++++++----- tests/test_voice_worker_gate.py | 24 ++++++++++++++++++++--- tests/test_voice_worker_real.py | 15 ++++++++------ 5 files changed, 49 insertions(+), 35 deletions(-) diff --git a/docs/v2/voice-and-llm.md b/docs/v2/voice-and-llm.md index 97af1e0..b2bb9d1 100644 --- a/docs/v2/voice-and-llm.md +++ b/docs/v2/voice-and-llm.md @@ -22,9 +22,9 @@ - **2단 디코딩**: 부분 전사는 beam 1(빠름), 최종 전사는 beam 2~3(정확도)입니다. - **게임 중 LLM이 답하는 동안**: STT와 LLM은 같은 GPU를 씁니다. 10명이 쉬지 않고 말하며 부분 전사를 계속 돌리면 LLM 출력이 1/2.5~1/3로 줄었습니다(M0 `gamemode_stt`). 그래서 게임 중에 LLM이 답을 만드는 동안에는 부분 전사를 멈추고(그동안 실시간 자막이 바뀌지 않음), 말이 끝난 뒤의 최종 전사는 기다리지 않고 바로 처리합니다. 게임이 없을 때는 LLM이 답하는 동안에도 부분 전사를 그대로 합니다(사용자 결정, 2026-11-10). 최종 전사가 부분 전사보다 먼저입니다. 멈추기로 한 것은 M0 `gamemode_tune` 측정 결과입니다(2026-11-11): 2초 간격은 37.5 tok/s, 음성 첫 문장 0.89초에 최종 전사 대기가 최대 1.2초였고, 멈추면 64.9 tok/s, 0.55초였습니다. 부분 전사를 멈췄을 때 beam 2~3 최종 전사와 긴 말의 실제 지연은 아직 재지 않았습니다([pc-features.md](pc-features.md#자동-조절-측정-m0-gamemode_tune-2026-11-11)). - **부분 전사는 2명씩만 묶음(M1 실측)**: Whisper 인코더는 말 길이와 상관없이 늘 30초 창을 계산해서, 묶어도 비용이 사람 수에 비례합니다(RTX 5050에서 1명 0.2초, 10명 2.1초). 10명분 부분 전사를 한 번에 돌리면 그동안 들어온 최종 전사가 2초 넘게 기다려서, 부분 전사는 한 번에 2명까지만 돌리고 그 사이에 최종 전사가 먼저 들어가게 했습니다. 여러 명이 함께 말하면 자막은 늦어지고 사람마다 가장 최근 소리만 전사합니다. 인코더 창을 줄이면 4~7배 빨라졌지만 같은 문장을 되풀이하는 오류가 생겨 쓰지 않습니다. -- **호출어 힌트**: 등록한 호출어를 STT에 힌트로 넘겨 잘못 알아듣는 일을 줄입니다. 힌트만 쓰면 웃음소리에서 "자비스"를 지어내거나 실제 문장 끝에 "자비스"를 붙여서(M1 측정, 2026-11-11), 힌트가 있으면 같은 소리를 힌트 없이도 한 번 더 해석해 그 결과로 판단합니다. 힌트는 호출어 철자를 고치는 데만 쓰이고 호출어를 더하거나 빼지 못합니다. +- **호출어 힌트**: 등록한 호출어를 STT에 힌트로 넘겨 잘못 알아듣는 일을 줄입니다. 힌트만 쓰면 웃음소리에서 "자비스"를 지어내거나 실제 문장 끝에 "자비스"를 붙여서(M1 측정, 2026-11-11), 힌트가 있으면 같은 소리를 힌트 없이도 한 번 더 해석해 그 결과로 판단합니다. 힌트 결과는 호출어 개수가 힌트 없는 결과와 정확히 같을 때만 쓰므로, 힌트가 호출어를 더하거나 빼거나 비슷한 말("서비스", "자비수")을 호출어로 바꾸지 못합니다. "자비수" 같은 비슷한 말을 호출어로 볼지는 호출 판정(M4)이 정합니다. - **음량 맞추기**: 사람마다 목소리 크기가 달라도 같은 크기로 맞춰 STT에 넣습니다. 목소리가 있는 구간만 재서 -20dBFS로 맞추고(최대 +40dB, 낮은 웅웅거림 제거, 큰 소리는 찌그러지지 않게 부드럽게 눌러 줌), 클릭이나 노크 소리가 음량을 정하지 않게 합니다. 측정하면 -60dBFS 속삭임부터 찌그러질 만큼 큰 소리까지 똑같이 받아 적었습니다. -- **잡음 거르기와 헛 전사 막기**: 목소리가 분명한 구간(음성 확률 0.5 이상)이 0.25초 넘게 있어야 STT를 돌립니다. 키보드, 마우스, 발소리, 청소기 같은 잡음은 여기서 걸러집니다. 기침, 웃음처럼 목소리 같은 소리는 STT까지 가지만 결과의 토큰당 평균 확신도(-0.7 이상)와 반복 여부로 거릅니다. 실제 잡음 54개(ESC-50)를 원래 크기와 -25dBFS로 넣은 108개 중 102개는 STT까지 가지 않았고, STT까지 간 6개(기침, 웃음, 울음)도 모두 빈 결과였습니다(호출어 힌트가 있을 때도 같음). 그 잡음 위에 말한 문장 89개는 문자 오류율 평균 4.8%였고, 남은 문제는 웃음 직후 "감사합니다." 한 번(확신도가 기준선에 걸침), 시끄러운 잡음 속 짧은 단어 2개 누락, 같은 단어 세 번 반복 한 번입니다. 이 모델(large-v3-turbo)의 "말 없음" 확률은 늘 0이라 쓰지 않습니다. +- **잡음 거르기와 헛 전사 막기**: 목소리가 분명한 구간(음성 확률 0.5 이상)이 0.25초 넘게 있어야 STT를 돌립니다. 키보드, 마우스, 발소리, 청소기 같은 잡음은 여기서 걸러집니다. 기침, 웃음처럼 목소리 같은 소리는 STT까지 가지만 결과의 토큰당 평균 확신도(-0.7 이상)와 반복 여부로 거릅니다. 실제 잡음 54개(ESC-50)를 원래 크기와 -25dBFS로 넣은 108개를 호출어 힌트를 켠 워커에 넣으니 103개는 STT까지 가지 않았고, STT까지 간 5개(기침, 웃음, 울음)도 모두 빈 결과였습니다. 그 잡음 위에 말한 문장 89개는 문자 오류율 평균 4.8%였고, 남은 문제는 웃음 직후 "감사합니다." 한 번(확신도가 기준선에 걸침), 시끄러운 잡음 속 짧은 단어 2개 누락, 같은 단어 세 번 반복 한 번입니다. 이 모델(large-v3-turbo)의 "말 없음" 확률은 늘 0이라 쓰지 않습니다. - **RealtimeSTT 사용 범위**: RealtimeSTT는 화자 하나에 인스턴스 하나 구조라 10명이면 모델을 10번 올립니다. 그래서 설계(부분/최종 전사, VAD 결합)만 참고하고, **모델 1개를 10명이 공유하는 배치 방식**으로 직접 구현합니다. - **선택지**: 더 낮은 지연이 필요하면 sherpa-onnx 스트리밍 모델을 "초고속" 옵션으로 검토합니다(한국어 정확도 확인 후). diff --git a/src/voice_worker/stt_whisper.py b/src/voice_worker/stt_whisper.py index f2f446a..5211975 100644 --- a/src/voice_worker/stt_whisper.py +++ b/src/voice_worker/stt_whisper.py @@ -48,31 +48,21 @@ def _edit_distance(a: str, b: str) -> int: 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 + """Exact occurrences of ``word`` in ``text``, ignoring case, spacing and punctuation. No fuzzy + matching: a near miss ("자비수", or the real word "서비스") is not the wake word as far as the + hint is concerned.""" + w = _letters(word) + return _letters(text).count(w) if w else 0 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). + The hint can make Whisper write a wake word that nobody said (on laughter, tacked onto a real + sentence, or in place of a similar word), 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 contains every + hotword exactly as often. It may change other words, never how many wake words were heard. """ if not keep_transcript(plain_text, plain_lp): return "" diff --git a/src/voice_worker/voice_worker.spec.md b/src/voice_worker/voice_worker.spec.md index 09a92d4..0c36e17 100644 --- a/src/voice_worker/voice_worker.spec.md +++ b/src/voice_worker/voice_worker.spec.md @@ -134,16 +134,19 @@ text is empty: - 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. + only when it stays within half the plain text's letters of it and contains every hotword exactly + as often as the plain one (ignoring case, spacing and punctuation, no fuzzy matching), so the hint + can never add, drop or create a wake word: not from laughter, not after a real sentence, not from + a one-letter wake word, and not by turning a similar word ("서비스", or the near miss "자비수") + into it. Otherwise the plain text is used; matching near misses is left to call detection. `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 +clips streamed through the worker with the wake word hint on, 103 never reached the model (the VAD +rule above) and the 5 that did (coughs, laughter, crying) all came out empty +(`test_real_noise_recordings_produce_no_text` with `JARVIS_NOISE_DIR`). 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 diff --git a/tests/test_voice_worker_gate.py b/tests/test_voice_worker_gate.py index 5e264e6..dc94e43 100644 --- a/tests/test_voice_worker_gate.py +++ b/tests/test_voice_worker_gate.py @@ -51,9 +51,27 @@ def test_a_wake_word_the_hint_adds_to_real_speech_is_dropped(): @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 +def test_a_one_letter_wake_word_the_hint_adds_is_dropped(): + assert choose_with_hint("봇 오늘 날씨 알려 줘", -0.1, "오늘 날씨 알려 줘", -0.1, ("봇",)) == "오늘 날씨 알려 줘" + + +@pytest.mark.unit +def test_the_hint_may_not_turn_a_similar_real_word_into_the_wake_word(): + assert choose_with_hint("자비스 신청해 줘", -0.1, "서비스 신청해 줘", -0.1, HINT) == "서비스 신청해 줘" + + +@pytest.mark.unit +def test_a_near_miss_spelling_is_left_as_heard_rather_than_guessed(): + # "자비수" may be the wake word or another word; text alone cannot tell, so the plain decode stands + # and fuzzy wake word matching is left to the call detection that reads it. + plain = "자비수, 오늘 서울 날씨 어때?" + assert choose_with_hint("자비스, 오늘 서울 날씨 어때?", -0.1, plain, -0.2, HINT) == plain + + +@pytest.mark.unit +def test_the_hint_is_used_when_it_keeps_the_wake_words_as_they_were(): + hinted = "자비스, 철수 화면 공유 보여 줘" + assert choose_with_hint(hinted, -0.1, "자비스 철수 화면공유 보여줘", -0.15, HINT) == hinted @pytest.mark.unit diff --git a/tests/test_voice_worker_real.py b/tests/test_voice_worker_real.py index c1311a4..885f95a 100644 --- a/tests/test_voice_worker_real.py +++ b/tests/test_voice_worker_real.py @@ -292,12 +292,13 @@ def test_quiet_and_loud_speakers_are_both_understood(engines, level_db): 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.""" + e.g. ESC-50 keyboard, mouse, breathing, coughing, laughing; ESC-50 is CC BY-NC, so it is not in + the repository). Each plays as recorded and at -25 dBFS; 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 = [] + texts, reached, clips = [], 0, 0 for path in sorted(Path(folder).glob("*.wav")): with wave.open(str(path), "rb") as w: x = np.frombuffer(w.readframes(w.getnframes()), dtype="