Repository navigation
Expand file tree
/
Copy pathfetch_fulltext.py
More file actions
788 lines (702 loc) · 40 KB
/
Copy pathfetch_fulltext.py
File metadata and controls
788 lines (702 loc) · 40 KB
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
"""Download the full texts of CML publications and PhD theses that are legally available, and record the rest.
Where it looks (in this order, for every document):
1. Each researcher's "Publications" tab on the university site, which links every item to the Leiden repository
(scholarlypublications.universiteitleiden.nl). The repository holds the open copies, including the author
versions deposited under the Taverne amendment ("You share, we take care").
2. PhD theses: the repository's list of all Leiden dissertations (OAI-PMH), filtered to CML (degree granted by the
Institute of Environmental Sciences, or supervised by current CML staff), plus the "Former PhD candidates" on
staff pages.
3. OpenAlex: open copies elsewhere (PubMed Central, arXiv, other repositories, open-access publishers) for papers
the repository does not have.
Only files that are openly downloadable are fetched. Closed, restricted (Leiden login) and embargoed files are not:
they are recorded in data/fulltext/missing.csv with the reason, and the assistant uses their title and abstract.
Output (data/fulltext/, not in git)
documents.json every document: metadata, CML people, where a copy was looked for, and the outcome
pdf/<id>/ downloaded files (theses split in chapters keep one file per chapter)
missing.csv documents without full text: reason, whether an abstract is available, URLs tried
report.md totals by outcome and per researcher
fetch.log what happened, with times
cache/ staff pages, repository records and OpenAlex locations (lets a run resume)
Usage
python3 fetch_fulltext.py everything; resumes where it stopped (first run: a few hours)
python3 fetch_fulltext.py --report only rewrite missing.csv and report.md
python3 fetch_fulltext.py --retry try failed downloads and passed embargoes again
python3 fetch_fulltext.py --refresh re-read staff pages, repository records and the thesis list
python3 fetch_fulltext.py --limit 5 test on the first 5 researchers
Needs requests and beautifulsoup4 (pip install -r requirements.txt) and the OpenAlex key in .env (for step 3).
Run harvest_openalex.py and build_network.py first.
"""
import argparse
import csv
import json
import os
import re
import sys
import time
import unicodedata
import xml.etree.ElementTree as ET
from collections import Counter, defaultdict
from datetime import date, datetime
from pathlib import Path
from urllib.parse import urljoin, urlparse
import requests
from bs4 import BeautifulSoup
import build_network as bn
import harvest_openalex as ho # .env, OpenAlex access with throttling
HERE = Path(__file__).resolve().parent
OUT = HERE / "data" / "fulltext"
CACHE = OUT / "cache"
PDF = OUT / "pdf"
LOG = OUT / "fetch.log"
STAFF_FILE = HERE / "leiden_staff.json"
SITE = os.environ.get("CML_SITE", "https://www.universiteitleiden.nl")
REPO = os.environ.get("LEIDEN_REPO", "https://scholarlypublications.universiteitleiden.nl").rstrip("/")
OAI = REPO + "/oai2"
THESIS_SET = "hdl_1887_9744" # "Dissertations" in the repository's OAI feed
MAX_MB = 80 # skip larger files (theses are usually 5-30 MB)
# The university site blocks unknown clients, so its pages are read like scrape_staff.py does.
SITE_HEADERS = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36", "Accept-Language": "en"}
CONTACT = os.environ.get("OPENALEX_MAILTO", "")
FILE_HEADERS = {"User-Agent": "cml-knowledge-base/0.3 (Leiden University, Institute of Environmental Sciences"
+ (f"; mailto:{CONTACT}" if CONTACT else "") + ")",
"Accept": "application/pdf,*/*;q=0.8"}
SESSION = requests.Session()
# Publication types on the staff pages (Dutch labels from the university's research system) that are not texts
SKIP_TYPES = re.compile(r"audio|visuele|optreden|tv, radio|boekredactie|redactie|interview|lezing|presentatie|"
r"poster|prijs|award", re.I)
# Thesis degree granted by CML (spelling varies over the years, also typos such as "Instititute")
CML_THESIS = re.compile(r"environmental scien|\(cml\)|centrum voor milieu|milieukunde", re.I)
# Thesis files that are not content
SKIP_FILES = re.compile(r"\bcover\b|propositions|stellingen|title ?pages?|^\d+\s*-\s*contents$", re.I)
PARTICLES = {"van", "de", "der", "den", "het", "ten", "ter", "von", "da", "di", "du", "le", "la", "del", "dos", "do"}
DELAY = {"site": 1.0, "repo": 0.5, "other": 1.0}
_last = defaultdict(float)
# ---------------------------------------------------------------- small helpers
def log(msg):
line = f"{datetime.now():%Y-%m-%d %H:%M:%S} {msg}"
print(msg, flush=True)
with open(LOG, "a", encoding="utf-8") as f:
f.write(line + "\n")
def load(path, default):
try:
return json.loads(Path(path).read_text(encoding="utf-8"))
except (OSError, ValueError):
return default
def save(path, data):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=0), encoding="utf-8")
tmp.replace(path)
def fold(s):
return unicodedata.normalize("NFKD", s or "").encode("ascii", "ignore").decode().lower()
def norm_title(t):
return re.sub(r"[^a-z0-9]+", "", fold(re.sub(r"<[^>]+>", "", t or "")))[:90]
def norm_doi(d):
d = (d or "").strip().lower()
d = re.sub(r"^(https?://)?(dx\.)?doi\.org/", "", d)
return d.removeprefix("doi:").strip() or None
def handle_of(url):
m = re.search(r"(?:hdl\.handle\.net|/handle)/1887/(\d+)", url or "")
return m.group(1) if m else None
def person_id(profile_url):
return profile_url.rstrip("/").rsplit("/staffmembers/", 1)[-1]
def name_key(name):
"""'Martina Vijver' / 'Vijver, M.G.' / 'Bodegom, P.M. van' -> ('vijver', 'm') for matching staff to repository names."""
name = fold(name).strip()
if "," in name:
last, first = [x.strip() for x in name.split(",", 1)]
else:
parts = name.split()
if len(parts) < 2:
return None
first, last = parts[0], " ".join(parts[1:])
words = [w for w in re.findall(r"[a-z]+", last) if w not in PARTICLES]
initial = re.findall(r"[a-z]", first)
return (words[-1], initial[0]) if words and initial else None
def polite(kind):
wait = DELAY[kind] - (time.time() - _last[kind])
if wait > 0:
time.sleep(wait)
_last[kind] = time.time()
def fetch(url, kind="other", headers=None, tries=4, stream=False):
"""GET with a pause per kind of site and retries on network or server errors. Returns the response (any status)."""
for i in range(tries):
polite(kind)
try:
r = SESSION.get(url, headers=headers or FILE_HEADERS, timeout=(20, 120), stream=stream, allow_redirects=True)
except (requests.ConnectionError, requests.Timeout) as e:
if i == tries - 1:
raise
log(f" network problem ({type(e).__name__}) for {url}, retrying")
time.sleep(5 * (i + 1))
continue
if r.status_code in (429, 500, 502, 503, 504) and i < tries - 1:
wait = min(float(r.headers.get("retry-after", "0") or 0) or 10 * (i + 1), 300)
log(f" HTTP {r.status_code} from {urlparse(url).hostname}, waiting {int(wait)}s")
time.sleep(wait)
continue
return r
return r
# ---------------------------------------------------------------- 1. staff publication pages
def research_staff():
staff = load(STAFF_FILE, None)
if staff is None:
sys.exit(f"{STAFF_FILE.name} not found: run scrape_staff.py first")
return [p for p in staff if p.get("rank") != "Support staff" and p.get("profile_url")]
def parse_staff_publications(html):
"""The Publications tab: items (link, citation text, type, year) and the theses of former PhD candidates.
The page as served lists them as <ul class="publications"><li data-year=.. data-category=..>; the browser
rebuilds that into year sections (.pub-lists), which is read too, in case the site starts serving that."""
soup = BeautifulSoup(html, "html.parser")
pubs, theses = [], []
def item(li, year, category=""):
a = li.find("a")
meta = li.find(class_="meta")
kind = meta.get_text(" ", strip=True) if meta else ""
if meta:
meta.extract()
href = a.get("href", "") if a else ""
return {"href": href, "handle": handle_of(href), "doi": norm_doi(href) if "doi.org" in href else None,
"citation": re.sub(r"\s+", " ", li.get_text(" ", strip=True)), "type": kind, "category": category,
"year": int(year) if str(year or "").isdigit() else None}
for ul in soup.select("ul.publications"):
if ul.get("data-pubtype", "publication") != "publication":
continue
for li in ul.find_all("li", recursive=False):
pubs.append(item(li, li.get("data-year"), li.get("data-category", "")))
if not pubs:
year = None
for el in soup.select(".pub-lists > *"):
if el.name in ("h2", "h3") and re.fullmatch(r"\d{4}", el.get_text(strip=True)):
year = int(el.get_text(strip=True))
if el.name == "ul" and "pub-items" in (el.get("class") or []):
pubs += [item(li, year) for li in el.find_all("li", recursive=False)]
for ul in soup.select("ul.scientists"):
box = ul.find_parent(class_="box")
head = box.find(["h2", "h3"]) if box else None
if head and "former phd" in head.get_text(" ", strip=True).lower():
for a in ul.find_all("a"):
h = handle_of(a.get("href", ""))
if h:
theses.append({"handle": h, "name": a.get_text(" ", strip=True)})
return pubs, theses
def crawl_staff(staff, refresh=False):
path = CACHE / "staff_pubs.json"
done = {} if refresh else load(path, {})
todo = [p for p in staff if p["profile_url"] not in done]
if todo:
log(f"Step 1: publication lists of {len(todo)} researchers (university site, 1 s apart)")
for n, p in enumerate(todo, 1):
url = p["profile_url"].rstrip("/") + "/publications"
try:
r = fetch(url, "site", SITE_HEADERS)
if r.status_code == 404:
pubs, theses = [], []
elif r.status_code != 200 or "Access blocked" in r.text[:3000]:
log(f" {p['name']}: HTTP {r.status_code}, skipped this time")
continue
else:
pubs, theses = parse_staff_publications(r.text)
except requests.RequestException as e:
log(f" {p['name']}: {type(e).__name__}, skipped this time")
continue
done[p["profile_url"]] = {"name": p["name"], "pubs": pubs, "theses": theses, "read": date.today().isoformat()}
if n % 10 == 0 or n == len(todo):
save(path, done)
log(f" {n}/{len(todo)} researchers read")
save(path, done)
return done
# ---------------------------------------------------------------- 2. repository records and the thesis list
def parse_item(html):
"""A repository record: metadata, abstract, and each file with its access (open / embargo / closed)."""
soup = BeautifulSoup(html, "html.parser")
metas = defaultdict(list)
for m in soup.find_all("meta"):
if (m.get("name") or "").startswith("citation_"):
metas[m["name"]].append(m.get("content", ""))
fields = {}
for dl in soup.select("main dl"):
for dt in dl.find_all("dt"):
dd = dt.find_next_sibling("dd")
if dd is not None:
fields.setdefault(dt.get_text(" ", strip=True).rstrip(":"), dd.get_text(" ", strip=True))
ab = soup.select_one("#abstract")
if ab and ab.find("h3"):
ab.find("h3").extract()
files = []
for doc in soup.select("#documents .document"):
cls = " ".join(doc.get("class") or [])
label_el = doc.select_one(".file_label")
a = label_el.find("a") if label_el else None
emb = doc.select_one(".file_embargo")
lic = doc.select_one(".file_license img")
files.append({
"label": label_el.get_text(" ", strip=True) if label_el else "",
"url": urljoin(REPO + "/", a["href"]) if a and a.get("href") else None,
"access": "open" if "open_access" in cls else "embargo" if ("embargo" in cls or emb) else "closed",
"embargo_until": (re.search(r"\d{4}-\d{2}-\d{2}", emb.get_text()) or [None])[0] if emb else None,
"version": (doc.select_one(".file_version").get_text(" ", strip=True).replace("version:", "").strip()
if doc.select_one(".file_version") else ""),
"licence": lic.get("alt", "") if lic else "",
})
title = (soup.select_one("h1.record-title") or soup.find("h1"))
return {
"title": title.get_text(" ", strip=True) if title else (metas["citation_title"] or [""])[0],
"authors": metas["citation_author"],
"year": int(m.group()) if (m := re.search(r"\d{4}", fields.get("Published", "") or (metas["citation_publication_date"] or [""])[0])) else None,
"type": fields.get("Publication type", ""),
"doi": norm_doi((metas["citation_doi"] or [fields.get("doi", "")])[0]),
"venue": (metas["citation_journal_title"] or [fields.get("Is part of", "")])[0],
"abstract": ab.get_text("\n", strip=True) if ab else (metas["citation_abstract"] or [""])[0],
"keywords": [t.get_text(" ", strip=True) for t in soup.select(".topics .topic")],
"supervisors": fields.get("Supervisor(s)", ""),
"advisors": fields.get("Advisor(s)", ""),
"institution": fields.get("Degree granting institution", ""),
"files": files,
}
def repo_items(handles, refresh=False, retry=False):
path = CACHE / "items.json"
items = {} if refresh else load(path, {})
today = date.today().isoformat()
def stale(h):
it = items.get(h)
if it is None:
return True
# look again when an embargo has passed or the record could not be read last time
return retry and (it.get("error") or any(f["access"] == "embargo" and (f["embargo_until"] or "9") <= today
for f in it.get("files", [])))
todo = [h for h in handles if stale(h)]
if todo:
log(f"Step 4: {len(todo)} repository records (about {len(todo) // 120 + 1} min)")
for n, h in enumerate(todo, 1):
try:
r = fetch(f"{REPO}/handle/1887/{h}", "repo")
items[h] = parse_item(r.text) if r.status_code == 200 else {"error": f"HTTP {r.status_code}", "files": []}
except requests.RequestException as e:
items[h] = {"error": type(e).__name__, "files": []}
items[h]["read"] = today
if n % 50 == 0 or n == len(todo):
save(path, items)
log(f" {n}/{len(todo)} records read")
save(path, items)
return items
def oai_theses(refresh=False):
"""All Leiden dissertations from the repository's OAI feed (Dublin Core), cached."""
path = CACHE / "theses_oai.json"
cached = None if refresh else load(path, None)
if cached is not None:
return cached
log("Step 2: list of Leiden PhD theses (OAI feed, about 150 pages)")
ns = {"o": "http://www.openarchives.org/OAI/2.0/", "dc": "http://purl.org/dc/elements/1.1/"}
out, token, page = [], None, 0
while True:
url = (f"{OAI}?verb=ListRecords&resumptionToken={requests.utils.quote(token)}" if token
else f"{OAI}?verb=ListRecords&metadataPrefix=oai_dc&set={THESIS_SET}")
r = fetch(url, "repo")
if r.status_code != 200:
raise RuntimeError(f"OAI feed: HTTP {r.status_code}")
root = ET.fromstring(r.content)
for rec in root.iter(f"{{{ns['o']}}}record"):
dc = rec.find(".//{http://www.openarchives.org/OAI/2.0/oai_dc/}dc")
if dc is None:
continue
get = lambda tag: [e.text or "" for e in dc.findall(f"dc:{tag}", ns)]
ids = get("identifier")
h = next((handle_of(i) for i in ids if handle_of(i)), None)
if h:
out.append({"handle": h, "title": (get("title") or [""])[0], "creator": get("creator"),
"contributor": get("contributor"), "date": (get("date") or [""])[0],
"description": get("description"), "subject": get("subject")})
tok = root.find(".//o:resumptionToken", ns)
token = tok.text.strip() if tok is not None and tok.text and tok.text.strip() else None
page += 1
if page % 20 == 0:
log(f" {page} pages, {len(out)} theses")
if not token:
break
save(path, out)
log(f" {len(out)} Leiden theses listed")
return out
SENIOR = re.compile(r"professor|lecturer|researcher|postdoc", re.I)
def cml_theses(oai, staff):
"""Theses granted by CML, or supervised by current senior CML staff at the Faculty of Science."""
senior = {name_key(p["name"]) for p in staff if SENIOR.search(p.get("rank", ""))} - {None}
keep = {}
for t in oai:
degree = " ".join(d for d in t["description"] if re.match(r"(ph\.?d|doctor|promotie)", d.strip(), re.I))
supervised = any(name_key(n) in senior for n in t["contributor"])
if CML_THESIS.search(degree) or (supervised and re.search(r"faculty of science", degree, re.I)):
keep[t["handle"]] = t
return keep
# ---------------------------------------------------------------- 3. OpenAlex locations
def openalex_locations(ids, refresh=False):
path = CACHE / "openalex_locations.json"
locs = {} if refresh else load(path, {})
todo = [i for i in ids if i not in locs]
if not todo:
return locs
log(f"Step 3: open-access locations of {len(todo)} papers from OpenAlex")
for k in range(0, len(todo), 50):
chunk = todo[k:k + 50]
r = ho.get(f"{ho.OA}/works", {"filter": "openalex:" + "|".join(chunk), "per-page": 50,
"select": "id,locations,best_oa_location,open_access"})
found = {}
for w in (r.json().get("results", []) if r is not None else []):
found[bn.short(w["id"])] = [{"pdf_url": l.get("pdf_url"), "landing_page_url": l.get("landing_page_url"),
"is_oa": l.get("is_oa"), "version": l.get("version"), "license": l.get("license"),
"source": ((l.get("source") or {}).get("display_name") or ""),
"source_type": ((l.get("source") or {}).get("type") or "")}
for l in w.get("locations") or []]
for i in chunk:
locs[i] = found.get(i, [])
save(path, locs)
return locs
def openalex_by_doi(dois, refresh=False):
"""Papers on staff pages that link only to a DOI and are not among the OpenAlex papers counted for CML
(e.g. before 2010, or under a name OpenAlex did not match): their metadata and open locations."""
path = CACHE / "openalex_extra.json"
got = {} if refresh else load(path, {})
todo = [d for d in dois if d not in got]
if todo:
log(f"Step 3: {len(todo)} papers listed on staff pages but not in the OpenAlex harvest")
for k in range(0, len(todo), 40):
chunk = todo[k:k + 40]
r = ho.get(f"{ho.OA}/works", {"filter": "doi:" + "|".join(chunk), "per-page": 50,
"select": "id,doi,title,publication_year,type,abstract_inverted_index,authorships,primary_location,locations"})
for w in (r.json().get("results", []) if r is not None else []):
d = norm_doi(w.get("doi"))
got[d] = {"id": bn.short(w["id"]), "title": w.get("title") or "", "year": w.get("publication_year"),
"type": w.get("type"), "abstract": ho.abstract_text(w.get("abstract_inverted_index")),
"venue": (((w.get("primary_location") or {}).get("source") or {}).get("display_name") or ""),
"authors": [(a.get("author") or {}).get("display_name") or "" for a in w.get("authorships") or []],
"locations": [{"pdf_url": l.get("pdf_url"), "landing_page_url": l.get("landing_page_url"),
"version": l.get("version"), "license": l.get("license"),
"source": ((l.get("source") or {}).get("display_name") or ""),
"source_type": ((l.get("source") or {}).get("type") or "")} for l in w.get("locations") or []]}
for d in chunk:
got.setdefault(d, None) # not in OpenAlex either
save(path, got)
return got
# ---------------------------------------------------------------- documents
def build_documents(staff, staff_pubs, items, theses, oa_works, p_works, people_csv, locs, extra):
"""One record per document. Id: the OpenAlex id when the document is in OpenAlex (so citations stay [W...]),
otherwise H + repository handle number."""
url_to_pid = {p["profile_url"]: person_id(p["profile_url"]) for p in staff}
aid_to_pid = {p["openalex_id"]: person_id(p["profile_url"]) for p in people_csv if p["openalex_id"]}
staff_by_key = defaultdict(list)
for p in staff:
k = name_key(p["name"])
if k:
staff_by_key[k].append(person_id(p["profile_url"]))
docs, by_doi, by_title = {}, {}, {}
# OpenAlex papers that count for current staff
for wid, w in oa_works.items():
auths = w.get("authorships") or []
people = []
for a in auths:
aid = bn.short((a.get("author") or {}).get("id"))
if aid in aid_to_pid and wid in p_works.get(aid, ()):
people.append({"id": aid_to_pid[aid], "role": a.get("author_position") or "author"})
d = {"id": wid, "kind": "thesis" if w.get("type") == "dissertation" else "paper", "title": w.get("title") or "",
"year": w.get("publication_year"), "doi": norm_doi(w.get("doi")), "handles": [], "type": w.get("type"),
"has_abstract": bool(w.get("abstract")), "people": people, "oa_status": (w.get("open_access") or {}).get("oa_status")}
docs[wid] = d
if d["doi"]:
by_doi[d["doi"]] = wid
by_title.setdefault(norm_title(d["title"]), []).append(wid)
for l in locs.get(wid, []): # OpenAlex knows the paper is in the Leiden repository
h = handle_of(l.get("landing_page_url"))
if h and h not in d["handles"]:
d["handles"].append(h)
def attach(handle, meta, person=None, role="author", year=None):
it = items.get(handle) or {}
doi = it.get("doi") or meta.get("doi")
wid = by_doi.get(doi) if doi else None
if not wid:
t = norm_title(it.get("title") or meta.get("title") or "")
y = it.get("year") or year
cands = [c for c in by_title.get(t, []) if not y or not docs[c]["year"] or abs(docs[c]["year"] - y) <= 1] if len(t) > 20 else []
wid = cands[0] if cands else None
if not wid:
wid = f"H{handle}"
if wid not in docs:
is_thesis = "thesis" in (it.get("type") or "").lower() or meta.get("thesis")
docs[wid] = {"id": wid, "kind": "thesis" if is_thesis else "paper",
"title": it.get("title") or meta.get("title") or "", "year": it.get("year") or year,
"doi": doi, "handles": [], "type": it.get("type") or meta.get("type", ""),
"has_abstract": bool(it.get("abstract")), "people": [], "oa_status": None}
d = docs[wid]
if handle not in d["handles"]:
d["handles"].append(handle)
d["has_abstract"] = d["has_abstract"] or bool(it.get("abstract"))
if "thesis" in (it.get("type") or "").lower():
d["kind"] = "thesis"
if person and all(x["id"] != person for x in d["people"]):
d["people"].append({"id": person, "role": role})
return d
# items on staff publication pages
unmatched = []
for url, entry in staff_pubs.items():
pid = url_to_pid.get(url)
for pub in entry["pubs"]:
if SKIP_TYPES.search(pub["type"] or "") or pub.get("category") == "Popular":
continue
if pub["handle"]:
attach(pub["handle"], {"title": pub["citation"], "type": pub["type"],
"thesis": "dissert" in (pub["type"] or "").lower()}, pid, "author", pub["year"])
elif pub["doi"] and (pub["doi"] in by_doi or extra.get(pub["doi"])):
if pub["doi"] not in by_doi: # found in OpenAlex by its DOI
e = extra[pub["doi"]]
docs[e["id"]] = {"id": e["id"], "kind": "thesis" if e["type"] == "dissertation" else "paper",
"title": e["title"], "year": e["year"], "doi": pub["doi"], "handles": [],
"type": e["type"], "has_abstract": bool(e["abstract"]), "people": [], "oa_status": None,
"meta": {k: e[k] for k in ("title", "year", "type", "abstract", "venue", "authors")}}
locs[e["id"]] = e["locations"]
by_doi[pub["doi"]] = e["id"]
d = docs[by_doi[pub["doi"]]]
if all(x["id"] != pid for x in d["people"]):
d["people"].append({"id": pid, "role": "author"})
elif pub["doi"]:
unmatched.append({"person": entry["name"], "citation": pub["citation"], "doi": pub["doi"], "year": pub["year"]})
for t in entry["theses"]: # former PhD candidates: this person supervised the thesis
attach(t["handle"], {"title": "", "thesis": True}, pid, "supervisor")
# CML theses from the repository list (author and supervisors matched to current staff)
for h, t in theses.items():
d = attach(h, {"title": t["title"], "thesis": True})
d["kind"] = "thesis"
it = items.get(h) or {}
roles = [(n, "author") for n in t["creator"]]
roles += [(n, "supervisor") for n in re.split(r";\s*", it.get("supervisors") or "") if n]
roles += [(n, "co-supervisor") for n in re.split(r";\s*", it.get("advisors") or "") if n]
for n, role in roles:
ids = staff_by_key.get(name_key(n) or ("", ""), [])
if len(ids) == 1 and all(x["id"] != ids[0] for x in d["people"]):
d["people"].append({"id": ids[0], "role": role})
d["thesis_author"] = (t["creator"] or [""])[0]
d["defence"] = t["date"]
for d in docs.values():
d.setdefault("thesis_author", "")
return docs, unmatched
def candidates(doc, items, locs):
"""Places to download a copy from, best first: Leiden repository, then open repositories, then publishers."""
out, notes = [], []
for h in doc["handles"]:
it = items.get(h) or {}
files = it.get("files") or []
if not files:
notes.append("Leiden repository: metadata only, no file" if not it.get("error") else f"Leiden repository: {it['error']}")
opened = [f for f in files if f["access"] == "open" and f["url"]]
if doc["kind"] == "thesis":
full = [f for f in opened if re.search(r"full ?text", f["label"], re.I)]
parts = full[:1] or [f for f in opened if not SKIP_FILES.search(re.sub(r"^\d+\s*-\s*", "", f["label"]))]
else:
full = [f for f in opened if re.search(r"full ?text", f["label"], re.I)]
parts = (full or opened)[:1]
if parts:
out.append({"from": "Leiden repository", "files": [{"url": f["url"], "label": f["label"]} for f in parts],
"licence": parts[0]["licence"], "version": parts[0]["version"]})
for f in files:
if f["access"] == "embargo":
notes.append(f"Leiden repository: embargo until {f['embargo_until'] or '?'}")
elif f["access"] == "closed":
notes.append("Leiden repository: restricted (closed access)")
rank = lambda l: (0 if re.search(r"pubmed central|europe pmc", l["source"], re.I) else
1 if l["source_type"] == "repository" else 2)
for l in sorted([l for l in locs.get(doc["id"], []) if l.get("pdf_url")], key=rank):
if handle_of(l.get("landing_page_url")) or "universiteitleiden" in (l["pdf_url"] or ""):
continue # the Leiden repository is read directly above
out.append({"from": l["source"] or urlparse(l["pdf_url"]).hostname, "files": [{"url": l["pdf_url"], "label": "full text"}],
"licence": l.get("license") or "", "version": l.get("version") or ""})
if not out and not notes:
notes.append("no open copy found (OpenAlex lists no open PDF)" if doc["id"].startswith("W") else "no file found")
return out, list(dict.fromkeys(notes))
def download(url, dest):
"""Save url to dest if it is a PDF. Returns (ok, reason)."""
kind = "repo" if url.startswith(REPO) else "other"
try:
r = fetch(url, kind, stream=True)
except requests.RequestException as e:
return False, f"network error ({type(e).__name__})"
with r:
if r.status_code != 200:
return False, f"HTTP {r.status_code}" + (" (blocked by the site)" if r.status_code in (401, 403) else "")
first = next(r.iter_content(8192), b"")
if not first.lstrip().startswith(b"%PDF"):
return False, "not a PDF (the site sent a web page instead)"
size, dest = len(first), Path(dest)
dest.parent.mkdir(parents=True, exist_ok=True)
tmp = dest.with_suffix(".part")
with open(tmp, "wb") as f:
f.write(first)
for chunk in r.iter_content(1 << 16):
size += len(chunk)
if size > MAX_MB << 20:
f.close()
tmp.unlink(missing_ok=True)
return False, f"larger than {MAX_MB} MB, skipped"
f.write(chunk)
tmp.replace(dest)
return True, f"{size // 1024} KB"
def fetch_documents(docs, items, locs, retry=False):
path = OUT / "downloads.json"
state = load(path, {})
today = date.today().isoformat()
def todo(d):
s = state.get(d["id"])
if s is None:
return True
if s["status"] == "downloaded":
return not all((OUT / f["path"]).exists() for f in s["files"])
return retry # failed, or embargo that may have passed
queue = [d for d in docs.values() if todo(d)]
if queue:
log(f"Step 5: looking for full texts of {len(queue)} documents")
for n, d in enumerate(queue, 1):
cands, notes = candidates(d, items, locs)
tried, result = [], None
for c in cands:
files, ok = [], True
for k, f in enumerate(c["files"], 1):
rel = f"pdf/{d['id']}/{k:02d}.pdf"
good, why = download(f["url"], OUT / rel)
tried.append(f"{f['url']} -> {why}")
if not good:
ok = False
break
files.append({"path": rel, "label": f["label"], "url": f["url"]})
if ok and files:
result = {"status": "downloaded", "source": c["from"], "files": files, "licence": c["licence"],
"version": c["version"]}
break
if result is None:
reason = "; ".join(notes) or "download failed"
if tried:
reason = (reason + "; " if notes else "") + "open copies found but none could be downloaded"
result = {"status": "missing", "reason": reason, "files": []}
result.update(tried=tried, checked=today)
state[d["id"]] = result
if n % 25 == 0 or n == len(queue):
save(path, state)
got = sum(1 for s in state.values() if s["status"] == "downloaded")
log(f" {n}/{len(queue)} checked; {got} full texts so far")
save(path, state)
return state
# ---------------------------------------------------------------- report
def write_report(docs, state, staff, unmatched=()):
names = {person_id(p["profile_url"]): p["name"] for p in staff}
rows, per = [], defaultdict(Counter)
for d in docs.values():
s = state.get(d["id"], {"status": "missing", "reason": "not checked yet", "tried": []})
d["fulltext"] = {k: s.get(k) for k in ("status", "source", "files", "licence", "version", "reason")}
for p in d["people"]:
per[p["id"]]["docs"] += 1
per[p["id"]]["full"] += s["status"] == "downloaded"
if s["status"] != "downloaded":
rows.append({"id": d["id"], "kind": d["kind"], "year": d["year"] or "", "title": d["title"], "doi": d["doi"] or "",
"repository": " ".join(f"https://hdl.handle.net/1887/{h}" for h in d["handles"]),
"cml_people": "; ".join(names.get(p["id"], p["id"]) for p in d["people"]),
"reason": s.get("reason", ""), "abstract_used": "yes" if d["has_abstract"] else "no (title only)",
"tried": " | ".join(s.get("tried", []))})
for u in unmatched:
rows.append({"id": "", "kind": "paper", "year": u["year"] or "", "title": u["citation"], "doi": u["doi"],
"repository": "", "cml_people": u["person"], "abstract_used": "no (not in the index)",
"reason": "listed on the staff page with a DOI that neither OpenAlex nor the Leiden repository knows",
"tried": ""})
save(OUT / "documents.json", list(docs.values()))
rows.sort(key=lambda r: (r["reason"], -(r["year"] or 0)))
with open(OUT / "missing.csv", "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0].keys()) if rows else ["id"])
w.writeheader()
w.writerows(rows)
total = len(docs)
got = sum(1 for d in docs.values() if d["fulltext"]["status"] == "downloaded")
by_kind = Counter((d["kind"], d["fulltext"]["status"] == "downloaded") for d in docs.values())
sources = Counter(d["fulltext"]["source"] for d in docs.values() if d["fulltext"]["status"] == "downloaded")
reasons = Counter()
for r in rows:
r0 = r["reason"]
reasons["embargo" if "embargo" in r0 else "restricted in the Leiden repository" if "restricted" in r0
else "open copy exists but could not be downloaded (publisher site blocked or not a PDF)" if "could not be downloaded" in r0
else "metadata only in the Leiden repository" if "metadata only" in r0
else "no open copy found" if "no open copy" in r0 or "no file" in r0
else "on a staff page, but unknown to OpenAlex and the repository (not indexed)" if "neither OpenAlex" in r0
else r0[:60]] += 1
lines = [f"# Full-text coverage ({date.today().isoformat()})", "",
f"{got} of {total} indexed documents have full text ({100 * got // max(total, 1)}%). "
f"For the other {total - got} the assistant uses the title and abstract "
f"({sum(1 for r in rows if r['abstract_used'].startswith('yes'))} have an abstract). "
+ (f"{len(unmatched)} more items on staff pages could not be identified and are not indexed. " if unmatched else "") +
"Details per document: `missing.csv`.", "",
"| | documents | with full text |", "|---|---|---|",
f"| Papers, reports, chapters | {by_kind[('paper', True)] + by_kind[('paper', False)]} | {by_kind[('paper', True)]} |",
f"| PhD theses | {by_kind[('thesis', True)] + by_kind[('thesis', False)]} | {by_kind[('thesis', True)]} |", "",
"## Where the full texts came from", ""] + [f"- {k}: {v}" for k, v in sources.most_common(12)] + [
"", "## Why the others have no full text", ""] + [f"- {k}: {v}" for k, v in reasons.most_common()] + [
"", "## Per researcher (fewest full texts first)", "", "| Researcher | documents | with full text |", "|---|---|---|"]
for pid, c in sorted(per.items(), key=lambda kv: (kv[1]["full"] / max(kv[1]["docs"], 1), -kv[1]["docs"])):
lines.append(f"| {names.get(pid, pid)} | {c['docs']} | {c['full']} |")
(OUT / "report.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
log(f"Full text for {got} of {total} documents. Wrote data/fulltext/report.md and missing.csv ({len(rows)} rows).")
# ---------------------------------------------------------------- main
def main():
ap = argparse.ArgumentParser(description="Download legally available full texts of CML papers and theses.")
ap.add_argument("--report", action="store_true", help="only rewrite report.md and missing.csv")
ap.add_argument("--retry", action="store_true", help="try failed downloads and passed embargoes again")
ap.add_argument("--refresh", action="store_true", help="re-read staff pages, repository records and the thesis list")
ap.add_argument("--limit", type=int, help="only the first N researchers (for a test)")
ap.add_argument("--no-openalex", action="store_true", help="skip OpenAlex (only the Leiden repository)")
a = ap.parse_args()
for d in (OUT, CACHE, PDF):
d.mkdir(parents=True, exist_ok=True)
log(f"=== fetch_fulltext started (python {sys.version.split()[0]}) ===")
staff = research_staff()
if a.limit:
staff = staff[:a.limit]
people_csv, p_works, _, oa_works, _ = bn.counted_works()
ids = {person_id(p["profile_url"]) for p in staff}
keep_aids = {p["openalex_id"] for p in people_csv if p["openalex_id"] and person_id(p["profile_url"]) in ids}
p_works = {aid: ws for aid, ws in p_works.items() if aid in keep_aids}
oa_works = {wid: w for wid, w in oa_works.items() if any(wid in ws for ws in p_works.values())}
try:
if a.report:
staff_pubs, items = load(CACHE / "staff_pubs.json", {}), load(CACHE / "items.json", {})
theses = cml_theses(load(CACHE / "theses_oai.json", []), staff)
locs = load(CACHE / "openalex_locations.json", {})
extra = load(CACHE / "openalex_extra.json", {})
else:
staff_pubs = crawl_staff(staff, a.refresh)
staff_pubs = {u: v for u, v in staff_pubs.items() if person_id(u) in ids}
theses = cml_theses(oai_theses(a.refresh), staff)
log(f" {len(theses)} theses granted by CML or supervised by current CML staff")
known_dois = {norm_doi(w.get("doi")) for w in oa_works.values()}
doi_only = sorted({p["doi"] for e in staff_pubs.values() for p in e["pubs"]
if p["doi"] and not p["handle"] and p["doi"] not in known_dois and not SKIP_TYPES.search(p["type"] or "")
and p.get("category") != "Popular"})
if a.no_openalex:
locs = load(CACHE / "openalex_locations.json", {})
extra = load(CACHE / "openalex_extra.json", {})
else:
ho.check_openalex()
locs = openalex_locations(sorted(oa_works), a.refresh)
extra = openalex_by_doi(doi_only, a.refresh)
handles = set(theses)
for e in staff_pubs.values():
handles |= {p["handle"] for p in e["pubs"] if p["handle"] and not SKIP_TYPES.search(p["type"] or "")
and p.get("category") != "Popular"}
handles |= {t["handle"] for t in e["theses"]}
for wid in oa_works:
handles |= {h for l in locs.get(wid, []) if (h := handle_of(l.get("landing_page_url")))}
items = repo_items(sorted(handles), a.refresh, a.retry)
docs, unmatched = build_documents(staff, staff_pubs, items, theses, oa_works, p_works, people_csv, locs, extra)
state = load(OUT / "downloads.json", {}) if a.report else fetch_documents(docs, items, locs, a.retry)
write_report(docs, state, staff, unmatched)
except ho.StopRun as e:
log(f"STOPPED: {e}")
sys.exit(1)
except KeyboardInterrupt:
log("Interrupted. Progress is saved: run the same command to continue.")
sys.exit(1)
if __name__ == "__main__":
main()