File size: 4,003 Bytes
0ec8fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#!/usr/bin/env python
"""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          # ~2 req/s
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())