cl-agentic-vault / _scripts /fetch_openreview_pdf.py
TLESORT's picture
Initial release of the Continual-Learning Ideas Vault (vault commit e3600181)
9542666 verified
Raw History Blame Contribute Delete
5.76 kB
#!/usr/bin/env python3
"""Download OpenReview PDFs through the official authenticated API.
Why this exists: accepted papers on OpenReview are public (`readers: everyone`),
but the site serves an anti-bot HTML interstitial to plain curl/urllib, so
non-interactive download fails. Authenticating through the official API v2 is the
*sanctioned* programmatic path and returns the real PDF. This is not gate-bypass:
the papers are public; the login only gets past the scraping wall via the API the
venue provides for exactly this.
SECURITY — read before use:
* Credentials come ONLY from the environment; they are never written, logged,
printed, or committed:
export OPENREVIEW_USERNAME='you@example.com'
export OPENREVIEW_PASSWORD='...' # your OWN account; rotate any
# credential ever shared in chat
* pdf/ is gitignored, so downloaded PDFs are not committed.
* Refuses to run on a paper whose note is not readable by 'everyone', so it is
mechanically incapable of pulling a still-anonymous/gated PDF.
Usage:
# pull every entry still listed in _no-pdf.md, keyed by its (slug):
python3 _scripts/fetch_openreview_pdf.py --from-no-pdf
# or specific ones: slug=title-or-forumid pairs
python3 _scripts/fetch_openreview_pdf.py \
luo2026-saber="SABER: Continual Learning with Representation Conflict Management"
Writes pdf/<slug>.pdf and reports per-paper status. Read-only w.r.t. the vault
notes; it only creates files under pdf/.
"""
import json
import os
import re
import sys
import time
import urllib.parse
import urllib.request
VAULT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
API = "https://api2.openreview.net"
UA = "Mozilla/5.0 (research vault OpenReview client)"
def _req(url, data=None, token=None, binary=False, timeout=30):
headers = {"User-Agent": UA}
if token:
headers["Authorization"] = f"Bearer {token}"
if data is not None:
data = json.dumps(data).encode()
headers["Content-Type"] = "application/json"
r = urllib.request.Request(url, data=data, headers=headers)
with urllib.request.urlopen(r, timeout=timeout) as resp:
raw = resp.read()
return raw if binary else json.loads(raw)
def login():
user = os.environ.get("OPENREVIEW_USERNAME")
pw = os.environ.get("OPENREVIEW_PASSWORD")
if not user or not pw:
sys.exit("ERROR: set OPENREVIEW_USERNAME and OPENREVIEW_PASSWORD in the "
"environment (never hardcode them). Aborting.")
try:
tok = _req(f"{API}/login", data={"id": user, "password": pw}).get("token")
except Exception as e:
sys.exit(f"ERROR: OpenReview login failed ({e}). Check credentials / rotate the shared one.")
if not tok:
sys.exit("ERROR: login returned no token.")
return tok
def _val(x):
return x.get("value") if isinstance(x, dict) else x
def _toks(s):
return set(re.sub(r"[^a-z0-9 ]", " ", (s or "").lower()).split())
def find_note(token, query):
"""query is a forum id (all hex/alnum, no spaces) or a title string."""
if re.fullmatch(r"[A-Za-z0-9_-]{8,}", query) and " " not in query:
try:
notes = _req(f"{API}/notes?forum={urllib.parse.quote(query)}", token=token).get("notes", [])
if notes:
return notes[0]
except Exception:
pass
notes = _req(f"{API}/notes/search?term={urllib.parse.quote(query)}&limit=5", token=token).get("notes", [])
best, best_ov = None, 0.0
for n in notes:
t = _val(n.get("content", {}).get("title", {})) or ""
ov = len(_toks(query) & _toks(t)) / max(1, len(_toks(query)))
if ov > best_ov:
best, best_ov = n, ov
return best if best_ov >= 0.7 else None
def download(token, slug, query):
n = find_note(token, query)
if not n:
return f"NO MATCH for {slug!r}"
if "everyone" not in (n.get("readers") or []):
return f"SKIP {slug}: note not public (readers={n.get('readers')}) — refusing to fetch a gated PDF"
pdf = _val(n.get("content", {}).get("pdf", {}))
if not pdf:
return f"SKIP {slug}: note has no PDF attachment"
url = pdf if pdf.startswith("http") else f"https://openreview.net{pdf}"
blob = _req(url, token=token, binary=True)
if blob[:5] != b"%PDF-":
return f"FAIL {slug}: got {len(blob)}B non-PDF (bot-wall?) — try the official openreview-py client"
out = os.path.join(VAULT, "pdf", f"{slug}.pdf")
with open(out, "wb") as f:
f.write(blob)
return f"OK {slug}: {len(blob)//1024} KB -> pdf/{slug}.pdf"
def from_no_pdf():
"""Parse `Title (slug)` cells out of _no-pdf.md."""
text = open(os.path.join(VAULT, "_no-pdf.md"), encoding="utf-8").read()
out = {}
for m in re.finditer(r"^\|\s*(.+?)\s*\(([a-z0-9][a-z0-9-]+)\)\s*\|", text, re.M):
out[m.group(2)] = m.group(1).strip()
return out
def main():
args = sys.argv[1:]
jobs = {}
if "--from-no-pdf" in args:
jobs = from_no_pdf()
args = [a for a in args if a != "--from-no-pdf"]
for a in args:
if "=" in a:
k, v = a.split("=", 1)
jobs[k] = v
if not jobs:
sys.exit("nothing to do — pass --from-no-pdf and/or slug=title args")
token = login()
print(f"authenticated; fetching {len(jobs)} paper(s)\n")
ok = 0
for slug, query in jobs.items():
try:
msg = download(token, slug, query)
except Exception as e:
msg = f"ERR {slug}: {e}"
print(" ", msg)
ok += msg.startswith("OK")
time.sleep(1.5)
print(f"\n{ok}/{len(jobs)} downloaded")
if __name__ == "__main__":
main()