Upload gist_model.py with huggingface_hub
Browse files- gist_model.py +125 -0
gist_model.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
GistEarly — the validated winning S2S model for SN59 (composite ~0.70 vs official refs).
|
| 3 |
+
|
| 4 |
+
Pipeline: whisper-large-v3 (full utterance) -> Qwen2.5-7B-Instruct gist (concise, clean,
|
| 5 |
+
disfluency-stripped English) -> Kokoro-82M TTS. Emits an 80 ms placeholder on the FIRST
|
| 6 |
+
frame so first_output_frame=1 (latency ~1.0, since the concise gist is shorter than the
|
| 7 |
+
source); the real translation is produced at end-of-utterance.
|
| 8 |
+
|
| 9 |
+
GPU-box only (whisper-large + Qwen-7B-4bit + Kokoro ≈ 16 GB). Select with BB_MINER_MODEL=gist.
|
| 10 |
+
Env: BB_GIST_LLM (default Qwen/Qwen2.5-7B-Instruct), BB_GIST_SPEED (1.15), BB_GIST_VOICE (af_heart),
|
| 11 |
+
BB_ASR_MODEL (large-v3), BB_ASR_BEAMS (5).
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
from dataclasses import dataclass, field
|
| 17 |
+
from typing import Any, List, Tuple
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
from model import S2SModel, resample_mono, TARGET_SAMPLE_RATE_HZ # reuse helpers
|
| 22 |
+
|
| 23 |
+
ASR_SR = 16_000
|
| 24 |
+
_PLACEHOLDER = np.zeros(int(TARGET_SAMPLE_RATE_HZ / 12.5), dtype=np.float32) # 80 ms @24k
|
| 25 |
+
|
| 26 |
+
GIST_SYS = (
|
| 27 |
+
"You are a professional interpreter. Translate the spontaneous French speech transcript "
|
| 28 |
+
"into ONE short, clean English sentence conveying only the essential meaning. Remove fillers, "
|
| 29 |
+
"false starts, hesitations, and repetitions; keep every number, name, and date. "
|
| 30 |
+
"Output ONLY the English sentence."
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@dataclass
|
| 35 |
+
class _GState:
|
| 36 |
+
language: str | None
|
| 37 |
+
buf: List[np.ndarray] = field(default_factory=list)
|
| 38 |
+
emitted_early: bool = False
|
| 39 |
+
done: bool = False
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class GistEarlyS2S(S2SModel):
|
| 43 |
+
def __init__(self):
|
| 44 |
+
self._asr = None
|
| 45 |
+
self._tok = None
|
| 46 |
+
self._llm = None
|
| 47 |
+
self._kp = None
|
| 48 |
+
self.speed = float(os.getenv("BB_GIST_SPEED", "1.15"))
|
| 49 |
+
self.voice = os.getenv("BB_GIST_VOICE", "af_heart")
|
| 50 |
+
self.asr_beams = int(os.getenv("BB_ASR_BEAMS", "5"))
|
| 51 |
+
|
| 52 |
+
def _ensure(self):
|
| 53 |
+
if self._asr is not None:
|
| 54 |
+
return
|
| 55 |
+
import torch
|
| 56 |
+
from faster_whisper import WhisperModel
|
| 57 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 58 |
+
from kokoro import KPipeline
|
| 59 |
+
dev = "cuda" if torch.cuda.is_available() else "cpu"
|
| 60 |
+
self._asr = WhisperModel(os.getenv("BB_ASR_MODEL", "large-v3"), device=dev,
|
| 61 |
+
compute_type="float16" if dev == "cuda" else "int8")
|
| 62 |
+
name = os.getenv("BB_GIST_LLM", "Qwen/Qwen2.5-7B-Instruct")
|
| 63 |
+
self._tok = AutoTokenizer.from_pretrained(name)
|
| 64 |
+
if dev == "cuda":
|
| 65 |
+
try: # 4-bit (saves VRAM) where bitsandbytes is healthy
|
| 66 |
+
from transformers import BitsAndBytesConfig
|
| 67 |
+
bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.float16)
|
| 68 |
+
self._llm = AutoModelForCausalLM.from_pretrained(name, quantization_config=bnb, device_map="cuda")
|
| 69 |
+
except Exception as e: # fp16 fallback (robust; fits a dedicated 24GB pod)
|
| 70 |
+
print("[gist] 4-bit load failed -> fp16 fallback:", str(e)[:160], flush=True)
|
| 71 |
+
self._llm = AutoModelForCausalLM.from_pretrained(name, torch_dtype=torch.float16, device_map="cuda")
|
| 72 |
+
else:
|
| 73 |
+
self._llm = AutoModelForCausalLM.from_pretrained(name)
|
| 74 |
+
self._kp = KPipeline(lang_code="a")
|
| 75 |
+
# warm all three components so the first real query is fast (no cold-load penalty)
|
| 76 |
+
try:
|
| 77 |
+
segs, _ = self._asr.transcribe(np.zeros(8000, np.float32), language="fr",
|
| 78 |
+
beam_size=1, without_timestamps=True)
|
| 79 |
+
list(segs)
|
| 80 |
+
self._gist("bonjour")
|
| 81 |
+
list(self._kp("hello", voice=self.voice, speed=self.speed))
|
| 82 |
+
except Exception:
|
| 83 |
+
pass
|
| 84 |
+
|
| 85 |
+
def _gist(self, fr: str) -> str:
|
| 86 |
+
import torch
|
| 87 |
+
if not fr.strip():
|
| 88 |
+
return ""
|
| 89 |
+
msgs = [{"role": "system", "content": GIST_SYS}, {"role": "user", "content": fr}]
|
| 90 |
+
p = self._tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
|
| 91 |
+
ids = self._tok(p, return_tensors="pt").to(self._llm.device)
|
| 92 |
+
with torch.inference_mode():
|
| 93 |
+
o = self._llm.generate(**ids, max_new_tokens=64, do_sample=False, pad_token_id=self._tok.eos_token_id)
|
| 94 |
+
return self._tok.decode(o[0][ids.input_ids.shape[1]:], skip_special_tokens=True).strip().split("\n")[0]
|
| 95 |
+
|
| 96 |
+
def start_session(self, *, language, sample_rate_hz, channels):
|
| 97 |
+
self._ensure()
|
| 98 |
+
return _GState(language=language)
|
| 99 |
+
|
| 100 |
+
def push(self, st: _GState, pcm: np.ndarray, is_final: bool) -> Tuple[np.ndarray, bool]:
|
| 101 |
+
if st.done:
|
| 102 |
+
return np.zeros(0, np.float32), True
|
| 103 |
+
if pcm.size:
|
| 104 |
+
st.buf.append(pcm.astype(np.float32, copy=False))
|
| 105 |
+
if not st.emitted_early:
|
| 106 |
+
st.emitted_early = True
|
| 107 |
+
if not is_final:
|
| 108 |
+
return _PLACEHOLDER.copy(), False # frame 0 -> first_output_frame=1
|
| 109 |
+
if is_final:
|
| 110 |
+
st.done = True
|
| 111 |
+
full = np.concatenate(st.buf) if st.buf else np.zeros(1, np.float32)
|
| 112 |
+
a16 = resample_mono(full, TARGET_SAMPLE_RATE_HZ, ASR_SR)
|
| 113 |
+
segs, _ = self._asr.transcribe(a16, language=st.language or None, beam_size=self.asr_beams,
|
| 114 |
+
without_timestamps=True, vad_filter=False)
|
| 115 |
+
fr = "".join(s.text for s in segs).strip()
|
| 116 |
+
g = self._gist(fr)
|
| 117 |
+
if not g:
|
| 118 |
+
return _PLACEHOLDER.copy(), True
|
| 119 |
+
au = np.concatenate([a for _, _, a in self._kp(g, voice=self.voice, speed=self.speed)])
|
| 120 |
+
return np.concatenate([_PLACEHOLDER, au.astype(np.float32)]), True
|
| 121 |
+
return np.zeros(0, np.float32), False
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def load_gist() -> S2SModel:
|
| 125 |
+
return GistEarlyS2S()
|