| |
| """Resolve unique DOIs via Crossref REST API. |
| |
| Resumable: results are appended to registry/crossref_resolved.jsonl as they |
| arrive; on rerun, DOIs already present there are skipped. |
| """ |
| import json |
| import re |
| import sys |
| import time |
| from pathlib import Path |
| from urllib.parse import quote |
|
|
| import httpx |
|
|
| REG = Path("/Users/dmpantiu/copernicus_mcp/publications/registry") |
| IN_FILE = REG / "unique_dois.jsonl" |
| OUT_FILE = REG / "crossref_resolved.jsonl" |
|
|
| UA = ("copernicus-rag-registry/1.0 " |
| "(https://marine.copernicus.eu EQC reference registry; " |
| "mailto:delon.riina@gmail.com)") |
| RATE_DELAY = 0.5 |
| MAX_RETRIES = 4 |
| JATS_TAG_RE = re.compile(r"<[^>]+>") |
|
|
|
|
| def parse_message(msg: dict) -> dict: |
| title = (msg.get("title") or [None])[0] |
| journal = (msg.get("container-title") or [None])[0] |
| year = None |
| for k in ("issued", "published-print", "published-online", "created"): |
| dp = (msg.get(k) or {}).get("date-parts") or [] |
| if dp and dp[0] and dp[0][0]: |
| year = dp[0][0] |
| break |
| authors = [] |
| for a in (msg.get("author") or [])[:6]: |
| fam = a.get("family") or a.get("name") |
| if fam: |
| authors.append(fam) |
| abstract = msg.get("abstract") |
| if abstract: |
| abstract = JATS_TAG_RE.sub(" ", abstract) |
| abstract = " ".join(abstract.split()) |
| return { |
| "title": title, |
| "journal": journal, |
| "year": year, |
| "authors": authors, |
| "abstract": abstract, |
| "type": msg.get("type"), |
| "is_referenced_by_count": msg.get("is-referenced-by-count"), |
| } |
|
|
|
|
| def main(): |
| dois = [json.loads(l)["doi"] for l in open(IN_FILE)] |
| done = set() |
| if OUT_FILE.exists(): |
| for l in open(OUT_FILE): |
| try: |
| done.add(json.loads(l)["doi"]) |
| except (json.JSONDecodeError, KeyError): |
| pass |
| todo = [d for d in dois if d not in done] |
| print(f"{len(dois)} DOIs total, {len(done)} already resolved, {len(todo)} to do", |
| flush=True) |
|
|
| client = httpx.Client( |
| headers={"User-Agent": UA}, |
| timeout=30.0, |
| follow_redirects=True, |
| ) |
| n_ok = n_fail = 0 |
| with open(OUT_FILE, "a") as out: |
| for i, doi in enumerate(todo): |
| url = f"https://api.crossref.org/works/{quote(doi, safe='')}" |
| rec = {"doi": doi, "resolved": False} |
| for attempt in range(MAX_RETRIES): |
| try: |
| r = client.get(url) |
| except httpx.HTTPError as e: |
| if attempt == MAX_RETRIES - 1: |
| rec["error"] = f"network:{type(e).__name__}" |
| time.sleep(2 * (attempt + 1)) |
| continue |
| if r.status_code == 200: |
| try: |
| msg = r.json()["message"] |
| rec.update(parse_message(msg)) |
| rec["resolved"] = True |
| except (ValueError, KeyError): |
| rec["error"] = "bad_json" |
| break |
| if r.status_code == 404: |
| rec["error"] = "not_found" |
| break |
| if r.status_code in (429, 500, 502, 503, 504): |
| wait = float(r.headers.get("Retry-After", 2 * (attempt + 1))) |
| time.sleep(min(wait, 30)) |
| continue |
| rec["error"] = f"http_{r.status_code}" |
| break |
| out.write(json.dumps(rec, ensure_ascii=False) + "\n") |
| out.flush() |
| if rec["resolved"]: |
| n_ok += 1 |
| else: |
| n_fail += 1 |
| if (i + 1) % 50 == 0: |
| print(f" {i+1}/{len(todo)} done (ok={n_ok} fail={n_fail})", |
| flush=True) |
| time.sleep(RATE_DELAY) |
| print(f"finished: ok={n_ok} fail={n_fail}", flush=True) |
|
|
|
|
| if __name__ == "__main__": |
| sys.exit(main()) |
|
|