- One shared faster-whisper model for every speaker, batched; finals go before partials and partial batches are capped at two so a final never waits behind a ten-speaker pass. - Per-speaker 48k stereo to 16k mono conversion, streaming Silero VAD, utterance ends on VAD silence, Discord speaking_end, missing audio, or the 28 s Whisper window. - MeloTTS in its own venv through a child process; sentences stream out one chunk each, with incremental text, cancel and failure reporting. - Loopback-only server with a token from the environment; logs carry no transcript text. - Spec in src/voice_worker/voice_worker.spec.md; unit tests with fake engines and an opt-in real-GPU test that streams ten speakers at once. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
79 lines
3.2 KiB
Python
79 lines
3.2 KiB
Python
"""faster-whisper batch transcription: one encoder and one decoder pass for every clip in a batch."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import glob
|
|
import os
|
|
import sys
|
|
|
|
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)
|
|
|
|
|
|
def add_cuda_dll_dirs() -> None:
|
|
"""On Windows ctranslate2 loads cuBLAS/cuDNN from the PATH; the pip wheels put them in nvidia/*/bin."""
|
|
if not hasattr(os, "add_dll_directory"):
|
|
return
|
|
for sp in sys.path:
|
|
for d in glob.glob(os.path.join(sp, "nvidia", "*", "bin")):
|
|
if os.path.isdir(d):
|
|
os.environ["PATH"] = d + os.pathsep + os.environ.get("PATH", "")
|
|
os.add_dll_directory(d)
|
|
|
|
|
|
class WhisperTranscriber:
|
|
def __init__(self, model: str = "large-v3-turbo", device: str = "cuda", compute_type: str = "int8_float16"):
|
|
add_cuda_dll_dirs()
|
|
from faster_whisper import WhisperModel
|
|
self.model = WhisperModel(model, device=device, compute_type=compute_type)
|
|
self._tokenizers: dict = {}
|
|
debug_log(f"whisper loaded model={model} device={device} compute={compute_type}", "voice_worker")
|
|
|
|
def _tokenizer(self, language: str):
|
|
tok = self._tokenizers.get(language)
|
|
if tok is None:
|
|
from faster_whisper.tokenizer import Tokenizer
|
|
tok = Tokenizer(self.model.hf_tokenizer, self.model.model.is_multilingual, task="transcribe",
|
|
language=language)
|
|
self._tokenizers[language] = tok
|
|
return tok
|
|
|
|
def warm_up(self) -> None:
|
|
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]:
|
|
m = self.model
|
|
n_frames = m.feature_extractor.nb_max_frames
|
|
feats = []
|
|
for c in clips:
|
|
a = peak_normalise(c[: SR * 30])
|
|
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))
|
|
if opts.language:
|
|
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
|