Delete models.py
Browse files
models.py
DELETED
|
@@ -1,218 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
models.py
|
| 3 |
-
---------
|
| 4 |
-
Single source of truth for every model used in the pipeline.
|
| 5 |
-
|
| 6 |
-
Component Model Params Device
|
| 7 |
-
----------- --------------------------------------- ------- ------
|
| 8 |
-
STT openai/whisper-base.en 74 M GPU/CPU (fp16/fp32)
|
| 9 |
-
LLM HuggingFaceTB/SmolLM2-1.7B-Instruct 1.7 B GPU/CPU (fp16/fp32)
|
| 10 |
-
TTS facebook/mms-tts-eng (VITS) ~430 M CPU (fp32)
|
| 11 |
-
VAD silero-vad 2 MB CPU
|
| 12 |
-
|
| 13 |
-
All models are loaded once at startup. Inference methods are synchronous
|
| 14 |
-
(blocking) — call them from a thread-pool executor inside async handlers.
|
| 15 |
-
"""
|
| 16 |
-
|
| 17 |
-
from __future__ import annotations
|
| 18 |
-
|
| 19 |
-
import logging
|
| 20 |
-
import time
|
| 21 |
-
from typing import Optional
|
| 22 |
-
|
| 23 |
-
import numpy as np
|
| 24 |
-
import torch
|
| 25 |
-
from transformers import (
|
| 26 |
-
AutoModelForCausalLM,
|
| 27 |
-
AutoTokenizer,
|
| 28 |
-
VitsModel,
|
| 29 |
-
WhisperForConditionalGeneration,
|
| 30 |
-
WhisperProcessor,
|
| 31 |
-
)
|
| 32 |
-
|
| 33 |
-
logger = logging.getLogger(__name__)
|
| 34 |
-
|
| 35 |
-
# --------------------------------------------------------------------------- #
|
| 36 |
-
# Model IDs (swap here for lighter / heavier variants) #
|
| 37 |
-
# --------------------------------------------------------------------------- #
|
| 38 |
-
STT_MODEL_ID = "openai/whisper-base.en" # 74 M — swap tiny.en for CPU-only
|
| 39 |
-
LLM_MODEL_ID = "HuggingFaceTB/SmolLM2-1.7B-Instruct" # 1.7 B — swap 360M for CPU-only
|
| 40 |
-
TTS_MODEL_ID = "facebook/mms-tts-eng" # VITS, 16 kHz output
|
| 41 |
-
|
| 42 |
-
STT_SR = 16_000 # Whisper expects 16 kHz
|
| 43 |
-
TTS_SR = 16_000 # MMS-TTS-ENG native output rate
|
| 44 |
-
MAX_NEW_TOKENS = 256 # Cap LLM response length for voice interaction
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
# --------------------------------------------------------------------------- #
|
| 48 |
-
# ModelManager #
|
| 49 |
-
# --------------------------------------------------------------------------- #
|
| 50 |
-
class ModelManager:
|
| 51 |
-
"""Load and expose all model inference in one place."""
|
| 52 |
-
|
| 53 |
-
def __init__(self):
|
| 54 |
-
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 55 |
-
self.compute_dtype = (
|
| 56 |
-
torch.float16 if self.device == "cuda" else torch.float32
|
| 57 |
-
)
|
| 58 |
-
logger.info("Device: %s | dtype: %s", self.device, self.compute_dtype)
|
| 59 |
-
|
| 60 |
-
# TTS always runs on CPU (saves GPU VRAM for STT + LLM)
|
| 61 |
-
self.tts_device = "cpu"
|
| 62 |
-
|
| 63 |
-
self._load_vad()
|
| 64 |
-
self._load_stt()
|
| 65 |
-
self._load_llm()
|
| 66 |
-
self._load_tts()
|
| 67 |
-
logger.info("✅ All models ready.")
|
| 68 |
-
|
| 69 |
-
# ------------------------------------------------------------------ #
|
| 70 |
-
# VAD #
|
| 71 |
-
# ------------------------------------------------------------------ #
|
| 72 |
-
def _load_vad(self):
|
| 73 |
-
logger.info("Loading VAD (silero-vad) …")
|
| 74 |
-
from silero_vad import VADIterator, load_silero_vad # type: ignore
|
| 75 |
-
|
| 76 |
-
vad_model = load_silero_vad()
|
| 77 |
-
# silence_ms=700 → 700 ms of quiet ends an utterance
|
| 78 |
-
self.vad_iter = VADIterator(
|
| 79 |
-
vad_model,
|
| 80 |
-
sampling_rate=STT_SR,
|
| 81 |
-
threshold=0.50,
|
| 82 |
-
min_silence_duration_ms=700,
|
| 83 |
-
speech_pad_ms=50,
|
| 84 |
-
)
|
| 85 |
-
logger.info("VAD ready.")
|
| 86 |
-
|
| 87 |
-
def vad_reset(self):
|
| 88 |
-
"""Reset VAD state between conversations."""
|
| 89 |
-
self.vad_iter.reset_states()
|
| 90 |
-
|
| 91 |
-
# ------------------------------------------------------------------ #
|
| 92 |
-
# STT — Whisper #
|
| 93 |
-
# ------------------------------------------------------------------ #
|
| 94 |
-
def _load_stt(self):
|
| 95 |
-
logger.info("Loading STT: %s …", STT_MODEL_ID)
|
| 96 |
-
self.stt_processor = WhisperProcessor.from_pretrained(STT_MODEL_ID)
|
| 97 |
-
self.stt_model = WhisperForConditionalGeneration.from_pretrained(
|
| 98 |
-
STT_MODEL_ID,
|
| 99 |
-
torch_dtype=self.compute_dtype,
|
| 100 |
-
).to(self.device)
|
| 101 |
-
self.stt_model.eval()
|
| 102 |
-
logger.info("STT ready on %s.", self.device)
|
| 103 |
-
|
| 104 |
-
def transcribe(self, audio_float32: np.ndarray) -> str:
|
| 105 |
-
"""
|
| 106 |
-
Transcribe a 16 kHz float32 numpy array to text.
|
| 107 |
-
|
| 108 |
-
Parameters
|
| 109 |
-
----------
|
| 110 |
-
audio_float32 : np.ndarray shape (N,), dtype float32, range [-1, 1]
|
| 111 |
-
"""
|
| 112 |
-
t0 = time.perf_counter()
|
| 113 |
-
|
| 114 |
-
inputs = self.stt_processor(
|
| 115 |
-
audio_float32,
|
| 116 |
-
sampling_rate=STT_SR,
|
| 117 |
-
return_tensors="pt",
|
| 118 |
-
)
|
| 119 |
-
features = inputs.input_features.to(
|
| 120 |
-
device=self.device, dtype=self.compute_dtype
|
| 121 |
-
)
|
| 122 |
-
|
| 123 |
-
with torch.no_grad():
|
| 124 |
-
ids = self.stt_model.generate(features, language="en", task="transcribe")
|
| 125 |
-
|
| 126 |
-
text = self.stt_processor.batch_decode(ids, skip_special_tokens=True)[0].strip()
|
| 127 |
-
logger.info("STT (%.0f ms): '%s'", (time.perf_counter() - t0) * 1000, text)
|
| 128 |
-
return text
|
| 129 |
-
|
| 130 |
-
# ------------------------------------------------------------------ #
|
| 131 |
-
# LLM — SmolLM2 #
|
| 132 |
-
# ------------------------------------------------------------------ #
|
| 133 |
-
def _load_llm(self):
|
| 134 |
-
logger.info("Loading LLM: %s …", LLM_MODEL_ID)
|
| 135 |
-
self.llm_tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL_ID)
|
| 136 |
-
self.llm = AutoModelForCausalLM.from_pretrained(
|
| 137 |
-
LLM_MODEL_ID,
|
| 138 |
-
torch_dtype=self.compute_dtype,
|
| 139 |
-
).to(self.device)
|
| 140 |
-
self.llm.eval()
|
| 141 |
-
logger.info("LLM ready on %s.", self.device)
|
| 142 |
-
|
| 143 |
-
def build_prompt(self, messages: list[dict]) -> str:
|
| 144 |
-
"""Apply the model's chat template and return a formatted string."""
|
| 145 |
-
return self.llm_tokenizer.apply_chat_template(
|
| 146 |
-
messages,
|
| 147 |
-
tokenize=False,
|
| 148 |
-
add_generation_prompt=True,
|
| 149 |
-
)
|
| 150 |
-
|
| 151 |
-
def tokenize(self, prompt: str) -> dict:
|
| 152 |
-
"""Tokenize a prompt string → dict of tensors on self.device."""
|
| 153 |
-
enc = self.llm_tokenizer(prompt, return_tensors="pt")
|
| 154 |
-
return {k: v.to(self.device) for k, v in enc.items()}
|
| 155 |
-
|
| 156 |
-
# ------------------------------------------------------------------ #
|
| 157 |
-
# TTS — MMS-TTS-ENG (VITS) #
|
| 158 |
-
# ------------------------------------------------------------------ #
|
| 159 |
-
def _load_tts(self):
|
| 160 |
-
logger.info("Loading TTS: %s …", TTS_MODEL_ID)
|
| 161 |
-
self.tts_tokenizer = AutoTokenizer.from_pretrained(TTS_MODEL_ID)
|
| 162 |
-
self.tts_model = VitsModel.from_pretrained(TTS_MODEL_ID) # fp32 on CPU
|
| 163 |
-
self.tts_model.eval()
|
| 164 |
-
self.tts_sample_rate: int = self.tts_model.config.sampling_rate # 16 000
|
| 165 |
-
logger.info("TTS ready on CPU (sample_rate=%d Hz).", self.tts_sample_rate)
|
| 166 |
-
|
| 167 |
-
def synthesize(self, text: str) -> Optional[bytes]:
|
| 168 |
-
"""
|
| 169 |
-
Synthesize text → raw PCM bytes (int16, mono, 16 kHz).
|
| 170 |
-
|
| 171 |
-
Returns None if text is empty or synthesis fails.
|
| 172 |
-
"""
|
| 173 |
-
text = text.strip()
|
| 174 |
-
if not text:
|
| 175 |
-
return None
|
| 176 |
-
|
| 177 |
-
t0 = time.perf_counter()
|
| 178 |
-
|
| 179 |
-
try:
|
| 180 |
-
inputs = self.tts_tokenizer(text, return_tensors="pt")
|
| 181 |
-
with torch.no_grad():
|
| 182 |
-
output = self.tts_model(**inputs)
|
| 183 |
-
|
| 184 |
-
# waveform: (1, T) float32 in roughly [-1, 1]
|
| 185 |
-
wav: np.ndarray = output.waveform.squeeze().cpu().numpy()
|
| 186 |
-
|
| 187 |
-
# Convert float32 → int16 PCM
|
| 188 |
-
wav_int16 = np.clip(wav * 32_767.0, -32_768, 32_767).astype(np.int16)
|
| 189 |
-
pcm_bytes = wav_int16.tobytes()
|
| 190 |
-
|
| 191 |
-
logger.debug(
|
| 192 |
-
"TTS (%.0f ms): %d chars → %d bytes",
|
| 193 |
-
(time.perf_counter() - t0) * 1000,
|
| 194 |
-
len(text),
|
| 195 |
-
len(pcm_bytes),
|
| 196 |
-
)
|
| 197 |
-
return pcm_bytes
|
| 198 |
-
|
| 199 |
-
except Exception as exc:
|
| 200 |
-
logger.error("TTS synthesis failed for %r: %s", text[:60], exc)
|
| 201 |
-
return None
|
| 202 |
-
|
| 203 |
-
# ------------------------------------------------------------------ #
|
| 204 |
-
# Convenience #
|
| 205 |
-
# ------------------------------------------------------------------ #
|
| 206 |
-
def warm_up(self):
|
| 207 |
-
"""Run a tiny inference on each model to pre-JIT all kernels."""
|
| 208 |
-
logger.info("Warming up models …")
|
| 209 |
-
silence = np.zeros(STT_SR, dtype=np.float32)
|
| 210 |
-
self.transcribe(silence)
|
| 211 |
-
dummy_msgs = [
|
| 212 |
-
{"role": "system", "content": "You are helpful."},
|
| 213 |
-
{"role": "user", "content": "hi"},
|
| 214 |
-
]
|
| 215 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