Download _scripts/fetch_pdfs.py from imecai/cl-agentic-vault: direct link, hf CLI and curl.
- Browser
- Download file 3.62 kB
-
https://huggingface.co/datasets/imecai/cl-agentic-vault/resolve/main/_scripts/fetch_pdfs.py
- Command line
-
hf download hf://datasets/imecai/cl-agentic-vault/_scripts/fetch_pdfs.py
-
curl -L -o fetch_pdfs.py https://huggingface.co/datasets/imecai/cl-agentic-vault/resolve/main/_scripts/fetch_pdfs.py
3.62 kB
| #!/usr/bin/env python3 | |
| """Download the papers' PDFs into pdf/<slug>.pdf from arXiv. | |
| PDFs are not shipped with the vault (most arXiv papers carry arXiv's default | |
| license, which does not allow redistribution), so each reader fetches their | |
| own copies from the source. Every paper note with an `arxiv:` id is fetched | |
| from arxiv.org, 3 s apart (arXiv's rate limit); existing files are skipped. | |
| Notes without an arXiv id are listed at the end with their venue, to get by | |
| hand (OpenReview ones: _scripts/fetch_openreview_pdf.py, own credentials). | |
| python3 _scripts/fetch_pdfs.py # everything missing | |
| python3 _scripts/fetch_pdfs.py --dry-run # list, download nothing | |
| python3 _scripts/fetch_pdfs.py --only kirkpatrick2017-ewc wu2019-bic | |
| """ | |
| import argparse | |
| import glob | |
| import os | |
| import re | |
| import time | |
| import urllib.request | |
| VAULT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| PDF = os.path.join(VAULT, "pdf") | |
| def field(fm: str, key: str) -> str: | |
| m = re.search(rf"^{key}:\s*(.*)$", fm, re.M) | |
| return m.group(1).strip().strip("\"'") if m else "" | |
| def load_papers() -> list[dict]: | |
| papers = [] | |
| for path in sorted(glob.glob(os.path.join(VAULT, "papers", "*.md"))): | |
| m = re.match(r"---\n(.*?)\n---", open(path, encoding="utf-8").read(), re.S) | |
| fm = m.group(1) if m else "" | |
| papers.append({"slug": os.path.splitext(os.path.basename(path))[0], | |
| "arxiv": field(fm, "arxiv"), "title": field(fm, "title"), | |
| "venue": field(fm, "venue"), "year": field(fm, "year")}) | |
| return papers | |
| def download(aid: str, dest: str) -> None: | |
| req = urllib.request.Request(f"https://arxiv.org/pdf/{aid}", | |
| headers={"User-Agent": "cl-vault-fetch-pdfs/1.0"}) | |
| with urllib.request.urlopen(req, timeout=60) as r: | |
| data = r.read() | |
| if not data.startswith(b"%PDF"): | |
| raise ValueError("response is not a PDF") | |
| tmp = dest + ".part" | |
| with open(tmp, "wb") as f: | |
| f.write(data) | |
| os.replace(tmp, dest) | |
| def main() -> None: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--only", nargs="+", metavar="SLUG", help="fetch only these papers") | |
| ap.add_argument("--dry-run", action="store_true", help="list what would be fetched") | |
| args = ap.parse_args() | |
| papers = load_papers() | |
| if args.only: | |
| papers = [p for p in papers if p["slug"] in set(args.only)] | |
| os.makedirs(PDF, exist_ok=True) | |
| todo = [p for p in papers if p["arxiv"] | |
| and not os.path.exists(os.path.join(PDF, p["slug"] + ".pdf"))] | |
| manual = [p for p in papers if not p["arxiv"] | |
| and not os.path.exists(os.path.join(PDF, p["slug"] + ".pdf"))] | |
| print(f"{len(papers)} papers · {len(todo)} to fetch from arXiv · {len(manual)} without arXiv id") | |
| ok = failed = 0 | |
| for i, p in enumerate(todo, 1): | |
| dest = os.path.join(PDF, p["slug"] + ".pdf") | |
| if args.dry_run: | |
| print(f" would fetch {p['arxiv']:>12} -> pdf/{p['slug']}.pdf") | |
| continue | |
| try: | |
| download(p["arxiv"], dest) | |
| ok += 1 | |
| print(f" [{i}/{len(todo)}] {p['slug']}") | |
| except Exception as e: | |
| failed += 1 | |
| print(f" [{i}/{len(todo)}] FAILED {p['slug']} ({p['arxiv']}): {e}") | |
| time.sleep(3) | |
| if not args.dry_run: | |
| print(f"fetched {ok}, failed {failed}") | |
| if manual: | |
| print("\nNo arXiv id, get by hand:") | |
| for p in manual: | |
| print(f" {p['slug']}: {p['title']} ({p['venue']}, {p['year']})") | |
| if __name__ == "__main__": | |
| main() | |