Files
teams-whisper/app/transcribe.py
T

120 lines
5.5 KiB
Python

"""Whisper transcription: faster-whisper (cuda) or OpenVINO GenAI (npu)."""
import gc, json, subprocess, time
from pathlib import Path
import numpy as np
import db
HERE = Path(__file__).parent
# Pre-converted OpenVINO Whisper model; downloaded on first NPU use.
NPU_MODEL_DIR = HERE / "models" / "whisper-large-v3-turbo-ov"
# Log via Prefect when inside a flow; print otherwise.
def _log(msg):
try:
from prefect import get_run_logger
get_run_logger().info(msg)
except Exception:
print(msg, flush=True)
def aggregate(segs):
"""(start,end,text) -> [(sec,text)]: flush on end punctuation, >1s gap, or >12s run. A segment repeated 3+ times in a row is a whisper loop (46x "Ciao."): keep 2."""
lines, buf, start, end, last, rep = [], [], 0, 0, None, 0
def flush():
if buf:
lines.append((int(start), " ".join(buf))); buf.clear()
for s, e, t in segs:
t = t.strip()
if not t: continue
# Count consecutive identical segments; the 3rd+ repeat is a whisper loop and is skipped.
rep = rep + 1 if t == last else 0; last = t
if rep >= 2: continue
# A pause over 1 s starts a new line.
if buf and s - end > 1: flush()
if not buf: start = s
buf.append(t); end = e
# End the line at sentence punctuation, or after 12 s.
if t.endswith((".", "?", "!", "…")) or end - start > 12: flush()
flush()
return lines
# Decode to 16 kHz mono float32 PCM via ffmpeg; the format whisper and the NPU pipeline expect.
def _decode(path):
raw = subprocess.run(["ffmpeg", "-v", "error", "-i", str(path), "-vn", "-ac", "1", "-ar", "16000", "-f", "f32le", "-"],
capture_output=True, check=True).stdout
return np.frombuffer(raw, np.float32)
# Faster-whisper on CUDA (CPU fallback in common.load_model); returns (segments, device). tick(done, total) reports progress.
def _cuda(audio, model, glossary, tick=lambda done, total: None):
import common
# Load the model; dev is 'cuda' or 'cpu'.
m, dev = common.load_model(model)
# ponytail: >~20 hotwords crowd whisper's prompt -> dropped text + repetition loops (seen with 60)
kw = {"hotwords": " ".join(glossary[:20]), "condition_on_previous_text": False} if glossary else {}
try:
# Italian forced; VAD (voice activity detection) skips silence.
segs, info = m.transcribe(str(audio), language="it", vad_filter=True, **kw)
out = []
# Keep each segment, reporting progress by its end time.
for s in segs: out.append((s.start, s.end, s.text)); tick(s.end, info.duration)
return out, dev
finally:
# Free the model (VRAM) before returning, even on error.
del m; gc.collect()
# OpenVINO GenAI Whisper on the Intel NPU. Failure raises 'NPU failed' so flow.py can fall back to CUDA.
def _npu(audio):
try:
import openvino_genai as ov
# First run: download the pre-converted model; if that fails, export it locally with optimum (slow).
if not NPU_MODEL_DIR.exists():
from huggingface_hub import snapshot_download
try:
snapshot_download("OpenVINO/whisper-large-v3-turbo-fp16-ov", local_dir=NPU_MODEL_DIR)
except Exception:
subprocess.run(["optimum-cli", "export", "openvino", "--model", "openai/whisper-large-v3-turbo",
"--weight-format", "fp16", str(NPU_MODEL_DIR)], check=True)
# Load the pipeline on the NPU device.
pipe = ov.WhisperPipeline(str(NPU_MODEL_DIR), "NPU")
res = pipe.generate(_decode(audio).tolist(), language="<|it|>", task="transcribe", return_timestamps=True)
# Empty output counts as failure.
if not res.chunks: raise RuntimeError("no chunks returned")
return [(c.start_ts, c.end_ts, c.text) for c in res.chunks]
except Exception as e:
raise RuntimeError(f"NPU failed: {e!r}")
# Transcribe one meeting into transcript.txt and DB lines. out_path is used by --bench-npu to write a side file only.
def run(name, model="large-v3-turbo", lang="it", device="cuda", out_path: Path | None = None):
audio = db.out_dir(name) / "audio.opus"
gl = db.out_dir(name) / "glossary.json"
# Glossary from shots (used as whisper hotwords).
glossary = json.loads(gl.read_text(encoding="utf-8")) if gl.exists() else []
t0 = time.time()
# NPU reports no progress; CUDA reports per segment.
if device == "npu":
db.tick(name, 0, 0, "trascrizione su NPU (nessun avanzamento parziale)")
segs, used = _npu(audio), "npu"
else:
tick = lambda done, total: db.tick(name, round(done), round(total), f"{done / 60:.0f} di {total / 60:.0f} min di audio")
segs, used = _cuda(audio, model, glossary, tick)
# Group segments into timestamped lines.
lines = aggregate(segs)
# Format as [mm:ss] text, the format diarize.py parses.
txt = "\n".join(f"[{t//60:02d}:{t%60:02d}] {x}" for t, x in lines)
for l in txt.splitlines(): _log(l)
secs = time.time() - t0
# Benchmark mode: write to the given file only; leave the DB alone.
if out_path is not None:
out_path.write_text(txt, encoding="utf-8")
return secs
# Normal mode: persist transcript file and DB rows, and record which device was used.
(db.out_dir(name) / "transcript.txt").write_text(txt, encoding="utf-8")
db.replace_lines(name, [(t, None, x) for t, x in lines])
db.upsert_recording(name, transcribe_device=used, transcribe_s=secs)
return secs