Files
hpr-intro-stripper/hpr_stripper/asr.py
T
Lee Hanken 9917320640 hpr-intro-stripper: layered intro/outro cut-point detection and trimming
Fetches HPR's own metadata, audio, and official transcripts live; falls
back to local speech recognition (tiny model, matching HPR's own
hpr-get-and-transcribe.bash tooling) only when needed, and to
correlation against vendored reference clips or sibling episodes
otherwise. License-aware, resumable, and never guesses -- flags
anything it isn't confident about for manual review rather than
producing a plausible-looking wrong cut.
2026-11-22 10:36:07 +00:00

62 lines
2.4 KiB
Python

"""
Pluggable ASR backend -- only ever invoked on short clips (config.
HEAD_CLIP_SECONDS / TAIL_CLIP_SECONDS), never a whole episode, and only
when neither the official SRT nor the metadata-arithmetic cross-check gave
a usable answer.
Default is plain `openai-whisper --model tiny`: not picked for being
"lighter" than alternatives, but for consistency with tooling already in
people's workflows -- it's exactly what HPR's own
hpr-get-and-transcribe.bash already runs on every raw submission. Swap
engines by passing a different `engine` to transcribe_clip(); a
whisper.cpp backend can be added the same way without touching callers.
"""
import json
import os
import subprocess
import tempfile
from . import config
def transcribe_clip(wav_path, engine=None, model=None, device=None):
"""Returns a list of (text, start, end) segments, or [] if the engine
isn't available / fails -- callers treat that as 'no ASR signal',
never an error that stops the pipeline."""
engine = engine or config.ASR_ENGINE
model = model or config.ASR_MODEL
device = device or config.ASR_DEVICE
if engine == "openai-whisper":
return _transcribe_openai_whisper(wav_path, model, device)
raise ValueError(f"Unknown ASR engine: {engine!r}")
def _transcribe_openai_whisper(wav_path, model, device):
with tempfile.TemporaryDirectory() as tmp_dir:
cmd = [
"whisper", wav_path,
"--model", model,
"--device", device,
"--output_dir", tmp_dir,
"--output_format", "json",
"--language", "English",
"--fp16", "True" if device == "cuda" else "False",
]
try:
result = subprocess.run(cmd, capture_output=True, text=True)
except OSError:
# whisper isn't installed / not on PATH -- treat exactly like
# any other "this engine isn't available" case, per the
# docstring above, rather than crashing the whole pipeline.
return []
if result.returncode != 0:
return []
base = os.path.splitext(os.path.basename(wav_path))[0]
json_path = os.path.join(tmp_dir, base + ".json")
if not os.path.exists(json_path):
return []
with open(json_path) as f:
data = json.load(f)
return [(seg["text"], seg["start"], seg["end"]) for seg in data.get("segments", [])]