"""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
]*>\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())