191 lines
6.8 KiB
Python
191 lines
6.8 KiB
Python
"""Whisper transcription: faster-whisper (cuda) or OpenVINO GenAI (npu)."""
|
|
|
|
import gc
|
|
import json
|
|
import subprocess
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import db
|
|
import numpy as np
|
|
|
|
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(message):
|
|
try:
|
|
from prefect import get_run_logger
|
|
|
|
get_run_logger().info(message)
|
|
except Exception:
|
|
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, pending, start, end, previous_text, repeat_count = [], [], 0, 0, None, 0
|
|
|
|
def flush():
|
|
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.
|
|
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 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 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):
|
|
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; 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)
|
|
kwargs = (
|
|
{"hotwords": " ".join(glossary[:20]), "condition_on_previous_text": False}
|
|
if glossary
|
|
else {}
|
|
)
|
|
try:
|
|
# Italian forced; VAD (voice activity detection) skips silence.
|
|
segments, info = whisper_model.transcribe(
|
|
str(audio), language="it", vad_filter=True, **kwargs
|
|
)
|
|
collected = []
|
|
# Keep each segment, reporting progress by its end time.
|
|
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 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
|
|
|
|
# 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 = 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 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"
|
|
glossary_path = db.out_dir(name) / "glossary.json"
|
|
# Glossary from shots (used as whisper hotwords).
|
|
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)")
|
|
segments, used_device = _npu(audio), "npu"
|
|
else:
|
|
|
|
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(segments)
|
|
# Format as [mm:ss] text, the format diarize.py parses.
|
|
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(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(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
|