- detect.py: _best_sibling_estimate() replaces a median/consensus across neighbouring episodes with the best match found. Found directly on a user-reported case (hpr0400): its three closest neighbours correlated at ~0 since they don't share this episode's specific jingle variant, but a fourth matched cleanly at 29.25s -- the median discarded that real evidence because it was outvoted by neighbours that simply aren't relevant, not because the intro genuinely doesn't match anything. Only the case where nothing nearby correlates at all is still flagged inconclusive. - cli.py: trim --episode N with no prior detect for that episode used to silently do nothing -- no output, no error, exit 0. Now errors clearly and tells the user to run detect first; a batch trim over a range still treats this as normal and reports a count instead. Also made trim's metadata connection lazy, so the error path doesn't need network access at all (a test that exercises it dropped from ~4s to instant). - docs/DESIGN.md: documented both fixes, and the format-default/ --format/precision fixes from immediately before this round. New tests: test_sibling_aggregation.py, test_cli_trim_errors.py.
239 lines
9.7 KiB
Python
239 lines
9.7 KiB
Python
"""
|
|
Command-line entry point. See README.md for usage examples.
|
|
|
|
Subcommands:
|
|
detect Run cut-point detection for one episode, a range, or N random
|
|
episodes (optionally stratified by era). Writes results to the
|
|
ledger; never touches audio beyond fetching/caching it.
|
|
trim Read the ledger and produce trimmed copies for episodes whose
|
|
detection succeeded and isn't flagged.
|
|
sweep Full-corpus detection pass. Interruptible: Ctrl+C at any point
|
|
leaves the ledger consistent, and re-running skips everything
|
|
already done (see docs/DESIGN.md, "Testing & resumability
|
|
strategy").
|
|
report Print a summary of what's in the ledger so far.
|
|
"""
|
|
import argparse
|
|
import random
|
|
import sys
|
|
|
|
from . import config, detect, ledger, metadata, trim
|
|
|
|
ERA_BOUNDARIES = [
|
|
(1, 1699, "pre-2015 (fixed jingle, no spoken announcement)"),
|
|
(1700, 2999, "~2015-2020 (simpler TTS template)"),
|
|
(3000, 999999, "~2020+ (fuller TTS template)"),
|
|
]
|
|
|
|
|
|
def _era_for(ep_id):
|
|
for lo, hi, label in ERA_BOUNDARIES:
|
|
if lo <= ep_id <= hi:
|
|
return label
|
|
return "unknown"
|
|
|
|
|
|
def _max_episode_id(cache_dir):
|
|
conn = metadata.connect(cache_dir)
|
|
row = conn.execute("SELECT MAX(id) FROM eps").fetchone()
|
|
return row[0]
|
|
|
|
|
|
def _build_settings(args):
|
|
"""Shared by every subcommand that fetches audio, so --cache-dir and
|
|
--format apply consistently everywhere rather than only to whichever
|
|
subcommand happened to wire them up."""
|
|
settings = config.default_settings()
|
|
settings.cache_dir = args.cache_dir
|
|
if getattr(args, "format", None):
|
|
settings.audio_format_preference = tuple(
|
|
ext.strip().lower() for ext in args.format.split(",") if ext.strip()
|
|
)
|
|
return settings
|
|
|
|
|
|
def _print_result(result):
|
|
r = result.__dict__ if hasattr(result, "__dict__") else result
|
|
print(
|
|
f"hpr{r['episode']:04d}: intro_end={r.get('intro_end')} ({r.get('intro_method')}"
|
|
f"{', FLAG: ' + r['intro_flag'] if r.get('intro_flag') else ''}) "
|
|
f"outro_start={r.get('outro_start')} ({r.get('outro_method')}"
|
|
f"{', FLAG: ' + r['outro_flag'] if r.get('outro_flag') else ''}) "
|
|
f"license={r.get('license')}{' [' + r['license_flag'] + ']' if r.get('license_flag') else ''}"
|
|
)
|
|
|
|
|
|
def cmd_detect(args):
|
|
settings = _build_settings(args)
|
|
conn = ledger.connect(settings.cache_dir)
|
|
|
|
episode_ids = []
|
|
if args.episode:
|
|
episode_ids = [args.episode]
|
|
elif args.range:
|
|
lo, hi = args.range.split("-")
|
|
episode_ids = list(range(int(lo), int(hi) + 1))
|
|
|
|
for ep_id in episode_ids:
|
|
if not args.force and ledger.is_done(conn, ep_id, settings):
|
|
print(f"hpr{ep_id:04d}: already done, skipping (use --force to redo)")
|
|
continue
|
|
result = detect.detect(ep_id, settings.cache_dir, settings)
|
|
ledger.record(conn, ep_id, result.__dict__, settings,
|
|
status="error" if result.error else "done")
|
|
_print_result(result)
|
|
|
|
|
|
def cmd_sweep(args):
|
|
settings = _build_settings(args)
|
|
conn = ledger.connect(settings.cache_dir)
|
|
max_id = args.max_episode or _max_episode_id(settings.cache_dir)
|
|
|
|
print(f"Sweeping episodes 1..{max_id}. Interrupt any time with Ctrl+C -- "
|
|
f"progress is saved after every episode and re-running resumes.")
|
|
done_count = 0
|
|
try:
|
|
for ep_id in range(1, max_id + 1):
|
|
if ledger.is_done(conn, ep_id, settings):
|
|
continue
|
|
result = detect.detect(ep_id, settings.cache_dir, settings)
|
|
ledger.record(conn, ep_id, result.__dict__, settings,
|
|
status="error" if result.error else "done")
|
|
done_count += 1
|
|
if done_count % 25 == 0:
|
|
print(f"... {done_count} episodes processed this run (last: hpr{ep_id:04d})")
|
|
except KeyboardInterrupt:
|
|
print(f"\nInterrupted after {done_count} episodes this run. "
|
|
f"Nothing lost -- re-run the same command to resume.")
|
|
sys.exit(130)
|
|
print(f"Sweep complete: {done_count} episodes processed this run.")
|
|
|
|
|
|
def cmd_random_sample(args):
|
|
"""Stratified random sample across the three known eras, so a lucky or
|
|
unlucky sample can't hide an era-specific regression."""
|
|
settings = _build_settings(args)
|
|
conn = ledger.connect(settings.cache_dir)
|
|
max_id = _max_episode_id(settings.cache_dir)
|
|
|
|
rng = random.Random(args.seed)
|
|
valid_eras = [(lo, min(hi, max_id), label) for lo, hi, label in ERA_BOUNDARIES if lo <= max_id]
|
|
# Distribute args.n across the eras as evenly as era size allows,
|
|
# giving any remainder to the earlier eras -- the result always has
|
|
# exactly min(args.n, total episodes available) entries, never a
|
|
# multiple of len(ERA_BOUNDARIES) regardless of what args.n was.
|
|
base, remainder = divmod(args.n, len(valid_eras))
|
|
chosen = []
|
|
for i, (lo, hi, label) in enumerate(valid_eras):
|
|
pool = list(range(lo, hi + 1))
|
|
want = base + (1 if i < remainder else 0)
|
|
chosen.extend(rng.sample(pool, min(want, len(pool))))
|
|
|
|
print(f"Random sample ({len(chosen)} episodes, seed={args.seed}):")
|
|
for ep_id in sorted(chosen):
|
|
result = detect.detect(ep_id, settings.cache_dir, settings)
|
|
ledger.record(conn, ep_id, result.__dict__, settings,
|
|
status="error" if result.error else "done")
|
|
print(f" [{_era_for(ep_id)}]")
|
|
_print_result(result)
|
|
|
|
|
|
def cmd_trim(args):
|
|
settings = _build_settings(args)
|
|
conn = ledger.connect(settings.cache_dir)
|
|
|
|
episode_ids = [args.episode] if args.episode else range(1, (args.max_episode or _max_episode_id(settings.cache_dir)) + 1)
|
|
done, skipped, not_detected = 0, 0, 0
|
|
meta_conn = None # connected lazily: not needed at all on the no-ledger-entry error path
|
|
for ep_id in episode_ids:
|
|
result = ledger.get(conn, ep_id)
|
|
if result is None:
|
|
if args.episode:
|
|
# An explicit --episode with nothing in the ledger is a
|
|
# real mistake, not a normal part of batch trimming (where
|
|
# most episodes legitimately haven't been detected yet) --
|
|
# say so plainly instead of silently doing nothing.
|
|
print(f"hpr{ep_id:04d}: no detection result found. "
|
|
f"Run `detect --episode {ep_id}` first.", file=sys.stderr)
|
|
sys.exit(1)
|
|
not_detected += 1
|
|
continue
|
|
ok, reason = trim.should_trim(result, force=args.force)
|
|
if not ok:
|
|
print(f"hpr{ep_id:04d}: SKIP ({reason})")
|
|
skipped += 1
|
|
continue
|
|
from . import fetch
|
|
src_path = fetch.fetch_audio(ep_id, settings.cache_dir, settings.audio_format_preference)
|
|
ext = src_path.rsplit(".", 1)[-1]
|
|
dst_path = f"{args.out_dir}/hpr{ep_id:04d}.trimmed.{ext}"
|
|
import os
|
|
os.makedirs(args.out_dir, exist_ok=True)
|
|
trim.trim_episode(src_path, dst_path, result.get("intro_end"), result.get("outro_start"),
|
|
result["duration_sec"])
|
|
meta_conn = meta_conn or metadata.connect(settings.cache_dir)
|
|
meta = metadata.get_episode(meta_conn, ep_id)
|
|
trim.write_sidecar(dst_path, meta, result)
|
|
print(f"hpr{ep_id:04d}: trimmed -> {dst_path}")
|
|
done += 1
|
|
summary = f"\n{done} trimmed, {skipped} skipped"
|
|
if not_detected:
|
|
summary += f", {not_detected} not yet detected (run detect/sweep first)"
|
|
print(summary + ".")
|
|
|
|
|
|
def cmd_report(args):
|
|
settings = _build_settings(args)
|
|
conn = ledger.connect(settings.cache_dir)
|
|
results = list(ledger.all_results(conn))
|
|
print(f"{len(results)} episodes in ledger.")
|
|
methods = {}
|
|
for r in results:
|
|
methods[r.get("intro_method")] = methods.get(r.get("intro_method"), 0) + 1
|
|
for method, count in sorted(methods.items(), key=lambda kv: -kv[1]):
|
|
print(f" intro_method={method}: {count}")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(prog="hpr-stripper", description=__doc__,
|
|
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
parser.add_argument("--cache-dir", default=config.DEFAULT_CACHE_DIR)
|
|
parser.add_argument(
|
|
"--format", metavar="EXT[,EXT...]",
|
|
help=f"audio format(s) to try, in order (default: {','.join(config.AUDIO_FORMAT_PREFERENCE)})"
|
|
)
|
|
sub = parser.add_subparsers(dest="command", required=True)
|
|
|
|
p = sub.add_parser("detect", help="detect cut points for one episode or a range")
|
|
selector = p.add_mutually_exclusive_group(required=True)
|
|
selector.add_argument("--episode", type=int)
|
|
selector.add_argument("--range", help="e.g. 3000-3050")
|
|
p.add_argument("--force", action="store_true")
|
|
p.set_defaults(func=cmd_detect)
|
|
|
|
p = sub.add_parser("sweep", help="full-corpus detection pass, interruptible/resumable")
|
|
p.add_argument("--max-episode", type=int)
|
|
p.set_defaults(func=cmd_sweep)
|
|
|
|
p = sub.add_parser("random-sample", help="detect N random episodes, stratified by era")
|
|
p.add_argument("--n", type=int, default=12)
|
|
p.add_argument("--seed", type=int, default=None)
|
|
p.set_defaults(func=cmd_random_sample)
|
|
|
|
p = sub.add_parser("trim", help="produce trimmed output for episodes with a usable, unflagged result")
|
|
p.add_argument("--episode", type=int)
|
|
p.add_argument("--max-episode", type=int)
|
|
p.add_argument("--out-dir", default="./trimmed")
|
|
p.add_argument("--force", action="store_true", help="trim even flagged/ND-licensed episodes (not recommended)")
|
|
p.set_defaults(func=cmd_trim)
|
|
|
|
p = sub.add_parser("report", help="summarize what's in the ledger")
|
|
p.set_defaults(func=cmd_report)
|
|
|
|
args = parser.parse_args()
|
|
args.func(args)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|