98 lines
3.9 KiB
Python
98 lines
3.9 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
|
|
NPU_MODEL_DIR = HERE / "models" / "whisper-large-v3-turbo-ov"
|
|
|
|
|
|
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
|
|
rep = rep + 1 if t == last else 0; last = t
|
|
if rep >= 2: continue
|
|
if buf and s - end > 1: flush()
|
|
if not buf: start = s
|
|
buf.append(t); end = e
|
|
if t.endswith((".", "?", "!", "…")) or end - start > 12: flush()
|
|
flush()
|
|
return lines
|
|
|
|
|
|
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)
|
|
|
|
|
|
def _cuda(audio, model, glossary, tick=lambda done, total: None):
|
|
import common
|
|
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:
|
|
segs, info = m.transcribe(str(audio), language="it", vad_filter=True, **kw)
|
|
out = []
|
|
for s in segs: out.append((s.start, s.end, s.text)); tick(s.end, info.duration)
|
|
return out, dev
|
|
finally:
|
|
del m; gc.collect()
|
|
|
|
|
|
def _npu(audio):
|
|
try:
|
|
import openvino_genai as ov
|
|
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)
|
|
pipe = ov.WhisperPipeline(str(NPU_MODEL_DIR), "NPU")
|
|
res = pipe.generate(_decode(audio).tolist(), language="<|it|>", task="transcribe", return_timestamps=True)
|
|
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}")
|
|
|
|
|
|
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 = json.loads(gl.read_text(encoding="utf-8")) if gl.exists() else []
|
|
t0 = time.time()
|
|
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)
|
|
lines = aggregate(segs)
|
|
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
|
|
if out_path is not None:
|
|
out_path.write_text(txt, encoding="utf-8")
|
|
return secs
|
|
(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
|