음성 인식: 최종 인식마다 단어별 확신도를 .smallclaw/logs/stt-confidence.jsonl에 기록(낮은 확률 단어 목록 포함)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Sonnet 5.5 committed 2026-10-19 17:55:12 +09:00
1 parent b1abe5912c
commit 5c15fbb53b
1 file changed
+48 -6
+48 -6
View File
@@ -40,6 +40,7 @@ import logging
import os
import tempfile
import threading
import time
import numpy as np
import websockets
@@ -127,6 +128,40 @@ def pcm16_bytes_to_float(pcm: bytes) -> np.ndarray:
return np.frombuffer(pcm, dtype='<i2').astype(np.float32) / 32768.0
# ── 확신도 로그 (2026-10-19) ───────────────────────────────────────────────
# 최종 인식(stt_final)마다 단어별 확률을 남긴다. 어떤 단어를 Whisper가 자주 불확실하게 듣는지 실데이터로 보고
# 용어 사전·보정 규칙을 늘리기 위한 것. 부분(partial) 디코딩은 기록하지 않는다. 로컬 파일이며 내용은 대화 로그와 같은 민감도.
STT_CONF_LOG = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '.smallclaw', 'logs', 'stt-confidence.jsonl')
STT_LOW_WORD_PROB = 0.6
def log_stt_confidence(src: str, segs: list, text: str, started: float):
try:
kept = [sg for sg in segs if sg.no_speech_prob < NO_SPEECH_PROB_CUTOFF]
words = [w for sg in kept for w in (sg.words or [])]
if not text or not words:
return
probs = [w.probability for w in words]
rec = {
'ts': time.strftime('%Y-%m-%dT%H:%M:%S%z'),
'src': src,
'audio_s': round(max(w.end for w in words), 2),
'decode_s': round(time.time() - started, 2),
'text': text,
'n_words': len(words),
'mean_prob': round(sum(probs) / len(probs), 3),
'min_prob': round(min(probs), 3),
'avg_logprob': round(sum(sg.avg_logprob for sg in kept) / len(kept), 3),
'max_no_speech': round(max(sg.no_speech_prob for sg in kept), 3),
'low': [[w.word.strip(), round(w.probability, 2)] for w in words if w.probability < STT_LOW_WORD_PROB],
}
os.makedirs(os.path.dirname(STT_CONF_LOG), exist_ok=True)
with open(STT_CONF_LOG, 'a', encoding='utf-8') as f:
f.write(json.dumps(rec, ensure_ascii=False) + '\n')
except Exception:
log.debug('stt confidence log failed', exc_info=True)
class Engine:
def __init__(self, args):
self.args = args
@@ -145,11 +180,14 @@ class Engine:
f.write(audio_bytes)
path = f.name
try:
t0 = time.time()
segments, info = self.stt_model.transcribe(
path, language=language or None, beam_size=5, vad_filter=True, condition_on_previous_text=False,
hallucination_silence_threshold=2.0, hotwords=STT_HOTWORDS,
hallucination_silence_threshold=2.0, hotwords=STT_HOTWORDS, word_timestamps=True,
)
text = ''.join(seg.text for seg in segments if seg.no_speech_prob < NO_SPEECH_PROB_CUTOFF).strip()
segs = list(segments)
text = ''.join(seg.text for seg in segs if seg.no_speech_prob < NO_SPEECH_PROB_CUTOFF).strip()
log_stt_confidence('full', segs, text, t0)
return text, (info.language if info else language)
finally:
try:
@@ -177,13 +215,17 @@ class Engine:
return pcm, self._tts_sample_rate
# ── Streaming STT (partial decode of an accumulating PCM buffer) ──────
def transcribe_pcm(self, pcm: bytes, language: str):
def transcribe_pcm(self, pcm: bytes, language: str, log_conf: bool = False):
audio = pcm16_bytes_to_float(pcm)
t0 = time.time()
segments, info = self.stt_model.transcribe(
audio, language=language or None, beam_size=1, vad_filter=True, condition_on_previous_text=False,
hallucination_silence_threshold=2.0, hotwords=STT_HOTWORDS,
hallucination_silence_threshold=2.0, hotwords=STT_HOTWORDS, word_timestamps=log_conf,
)
text = ''.join(seg.text for seg in segments if seg.no_speech_prob < NO_SPEECH_PROB_CUTOFF).strip()
segs = list(segments)
text = ''.join(seg.text for seg in segs if seg.no_speech_prob < NO_SPEECH_PROB_CUTOFF).strip()
if log_conf:
log_stt_confidence('stream', segs, text, t0)
return text, (info.language if info else language)
# ── "Streaming" TTS ─────────────────────────────────────────────────
@@ -336,7 +378,7 @@ async def handle_connection(ws, engine: Engine):
loop = asyncio.get_event_loop()
text, lang = ('', state.stt_language)
if len(buf) >= 320: # at least ~10ms, skip empty stop
text, lang = await loop.run_in_executor(None, engine.transcribe_pcm, buf, state.stt_language)
text, lang = await loop.run_in_executor(None, engine.transcribe_pcm, buf, state.stt_language, True)
await ws.send(json.dumps({'type': 'stt_final', 'text': text, 'language': lang, 'id': req_id}))
elif mtype == 'tts_start':