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.
172 lines
6.1 KiB
Python
172 lines
6.1 KiB
Python
"""
|
|
Fetch and refresh HPR's own canonical metadata dump.
|
|
|
|
Never bundles a snapshot and never trusts a pre-existing local hpr.db just
|
|
because one happens to be lying around -- every run can refresh from
|
|
config.HPR_SQL_URL, the exact URL hpr_generator's own download_hpr_sql pulls
|
|
from. Conversion uses the same tool HPR's own tooling uses (mysql2sqlite,
|
|
vendored in references/), not a bespoke parser.
|
|
"""
|
|
import os
|
|
import sqlite3
|
|
import subprocess
|
|
import time
|
|
import urllib.request
|
|
|
|
from . import config
|
|
|
|
SQL_DUMP_NAME = "hpr.sql"
|
|
DB_NAME = "hpr.db"
|
|
REFRESH_INTERVAL_SECONDS = 24 * 3600 # re-fetch at most once a day by default
|
|
|
|
|
|
def _atomic_write(final_path, write_fn):
|
|
tmp_path = final_path + ".tmp"
|
|
write_fn(tmp_path)
|
|
os.replace(tmp_path, final_path)
|
|
|
|
|
|
def fetch_sql_dump(cache_dir, force=False):
|
|
"""Download the canonical hpr.sql dump, atomically. Skips if a recent
|
|
copy is already cached, unless force=True."""
|
|
os.makedirs(cache_dir, exist_ok=True)
|
|
dest = os.path.join(cache_dir, SQL_DUMP_NAME)
|
|
if not force and os.path.exists(dest):
|
|
age = time.time() - os.path.getmtime(dest)
|
|
if age < REFRESH_INTERVAL_SECONDS:
|
|
return dest
|
|
|
|
def _write(tmp_path):
|
|
with urllib.request.urlopen(config.HPR_SQL_URL, timeout=60) as resp:
|
|
data = resp.read()
|
|
if len(data) < 1024:
|
|
raise RuntimeError(f"hpr.sql download looked truncated ({len(data)} bytes)")
|
|
with open(tmp_path, "wb") as f:
|
|
f.write(data)
|
|
|
|
_atomic_write(dest, _write)
|
|
return dest
|
|
|
|
|
|
def build_sqlite_db(cache_dir, sql_dump_path=None, force=False):
|
|
"""Convert the dump to SQLite via the vendored mysql2sqlite, the same
|
|
way hpr_generator's own update-hpr.sh does it."""
|
|
sql_dump_path = sql_dump_path or os.path.join(cache_dir, SQL_DUMP_NAME)
|
|
dest = os.path.join(cache_dir, DB_NAME)
|
|
if not force and os.path.exists(dest):
|
|
dump_mtime = os.path.getmtime(sql_dump_path)
|
|
db_mtime = os.path.getmtime(dest)
|
|
if db_mtime >= dump_mtime:
|
|
return dest
|
|
|
|
converter = os.path.join(config.REFERENCES_DIR, "mysql2sqlite")
|
|
|
|
def _write(tmp_path):
|
|
if os.path.exists(tmp_path):
|
|
os.remove(tmp_path)
|
|
# Same preprocessing hpr_generator's own update-hpr.sh does before
|
|
# running mysql2sqlite: strip DELIMITER-wrapped trigger
|
|
# definitions, which its AWK parser can't handle.
|
|
with open(sql_dump_path, "rb") as f:
|
|
sed_proc = subprocess.run(
|
|
["sed", "/^DELIMITER ;;/,/^DELIMITER ;/d"],
|
|
stdin=f, capture_output=True, check=True,
|
|
)
|
|
proc = subprocess.run(
|
|
["awk", "-f", converter, "/dev/stdin"],
|
|
input=sed_proc.stdout, capture_output=True,
|
|
)
|
|
if proc.returncode != 0:
|
|
raise RuntimeError(f"mysql2sqlite failed: {proc.stderr.decode(errors='replace')[:500]}")
|
|
sqlite_proc = subprocess.run(
|
|
["sqlite3", tmp_path], input=proc.stdout, capture_output=True,
|
|
)
|
|
if sqlite_proc.returncode != 0:
|
|
raise RuntimeError(f"sqlite3 import failed: {sqlite_proc.stderr.decode(errors='replace')[:2000]}")
|
|
|
|
_atomic_write(dest, _write)
|
|
return dest
|
|
|
|
|
|
def refresh(cache_dir=None, force=False):
|
|
"""Fetch + convert in one call. Returns the local sqlite path."""
|
|
cache_dir = cache_dir or config.DEFAULT_CACHE_DIR
|
|
sql_path = fetch_sql_dump(cache_dir, force=force)
|
|
return build_sqlite_db(cache_dir, sql_path, force=force)
|
|
|
|
|
|
def connect(cache_dir=None):
|
|
cache_dir = cache_dir or config.DEFAULT_CACHE_DIR
|
|
db_path = os.path.join(cache_dir, DB_NAME)
|
|
if not os.path.exists(db_path):
|
|
db_path = refresh(cache_dir)
|
|
conn = sqlite3.connect(db_path)
|
|
conn.row_factory = sqlite3.Row
|
|
return conn
|
|
|
|
|
|
def get_episode(conn, ep_num):
|
|
row = conn.execute(
|
|
"""
|
|
SELECT eps.id, eps.title, eps.summary, eps.duration, eps.date,
|
|
eps.explicit, eps.license, eps.series, eps.hostid,
|
|
hosts.host, hosts.espeak_name,
|
|
licenses.long_name AS license_long_name
|
|
FROM eps
|
|
LEFT JOIN hosts ON eps.hostid = hosts.hostid
|
|
LEFT JOIN licenses ON licenses.short_name = eps.license
|
|
WHERE eps.id = ?
|
|
""",
|
|
(ep_num,),
|
|
).fetchone()
|
|
return dict(row) if row else None
|
|
|
|
|
|
def synopsis_text(conn, ep_num):
|
|
"""Reproduce the exact announcement text hpr_hub/cms/say.php builds
|
|
from the database, by the same plain string concatenation it uses.
|
|
Used for the deterministic intro-alignment spike (see docs/DESIGN.md);
|
|
not required for the ASR-anchor detection path."""
|
|
import datetime
|
|
|
|
ep = get_episode(conn, ep_num)
|
|
if ep is None:
|
|
return None
|
|
|
|
date = datetime.datetime.strptime(ep["date"], "%Y-%m-%d")
|
|
host_name = ep["espeak_name"] or ep["host"]
|
|
|
|
total = conn.execute(
|
|
"SELECT count(id) AS total FROM eps WHERE hostid = ?", (ep["hostid"],)
|
|
).fetchone()["total"]
|
|
if total == 1:
|
|
host_notes = f". It is the first show by new host {host_name}, "
|
|
elif total % 10 == 0:
|
|
host_notes = f". It is the {total}th show of {host_name}, "
|
|
else:
|
|
host_notes = f". It is hosted by {host_name}, "
|
|
|
|
synopsis = (
|
|
f"This is Hacker Public Radio episode {ep_num} for "
|
|
f"{date.strftime('%A')} the {date.strftime('%d').lstrip('0')} "
|
|
f"of {date.strftime('%B %Y')}. Todays show is entitled. {ep['title']}."
|
|
)
|
|
if ep["series"] and int(ep["series"]) > 0:
|
|
series_row = conn.execute(
|
|
"SELECT name FROM miniseries WHERE id = ?", (ep["series"],)
|
|
).fetchone()
|
|
if series_row:
|
|
synopsis += f" It is part of the series \"{series_row['name']}\""
|
|
|
|
minutes = round(ep["duration"] / 60)
|
|
synopsis += f"{host_notes} and is about {minutes} minutes long. It carries "
|
|
synopsis += " a clean flag. " if ep["explicit"] == 0 else " an explicit flag. "
|
|
|
|
if ep["summary"]:
|
|
synopsis += f". The summary is. {ep['summary']}"
|
|
|
|
if ep["license"] != "CC-BY-SA":
|
|
synopsis += f". Todays show is licensed under a {ep['license_long_name']} license."
|
|
|
|
return synopsis
|