NarratifAI / src /voice.py
NarratifAI deploy
Deploy asr_system fa0cec3 (origin/release/nari-main, Nari voice)
adebf46
Raw History Blame Contribute Delete
4.5 kB
"""Short voice clips for Nari (the NarratifAI companion): a person taps the
mic, speaks, and the clip is turned into text here, with the same models and
Nigerian-language support as transcription.
Only Nari's backend (the Supabase function nari-voice) may call this: it
authenticates the user, applies limits and billing, then forwards the clip
with a shared secret. Nothing is charged or stored here."""
from __future__ import annotations
import hmac
MAX_VOICE_BYTES = 3 * 1024 * 1024 # about 60 s of compressed speech, with room
MAX_VOICE_SECONDS = 62.0
LANGS = {"en", "yo", "ig", "ha", "pcm", "fr", "ar", "pt", "es", "fa", "sw", "hi", "zh", "de"}
def authorized(given: str | None, secret: str | None) -> bool:
"""The shared secret must be set (16+ characters) and match exactly."""
if not secret or len(secret) < 16 or not given:
return False
return hmac.compare_digest(given.encode(), secret.encode())
def languages(raw: str | None) -> list[str]:
"""'yo,en' -> ['yo', 'en']; unknown codes and 'auto' are dropped (auto-detect)."""
out = []
for part in (raw or "").split(","):
code = part.strip().lower()
if code in LANGS and code not in out:
out.append(code)
return out[:3]
def clean_text(text: str | None) -> str:
"""Whisper sometimes returns a lone placeholder for silence."""
t = " ".join((text or "").split())
if t.lower().strip(" .!?") in {"", "you", "thank you", "thanks for watching", "[music]", "[silence]"}:
return ""
return t[:4000]
# ---------------------------------------------------------------------------
# Fast path: a dedicated model kept loaded just for voice questions, outside
# the shared engine (whose model swaps unload everything else). Short clips
# decode in well under a second on the T4 and never wait behind a meeting job.
# Yoruba, Igbo and Hausa still go through the engine's Nigerian models.
# ---------------------------------------------------------------------------
import os
import subprocess
import tempfile
import threading
FAST_MODEL = os.getenv("NARI_VOICE_MODEL", "openai/whisper-large-v3-turbo")
NIGERIAN = {"yo", "ig", "ha"}
_pipe = None
_pipe_lock = threading.Lock() # building the model
_run_lock = threading.Lock() # one voice clip at a time on the fast model
def wants_engine(langs: list[str]) -> bool:
"""Nigerian languages need the engine's dedicated models."""
return any(l in NIGERIAN for l in langs)
def fast_pipeline():
"""The voice model, built once (at startup when voice is configured)."""
global _pipe
if _pipe is not None:
return _pipe
with _pipe_lock:
if _pipe is None:
import torch
from transformers import pipeline
cuda = torch.cuda.is_available()
_pipe = pipeline("automatic-speech-recognition", model=FAST_MODEL,
torch_dtype=torch.float16 if cuda else torch.float32,
device="cuda:0" if cuda else "cpu")
return _pipe
def decode(content: bytes, suffix: str = ".webm"):
"""Any browser recording -> 16 kHz mono float audio (via ffmpeg)."""
import numpy as np
with tempfile.TemporaryDirectory() as tmp:
src = os.path.join(tmp, "in" + (suffix if suffix.startswith(".") and len(suffix) <= 6 else ".bin"))
with open(src, "wb") as f:
f.write(content)
out = subprocess.run(["ffmpeg", "-nostdin", "-loglevel", "error", "-i", src, "-ac", "1", "-ar", "16000", "-f", "f32le", "-"],
capture_output=True, timeout=30)
if out.returncode != 0:
raise ValueError("Unreadable audio")
return np.frombuffer(out.stdout, dtype=np.float32)
def transcribe_fast(content: bytes, suffix: str, langs: list[str]) -> dict:
audio = decode(content, suffix)
seconds = len(audio) / 16000
if seconds > MAX_VOICE_SECONDS:
return {"text": "", "seconds": seconds, "language": None, "too_long": True}
if seconds < 0.3:
return {"text": "", "seconds": seconds, "language": None}
gen = {"task": "transcribe"}
if langs:
gen["language"] = langs[0]
pipe = fast_pipeline()
with _run_lock:
out = pipe({"raw": audio, "sampling_rate": 16000}, generate_kwargs=gen, return_timestamps=seconds > 30)
return {"text": clean_text(out.get("text") if isinstance(out, dict) else ""), "seconds": round(seconds, 2), "language": langs[0] if langs else None}