Files
hpr-intro-stripper/hpr_stripper/detect.py
T
Lee Hanken 815ac0b1df Wire the pre-2015 jingle reference into the main detection path
Previously the vendored references/pre2015_jingle_variant_b.flac only
helped via _sibling_fallback's own DTW fallback, which is scoped to a
narrow +/-2 neighbour radius -- confirmed matches like hpr0908, hpr1117,
and hpr1467 are nowhere near hpr0900 or each other, so they'd never have
been found that way.

Adds detect._check_pre2015_variants: checks every vendored pre-2015
jingle variant directly against the episode being detected (fast
correlation first, DTW chroma matching as the per-variant fallback),
tried before falling back to neighbour-matching. This is the pre-2015
era's main-line reference check now, not just a neighbour-radius
fallback -- the old episodes are this tool's core use case, not an edge
case, and the ones most likely to have no official SRT and no other
usable signal.

Verified directly against real episodes outside any neighbour
relationship: hpr0908/hpr1117/hpr1467 resolve via fast correlation,
hpr0901/hpr0902 (tempo-drifted) via DTW, hpr0898 (confirmed no intro)
correctly finds nothing. hpr0899, previously assumed a non-match from
the old buggy correlation-only approach, now also resolves as a real
match -- consistent with that earlier label having been wrong.
2026-11-22 15:24:54 +00:00

417 lines
20 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. For the intro specifically: synopsis-alignment (sequence-aligning
the transcript against the deterministically-known expected TTS
text for this exact episode, metadata.synopsis_text() -- tolerant
of scattered ASR mis-hearings throughout, not just at phrase
boundaries), falling back to fixed-phrase marker matching
(markers.json) only when there's no expected text to align against.
Tried against *both* the official SRT and the ASR-anchor clips --
wording drift and ASR mis-hearings affect both equally.
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 glob
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 _resolve_intro_end(segments, expected_synopsis, marker_lib, phrase_match_label):
"""Tries synopsis-alignment first (tolerant of scattered ASR
mis-hearings; see markers.find_intro_end_via_synopsis's docstring),
falling back to fixed-phrase matching when there's no expected text
to align against or the alignment itself found nothing confident.
Shared between the official-SRT and ASR-anchor paths, since both can
have the same wording-drift/mis-hearing problems; phrase_match_label
lets each caller keep its own familiar method name for the fallback
case ("official_srt" vs. "asr_anchor")."""
if expected_synopsis:
synopsis_intro_end = markers.find_intro_end_via_synopsis(segments, expected_synopsis, marker_lib)
if synopsis_intro_end is not None:
return synopsis_intro_end, "synopsis_alignment"
phrase_match_end = markers.find_intro_end(segments, marker_lib)
if phrase_match_end is not None:
return phrase_match_end, phrase_match_label
return None, None
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 _best_sibling_estimate(estimates, min_confident_seconds=2):
"""Takes the BEST match found across neighbours, not a median/consensus.
A genuine shared jingle correlates very cleanly (r >= ~0.97, sustained
for several seconds) -- that's strong evidence on its own, not
something that happens by chance. But most immediate neighbours often
do *not* happen to share the exact same jingle variant (found
directly: hpr0400 correlated at ~0 against its three closest
neighbours, 399/401/402, but at a clean 29.25s against 398) -- a
median across a radius-2 neighbourhood then discards the one genuine
match because it's outvoted by neighbours that simply don't share
this episode's specific variant, which isn't evidence of anything,
just a different pairing. Only the weak case (nothing found anywhere
nearby) should be flagged as inconclusive. Returns (value, flag)."""
if not estimates:
return None, None
best = max(estimates)
flag = "no_asr_anchor_and_xcorr_inconclusive" if best < min_confident_seconds else None
return best, flag
def _pre2015_variant_paths():
"""Every vendored pre-2015 jingle variant, e.g.
references/pre2015_jingle_variant_b.flac -- there's only one so far,
but the naming is deliberately open-ended so more can be added the
same way they were found (see docs/DESIGN.md)."""
return sorted(glob.glob(os.path.join(config.REFERENCES_DIR, "pre2015_jingle_variant_*.flac")))
def _check_pre2015_variants(audio_path):
"""Checks audio_path's opening against every vendored pre-2015 jingle
variant: fast correlation first (cheap, catches an exact/near-exact
copy), falling back to DTW chroma matching per variant (tried only if
correlation found nothing for that variant -- see
audio.dtw_chroma_match's docstring for why fixed-lag correlation alone
isn't enough here). This is the pre-2015 era's main-line reference
check, not just a neighbour-radius fallback -- the old episodes are
this tool's core use case, and they're the ones most likely to have no
official SRT and no other usable signal, so this needs to work for any
episode, not just ones lucky enough to have a same-variant neighbour
within _sibling_fallback's small search radius.
Returns (intro_end_seconds, method_label) for the first variant that
matches, or (None, None) if none do."""
for variant_path in _pre2015_variant_paths():
variant_name = os.path.splitext(os.path.basename(variant_path))[0]
try:
xcorr = audio.reference_prefix_match_seconds(audio_path, variant_path)
except Exception:
xcorr = None
if xcorr and xcorr > 2:
return xcorr, f"pre2015_reference_xcorr:{variant_name}"
try:
dtw_result = audio.dtw_chroma_match(variant_path, audio_path)
except Exception:
dtw_result = None
if dtw_result is not None:
cost, end_seconds = dtw_result
if cost <= config.DTW_MATCH_THRESHOLD:
return end_seconds, f"pre2015_reference_dtw:{variant_name}"
return None, None
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)
estimate = audio.leading_match_seconds(corrs, win)
if estimate < 2:
# Fixed-lag correlation found nothing, but that's not
# proof the two don't share a jingle -- found directly
# on hpr0901/hpr0902 vs hpr0900's confirmed jingle:
# never correlated above ~0.3-0.4 at any single lag or
# speed ratio, because the real match has internal
# tempo variation no fixed alignment can follow. DTW
# isn't defeated by that (see audio.dtw_chroma_match);
# it's an optional check (returns None if librosa
# isn't installed), tried only as a last resort here
# since it's much more expensive than correlation.
# neighbour_path is the reference here, audio_path the
# candidate -- dtw_chroma_match's end_seconds is always
# in the *candidate*'s timeline, and it's audio_path's
# intro_end we need, not the neighbour's.
dtw_result = audio.dtw_chroma_match(neighbour_path, audio_path)
if dtw_result is not None:
cost, end_seconds = dtw_result
if cost <= config.DTW_MATCH_THRESHOLD:
estimate = end_seconds
estimates.append(estimate)
except Exception:
continue
best, flag = _best_sibling_estimate(estimates)
return best, 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
expected_synopsis = metadata.synopsis_text(conn, ep_id)
if official_segments is not None:
intro_end, intro_source = _resolve_intro_end(
official_segments, expected_synopsis, marker_lib, phrase_match_label="official_srt"
)
if intro_source == "synopsis_alignment":
intro_source = "official_srt+synopsis_alignment"
outro_start = markers.find_outro_start(official_segments, 0.0, marker_lib)
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:
intro_end, intro_source = _resolve_intro_end(
head_segments, expected_synopsis, marker_lib, phrase_match_label="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:
variant_end, variant_method = _check_pre2015_variants(audio_path)
if variant_end is not None:
result.intro_end, result.intro_method = variant_end, variant_method
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"
)
# Several of the signals above compute timestamps via float arithmetic
# on sample counts/sample rates (e.g. duration - some_xcorr_offset),
# which produces values like 1807.7893962..., meaningless past
# hundredths of a second given the underlying windowing/segment
# granularity. Round once here rather than at every call site.
for field in ("duration_sec", "intro_end", "outro_start"):
value = getattr(result, field)
if value is not None:
setattr(result, field, round(value, 2))
return result