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.
- paperminertoolkit/__init__.py +10 -0
- paperminertoolkit/_version.py +11 -0
- paperminertoolkit/cli.py +1053 -0
- paperminertoolkit/corpus/__init__.py +1 -0
- paperminertoolkit/corpus/database.py +1542 -0
- paperminertoolkit/corpus/documents.py +313 -0
- paperminertoolkit/corpus/filtering.py +1390 -0
- paperminertoolkit/corpus/metadata.py +532 -0
- paperminertoolkit/extraction/__init__.py +1 -0
- paperminertoolkit/extraction/compression.py +486 -0
- paperminertoolkit/extraction/extract.py +573 -0
- paperminertoolkit/extraction/models.py +784 -0
- paperminertoolkit/extraction/recipes.py +241 -0
- paperminertoolkit/extraction/scrape.py +737 -0
- paperminertoolkit/extraction/store.py +244 -0
- paperminertoolkit/extraction/tokenizer.py +313 -0
- paperminertoolkit/providers/__init__.py +1 -0
- paperminertoolkit/providers/arxiv.py +760 -0
- paperminertoolkit/providers/base.py +514 -0
- paperminertoolkit/providers/biorxiv.py +561 -0
- paperminertoolkit/providers/chemrxiv.py +1115 -0
- paperminertoolkit/providers/core.py +423 -0
- paperminertoolkit/providers/crossref.py +649 -0
- paperminertoolkit/providers/elsevier.py +455 -0
- paperminertoolkit/providers/medrxiv.py +548 -0
- paperminertoolkit/providers/openalex.py +471 -0
- paperminertoolkit/providers/pubmed.py +1272 -0
- paperminertoolkit/providers/registry.py +521 -0
- paperminertoolkit/providers/rxiv.py +936 -0
- paperminertoolkit/providers/unpaywall.py +162 -0
- paperminertoolkit/resources/recipes.json +1670 -0
- paperminertoolkit/settings.py +661 -0
- paperminertoolkit/workflows/__init__.py +1 -0
- paperminertoolkit/workflows/download.py +1748 -0
- paperminertoolkit/workflows/enrichment.py +1906 -0
- paperminertoolkit/workflows/imports.py +121 -0
- paperminertoolkit/workflows/search.py +877 -0
- paperminertoolkit/workflows/topics.py +2837 -0
- paperminertoolkit/workflows/utilities.py +73 -0
- paperminertoolkit-1.0.0.dist-info/METADATA +126 -0
- paperminertoolkit-1.0.0.dist-info/RECORD +45 -0
- paperminertoolkit-1.0.0.dist-info/WHEEL +5 -0
- paperminertoolkit-1.0.0.dist-info/entry_points.txt +2 -0
- paperminertoolkit-1.0.0.dist-info/licenses/LICENSE +21 -0
- paperminertoolkit-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,649 @@
|
|
|
1
|
+
"""Discover an author's works through Crossref and import their metadata."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import unicodedata
|
|
7
|
+
from collections.abc import Mapping, Sequence
|
|
8
|
+
from os import PathLike
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, TypeAlias
|
|
11
|
+
from urllib.parse import quote
|
|
12
|
+
|
|
13
|
+
import pandas as pd
|
|
14
|
+
import requests
|
|
15
|
+
|
|
16
|
+
from paperminertoolkit.corpus.database import connect, find_paper, upsert_paper, upsert_papers
|
|
17
|
+
from paperminertoolkit.providers import base as provider
|
|
18
|
+
from paperminertoolkit.corpus.metadata import clean_doi
|
|
19
|
+
from paperminertoolkit.settings import load_settings
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
CROSSREF_WORKS_URL = 'https://api.crossref.org/v1/works'
|
|
23
|
+
CROSSREF_SINGLE_WORK_URL = 'https://api.crossref.org/works'
|
|
24
|
+
CROSSREF_MIN_INTERVAL = 0.34
|
|
25
|
+
MAX_FILTER_VALUES = 100
|
|
26
|
+
BATCHABLE_DOI_PATTERN = re.compile(r'^10\.\d{4,9}/[^\s,]+$')
|
|
27
|
+
ORCID_PATTERN = re.compile(r'^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$', re.IGNORECASE)
|
|
28
|
+
REVIEW_COLUMNS = ['paper_id', 'doi', 'title', 'journal', 'publication_date', 'authors', 'sources']
|
|
29
|
+
_CrossrefRecord: TypeAlias = dict[str, Any]
|
|
30
|
+
LIMITER = provider.RateLimiter(CROSSREF_MIN_INTERVAL)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def normalize_orcid(value: str | None) -> str:
|
|
34
|
+
"""Normalize and validate an ORCID identifier.
|
|
35
|
+
|
|
36
|
+
Parameters
|
|
37
|
+
----------
|
|
38
|
+
value : str or None
|
|
39
|
+
Bare ORCID or ORCID URL.
|
|
40
|
+
|
|
41
|
+
Returns
|
|
42
|
+
-------
|
|
43
|
+
str
|
|
44
|
+
Upper-case, hyphenated ORCID identifier.
|
|
45
|
+
|
|
46
|
+
Raises
|
|
47
|
+
------
|
|
48
|
+
ValueError
|
|
49
|
+
If the identifier format or checksum is invalid.
|
|
50
|
+
"""
|
|
51
|
+
orcid = str(value or '').strip().rstrip('/').split('/')[-1].upper()
|
|
52
|
+
if not ORCID_PATTERN.fullmatch(orcid):
|
|
53
|
+
raise ValueError(f'Invalid ORCID: {value}')
|
|
54
|
+
compact = orcid.replace('-', '')
|
|
55
|
+
total = 0
|
|
56
|
+
for digit in compact[:-1]:
|
|
57
|
+
total = (total + int(digit)) * 2
|
|
58
|
+
checksum = (12 - (total % 11)) % 11
|
|
59
|
+
expected = 'X' if checksum == 10 else str(checksum)
|
|
60
|
+
if compact[-1] != expected:
|
|
61
|
+
raise ValueError(f'Invalid ORCID checksum: {value}')
|
|
62
|
+
return orcid
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _normalize_text(value: object) -> str:
|
|
66
|
+
"""Normalize human-readable metadata for comparison.
|
|
67
|
+
|
|
68
|
+
Parameters
|
|
69
|
+
----------
|
|
70
|
+
value : object
|
|
71
|
+
Value to normalize as text.
|
|
72
|
+
|
|
73
|
+
Returns
|
|
74
|
+
-------
|
|
75
|
+
str
|
|
76
|
+
Lower-case ASCII comparison key.
|
|
77
|
+
"""
|
|
78
|
+
value = unicodedata.normalize('NFKD', str(value or ''))
|
|
79
|
+
value = ''.join(character for character in value if not unicodedata.combining(character))
|
|
80
|
+
return re.sub(r'[^a-z0-9]+', ' ', value.lower()).strip()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _given_names_match(target: object, candidate: object) -> bool:
|
|
84
|
+
"""Compare given names while allowing initials.
|
|
85
|
+
|
|
86
|
+
Parameters
|
|
87
|
+
----------
|
|
88
|
+
target : object
|
|
89
|
+
Requested given names.
|
|
90
|
+
candidate : object
|
|
91
|
+
Deposited given names to compare.
|
|
92
|
+
|
|
93
|
+
Returns
|
|
94
|
+
-------
|
|
95
|
+
bool
|
|
96
|
+
Whether the normalized names match.
|
|
97
|
+
"""
|
|
98
|
+
target_parts = _normalize_text(target).split()
|
|
99
|
+
candidate_parts = _normalize_text(candidate).split()
|
|
100
|
+
if not target_parts or not candidate_parts:
|
|
101
|
+
return False
|
|
102
|
+
if target_parts == candidate_parts:
|
|
103
|
+
return True
|
|
104
|
+
if all(len(part) > 1 for part in target_parts + candidate_parts):
|
|
105
|
+
return False
|
|
106
|
+
return ''.join(part[0] for part in target_parts) == ''.join(part[0] for part in candidate_parts)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _matching_authors(work: _CrossrefRecord, author_name: str) -> list[_CrossrefRecord]:
|
|
110
|
+
"""Find Crossref authors matching a human name.
|
|
111
|
+
|
|
112
|
+
Parameters
|
|
113
|
+
----------
|
|
114
|
+
work : _CrossrefRecord
|
|
115
|
+
Crossref work record containing author metadata.
|
|
116
|
+
author_name : str
|
|
117
|
+
Given and family names to match.
|
|
118
|
+
|
|
119
|
+
Returns
|
|
120
|
+
-------
|
|
121
|
+
list[_CrossrefRecord]
|
|
122
|
+
Matching Crossref author records.
|
|
123
|
+
|
|
124
|
+
Raises
|
|
125
|
+
------
|
|
126
|
+
ValueError
|
|
127
|
+
If ``author_name`` does not contain given and family names.
|
|
128
|
+
"""
|
|
129
|
+
parts = _normalize_text(author_name).split()
|
|
130
|
+
if len(parts) < 2:
|
|
131
|
+
raise ValueError('Author name must include given and family names.')
|
|
132
|
+
target_given = ' '.join(parts[:-1])
|
|
133
|
+
target_family = parts[-1]
|
|
134
|
+
return [
|
|
135
|
+
author
|
|
136
|
+
for author in work.get('author') or []
|
|
137
|
+
if _normalize_text(author.get('family')) == target_family
|
|
138
|
+
and _given_names_match(target_given, author.get('given'))
|
|
139
|
+
]
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _author_orcid(author: _CrossrefRecord) -> str:
|
|
143
|
+
"""Read a valid ORCID from an author record.
|
|
144
|
+
|
|
145
|
+
Parameters
|
|
146
|
+
----------
|
|
147
|
+
author : _CrossrefRecord
|
|
148
|
+
Crossref author record.
|
|
149
|
+
|
|
150
|
+
Returns
|
|
151
|
+
-------
|
|
152
|
+
str
|
|
153
|
+
Normalized ORCID, or an empty string for malformed values.
|
|
154
|
+
"""
|
|
155
|
+
try:
|
|
156
|
+
return normalize_orcid(author.get('ORCID'))
|
|
157
|
+
except ValueError:
|
|
158
|
+
return ''
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def work_matches_author(
|
|
162
|
+
work: _CrossrefRecord,
|
|
163
|
+
author_name: str | None = None,
|
|
164
|
+
orcid: str | None = None,
|
|
165
|
+
affiliation: str | None = None,
|
|
166
|
+
) -> bool:
|
|
167
|
+
"""Check whether a work contains the requested author identity.
|
|
168
|
+
|
|
169
|
+
Parameters
|
|
170
|
+
----------
|
|
171
|
+
work : _CrossrefRecord
|
|
172
|
+
Crossref work record.
|
|
173
|
+
author_name : str, optional
|
|
174
|
+
Human-readable author name to match when no ORCID is supplied.
|
|
175
|
+
orcid : str, optional
|
|
176
|
+
ORCID identifier to match exactly.
|
|
177
|
+
affiliation : str, optional
|
|
178
|
+
Affiliation fragment required on a matching author record.
|
|
179
|
+
|
|
180
|
+
Returns
|
|
181
|
+
-------
|
|
182
|
+
bool
|
|
183
|
+
Whether the requested identity is present.
|
|
184
|
+
|
|
185
|
+
Raises
|
|
186
|
+
------
|
|
187
|
+
ValueError
|
|
188
|
+
If ``orcid`` is invalid or ``author_name`` lacks both given and family
|
|
189
|
+
names.
|
|
190
|
+
"""
|
|
191
|
+
authors = work.get('author') or []
|
|
192
|
+
if orcid:
|
|
193
|
+
expected = normalize_orcid(orcid)
|
|
194
|
+
matches = [
|
|
195
|
+
author for author in authors
|
|
196
|
+
if _author_orcid(author) == expected
|
|
197
|
+
]
|
|
198
|
+
else:
|
|
199
|
+
matches = _matching_authors(work, author_name)
|
|
200
|
+
if not matches:
|
|
201
|
+
return False
|
|
202
|
+
if not affiliation:
|
|
203
|
+
return True
|
|
204
|
+
affiliation_key = _normalize_text(affiliation)
|
|
205
|
+
return any(
|
|
206
|
+
affiliation_key in _normalize_text(entry.get('name'))
|
|
207
|
+
for author in matches
|
|
208
|
+
for entry in author.get('affiliation') or []
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _request_page(
|
|
213
|
+
session: provider.HTTPClient,
|
|
214
|
+
params: dict[str, str | int],
|
|
215
|
+
email: str,
|
|
216
|
+
url: str = CROSSREF_WORKS_URL,
|
|
217
|
+
timeout: float = 60,
|
|
218
|
+
attempts: int = 4,
|
|
219
|
+
pace: float | None = None,
|
|
220
|
+
) -> _CrossrefRecord:
|
|
221
|
+
"""Request one Crossref page with bounded retries.
|
|
222
|
+
|
|
223
|
+
Parameters
|
|
224
|
+
----------
|
|
225
|
+
session : provider.HTTPClient
|
|
226
|
+
HTTP session used for the request.
|
|
227
|
+
params : dict[str, str or int]
|
|
228
|
+
Crossref query parameters.
|
|
229
|
+
email : str
|
|
230
|
+
Contact email included in the user agent.
|
|
231
|
+
url : str, optional
|
|
232
|
+
Crossref endpoint to request.
|
|
233
|
+
timeout : float, optional
|
|
234
|
+
Request timeout in seconds.
|
|
235
|
+
attempts : int, optional
|
|
236
|
+
Maximum number of request attempts.
|
|
237
|
+
pace : float or None, optional
|
|
238
|
+
Pacing override for this request, in seconds.
|
|
239
|
+
|
|
240
|
+
Returns
|
|
241
|
+
-------
|
|
242
|
+
_CrossrefRecord
|
|
243
|
+
Crossref response message.
|
|
244
|
+
|
|
245
|
+
Raises
|
|
246
|
+
------
|
|
247
|
+
RuntimeError
|
|
248
|
+
If every request attempt fails or returns an invalid payload.
|
|
249
|
+
"""
|
|
250
|
+
response = provider.request(url, label='Crossref', limiter=LIMITER, params=params,
|
|
251
|
+
headers=provider.default_headers(email), session=session,
|
|
252
|
+
timeout=timeout, attempts=attempts, missing_ok=False,
|
|
253
|
+
interval=pace,
|
|
254
|
+
error_types=(*provider.RETRY_ERRORS, KeyError))
|
|
255
|
+
if response is None:
|
|
256
|
+
raise RuntimeError(f'Crossref request failed after {attempts} attempts: 404')
|
|
257
|
+
return response.json()['message']
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def configured_email(settings: Mapping[str, str] | None = None) -> str:
|
|
261
|
+
"""Return the configured Crossref contact email.
|
|
262
|
+
|
|
263
|
+
Parameters
|
|
264
|
+
----------
|
|
265
|
+
settings : Mapping[str, str] or None, optional
|
|
266
|
+
Settings mapping to inspect instead of loading the stored settings.
|
|
267
|
+
|
|
268
|
+
Returns
|
|
269
|
+
-------
|
|
270
|
+
str
|
|
271
|
+
Configured contact email, or an empty string when none is stored.
|
|
272
|
+
"""
|
|
273
|
+
settings = settings if settings is not None else load_settings()
|
|
274
|
+
return str(settings.get('crossref_email') or '')
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def resolve_email(email: str | None = None) -> str:
|
|
278
|
+
"""Resolve the Crossref contact email, preferring an explicit value.
|
|
279
|
+
|
|
280
|
+
Parameters
|
|
281
|
+
----------
|
|
282
|
+
email : str or None, optional
|
|
283
|
+
Contact email supplied by the caller.
|
|
284
|
+
|
|
285
|
+
Returns
|
|
286
|
+
-------
|
|
287
|
+
str
|
|
288
|
+
Resolved contact email.
|
|
289
|
+
|
|
290
|
+
Raises
|
|
291
|
+
------
|
|
292
|
+
ValueError
|
|
293
|
+
If no valid contact email is available.
|
|
294
|
+
"""
|
|
295
|
+
resolved = str(email or '').strip() or configured_email()
|
|
296
|
+
if not resolved or '@' not in resolved:
|
|
297
|
+
raise ValueError(
|
|
298
|
+
'A contact email is required for Crossref requests. '
|
|
299
|
+
'Run pmt config crossref-email, set CROSSREF_EMAIL, or pass --email.'
|
|
300
|
+
)
|
|
301
|
+
return resolved
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def work_by_doi(doi: str,
|
|
305
|
+
email: str | None = None,
|
|
306
|
+
session: provider.HTTPClient | None = None,
|
|
307
|
+
timeout: float = 60) -> _CrossrefRecord | None:
|
|
308
|
+
"""Look up one Crossref work through the single-work route.
|
|
309
|
+
|
|
310
|
+
Parameters
|
|
311
|
+
----------
|
|
312
|
+
doi : str
|
|
313
|
+
DOI to look up.
|
|
314
|
+
email : str or None, optional
|
|
315
|
+
Contact email for Crossref requests.
|
|
316
|
+
session : provider.HTTPClient or None, optional
|
|
317
|
+
HTTP session used for the request.
|
|
318
|
+
timeout : float, default=60
|
|
319
|
+
Request timeout in seconds.
|
|
320
|
+
|
|
321
|
+
Returns
|
|
322
|
+
-------
|
|
323
|
+
_CrossrefRecord or None
|
|
324
|
+
Crossref work record, or ``None`` when Crossref does not know the DOI.
|
|
325
|
+
|
|
326
|
+
Raises
|
|
327
|
+
------
|
|
328
|
+
ValueError
|
|
329
|
+
If no contact email is available.
|
|
330
|
+
RuntimeError
|
|
331
|
+
If the Crossref request exhausts its retries.
|
|
332
|
+
"""
|
|
333
|
+
doi = clean_doi(doi)
|
|
334
|
+
if not doi:
|
|
335
|
+
return None
|
|
336
|
+
email = resolve_email(email)
|
|
337
|
+
session = session or requests.Session()
|
|
338
|
+
url = f'{CROSSREF_SINGLE_WORK_URL}/{quote(doi, safe="")}'
|
|
339
|
+
try:
|
|
340
|
+
return _request_page(session, {'mailto': email}, email, url=url)
|
|
341
|
+
except RuntimeError:
|
|
342
|
+
return None
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def works_by_doi(dois: Sequence[str],
|
|
346
|
+
email: str | None = None,
|
|
347
|
+
session: provider.HTTPClient | None = None,
|
|
348
|
+
batch_size: int = MAX_FILTER_VALUES,
|
|
349
|
+
pace: float = CROSSREF_MIN_INTERVAL) -> dict[str, _CrossrefRecord]:
|
|
350
|
+
"""Look up Crossref works in paced DOI batches.
|
|
351
|
+
|
|
352
|
+
Crossref treats repeated ``doi`` filters as alternatives, returns matches
|
|
353
|
+
in an arbitrary order, and omits DOIs it does not know, so results are
|
|
354
|
+
keyed by cleaned DOI rather than zipped onto the request order. No
|
|
355
|
+
``select`` is sent because ``language`` is returned by default but is not a
|
|
356
|
+
selectable field. DOIs containing a comma are requested individually
|
|
357
|
+
because the comma separates Crossref filter terms.
|
|
358
|
+
|
|
359
|
+
Parameters
|
|
360
|
+
----------
|
|
361
|
+
dois : Sequence[str]
|
|
362
|
+
DOIs to look up.
|
|
363
|
+
email : str or None, optional
|
|
364
|
+
Contact email for Crossref requests.
|
|
365
|
+
session : provider.HTTPClient or None, optional
|
|
366
|
+
HTTP session used for the requests.
|
|
367
|
+
batch_size : int, default=100
|
|
368
|
+
DOIs requested per Crossref page.
|
|
369
|
+
pace : float, default=0.34
|
|
370
|
+
Seconds to wait between consecutive Crossref requests.
|
|
371
|
+
|
|
372
|
+
Returns
|
|
373
|
+
-------
|
|
374
|
+
dict[str, _CrossrefRecord]
|
|
375
|
+
Crossref work records keyed by cleaned DOI.
|
|
376
|
+
|
|
377
|
+
Raises
|
|
378
|
+
------
|
|
379
|
+
ValueError
|
|
380
|
+
If ``batch_size`` is invalid or no contact email is available.
|
|
381
|
+
RuntimeError
|
|
382
|
+
If a Crossref request exhausts its retries.
|
|
383
|
+
"""
|
|
384
|
+
if batch_size < 1 or batch_size > MAX_FILTER_VALUES:
|
|
385
|
+
raise ValueError(f'batch_size must be between 1 and {MAX_FILTER_VALUES}.')
|
|
386
|
+
email = resolve_email(email)
|
|
387
|
+
session = session or requests.Session()
|
|
388
|
+
wanted = list(dict.fromkeys(clean_doi(doi) for doi in dois if clean_doi(doi)))
|
|
389
|
+
batched = [doi for doi in wanted if BATCHABLE_DOI_PATTERN.match(doi)]
|
|
390
|
+
individual = [doi for doi in wanted if not BATCHABLE_DOI_PATTERN.match(doi)]
|
|
391
|
+
|
|
392
|
+
works = {}
|
|
393
|
+
for start in range(0, len(batched), batch_size):
|
|
394
|
+
chunk = batched[start:start + batch_size]
|
|
395
|
+
try:
|
|
396
|
+
message = _request_page(
|
|
397
|
+
session,
|
|
398
|
+
{
|
|
399
|
+
'filter': ','.join(f'doi:{doi}' for doi in chunk),
|
|
400
|
+
'rows': len(chunk),
|
|
401
|
+
'mailto': email,
|
|
402
|
+
},
|
|
403
|
+
email,
|
|
404
|
+
pace=pace,
|
|
405
|
+
)
|
|
406
|
+
except RuntimeError:
|
|
407
|
+
# Crossref rejects an entire filter when one value is unusable, so
|
|
408
|
+
# fall back to single-work lookups rather than losing the chunk.
|
|
409
|
+
individual.extend(chunk)
|
|
410
|
+
continue
|
|
411
|
+
for work in message.get('items') or []:
|
|
412
|
+
key = clean_doi(work.get('DOI'))
|
|
413
|
+
if key:
|
|
414
|
+
works[key] = work
|
|
415
|
+
for doi in individual:
|
|
416
|
+
work = work_by_doi(doi, email=email, session=session)
|
|
417
|
+
if work:
|
|
418
|
+
works[clean_doi(work.get('DOI')) or doi] = work
|
|
419
|
+
return works
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def author_works(orcid: str | None = None,
|
|
423
|
+
author_name: str | None = None,
|
|
424
|
+
affiliation: str | None = None,
|
|
425
|
+
email: str | None = None,
|
|
426
|
+
max_results: int | None = 500,
|
|
427
|
+
page_size: int = 200,
|
|
428
|
+
session: provider.HTTPClient | None = None) -> list[_CrossrefRecord]:
|
|
429
|
+
"""Retrieve DOI-bearing works for one author.
|
|
430
|
+
|
|
431
|
+
Parameters
|
|
432
|
+
----------
|
|
433
|
+
orcid : str, optional
|
|
434
|
+
ORCID identifier used for exact server-side filtering.
|
|
435
|
+
author_name : str, optional
|
|
436
|
+
Given and family names used for search and local filtering.
|
|
437
|
+
affiliation : str, optional
|
|
438
|
+
Affiliation fragment required on the matched author record.
|
|
439
|
+
email : str, optional
|
|
440
|
+
Contact email for Crossref polite-pool requests.
|
|
441
|
+
max_results : int or None, optional
|
|
442
|
+
Maximum accepted works, or ``None`` for no explicit limit.
|
|
443
|
+
page_size : int, optional
|
|
444
|
+
Number of records requested per Crossref page.
|
|
445
|
+
session : provider.HTTPClient or None, optional
|
|
446
|
+
HTTP session, primarily for connection reuse or testing.
|
|
447
|
+
|
|
448
|
+
Returns
|
|
449
|
+
-------
|
|
450
|
+
list[_CrossrefRecord]
|
|
451
|
+
Unique matching Crossref work records.
|
|
452
|
+
|
|
453
|
+
Raises
|
|
454
|
+
------
|
|
455
|
+
ValueError
|
|
456
|
+
If identity, contact, or pagination options are invalid.
|
|
457
|
+
RuntimeError
|
|
458
|
+
If a Crossref request exhausts its retries.
|
|
459
|
+
"""
|
|
460
|
+
if bool(orcid) == bool(author_name):
|
|
461
|
+
raise ValueError('Provide exactly one of orcid or author_name.')
|
|
462
|
+
if not email or '@' not in email:
|
|
463
|
+
raise ValueError('A contact email is required for Crossref polite-pool requests. '
|
|
464
|
+
'Run pmt config crossref-email, set CROSSREF_EMAIL, or pass --email.')
|
|
465
|
+
if max_results is not None and max_results < 1:
|
|
466
|
+
raise ValueError('max_results must be a positive integer or None.')
|
|
467
|
+
if page_size < 1 or page_size > 1000:
|
|
468
|
+
raise ValueError('page_size must be between 1 and 1000.')
|
|
469
|
+
|
|
470
|
+
session = session or requests.Session()
|
|
471
|
+
params = {'rows': page_size, 'cursor': '*', 'mailto': email}
|
|
472
|
+
if orcid:
|
|
473
|
+
orcid = normalize_orcid(orcid)
|
|
474
|
+
params['filter'] = f'orcid:{orcid}'
|
|
475
|
+
else:
|
|
476
|
+
params['query.author'] = author_name
|
|
477
|
+
|
|
478
|
+
works = []
|
|
479
|
+
seen_dois = set()
|
|
480
|
+
while True:
|
|
481
|
+
message = _request_page(session, params, email)
|
|
482
|
+
items = message.get('items') or []
|
|
483
|
+
for work in items:
|
|
484
|
+
doi = str(work.get('DOI') or '').strip().lower()
|
|
485
|
+
if not doi or doi in seen_dois:
|
|
486
|
+
continue
|
|
487
|
+
if not work_matches_author(work, author_name=author_name, orcid=orcid, affiliation=affiliation):
|
|
488
|
+
continue
|
|
489
|
+
seen_dois.add(doi)
|
|
490
|
+
works.append(work)
|
|
491
|
+
if max_results is not None and len(works) >= max_results:
|
|
492
|
+
return works
|
|
493
|
+
if len(items) < page_size:
|
|
494
|
+
break
|
|
495
|
+
next_cursor = message.get('next-cursor')
|
|
496
|
+
if not next_cursor or next_cursor == params['cursor']:
|
|
497
|
+
break
|
|
498
|
+
params['cursor'] = next_cursor
|
|
499
|
+
return works
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def _first(value: object) -> str:
|
|
503
|
+
"""Select the first non-empty Crossref field value.
|
|
504
|
+
|
|
505
|
+
Parameters
|
|
506
|
+
----------
|
|
507
|
+
value : object
|
|
508
|
+
Scalar or list Crossref field value.
|
|
509
|
+
|
|
510
|
+
Returns
|
|
511
|
+
-------
|
|
512
|
+
str
|
|
513
|
+
First non-empty string, or an empty string.
|
|
514
|
+
"""
|
|
515
|
+
if isinstance(value, list):
|
|
516
|
+
return next((str(item).strip() for item in value if str(item).strip()), '')
|
|
517
|
+
return str(value or '').strip()
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def _publication_date(work: _CrossrefRecord) -> str:
|
|
521
|
+
"""Extract the best available Crossref publication date.
|
|
522
|
+
|
|
523
|
+
Parameters
|
|
524
|
+
----------
|
|
525
|
+
work : _CrossrefRecord
|
|
526
|
+
Crossref work record.
|
|
527
|
+
|
|
528
|
+
Returns
|
|
529
|
+
-------
|
|
530
|
+
str
|
|
531
|
+
ISO-like publication date, or an empty string.
|
|
532
|
+
"""
|
|
533
|
+
for key in ['published-print', 'published-online', 'published', 'issued', 'created']:
|
|
534
|
+
value = work.get(key) or {}
|
|
535
|
+
parts = value.get('date-parts') if isinstance(value, dict) else None
|
|
536
|
+
if parts and parts[0]:
|
|
537
|
+
return '-'.join(f'{int(part):02d}' if index else str(part)
|
|
538
|
+
for index, part in enumerate(parts[0][:3]))
|
|
539
|
+
return ''
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
def crossref_work_to_paper(work: _CrossrefRecord) -> dict[str, Any]:
|
|
543
|
+
"""Map a Crossref work to the corpus schema.
|
|
544
|
+
|
|
545
|
+
Parameters
|
|
546
|
+
----------
|
|
547
|
+
work : _CrossrefRecord
|
|
548
|
+
Crossref work record.
|
|
549
|
+
|
|
550
|
+
Returns
|
|
551
|
+
-------
|
|
552
|
+
dict[str, Any]
|
|
553
|
+
Normalized paper metadata suitable for corpus insertion.
|
|
554
|
+
"""
|
|
555
|
+
doi = str(work.get('DOI') or '').strip().lower()
|
|
556
|
+
authors = '; '.join(
|
|
557
|
+
' '.join(part for part in [str(author.get('given') or '').strip(),
|
|
558
|
+
str(author.get('family') or '').strip()] if part)
|
|
559
|
+
for author in work.get('author') or []
|
|
560
|
+
)
|
|
561
|
+
return {
|
|
562
|
+
'paper_id': f'doi:{doi}',
|
|
563
|
+
'doi': doi,
|
|
564
|
+
'title': _first(work.get('title')),
|
|
565
|
+
'journal': _first(work.get('container-title')),
|
|
566
|
+
'publication_date': _publication_date(work),
|
|
567
|
+
'authors': authors,
|
|
568
|
+
'sources': 'crossref',
|
|
569
|
+
'metadata_status': 'retrieved',
|
|
570
|
+
'metadata': work,
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def import_author_works(db_path: str | PathLike[str],
|
|
575
|
+
email: str | None = None,
|
|
576
|
+
orcid: str | None = None,
|
|
577
|
+
author_name: str | None = None,
|
|
578
|
+
affiliation: str | None = None,
|
|
579
|
+
max_results: int | None = 500,
|
|
580
|
+
review_csv: str | PathLike[str] | None = None,
|
|
581
|
+
session: provider.HTTPClient | None = None,
|
|
582
|
+
enrich: bool = False) -> dict[str, int]:
|
|
583
|
+
"""Discover and import an author's Crossref works.
|
|
584
|
+
|
|
585
|
+
Parameters
|
|
586
|
+
----------
|
|
587
|
+
db_path : str or os.PathLike[str]
|
|
588
|
+
Destination corpus database.
|
|
589
|
+
email : str or None, optional
|
|
590
|
+
Contact email for Crossref requests. Defaults to the stored
|
|
591
|
+
``crossref_email`` setting.
|
|
592
|
+
orcid : str, optional
|
|
593
|
+
ORCID identifier for exact author discovery.
|
|
594
|
+
author_name : str, optional
|
|
595
|
+
Author name used when no ORCID is supplied.
|
|
596
|
+
affiliation : str, optional
|
|
597
|
+
Affiliation fragment required on the matched author record.
|
|
598
|
+
max_results : int or None, optional
|
|
599
|
+
Maximum number of works to import.
|
|
600
|
+
review_csv : str, os.PathLike[str], or None, optional
|
|
601
|
+
CSV path for a human-readable import review.
|
|
602
|
+
session : provider.HTTPClient or None, optional
|
|
603
|
+
HTTP session used for discovery.
|
|
604
|
+
enrich : bool, default=False
|
|
605
|
+
Whether to supplement imported works with Crossref and OpenAlex
|
|
606
|
+
metadata.
|
|
607
|
+
|
|
608
|
+
Returns
|
|
609
|
+
-------
|
|
610
|
+
dict[str, int]
|
|
611
|
+
Counts of found, added, updated, and enriched papers.
|
|
612
|
+
|
|
613
|
+
Raises
|
|
614
|
+
------
|
|
615
|
+
ValueError
|
|
616
|
+
If the author identity, contact email, result limit, or ORCID is
|
|
617
|
+
invalid.
|
|
618
|
+
RuntimeError
|
|
619
|
+
If a Crossref request exhausts its retries or the corpus schema is
|
|
620
|
+
newer than this package supports.
|
|
621
|
+
"""
|
|
622
|
+
email = resolve_email(email)
|
|
623
|
+
works = author_works(
|
|
624
|
+
orcid=orcid,
|
|
625
|
+
author_name=author_name,
|
|
626
|
+
affiliation=affiliation,
|
|
627
|
+
email=email,
|
|
628
|
+
max_results=max_results,
|
|
629
|
+
session=session,
|
|
630
|
+
)
|
|
631
|
+
papers = [crossref_work_to_paper(work) for work in works]
|
|
632
|
+
if review_csv:
|
|
633
|
+
review_path = Path(review_csv)
|
|
634
|
+
review_path.parent.mkdir(parents=True, exist_ok=True)
|
|
635
|
+
pd.DataFrame(papers, columns=REVIEW_COLUMNS).to_csv(review_path, index=False)
|
|
636
|
+
with connect(db_path) as conn:
|
|
637
|
+
added, updated = upsert_papers(conn, papers)
|
|
638
|
+
for paper in papers:
|
|
639
|
+
matched = find_paper(conn, paper)
|
|
640
|
+
if matched is None:
|
|
641
|
+
continue
|
|
642
|
+
matched['metadata'] = paper['metadata']
|
|
643
|
+
upsert_paper(conn, matched)
|
|
644
|
+
enriched = 0
|
|
645
|
+
if enrich:
|
|
646
|
+
from paperminertoolkit.workflows.enrichment import enrich_papers
|
|
647
|
+
|
|
648
|
+
enriched = enrich_papers(conn, papers, email=email)['succeeded']
|
|
649
|
+
return {'found': len(papers), 'added': added, 'updated': updated, 'enriched': enriched}
|