"""Download Protocol and SAP PDFs for each row of file.csv. Outputs go to source/downloads/row_<#>/{protocol,sap}.pdf. Skips rows with empty links and rows already downloaded. """ from __future__ import annotations import csv import sys import time import urllib.error import urllib.request from pathlib import Path from urllib.parse import urlparse CSV_PATH = Path(__file__).parent / "file.csv" OUT_ROOT = Path(__file__).parent / "downloads" TIMEOUT = 60 RETRIES = 2 SLEEP_BETWEEN = 0.3 UA = ( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) " "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" ) def paper_link_slug(link: str) -> str: path = urlparse((link or "").strip()).path.strip("/") parts = [p for p in path.split("/") if p] return "_".join(parts[-2:]) if len(parts) >= 2 else "" def download(url: str, dest: Path) -> tuple[bool, str]: if dest.exists() and dest.stat().st_size > 0: return True, "exists" req = urllib.request.Request(url, headers={"User-Agent": UA}) last_err = "" for attempt in range(RETRIES + 1): try: with urllib.request.urlopen(req, timeout=TIMEOUT) as resp: data = resp.read() dest.write_bytes(data) return True, f"ok ({len(data)} bytes)" except urllib.error.HTTPError as e: last_err = f"HTTP {e.code}" except (urllib.error.URLError, TimeoutError) as e: last_err = f"network: {e}" except Exception as e: # noqa: BLE001 last_err = f"error: {e}" time.sleep(1 + attempt) return False, last_err def main(start_row: int = 3) -> None: OUT_ROOT.mkdir(exist_ok=True) with CSV_PATH.open(newline="", encoding="utf-8") as fh: reader = csv.DictReader(fh) for row in reader: num_str = (row.get("#") or "").strip() if not num_str.isdigit(): continue num = int(num_str) if num < start_row: continue protocol = (row.get("Study Protocol Link") or "").strip() sap = (row.get("Protocol+SAP / SAP Link") or "").strip() if not protocol and not sap: print(f"[{num}] skip: no links") continue slug = paper_link_slug(row.get("Paper Link") or "") if not slug: print(f"[{num}] skip: no usable Paper Link") continue row_dir = OUT_ROOT / slug row_dir.mkdir(exist_ok=True) if protocol: ok, msg = download(protocol, row_dir / "protocol.pdf") print(f"[{num}] protocol: {msg}") if not ok: (row_dir / "protocol.error.txt").write_text( f"{protocol}\n{msg}\n", encoding="utf-8" ) time.sleep(SLEEP_BETWEEN) if sap: ok, msg = download(sap, row_dir / "sap.pdf") print(f"[{num}] sap: {msg}") if not ok: (row_dir / "sap.error.txt").write_text( f"{sap}\n{msg}\n", encoding="utf-8" ) time.sleep(SLEEP_BETWEEN) if __name__ == "__main__": start = int(sys.argv[1]) if len(sys.argv) > 1 else 3 main(start_row=start)