Files
hpr-intro-stripper/hpr_stripper/detect.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

294 lines
14 KiB
Python

"""
The layered cut-point detector. Each episode gets whichever signal
actually works for it, tried cheapest/most-certain first, with a record of
which one was used -- see docs/DESIGN.md, "Cut-point detection strategy".
1. Official SRT, when present and non-empty.
2. Metadata-duration arithmetic, as a cross-check (modern era only).
3. ASR-anchor phrase matching on short clips (the tested fallback).
4. Cross-correlation against the vendored reference clips / a sibling
episode, used both as a primary signal (pre-TTS era, and the outro in
every era) and as an anomaly flag (e.g. shows with their own bonus
intro music, which must never be touched -- see Linux Inlaws in
docs/DESIGN.md).
A marker match or an official SRT result is never accepted blindly: it is
always cross-checked against whichever reference-correlation/metadata
signal is also available, and a disagreement between them is surfaced as
a flag rather than silently resolved in either direction.
Nothing here ever guesses: an episode with no usable signal is flagged for
manual review, never given a plausible-looking wrong answer.
"""
import os
from dataclasses import dataclass
from typing import Optional
from . import audio, config, fetch, markers, metadata, srt
DISAGREEMENT_THRESHOLD_SECONDS = 10
MIN_CONFIDENT_XCORR_SECONDS = 5
@dataclass
class DetectionResult:
episode: int
duration_sec: Optional[float] = None
intro_end: Optional[float] = None
intro_method: str = "none"
intro_flag: Optional[str] = None
outro_start: Optional[float] = None
outro_method: str = "none"
outro_flag: Optional[str] = None
license: Optional[str] = None
license_flag: Optional[str] = None
error: Optional[str] = None
def _add_flag(result_field_name, result, text):
existing = getattr(result, result_field_name)
setattr(result, result_field_name, text if not existing else f"{existing}; {text}")
def _try_official_srt(ep_id, cache_dir):
path = fetch.fetch_official_srt(ep_id, cache_dir)
if path is None:
return None
segments = srt.parse_file(path)
if not segments:
return None
return segments
def _asr_on_clips(audio_path, episode_duration, settings):
tmp_dir = os.path.join(settings.cache_dir, "tmp")
os.makedirs(tmp_dir, exist_ok=True)
ep_base = os.path.splitext(os.path.basename(audio_path))[0]
head_wav = os.path.join(tmp_dir, f"{ep_base}_head.wav")
tail_wav = os.path.join(tmp_dir, f"{ep_base}_tail.wav")
tail_start = max(0, episode_duration - settings.tail_clip_seconds)
try:
audio.extract_clip(audio_path, head_wav, 0, min(settings.head_clip_seconds, episode_duration))
audio.extract_clip(audio_path, tail_wav, tail_start, None)
from . import asr
head_segments = asr.transcribe_clip(head_wav, engine=settings.asr_engine,
model=settings.asr_model, device=settings.asr_device)
tail_segments = asr.transcribe_clip(tail_wav, engine=settings.asr_engine,
model=settings.asr_model, device=settings.asr_device)
return head_segments, tail_segments, tail_start
finally:
for p in (head_wav, tail_wav):
if os.path.exists(p):
os.remove(p)
def _fetch_neighbour_audio(ep_id, cache_dir, settings, radius=2):
"""Only called lazily, when every cheaper signal has failed for this
episode -- not pre-fetched for every episode in a batch, to avoid
multiplying bandwidth use for a secondary signal most episodes never
need."""
paths = []
for offset in range(1, radius + 1):
for neighbour_id in (ep_id - offset, ep_id + offset):
if neighbour_id < 1:
continue
try:
path = fetch.fetch_audio(neighbour_id, cache_dir, settings.audio_format_preference)
except Exception:
path = None
if path:
paths.append(path)
return paths
def _sibling_fallback(audio_path, duration, ep_id, cache_dir, settings, neighbour_audio_paths, suffix):
"""Shared by both the intro and outro sibling-correlation fallback --
they're symmetric except for which end of the clip is compared."""
neighbour_audio_paths = (
neighbour_audio_paths if neighbour_audio_paths is not None
else _fetch_neighbour_audio(ep_id, cache_dir, settings)
)
estimates = []
for neighbour_path in neighbour_audio_paths:
try:
if suffix:
neighbour_duration = audio.duration_seconds(neighbour_path)
estimates.append(audio.sibling_suffix_match_seconds(
audio_path, duration, neighbour_path, neighbour_duration))
else:
a = audio.load_pcm_f32(audio_path, 0, 60)
b = audio.load_pcm_f32(neighbour_path, 0, 60)
corrs, win = audio.windowed_corr(a, b)
estimates.append(audio.leading_match_seconds(corrs, win))
except Exception:
continue
if not estimates:
return None, None, neighbour_audio_paths
median = sorted(estimates)[len(estimates) // 2]
spread = max(estimates) - min(estimates) if len(estimates) > 1 else 0
flag = "no_asr_anchor_and_xcorr_inconclusive" if (median < 2 or spread > median) else None
return median, flag, neighbour_audio_paths
def detect(ep_id, cache_dir, settings, neighbour_audio_paths=None):
"""Runs the full layered pipeline for one episode. `settings` is a
config.Settings. `neighbour_audio_paths` can be supplied to skip the
automatic lazy fetch below (useful for tests); normally left as None
and only fetched if every cheaper signal fails."""
result = DetectionResult(episode=ep_id)
conn = metadata.connect(cache_dir)
meta = metadata.get_episode(conn, ep_id)
if meta is None:
result.error = "episode not found in metadata"
return result
result.license = meta["license"]
if meta["license"] in config.NO_DERIVATIVES_LICENSES and not settings.allow_no_derivatives:
result.license_flag = (
f"{meta['license']} forbids derivative redistribution without permission; "
"cut points may still be shown, but trimming is refused by default "
"(pass allow_no_derivatives to override)."
)
audio_path = fetch.fetch_audio(ep_id, cache_dir, settings.audio_format_preference)
if audio_path is None:
result.error = "audio unavailable"
return result
duration = audio.duration_seconds(audio_path)
result.duration_sec = duration
marker_lib = markers.load_markers()
# --- Layer 1: official SRT -----------------------------------------
official_segments = _try_official_srt(ep_id, cache_dir)
intro_end = outro_start = None
intro_source = outro_source = None
if official_segments is not None:
intro_end = markers.find_intro_end(official_segments, marker_lib)
outro_start = markers.find_outro_start(official_segments, 0.0, marker_lib)
if intro_end is not None:
intro_source = "official_srt"
if outro_start is not None:
outro_source = "official_srt"
# --- Layer 3: ASR-anchor on short clips -----------------------------
# Run whenever the official SRT didn't give us *both* answers -- a
# present-but-unhelpful SRT (wrong language, unrecognized wording)
# must not silently suppress this fallback for whichever side it
# failed to resolve.
if intro_end is None or outro_start is None:
head_segments, tail_segments, tail_offset = _asr_on_clips(audio_path, duration, settings)
if intro_end is None:
asr_intro_end = markers.find_intro_end(head_segments, marker_lib)
if asr_intro_end is not None:
intro_end, intro_source = asr_intro_end, "asr_anchor"
if outro_start is None:
asr_outro_start = markers.find_outro_start(tail_segments, tail_offset, marker_lib)
if asr_outro_start is not None:
outro_start, outro_source = asr_outro_start, "asr_anchor"
# --- Layer 4a: reference-asset correlation (outro) ------------------
outro_ref_path = os.path.join(config.REFERENCES_DIR, "outro.flac")
outro_xcorr = None
if os.path.exists(outro_ref_path):
try:
outro_xcorr = audio.reference_suffix_match_seconds(audio_path, duration, outro_ref_path)
except Exception:
outro_xcorr = None
outro_xcorr_start = (duration - outro_xcorr) if outro_xcorr else None
if outro_start is not None:
# Sanity-check the marker-based result against the independent
# reference-correlation signal rather than trusting it blindly.
if (outro_xcorr and outro_xcorr >= MIN_CONFIDENT_XCORR_SECONDS
and abs(outro_xcorr_start - outro_start) > DISAGREEMENT_THRESHOLD_SECONDS):
_add_flag("outro_flag", result,
f"reference_xcorr disagrees with {outro_source} "
f"({outro_xcorr_start:.1f}s vs {outro_start:.1f}s)")
result.outro_start, result.outro_method = outro_start, outro_source
elif outro_xcorr and outro_xcorr > 2:
result.outro_start, result.outro_method = outro_xcorr_start, "reference_xcorr"
else:
median, flag, neighbour_audio_paths = _sibling_fallback(
audio_path, duration, ep_id, cache_dir, settings, neighbour_audio_paths, suffix=True)
if median is not None:
result.outro_start, result.outro_method = duration - median, "sibling_xcorr_fallback"
if flag:
result.outro_flag = flag
else:
result.outro_method = "none"
result.outro_flag = "no_signal"
# --- Layer 4b: reference-asset correlation (intro music bed) -------
theme_ref_path = os.path.join(config.REFERENCES_DIR, "theme.flac")
theme_xcorr = None
if os.path.exists(theme_ref_path):
try:
theme_xcorr = audio.reference_prefix_match_seconds(audio_path, theme_ref_path)
except Exception:
theme_xcorr = None
if intro_end is not None:
result.intro_end, result.intro_method = intro_end, intro_source
if theme_xcorr and theme_xcorr > result.intro_end + 1:
# The theme bed can run a little past the recognized speech in
# short-text episodes (sox -m mixes to the longer of its two
# inputs) -- trust the floor it sets rather than cutting into
# the tail of the music bed.
result.intro_end = theme_xcorr
result.intro_method = f"{intro_source}+reference_xcorr_floor"
# Deliberately NOT flagging the opposite case (theme_xcorr well
# *shorter* than the marker-based boundary) as a disagreement: a
# leading-run correlation against theme.flac predictably drops
# once the TTS speech starts masking it (the mix is additive, not
# sequential -- see docs/DESIGN.md), even while the theme is still
# legitimately present underneath. Confirmed empirically on
# hpr4775: theme_xcorr read 6.2s while the real, verified boundary
# was 27.3s -- a real mixing artefact, not evidence the marker
# match was wrong. Treating that as a "disagreement" would flag
# nearly every modern episode for nothing. (The leading-run
# correlation also can't bridge a genuine silence gap between the
# spoken block and the host's own greeting, which is a real, still
# -open limitation -- see "Edge cases & known limitations" in
# docs/DESIGN.md.)
elif theme_xcorr and theme_xcorr > 2:
result.intro_end, result.intro_method = theme_xcorr, "reference_xcorr"
else:
median, flag, neighbour_audio_paths = _sibling_fallback(
audio_path, duration, ep_id, cache_dir, settings, neighbour_audio_paths, suffix=False)
if median is not None:
result.intro_end, result.intro_method = median, "sibling_xcorr_fallback"
if flag:
result.intro_flag = flag
else:
result.intro_method = "none"
result.intro_flag = "no_signal"
# --- Layer 2: metadata-duration arithmetic --------------------------
# eps.duration appears to hold the raw submitted (pre-intro/outro)
# length for modern episodes (validated in docs/DESIGN.md against
# three real test episodes, within a few seconds; known NOT to hold
# for older ones). Used here as a cross-check against whatever
# intro_end/outro_start were already found, and -- only as a last
# resort, clearly flagged -- as a source in its own right when
# nothing else produced an intro_end at all.
raw_duration = meta.get("duration")
if raw_duration and result.outro_start is not None and not result.outro_flag:
arithmetic_intro_end = result.outro_start - raw_duration
plausible = 0 <= arithmetic_intro_end <= duration / 2
if plausible:
if result.intro_method not in ("none",) and result.intro_end is not None:
if abs(arithmetic_intro_end - result.intro_end) > DISAGREEMENT_THRESHOLD_SECONDS:
_add_flag("intro_flag", result,
f"metadata_arithmetic disagrees with {result.intro_method} "
f"({arithmetic_intro_end:.1f}s vs {result.intro_end:.1f}s)")
elif result.intro_method == "none":
result.intro_end = arithmetic_intro_end
result.intro_method = "metadata_arithmetic"
result.intro_flag = (
"metadata_arithmetic is a cross-check signal, not independently "
"validated for this episode's era -- verify before trusting"
)
return result