paperminertoolkit 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. paperminertoolkit/__init__.py +10 -0
  2. paperminertoolkit/_version.py +11 -0
  3. paperminertoolkit/cli.py +1053 -0
  4. paperminertoolkit/corpus/__init__.py +1 -0
  5. paperminertoolkit/corpus/database.py +1542 -0
  6. paperminertoolkit/corpus/documents.py +313 -0
  7. paperminertoolkit/corpus/filtering.py +1390 -0
  8. paperminertoolkit/corpus/metadata.py +532 -0
  9. paperminertoolkit/extraction/__init__.py +1 -0
  10. paperminertoolkit/extraction/compression.py +486 -0
  11. paperminertoolkit/extraction/extract.py +573 -0
  12. paperminertoolkit/extraction/models.py +784 -0
  13. paperminertoolkit/extraction/recipes.py +241 -0
  14. paperminertoolkit/extraction/scrape.py +737 -0
  15. paperminertoolkit/extraction/store.py +244 -0
  16. paperminertoolkit/extraction/tokenizer.py +313 -0
  17. paperminertoolkit/providers/__init__.py +1 -0
  18. paperminertoolkit/providers/arxiv.py +760 -0
  19. paperminertoolkit/providers/base.py +514 -0
  20. paperminertoolkit/providers/biorxiv.py +561 -0
  21. paperminertoolkit/providers/chemrxiv.py +1115 -0
  22. paperminertoolkit/providers/core.py +423 -0
  23. paperminertoolkit/providers/crossref.py +649 -0
  24. paperminertoolkit/providers/elsevier.py +455 -0
  25. paperminertoolkit/providers/medrxiv.py +548 -0
  26. paperminertoolkit/providers/openalex.py +471 -0
  27. paperminertoolkit/providers/pubmed.py +1272 -0
  28. paperminertoolkit/providers/registry.py +521 -0
  29. paperminertoolkit/providers/rxiv.py +936 -0
  30. paperminertoolkit/providers/unpaywall.py +162 -0
  31. paperminertoolkit/resources/recipes.json +1670 -0
  32. paperminertoolkit/settings.py +661 -0
  33. paperminertoolkit/workflows/__init__.py +1 -0
  34. paperminertoolkit/workflows/download.py +1748 -0
  35. paperminertoolkit/workflows/enrichment.py +1906 -0
  36. paperminertoolkit/workflows/imports.py +121 -0
  37. paperminertoolkit/workflows/search.py +877 -0
  38. paperminertoolkit/workflows/topics.py +2837 -0
  39. paperminertoolkit/workflows/utilities.py +73 -0
  40. paperminertoolkit-1.0.0.dist-info/METADATA +126 -0
  41. paperminertoolkit-1.0.0.dist-info/RECORD +45 -0
  42. paperminertoolkit-1.0.0.dist-info/WHEEL +5 -0
  43. paperminertoolkit-1.0.0.dist-info/entry_points.txt +2 -0
  44. paperminertoolkit-1.0.0.dist-info/licenses/LICENSE +21 -0
  45. paperminertoolkit-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1906 @@
1
+ """Supplement corpus metadata from bibliographic and preprint providers.
2
+
3
+ Discovery and download populate only a handful of bibliographic fields. This
4
+ module fills in the rest: publisher, work type, volume/issue/pages, ISSNs and
5
+ language from Crossref; citation counts, open-access status, licence and
6
+ subject classification from OpenAlex; and structured authors, subjects and
7
+ reference lists in the corpus child tables.
8
+
9
+ Crossref is treated as authoritative for the metadata a publisher deposits
10
+ against the DOI, and OpenAlex for everything it derives that no publisher
11
+ deposits. Where the two disagree, both values are recorded in
12
+ ``papers.enrichment_json`` so nothing is silently discarded.
13
+
14
+ arXiv ranks below those two, because its record describes a preprint rather
15
+ than the version of record. It contributes what no other provider holds: the
16
+ arXiv subject taxonomy, the author-deposited DOI that lets a preprint-only row
17
+ reach Crossref and OpenAlex on a later pass, and the fact that the paper is
18
+ freely readable. Unlike the other three it cannot be reached from a DOI at all,
19
+ because arXiv exposes no DOI search field, so it enriches only rows that
20
+ already carry an arXiv identifier.
21
+
22
+ medRxiv and bioRxiv rank last, for the same reason as arXiv and one more: a
23
+ preprint row that names a published version already holds that version's DOI,
24
+ so Crossref and OpenAlex describe the paper better than the preprint record
25
+ does. What only they hold is their own subject category, the preprint's licence,
26
+ and the link between the two DOIs. Like arXiv both are reachable only from an
27
+ identifier they issued themselves, which here is the preprint DOI rather than
28
+ the published one. They are separate sources rather than one because they are
29
+ separate archives: a DOI belongs to exactly one of them, and asking the wrong
30
+ one costs a request and returns nothing.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import json
36
+ import sqlite3
37
+ from collections.abc import Callable, Iterable, Mapping, Sequence
38
+ from dataclasses import dataclass, field
39
+ from datetime import datetime, timedelta, timezone
40
+ from os import PathLike
41
+ from typing import Any, TypeAlias
42
+
43
+ from tqdm import tqdm
44
+
45
+ from paperminertoolkit.providers import arxiv
46
+ from paperminertoolkit.providers import base as provider
47
+ from paperminertoolkit.providers import registry
48
+ from paperminertoolkit.providers import biorxiv
49
+ from paperminertoolkit.providers import chemrxiv
50
+ from paperminertoolkit.providers import crossref as crossref_client
51
+ from paperminertoolkit.providers import medrxiv
52
+ from paperminertoolkit.providers import openalex
53
+ from paperminertoolkit.providers import pubmed
54
+ from paperminertoolkit.corpus.database import (connect,
55
+ enrichment_candidates,
56
+ enrichment_update_fields,
57
+ find_paper,
58
+ paper_rows,
59
+ set_enrichment_status,
60
+ utc_now,
61
+ write_enrichment)
62
+ from paperminertoolkit.corpus.metadata import clean_doi, crossref_fields as crossref_metadata_fields
63
+
64
+ ENRICHMENT_SOURCES = registry.names(registry.ENRICH)
65
+ MAX_BATCH_SIZE = 100
66
+ _Record: TypeAlias = dict[str, Any]
67
+ _Fields: TypeAlias = dict[str, Any]
68
+
69
+
70
+ def _configured_sources(sources: Sequence[str] | None) -> list[str]:
71
+ """Resolve requested enrichment providers, expanding ``all``.
72
+
73
+ Parameters
74
+ ----------
75
+ sources : Sequence[str] or None
76
+ Requested provider names, or ``None`` for every provider.
77
+
78
+ Returns
79
+ -------
80
+ list[str]
81
+ Provider names in a stable order.
82
+
83
+ Raises
84
+ ------
85
+ ValueError
86
+ If a requested provider is not supported.
87
+ """
88
+ return registry.resolve_names(sources, registry.ENRICH, label='enrichment')
89
+
90
+
91
+ def _short_openalex_id(value: object) -> str:
92
+ """Reduce an OpenAlex entity URL to its short identifier."""
93
+ identifier = str(value or '').strip().rstrip('/')
94
+ return identifier.rsplit('/', 1)[-1] if identifier else ''
95
+
96
+
97
+ def _text(value: object) -> str:
98
+ """Normalize an optional provider value to stripped text."""
99
+ return '' if value is None else str(value).strip()
100
+
101
+
102
+ def _partition_candidates(
103
+ candidates: Sequence[Mapping[str, Any]],
104
+ ) -> tuple[dict[str, str], dict[str, str], list[str]]:
105
+ """Split candidates by the lookup key each one can be resolved with.
106
+
107
+ Parameters
108
+ ----------
109
+ candidates : Sequence[Mapping[str, Any]]
110
+ Candidate corpus rows carrying ``paper_id``, ``doi`` and ``openalex_id``.
111
+
112
+ Returns
113
+ -------
114
+ by_doi : dict[str, str]
115
+ Cleaned DOI to paper identifier.
116
+ by_openalex : dict[str, str]
117
+ Short OpenAlex identifier to paper identifier, for DOI-less rows.
118
+ unresolved : list[str]
119
+ Paper identifiers with no usable lookup key.
120
+ """
121
+ by_doi = {}
122
+ by_openalex = {}
123
+ unresolved = []
124
+ for candidate in candidates:
125
+ paper_id = str(candidate.get('paper_id') or '')
126
+ if not paper_id:
127
+ continue
128
+ doi = clean_doi(candidate.get('doi'))
129
+ identifier = _short_openalex_id(candidate.get('openalex_id'))
130
+ if not identifier and paper_id.startswith('openalex:'):
131
+ identifier = paper_id.split(':', 1)[1]
132
+ if doi:
133
+ by_doi[doi] = paper_id
134
+ elif identifier:
135
+ by_openalex[identifier] = paper_id
136
+ else:
137
+ unresolved.append(paper_id)
138
+ return by_doi, by_openalex, unresolved
139
+
140
+
141
+ def _pubmed_candidates(candidates: Sequence[Mapping[str, Any]]) -> dict[str, str]:
142
+ """Map each candidate's PubMed identifier to its paper identifier.
143
+
144
+ This is a parallel accessor rather than a fourth
145
+ :func:`_partition_candidates` bucket, because a PMID is read from the same
146
+ candidate row that already supplies the DOI and OpenAlex keys.
147
+
148
+ Parameters
149
+ ----------
150
+ candidates : Sequence[Mapping[str, Any]]
151
+ Candidate corpus rows carrying ``paper_id`` and ``pmid``.
152
+
153
+ Returns
154
+ -------
155
+ dict[str, str]
156
+ Bare PMID to paper identifier, for rows that carry one.
157
+ """
158
+ by_pmid = {}
159
+ for candidate in candidates:
160
+ paper_id = str(candidate.get('paper_id') or '')
161
+ if not paper_id:
162
+ continue
163
+ pmid = pubmed.normalize_pmid(candidate.get('pmid'))
164
+ if not pmid and paper_id.startswith('pmid:'):
165
+ pmid = pubmed.normalize_pmid(paper_id.split(':', 1)[1])
166
+ if pmid:
167
+ by_pmid[pmid] = paper_id
168
+ return by_pmid
169
+
170
+
171
+ def _pubmed_fields(article: Mapping[str, Any]) -> _Fields:
172
+ """Map one PubMed article onto the shared enrichment field set.
173
+
174
+ Parameters
175
+ ----------
176
+ article : Mapping[str, Any]
177
+ Article mapping produced by :func:`paperminertoolkit.providers.pubmed.article_to_paper`.
178
+
179
+ Returns
180
+ -------
181
+ dict[str, Any]
182
+ Enrichment fields contributed by PubMed.
183
+ """
184
+ types = article.get('publication_types') or []
185
+ return {
186
+ 'doi': clean_doi(article.get('doi')) if article.get('doi') else '',
187
+ 'title': _text(article.get('title')),
188
+ 'journal': _text(article.get('journal')),
189
+ 'publication_date': _text(article.get('publication_date')),
190
+ 'authors': _text(article.get('authors')),
191
+ 'pmid': pubmed.normalize_pmid(article.get('pmid')),
192
+ 'pmcid': pubmed.normalize_pmcid(article.get('pmcid')),
193
+ 'work_type': _text((types[0] or {}).get('name')) if types else '',
194
+ }
195
+
196
+
197
+ def _pubmed_subject_rows(paper_id: str, article: Mapping[str, Any] | None) -> list[_Record]:
198
+ """Build ``paper_subjects`` rows from a PubMed article's controlled terms.
199
+
200
+ MeSH descriptors, MeSH qualifiers, publication types and author keywords
201
+ are kept in separate schemes. PubMed keywords use ``mesh_keyword`` rather
202
+ than ``keyword`` so they stay distinguishable from the OpenAlex keywords
203
+ that share the ``(paper_id, scheme, subject_id)`` primary key.
204
+
205
+ Parameters
206
+ ----------
207
+ paper_id : str
208
+ Paper the rows belong to.
209
+ article : Mapping[str, Any] or None
210
+ Article mapping produced by :func:`paperminertoolkit.providers.pubmed.article_to_paper`.
211
+
212
+ Returns
213
+ -------
214
+ list[dict[str, Any]]
215
+ Rows for the ``paper_subjects`` table.
216
+ """
217
+ if not article:
218
+ return []
219
+ rows: list[_Record] = []
220
+ for rank, term in enumerate(article.get('mesh') or []):
221
+ rows.append({
222
+ 'paper_id': paper_id, 'scheme': term.get('scheme') or 'mesh',
223
+ 'subject_id': term.get('id'), 'display_name': _text(term.get('name')),
224
+ 'subject_rank': rank, 'is_primary': int(term.get('is_primary') == '1'),
225
+ 'source': 'pubmed',
226
+ })
227
+ for rank, entry in enumerate(article.get('publication_types') or []):
228
+ rows.append({
229
+ 'paper_id': paper_id, 'scheme': 'publication_type',
230
+ 'subject_id': entry.get('id'), 'display_name': _text(entry.get('name')),
231
+ 'subject_rank': rank, 'source': 'pubmed',
232
+ })
233
+ for rank, keyword in enumerate(article.get('keywords') or []):
234
+ rows.append({
235
+ 'paper_id': paper_id, 'scheme': 'mesh_keyword', 'subject_id': keyword,
236
+ 'display_name': keyword, 'subject_rank': rank, 'source': 'pubmed',
237
+ })
238
+ seen = set()
239
+ unique = []
240
+ for row in rows:
241
+ key = (row['scheme'], row['subject_id'])
242
+ if not row['subject_id'] or key in seen:
243
+ continue
244
+ seen.add(key)
245
+ unique.append(row)
246
+ return unique
247
+
248
+
249
+ def _arxiv_candidates(candidates: Sequence[Mapping[str, Any]]) -> dict[str, str]:
250
+ """Map each candidate's arXiv identifier to its paper identifier.
251
+
252
+ Unlike :func:`_pubmed_candidates`, which can fall back to resolving a PMID
253
+ from a DOI, this can only ever see rows that already carry an arXiv
254
+ identifier: arXiv publishes no DOI search field, so a DOI-only row is
255
+ unreachable no matter how many requests are spent.
256
+
257
+ Parameters
258
+ ----------
259
+ candidates : Sequence[Mapping[str, Any]]
260
+ Candidate corpus rows carrying ``paper_id`` and ``arxiv_id``.
261
+
262
+ Returns
263
+ -------
264
+ dict[str, str]
265
+ Bare arXiv identifier to paper identifier, for rows that carry one.
266
+ """
267
+ by_arxiv = {}
268
+ for candidate in candidates:
269
+ paper_id = str(candidate.get('paper_id') or '')
270
+ if not paper_id:
271
+ continue
272
+ identifier = arxiv.normalize_arxiv_id(candidate.get('arxiv_id'))
273
+ if not identifier and paper_id.startswith('arxiv:'):
274
+ identifier = arxiv.normalize_arxiv_id(paper_id.split(':', 1)[1])
275
+ if identifier:
276
+ by_arxiv[identifier] = paper_id
277
+ return by_arxiv
278
+
279
+
280
+ def _arxiv_fields(entry: Mapping[str, Any]) -> _Fields:
281
+ """Map one arXiv entry onto the shared enrichment field set.
282
+
283
+ Every arXiv paper is freely readable, so ``is_oa`` and ``oa_status`` are
284
+ asserted here rather than left at the OpenAlex default, which would record
285
+ a plainly false value for a row OpenAlex has never seen.
286
+
287
+ Parameters
288
+ ----------
289
+ entry : Mapping[str, Any]
290
+ Entry mapping produced by :func:`paperminertoolkit.providers.arxiv.entry_to_paper`.
291
+
292
+ Returns
293
+ -------
294
+ dict[str, Any]
295
+ Enrichment fields contributed by arXiv.
296
+ """
297
+ published = clean_doi(entry.get('published_doi')) if entry.get('published_doi') else ''
298
+ return {
299
+ 'doi': clean_doi(entry.get('doi')) if entry.get('doi') else '',
300
+ 'title': _text(entry.get('title')),
301
+ 'journal': _text(entry.get('journal')),
302
+ 'publication_date': _text(entry.get('publication_date')),
303
+ 'authors': _text(entry.get('authors')),
304
+ 'arxiv_id': arxiv.normalize_arxiv_id(entry.get('arxiv_id')),
305
+ 'work_type': '' if published else 'preprint',
306
+ 'is_oa': 1,
307
+ 'oa_status': 'green',
308
+ }
309
+
310
+
311
+ def _arxiv_subject_rows(paper_id: str, entry: Mapping[str, Any] | None) -> list[_Record]:
312
+ """Build ``paper_subjects`` rows from an arXiv entry's categories.
313
+
314
+ Categories use the ``arxiv_category`` scheme, which is disjoint from every
315
+ scheme OpenAlex and PubMed write, so the three providers cannot collide on
316
+ the ``(paper_id, scheme, subject_id)`` primary key. The primary category is
317
+ flagged rather than given a scheme of its own, matching how a major MeSH
318
+ descriptor is marked.
319
+
320
+ Parameters
321
+ ----------
322
+ paper_id : str
323
+ Paper the rows belong to.
324
+ entry : Mapping[str, Any] or None
325
+ Entry mapping produced by :func:`paperminertoolkit.providers.arxiv.entry_to_paper`.
326
+
327
+ Returns
328
+ -------
329
+ list[dict[str, Any]]
330
+ Rows for the ``paper_subjects`` table.
331
+ """
332
+ if not entry:
333
+ return []
334
+ rows: list[_Record] = []
335
+ seen = set()
336
+ for rank, category in enumerate(entry.get('categories') or []):
337
+ term = _text(category.get('id'))
338
+ if not term or term in seen:
339
+ continue
340
+ seen.add(term)
341
+ rows.append({
342
+ 'paper_id': paper_id, 'scheme': 'arxiv_category', 'subject_id': term,
343
+ 'display_name': _text(category.get('name')) or term, 'subject_rank': rank,
344
+ 'is_primary': int(bool(category.get('is_primary'))), 'source': 'arxiv',
345
+ })
346
+ return rows
347
+
348
+
349
+ def _medrxiv_candidates(candidates: Sequence[Mapping[str, Any]]) -> dict[str, str]:
350
+ """Map each candidate's medRxiv DOI to its paper identifier.
351
+
352
+ Like :func:`_arxiv_candidates`, this can only see rows that already carry
353
+ the identifier medRxiv issued. A row's ``doi`` is not a usable substitute
354
+ once the preprint has been published, because it then names the journal
355
+ version, which medRxiv does not index.
356
+
357
+ Parameters
358
+ ----------
359
+ candidates : Sequence[Mapping[str, Any]]
360
+ Candidate corpus rows carrying ``paper_id`` and ``medrxiv_doi``.
361
+
362
+ Returns
363
+ -------
364
+ dict[str, str]
365
+ Bare medRxiv DOI to paper identifier, for rows that carry one.
366
+ """
367
+ by_medrxiv = {}
368
+ for candidate in candidates:
369
+ paper_id = str(candidate.get('paper_id') or '')
370
+ if not paper_id:
371
+ continue
372
+ identifier = medrxiv.resolve_medrxiv_doi(candidate)
373
+ if identifier:
374
+ by_medrxiv[identifier] = paper_id
375
+ return by_medrxiv
376
+
377
+
378
+ def _medrxiv_fields(entry: Mapping[str, Any]) -> _Fields:
379
+ """Map one medRxiv record onto the shared enrichment field set.
380
+
381
+ Every medRxiv preprint is freely readable, so ``is_oa`` and ``oa_status``
382
+ are asserted here rather than left at the OpenAlex default, which would
383
+ record a plainly false value for a row OpenAlex has never seen.
384
+
385
+ ``work_type`` is only ``preprint`` while the paper is unpublished. Once
386
+ medRxiv names a published version, the corpus row describes that version,
387
+ and calling it a preprint would contradict the DOI stored beside it.
388
+
389
+ Parameters
390
+ ----------
391
+ entry : Mapping[str, Any]
392
+ Record mapping produced by :func:`paperminertoolkit.providers.medrxiv.record_to_paper`.
393
+
394
+ Returns
395
+ -------
396
+ dict[str, Any]
397
+ Enrichment fields contributed by medRxiv.
398
+ """
399
+ published = clean_doi(entry.get('published_doi')) if entry.get('published_doi') else ''
400
+ return {
401
+ 'doi': published or clean_doi(entry.get('medrxiv_doi') or ''),
402
+ 'title': _text(entry.get('title')),
403
+ 'journal': _text(entry.get('journal')),
404
+ 'publication_date': _text(entry.get('publication_date')),
405
+ 'authors': _text(entry.get('authors')),
406
+ 'medrxiv_doi': medrxiv.normalize_medrxiv_doi(entry.get('medrxiv_doi')),
407
+ 'work_type': '' if published else 'preprint',
408
+ 'license': _text(entry.get('license')),
409
+ 'is_oa': 1,
410
+ 'oa_status': 'green',
411
+ }
412
+
413
+
414
+ def _medrxiv_subject_rows(paper_id: str, entry: Mapping[str, Any] | None) -> list[_Record]:
415
+ """Build ``paper_subjects`` rows from a medRxiv record's category.
416
+
417
+ Categories use the ``medrxiv_category`` scheme, which is disjoint from
418
+ every scheme the other providers write, so they cannot collide on the
419
+ ``(paper_id, scheme, subject_id)`` primary key. medRxiv files each preprint
420
+ under exactly one category, so the single row is flagged primary.
421
+
422
+ Parameters
423
+ ----------
424
+ paper_id : str
425
+ Paper the rows belong to.
426
+ entry : Mapping[str, Any] or None
427
+ Record mapping produced by
428
+ :func:`paperminertoolkit.providers.medrxiv.record_to_paper`.
429
+
430
+ Returns
431
+ -------
432
+ list[dict[str, Any]]
433
+ Rows for the ``paper_subjects`` table.
434
+ """
435
+ if not entry:
436
+ return []
437
+ rows: list[_Record] = []
438
+ for rank, category in enumerate(entry.get('categories') or []):
439
+ term = _text(category.get('id'))
440
+ if not term:
441
+ continue
442
+ rows.append({
443
+ 'paper_id': paper_id, 'scheme': 'medrxiv_category', 'subject_id': term,
444
+ 'display_name': _text(category.get('name')) or term, 'subject_rank': rank,
445
+ 'is_primary': int(bool(category.get('is_primary'))), 'source': 'medrxiv',
446
+ })
447
+ return rows
448
+
449
+
450
+ def _biorxiv_candidates(candidates: Sequence[Mapping[str, Any]]) -> dict[str, str]:
451
+ """Map each candidate's bioRxiv DOI to its paper identifier.
452
+
453
+ Like :func:`_medrxiv_candidates`, this can only see rows that already carry
454
+ the identifier bioRxiv issued. A row's ``doi`` is not a usable substitute
455
+ once the preprint has been published, because it then names the journal
456
+ version, which bioRxiv does not index.
457
+
458
+ Parameters
459
+ ----------
460
+ candidates : Sequence[Mapping[str, Any]]
461
+ Candidate corpus rows carrying ``paper_id`` and ``biorxiv_doi``.
462
+
463
+ Returns
464
+ -------
465
+ dict[str, str]
466
+ Bare bioRxiv DOI to paper identifier, for rows that carry one.
467
+ """
468
+ by_biorxiv = {}
469
+ for candidate in candidates:
470
+ paper_id = str(candidate.get('paper_id') or '')
471
+ if not paper_id:
472
+ continue
473
+ identifier = biorxiv.resolve_biorxiv_doi(candidate)
474
+ if identifier:
475
+ by_biorxiv[identifier] = paper_id
476
+ return by_biorxiv
477
+
478
+
479
+ def _biorxiv_fields(entry: Mapping[str, Any]) -> _Fields:
480
+ """Map one bioRxiv record onto the shared enrichment field set.
481
+
482
+ Every bioRxiv preprint is freely readable, so ``is_oa`` and ``oa_status``
483
+ are asserted here rather than left at the OpenAlex default, which would
484
+ record a plainly false value for a row OpenAlex has never seen.
485
+
486
+ ``work_type`` is only ``preprint`` while the paper is unpublished. Once
487
+ bioRxiv names a published version, the corpus row describes that version,
488
+ and calling it a preprint would contradict the DOI stored beside it.
489
+
490
+ Parameters
491
+ ----------
492
+ entry : Mapping[str, Any]
493
+ Record mapping produced by :func:`paperminertoolkit.providers.biorxiv.record_to_paper`.
494
+
495
+ Returns
496
+ -------
497
+ dict[str, Any]
498
+ Enrichment fields contributed by bioRxiv.
499
+ """
500
+ published = clean_doi(entry.get('published_doi')) if entry.get('published_doi') else ''
501
+ return {
502
+ 'doi': published or clean_doi(entry.get('biorxiv_doi') or ''),
503
+ 'title': _text(entry.get('title')),
504
+ 'journal': _text(entry.get('journal')),
505
+ 'publication_date': _text(entry.get('publication_date')),
506
+ 'authors': _text(entry.get('authors')),
507
+ 'biorxiv_doi': biorxiv.normalize_biorxiv_doi(entry.get('biorxiv_doi')),
508
+ 'work_type': '' if published else 'preprint',
509
+ 'license': _text(entry.get('license')),
510
+ 'is_oa': 1,
511
+ 'oa_status': 'green',
512
+ }
513
+
514
+
515
+ def _biorxiv_subject_rows(paper_id: str, entry: Mapping[str, Any] | None) -> list[_Record]:
516
+ """Build ``paper_subjects`` rows from a bioRxiv record's category.
517
+
518
+ Categories use the ``biorxiv_category`` scheme, which is disjoint from
519
+ every scheme the other providers write -- medRxiv's included, because the
520
+ two archives classify under different subject lists -- so they cannot
521
+ collide on the ``(paper_id, scheme, subject_id)`` primary key. bioRxiv files
522
+ each preprint under exactly one category, so the single row is flagged
523
+ primary.
524
+
525
+ Parameters
526
+ ----------
527
+ paper_id : str
528
+ Paper the rows belong to.
529
+ entry : Mapping[str, Any] or None
530
+ Record mapping produced by
531
+ :func:`paperminertoolkit.providers.biorxiv.record_to_paper`.
532
+
533
+ Returns
534
+ -------
535
+ list[dict[str, Any]]
536
+ Rows for the ``paper_subjects`` table.
537
+ """
538
+ if not entry:
539
+ return []
540
+ rows: list[_Record] = []
541
+ for rank, category in enumerate(entry.get('categories') or []):
542
+ term = _text(category.get('id'))
543
+ if not term:
544
+ continue
545
+ rows.append({
546
+ 'paper_id': paper_id, 'scheme': 'biorxiv_category', 'subject_id': term,
547
+ 'display_name': _text(category.get('name')) or term, 'subject_rank': rank,
548
+ 'is_primary': int(bool(category.get('is_primary'))), 'source': 'biorxiv',
549
+ })
550
+ return rows
551
+
552
+
553
+ def _openalex_fields(work: Mapping[str, Any]) -> _Fields:
554
+ """Map one OpenAlex work onto the shared enrichment field set.
555
+
556
+ Parameters
557
+ ----------
558
+ work : Mapping[str, Any]
559
+ OpenAlex work record.
560
+
561
+ Returns
562
+ -------
563
+ dict[str, Any]
564
+ Enrichment fields contributed by OpenAlex.
565
+ """
566
+ primary = work.get('primary_location') or {}
567
+ best = work.get('best_oa_location') or {}
568
+ source = primary.get('source') or {}
569
+ biblio = work.get('biblio') or {}
570
+ access = work.get('open_access') or {}
571
+ identifiers = work.get('ids') or {}
572
+ pages = [_text(biblio.get('first_page')), _text(biblio.get('last_page'))]
573
+ authors = '; '.join(
574
+ name for name in (
575
+ ((authorship or {}).get('author') or {}).get('display_name')
576
+ for authorship in work.get('authorships') or []
577
+ ) if name
578
+ )
579
+ return {
580
+ 'openalex_id': openalex.work_id(work),
581
+ 'doi': clean_doi(work.get('doi')),
582
+ 'title': _text(work.get('title') or work.get('display_name')),
583
+ 'journal': _text(source.get('display_name')),
584
+ 'publication_date': _text(work.get('publication_date') or work.get('publication_year')),
585
+ 'authors': authors,
586
+ 'publisher': _text(source.get('host_organization_name')),
587
+ 'work_type': _text(work.get('type')),
588
+ 'volume': _text(biblio.get('volume')),
589
+ 'issue': _text(biblio.get('issue')),
590
+ 'pages': '-'.join(part for part in pages if part),
591
+ 'issn': ';'.join(_text(value) for value in source.get('issn') or [] if _text(value)),
592
+ 'issn_l': _text(source.get('issn_l')),
593
+ 'language': _text(work.get('language')),
594
+ 'is_oa': int(bool(access.get('is_oa'))),
595
+ 'oa_status': _text(access.get('oa_status')),
596
+ 'license': _text(best.get('license') or primary.get('license')),
597
+ 'is_retracted': int(bool(work.get('is_retracted'))),
598
+ 'cited_by_count': work.get('cited_by_count'),
599
+ 'referenced_works_count': work.get('referenced_works_count'),
600
+ 'pmid': pubmed.normalize_pmid(identifiers.get('pmid')),
601
+ 'pmcid': pubmed.normalize_pmcid(identifiers.get('pmcid')),
602
+ }
603
+
604
+
605
+ def _crossref_retraction(work: Mapping[str, Any]) -> tuple[bool, str]:
606
+ """Detect a retraction notice on a Crossref work.
607
+
608
+ ``updated-by`` also carries corrections, errata and expressions of concern,
609
+ so the update type is checked rather than the presence of the array.
610
+
611
+ Parameters
612
+ ----------
613
+ work : Mapping[str, Any]
614
+ Crossref work message.
615
+
616
+ Returns
617
+ -------
618
+ retracted : bool
619
+ Whether a retraction notice references this work.
620
+ notice_doi : str
621
+ DOI of the retraction notice, or an empty string.
622
+ """
623
+ for update in work.get('updated-by') or []:
624
+ if str((update or {}).get('type') or '').lower() == 'retraction':
625
+ return True, clean_doi(update.get('DOI'))
626
+ return False, ''
627
+
628
+
629
+ def _crossref_fields(work: Mapping[str, Any]) -> _Fields:
630
+ """Map one Crossref work onto the shared enrichment field set.
631
+
632
+ Parameters
633
+ ----------
634
+ work : Mapping[str, Any]
635
+ Crossref work message.
636
+
637
+ Returns
638
+ -------
639
+ dict[str, Any]
640
+ Enrichment fields contributed by Crossref.
641
+ """
642
+ mapped = crossref_metadata_fields(work)
643
+ mapped.pop('crossref_message', None)
644
+ retracted, _ = _crossref_retraction(work)
645
+ mapped.update({
646
+ 'doi': clean_doi(mapped.get('doi')),
647
+ 'authors': '; '.join(
648
+ ' '.join(part for part in [_text(author.get('given')), _text(author.get('family'))] if part)
649
+ for author in work.get('author') or []
650
+ ),
651
+ 'is_retracted': int(retracted),
652
+ 'referenced_works_count': work.get('references-count'),
653
+ 'license': _crossref_license(work),
654
+ })
655
+ return mapped
656
+
657
+
658
+ def _crossref_license(work: Mapping[str, Any]) -> str:
659
+ """Read a Crossref licence URL, ignoring text-mining-only grants."""
660
+ for entry in work.get('license') or []:
661
+ if str((entry or {}).get('content-version') or '').lower() in {'vor', 'am'}:
662
+ return _text(entry.get('URL'))
663
+ return ''
664
+
665
+
666
+ def _chemrxiv_candidates(candidates: Sequence[Mapping[str, Any]]) -> dict[str, str]:
667
+ """Map each candidate's chemRxiv DOI to its paper identifier.
668
+
669
+ Like the other preprint servers, this can only see rows that already carry
670
+ the identifier chemRxiv issued. A row's ``doi`` is not a usable substitute
671
+ once the preprint has been published, because it then names the journal
672
+ version, which chemRxiv does not index.
673
+
674
+ Parameters
675
+ ----------
676
+ candidates : Sequence[Mapping[str, Any]]
677
+ Candidate corpus rows carrying ``paper_id`` and ``chemrxiv_doi``.
678
+
679
+ Returns
680
+ -------
681
+ dict[str, str]
682
+ chemRxiv DOI to paper identifier, for rows that carry one.
683
+ """
684
+ by_chemrxiv = {}
685
+ for candidate in candidates:
686
+ paper_id = str(candidate.get('paper_id') or '')
687
+ if not paper_id:
688
+ continue
689
+ identifier = chemrxiv.resolve_chemrxiv_doi(candidate)
690
+ if identifier:
691
+ by_chemrxiv[identifier] = paper_id
692
+ return by_chemrxiv
693
+
694
+
695
+ def _chemrxiv_fields(entry: Mapping[str, Any]) -> _Fields:
696
+ """Map one chemRxiv record onto the shared enrichment field set.
697
+
698
+ Every chemRxiv preprint is freely readable, so ``is_oa`` and ``oa_status``
699
+ are asserted here rather than left at the OpenAlex default, which would
700
+ record a plainly false value for a row OpenAlex has never seen.
701
+
702
+ ``work_type`` is only ``preprint`` while the paper is unpublished. Once
703
+ chemRxiv names a published version, the corpus row describes that version,
704
+ and calling it a preprint would contradict the DOI stored beside it.
705
+
706
+ The chemRxiv DOI keeps the version suffix it was issued with, which is why
707
+ it is normalized by :func:`paperminertoolkit.providers.chemrxiv.normalize_chemrxiv_doi`
708
+ rather than by :func:`paperminertoolkit.corpus.metadata.clean_doi` alone.
709
+
710
+ Parameters
711
+ ----------
712
+ entry : Mapping[str, Any]
713
+ Record mapping produced by
714
+ :func:`paperminertoolkit.providers.chemrxiv.record_to_paper`.
715
+
716
+ Returns
717
+ -------
718
+ dict[str, Any]
719
+ Enrichment fields contributed by chemRxiv.
720
+ """
721
+ published = clean_doi(entry.get('published_doi')) if entry.get('published_doi') else ''
722
+ identifier = chemrxiv.normalize_chemrxiv_doi(entry.get('chemrxiv_doi'))
723
+ return {
724
+ 'doi': published or identifier,
725
+ 'title': _text(entry.get('title')),
726
+ 'journal': _text(entry.get('journal')),
727
+ 'publication_date': _text(entry.get('publication_date')),
728
+ 'authors': _text(entry.get('authors')),
729
+ 'chemrxiv_doi': identifier,
730
+ 'work_type': '' if published else 'preprint',
731
+ 'license': _text(entry.get('license')),
732
+ 'is_oa': 1,
733
+ 'oa_status': 'green',
734
+ }
735
+
736
+
737
+ def _chemrxiv_subject_rows(paper_id: str, entry: Mapping[str, Any] | None) -> list[_Record]:
738
+ """Build ``paper_subjects`` rows from a chemRxiv record's terms.
739
+
740
+ Two schemes are written. ``chemrxiv_category`` carries the subject
741
+ categories chemRxiv files the preprint under, of which there may be several
742
+ where medRxiv and bioRxiv allow exactly one, so only the first is flagged
743
+ primary. ``chemrxiv_keyword`` carries the author-supplied keywords, which
744
+ the other preprint servers do not publish. Both are disjoint from every
745
+ scheme the other providers write, so they cannot collide on the
746
+ ``(paper_id, scheme, subject_id)`` primary key.
747
+
748
+ Parameters
749
+ ----------
750
+ paper_id : str
751
+ Paper the rows belong to.
752
+ entry : Mapping[str, Any] or None
753
+ Record mapping produced by
754
+ :func:`paperminertoolkit.providers.chemrxiv.record_to_paper`.
755
+
756
+ Returns
757
+ -------
758
+ list[dict[str, Any]]
759
+ Rows for the ``paper_subjects`` table.
760
+ """
761
+ if not entry:
762
+ return []
763
+ rows: list[_Record] = []
764
+ for rank, category in enumerate(entry.get('categories') or []):
765
+ term = _text(category.get('id'))
766
+ if not term:
767
+ continue
768
+ rows.append({
769
+ 'paper_id': paper_id, 'scheme': 'chemrxiv_category', 'subject_id': term,
770
+ 'display_name': _text(category.get('name')) or term, 'subject_rank': rank,
771
+ 'is_primary': int(bool(category.get('is_primary'))), 'source': 'chemrxiv',
772
+ })
773
+ for rank, keyword in enumerate(entry.get('keywords') or []):
774
+ term = _text(keyword)
775
+ if not term:
776
+ continue
777
+ rows.append({
778
+ 'paper_id': paper_id, 'scheme': 'chemrxiv_keyword', 'subject_id': term.lower(),
779
+ 'display_name': term, 'subject_rank': rank,
780
+ 'is_primary': 0, 'source': 'chemrxiv',
781
+ })
782
+ return rows
783
+
784
+
785
+ def _provenance(crossref: Mapping[str, Any] | None,
786
+ openalex_work: Mapping[str, Any] | None,
787
+ pubmed_article: Mapping[str, Any] | None = None,
788
+ arxiv_entry: Mapping[str, Any] | None = None,
789
+ medrxiv_entry: Mapping[str, Any] | None = None,
790
+ biorxiv_entry: Mapping[str, Any] | None = None,
791
+ chemrxiv_entry: Mapping[str, Any] | None = None) -> _Record:
792
+ """Build the trimmed provenance document stored in ``enrichment_json``."""
793
+ provenance: _Record = {'fetched_at': utc_now()}
794
+ if crossref is not None:
795
+ retracted, notice = _crossref_retraction(crossref)
796
+ provenance['crossref'] = {
797
+ 'publisher': _text(crossref.get('publisher')),
798
+ 'is_referenced_by_count': crossref.get('is-referenced-by-count'),
799
+ 'references_count': crossref.get('references-count'),
800
+ 'issn_type': crossref.get('issn-type') or [],
801
+ 'license': crossref.get('license') or [],
802
+ 'published_print': _date_parts(crossref.get('published-print')),
803
+ 'published_online': _date_parts(crossref.get('published-online')),
804
+ 'is_retracted': retracted,
805
+ 'retraction_doi': notice,
806
+ }
807
+ if openalex_work is not None:
808
+ primary = openalex_work.get('primary_location') or {}
809
+ source = primary.get('source') or {}
810
+ provenance['openalex'] = {
811
+ 'id': openalex.work_id(openalex_work),
812
+ 'ids': openalex_work.get('ids') or {},
813
+ 'publisher': _text(source.get('host_organization_name')),
814
+ 'publication_date': _text(openalex_work.get('publication_date')),
815
+ 'cited_by_count': openalex_work.get('cited_by_count'),
816
+ 'is_authors_truncated': bool(openalex_work.get('is_authors_truncated')),
817
+ 'primary_location_license': _text(primary.get('license')),
818
+ 'best_oa_location_license': _text((openalex_work.get('best_oa_location') or {}).get('license')),
819
+ }
820
+ if pubmed_article is not None:
821
+ provenance['pubmed'] = {
822
+ 'pmid': pubmed.normalize_pmid(pubmed_article.get('pmid')),
823
+ 'pmcid': pubmed.normalize_pmcid(pubmed_article.get('pmcid')),
824
+ 'article_type': _text(pubmed_article.get('article_type')),
825
+ 'publication_types': [_text(entry.get('name'))
826
+ for entry in pubmed_article.get('publication_types') or []],
827
+ 'mesh_count': len(pubmed_article.get('mesh') or []),
828
+ }
829
+ if arxiv_entry is not None:
830
+ provenance['arxiv'] = {
831
+ 'arxiv_id': arxiv.normalize_arxiv_id(arxiv_entry.get('arxiv_id')),
832
+ 'version': _text(arxiv_entry.get('version')),
833
+ 'primary_category': _text(arxiv_entry.get('primary_category')),
834
+ 'categories': [_text(term.get('id'))
835
+ for term in arxiv_entry.get('categories') or []],
836
+ 'journal_ref': _text(arxiv_entry.get('journal_ref')),
837
+ 'comment': _text(arxiv_entry.get('comment')),
838
+ }
839
+ if medrxiv_entry is not None:
840
+ provenance['medrxiv'] = {
841
+ 'medrxiv_doi': medrxiv.normalize_medrxiv_doi(medrxiv_entry.get('medrxiv_doi')),
842
+ 'version': _text(medrxiv_entry.get('version')),
843
+ 'category': _text(medrxiv_entry.get('category')),
844
+ 'license': _text(medrxiv_entry.get('license')),
845
+ 'published_doi': _text(medrxiv_entry.get('published_doi')),
846
+ 'jatsxml': _text(medrxiv_entry.get('jatsxml')),
847
+ }
848
+ if biorxiv_entry is not None:
849
+ provenance['biorxiv'] = {
850
+ 'biorxiv_doi': biorxiv.normalize_biorxiv_doi(biorxiv_entry.get('biorxiv_doi')),
851
+ 'version': _text(biorxiv_entry.get('version')),
852
+ 'category': _text(biorxiv_entry.get('category')),
853
+ 'license': _text(biorxiv_entry.get('license')),
854
+ 'published_doi': _text(biorxiv_entry.get('published_doi')),
855
+ 'jatsxml': _text(biorxiv_entry.get('jatsxml')),
856
+ }
857
+ if chemrxiv_entry is not None:
858
+ # No jatsxml: chemRxiv serves PDFs and abstracts but no full text.
859
+ provenance['chemrxiv'] = {
860
+ 'chemrxiv_doi': chemrxiv.normalize_chemrxiv_doi(chemrxiv_entry.get('chemrxiv_doi')),
861
+ 'version': _text(chemrxiv_entry.get('version')),
862
+ 'category': _text(chemrxiv_entry.get('category')),
863
+ 'keywords': list(chemrxiv_entry.get('keywords') or []),
864
+ 'license': _text(chemrxiv_entry.get('license')),
865
+ 'published_doi': _text(chemrxiv_entry.get('published_doi')),
866
+ 'asset_url': _text(chemrxiv_entry.get('asset_url')),
867
+ }
868
+ return provenance
869
+
870
+
871
+ def _date_parts(value: object) -> str:
872
+ """Format a Crossref ``date-parts`` container as an ISO-like date."""
873
+ parts = (value or {}).get('date-parts') if isinstance(value, Mapping) else None
874
+ if not parts or not parts[0]:
875
+ return ''
876
+ date = [int(part) for part in parts[0][:3]]
877
+ return '-'.join(f'{part:02d}' if index else f'{part:04d}' for index, part in enumerate(date))
878
+
879
+
880
+ CROSSREF_PREFERRED = ('publisher', 'work_type', 'volume', 'issue', 'pages', 'issn', 'language')
881
+ OPENALEX_ONLY = ('openalex_id', 'issn_l', 'is_oa', 'oa_status', 'license', 'cited_by_count')
882
+ FILL_COLUMNS = ('doi', 'title', 'journal', 'publication_date', 'authors', 'pmid', 'pmcid',
883
+ 'arxiv_id', 'medrxiv_doi', 'biorxiv_doi', 'chemrxiv_doi')
884
+ PRESERVED_ON_PROVIDER_ERROR = (CROSSREF_PREFERRED + OPENALEX_ONLY
885
+ + ('referenced_works_count', 'is_retracted'))
886
+
887
+
888
+ def _merge_fields(paper_id: str,
889
+ crossref: Mapping[str, Any] | None,
890
+ openalex_work: Mapping[str, Any] | None,
891
+ requested: Sequence[str],
892
+ pubmed_article: Mapping[str, Any] | None = None,
893
+ arxiv_entry: Mapping[str, Any] | None = None,
894
+ medrxiv_entry: Mapping[str, Any] | None = None,
895
+ biorxiv_entry: Mapping[str, Any] | None = None,
896
+ chemrxiv_entry: Mapping[str, Any] | None = None,
897
+ provider_errors: Mapping[str, str] | None = None) -> _Record:
898
+ """Apply the provider precedence rules and build one paper's update.
899
+
900
+ Parameters
901
+ ----------
902
+ paper_id : str
903
+ Paper the update applies to.
904
+ crossref : Mapping[str, Any] or None
905
+ Crossref work message, or ``None`` when Crossref had no record.
906
+ openalex_work : Mapping[str, Any] or None
907
+ OpenAlex work record, or ``None`` when OpenAlex had no record.
908
+ requested : Sequence[str]
909
+ Providers that were queried for this paper.
910
+ pubmed_article : Mapping[str, Any] or None, optional
911
+ PubMed article mapping, or ``None`` when PubMed had no record.
912
+ arxiv_entry : Mapping[str, Any] or None, optional
913
+ arXiv entry mapping, or ``None`` when arXiv had no record.
914
+ medrxiv_entry : Mapping[str, Any] or None, optional
915
+ medRxiv record mapping, or ``None`` when medRxiv had no record.
916
+ biorxiv_entry : Mapping[str, Any] or None, optional
917
+ bioRxiv record mapping, or ``None`` when bioRxiv had no record.
918
+ chemrxiv_entry : Mapping[str, Any] or None, optional
919
+ chemRxiv record mapping, or ``None`` when chemRxiv had no record.
920
+ provider_errors : Mapping[str, str] or None, optional
921
+ Failures from providers that were applicable to this paper. These make
922
+ an otherwise empty result ``failed`` rather than ``not_found``.
923
+
924
+ Returns
925
+ -------
926
+ dict[str, Any]
927
+ Mapping covering every enrichment update parameter.
928
+ """
929
+ from_crossref = _crossref_fields(crossref) if crossref is not None else {}
930
+ from_openalex = _openalex_fields(openalex_work) if openalex_work is not None else {}
931
+ from_pubmed = _pubmed_fields(pubmed_article) if pubmed_article is not None else {}
932
+ from_arxiv = _arxiv_fields(arxiv_entry) if arxiv_entry is not None else {}
933
+ from_medrxiv = _medrxiv_fields(medrxiv_entry) if medrxiv_entry is not None else {}
934
+ from_biorxiv = _biorxiv_fields(biorxiv_entry) if biorxiv_entry is not None else {}
935
+ from_chemrxiv = _chemrxiv_fields(chemrxiv_entry) if chemrxiv_entry is not None else {}
936
+ update = {field: '' for field in enrichment_update_fields()}
937
+
938
+ for column in FILL_COLUMNS + CROSSREF_PREFERRED:
939
+ update[column] = (from_crossref.get(column)
940
+ or from_openalex.get(column)
941
+ or from_pubmed.get(column)
942
+ or from_arxiv.get(column)
943
+ or from_medrxiv.get(column)
944
+ or from_biorxiv.get(column)
945
+ or from_chemrxiv.get(column)
946
+ or '')
947
+ for column in OPENALEX_ONLY:
948
+ update[column] = from_openalex.get(column) if from_openalex.get(column) is not None else ''
949
+ update['referenced_works_count'] = (from_openalex.get('referenced_works_count')
950
+ or from_crossref.get('referenced_works_count') or 0)
951
+ update['is_retracted'] = int(bool(from_crossref.get('is_retracted'))
952
+ or bool(from_openalex.get('is_retracted')))
953
+ update['is_oa'] = int(bool(from_openalex.get('is_oa'))
954
+ or bool(from_arxiv.get('is_oa'))
955
+ or bool(from_medrxiv.get('is_oa'))
956
+ or bool(from_biorxiv.get('is_oa'))
957
+ or bool(from_chemrxiv.get('is_oa')))
958
+ for preprint in (from_arxiv, from_medrxiv, from_biorxiv, from_chemrxiv):
959
+ if not update['oa_status'] and preprint.get('oa_status'):
960
+ update['oa_status'] = preprint['oa_status']
961
+ # OPENALEX_ONLY blanks the licence for a row OpenAlex has no record of,
962
+ # which would discard the one the preprint server states on the posting.
963
+ for preprint in (from_medrxiv, from_biorxiv, from_chemrxiv):
964
+ if not update['license'] and preprint.get('license'):
965
+ update['license'] = preprint['license']
966
+ update['cited_by_count'] = from_openalex.get('cited_by_count') or 0
967
+
968
+ found = [source for source, record in (('crossref', crossref),
969
+ ('openalex', openalex_work),
970
+ ('pubmed', pubmed_article),
971
+ ('arxiv', arxiv_entry),
972
+ ('medrxiv', medrxiv_entry),
973
+ ('biorxiv', biorxiv_entry),
974
+ ('chemrxiv', chemrxiv_entry))
975
+ if record is not None]
976
+ provider_errors = dict(provider_errors or {})
977
+ if not found and provider_errors:
978
+ status = 'failed'
979
+ elif not found:
980
+ status = 'not_found'
981
+ elif len(found) == len(requested):
982
+ status = 'succeeded'
983
+ else:
984
+ status = 'partial'
985
+
986
+ now = utc_now()
987
+ provenance = _provenance(crossref, openalex_work, pubmed_article, arxiv_entry,
988
+ medrxiv_entry, biorxiv_entry, chemrxiv_entry)
989
+ if provider_errors:
990
+ provenance['provider_errors'] = provider_errors
991
+ update.update({
992
+ 'paper_id': paper_id,
993
+ 'enrichment_sources': ';'.join(found),
994
+ 'enrichment_json': provenance,
995
+ 'enriched_at': now if found else '',
996
+ 'enrichment_status': status,
997
+ 'updated_at': now,
998
+ })
999
+ return update
1000
+
1001
+
1002
+ def _preserve_stored_values(update: _Record, stored: Mapping[str, Any]) -> None:
1003
+ """Keep non-empty enrichment values when a partial refresh cannot replace them.
1004
+
1005
+ A zero is a valid fresh value, but during a provider failure it is also the
1006
+ default produced for missing counts and flags. Keeping the previous non-zero
1007
+ value until every requested provider completes avoids turning an outage into
1008
+ an apparent metadata change.
1009
+ """
1010
+ for column in PRESERVED_ON_PROVIDER_ERROR:
1011
+ if update.get(column) in ('', None, 0) and stored[column] not in ('', None, 0):
1012
+ update[column] = stored[column]
1013
+
1014
+
1015
+ def _position_label(index: int, total: int, authorship: Mapping[str, Any] | None) -> str:
1016
+ """Choose a shared author-position label across both providers."""
1017
+ if authorship and _text(authorship.get('author_position')):
1018
+ return _text(authorship.get('author_position'))
1019
+ if index == 0:
1020
+ return 'first'
1021
+ return 'last' if index == total - 1 else 'middle'
1022
+
1023
+
1024
+ def _safe_orcid(value: object) -> str:
1025
+ """Normalize an ORCID, returning an empty string for malformed values."""
1026
+ try:
1027
+ return crossref_client.normalize_orcid(value)
1028
+ except ValueError:
1029
+ return ''
1030
+
1031
+
1032
+ def _author_rows(paper_id: str,
1033
+ crossref: Mapping[str, Any] | None,
1034
+ openalex_work: Mapping[str, Any] | None) -> list[_Record]:
1035
+ """Build one ``paper_authors`` row per author and affiliation.
1036
+
1037
+ OpenAlex authorships are the spine because they alone carry ORCIDs,
1038
+ disambiguated author identifiers and ROR-matched institutions. Crossref
1039
+ supplies the deposited given/family split by ordinal, and extends the list
1040
+ when OpenAlex reports a truncated author set.
1041
+
1042
+ Parameters
1043
+ ----------
1044
+ paper_id : str
1045
+ Paper the rows belong to.
1046
+ crossref : Mapping[str, Any] or None
1047
+ Crossref work message.
1048
+ openalex_work : Mapping[str, Any] or None
1049
+ OpenAlex work record.
1050
+
1051
+ Returns
1052
+ -------
1053
+ list[dict[str, Any]]
1054
+ Rows for the ``paper_authors`` table.
1055
+ """
1056
+ authorships = list((openalex_work or {}).get('authorships') or [])
1057
+ crossref_authors = list((crossref or {}).get('author') or [])
1058
+ rows: list[_Record] = []
1059
+
1060
+ for index, authorship in enumerate(authorships):
1061
+ author = (authorship or {}).get('author') or {}
1062
+ deposited = crossref_authors[index] if index < len(crossref_authors) else {}
1063
+ institutions = list(authorship.get('institutions') or [])
1064
+ raw_affiliations = list(authorship.get('raw_affiliation_strings') or [])
1065
+ base = {
1066
+ 'paper_id': paper_id,
1067
+ 'author_position': index,
1068
+ 'position_label': _position_label(index, len(authorships), authorship),
1069
+ 'display_name': _text(author.get('display_name')),
1070
+ 'given_name': _text(deposited.get('given')),
1071
+ 'family_name': _text(deposited.get('family')),
1072
+ 'orcid': _safe_orcid(author.get('orcid')) or _safe_orcid(deposited.get('ORCID')),
1073
+ 'is_corresponding': int(bool(authorship.get('is_corresponding'))),
1074
+ 'openalex_author_id': _short_openalex_id(author.get('id')),
1075
+ 'institution_name': '',
1076
+ 'institution_ror': '',
1077
+ 'institution_country': '',
1078
+ 'source': 'openalex',
1079
+ }
1080
+ if not institutions:
1081
+ rows.append({**base, 'affiliation_rank': 0,
1082
+ 'affiliation': raw_affiliations[0] if raw_affiliations else ''})
1083
+ continue
1084
+ for rank, institution in enumerate(institutions):
1085
+ institution = institution or {}
1086
+ rows.append({
1087
+ **base,
1088
+ 'affiliation_rank': rank,
1089
+ 'affiliation': raw_affiliations[rank] if rank < len(raw_affiliations) else '',
1090
+ 'institution_name': _text(institution.get('display_name')),
1091
+ 'institution_ror': _short_openalex_id(institution.get('ror')),
1092
+ 'institution_country': _text(institution.get('country_code')),
1093
+ })
1094
+
1095
+ for index in range(len(authorships), len(crossref_authors)):
1096
+ deposited = crossref_authors[index] or {}
1097
+ affiliations = list(deposited.get('affiliation') or [])
1098
+ base = {
1099
+ 'paper_id': paper_id,
1100
+ 'author_position': index,
1101
+ 'position_label': _position_label(index, len(crossref_authors), None),
1102
+ 'display_name': ' '.join(part for part in [_text(deposited.get('given')),
1103
+ _text(deposited.get('family'))] if part),
1104
+ 'given_name': _text(deposited.get('given')),
1105
+ 'family_name': _text(deposited.get('family')),
1106
+ 'orcid': _safe_orcid(deposited.get('ORCID')),
1107
+ 'is_corresponding': 0,
1108
+ 'openalex_author_id': '',
1109
+ 'institution_name': '',
1110
+ 'institution_ror': '',
1111
+ 'institution_country': '',
1112
+ 'source': 'crossref',
1113
+ }
1114
+ if not affiliations:
1115
+ rows.append({**base, 'affiliation_rank': 0, 'affiliation': ''})
1116
+ continue
1117
+ for rank, affiliation in enumerate(affiliations):
1118
+ rows.append({**base, 'affiliation_rank': rank,
1119
+ 'affiliation': _text((affiliation or {}).get('name'))})
1120
+ return rows
1121
+
1122
+
1123
+ def _subject_rows(paper_id: str, openalex_work: Mapping[str, Any] | None) -> list[_Record]:
1124
+ """Build ``paper_subjects`` rows from an OpenAlex work.
1125
+
1126
+ Crossref retired subject assignment and returns an empty list, so subjects
1127
+ come from OpenAlex only. Topics, concepts, keywords, sustainable
1128
+ development goals and the topic hierarchy are kept in separate schemes.
1129
+
1130
+ Parameters
1131
+ ----------
1132
+ paper_id : str
1133
+ Paper the rows belong to.
1134
+ openalex_work : Mapping[str, Any] or None
1135
+ OpenAlex work record.
1136
+
1137
+ Returns
1138
+ -------
1139
+ list[dict[str, Any]]
1140
+ Rows for the ``paper_subjects`` table.
1141
+ """
1142
+ if not openalex_work:
1143
+ return []
1144
+ rows: list[_Record] = []
1145
+ primary_id = _short_openalex_id((openalex_work.get('primary_topic') or {}).get('id'))
1146
+
1147
+ for rank, topic in enumerate(openalex_work.get('topics') or []):
1148
+ topic = topic or {}
1149
+ identifier = _short_openalex_id(topic.get('id'))
1150
+ if not identifier:
1151
+ continue
1152
+ rows.append({
1153
+ 'paper_id': paper_id, 'scheme': 'topic', 'subject_id': identifier,
1154
+ 'display_name': _text(topic.get('display_name')), 'score': topic.get('score'),
1155
+ 'subject_rank': rank, 'is_primary': int(identifier == primary_id),
1156
+ 'parent_field': _text((topic.get('field') or {}).get('display_name')),
1157
+ 'parent_domain': _text((topic.get('domain') or {}).get('display_name')),
1158
+ 'source': 'openalex',
1159
+ })
1160
+
1161
+ for level_name in ('subfield', 'field', 'domain'):
1162
+ entry = (openalex_work.get('primary_topic') or {}).get(level_name) or {}
1163
+ identifier = _short_openalex_id(entry.get('id'))
1164
+ if identifier:
1165
+ rows.append({
1166
+ 'paper_id': paper_id, 'scheme': level_name, 'subject_id': identifier,
1167
+ 'display_name': _text(entry.get('display_name')), 'is_primary': 1,
1168
+ 'source': 'openalex',
1169
+ })
1170
+
1171
+ for rank, concept in enumerate(openalex_work.get('concepts') or []):
1172
+ concept = concept or {}
1173
+ identifier = _short_openalex_id(concept.get('id'))
1174
+ if identifier:
1175
+ rows.append({
1176
+ 'paper_id': paper_id, 'scheme': 'concept', 'subject_id': identifier,
1177
+ 'display_name': _text(concept.get('display_name')), 'score': concept.get('score'),
1178
+ 'subject_rank': rank, 'level': concept.get('level'), 'source': 'openalex',
1179
+ })
1180
+
1181
+ for rank, keyword in enumerate(openalex_work.get('keywords') or []):
1182
+ keyword = keyword or {}
1183
+ identifier = _short_openalex_id(keyword.get('id')) or _text(keyword.get('display_name'))
1184
+ if identifier:
1185
+ rows.append({
1186
+ 'paper_id': paper_id, 'scheme': 'keyword', 'subject_id': identifier,
1187
+ 'display_name': _text(keyword.get('display_name')), 'score': keyword.get('score'),
1188
+ 'subject_rank': rank, 'source': 'openalex',
1189
+ })
1190
+
1191
+ for rank, goal in enumerate(openalex_work.get('sustainable_development_goals') or []):
1192
+ goal = goal or {}
1193
+ identifier = _short_openalex_id(goal.get('id'))
1194
+ if identifier:
1195
+ rows.append({
1196
+ 'paper_id': paper_id, 'scheme': 'sdg', 'subject_id': identifier,
1197
+ 'display_name': _text(goal.get('display_name')), 'score': goal.get('score'),
1198
+ 'subject_rank': rank, 'source': 'openalex',
1199
+ })
1200
+
1201
+ seen = set()
1202
+ unique = []
1203
+ for row in rows:
1204
+ key = (row['scheme'], row['subject_id'])
1205
+ if key in seen:
1206
+ continue
1207
+ seen.add(key)
1208
+ unique.append(row)
1209
+ return unique
1210
+
1211
+
1212
+ def _reference_rows(paper_id: str,
1213
+ crossref: Mapping[str, Any] | None,
1214
+ openalex_work: Mapping[str, Any] | None) -> list[_Record]:
1215
+ """Build ``paper_references`` rows from both providers.
1216
+
1217
+ The two reference lists are stored side by side rather than merged:
1218
+ Crossref carries publisher-asserted DOIs, while OpenAlex covers works whose
1219
+ publisher deposited no reference list but yields its own identifiers.
1220
+
1221
+ Parameters
1222
+ ----------
1223
+ paper_id : str
1224
+ Paper the rows belong to.
1225
+ crossref : Mapping[str, Any] or None
1226
+ Crossref work message.
1227
+ openalex_work : Mapping[str, Any] or None
1228
+ OpenAlex work record.
1229
+
1230
+ Returns
1231
+ -------
1232
+ list[dict[str, Any]]
1233
+ Rows for the ``paper_references`` table.
1234
+ """
1235
+ rows: list[_Record] = []
1236
+ for rank, reference in enumerate((crossref or {}).get('reference') or []):
1237
+ reference = reference or {}
1238
+ rows.append({
1239
+ 'paper_id': paper_id, 'source': 'crossref', 'reference_rank': rank,
1240
+ 'referenced_doi': clean_doi(reference.get('DOI')),
1241
+ 'referenced_title': _text(reference.get('article-title')
1242
+ or reference.get('volume-title')
1243
+ or reference.get('journal-title')),
1244
+ 'unstructured': _text(reference.get('unstructured')),
1245
+ })
1246
+ for rank, referenced in enumerate((openalex_work or {}).get('referenced_works') or []):
1247
+ identifier = _short_openalex_id(referenced)
1248
+ if identifier:
1249
+ rows.append({
1250
+ 'paper_id': paper_id, 'source': 'openalex', 'reference_rank': rank,
1251
+ 'referenced_openalex_id': identifier,
1252
+ })
1253
+ return rows
1254
+
1255
+
1256
+ @dataclass(frozen=True)
1257
+ class _FetchContext:
1258
+ """Inputs shared by the registry-backed enrichment fetch handlers."""
1259
+
1260
+ dois: Sequence[str]
1261
+ identifiers: Sequence[str]
1262
+ email: str
1263
+ api_key: str | None
1264
+ openalex_session: provider.HTTPClient | None
1265
+ crossref_session: provider.HTTPClient | None
1266
+ pace: float
1267
+ pmids: Sequence[str] = ()
1268
+ pubmed_session: provider.HTTPClient | None = None
1269
+ pubmed_api_key: str | None = None
1270
+ arxiv_ids: Sequence[str] = ()
1271
+ arxiv_session: provider.HTTPClient | None = None
1272
+ medrxiv_dois: Sequence[str] = ()
1273
+ medrxiv_session: provider.HTTPClient | None = None
1274
+ biorxiv_dois: Sequence[str] = ()
1275
+ biorxiv_session: provider.HTTPClient | None = None
1276
+ chemrxiv_dois: Sequence[str] = ()
1277
+ chemrxiv_session: provider.HTTPClient | None = None
1278
+
1279
+
1280
+ @dataclass
1281
+ class _FetchResult:
1282
+ """Records and provider failures produced while enriching one batch."""
1283
+
1284
+ crossref_works: dict[str, _Record] = field(default_factory=dict)
1285
+ openalex_by_doi: dict[str, _Record] = field(default_factory=dict)
1286
+ openalex_by_id: dict[str, _Record] = field(default_factory=dict)
1287
+ pubmed_by_pmid: dict[str, _Record] = field(default_factory=dict)
1288
+ arxiv_by_id: dict[str, _Record] = field(default_factory=dict)
1289
+ medrxiv_by_doi: dict[str, _Record] = field(default_factory=dict)
1290
+ biorxiv_by_doi: dict[str, _Record] = field(default_factory=dict)
1291
+ chemrxiv_by_doi: dict[str, _Record] = field(default_factory=dict)
1292
+ errors: dict[str, str] = field(default_factory=dict)
1293
+
1294
+
1295
+ def _fetch_crossref(context: _FetchContext) -> dict[str, dict[str, _Record]]:
1296
+ """Fetch Crossref records for one enrichment batch."""
1297
+ if not context.dois:
1298
+ return {}
1299
+ return {'crossref_works': crossref_client.works_by_doi(
1300
+ context.dois, email=context.email, session=context.crossref_session,
1301
+ pace=context.pace)}
1302
+
1303
+
1304
+ def _fetch_openalex(context: _FetchContext) -> dict[str, dict[str, _Record]]:
1305
+ """Fetch OpenAlex records for one enrichment batch."""
1306
+ records: dict[str, dict[str, _Record]] = {}
1307
+ if context.dois:
1308
+ records['openalex_by_doi'] = openalex.works_batch(
1309
+ context.dois, api_key=context.api_key, session=context.openalex_session,
1310
+ mailto=context.email)
1311
+ if context.identifiers:
1312
+ records['openalex_by_id'] = openalex.works_batch(
1313
+ context.identifiers, filter_name='ids.openalex', api_key=context.api_key,
1314
+ session=context.openalex_session, mailto=context.email)
1315
+ return records
1316
+
1317
+
1318
+ def _fetch_pubmed(context: _FetchContext) -> dict[str, dict[str, _Record]]:
1319
+ """Fetch PubMed records for one enrichment batch."""
1320
+ records: dict[str, _Record] = {}
1321
+ for chunk in provider.chunked(list(context.pmids), pubmed.EFETCH_BATCH_SIZE):
1322
+ articles = pubmed.parse_articles(pubmed.efetch_ids(
1323
+ chunk, api_key=context.pubmed_api_key, email=context.email,
1324
+ session=context.pubmed_session))
1325
+ for article in articles:
1326
+ pmid = pubmed.normalize_pmid(article.get('pmid'))
1327
+ if pmid:
1328
+ records[pmid] = article
1329
+ return {'pubmed_by_pmid': records} if records else {}
1330
+
1331
+
1332
+ def _fetch_arxiv(context: _FetchContext) -> dict[str, dict[str, _Record]]:
1333
+ """Fetch arXiv records for one enrichment batch."""
1334
+ records: dict[str, _Record] = {}
1335
+ for chunk in provider.chunked(list(context.arxiv_ids), arxiv.ID_BATCH_SIZE):
1336
+ for entry in arxiv.parse_entries(arxiv.fetch_ids(chunk, session=context.arxiv_session)):
1337
+ identifier = arxiv.normalize_arxiv_id(entry.get('arxiv_id'))
1338
+ if identifier:
1339
+ records[identifier] = entry
1340
+ return {'arxiv_by_id': records} if records else {}
1341
+
1342
+
1343
+ def _fetch_rxiv(identifiers: Sequence[str],
1344
+ fetcher: Callable[..., Mapping[str, Any] | None],
1345
+ session: provider.HTTPClient | None,
1346
+ bucket: str) -> dict[str, dict[str, _Record]]:
1347
+ """Fetch DOI-addressed preprint records for one enrichment batch."""
1348
+ records: dict[str, _Record] = {}
1349
+ for identifier in identifiers:
1350
+ entry = fetcher(identifier, session=session)
1351
+ if entry is not None:
1352
+ records[identifier] = entry
1353
+ return {bucket: records} if records else {}
1354
+
1355
+
1356
+ def _fetch_medrxiv(context: _FetchContext) -> dict[str, dict[str, _Record]]:
1357
+ """Fetch medRxiv records for one enrichment batch."""
1358
+ return _fetch_rxiv(context.medrxiv_dois, medrxiv.fetch_doi,
1359
+ context.medrxiv_session, 'medrxiv_by_doi')
1360
+
1361
+
1362
+ def _fetch_biorxiv(context: _FetchContext) -> dict[str, dict[str, _Record]]:
1363
+ """Fetch bioRxiv records for one enrichment batch."""
1364
+ return _fetch_rxiv(context.biorxiv_dois, biorxiv.fetch_doi,
1365
+ context.biorxiv_session, 'biorxiv_by_doi')
1366
+
1367
+
1368
+ def _fetch_chemrxiv(context: _FetchContext) -> dict[str, dict[str, _Record]]:
1369
+ """Fetch chemRxiv records for one enrichment batch."""
1370
+ return _fetch_rxiv(context.chemrxiv_dois, chemrxiv.fetch_doi,
1371
+ context.chemrxiv_session, 'chemrxiv_by_doi')
1372
+
1373
+
1374
+ def _fetch(source_names: Sequence[str], context: _FetchContext) -> _FetchResult:
1375
+ """Fetch one batch, isolating failures when several providers were selected."""
1376
+ result = _FetchResult()
1377
+ for name in source_names:
1378
+ try:
1379
+ fetched = registry.resolve_handler(name, registry.ENRICH)(context)
1380
+ except Exception as error:
1381
+ if len(source_names) == 1:
1382
+ raise
1383
+ result.errors[name] = str(error)
1384
+ print(f'{registry.SOURCES[name].label} enrichment skipped: {error}')
1385
+ continue
1386
+ for bucket, records in fetched.items():
1387
+ getattr(result, bucket).update(records)
1388
+ return result
1389
+
1390
+
1391
+ def _enrich_batch(conn: sqlite3.Connection,
1392
+ candidates: Sequence[Mapping[str, Any]],
1393
+ sources: Sequence[str],
1394
+ email: str,
1395
+ api_key: str | None = None,
1396
+ references: bool = True,
1397
+ openalex_session: provider.HTTPClient | None = None,
1398
+ crossref_session: provider.HTTPClient | None = None,
1399
+ pace: float = crossref_client.CROSSREF_MIN_INTERVAL,
1400
+ pubmed_session: provider.HTTPClient | None = None,
1401
+ pubmed_api_key: str | None = None,
1402
+ arxiv_session: provider.HTTPClient | None = None,
1403
+ medrxiv_session: provider.HTTPClient | None = None,
1404
+ biorxiv_session: provider.HTTPClient | None = None,
1405
+ chemrxiv_session: provider.HTTPClient | None = None) -> dict[str, int]:
1406
+ """Fetch, map and store enrichment for one batch of papers.
1407
+
1408
+ Parameters
1409
+ ----------
1410
+ conn : sqlite3.Connection
1411
+ Open corpus connection.
1412
+ candidates : Sequence[Mapping[str, Any]]
1413
+ Candidate corpus rows to enrich.
1414
+ sources : Sequence[str]
1415
+ Providers to query.
1416
+ email : str
1417
+ Contact email sent to both providers.
1418
+ api_key : str or None, optional
1419
+ OpenAlex API key to attach.
1420
+ references : bool, default=True
1421
+ Whether to store reference lists.
1422
+ openalex_session : provider.HTTPClient or None, optional
1423
+ HTTP client used for OpenAlex requests.
1424
+ crossref_session : provider.HTTPClient or None, optional
1425
+ HTTP session used for Crossref requests.
1426
+ pace : float, optional
1427
+ Seconds to wait between consecutive Crossref requests.
1428
+ pubmed_session : provider.HTTPClient or None, optional
1429
+ HTTP client used for PubMed requests.
1430
+ pubmed_api_key : str or None, optional
1431
+ NCBI API key to attach to PubMed requests.
1432
+ arxiv_session : provider.HTTPClient or None, optional
1433
+ HTTP client used for arXiv requests.
1434
+ medrxiv_session : provider.HTTPClient or None, optional
1435
+ HTTP client used for medRxiv requests.
1436
+ biorxiv_session : provider.HTTPClient or None, optional
1437
+ HTTP client used for bioRxiv requests.
1438
+ chemrxiv_session : provider.HTTPClient or None, optional
1439
+ HTTP client used for chemRxiv requests.
1440
+
1441
+ Returns
1442
+ -------
1443
+ dict[str, int]
1444
+ Counts of each resulting status and of stored child rows.
1445
+ """
1446
+ summary = {status: 0 for status in
1447
+ ('succeeded', 'partial', 'not_found', 'unresolved', 'failed')}
1448
+ summary.update({'authors': 0, 'subjects': 0, 'references': 0})
1449
+ if not candidates:
1450
+ return summary
1451
+
1452
+ by_doi, by_openalex, unresolved = _partition_candidates(candidates)
1453
+ by_pmid = _pubmed_candidates(candidates) if 'pubmed' in sources else {}
1454
+ by_arxiv = _arxiv_candidates(candidates) if 'arxiv' in sources else {}
1455
+ by_medrxiv = _medrxiv_candidates(candidates) if 'medrxiv' in sources else {}
1456
+ by_biorxiv = _biorxiv_candidates(candidates) if 'biorxiv' in sources else {}
1457
+ by_chemrxiv = _chemrxiv_candidates(candidates) if 'chemrxiv' in sources else {}
1458
+ openalex_papers = set(by_openalex.values())
1459
+ pubmed_papers = set(by_pmid.values())
1460
+ arxiv_papers = set(by_arxiv.values())
1461
+ medrxiv_papers = set(by_medrxiv.values())
1462
+ biorxiv_papers = set(by_biorxiv.values())
1463
+ chemrxiv_papers = set(by_chemrxiv.values())
1464
+ # A row known only to PubMed, arXiv, medRxiv, bioRxiv, or chemRxiv carries no DOI or
1465
+ # OpenAlex ID, so _partition_candidates reports it unresolved. It is
1466
+ # resolvable whenever the provider that already knows its identifier is
1467
+ # being queried.
1468
+ identifier_papers = (pubmed_papers | arxiv_papers | medrxiv_papers | biorxiv_papers
1469
+ | chemrxiv_papers)
1470
+ identifier_only = [paper_id for paper_id in unresolved if paper_id in identifier_papers]
1471
+ unresolved = [paper_id for paper_id in unresolved if paper_id not in identifier_papers]
1472
+ if unresolved:
1473
+ set_enrichment_status(conn, unresolved, 'unresolved')
1474
+ summary['unresolved'] += len(unresolved)
1475
+ if not by_doi and not by_openalex and not identifier_only:
1476
+ return summary
1477
+
1478
+ fetched = _fetch(sources, _FetchContext(
1479
+ dois=list(by_doi), identifiers=list(by_openalex), email=email, api_key=api_key,
1480
+ openalex_session=openalex_session, crossref_session=crossref_session, pace=pace,
1481
+ pmids=list(by_pmid), pubmed_session=pubmed_session, pubmed_api_key=pubmed_api_key,
1482
+ arxiv_ids=list(by_arxiv), arxiv_session=arxiv_session,
1483
+ medrxiv_dois=list(by_medrxiv), medrxiv_session=medrxiv_session,
1484
+ biorxiv_dois=list(by_biorxiv), biorxiv_session=biorxiv_session,
1485
+ chemrxiv_dois=list(by_chemrxiv), chemrxiv_session=chemrxiv_session))
1486
+ pubmed_by_paper = {paper_id: fetched.pubmed_by_pmid[pmid]
1487
+ for pmid, paper_id in by_pmid.items() if pmid in fetched.pubmed_by_pmid}
1488
+ arxiv_by_paper = {paper_id: fetched.arxiv_by_id[identifier]
1489
+ for identifier, paper_id in by_arxiv.items()
1490
+ if identifier in fetched.arxiv_by_id}
1491
+ medrxiv_by_paper = {paper_id: fetched.medrxiv_by_doi[identifier]
1492
+ for identifier, paper_id in by_medrxiv.items()
1493
+ if identifier in fetched.medrxiv_by_doi}
1494
+ biorxiv_by_paper = {paper_id: fetched.biorxiv_by_doi[identifier]
1495
+ for identifier, paper_id in by_biorxiv.items()
1496
+ if identifier in fetched.biorxiv_by_doi}
1497
+ chemrxiv_by_paper = {paper_id: fetched.chemrxiv_by_doi[identifier]
1498
+ for identifier, paper_id in by_chemrxiv.items()
1499
+ if identifier in fetched.chemrxiv_by_doi}
1500
+
1501
+ targets = [(paper_id, fetched.crossref_works.get(key),
1502
+ fetched.openalex_by_doi.get(key), True)
1503
+ for key, paper_id in by_doi.items()]
1504
+ targets += [(paper_id, None, fetched.openalex_by_id.get(key), False)
1505
+ for key, paper_id in by_openalex.items()]
1506
+ targets += [(paper_id, None, None, False) for paper_id in identifier_only]
1507
+
1508
+ updates, authors, subjects, reference_records = [], [], [], []
1509
+ for paper_id, crossref_work, openalex_work, keyed_by_doi in targets:
1510
+ pubmed_article = pubmed_by_paper.get(paper_id)
1511
+ arxiv_entry = arxiv_by_paper.get(paper_id)
1512
+ medrxiv_entry = medrxiv_by_paper.get(paper_id)
1513
+ biorxiv_entry = biorxiv_by_paper.get(paper_id)
1514
+ chemrxiv_entry = chemrxiv_by_paper.get(paper_id)
1515
+ requested = [source for source in sources
1516
+ if (source == 'crossref' and keyed_by_doi)
1517
+ or (source == 'openalex'
1518
+ and (keyed_by_doi or paper_id in openalex_papers))
1519
+ or (source == 'pubmed' and paper_id in pubmed_papers)
1520
+ or (source == 'arxiv' and paper_id in arxiv_papers)
1521
+ or (source == 'medrxiv' and paper_id in medrxiv_papers)
1522
+ or (source == 'biorxiv' and paper_id in biorxiv_papers)
1523
+ or (source == 'chemrxiv' and paper_id in chemrxiv_papers)]
1524
+ errors = {source: fetched.errors[source]
1525
+ for source in requested if source in fetched.errors}
1526
+ update = _merge_fields(paper_id, crossref_work, openalex_work, requested,
1527
+ pubmed_article, arxiv_entry, medrxiv_entry, biorxiv_entry,
1528
+ chemrxiv_entry, provider_errors=errors)
1529
+ if errors:
1530
+ stored = conn.execute(
1531
+ 'SELECT * FROM papers WHERE paper_id = ?', (paper_id,)).fetchone()
1532
+ if stored is not None:
1533
+ _preserve_stored_values(update, stored)
1534
+ updates.append(update)
1535
+ summary[update['enrichment_status']] += 1
1536
+ if update['enrichment_status'] in {'failed', 'not_found'}:
1537
+ continue
1538
+ authors.extend(_author_rows(paper_id, crossref_work, openalex_work))
1539
+ subjects.extend(_subject_rows(paper_id, openalex_work))
1540
+ subjects.extend(_pubmed_subject_rows(paper_id, pubmed_article))
1541
+ subjects.extend(_arxiv_subject_rows(paper_id, arxiv_entry))
1542
+ subjects.extend(_medrxiv_subject_rows(paper_id, medrxiv_entry))
1543
+ subjects.extend(_biorxiv_subject_rows(paper_id, biorxiv_entry))
1544
+ subjects.extend(_chemrxiv_subject_rows(paper_id, chemrxiv_entry))
1545
+ if references:
1546
+ reference_records.extend(_reference_rows(paper_id, crossref_work, openalex_work))
1547
+
1548
+ for update in updates:
1549
+ update['enrichment_json'] = _json_text(update['enrichment_json'])
1550
+ # A provider outage is not evidence that its previously stored child rows
1551
+ # disappeared. Replace rows only for providers that completed this batch.
1552
+ completed_sources = [source for source in sources if source not in fetched.errors]
1553
+ write_enrichment(conn, updates, authors, subjects, reference_records,
1554
+ sources=completed_sources)
1555
+ summary['authors'] += len(authors)
1556
+ summary['subjects'] += len(subjects)
1557
+ summary['references'] += len(reference_records)
1558
+ return summary
1559
+
1560
+
1561
+ def _json_text(value: object) -> str:
1562
+ """Serialize a provenance document the way the corpus stores JSON."""
1563
+ if isinstance(value, str):
1564
+ return value
1565
+ return json.dumps(value or {}, sort_keys=True, default=str)
1566
+
1567
+
1568
+ def _enrich_from_crossref_message(conn: sqlite3.Connection,
1569
+ paper_id: str,
1570
+ message: Mapping[str, Any]) -> None:
1571
+ """Store enrichment for one paper from an already-fetched Crossref work.
1572
+
1573
+ This is the write path that keeps ``pmt import pdfs`` from discarding the
1574
+ publisher, work type, volume, issue, pages, ISSN and language it already
1575
+ fetched while resolving a PDF's DOI.
1576
+
1577
+ Parameters
1578
+ ----------
1579
+ conn : sqlite3.Connection
1580
+ Open corpus connection.
1581
+ paper_id : str
1582
+ Paper the Crossref record belongs to.
1583
+ message : Mapping[str, Any]
1584
+ Crossref work message.
1585
+ """
1586
+ if not paper_id or not message:
1587
+ return
1588
+ update = _merge_fields(paper_id, message, None, ['crossref'])
1589
+ update['enrichment_json'] = _json_text(update['enrichment_json'])
1590
+ write_enrichment(conn,
1591
+ [update],
1592
+ _author_rows(paper_id, message, None),
1593
+ [],
1594
+ _reference_rows(paper_id, message, None))
1595
+
1596
+
1597
+ def enrich_papers(conn: sqlite3.Connection,
1598
+ papers: Iterable[Mapping[str, Any]],
1599
+ sources: Sequence[str] | None = None,
1600
+ batch_size: int = MAX_BATCH_SIZE,
1601
+ references: bool = True,
1602
+ email: str | None = None,
1603
+ api_key: str | None = None,
1604
+ openalex_session: provider.HTTPClient | None = None,
1605
+ crossref_session: provider.HTTPClient | None = None,
1606
+ pace: float = crossref_client.CROSSREF_MIN_INTERVAL,
1607
+ pubmed_session: provider.HTTPClient | None = None,
1608
+ pubmed_api_key: str | None = None,
1609
+ arxiv_session: provider.HTTPClient | None = None,
1610
+ medrxiv_session: provider.HTTPClient | None = None,
1611
+ biorxiv_session: provider.HTTPClient | None = None,
1612
+ chemrxiv_session: provider.HTTPClient | None = None) -> dict[str, int]:
1613
+ """Enrich specific papers on an already-open corpus connection.
1614
+
1615
+ Incoming rows are resolved against the corpus first, because discovery
1616
+ merges matching records and the stored row may carry a different paper
1617
+ identifier than the provider row that produced it.
1618
+
1619
+ Parameters
1620
+ ----------
1621
+ conn : sqlite3.Connection
1622
+ Open corpus connection.
1623
+ papers : Iterable[Mapping[str, Any]]
1624
+ Paper rows to enrich.
1625
+ sources : Sequence[str] or None, optional
1626
+ Providers to query. ``None`` selects every provider.
1627
+ batch_size : int, default=100
1628
+ Papers looked up per provider request.
1629
+ references : bool, default=True
1630
+ Whether to store reference lists.
1631
+ email : str or None, optional
1632
+ Contact email. Defaults to the stored Crossref setting.
1633
+ api_key : str or None, optional
1634
+ OpenAlex API key. Defaults to the configured key.
1635
+ openalex_session : provider.HTTPClient or None, optional
1636
+ HTTP client used for OpenAlex requests.
1637
+ crossref_session : provider.HTTPClient or None, optional
1638
+ HTTP session used for Crossref requests.
1639
+ pace : float, optional
1640
+ Seconds to wait between consecutive Crossref requests.
1641
+ pubmed_session : provider.HTTPClient or None, optional
1642
+ HTTP client used for PubMed requests.
1643
+ pubmed_api_key : str or None, optional
1644
+ NCBI API key. Defaults to the configured key.
1645
+ arxiv_session : provider.HTTPClient or None, optional
1646
+ HTTP client used for arXiv requests.
1647
+ medrxiv_session : provider.HTTPClient or None, optional
1648
+ HTTP client used for medRxiv requests.
1649
+ biorxiv_session : provider.HTTPClient or None, optional
1650
+ HTTP client used for bioRxiv requests.
1651
+ chemrxiv_session : provider.HTTPClient or None, optional
1652
+ HTTP client used for chemRxiv requests.
1653
+
1654
+ Returns
1655
+ -------
1656
+ dict[str, int]
1657
+ Counts of each resulting status and of stored child rows.
1658
+ """
1659
+ sources = _configured_sources(sources)
1660
+ email = crossref_client.resolve_email(email) if 'crossref' in sources else (email or '')
1661
+ if not email and 'pubmed' in sources:
1662
+ email = pubmed.configured_email()
1663
+ api_key = api_key if api_key is not None else openalex.configured_api_key()
1664
+ if pubmed_api_key is None and 'pubmed' in sources:
1665
+ pubmed_api_key = pubmed.configured_api_key()
1666
+
1667
+ resolved: dict[str, _Record] = {}
1668
+ stored = {row['paper_id']: row for row in paper_rows(conn)}
1669
+ for paper in papers:
1670
+ paper_id = str(paper.get('paper_id') or '')
1671
+ row = stored.get(paper_id) or find_paper(conn, paper)
1672
+ if row:
1673
+ resolved[str(row['paper_id'])] = row
1674
+
1675
+ summary = {status: 0 for status in
1676
+ ('succeeded', 'partial', 'not_found', 'unresolved', 'failed')}
1677
+ summary.update({'authors': 0, 'subjects': 0, 'references': 0})
1678
+ candidates = list(resolved.values())
1679
+ batch_size = max(1, min(batch_size, MAX_BATCH_SIZE))
1680
+ for start in range(0, len(candidates), batch_size):
1681
+ batch = candidates[start:start + batch_size]
1682
+ for key, value in _enrich_batch(conn, batch, sources, email, api_key, references,
1683
+ openalex_session, crossref_session, pace,
1684
+ pubmed_session, pubmed_api_key,
1685
+ arxiv_session, medrxiv_session,
1686
+ biorxiv_session, chemrxiv_session).items():
1687
+ summary[key] += value
1688
+ return summary
1689
+
1690
+
1691
+ def _selected_statuses(force: bool, retry_failed: bool) -> tuple[str, ...]:
1692
+ """Choose which enrichment statuses a run re-processes."""
1693
+ statuses = ['pending']
1694
+ if force:
1695
+ statuses.extend(['succeeded', 'partial', 'not_found'])
1696
+ if retry_failed:
1697
+ statuses.append('failed')
1698
+ return tuple(statuses)
1699
+
1700
+
1701
+ def enrich_corpus(db_path: str | PathLike[str] = 'papers.db',
1702
+ sources: Sequence[str] | None = None,
1703
+ batch_size: int = MAX_BATCH_SIZE,
1704
+ limit: int | None = None,
1705
+ force: bool = False,
1706
+ retry_failed: bool = False,
1707
+ refresh_after: int = 0,
1708
+ references: bool = True,
1709
+ resolve_references: bool = False,
1710
+ email: str | None = None,
1711
+ api_key: str | None = None,
1712
+ openalex_session: provider.HTTPClient | None = None,
1713
+ crossref_session: provider.HTTPClient | None = None,
1714
+ pace: float = crossref_client.CROSSREF_MIN_INTERVAL,
1715
+ pubmed_session: provider.HTTPClient | None = None,
1716
+ pubmed_api_key: str | None = None,
1717
+ arxiv_session: provider.HTTPClient | None = None,
1718
+ medrxiv_session: provider.HTTPClient | None = None,
1719
+ biorxiv_session: provider.HTTPClient | None = None,
1720
+ chemrxiv_session: provider.HTTPClient | None = None) -> dict[str, int]:
1721
+ """Supplement every candidate paper in a corpus with provider metadata.
1722
+
1723
+ Progress is committed after each batch, so an interrupted or budget-limited
1724
+ run keeps the work it already did and a later run resumes from the first
1725
+ paper that is still pending.
1726
+
1727
+ Parameters
1728
+ ----------
1729
+ db_path : str or os.PathLike[str], default='papers.db'
1730
+ Path to the SQLite paper corpus.
1731
+ sources : Sequence[str] or None, optional
1732
+ Providers to query. ``None`` selects every provider.
1733
+ batch_size : int, default=100
1734
+ Papers looked up per provider request.
1735
+ limit : int or None, optional
1736
+ Stop after enriching this many papers.
1737
+ force : bool, default=False
1738
+ Re-enrich papers whose enrichment already succeeded.
1739
+ retry_failed : bool, default=False
1740
+ Retry papers whose previous enrichment failed.
1741
+ refresh_after : int, default=0
1742
+ Re-enrich succeeded papers older than this many days. ``0`` disables it.
1743
+ references : bool, default=True
1744
+ Whether to store reference lists.
1745
+ resolve_references : bool, default=False
1746
+ Whether to resolve OpenAlex reference identifiers to DOIs afterwards.
1747
+ email : str or None, optional
1748
+ Contact email. Defaults to the stored Crossref setting.
1749
+ api_key : str or None, optional
1750
+ OpenAlex API key. Defaults to the configured key.
1751
+ openalex_session : provider.HTTPClient or None, optional
1752
+ HTTP client used for OpenAlex requests.
1753
+ crossref_session : provider.HTTPClient or None, optional
1754
+ HTTP session used for Crossref requests.
1755
+ pace : float, optional
1756
+ Seconds to wait between consecutive Crossref requests.
1757
+ pubmed_session : provider.HTTPClient or None, optional
1758
+ HTTP client used for PubMed requests.
1759
+ pubmed_api_key : str or None, optional
1760
+ NCBI API key. Defaults to the configured key.
1761
+ arxiv_session : provider.HTTPClient or None, optional
1762
+ HTTP client used for arXiv requests.
1763
+ medrxiv_session : provider.HTTPClient or None, optional
1764
+ HTTP client used for medRxiv requests.
1765
+ biorxiv_session : provider.HTTPClient or None, optional
1766
+ HTTP client used for bioRxiv requests.
1767
+ chemrxiv_session : provider.HTTPClient or None, optional
1768
+ HTTP client used for chemRxiv requests.
1769
+
1770
+ Returns
1771
+ -------
1772
+ dict[str, int]
1773
+ Counts of each resulting status and of stored child rows.
1774
+
1775
+ Raises
1776
+ ------
1777
+ ValueError
1778
+ If the provider selection, batch size, or contact email is invalid.
1779
+ RuntimeError
1780
+ If a provider request cannot be completed.
1781
+ """
1782
+ sources = _configured_sources(sources)
1783
+ if batch_size < 1 or batch_size > MAX_BATCH_SIZE:
1784
+ raise ValueError(f'batch_size must be between 1 and {MAX_BATCH_SIZE}.')
1785
+ email = crossref_client.resolve_email(email) if 'crossref' in sources else (email or '')
1786
+ if not email and 'pubmed' in sources:
1787
+ email = pubmed.configured_email()
1788
+ api_key = api_key if api_key is not None else openalex.configured_api_key()
1789
+ if pubmed_api_key is None and 'pubmed' in sources:
1790
+ pubmed_api_key = pubmed.configured_api_key()
1791
+ statuses = _selected_statuses(force, retry_failed)
1792
+ refreshed_before = ''
1793
+ if refresh_after > 0:
1794
+ cutoff = datetime.now(timezone.utc) - timedelta(days=refresh_after)
1795
+ refreshed_before = cutoff.isoformat(timespec='seconds')
1796
+
1797
+ summary = {status: 0 for status in
1798
+ ('succeeded', 'partial', 'not_found', 'unresolved', 'failed')}
1799
+ summary.update({'authors': 0, 'subjects': 0, 'references': 0, 'batches': 0})
1800
+
1801
+ with connect(db_path) as conn:
1802
+ remaining = limit
1803
+ after_rowid = 0
1804
+ with tqdm(total=limit, desc='Enriching Papers', colour='#FFA500') as progress:
1805
+ while remaining is None or remaining > 0:
1806
+ page = batch_size if remaining is None else min(batch_size, remaining)
1807
+ candidates = enrichment_candidates(conn, statuses=statuses,
1808
+ after_rowid=after_rowid, limit=page,
1809
+ refreshed_before=refreshed_before)
1810
+ if not candidates:
1811
+ break
1812
+ after_rowid = int(candidates[-1]['rowid'])
1813
+ counts = _enrich_batch(conn, candidates, sources, email, api_key, references,
1814
+ openalex_session, crossref_session, pace,
1815
+ pubmed_session, pubmed_api_key, arxiv_session,
1816
+ medrxiv_session, biorxiv_session, chemrxiv_session)
1817
+ for key, value in counts.items():
1818
+ summary[key] += value
1819
+ summary['batches'] += 1
1820
+ progress.update(len(candidates))
1821
+ if remaining is not None:
1822
+ remaining -= len(candidates)
1823
+ if resolve_references:
1824
+ _resolve_reference_targets(conn)
1825
+ return summary
1826
+
1827
+
1828
+ def resolve_reference_dois(db_path: str | PathLike[str] = 'papers.db',
1829
+ batch_size: int = MAX_BATCH_SIZE,
1830
+ api_key: str | None = None,
1831
+ session: provider.HTTPClient | None = None,
1832
+ mailto: str = '') -> int:
1833
+ """Resolve stored OpenAlex reference identifiers to DOIs.
1834
+
1835
+ Identifiers are deduplicated across the whole corpus first, so a work cited
1836
+ by many papers costs one lookup rather than one lookup per citing paper.
1837
+
1838
+ Parameters
1839
+ ----------
1840
+ db_path : str or os.PathLike[str], default='papers.db'
1841
+ Path to the SQLite paper corpus.
1842
+ batch_size : int, default=100
1843
+ Identifiers looked up per OpenAlex request.
1844
+ api_key : str or None, optional
1845
+ OpenAlex API key. Defaults to the configured key.
1846
+ session : provider.HTTPClient or None, optional
1847
+ HTTP client used for OpenAlex requests.
1848
+ mailto : str, default=''
1849
+ Contact email sent with the requests.
1850
+
1851
+ Returns
1852
+ -------
1853
+ int
1854
+ Number of reference rows given a DOI.
1855
+ """
1856
+ api_key = api_key if api_key is not None else openalex.configured_api_key()
1857
+ updated = 0
1858
+ with connect(db_path) as conn:
1859
+ pending = [row[0] for row in conn.execute(
1860
+ "SELECT DISTINCT referenced_openalex_id FROM paper_references "
1861
+ "WHERE referenced_openalex_id <> '' AND referenced_doi = ''"
1862
+ ).fetchall()]
1863
+ for start in range(0, len(pending), batch_size):
1864
+ chunk = pending[start:start + batch_size]
1865
+ works = openalex.works_batch(chunk, filter_name='ids.openalex',
1866
+ select=('id', 'doi'), api_key=api_key,
1867
+ session=session, mailto=mailto)
1868
+ resolved = [(clean_doi(work.get('doi')), identifier)
1869
+ for identifier, work in works.items() if clean_doi(work.get('doi'))]
1870
+ if not resolved:
1871
+ continue
1872
+ cursor = conn.executemany(
1873
+ 'UPDATE paper_references SET referenced_doi = ? WHERE referenced_openalex_id = ?',
1874
+ resolved,
1875
+ )
1876
+ updated += cursor.rowcount if cursor.rowcount > 0 else 0
1877
+ conn.commit()
1878
+ _resolve_reference_targets(conn)
1879
+ return updated
1880
+
1881
+
1882
+ def _resolve_reference_targets(conn: sqlite3.Connection) -> int:
1883
+ """Link referenced DOIs to papers already present in the corpus.
1884
+
1885
+ Parameters
1886
+ ----------
1887
+ conn : sqlite3.Connection
1888
+ Open corpus connection.
1889
+
1890
+ Returns
1891
+ -------
1892
+ int
1893
+ Number of reference rows linked to a corpus paper.
1894
+ """
1895
+ cursor = conn.execute(
1896
+ """
1897
+ UPDATE paper_references
1898
+ SET referenced_paper_id = COALESCE(
1899
+ (SELECT papers.paper_id FROM papers WHERE papers.doi = paper_references.referenced_doi),
1900
+ ''
1901
+ )
1902
+ WHERE referenced_doi <> ''
1903
+ """
1904
+ )
1905
+ conn.commit()
1906
+ return cursor.rowcount if cursor.rowcount > 0 else 0