Apply ruff lint and rename cryptic identifiers to readable names
This commit is contained in:
+125
-54
@@ -1,8 +1,13 @@
|
||||
"""Whisper transcription: faster-whisper (cuda) or OpenVINO GenAI (npu)."""
|
||||
import gc, json, subprocess, time
|
||||
|
||||
import gc
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
|
||||
import db
|
||||
import numpy as np
|
||||
|
||||
HERE = Path(__file__).parent
|
||||
# Pre-converted OpenVINO Whisper model; downloaded on first NPU use.
|
||||
@@ -10,110 +15,176 @@ NPU_MODEL_DIR = HERE / "models" / "whisper-large-v3-turbo-ov"
|
||||
|
||||
|
||||
# Log via Prefect when inside a flow; print otherwise.
|
||||
def _log(msg):
|
||||
def _log(message):
|
||||
try:
|
||||
from prefect import get_run_logger
|
||||
get_run_logger().info(msg)
|
||||
|
||||
get_run_logger().info(message)
|
||||
except Exception:
|
||||
print(msg, flush=True)
|
||||
print(message, 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
|
||||
lines, pending, start, end, previous_text, repeat_count = [], [], 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
|
||||
if pending:
|
||||
lines.append((int(start), " ".join(pending)))
|
||||
pending.clear()
|
||||
|
||||
for seg_start, seg_end, raw_text in segs:
|
||||
text = raw_text.strip()
|
||||
if not text:
|
||||
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
|
||||
repeat_count = repeat_count + 1 if text == previous_text else 0
|
||||
previous_text = text
|
||||
if repeat_count >= 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
|
||||
if pending and seg_start - end > 1:
|
||||
flush()
|
||||
if not pending:
|
||||
start = seg_start
|
||||
pending.append(text)
|
||||
end = seg_end
|
||||
# End the line at sentence punctuation, or after 12 s.
|
||||
if t.endswith((".", "?", "!", "…")) or end - start > 12: flush()
|
||||
if text.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)
|
||||
pcm_bytes = subprocess.run(
|
||||
[
|
||||
"ffmpeg",
|
||||
"-v",
|
||||
"error",
|
||||
"-i",
|
||||
str(path),
|
||||
"-vn",
|
||||
"-ac",
|
||||
"1",
|
||||
"-ar",
|
||||
"16000",
|
||||
"-f",
|
||||
"f32le",
|
||||
"-",
|
||||
],
|
||||
capture_output=True,
|
||||
check=True,
|
||||
).stdout
|
||||
return np.frombuffer(pcm_bytes, 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)
|
||||
|
||||
# Load the model; used_device is 'cuda' or 'cpu'.
|
||||
whisper_model, used_device = 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 {}
|
||||
kwargs = (
|
||||
{"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 = []
|
||||
segments, info = whisper_model.transcribe(
|
||||
str(audio), language="it", vad_filter=True, **kwargs
|
||||
)
|
||||
collected = []
|
||||
# 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
|
||||
for segment in segments:
|
||||
collected.append((segment.start, segment.end, segment.text))
|
||||
tick(segment.end, info.duration)
|
||||
return collected, used_device
|
||||
finally:
|
||||
# Free the model (VRAM) before returning, even on error.
|
||||
del m; gc.collect()
|
||||
del whisper_model
|
||||
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
|
||||
import openvino_genai
|
||||
|
||||
# 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)
|
||||
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)
|
||||
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)
|
||||
pipe = openvino_genai.WhisperPipeline(str(NPU_MODEL_DIR), "NPU")
|
||||
result = 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}")
|
||||
if not result.chunks:
|
||||
raise RuntimeError("no chunks returned")
|
||||
return [(chunk.start_ts, chunk.end_ts, chunk.text) for chunk in result.chunks]
|
||||
except Exception as error:
|
||||
raise RuntimeError(f"NPU failed: {error!r}") from error
|
||||
|
||||
|
||||
# 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_path = 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()
|
||||
glossary = (
|
||||
json.loads(glossary_path.read_text(encoding="utf-8")) if glossary_path.exists() else []
|
||||
)
|
||||
start_time = 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"
|
||||
segments, used_device = _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)
|
||||
|
||||
def tick(done, total):
|
||||
return db.tick(
|
||||
name, round(done), round(total), f"{done / 60:.0f} di {total / 60:.0f} min di audio"
|
||||
)
|
||||
|
||||
segments, used_device = _cuda(audio, model, glossary, tick)
|
||||
# Group segments into timestamped lines.
|
||||
lines = aggregate(segs)
|
||||
lines = aggregate(segments)
|
||||
# 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
|
||||
transcript_text = "\n".join(
|
||||
f"[{time_s // 60:02d}:{time_s % 60:02d}] {text}" for time_s, text in lines
|
||||
)
|
||||
for line in transcript_text.splitlines():
|
||||
_log(line)
|
||||
elapsed_s = time.time() - start_time
|
||||
# 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
|
||||
out_path.write_text(transcript_text, encoding="utf-8")
|
||||
return elapsed_s
|
||||
# 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
|
||||
(db.out_dir(name) / "transcript.txt").write_text(transcript_text, encoding="utf-8")
|
||||
db.replace_lines(name, [(time_s, None, text) for time_s, text in lines])
|
||||
db.upsert_recording(name, transcribe_device=used_device, transcribe_s=elapsed_s)
|
||||
return elapsed_s
|
||||
|
||||
Reference in New Issue
Block a user