Files
hpr-intro-stripper/hpr_stripper/fetch.py
T

136 lines
4.8 KiB
Python

"""
All network access to the live HPR archive goes through this module, and
every URL it builds goes through config.CCDN_BASE -- never a backend host
observed in a redirect or error message (that's an implementation detail of
HPR's current hosting, not a stable contract; see docs/DESIGN.md).
AccessDenied, 403, 404, and a 200-with-empty-body are all treated as the
same outcome: "not available right now" -- callers fall back to the next
detection signal rather than special-casing any one status code.
"""
import os
import threading
import time
import urllib.error
import urllib.request
from . import config
MIN_PLAUSIBLE_BYTES = 16 # anything smaller than this is treated as a placeholder
_last_request_lock = threading.Lock()
_last_request_at = 0.0
def _wait_for_politeness_gap():
"""Enforces config.REQUEST_DELAY_SECONDS between any two requests this
process makes to HPR's servers, regardless of which function issued
them (audio, SRT, txt, or a neighbour's audio during sibling
correlation all share this gate)."""
global _last_request_at
with _last_request_lock:
wait = config.REQUEST_DELAY_SECONDS - (time.monotonic() - _last_request_at)
if wait > 0:
time.sleep(wait)
_last_request_at = time.monotonic()
# A byte-length check alone isn't enough -- an error response large enough
# to clear MIN_PLAUSIBLE_BYTES (an HTML 404 page, an S3-style AccessDenied
# XML body) would otherwise get saved under an audio/SRT filename and fail
# much later, confusingly, in ffprobe or SRT parsing. Reject anything that
# looks like markup rather than real content before it's ever written to
# disk.
_ERROR_PAGE_PREFIXES = (b"<html", b"<!doctype html", b"<?xml")
def _episode_url(ep_id, ext):
return f"{config.CCDN_BASE}?filename=/eps/hpr{ep_id:04d}/hpr{ep_id:04d}.{ext}"
def _looks_like_error_page(data):
head = data[:256].lstrip().lower()
return any(head.startswith(prefix) for prefix in _ERROR_PAGE_PREFIXES)
def _fetch_bytes(url, timeout=30):
_wait_for_politeness_gap()
try:
with urllib.request.urlopen(url, timeout=timeout) as resp:
data = resp.read()
except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError):
return None
if len(data) < MIN_PLAUSIBLE_BYTES or _looks_like_error_page(data):
return None
return data
def _atomic_save(data, dest_path):
os.makedirs(os.path.dirname(dest_path), exist_ok=True)
tmp_path = dest_path + ".tmp"
with open(tmp_path, "wb") as f:
f.write(data)
os.replace(tmp_path, dest_path)
def fetch_audio(ep_id, cache_dir, format_preference=None, force=False):
"""Returns the local path to the episode's audio, fetching whichever
format succeeds first from format_preference (default: mp3, ogg, opus)."""
format_preference = format_preference or config.AUDIO_FORMAT_PREFERENCE
audio_dir = os.path.join(cache_dir, "audio")
if not force:
for ext in format_preference:
existing = os.path.join(audio_dir, f"hpr{ep_id:04d}.{ext}")
if os.path.exists(existing):
return existing
from . import audio # deferred to avoid importing numpy for callers that never need it
for ext in format_preference:
data = _fetch_bytes(_episode_url(ep_id, ext))
if data is None:
continue
dest = os.path.join(audio_dir, f"hpr{ep_id:04d}.{ext}")
_atomic_save(data, dest)
try:
if audio.duration_seconds(dest) > 0:
return dest
except Exception:
pass
os.remove(dest) # saved bytes didn't decode as real audio -- try the next format
return None
def fetch_official_srt(ep_id, cache_dir, force=False):
"""Returns the local path to the official SRT if HPR has published a
real one for this episode, else None. A 0-byte/placeholder response is
treated the same as 404 -- never assumed present from the episode page
or from era alone."""
from . import srt # deferred to avoid a module-level cycle with srt.py's own imports
dest = os.path.join(cache_dir, "transcripts", f"hpr{ep_id:04d}.srt")
if not force and os.path.exists(dest):
return dest
data = _fetch_bytes(_episode_url(ep_id, "srt"))
if data is None:
return None
_atomic_save(data, dest)
try:
if srt.parse_file(dest):
return dest
except Exception:
pass
os.remove(dest) # saved bytes didn't parse as at least one real SRT segment
return None
def fetch_official_txt(ep_id, cache_dir, force=False):
dest = os.path.join(cache_dir, "transcripts", f"hpr{ep_id:04d}.txt")
if not force and os.path.exists(dest):
return dest
data = _fetch_bytes(_episode_url(ep_id, "txt"))
if data is None:
return None
_atomic_save(data, dest)
return dest