Files
homeclaw/src/tools/voice_engine.py
T

564 lines
25 KiB
Python

#!/usr/bin/env python3
"""
Persistent GPU voice engine: loads faster-whisper (STT) and OmniVoice (TTS)
once and serves them over a localhost WebSocket so Node never pays model
load latency per request.
Batch protocol (used by Telegram + the existing single-shot web TTS button):
-> {"type":"ping"}
<- {"type":"pong","ready":true}
-> {"type":"stt_transcribe_full","audioBase64":"...","format":"webm","language":"ko"}
<- {"type":"stt_final","text":"...","language":"ko"}
-> {"type":"tts_synthesize_full","text":"..."}
<- {"type":"tts_result","audioBase64":"...","sampleRate":24000}
Streaming protocol (used by the web UI continuous-conversation mode):
-> {"type":"stt_start","sampleRate":16000,"language":"ko"}
-> <binary PCM16 mono frames at sampleRate, repeated>
<- {"type":"stt_partial","text":"..."} (emitted opportunistically as audio accumulates)
-> {"type":"stt_stop"}
<- {"type":"stt_final","text":"..."}
-> {"type":"tts_start","text":"...","id":"..."}
<- {"type":"tts_stream_start","sampleRate":24000,"id":"..."}
<- <binary PCM16 mono frames, in order>
<- {"type":"tts_end","id":"..."}
-> {"type":"tts_cancel"} (aborts the in-flight stream started by tts_start)
<- {"type":"error","message":"..."} on failure (echoes "id" when the request had one)
One WS connection == one call session; STT and TTS state live in ConnectionState
(handle_connection is invoked fresh per client by websockets.serve).
"""
import argparse
import asyncio
import base64
import json
import logging
import os
import re
import tempfile
import threading
import time
import numpy as np
import websockets
logging.basicConfig(level=logging.INFO, format='[voice_engine] %(asctime)s %(levelname)s %(message)s')
log = logging.getLogger('voice_engine')
# faster-whisper logs "Processing audio with duration ..." / "VAD filter
# removed ..." at INFO level on every partial decode during streaming STT —
# multiple times per second during a live conversation. Keep our own INFO
# logs but quiet this one down to WARNING.
logging.getLogger('faster_whisper').setLevel(logging.WARNING)
MIN_PARTIAL_BYTES = int(16000 * 2 * 0.6) # ~0.6s of 16kHz mono PCM16 before we bother decoding
# Segments where Whisper itself flags no_speech_prob above this are dropped before
# joining the transcript — catches noise/background-voice hallucination (a garbled
# guess is still emitted with low no_speech_prob when a second voice overlaps the
# caller's, so this isn't a full fix, just a confidence floor).
NO_SPEECH_PROB_CUTOFF = 0.6
# 고유어·지명 사전(faster-whisper hotwords). 2026-10-18 측정: CER 7.4% → 3.7%. VAD가 켜져 있어 무음/잡음에서는 환각이 없다.
STT_HOTWORDS = None
STT_DROP_MEAN_PROB = 0.12 # 최종 인식의 평균 단어 확률이 이보다 낮으면 환각으로 보고 버린다(실측: 환각 0.008, 정상 발화 ≥0.3)
def is_unrecoverable_cuda_error(e: Exception) -> bool:
# A CUDA "device-side assert" poisons the whole CUDA context for the rest of
# the process — every GPU call after it fails identically, whisper included.
# There is no in-process recovery; the only fix is a fresh CUDA context, i.e.
# a restart.
msg = str(e)
return 'CUDA' in msg and ('assert' in msg.lower() or 'device-side' in msg.lower() or 'failed' in msg.lower())
def crash_and_restart(where: str, e: Exception):
log.error('Unrecoverable CUDA error in %s: %s — exiting so the supervisor restarts with a fresh CUDA context.', where, e)
os._exit(1)
# Every TTS request (call streaming + the single-shot text button) serializes
# on the same GPU (measured: one request already saturates it, see
# project_tts_edge memory), so this counter doubles as an honest queue
# position — no separate scheduler needed.
_gpu_pending_lock = threading.Lock()
_gpu_pending = 0
def gpu_queue_enter() -> int:
global _gpu_pending
with _gpu_pending_lock:
_gpu_pending += 1
return _gpu_pending
def gpu_queue_exit():
global _gpu_pending
with _gpu_pending_lock:
_gpu_pending -= 1
def load_models(args):
log.info('Loading faster-whisper model=%s device=%s ...', args.stt_model, args.device)
from faster_whisper import WhisperModel
stt_model = WhisperModel(args.stt_model, device=args.device, compute_type='float16' if args.device == 'cuda' else 'int8')
log.info('faster-whisper ready.')
log.info('Transcribing speaker reference %s for the voice-clone prompt text ...', args.speaker_wav)
segments, _info = stt_model.transcribe(args.speaker_wav, language='ko', beam_size=5, vad_filter=True)
ref_text = ''.join(seg.text for seg in segments).strip()
log.info('Speaker reference text: %r', ref_text)
log.info('Loading OmniVoice (%s) ...', args.tts_model)
import torch
from omnivoice import OmniVoice
tts_model = OmniVoice.from_pretrained(args.tts_model, device_map=args.device, dtype=torch.float16, load_asr=False)
voice_clone_prompt = tts_model.create_voice_clone_prompt(ref_audio=args.speaker_wav, ref_text=ref_text)
log.info('Warming up OmniVoice ...')
tts_model.generate(text='안녕하세요.', language='Korean', voice_clone_prompt=voice_clone_prompt)
log.info('OmniVoice ready (sample_rate=%d).', tts_model.sampling_rate)
return stt_model, tts_model, voice_clone_prompt, tts_model.sampling_rate
def pcm16_from_float(audio: np.ndarray) -> bytes:
clipped = np.clip(audio, -1.0, 1.0)
return (clipped * 32767.0).astype('<i2').tobytes()
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, spk_sim=None, user=None):
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],
}
if user:
rec['user'] = user
if spk_sim is not None:
rec['spk_sim'] = round(spk_sim, 3)
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)
# ── 화자 확인 (2026-10-19, 1단계: 점수 기록만 — 거르지 않는다) ─────────────────────────────
# speechbrain ECAPA-TDNN 임베딩(CPU, 발화당 ~0.1초). 등록된 목소리와의 코사인 유사도를 확신도 로그의 spk_sim으로 남겨,
# 본인/TV/타인 발화의 점수 분포를 본 뒤에 문턱값을 정한다. 등록은 통화 중 "내 목소리 등록" 모드(spk_enroll)로.
SPK_MODEL_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '.smallclaw', 'models', 'spkrec-ecapa-voxceleb')
SPK_PROFILE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '.smallclaw', 'voice', 'speaker_profiles')
SPK_MIN_SEC = 1.0
class SpeakerGate:
"""계정별 화자 프로필. 모델은 공유, 프로필(.npy)과 등록 상태는 사용자/연결별."""
def __init__(self):
self.model = None
self.lock = threading.Lock()
self.profiles = {} # user -> 정규화된 평균 임베딩
threading.Thread(target=self._load, daemon=True).start()
@staticmethod
def _safe(user: str) -> str:
return re.sub(r'[^A-Za-z0-9_.-]', '_', user or '')[:64] or '_anon'
def _path(self, user: str) -> str:
return os.path.join(SPK_PROFILE_DIR, self._safe(user) + '.npy')
def profile(self, user: str):
if user not in self.profiles:
try:
self.profiles[user] = np.load(self._path(user)) if os.path.exists(self._path(user)) else None
except Exception:
log.warning('speaker profile load failed (%s)', user, exc_info=True)
self.profiles[user] = None
return self.profiles[user]
def _load(self):
try:
import torch # noqa: F401
from speechbrain.inference.speaker import EncoderClassifier
cache = os.path.join(tempfile.gettempdir(), 'spk_cache')
self.model = EncoderClassifier.from_hparams(source=SPK_MODEL_DIR, savedir=cache, run_opts={'device': 'cpu'})
log.info('speaker model loaded')
except Exception:
log.warning('speaker model unavailable — spk_sim disabled', exc_info=True)
def embed(self, audio):
"""audio: float32 mono 16 kHz. 반환: 정규화된 임베딩 또는 None."""
if self.model is None or audio is None or len(audio) < SPK_MIN_SEC * 16000:
return None
try:
import torch
with self.lock, torch.no_grad():
e = self.model.encode_batch(torch.from_numpy(np.asarray(audio, dtype=np.float32)).unsqueeze(0)).squeeze().cpu().numpy()
n = np.linalg.norm(e)
return e / n if n > 0 else None
except Exception:
log.debug('speaker embed failed', exc_info=True)
return None
def observe(self, audio, ctx):
"""최종 발화마다 호출. 등록 모드면 임베딩을 모으고, 아니면 이 사용자 프로필과의 유사도를 돌려준다. ctx = ConnectionState."""
emb = self.embed(audio)
if emb is None:
return None
if ctx.spk_enrolling:
ctx.spk_embs.append(emb)
return None
prof = self.profile(ctx.user)
return float(np.dot(prof, emb)) if prof is not None else None
def enroll_finish(self, ctx) -> bool:
ctx.spk_enrolling = False
if len(ctx.spk_embs) < 3:
return False
m = np.mean(np.stack(ctx.spk_embs), axis=0)
m = m / np.linalg.norm(m)
os.makedirs(SPK_PROFILE_DIR, exist_ok=True)
np.save(self._path(ctx.user), m)
self.profiles[ctx.user] = m
ctx.spk_embs = []
return True
def reset(self, user: str):
self.profiles[user] = None
try:
os.unlink(self._path(user))
except OSError:
pass
def status(self, ctx):
return {'type': 'spk_enroll_status', 'enrolling': ctx.spk_enrolling, 'count': len(ctx.spk_embs),
'enrolled': self.profile(ctx.user) is not None, 'modelReady': self.model is not None}
class Engine:
def __init__(self, args):
self.args = args
self.stt_model = None
self.spk = SpeakerGate()
self.tts_model = None # omnivoice.OmniVoice
self.voice_clone_prompt = None # precomputed — avoids re-encoding the speaker ref every call
self._tts_sample_rate = 24000
def ready(self) -> bool:
return self.stt_model is not None and self.tts_model is not None
# ── Batch STT/TTS (Telegram, single-shot web button) ──────────────────
def transcribe_full(self, audio_bytes: bytes, fmt: str, language: str):
suffix = '.' + (fmt or 'webm').lstrip('.')
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as f:
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, word_timestamps=True,
)
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:
os.unlink(path)
except OSError:
pass
# num_step default lowered from the library default (32) to 16: measured
# ~1.9x faster generation with no detectable quality loss via STT
# round-trip (2026-07-10, see project_tts_edge memory). 8 was tested and
# rejected — clearly audible/transcribable garbling on a full clause.
def synthesize_full(self, text: str, speed=None, num_step=None):
if num_step is None:
num_step = 16
if speed is None:
speed = 1.15
audio = self.tts_model.generate(
text=text[:4000],
language='Korean',
voice_clone_prompt=self.voice_clone_prompt,
speed=speed,
num_step=num_step,
)
pcm = pcm16_from_float(np.asarray(audio[0], dtype=np.float32))
return pcm, self._tts_sample_rate
# ── Streaming STT (partial decode of an accumulating PCM buffer) ──────
def transcribe_pcm(self, pcm: bytes, language: str, log_conf: bool = False, ctx=None):
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, word_timestamps=log_conf,
)
segs = list(segments)
text = ''.join(seg.text for seg in segs if seg.no_speech_prob < NO_SPEECH_PROB_CUTOFF).strip()
if log_conf:
sim = self.spk.observe(audio, ctx) if (text and ctx is not None) else None
log_stt_confidence('stream', segs, text, t0, sim, ctx.user if ctx is not None else None)
# 거의 무음·잡음에서 hotwords를 그대로 뱉는 환각("네스트 젬마 제미나이", 단어 확률 ~0.01)은 버린다.
probs = [w.probability for sg in segs if sg.no_speech_prob < NO_SPEECH_PROB_CUTOFF for w in (sg.words or [])]
if text and probs and sum(probs) / len(probs) < STT_DROP_MEAN_PROB:
log.info('STT dropped (mean_prob %.3f): %r', sum(probs) / len(probs), text)
text = ''
return text, (info.language if info else language)
# ── "Streaming" TTS ─────────────────────────────────────────────────
# OmniVoice's public API is a batch call (no token-level generator), so a
# "stream" here is one full synthesis emitted as a single chunk. At ~2x
# real-time it's fast enough that per-sentence batching (the client already
# buffers LLM output into sentence-sized pieces before calling tts_start)
# doesn't feel laggy the way XTTS/Qwen3-TTS did.
def synthesize_stream(self, text: str, is_cancelled):
if is_cancelled() or not text.strip():
return
pcm, _sample_rate = self.synthesize_full(text)
if is_cancelled():
return
yield pcm
@property
def tts_sample_rate(self) -> int:
return self._tts_sample_rate
class ConnectionState:
def __init__(self):
self.stt_buffer = bytearray()
self.stt_decoding = False
self.stt_language = 'ko'
self.tts_cancel_flags = {} # id -> bool, checked by the producer thread
self.user = '_anon' # 로그인 계정(게이트웨이가 X-HC-User 헤더로 전달)
self.spk_enrolling = False
self.spk_embs = []
async def handle_stt_partial(ws, engine: Engine, state: ConnectionState):
if state.stt_decoding or len(state.stt_buffer) < MIN_PARTIAL_BYTES:
return
state.stt_decoding = True
try:
buf = bytes(state.stt_buffer)
loop = asyncio.get_event_loop()
text, _lang = await loop.run_in_executor(None, engine.transcribe_pcm, buf, state.stt_language)
if text:
await ws.send(json.dumps({'type': 'stt_partial', 'text': text}))
except Exception as e:
log.exception('stt_partial failed')
if is_unrecoverable_cuda_error(e):
crash_and_restart('handle_stt_partial', e)
finally:
state.stt_decoding = False
async def handle_tts_start(ws, engine: Engine, state: ConnectionState, msg: dict):
text = msg.get('text', '')
req_id = msg.get('id')
state.tts_cancel_flags[req_id] = False
loop = asyncio.get_event_loop()
queue: asyncio.Queue = asyncio.Queue()
def is_cancelled():
return state.tts_cancel_flags.get(req_id, False)
def produce():
try:
for chunk in engine.synthesize_stream(text, is_cancelled):
loop.call_soon_threadsafe(queue.put_nowait, ('chunk', chunk))
loop.call_soon_threadsafe(queue.put_nowait, ('done', None))
except Exception as e: # noqa: BLE001
log.exception('tts stream failed')
loop.call_soon_threadsafe(queue.put_nowait, ('error', str(e)))
if is_unrecoverable_cuda_error(e):
crash_and_restart('handle_tts_start', e)
finally:
gpu_queue_exit()
position = gpu_queue_enter()
if position > 1:
# Someone else's synthesis is already running on the GPU (it's
# effectively serialized — see project_tts_edge memory); let the
# client show a queue indicator instead of silently hanging.
await ws.send(json.dumps({'type': 'tts_queue', 'aheadCount': position - 1, 'id': req_id}))
threading.Thread(target=produce, daemon=True).start()
try:
stream_started = False
while True:
kind, payload = await queue.get()
if kind == 'chunk':
if not stream_started:
# synthesize_stream yields the whole clip as one chunk
# (see its docstring) once GPU generation actually
# finishes, so this is the right moment to tell the
# client "now speaking" — sending it eagerly up front
# would stomp the tts_queue status above.
await ws.send(json.dumps({'type': 'tts_stream_start', 'sampleRate': engine.tts_sample_rate, 'id': req_id}))
stream_started = True
await ws.send(payload)
elif kind == 'error':
await ws.send(json.dumps({'type': 'error', 'message': payload, 'id': req_id}))
break
else:
await ws.send(json.dumps({'type': 'tts_end', 'id': req_id}))
break
finally:
state.tts_cancel_flags.pop(req_id, None)
async def handle_connection(ws, engine: Engine):
await _handle_connection(ws, engine)
async def _handle_connection(ws, engine: Engine):
state = ConnectionState()
try:
hdrs = getattr(getattr(ws, 'request', None), 'headers', None)
u = hdrs.get('X-HC-User') if hdrs is not None else None
if u:
from urllib.parse import unquote
state.user = unquote(u)
except Exception:
pass
async for raw in ws:
try:
if isinstance(raw, (bytes, bytearray)):
state.stt_buffer.extend(raw)
asyncio.create_task(handle_stt_partial(ws, engine, state))
continue
msg = json.loads(raw)
mtype = msg.get('type')
req_id = msg.get('id')
if mtype == 'ping':
await ws.send(json.dumps({'type': 'pong', 'ready': engine.ready(), 'id': req_id}))
elif mtype == 'stt_transcribe_full':
audio_bytes = base64.b64decode(msg['audioBase64'])
fmt = msg.get('format', 'webm')
language = msg.get('language', 'ko')
loop = asyncio.get_event_loop()
text, lang = await loop.run_in_executor(None, engine.transcribe_full, audio_bytes, fmt, language)
await ws.send(json.dumps({'type': 'stt_final', 'text': text, 'language': lang, 'id': req_id}))
elif mtype == 'tts_synthesize_full':
text = msg.get('text', '')
speed = msg.get('speed')
num_step = msg.get('num_step')
loop = asyncio.get_event_loop()
gpu_queue_enter()
try:
pcm, sample_rate = await loop.run_in_executor(None, engine.synthesize_full, text, speed, num_step)
finally:
gpu_queue_exit()
await ws.send(json.dumps({
'type': 'tts_result',
'audioBase64': base64.b64encode(pcm).decode('ascii'),
'sampleRate': sample_rate,
'id': req_id,
}))
elif mtype == 'spk_enroll':
act = msg.get('action')
if act == 'start':
state.spk_enrolling = True; state.spk_embs = []
elif act == 'finish':
engine.spk.enroll_finish(state)
elif act == 'cancel':
state.spk_enrolling = False; state.spk_embs = []
elif act == 'reset':
engine.spk.reset(state.user)
await ws.send(json.dumps(engine.spk.status(state)))
elif mtype == 'stt_start':
state.stt_buffer = bytearray()
state.stt_language = msg.get('language', 'ko')
elif mtype == 'stt_stop':
buf = bytes(state.stt_buffer)
state.stt_buffer = bytearray()
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, True, state)
await ws.send(json.dumps({'type': 'stt_final', 'text': text, 'language': lang, 'id': req_id}))
elif mtype == 'tts_start':
asyncio.create_task(handle_tts_start(ws, engine, state, msg))
elif mtype == 'tts_cancel':
target_id = msg.get('id')
if target_id is not None:
state.tts_cancel_flags[target_id] = True
else:
for k in state.tts_cancel_flags:
state.tts_cancel_flags[k] = True
else:
await ws.send(json.dumps({'type': 'error', 'message': f'unknown type {mtype}', 'id': req_id}))
except Exception as e:
log.exception('request failed')
try:
await ws.send(json.dumps({'type': 'error', 'message': str(e), 'id': msg.get('id') if 'msg' in dir() else None}))
except Exception:
pass
if is_unrecoverable_cuda_error(e):
crash_and_restart('handle_connection', e)
async def main():
parser = argparse.ArgumentParser()
parser.add_argument('--port', type=int, default=8765)
parser.add_argument('--stt-model', default='medium')
parser.add_argument('--stt-hotwords', default='', help='Whisper hotwords (space-separated vocabulary)')
parser.add_argument('--tts-model', default='k2-fsa/OmniVoice')
parser.add_argument('--speaker-wav', default='')
parser.add_argument('--device', default='cuda')
args = parser.parse_args()
global STT_HOTWORDS
STT_HOTWORDS = (args.stt_hotwords or '').strip() or None
log.info('STT hotwords: %s', STT_HOTWORDS or '(none)')
engine = Engine(args)
(engine.stt_model, engine.tts_model, engine.voice_clone_prompt,
engine._tts_sample_rate) = load_models(args)
async with websockets.serve(lambda ws: handle_connection(ws, engine), '127.0.0.1', args.port, max_size=64 * 1024 * 1024):
log.info('voice_engine listening on 127.0.0.1:%d', args.port)
await asyncio.Future()
if __name__ == '__main__':
asyncio.run(main())