Files
hpr-intro-stripper/docs/DESIGN.md
T
Lee Hanken 17dec27955 Replace fixed-phrase marker matching with synopsis-alignment as the primary intro method
markers.find_intro_end_via_synopsis sequence-aligns the ASR transcript
against metadata.synopsis_text()'s deterministic reconstruction of the
expected per-episode announcement text (the say.php reproduction from
earlier), rather than matching against a fixed phrase list. This was a
direct response to the pattern across the last several fixes: each one
patched a single new mis-hearing variant, with no ceiling on how many
exist. Sequence alignment tolerates scattered word-level ASR errors
throughout the transcript, not just at phrase boundaries someone thought
to special-case.

Applied to both the official-SRT and ASR-anchor paths (_resolve_intro_end
in detect.py), since wording drift and ASR mis-hearings affect both.
Falls back to the existing fixed-phrase matching when there's no
expected text to align against, and still defers to it entirely for the
sponsor-ad-read continuation, which has no deterministic per-episode
text of its own.

Live-verified: hpr2157 moved from 15.1s (old marker match) to 30.6s;
hpr3237 to 34.7s; hpr3009 (Linux Inlaws) extended further but stayed
correctly flagged rather than silently trusted; hpr4775 now resolves via
official_srt+synopsis_alignment+reference_xcorr_floor, composing all
three recent fixes. hpr1892 correctly still returns None -- its garbling
is concentrated in the first ~17 words, with no confident anchor near
the start, which the leading-anchor check is specifically designed to
catch rather than trust a coincidental later match.

Also fixes a real bug found while validating this: the sponsor-ad-read
continuation was filtering segments by end time instead of start time,
so a segment that merely ended near the anchor but started before it
broke the extension chain immediately, discarding a real extension
(caught on hpr2157's own sponsor read).

New test file test_synopsis_alignment.py (8 tests), plus two tests
locking in the earlier narrowly-scoped fuzzy-threshold exception for the
station-name marker (validated against both the real mis-hearing and the
original hpr0500 regression case before being enabled).
2026-11-22 12:24:56 +00:00

40 KiB
Raw Blame History

Design

Detailed technical background for hpr-intro-stripper. For usage, see the top-level README.md.

Goals & non-goals

Goals:

  • Given an HPR episode number (or a range), produce the "inner" audio — the host's originally submitted recording, with HPR's own added intro and outro removed — individually or in batch.
  • Work unattended against the live HPR archive: fetch whatever metadata/audio/transcript it needs itself, rather than assuming a pre-populated local mirror.
  • Run on modest hardware. No step requires a GPU or a specific speech- recognition setup. Dependency weight is comparable to a repo that says "install these packages from your distro" — ffmpeg, Python 3, numpy, sqlite3, awk, optionally one CPU ASR tool — not a PyTorch/CUDA stack as a hard requirement.
  • Be safe by default: never silently produce or redistribute a trimmed derivative of a No-Derivatives-licensed episode; never touch audio the detector isn't confident about; always leave an audit trail (what was cut, by which method, with what confidence) alongside trimmed output.

Non-goals:

  • Not a bulk mirror of HPR's audio. No episode audio or bulk transcript corpus lives in this repo — only code, a small marker-phrase library, and a per-episode cut-point cache (gitignored).
  • Not a replacement for HPR's own transcription pipeline. Where HPR already publishes a transcript/SRT, this tool uses it rather than re-deriving it.
  • Not an attempt to perfectly restore the exact original submitted file byte-for-byte — the goal is the host's spoken content, cleanly bounded, not bit-identical reconstruction.

Why this is harder than "just trim N seconds"

The intro/outro have never been one fixed-length clip across HPR's 18-year history, and the boundary moved more than once:

  • Pre-~2015 (roughly episode <1700): no spoken announcement at all — just a shared, unchanging music jingle before the host's own cold open. Confirmed by cross-correlating two episodes' openings sample-for-sample: hpr0500 vs hpr0600 matched at r≥0.99 for exactly 15.0s, then diverged sharply. This era is the one case where "fixed timing" really is trivial, if you know the length.
  • ~2015 onward: HPR began auto-generating a spoken per-episode metadata announcement (episode number, date, title, series, flag, summary) read before the host's own greeting. Its length is not fixed — it tracks how much text there is to read — and its exact wording drifted at least twice more. ASR testing across 9 real episodes (2008–2025) measured intro lengths from 13s to 48s depending on title/summary length.
  • The outro turns out to be fixed after all — but only once you know which asset is current (see below): a single unchanging 40.0-second clip in the current era, not something to measure per episode, but it has presumably changed at least once already (branding, hosting-sponsor wording) and will again.

So "trim N seconds" is right for the outro (per era) and wrong for the intro (always, by construction) — any workable tool has to detect the intro boundary per-episode, and detect the outro's current fixed length rather than hard-coding one.

What HPR's own pipeline already does

Read directly from repo.anhonesthost.net/HPR/hpr-tools (cloned locally and read, not guessed):

  • workflow/hpr-get-and-transcribe.bash runs, on each newly submitted raw episode file, before intro/outro are ever added:

    whisper --output_format srt --model tiny --language en --output_dir "${show_dir}" "${this_media}"
    

    This is HPR's own standard: the smallest Whisper model, on the raw submission, as routine janitor tooling — strong precedent for what this project assumes is a reasonable dependency to ask of a contributor's machine. This repo's own ASR fallback matches it exactly (see "ASR dependency strategy" below).

  • workflow/hpr-process_episode.bash assembles the final published SRT by concatenating intro.srt (template) + the body SRT from the step above (time-shifted by the real rendered intro duration, read via mediainfo) + outro.srt (time-shifted again). The exact cut points are computed server-side and deterministic — they're just not published as a separate field anywhere.

  • workflow/intro.srt (vendored into references/intro.srt) is a 5-line template with placeholders for: episode number + date, title, series, flag + license, summary. Nominal total length 27.32s — but this is a default template; the real TTS-rendered audio varies with actual text length (matches the 13–48s range measured by ASR).

  • workflow/outro.srt + workflow/outro.flac (vendored into references/) are completely static — no per-episode substitution at all. outro.flac measured via ffprobe at exactly 40.0 seconds. theme.flac (the intro music bed, vendored alongside it) measured at 40.52 seconds — the raw bed length available to loop/crop under the TTS speech, not the per-episode intro duration.

  • hpr_hub/cms/say.php builds the exact spoken announcement text — the synopsis field — by plain string concatenation from the eps, hosts, licenses, and miniseries tables (the same schema the fetched hpr.sql gives this tool). hpr-process_episode.bash's create_tts_summary() then feeds that text verbatim into piper --model en_US-ljspeech-high.onnx with no further processing, and generate_intro() mixes the resulting speech with theme.flac additively (sox -m, a mix, not a sequential splice) — so the real intro audio is theme-plus-speech layered together for most of its length, not theme-then-speech.

Implication: for the current era, the outro is not something to detect per episode at all — it's a known, fixed-length clip, safe to match directly against the vendored outro.flac. The intro is the only part that genuinely requires per-episode detection, though the vendored theme.flac still gives a useful independent boundary signal (see below).

A documentation/code discrepancy worth noting plainly: hpr_documentation/branding.md states the intro "will always be 30 seconds long and in some edge cases may be slightly longer." The actual generation code enforces no such cap (create_tts_summary() has no length limit; generate_intro()'s sox -m just takes the longer of its two inputs), and empirical ASR measurements (13–48s) match the code's behaviour, not the documented policy. Treated here as a sign the docs lag the implementation in places, not a sign the measurements are wrong.

Data acquisition

Audio and sibling files. Confirmed working endpoint (verified directly, not guessed):

https://hub.hackerpublicradio.org/ccdn.php?filename=/eps/hprNNNN/hprNNNN.{mp3,ogg,opus,txt,srt,json}

Episode number zero-padded to 4 digits, directory and filename both hprNNNN. HPR publishes every episode in mp3, ogg, and opus simultaneously — format is a configurable preference with fallback (default order: opus → ogg → mp3), never hardcoded, since ffmpeg/ ffprobe handle all three natively at no extra dependency cost.

Design rule, not just a bug workaround: never hardcode a storage backend host. The proxy has been observed redirecting to a DigitalOcean Spaces bucket (*.digitaloceanspaces.com) — and hitting that bucket directly can return an AccessDenied XML error even for files the proxy serves fine (confirmed: hpr0400, hpr1000). HPR's hosting is explicitly designed to be swappable (see the CCDN architecture doc's own multi-origin, DNS-round-robin design), so a URL seen once in a redirect or an error message is an observation, never a contract. This tool only ever constructs URLs against ccdn.php and follows whatever it redirects to; it never remembers or reconstructs a backend host itself. AccessDenied, 403, 404, and a 200-with-empty-body are all treated as the same outcome — "not available right now, fall back to the next signal" — never special-cased per status code.

No public bulk endpoint exists. HPR/hpr_documentation/ccdn/ccdn_architecture.md documents HPR's CCDN as a private origin-to-mirror-node design: volunteer-run edge nodes rsync over SSH from a private origin, not open to the public, with directory browsing explicitly disabled. The practical approach is a polite, resumable, per-episode HTTP fetch loop — not an attempt to find or build a bulk-sync path. Concretely: every request to HPR's servers goes through a single gate (fetch._wait_for_politeness_gap()) enforcing a minimum config.REQUEST_DELAY_SECONDS (default 0.5s) between requests, regardless of which function issued them, and fetch_audio/fetch_official_srt skip the network entirely once a file is cached. Retry-with-backoff on a transient failure is not implemented — a failed request is currently treated the same as "not available," falling through to the next detection signal rather than being retried.

Official transcripts/SRT exist, but coverage is patchy — confirmed by direct testing, not assumed. Even episodes from 2024–2025 sometimes return a genuine transcript, sometimes a 200-with-empty-body placeholder, and older ones sometimes 404 or 403. The tool always fetches and checks actual byte content, never infers availability from the episode page or from era alone.

Metadata. Fetched from the canonical source — https://www.hackerpublicradio.org/hpr.sql — the exact URL hpr_generator's own utils/lib_utils.sh (download_hpr_sql) pulls from, converted to SQLite with the same vendored mysql2sqlite AWK script HPR's own update-hpr.sh uses. This repo ships no snapshot and assumes no pre-existing local copy; a bootstrap step downloads the current dump and refreshes it periodically, so every run reflects the live database.

Cut-point detection strategy

Four layered signals, tried in order, cheapest/most-certain first. Every episode gets whichever signal actually works for it, plus a record of which one was used. A code-review pass found that an earlier version of this document described this cross-checking as already real when it wasn't yet implemented; hpr_stripper/detect.py now actually does what's described below, not just the parts that were easy.

  1. Official SRT, when present and non-empty. Gives the boundary for free — but a present SRT that fails to yield an answer for one side (e.g. only the intro marker matches, not the outro) doesn't suppress the ASR-anchor fallback for the side it couldn't resolve; each side is tracked and filled independently. Every accepted result is also sanity-checked against whichever reference-correlation/metadata signal is independently available — a disagreement surfaces as a flag on the result rather than being silently resolved in either direction (see DISAGREEMENT_THRESHOLD_SECONDS in detect.py). Caught a real bug this way during review: see "Era wording drift" under Edge Cases.

  2. Metadata-duration arithmetic, as a cross-check for the modern era. The eps.duration field appears to represent the raw submitted (pre-intro/outro) length — validated against three real test episodes (hpr3700: 882s vs. 880.98s measured; hpr3900: 704s vs. 700.34s; hpr4300: 1105s vs. 1101.7s), all within a few seconds. Does not hold for older episodes (hpr2100: 280s vs. 333.23s measured, a 53s gap) — likely because this exact invariant in hpr-process_episode.bash is itself a newer part of the pipeline. Used only as corroboration for recent episodes, never as sole truth for old ones.

  3. For the intro boundary specifically: synopsis-alignment, now the primary method (markers.find_intro_end_via_synopsis), with fixed-phrase marker matching (hpr_stripper/markers.json) as the fallback. Extracts only the first ~120s and last ~70s via ffmpeg — never the whole episode — transcribes with Whisper, then instead of asking "does this segment contain one of ~25 known phrases," aligns the whole transcript against the deterministically-known expected text for this exact episode (metadata.synopsis_text(), the say.php reproduction from "What HPR's own pipeline already does"), using difflib.SequenceMatcher at the word level.

    This exists because a fixed phrase list breaks on any single ASR mis-hearing of a marker phrase, with no ceiling on how many variants exist — three different ones turned up in one afternoon of testing ("Haka" for "Hacker", "to its" for "today's", "in part" for "is part"). Sequence alignment tolerates scattered word-level errors throughout, not just at phrase boundaries someone thought to special-case: hpr2157's title, host name, and series name are each garbled differently from their real text, and no single phrase marker, literal or fuzzy, could reconstruct the whole picture, but the surrounding boilerplate words still align fine (correctly moved its intro boundary from 15.1s, under the old marker-only approach, to 30.6s). It requires a confirmed anchor near the very start of the transcript, the same anchoring principle as the audio-correlation fix below — hpr1892's transcript is garbled specifically in its first ~17 words, leaving no confident early match at all, and the method correctly declines rather than trusting a match found only deep into the clip. That's an accepted limitation, not a bug: some transcripts are too degraded for any automated method, and should stay flagged for manual review.

    Once the per-episode TTS block is confirmed, the boundary is extended (without needing its own fresh evidence) through whatever markers.json recognizes immediately afterwards — a sponsor ad-read has no deterministic per-episode text of its own to align against, so this is where the marker list is still genuinely needed, not for the episode-specific announcement anymore.

    hpr_stripper/markers.py's fixed-phrase matching remains the fallback for episodes with no reconstructable expected text, and carries its own history of two real false-positive bugs found and fixed while building the original prototype this was ported from (see the docstring for the full story): a too-loose fuzzy match once nearly truncated a host's own sign-off by confusing it with a short outro marker, and a host's organic "this is X and this is Hacker Public Radio" cold open was once briefly mistaken for the start of the TTS announcement. Both are fixed by (a) requiring markers to have ≥5 words before any fuzzy matching applies at all (one exception: a validated ≥4-word/0.88-ratio threshold specifically for the station-name marker, see below), and (b) splitting intro markers into "strong" (exact-substring only, impossible to say by coincidence) vs. "greeting" (can extend an established run, never start one). A later, narrowly-scoped exception to the ≥5-word fuzzy rule was added and empirically validated against that same regression case before being enabled: fuzzy matching the long, distinctive "hacker public radio episode" marker specifically (ratio ≥0.88) catches real mis-hearings like "Haka Public Radio episode" (scores 0.923) while still rejecting the original hpr0500 regression case (scores 0.824) — tested directly against both before shipping, not just assumed safe.

  4. Cross-correlation, used three ways:

    • Against the vendored reference assets (references/theme.flac, references/outro.flac) — the cleanest signal for the current era. outro.flac is the complete rendered outro; correlating it directly against an episode's tail is simpler and more universal than comparing to a sibling episode, and self-detects when HPR changes the asset (correlation quality drops across the board, signalling "go vendor the new one"). theme.flac is only the music bed, additively mixed with speech in the real intro — correlating it still works as a boundary detector (it stays high wherever the theme is actually present underneath the speech, and drops sharply once the bed ends and the host's own raw recording begins), and gives a useful floor: if the theme-correlation run is longer than what the ASR anchor found, the theme bed is still playing past the recognized speech (short-text episodes), and the floor wins.
    • Against a sibling episode, as the primary method for the intro in the pre-~2015 fixed-jingle era (no reference asset exists for that era yet) — e.g. hpr0500 vs hpr0600 matched at r≥0.99 for exactly 15.0s before diverging.
    • As an anomaly flag: when an episode's measured match length against its neighbours is a big outlier, flag it rather than trust it. This is exactly what caught Linux Inlaws correctly in testing — hpr3009 vs. a normal sibling (hpr3010) matched for only 2.5s before diverging. Their extra theme music plays after the standard HPR greeting, as their own content, and must never be touched.

Nothing in this pipeline ever guesses: an episode with no usable signal at all is flagged for manual review (intro_flag / outro_flag in the result), never given a plausible-looking wrong answer.

ASR dependency strategy

Decided: the shipped default is plain openai-whisper --model tiny, not whisper.cpp. Rationale: consistency with tooling already in people's workflows — this is literally what HPR's own hpr-get-and-transcribe.bash already runs — and it's what the original tested prototype already used. whisper.cpp remains a reasonable pluggable alternative for anyone who wants an even smaller footprint (hpr_stripper/asr.py is written as a one-engine-at-a-time dispatch specifically so a second backend can be added without touching callers), but it is not the default.

Real CPU benchmarks (openai-whisper, CPU-only, capped to 4 cores via taskset, on a 90-second clip, on a modern desktop CPU — AMD Ryzen 9 3950X):

Model Wall time
tiny 11.7s
base 23.0s
small 57.0s

A 2016 dual-core laptop would likely run 2–4× slower per the cores-and- clock gap — plausibly 30–50s for tiny — but that's for a 90-second clip, never the whole episode: this design only ever transcribes short head/tail clips, when ASR is needed at all (i.e. when neither the official SRT nor the metadata-arithmetic cross-check gave a usable answer).

License handling

The HPR database has a real licenses table, not one blanket license — confirmed directly from hpr.db:

License Episodes
CC-BY-SA 3,923
CC-BY-NC-SA 772
CC-0 33
CC-BY 8
CC-BY-NC-ND 6
CC-BY-NC 5
CC-BY-ND (listed, 0 currently assigned)
MIT (listed)

The two No-Derivatives variants (CC-BY-ND, CC-BY-NC-ND) legally forbid producing or redistributing a modified/derivative version of the work — which a trimmed audio file is — without separate rightsholder permission. 6 episodes currently carry CC-BY-NC-ND.

Every pipeline run reads the episode's license from metadata and carries it through to the result and the trimmed output's sidecar file. By default, hpr_stripper/trim.py's should_trim() refuses ND-licensed episodes (--force overrides this, not recommended) — detection can still run and show the cut points, but the trim step won't silently produce output for distribution.

This goes further than just the 6 ND episodes. Per hpr_documentation/branding.md, on the "Who?" segment of the intro: "We are required by the CC-BY-SA... license to credit our hosts, so we do." The intro is HPR's actual mechanism for satisfying CC-BY-SA host attribution — so stripping it removes a legally required notice for every CC-BY-SA/CC-BY episode, not only the ND-licensed ones. That's why trim.write_sidecar() always writes a small JSON file alongside trimmed output recording the host, episode number, date, license, and original URL, regardless of which license applies — trimmed audio stays self-documenting if it's ever shared separately from this tool.

Historical/ethos note: HPR dropped the CC-BY-NC license as an option in a 2025 policy change (see hpr_documentation/policies.md) and clarified that contributions default to CC-BY-SA 4.0 unless otherwise stated — the 772 CC-BY-NC-SA / 5 CC-BY-NC episodes are a legacy category, not one expected to keep growing.

Repo structure & pipeline stages

hpr-intro-stripper/
├── README.md              # minimal: usage, requirements, brief how-it-works
├── docs/
│   └── DESIGN.md          # this file
├── references/            # vendored from HPR's own hpr-tools repo (CC0/CC-BY-SA, not this repo's code license)
│   ├── theme.flac
│   ├── outro.flac
│   ├── intro.srt
│   ├── outro.srt
│   ├── mysql2sqlite       # the same AWK converter HPR's own tooling uses
│   └── LICENSE_NOTICE.md
├── hpr_stripper/
│   ├── config.py          # the one place to change defaults
│   ├── markers.json       # versioned, plain-text boilerplate phrase library
│   ├── markers.py         # fuzzy matching against markers.json
│   ├── metadata.py        # canonical hpr.sql fetch + sqlite conversion + queries
│   ├── fetch.py           # audio/transcript/SRT fetch via ccdn.php only
│   ├── srt.py             # minimal SRT parser (stdlib only)
│   ├── audio.py           # ffmpeg/ffprobe wrappers, cross-correlation
│   ├── asr.py             # pluggable ASR backend dispatch
│   ├── detect.py          # the layered detection pipeline
│   ├── ledger.py          # resumable per-episode progress tracking
│   ├── trim.py            # atomic trim + license gating + sidecar metadata
│   └── cli.py             # detect / sweep / random-sample / trim / report
├── tools/
│   └── visualize_clip.sh  # renders a waveform/spectrogram for a clip, for inspecting a cut point directly
└── cache/                 # gitignored: hpr.db, downloaded audio, transcripts, ledger.db, trimmed output

What lives in git: code, the marker-phrase library, the vendored reference assets (small, clearly licensed), and this documentation.

What never lives in git: episode audio, bulk transcripts, the metadata database, and trimmed output — all fetched or produced into cache/ on demand, so cloning the repo stays small regardless of how much of the archive someone has processed.

Config surface: hpr_stripper/config.py — one file selecting the ASR backend/model, audio format preference, fetch/clip sizes, and cache location.

Testing & resumability strategy

Two first-class test modes, not ad hoc spot checks:

  • Random-sample test (cli.py random-sample): picks N episodes at random, stratified across the three known eras (pre-2015, ~2016–2020, ~2020+) so a lucky or unlucky sample can't hide an era-specific regression. Fast, for day-to-day development checks.
  • Full-corpus sweep test (cli.py sweep): runs detection (not trimming) across every episode in the archive. Slow — a real, continuous run of 21 episodes from the hardest category (pre-2015, no official transcript, full ASR + sibling-correlation fallback) averaged 32.1 seconds/episode on the hardware this was developed on; scaled to the full ~4,750-episode archive that's on the order of a day or two of continuous wall-clock time, not weeks, though a weaker CPU or the politeness delay (see "Data acquisition") would push it higher — and explicitly designed to be interrupted.
  • Interrupt/resume was smoke-tested for real, not just unit-tested: a sweep was started, sent a real SIGINT mid-episode, resumed (and confirmed it skipped the already-completed episodes rather than reprocessing them), interrupted again, and resumed to completion. No lost work, no stray subprocesses left running after either interrupt, no corrupted ledger state.

Resumability is a hard requirement, because a half-hour-plus batch run will get interrupted (Ctrl+C, laptop sleep, SSH drop):

  • Idempotent, per-episode units of work. Every stage treats one episode as the atomic unit (ledger.is_done() checked before any work starts).
  • Atomic writes, never partial files. fetch.py and trim.py both write to a .tmp path and os.replace() into place only on success.
  • A persistent progress ledger (hpr_stripper/ledger.py, SQLite): one durable, committed row per episode, written immediately after that episode finishes. Ctrl+C at minute 29 of a 30-minute sweep costs at most the one in-flight episode.
  • Safe to re-run after changing settings. The ledger stamps each row with the marker-library version and ASR engine/model that produced it (config.MARKERS_VERSION); ledger.is_done() only returns true if those still match the current settings, so bumping the marker version or switching ASR models re-processes exactly the episodes affected, not everything.

Fit with HPR's own ethos & principles

Read directly from hpr_documentation (branding.md, policies.md) and from the generation code itself, not inferred:

  • The intro's spoken metadata exists partly for accessibility, not just branding. branding.md: "We started to do it because some of our Visually Impaired users appreciated knowing what show is playing." Stripping it removes a real accessibility aid for listeners who rely on audio cues rather than a visual player UI. This tool is an optional alternate listening format for people who've chosen to opt out of that cue — never a claim that HPR's own intro design is a defect to fix.
  • The intro is also how HPR satisfies its CC-BY-SA attribution requirement — see "License handling" above.
  • A documentation/code discrepancy, flagged rather than smoothed over — see "What HPR's own pipeline already does" above (the "30 seconds" claim vs. the actual uncapped generation code).
  • The exact spoken text is fully reconstructable from the database — hpr_hub/cms/say.php's plain string concatenation, reproduced (not required for the primary detection path) in metadata.synopsis_text(), as a foundation for a possible future deterministic, zero-ASR intro-alignment spike: resynthesize the expected text with the same Piper voice (en_US-ljspeech-high.onnx) and correlate the result against the real episode, rather than relying on ASR at all. Not yet built — the ASR-anchor path already works and shipped first.
  • The project is careful, consensus-driven, and averse to touching canonical identifiers. policies.md: "The janitors really do not like to move shows around once they are posted" — doing so breaks RSS readers and CCDN sync. This tool stays strictly read-only against the official archive: it never proposes renaming, renumbering, or otherwise modifying HPR's own canonical releases, and names its own output so it can never be confused with the original (hprNNNN. trimmed.ext, never literally hprNNNN.mp3).
  • Harm is handled by response episodes and janitor review, not unilateral editing. policies.md: the remedy for a problematic show is a response episode or raising it with the janitors — never silently altering what's published. This tool's framing matches that norm.
  • General ethos match. The CCDN architecture doc's explicit preference for minimal, boring, FLOSS, Debian-stable tooling over frameworks ("The system intentionally avoids: Databases, PHP, Python web applications, Kubernetes, Redis...") lines up with the dependency-weight goal here — ffmpeg + Python stdlib + numpy, no heavy framework, ASR optional.

Edge cases & known limitations

  • Shows with their own bonus intro music (Linux Inlaws and similar). Their extra theme plays after the standard HPR greeting — it's the hosts' own content, not station boilerplate, and must never be stripped. The cross-correlation anomaly check catches this automatically (see "Cut-point detection strategy" above); the ASR-anchor method independently stops at the right place anyway, because it only recognizes station-specific metadata phrases.
  • Episodes with no usable signal at all — flagged for manual review, never guessed. Confirmed in testing: of 9 sample episodes, 2 correctly fell back to "no reliable signal" rather than a plausible-looking but wrong cut (one of them, hpr0500, for the same reason described in the markers.py docstring — an organic cold open that merely echoes the greeting pattern).
  • Era wording drift. The marker-phrase library (hpr_stripper/markers.json) is not a fixed constant — it's already been through at least 4 generations of wording and will keep drifting. Extend it there, not in code, the same way a spam-filter rule file gets maintained. Concretely caught once already: a code-review pass flagged a metadata_arithmetic-vs-marker-match disagreement on hpr4775 (40.0s vs 16.4s); rendering the clip with tools/visualize_clip.sh and comparing the resulting waveform/spectrogram against the real official SRT showed it had moved to a newer phrasing — "the host is X and the duration is Y" / "the flag is Y, and the license is Z" — that the marker set didn't recognize yet, so matching stopped two segments early. Fixed in markers.json (bumped to version 2); see tests/test_markers.py's test_2026_wording_variant_is_recognized for the locked-in regression test. The same technique (a random-sample run flagging a metadata_arithmetic disagreement, then rendering the clip to check which side was actually right) found two more gaps in one pass: hpr2157's era apparently used the bare abbreviation "HPR episode" rather than "Hacker Public Radio episode" (intro_end was landing at 3.25s via the much weaker sibling-correlation fallback, instead of a proper marker match), and Whisper tiny mis-hearing "Today's" as "To its" on hpr3356 broke the same marker a different way. Both fixed in markers.json (version 3). hpr3356 itself (a 282-minute New Year's Eve marathon episode) remains an open case even after the fix — its structure doesn't cleanly match the standard template, and it's still correctly flagged for manual review rather than given a confident wrong answer. Superseded for the TTS-announcement portion specifically once markers.find_intro_end_via_synopsis (see "Cut-point detection strategy") became the primary method: sequence-aligning against the actual expected text tolerates most per-episode wording drift and ASR mis-hearing automatically, without a marker-list update at all (e.g. hpr2157 and hpr3237, both episodes from this list, now resolve via synopsis-alignment rather than needing the aliases added for them). markers.json still needs maintaining for the sponsor-ad-read scripts and the outro boilerplate, which have no per-episode deterministic text to align against.
  • The theme-correlation fallback couldn't bridge a genuine silence gap — resolved. Raised as a question of whether this whole class of problem would be better solved by general music/audio detection instead of continuing to patch text markers; the answer that bore out is "neither, for different sub-problems" (see the discussion that follows this list). generate_intro() mixes TTS speech additively onto theme.flac (sox -m), so correlating the vendored reference against a real episode predictably drops once speech starts masking it — expected, and still not treated as a disagreement (see the comment in detect.py next to theme_xcorr). The old "leading contiguous run" correlation algorithm couldn't recover once correlation legitimately resumed after that masked stretch (hpr4775: real TTS speech 0–27.3s, then an honest ~13s silence/instrumental gap before the host's own greeting at ~40s, matching theme.flac's own 40.52s length closely). Fixed by audio.last_high_correlation_run_seconds(), which finds contiguous correlated runs of a minimum length (ignoring single-window noise spikes) and returns the end of the last qualifying run rather than only the first unbroken one — as long as the very first run still starts near the beginning, so a later island of coincidental correlation is never trusted without a confirmed anchor. Re-verified live: hpr4775 now resolves to 40.5s (official_srt+reference_xcorr_floor), matching the real boundary found by waveform inspection almost exactly.
  • A second real bug found while fixing the above: markers containing literal punctuation could never match. markers.normalize() strips punctuation from the input text before comparison, but marker strings from markers.json were compared raw -- so a marker like "brought to you by archive.org" could never match normalized text (which has "archive.org" turned into "archive org"). Fixed by normalizing the marker string too before comparison, in fuzzy_contains(). Found by a failing test, not by inspection -- a reminder that the test suite earns its keep even on marker-only changes that look like plain data edits.
  • Sponsor ad-read segments were also a real, recurring gap (hpr3356, hpr2263, hpr3419): a fixed, reused ad script per sponsor sits between the TTS block and the real content gap, and wasn't recognized at all. Unlike the TTS wording itself, HPR's outro names only three sponsors in total (anhonesthost.com, Internet Archive, rsync.net), so their ad scripts were enumerated as markers the same way outro_markers are, rather than attempting a generic "anything right after a confirmed match with a small gap counts too" heuristic — that heuristic was considered and rejected: it would also have swallowed a host's own content whenever they start talking immediately after the TTS block with no gap at all, which is the common case, not the exception. An rsync.net ad script hasn't been observed yet, so it isn't guessed at (version 4).
  • Even with synopsis-alignment, not every garbled transcript is resolvable — and that's correct, not a shortfall. hpr2157's garbling is scattered across the title, host name, and series fields, but the surrounding boilerplate words still align (resolves to 30.6s). hpr1892's garbling is concentrated in its first ~17 words specifically — no confident match anywhere near the start of the transcript — so find_intro_end_via_synopsis's leading-anchor check correctly declines rather than trusting a match found only deep into the clip. Both outcomes are intentional (see the docstring and tests/test_synopsis_alignment.py for both, side by side): some transcripts are simply too degraded for any automated method, and should stay flagged for manual review rather than guessed at either way.
  • A real bug found while validating the above: the sponsor-ad-read continuation filtered segments by end time instead of start time. A segment that merely ended near the confirmed synopsis-alignment boundary, but had started before it, was processed first and broke the extension chain immediately (it doesn't match any marker, being part of the already-confirmed TTS block) — silently discarding a real extension through a following sponsor ad-read (found on hpr2157, whose live result briefly regressed to a too-short boundary before this was caught and fixed).
  • Official SRT segment timing may not always be trustworthy even when present — the checked-in intro.srt template's timestamps are nominal defaults, not necessarily exact for every real episode's rendered TTS audio (observed variance: true intro lengths 13–48s against a 27.32s nominal template).
  • The duration-field arithmetic cross-check is era-limited — matched real ASR-measured boundaries within a few seconds for three modern test episodes, but was off by 53 seconds for an older one. Corroboration only, for recent episodes.

Why not just detect music, generally?

Worth a direct answer, since it came up again after a run of marker-list patches started looking like whack-a-mole: the intro genuinely splits into two different sub-problems that want different tools, not one.

Finding where the music bed ends is a real acoustic question, and audio correlation (against theme.flac) is the right tool for it — the remaining gap there was a bug in the correlation algorithm itself (fixed above), not a reason to abandon audio-based detection.

Finding where station-inserted speech ends — the TTS announcement, and any sponsor ad-read that follows it — is not an acoustic question at all. The sponsor ad-reads that caused the marker-list patches above are audio-feature-identical to a host's own speech: same microphone, same format, no music, no silence, nothing a spectral or music-presence classifier could key on. Only understanding what's being said distinguishes them. The reassuring part is that this half of the problem is bounded, not open-ended: HPR's wording has drifted a handful of times in 18 years, and HPR names exactly three sponsors in total. Each discovery here has been closing in on a small, enumerable set, not chasing an unbounded one — which is also why a generic "small gap after a confirmed match still counts" heuristic was considered and rejected (see above): it would have been simpler, but it would have broken the common case (a host beginning to talk immediately after the TTS block, with no gap at all) in exchange for handling the rarer one.

Open items

  • Deterministic, zero-ASR intro alignment — half built. The text-level half is done: markers.find_intro_end_via_synopsis sequence-aligns the ASR transcript against metadata.synopsis_text()'s reproduction of the expected announcement, and is now the primary intro-boundary method (see "Cut-point detection strategy"). Still open is the audio-level half originally envisioned — resynthesizing the expected speech with the same Piper voice (en_US-ljspeech-high.onnx) and correlating that against the real episode, which would remove the need to run ASR at all for episodes where this text-alignment method already works well. Given how well the text-alignment half has performed, this is now a "would remove a dependency" improvement rather than a "would fix broken detection" one — lower priority than it looked before this was built.
  • Sidecar metadata format — currently a JSON file alongside each trimmed output (trim.write_sidecar()); ID3 tags are a reasonable addition if trimmed files are likely to circulate without their sidecar.
  • A reference-free acoustic signal for the pre-2015 era (no vendored theme clip exists for it) was tried once, with mixed results — noted for completeness, not because it's expected to pan out. Tested a chroma_stability / onset-periodicity / spectral-flatness scoring approach (librosa) against theme.flac and two real episodes. The full weighted formula didn't track known boundaries cleanly for either. Breaking it into components showed chroma_stability alone reproduced the hpr4775 gap-boundary (~40s) that the correlation fix also found, independently and without the reference file — a real result, but for the era where correlation already works, not the one that needs a reference-free option. The one old-era test (hpr0600) that would actually matter was inconclusive — no clean signal, but also no verified transcript to judge the result against, so this doesn't confirm the approach fails there either, just that it's unproven. Would also add a genuinely heavy dependency (numba, scipy, scikit-learn, soundfile, pooch — comparable to the ASR stack, which stays optional for exactly this reason). Not adopted; would need real verified-transcript test cases from the pre-2015 era before it's worth revisiting, and might still turn out not to help there.