IMF-Reports / pipeline /src /cd_eval /imf_scraper.py
FrenchCastle's picture
Upload complete IMF reports research corpus (part 27)
e58f9dd verified
Raw
History Blame Contribute Delete
38.1 kB
"""Build a reproducible raw corpus of IMF technical-assistance reports.
The IMF landing page renders its result list through the public Coveo search API.
This module snapshots that inventory and downloads the corresponding PDFs. The
PDF URL is deterministic for most reports. For legacy Country Report entries,
the Internet Archive is used only to recover the PDF link from an archived IMF
publication page when the deterministic IMF URL does not exist.
No document text is transformed in this stage: ``data/raw`` is provenance-rich,
immutable source material for later processing.
"""
from __future__ import annotations
import argparse
import concurrent.futures
import dataclasses
import datetime as dt
import gzip
import hashlib
import html.parser
import json
import os
import re
import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any, Iterable, Iterator, Sequence
LANDING_PAGE = (
"https://www.imf.org/en/publications/sprolls/"
"technical-assistance-country-reports"
)
ROBOTS_URL = "https://www.imf.org/robots.txt"
COVEO_ORGANIZATION = "imfproduction561s308u"
COVEO_ENDPOINT = (
f"https://{COVEO_ORGANIZATION}.org.coveo.com/rest/search/v2"
f"?organizationId={COVEO_ORGANIZATION}"
)
# This is the public, search-only token shipped in the IMF site's client bundle,
# not a private project credential. Override with IMF_COVEO_TOKEN if IMF rotates it.
DEFAULT_COVEO_TOKEN = "xx742a6c66-f427-4f5a-ae1e-770dc7264e8a"
# IMF's Akamai policy rejects unknown User-Agent products while allowing standard
# library clients. Keep a truthful standard-library identifier by default; callers
# can override it from the CLI when their network policy requires one.
DEFAULT_USER_AGENT = "Python-urllib/3"
COVEO_SOURCES = [
"IMFORG-ADMINTRIB",
"IMFORG-AM-VIDEOS",
"IMFORG-AM-VIDEOS-PREV",
"IMFORG-FAD",
"IMFORG-FANDD",
"IMFORG-MAIN",
"IMFORG-MAIN-VIDEOS",
"IMFORG-SELDEC",
"IMFORG-SM-VIDEOS",
"IMFORG-SM-VIDEOS-PREV",
"IMFORG-STAFFPAPERS",
]
# This expression is the one configured on the IMF SPROLLResults component.
# Keeping it verbatim makes this inventory match the linked landing page.
IMF_FILTER_EXPRESSION = (
'(((((NOT @uri*=40097 @imfseries*="Country-Reports") OR '
'@imfseries=="Technical Assistance Reports") '
'(((((((@uri*=26150 OR @uri*=25186) OR @uri*=24973) OR @uri*=23886) '
'OR @uri*=24377) OR @uri*=24049) OR @uri*=26118) '
'OR @title*="technical-assistance")) '
'NOT @z95xtemplatename==("Bucket","Media folder"))) (@imfdate)'
)
SERIES_RE = re.compile(
r"^\s*(Country Report|Technical Assistance Report)\s+No\.\s*"
r"(?P<year>\d{4})/(?P<number>\d+)\s*$",
re.IGNORECASE,
)
PAGE_ID_RE = re.compile(r"-(\d+)$")
PDF_LINK_HINTS = (
".pdf",
".ashx",
"/media/files/publications/",
"/media/websites/imf/imported-full-text-pdf/",
"/external/pubs/ft/scr/",
"elibrary.imf.org/downloadpdf",
)
class ScraperError(RuntimeError):
"""An expected acquisition error with useful context."""
class NotPDFError(ScraperError):
"""A URL returned content that was not a PDF."""
class HostRateLimiter:
"""A small thread-safe, per-host delay to avoid bursty requests."""
def __init__(self, minimum_delay: float) -> None:
self.minimum_delay = max(0.0, minimum_delay)
self._lock = threading.Lock()
self._last_request: dict[str, float] = {}
def wait(self, url: str) -> None:
host = urllib.parse.urlsplit(url).netloc.lower()
with self._lock:
now = time.monotonic()
remaining = self.minimum_delay - (now - self._last_request.get(host, 0.0))
if remaining > 0:
time.sleep(remaining)
self._last_request[host] = time.monotonic()
class HttpClient:
"""Retrying HTTP client using only the Python standard library."""
def __init__(
self,
user_agent: str = DEFAULT_USER_AGENT,
minimum_delay: float = 0.2,
retries: int = 3,
) -> None:
self.user_agent = user_agent
self.retries = retries
self.rate_limiter = HostRateLimiter(minimum_delay)
def _request(
self,
url: str,
*,
data: bytes | None = None,
headers: dict[str, str] | None = None,
timeout: float = 90,
) -> Any:
request_headers = {
"User-Agent": self.user_agent,
"Accept": "*/*",
}
if headers:
request_headers.update(headers)
request = urllib.request.Request(url, data=data, headers=request_headers)
last_error: Exception | None = None
for attempt in range(self.retries + 1):
self.rate_limiter.wait(url)
try:
return urllib.request.urlopen(request, timeout=timeout)
except urllib.error.HTTPError as exc:
last_error = exc
if exc.code not in {408, 425, 429, 500, 502, 503, 504}:
raise
retry_after = exc.headers.get("Retry-After")
delay = float(retry_after) if retry_after and retry_after.isdigit() else 2**attempt
except (urllib.error.URLError, TimeoutError, OSError) as exc:
last_error = exc
delay = 2**attempt
if attempt < self.retries:
time.sleep(delay)
raise ScraperError(f"request failed after retries: {url}: {last_error}")
def get_bytes(self, url: str, *, timeout: float = 90) -> tuple[bytes, str, Any]:
with self._request(url, timeout=timeout) as response:
body = response.read()
# Internet Archive's ``id_`` replay occasionally returns a stored,
# gzip-encoded entity without decoding it at the HTTP layer.
if body.startswith(b"\x1f\x8b"):
body = gzip.decompress(body)
return body, response.geturl(), response.headers
def get_json(self, url: str, *, timeout: float = 90) -> Any:
body, _, _ = self.get_bytes(url, timeout=timeout)
return json.loads(body)
def post_json(self, url: str, payload: Any, *, token: str) -> Any:
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
with self._request(
url,
data=body,
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {token}",
},
timeout=90,
) as response:
return json.load(response)
def download_pdf(self, url: str, destination: Path) -> dict[str, Any]:
"""Stream a URL atomically to destination and validate PDF magic bytes."""
destination.parent.mkdir(parents=True, exist_ok=True)
temporary = destination.with_name(
f".{destination.name}.{threading.get_ident()}.part"
)
digest = hashlib.sha256()
size = 0
try:
with self._request(url, timeout=180) as response, temporary.open("wb") as output:
first = response.read(64 * 1024)
if not first.startswith(b"%PDF-"):
content_type = response.headers.get("Content-Type", "unknown")
raise NotPDFError(
f"not a PDF (type={content_type}, first={first[:20]!r}, "
f"final={response.geturl()})"
)
output.write(first)
digest.update(first)
size += len(first)
while True:
chunk = response.read(1024 * 1024)
if not chunk:
break
output.write(chunk)
digest.update(chunk)
size += len(chunk)
output.flush()
os.fsync(output.fileno())
final_url = response.geturl()
content_type = response.headers.get("Content-Type")
last_modified = response.headers.get("Last-Modified")
if size < 1024:
raise NotPDFError(f"implausibly small PDF ({size} bytes)")
os.replace(temporary, destination)
return {
"source_pdf_url": url,
"resolved_pdf_url": final_url,
"content_type": content_type,
"last_modified": last_modified,
"bytes": size,
"sha256": digest.hexdigest(),
}
finally:
temporary.unlink(missing_ok=True)
def utc_now() -> str:
return dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat()
def json_dump(path: Path, value: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
temporary.write_text(
json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
)
os.replace(temporary, path)
def jsonl_dump(path: Path, rows: Iterable[dict[str, Any]]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
with temporary.open("w", encoding="utf-8") as output:
for row in rows:
output.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")
os.replace(temporary, path)
def jsonl_load(path: Path) -> list[dict[str, Any]]:
if not path.exists():
return []
with path.open(encoding="utf-8") as source:
return [json.loads(line) for line in source if line.strip()]
def build_coveo_query(first_result: int, number_of_results: int) -> dict[str, Any]:
source_values = ",".join(
[f'"{source}"' for source in ["IMF-ORG", *COVEO_SOURCES]]
)
return {
"q": "",
"aq": "",
"cq": f"(@source==({source_values})) {IMF_FILTER_EXPRESSION}",
"searchHub": "Search",
"sortCriteria": "@imfdate descending",
"firstResult": first_result,
"numberOfResults": number_of_results,
}
def canonical_page_url(result: dict[str, Any]) -> str:
return (
result.get("clickUri")
or result.get("raw", {}).get("imf_resolved_url")
or result.get("uri")
or ""
)
def report_id_for(result: dict[str, Any]) -> str:
raw = result.get("raw", {})
series_volume = raw.get("seriesvolumeno") or ""
match = SERIES_RE.match(series_volume)
if match:
prefix = (
"tar"
if match.group(1).lower().startswith("technical")
else "cr"
)
return f"{prefix}-{match.group('year')}-{int(match.group('number')):03d}"
page_url = canonical_page_url(result)
page_id = page_numeric_id(page_url)
if page_id:
return f"legacy-{page_id}"
short_hash = hashlib.sha256(page_url.encode("utf-8")).hexdigest()[:12]
return f"legacy-{short_hash}"
def millis_to_iso(value: Any) -> str | None:
if not isinstance(value, (int, float)):
return None
return dt.datetime.fromtimestamp(value / 1000, tz=dt.timezone.utc).isoformat()
def normalize_result(result: dict[str, Any]) -> dict[str, Any]:
raw = result.get("raw", {})
return {
"report_id": report_id_for(result),
"title": result.get("title") or raw.get("title"),
"source_page_url": canonical_page_url(result),
"source_index_uri": result.get("uri"),
"series": raw.get("imfseries", []),
"series_volume_no": raw.get("seriesvolumeno"),
"publication_date": raw.get("imf_search_date")
or millis_to_iso(raw.get("imfdate")),
"countries": raw.get("imfcountry", []),
"formal_countries": raw.get("imfformalcountry", []),
"iso_codes": raw.get("imfisocode", []),
"author_indexed": raw.get("author"),
"description": raw.get("imfdescription"),
"subjects": raw.get("imfpublicationsubject", []),
"topics": raw.get("imfsearchtopics", []),
"keywords": raw.get("imfkeywords", []),
"language": raw.get("language", []),
"coveo_result": {
"unique_id": result.get("uniqueId"),
"primary_id": result.get("primaryid"),
"raw": raw,
},
}
def fetch_inventory(
client: HttpClient,
token: str,
*,
page_size: int = 100,
limit: int | None = None,
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
results: list[dict[str, Any]] = []
total = None
offset = 0
search_uids: list[str] = []
while total is None or offset < total:
response = client.post_json(
COVEO_ENDPOINT,
build_coveo_query(offset, page_size),
token=token,
)
if total is None:
total = int(response["totalCount"])
page_results = response.get("results", [])
if not page_results:
break
results.extend(page_results)
if response.get("searchUid"):
search_uids.append(response["searchUid"])
offset += len(page_results)
print(f"inventory: {min(len(results), total)}/{total}", file=sys.stderr)
if limit is not None and len(results) >= limit:
results = results[:limit]
break
normalized = [normalize_result(result) for result in results]
ids = [row["report_id"] for row in normalized]
if len(ids) != len(set(ids)):
duplicates = [key for key, count in Counter(ids).items() if count > 1]
raise ScraperError(f"non-unique report IDs: {duplicates}")
metadata = {
"fetched_at": utc_now(),
"landing_page": LANDING_PAGE,
"robots_url": ROBOTS_URL,
"inventory_source": COVEO_ENDPOINT,
"coveo_organization": COVEO_ORGANIZATION,
"configured_total": total,
"saved_count": len(normalized),
"search_uids": search_uids,
"query": build_coveo_query(0, page_size),
}
return normalized, metadata
def page_numeric_id(url: str) -> str | None:
path = urllib.parse.urlsplit(url).path.rstrip("/")
match = PAGE_ID_RE.search(path)
return match.group(1) if match else None
def normalized_url_key(url: str) -> str:
parsed = urllib.parse.urlsplit(url)
path = re.sub(r"/+", "/", urllib.parse.unquote(parsed.path)).rstrip("/")
return f"{parsed.netloc.lower()}{path.lower()}"
def series_parts(report: dict[str, Any]) -> tuple[str, int, int] | None:
match = SERIES_RE.match(report.get("series_volume_no") or "")
if not match:
return None
kind = "tar" if match.group(1).lower().startswith("technical") else "cr"
return kind, int(match.group("year")), int(match.group("number"))
def deterministic_pdf_candidates(report: dict[str, Any]) -> list[str]:
parts = series_parts(report)
if not parts:
return []
kind, year, number = parts
if kind == "tar":
stem = f"tarea{year}{number:03d}"
root = f"https://www.imf.org/-/media/Files/Publications/TAR/{year}/English"
candidates = [
f"{root}/{stem}.ashx",
f"{root}/{stem}-print-pdf.ashx",
# IMF introduced this suffix for source files in late 2025.
f"{root}/{stem}-source-pdf.ashx",
]
description = (report.get("description") or "").lower()
if "only available in spanish" in description:
spanish_root = (
f"https://www.imf.org/-/media/Files/Publications/TAR/{year}/Spanish"
)
spanish_stem = f"tarsa{year}{number:03d}"
candidates.extend(
[
f"{spanish_root}/{spanish_stem}.ashx",
f"{spanish_root}/{spanish_stem}-print-pdf.ashx",
f"{spanish_root}/{spanish_stem}-source-pdf.ashx",
]
)
return candidates
# Legacy Staff Country Reports used crYYN.pdf, with at least two digits for N.
code = f"cr{year % 100:02d}{number:02d}"
candidates = [
f"https://www.imf.org/external/pubs/ft/scr/{year}/{code}.pdf",
(
"https://www.imf.org/-/media/Websites/IMF/imported-full-text-pdf/"
f"external/pubs/ft/scr/{year}/_{code}.ashx"
),
]
# A January 2023 release made a historical Mozambique TA collection public
# under sequential stock numbers rather than Country Report numbers.
iso_codes = {str(value).upper() for value in report.get("iso_codes", [])}
stock_sequence = None
if year == 2023 and "MOZ" in iso_codes:
if 9 <= number <= 26:
stock_sequence = number - 8
elif 45 <= number <= 47:
stock_sequence = number - 26
if stock_sequence is not None:
stock_suffix = f"2023{stock_sequence:03d}.ashx"
# The historical collection mixes English and Portuguese source files.
candidates[0:0] = [
"https://www.imf.org/-/media/Files/Publications/CR/2023/English/"
f"1MOZEA{stock_suffix}",
"https://www.imf.org/-/media/Files/Publications/CR/2023/Portuguese/"
f"1MOZPA{stock_suffix}",
]
# This regional issue has no ISO code or archived page in the source index.
if year == 2022 and number == 353 and report.get("title", "").startswith(
"Eastern Caribbean Currency Union:"
):
candidates.insert(
0,
"https://www.imf.org/-/media/Files/Publications/CR/2022/English/"
"1ECCEA2022003.ashx",
)
return candidates
class PDFLinkParser(html.parser.HTMLParser):
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.links: list[str] = []
def handle_starttag(
self, tag: str, attrs: list[tuple[str, str | None]]
) -> None:
values = {name.lower(): value for name, value in attrs if value is not None}
if tag.lower() in {"a", "link"} and values.get("href"):
self.links.append(values["href"])
if tag.lower() == "meta":
name = (values.get("name") or values.get("property") or "").lower()
if "pdf" in name and values.get("content"):
self.links.append(values["content"])
def extract_pdf_links(html: bytes, page_url: str) -> list[str]:
text = html.decode("utf-8", errors="replace")
parser = PDFLinkParser()
parser.feed(text)
links: list[str] = []
for href in parser.links:
url = urllib.parse.urljoin(page_url, href.strip())
lowered = url.lower()
if any(hint in lowered for hint in PDF_LINK_HINTS):
links.append(url)
# Older issue pages sometimes displayed a stock number but deliberately had
# no PDF anchor. IMF media filenames use that stock number verbatim.
stock_numbers = re.findall(
r"Stock\s+No\s*:</p>\s*<p[^>]*>\s*([A-Z0-9-]+)",
text,
flags=re.IGNORECASE,
)
language_names = {
"E": "English",
"F": "French",
"P": "Portuguese",
"S": "Spanish",
}
for stock in stock_numbers:
stock = stock.strip().upper()
match = re.fullmatch(r"1[A-Z]{3}([EFPS])A(\d{4})\d{3}", stock)
if match:
language = language_names[match.group(1)]
year = match.group(2)
links.append(
"https://www.imf.org/-/media/Files/Publications/CR/"
f"{year}/{language}/{stock}.ashx"
)
# Prefer original IMF source files, while preserving page order within a class.
def priority(url: str) -> tuple[int, str]:
lowered = url.lower()
if "imf.org/-/media/" in lowered or "imf.org/~/media/" in lowered:
return 0, lowered
if "imf.org/external/pubs/" in lowered:
return 1, lowered
if "elibrary.imf.org" in lowered:
return 2, lowered
return 3, lowered
return sorted(dict.fromkeys(links), key=priority)
@dataclasses.dataclass(frozen=True)
class Capture:
timestamp: str
original: str
@property
def replay_url(self) -> str:
return f"https://web.archive.org/web/{self.timestamp}id_/{self.original}"
def replay_for(self, source_url: str) -> str:
return f"https://web.archive.org/web/{self.timestamp}id_/{source_url}"
class WaybackResolver:
"""Locate archived publication pages and recover their original PDF links."""
CDX_ENDPOINT = "https://web.archive.org/cdx/search/cdx"
PREFIXES = {
"tar": "www.imf.org/en/Publications/technical-assistance-reports/Issues/*",
"cr": "www.imf.org/en/Publications/CR/Issues/*",
}
def __init__(self, client: HttpClient, manifest_dir: Path, refresh: bool = False) -> None:
self.client = client
self.manifest_dir = manifest_dir
self.refresh = refresh
self.by_page_id: dict[str, list[Capture]] = defaultdict(list)
self.by_url: dict[str, list[Capture]] = defaultdict(list)
self._exact_lock = threading.Lock()
self._prepare_lock = threading.Lock()
self._prepared = False
def _cdx_url(self, **params: str) -> str:
return f"{self.CDX_ENDPOINT}?{urllib.parse.urlencode(params)}"
def prepare(self) -> None:
with self._prepare_lock:
if self._prepared:
return
self.manifest_dir.mkdir(parents=True, exist_ok=True)
for kind, prefix in self.PREFIXES.items():
path = self.manifest_dir / f"wayback_{kind}_cdx.json"
if self.refresh or not path.exists():
url = self._cdx_url(
url=prefix,
output="json",
filter="statuscode:200",
fl="timestamp,original",
collapse="urlkey",
limit="100000",
)
print(f"wayback: fetching {kind} URL index", file=sys.stderr)
body, _, _ = self.client.get_bytes(url, timeout=300)
path.write_bytes(body)
self._index_rows(json.loads(path.read_text(encoding="utf-8")))
self._prepared = True
def _index_rows(self, rows: Any) -> None:
if not rows:
return
header = rows[0]
for values in rows[1:]:
row = dict(zip(header, values))
if not row.get("timestamp") or not row.get("original"):
continue
capture = Capture(row["timestamp"], row["original"])
page_id = page_numeric_id(capture.original)
if page_id:
self.by_page_id[page_id].append(capture)
self.by_url[normalized_url_key(capture.original)].append(capture)
def _exact_captures(self, page_url: str) -> list[Capture]:
# Keep exact CDX calls serialized and gently rate-limited by HttpClient.
with self._exact_lock:
url = self._cdx_url(
url=page_url,
output="json",
filter="statuscode:200",
fl="timestamp,original",
collapse="digest",
limit="10",
)
try:
rows = self.client.get_json(url, timeout=120)
except Exception:
return []
if not rows:
return []
header = rows[0]
return [
Capture(row["timestamp"], row["original"])
for values in rows[1:]
if (row := dict(zip(header, values))).get("timestamp")
and row.get("original")
]
def captures_for(self, page_url: str) -> list[Capture]:
self.prepare()
page_id = page_numeric_id(page_url)
captures = list(self.by_page_id.get(page_id or "", []))
captures.extend(self.by_url.get(normalized_url_key(page_url), []))
if not captures:
captures = self._exact_captures(page_url)
unique = {(capture.timestamp, capture.original): capture for capture in captures}
return sorted(unique.values(), key=lambda capture: capture.timestamp, reverse=True)
def pdf_candidates(
self, page_url: str
) -> tuple[list[str], Capture | None, list[str]]:
errors: list[str] = []
for capture in self.captures_for(page_url):
try:
body, _, _ = self.client.get_bytes(capture.replay_url, timeout=180)
links = extract_pdf_links(body, capture.original)
if links:
return links, capture, errors
errors.append(f"{capture.replay_url}: no PDF link")
except Exception as exc:
errors.append(f"{capture.replay_url}: {type(exc).__name__}: {exc}")
return [], None, errors
def file_sha256(path: Path) -> tuple[int, str]:
digest = hashlib.sha256()
size = 0
with path.open("rb") as source:
if source.read(5) != b"%PDF-":
raise NotPDFError(f"existing file is not a PDF: {path}")
source.seek(0)
for chunk in iter(lambda: source.read(1024 * 1024), b""):
digest.update(chunk)
size += len(chunk)
return size, digest.hexdigest()
def concise_error(exc: Exception) -> str:
if isinstance(exc, urllib.error.HTTPError):
return f"HTTP {exc.code}"
return f"{type(exc).__name__}: {exc}"
def download_one(
report: dict[str, Any],
*,
client: HttpClient,
resolver: WaybackResolver,
pdf_dir: Path,
refresh: bool,
previous: dict[str, Any] | None = None,
) -> dict[str, Any]:
report_id = report["report_id"]
destination = pdf_dir / f"{report_id}.pdf"
started = utc_now()
if destination.exists() and not refresh:
try:
size, sha256 = file_sha256(destination)
if previous and previous.get("sha256") not in {None, sha256}:
raise ScraperError(
f"raw PDF hash changed for {report_id}: "
f"manifest={previous['sha256']} disk={sha256}"
)
return {
**(previous or {}),
"report_id": report_id,
"status": "existing",
"verified_at": started,
"local_path": destination.as_posix(),
"bytes": size,
"sha256": sha256,
"source_page_url": report["source_page_url"],
}
except NotPDFError:
destination.unlink(missing_ok=True)
attempts: list[dict[str, str]] = []
direct_candidates = deterministic_pdf_candidates(report)
for candidate in direct_candidates:
try:
result = client.download_pdf(candidate, destination)
return {
"report_id": report_id,
"status": "downloaded",
"attempted_at": started,
"local_path": destination.as_posix(),
"source_page_url": report["source_page_url"],
"discovery_method": "deterministic_url",
"attempts": attempts,
**result,
}
except Exception as exc:
attempts.append({"url": candidate, "error": concise_error(exc)})
archive_candidates, capture, archive_errors = resolver.pdf_candidates(
report["source_page_url"]
)
attempts.extend({"url": "wayback-page", "error": error} for error in archive_errors)
for candidate in archive_candidates:
try:
result = client.download_pdf(candidate, destination)
return {
"report_id": report_id,
"status": "downloaded",
"attempted_at": started,
"local_path": destination.as_posix(),
"source_page_url": report["source_page_url"],
"discovery_method": "archived_publication_page",
"archive_page_url": capture.replay_url if capture else None,
"attempts": attempts,
**result,
}
except Exception as exc:
attempts.append({"url": candidate, "error": concise_error(exc)})
# If the IMF origin no longer serves the discovered PDF, recover the exact
# source bytes through the same archived page capture.
if capture:
for candidate in archive_candidates:
archived_candidate = capture.replay_for(candidate)
try:
result = client.download_pdf(archived_candidate, destination)
return {
"report_id": report_id,
"status": "downloaded",
"attempted_at": started,
"local_path": destination.as_posix(),
"source_page_url": report["source_page_url"],
"source_pdf_url": candidate,
"archive_pdf_url": archived_candidate,
"discovery_method": "internet_archive_pdf_replay",
"archive_page_url": capture.replay_url,
"attempts": attempts,
**{
key: value
for key, value in result.items()
if key != "source_pdf_url"
},
}
except Exception as exc:
attempts.append({"url": archived_candidate, "error": concise_error(exc)})
return {
"report_id": report_id,
"status": "failed",
"attempted_at": started,
"local_path": destination.as_posix(),
"source_page_url": report["source_page_url"],
"attempts": attempts,
}
def download_reports(
inventory: Sequence[dict[str, Any]],
*,
raw_dir: Path,
client: HttpClient,
workers: int,
refresh: bool,
) -> list[dict[str, Any]]:
manifest_dir = raw_dir / "manifests"
pdf_dir = raw_dir / "pdfs"
resolver = WaybackResolver(client, manifest_dir, refresh=False)
previous_manifest = {
row["report_id"]: row
for row in jsonl_load(manifest_dir / "download_manifest.jsonl")
}
results: dict[str, dict[str, Any]] = {}
completed = 0
total = len(inventory)
with concurrent.futures.ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
futures = {
pool.submit(
download_one,
report,
client=client,
resolver=resolver,
pdf_dir=pdf_dir,
refresh=refresh,
previous=previous_manifest.get(report["report_id"]),
): report
for report in inventory
}
for future in concurrent.futures.as_completed(futures):
report = futures[future]
try:
result = future.result()
except Exception as exc: # Keep the full run alive and record the failure.
result = {
"report_id": report["report_id"],
"status": "failed",
"attempted_at": utc_now(),
"source_page_url": report["source_page_url"],
"local_path": (pdf_dir / f"{report['report_id']}.pdf").as_posix(),
"attempts": [
{"url": "internal", "error": concise_error(exc)}
],
}
results[report["report_id"]] = result
completed += 1
print(
f"download: {completed}/{total} {result['status']}: "
f"{report['report_id']}",
file=sys.stderr,
)
ordered = [results[report["report_id"]] for report in inventory]
jsonl_dump(manifest_dir / "download_manifest.jsonl", ordered)
counts = Counter(result["status"] for result in ordered)
successful = [result for result in ordered if result["status"] != "failed"]
by_hash: dict[str, list[str]] = defaultdict(list)
for result in successful:
by_hash[result["sha256"]].append(result["report_id"])
duplicate_groups = [
{"sha256": sha256, "report_ids": report_ids}
for sha256, report_ids in sorted(by_hash.items())
if len(report_ids) > 1
]
summary = {
"updated_at": utc_now(),
"complete": len(successful) == len(inventory),
"inventory_count": len(inventory),
"status_counts": dict(sorted(counts.items())),
"discovery_method_counts": dict(
sorted(
Counter(
result.get("discovery_method") or "unknown" for result in successful
).items()
)
),
"pdf_count": len(successful),
"unique_pdf_sha256_count": len(by_hash),
"exact_duplicate_sha256_groups": duplicate_groups,
"total_bytes": sum(result.get("bytes", 0) for result in successful),
"failed_report_ids": [
result["report_id"] for result in ordered if result["status"] == "failed"
],
}
json_dump(manifest_dir / "download_summary.json", summary)
return ordered
def check_robots(client: HttpClient, raw_dir: Path) -> None:
"""Snapshot robots.txt and fail if the target path later becomes disallowed."""
body, final_url, _ = client.get_bytes(ROBOTS_URL)
text = body.decode("utf-8", errors="replace")
path = raw_dir / "manifests" / "robots.txt"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
# The current robots file only disallows unrelated /external paths. This
# conservative check catches a future blanket disallow before acquisition.
disallows = [
line.split(":", 1)[1].strip()
for line in text.splitlines()
if line.lower().startswith("disallow:")
]
target_path = urllib.parse.urlsplit(LANDING_PAGE).path
for disallow in disallows:
if disallow == "/" or (disallow and target_path.startswith(disallow)):
raise ScraperError(
f"robots.txt at {final_url} disallows target path {target_path}"
)
def run_inventory(args: argparse.Namespace, client: HttpClient) -> list[dict[str, Any]]:
raw_dir = args.raw_dir
check_robots(client, raw_dir)
token = args.token or os.environ.get("IMF_COVEO_TOKEN") or DEFAULT_COVEO_TOKEN
inventory, metadata = fetch_inventory(client, token, limit=args.limit)
manifest_dir = raw_dir / "manifests"
jsonl_dump(manifest_dir / "inventory.jsonl", inventory)
json_dump(manifest_dir / "inventory_summary.json", metadata)
print(
f"saved {len(inventory)} inventory records to "
f"{manifest_dir / 'inventory.jsonl'}",
file=sys.stderr,
)
return inventory
def build_parser() -> argparse.ArgumentParser:
common = argparse.ArgumentParser(add_help=False)
common.add_argument(
"--raw-dir", type=Path, default=Path("data/raw"), help="raw data root"
)
common.add_argument(
"--user-agent", default=DEFAULT_USER_AGENT, help="HTTP User-Agent"
)
common.add_argument(
"--delay",
type=float,
default=0.2,
help="minimum delay in seconds between requests to the same host",
)
common.add_argument("--retries", type=int, default=3)
parser = argparse.ArgumentParser(
description="Acquire IMF technical-assistance report PDFs"
)
subparsers = parser.add_subparsers(dest="command", required=True)
inventory = subparsers.add_parser(
"inventory", parents=[common], help="snapshot the IMF report inventory"
)
inventory.add_argument("--token", help="override the public Coveo search token")
inventory.add_argument("--limit", type=int, help="save only N reports (for tests)")
download = subparsers.add_parser(
"download", parents=[common], help="download PDFs from an existing inventory"
)
download.add_argument("--workers", type=int, default=4)
download.add_argument("--refresh", action="store_true", help="redownload PDFs")
download.add_argument("--allow-partial", action="store_true")
download.add_argument("--limit", type=int, help="download only N reports")
all_command = subparsers.add_parser(
"all", parents=[common], help="snapshot inventory, then download all PDFs"
)
all_command.add_argument("--token", help="override the public Coveo search token")
all_command.add_argument("--workers", type=int, default=4)
all_command.add_argument("--refresh", action="store_true", help="redownload PDFs")
all_command.add_argument("--allow-partial", action="store_true")
all_command.add_argument("--limit", type=int, help="process only N reports")
return parser
def main(argv: Sequence[str] | None = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
client = HttpClient(
user_agent=args.user_agent,
minimum_delay=args.delay,
retries=args.retries,
)
if args.command in {"inventory", "all"}:
inventory = run_inventory(args, client)
if args.command == "inventory":
return 0
else:
inventory_path = args.raw_dir / "manifests" / "inventory.jsonl"
inventory = jsonl_load(inventory_path)
if not inventory:
parser.error(f"no inventory found at {inventory_path}; run inventory first")
if args.limit is not None:
inventory = inventory[: args.limit]
results = download_reports(
inventory,
raw_dir=args.raw_dir,
client=client,
workers=args.workers,
refresh=args.refresh,
)
failures = [result for result in results if result["status"] == "failed"]
if failures:
print(
f"{len(failures)} report(s) failed; see "
f"{args.raw_dir / 'manifests' / 'download_manifest.jsonl'}",
file=sys.stderr,
)
return 0 if args.allow_partial else 1
print(f"complete: {len(results)} PDFs", file=sys.stderr)
return 0
if __name__ == "__main__":
raise SystemExit(main())