catholiccorpus / archive_helpers.py
ddbaula's picture
Add files using upload-large-folder tool
943f1dc verified
Raw
History Blame Contribute Delete
14 kB
"""
Shared helpers for CatholicCorpus download scripts.
Why this exists:
- Archive.org returns 503 under load; naive single-shot downloads fail.
- Item IDs guessed from search results often point to redirected or
renamed items; the /metadata/ API tells us the real PDF filename.
Public API:
fetch_metadata(item) -> dict | None
resolve_pdf_url(item) -> (url, server_filename) | (None, None)
download_with_retry(url, dest) -> bool (exponential backoff on 5xx/429)
archive_pdf_smart(item, dest) -> bool (metadata lookup + retry download)
"""
from __future__ import annotations
import atexit
import json
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import List, Optional, Tuple
import requests
# Persistent lending-restricted log — shared across all tasks
_LENDING_LOG = Path(__file__).resolve().parent / "LENDING_RESTRICTED.json"
UA = {"User-Agent": "CatholicCorpus/1.0 (academic research; admin@catholiccorpus.org)"}
TIMEOUT = 180
CHUNK = 1 << 15
# Retry policy
RETRY_STATUSES = {429, 500, 502, 503, 504}
MAX_RETRIES = 3 # 3 attempts (not 5) — cuts wait from 124s to 28s per item
BACKOFF_BASE = 4 # 4, 8, 16 → 28s max total wait per item
BACKOFF_MAX = 30
# Circuit breaker: if archive.org fires N consecutive 5xx/metadata-nulls,
# pause for a cooldown period then try again. Prevents wasting time on a
# degraded server while still retrying later in the same run.
_consecutive_failures = 0
_CIRCUIT_BREAKER_THRESHOLD = 5
_circuit_open = False
_circuit_opened_at = 0.0
_CIRCUIT_COOLDOWN = 60 # seconds before auto-resetting the circuit
def _note_failure():
global _consecutive_failures, _circuit_open, _circuit_opened_at
_consecutive_failures += 1
if _consecutive_failures >= _CIRCUIT_BREAKER_THRESHOLD and not _circuit_open:
_circuit_open = True
_circuit_opened_at = time.time()
_log(f" [!] Circuit breaker: {_consecutive_failures} consecutive archive.org failures")
_log(f" Likely causes: archive.org is degraded (5xx), IP is being rate-limited,")
_log(f" or the guessed item IDs don't exist.")
_log(f" Pausing for {_CIRCUIT_COOLDOWN}s cooldown, then retrying.")
def _note_success():
global _consecutive_failures, _circuit_open
_consecutive_failures = 0
_circuit_open = False
def circuit_is_open() -> bool:
global _circuit_open, _consecutive_failures
if _circuit_open and (time.time() - _circuit_opened_at) >= _CIRCUIT_COOLDOWN:
_log(f" [circuit cooldown elapsed — retrying archive.org]")
_circuit_open = False
_consecutive_failures = 0
return _circuit_open
def _log(msg: str) -> None:
print(msg, flush=True)
# ---------------------------------------------------------------------------
# Lending-restricted item tracker
# ---------------------------------------------------------------------------
def _record_lending_restricted(item: str, title: str, task_hint: str = "") -> None:
"""Append a lending-restricted item to LENDING_RESTRICTED.json."""
entries = {}
if _LENDING_LOG.exists():
try:
entries = json.loads(_LENDING_LOG.read_text())
except (json.JSONDecodeError, OSError):
entries = {}
if item not in entries:
entries[item] = {
"title": title,
"task": task_hint,
"url": f"https://archive.org/details/{item}",
"discovered": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
}
_LENDING_LOG.write_text(json.dumps(entries, indent=2, ensure_ascii=False) + "\n")
_log(f" → logged to LENDING_RESTRICTED.json")
def render_lending_restricted_md() -> None:
"""Generate LENDING_RESTRICTED.md from the JSON log."""
if not _LENDING_LOG.exists():
return
try:
entries = json.loads(_LENDING_LOG.read_text())
except (json.JSONDecodeError, OSError):
return
if not entries:
return
md_path = _LENDING_LOG.with_suffix(".md")
by_task: dict[str, list] = {}
for item_id, info in entries.items():
task = info.get("task", "unknown")
by_task.setdefault(task, []).append((item_id, info))
lines = [
"# Lending-Restricted Items",
"",
"These archive.org items exist but are **borrow-only** (`access-restricted-item: true`).",
"They cannot be bulk-downloaded without an Open Library lending session.",
f"",
f"Total: {len(entries)} items across {len(by_task)} tasks.",
"",
]
for task in sorted(by_task):
lines.append(f"## {task}")
lines.append("")
for item_id, info in sorted(by_task[task], key=lambda x: x[0]):
lines.append(f"- **{item_id}**")
lines.append(f" - Title: {info.get('title', '?')}")
lines.append(f" - URL: {info.get('url', '?')}")
lines.append(f" - Discovered: {info.get('discovered', '?')}")
lines.append("")
lines.append("---")
lines.append("*Auto-generated by archive_helpers.py — do not edit manually.*")
lines.append("")
md_path.write_text("\n".join(lines))
_log(f"Updated {md_path.name} ({len(entries)} items)")
# Auto-render the markdown when any script using archive_helpers exits
atexit.register(render_lending_restricted_md)
# ---------------------------------------------------------------------------
# Sentinel distinguishing "item exists but metadata API was unreachable"
# (fall back to URL guess) from "metadata said the item does not exist"
# (don't bother guessing — item literally is not on archive.org).
_META_UNREACHABLE = object()
def fetch_metadata(item: str) -> dict | None | object:
"""
Return parsed /metadata/{item} payload.
- dict: item exists and has files
- None: item does NOT exist on archive.org (metadata returned {} or 404)
- _META_UNREACHABLE: could not reach metadata API (5xx / network error)
→ caller may want to fall back to URL guessing
"""
url = f"https://archive.org/metadata/{item}"
for attempt in range(MAX_RETRIES):
try:
r = requests.get(url, headers=UA, timeout=30)
except requests.RequestException as e:
wait = min(BACKOFF_BASE * (2 ** attempt), BACKOFF_MAX)
_log(f" metadata {item}: {type(e).__name__}, retry in {wait}s")
time.sleep(wait)
continue
if r.status_code == 200:
try:
data = r.json()
except ValueError:
return None
# Archive.org returns {} for items that do not exist
if not data or "files" not in data:
return None
return data
if r.status_code in RETRY_STATUSES:
wait = min(BACKOFF_BASE * (2 ** attempt), BACKOFF_MAX)
_log(f" metadata {item}: HTTP {r.status_code}, retry in {wait}s")
time.sleep(wait)
continue
# 404 etc. — item doesn't exist
return None
# All retries exhausted on network error or 5xx — API was unreachable
return _META_UNREACHABLE
def _pick_best_pdf(meta: dict, item: str) -> tuple[str | None, str | None]:
"""
Given a metadata dict, find the best PDF file.
Returns (download_url, server_filename). Returns (None, None) if nothing found.
Strategy:
1. Prefer files whose `format` is 'Text PDF' or 'Abbyy PDF'.
2. Prefer the largest PDF.
3. Fall back to any .pdf file.
"""
pdfs = []
for f in meta.get("files", []):
name = f.get("name", "")
if not name.lower().endswith(".pdf"):
continue
# Skip encrypted PDFs (lending artifacts)
if "_encrypted" in name.lower():
continue
try:
size = int(f.get("size", "0"))
except ValueError:
size = 0
fmt = (f.get("format") or "").lower()
pdfs.append((fmt, size, name))
if not pdfs:
return None, None
# Prefer Text/Abbyy PDFs, then largest
def _score(p):
fmt, size, _ = p
preferred = any(k in fmt for k in ("text pdf", "abbyy"))
return (preferred, size)
pdfs.sort(key=_score, reverse=True)
_, _, best = pdfs[0]
return f"https://archive.org/download/{item}/{best}", best
def resolve_pdf_url(item: str) -> tuple[str | None, str | None]:
"""
Given an archive.org item, find its best PDF file via the metadata API.
Returns (download_url, server_filename). Returns (None, None) if nothing found.
"""
meta = fetch_metadata(item)
if meta is _META_UNREACHABLE:
return _META_UNREACHABLE, None
if not meta:
return None, None
return _pick_best_pdf(meta, item)
# ---------------------------------------------------------------------------
def _validate(path: Path, min_bytes: int, markers: list[bytes] | None) -> bool:
if not path.exists():
return False
size = path.stat().st_size
if size < min_bytes:
_log(f" ✗ too small ({size} bytes < {min_bytes})")
return False
with path.open("rb") as fh:
head = fh.read(1024)
if head.startswith(b"<!") or head.lstrip().lower().startswith(b"<html"):
_log(" ✗ looks like HTML landing page")
return False
if not head.startswith(b"%PDF") and not head.startswith(b"PK") and not head.startswith(b"\x1f\x8b"):
# Not PDF, not zip, not gzip — may be djvu.txt which is fine
if markers:
# fall through to marker check
pass
else:
_log(" ✗ unknown file format")
return False
if markers:
# Read more for marker search
with path.open("rb") as fh:
blob = fh.read(1 << 20)
low = blob.lower()
if not any(m.lower() in low for m in markers):
_log(" ✗ expected markers not found")
return False
return True
def download_with_retry(
url: str,
dest: Path,
min_bytes: int = 200_000,
markers: list[bytes] | None = None,
) -> bool:
"""Stream-download url → dest, validate, retry on 5xx/429."""
for attempt in range(MAX_RETRIES):
try:
r = requests.get(url, headers=UA, timeout=TIMEOUT, stream=True, allow_redirects=True)
except requests.RequestException as e:
wait = min(BACKOFF_BASE * (2 ** attempt), BACKOFF_MAX)
_log(f" network {type(e).__name__}: {e!s}, retry in {wait}s")
time.sleep(wait)
continue
if r.status_code == 200:
try:
with dest.open("wb") as fh:
for chunk in r.iter_content(CHUNK):
if chunk:
fh.write(chunk)
except Exception as e:
_log(f" write failed: {e}")
if dest.exists():
dest.unlink()
return False
if _validate(dest, min_bytes, markers):
return True
if dest.exists():
dest.unlink()
# Not retrying on validation failure — the server gave a bad file
return False
if r.status_code in RETRY_STATUSES:
wait = min(BACKOFF_BASE * (2 ** attempt), BACKOFF_MAX)
_log(f" HTTP {r.status_code}, retry in {wait}s (attempt {attempt + 1}/{MAX_RETRIES})")
time.sleep(wait)
continue
_log(f" HTTP {r.status_code}, giving up")
return False
_log(" retries exhausted")
return False
def archive_pdf_smart(
item: str,
dest: Path,
min_bytes: int = 200_000,
) -> bool:
"""
Resolve the item's real PDF via the metadata API, then download with retry.
Falls back to the conventional /download/{item}/{item}.pdf URL if metadata is unreachable.
Circuit breaker: after N consecutive failures, returns False immediately
without hitting the network. Reset between script runs.
"""
if circuit_is_open():
_log(f" [circuit open] skipping {item}")
return False
meta = fetch_metadata(item)
# Metadata API is unreachable (5xx/network). We don't know if the item
# exists, so fall back to the conventional URL as a last resort.
if meta is _META_UNREACHABLE:
_log(f" [metadata unreachable, trying convention] /download/{item}/{item}.pdf")
ok = download_with_retry(
f"https://archive.org/download/{item}/{item}.pdf",
dest,
min_bytes=min_bytes,
)
if ok:
_note_success()
else:
_note_failure()
return ok
if not meta:
_log(f" [not on archive.org] {item}")
return False
# Check if the item is lending-restricted (borrow-only).
# These always return 401/403 on direct download — skip without
# counting as a failure (it's not a server problem).
item_meta = meta.get("metadata", {})
restricted = item_meta.get("access-restricted-item", "false")
if restricted == "true" or restricted is True:
title = item_meta.get("title", "?")
# Infer task from dest path (e.g. .../13_mystics/emmerich/file.pdf)
task_hint = ""
for parent in dest.parents:
if parent.name and parent.name[:2].isdigit():
task_hint = parent.name
break
_log(f" [lending-restricted] {item} — borrow-only, skipping")
_record_lending_restricted(item, title, task_hint)
return False
# Find best PDF from metadata
url, fname = _pick_best_pdf(meta, item)
if url:
_log(f" [metadata] {item}{fname}")
if download_with_retry(url, dest, min_bytes=min_bytes):
_note_success()
return True
_note_failure()
return False
_log(f" [no PDF found] {item}")
return False