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,1748 @@
|
|
|
1
|
+
"""Download paper text and PDFs from configured open-access and publisher sources.
|
|
2
|
+
|
|
3
|
+
This module powers ``pmt download``. It can fetch Elsevier, PubMed Central
|
|
4
|
+
open-access, medRxiv, and bioRxiv full text, try PDFs from Unpaywall, OpenAlex,
|
|
5
|
+
CORE, Elsevier, PubMed Central, medRxiv, bioRxiv, and arXiv, and update
|
|
6
|
+
per-paper download status in the SQLite paper corpus after each row. arXiv
|
|
7
|
+
serves PDFs and abstracts but no full text, because it publishes no
|
|
8
|
+
machine-readable full-text format. medRxiv and bioRxiv publish both: their PDFs
|
|
9
|
+
and their JATS full text, the latter being the same format PubMed Central
|
|
10
|
+
serves, so text from either needs no PDF scrape.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import ast
|
|
16
|
+
import html
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
import requests
|
|
21
|
+
import sqlite3
|
|
22
|
+
import tempfile
|
|
23
|
+
from collections.abc import Callable, Iterable, Mapping, MutableMapping
|
|
24
|
+
from os import PathLike
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from tqdm import tqdm
|
|
27
|
+
from typing import Any, TypeAlias
|
|
28
|
+
from urllib.parse import quote
|
|
29
|
+
|
|
30
|
+
from paperminertoolkit.providers import (arxiv, biorxiv, chemrxiv, core, elsevier, medrxiv,
|
|
31
|
+
openalex, pubmed, unpaywall)
|
|
32
|
+
from paperminertoolkit.corpus.database import (PIPELINE_COLUMNS, add_asset, connect,
|
|
33
|
+
get_asset_metadata, paper_rows, upsert_paper)
|
|
34
|
+
from paperminertoolkit.providers import registry
|
|
35
|
+
from paperminertoolkit.settings import load_settings
|
|
36
|
+
|
|
37
|
+
DOWNLOAD_FORMATS = {'abstract', 'text', 'pdf', 'both'}
|
|
38
|
+
DOWNLOAD_SOURCES = {*registry.names(registry.PDF), *registry.names(registry.TEXT),
|
|
39
|
+
*registry.names(registry.ABSTRACT)}
|
|
40
|
+
# Providers that serve a machine-readable full text rather than only a PDF.
|
|
41
|
+
TEXT_SOURCES = set(registry.names(registry.TEXT))
|
|
42
|
+
_Paper: TypeAlias = dict[str, Any]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _elsevier_string_formatter(text: str) -> str:
|
|
46
|
+
"""Clean wrapper artifacts from Elsevier original text.
|
|
47
|
+
|
|
48
|
+
Parameters
|
|
49
|
+
----------
|
|
50
|
+
text : str
|
|
51
|
+
Raw ``originalText`` value.
|
|
52
|
+
|
|
53
|
+
Returns
|
|
54
|
+
-------
|
|
55
|
+
str
|
|
56
|
+
Cleaned article text.
|
|
57
|
+
"""
|
|
58
|
+
if text.count('Acknowledgements') == 2:
|
|
59
|
+
text = text.split('Acknowledgements')[1]
|
|
60
|
+
elif text.count('References') == 2:
|
|
61
|
+
text = text.split('References')[1]
|
|
62
|
+
if 'amazonaws.com/' in text:
|
|
63
|
+
text = text.split('amazonaws.com/')[-1]
|
|
64
|
+
text = text[text.find(' '):]
|
|
65
|
+
return text
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _full_text_uri(paper: Mapping[str, Any]) -> str | None:
|
|
69
|
+
"""Extract an Elsevier full-text URI or DOI retrieval URL from a paper row."""
|
|
70
|
+
link = paper.get('elsevier_link')
|
|
71
|
+
for value in _link_values(link):
|
|
72
|
+
uri = _full_text_uri_from_link_value(value)
|
|
73
|
+
if uri:
|
|
74
|
+
return uri
|
|
75
|
+
doi = paper.get('doi')
|
|
76
|
+
if _has_value(doi):
|
|
77
|
+
return elsevier.article_url_from_doi(str(doi))
|
|
78
|
+
return None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _link_values(link: object) -> list[Any]:
|
|
82
|
+
"""Return one or more Elsevier link values from strings, lists, or dictionaries."""
|
|
83
|
+
if isinstance(link, list):
|
|
84
|
+
return link
|
|
85
|
+
if isinstance(link, dict):
|
|
86
|
+
return [link]
|
|
87
|
+
if not isinstance(link, str) or not link.strip():
|
|
88
|
+
return []
|
|
89
|
+
text = link.strip()
|
|
90
|
+
if text[0] in '[{':
|
|
91
|
+
for parser in (json.loads, ast.literal_eval):
|
|
92
|
+
try:
|
|
93
|
+
return _link_values(parser(text))
|
|
94
|
+
except (ValueError, SyntaxError, TypeError):
|
|
95
|
+
continue
|
|
96
|
+
return [text]
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _full_text_uri_from_link_value(value: object) -> str | None:
|
|
100
|
+
"""Extract a full-text URI from one Elsevier link object or string."""
|
|
101
|
+
if isinstance(value, dict):
|
|
102
|
+
ref = str(value.get('@ref') or value.get('ref') or '').lower()
|
|
103
|
+
href = value.get('@href') or value.get('href') or value.get('url') or ''
|
|
104
|
+
if href and ('full-text' in ref or _is_elsevier_article_endpoint(str(href))):
|
|
105
|
+
return str(href)
|
|
106
|
+
return None
|
|
107
|
+
if not isinstance(value, str):
|
|
108
|
+
return None
|
|
109
|
+
if _is_elsevier_article_endpoint(value):
|
|
110
|
+
return value
|
|
111
|
+
if 'full-text' not in value.lower():
|
|
112
|
+
return None
|
|
113
|
+
quoted = [part for part in re.findall(r"""['"]([^'"]+)['"]""", value) if part.lower() != 'full-text']
|
|
114
|
+
if quoted:
|
|
115
|
+
return quoted[-1]
|
|
116
|
+
if value.startswith('http'):
|
|
117
|
+
return value
|
|
118
|
+
return None
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _is_elsevier_article_endpoint(value: str) -> bool:
|
|
122
|
+
"""Return whether a URL is an Elsevier article retrieval endpoint."""
|
|
123
|
+
return 'api.elsevier.com/content/article/' in value.lower()
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _has_value(value: object) -> bool:
|
|
127
|
+
"""Return whether a paper field contains a meaningful non-empty value."""
|
|
128
|
+
return value is not None and str(value).strip() != ''
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _set_status(paper: _Paper, column: str, status: str, error: str | None = None) -> None:
|
|
132
|
+
"""Update a corpus paper status field and optional error text."""
|
|
133
|
+
if column not in PIPELINE_COLUMNS:
|
|
134
|
+
raise KeyError(f'Unknown pipeline status column: {column}')
|
|
135
|
+
paper[column] = status
|
|
136
|
+
if error:
|
|
137
|
+
paper['last_error'] = error
|
|
138
|
+
elif status in {'succeeded', 'stored'}:
|
|
139
|
+
paper['last_error'] = ''
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _download_text(paper: Mapping[str, Any], filepath: str | PathLike[str]) -> bool:
|
|
143
|
+
"""Download Elsevier full text for one paper row to ``filepath``.
|
|
144
|
+
|
|
145
|
+
The payload is read in memory and written straight to the destination. It
|
|
146
|
+
used to be staged through a ``data`` directory created in the working
|
|
147
|
+
directory, every file of which was deleted first -- so a download run wiped
|
|
148
|
+
whatever a user happened to keep in ``./data``.
|
|
149
|
+
|
|
150
|
+
Parameters
|
|
151
|
+
----------
|
|
152
|
+
paper : Mapping[str, Any]
|
|
153
|
+
Corpus paper row.
|
|
154
|
+
filepath : str or os.PathLike[str]
|
|
155
|
+
Destination path for the downloaded text.
|
|
156
|
+
|
|
157
|
+
Returns
|
|
158
|
+
-------
|
|
159
|
+
bool
|
|
160
|
+
Whether text was retrieved and written.
|
|
161
|
+
"""
|
|
162
|
+
uri = _full_text_uri(paper)
|
|
163
|
+
if not uri:
|
|
164
|
+
return False
|
|
165
|
+
payload = elsevier.request_json(uri, elsevier.configured_api_key(),
|
|
166
|
+
params={'httpAccept': 'application/json'})
|
|
167
|
+
text = elsevier.full_text(payload)
|
|
168
|
+
if not text:
|
|
169
|
+
return False
|
|
170
|
+
with open(filepath, 'w', encoding='utf-8') as out_file:
|
|
171
|
+
out_file.write(_elsevier_string_formatter(text))
|
|
172
|
+
return True
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _pdf_urls(paper: Mapping[str, Any]) -> list[str]:
|
|
176
|
+
"""Build Elsevier PDF endpoint candidates for a normalized paper row."""
|
|
177
|
+
urls = []
|
|
178
|
+
doi = paper.get('doi')
|
|
179
|
+
if _has_value(doi):
|
|
180
|
+
urls.append(elsevier.article_url_from_doi(str(doi)))
|
|
181
|
+
uri = _full_text_uri(paper)
|
|
182
|
+
if uri:
|
|
183
|
+
urls.append(uri)
|
|
184
|
+
return urls
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _download_pdf(paper: Mapping[str, Any], filepath: str | PathLike[str]) -> bool:
|
|
188
|
+
"""Try to download an Elsevier PDF for one paper row."""
|
|
189
|
+
api_key = elsevier.configured_api_key()
|
|
190
|
+
params = {'httpAccept': 'application/pdf'}
|
|
191
|
+
last_error = None
|
|
192
|
+
for url in _pdf_urls(paper):
|
|
193
|
+
try:
|
|
194
|
+
response = elsevier.get_content(api_key, url, accept='application/pdf', params=params)
|
|
195
|
+
content_type = response.headers.get('Content-Type', '').lower()
|
|
196
|
+
if 'pdf' in content_type or response.content.startswith(b'%PDF'):
|
|
197
|
+
with open(filepath, 'wb') as out_file:
|
|
198
|
+
out_file.write(response.content)
|
|
199
|
+
return True
|
|
200
|
+
last_error = f'non-PDF response from {url}'
|
|
201
|
+
except requests.HTTPError as e:
|
|
202
|
+
response = getattr(e, 'response', None)
|
|
203
|
+
status_code = response.status_code if response is not None else 'HTTP error'
|
|
204
|
+
last_error = f'{status_code} from {url}'
|
|
205
|
+
except requests.RequestException as e:
|
|
206
|
+
last_error = str(e)
|
|
207
|
+
if last_error:
|
|
208
|
+
print(f'PDF download failed for {paper.get("paper_id")}: {last_error}')
|
|
209
|
+
return False
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _safe_filename(paper: Mapping[str, Any]) -> str:
|
|
213
|
+
"""Create a filesystem-safe filename stem for a paper row."""
|
|
214
|
+
for column in ['doi', 'core_id', 'paper_id']:
|
|
215
|
+
value = paper.get(column)
|
|
216
|
+
if _has_value(value):
|
|
217
|
+
safe = re.sub(r'[^A-Za-z0-9._-]+', '_', str(value).strip())
|
|
218
|
+
safe = safe.strip('._')
|
|
219
|
+
if safe:
|
|
220
|
+
return safe
|
|
221
|
+
return 'paper'
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _unpaywall_email(settings: Mapping[str, str] | None = None) -> str | None:
|
|
225
|
+
"""Return the configured email address used for Unpaywall requests.
|
|
226
|
+
|
|
227
|
+
Parameters
|
|
228
|
+
----------
|
|
229
|
+
settings : Mapping[str, str] or None, optional
|
|
230
|
+
Loaded PaperMinerToolkit settings.
|
|
231
|
+
|
|
232
|
+
Returns
|
|
233
|
+
-------
|
|
234
|
+
str or None
|
|
235
|
+
Contact address, or ``None`` when none is configured.
|
|
236
|
+
"""
|
|
237
|
+
return unpaywall.configured_email(settings) or None
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _download_url_to_pdf(
|
|
241
|
+
url: str | None,
|
|
242
|
+
filepath: str | PathLike[str],
|
|
243
|
+
headers: Mapping[str, str] | None = None,
|
|
244
|
+
) -> tuple[bool, str]:
|
|
245
|
+
"""Fetch a URL and save it only when the response appears to be a PDF."""
|
|
246
|
+
if not url:
|
|
247
|
+
return False, 'missing URL'
|
|
248
|
+
try:
|
|
249
|
+
response = requests.get(url, headers=headers or {}, timeout=60, allow_redirects=True)
|
|
250
|
+
if response.status_code >= 400:
|
|
251
|
+
return False, f'{response.status_code} from {url}'
|
|
252
|
+
content_type = response.headers.get('Content-Type', '').lower()
|
|
253
|
+
if 'pdf' not in content_type and not response.content.startswith(b'%PDF'):
|
|
254
|
+
return False, f'non-PDF response from {url}'
|
|
255
|
+
with open(filepath, 'wb') as out_file:
|
|
256
|
+
out_file.write(response.content)
|
|
257
|
+
return True, ''
|
|
258
|
+
except requests.RequestException as e:
|
|
259
|
+
return False, str(e)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _download_unpaywall_pdf(
|
|
263
|
+
paper: Mapping[str, Any],
|
|
264
|
+
filepath: str | PathLike[str],
|
|
265
|
+
) -> tuple[bool, str]:
|
|
266
|
+
"""Use Unpaywall metadata to locate and download an open-access PDF.
|
|
267
|
+
|
|
268
|
+
Parameters
|
|
269
|
+
----------
|
|
270
|
+
paper : Mapping[str, Any]
|
|
271
|
+
Corpus paper row.
|
|
272
|
+
filepath : str or os.PathLike[str]
|
|
273
|
+
Destination path for the downloaded PDF.
|
|
274
|
+
|
|
275
|
+
Returns
|
|
276
|
+
-------
|
|
277
|
+
tuple[bool, str]
|
|
278
|
+
Success flag, and the URL used or the failure reason.
|
|
279
|
+
"""
|
|
280
|
+
doi = paper.get('doi')
|
|
281
|
+
if not _has_value(doi):
|
|
282
|
+
return False, 'missing DOI'
|
|
283
|
+
try:
|
|
284
|
+
metadata = unpaywall.get_work(doi)
|
|
285
|
+
except (ValueError, RuntimeError) as e:
|
|
286
|
+
return False, str(e)
|
|
287
|
+
if not metadata:
|
|
288
|
+
return False, 'Unpaywall knows nothing of this DOI'
|
|
289
|
+
last_error = 'no Unpaywall PDF URL found'
|
|
290
|
+
for url in unpaywall.pdf_candidates(metadata):
|
|
291
|
+
ok, error = _download_url_to_pdf(url, filepath)
|
|
292
|
+
if ok:
|
|
293
|
+
return True, url
|
|
294
|
+
last_error = error
|
|
295
|
+
return False, last_error
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _download_core_pdf(
|
|
299
|
+
paper: Mapping[str, Any],
|
|
300
|
+
filepath: str | PathLike[str],
|
|
301
|
+
) -> tuple[bool, str]:
|
|
302
|
+
"""Download a PDF through CORE using a stored PDF URL or CORE work ID."""
|
|
303
|
+
urls = []
|
|
304
|
+
url = paper.get('pdf_url')
|
|
305
|
+
if _has_value(url):
|
|
306
|
+
urls.append(str(url).strip())
|
|
307
|
+
core_id = core.resolve_core_id(paper)
|
|
308
|
+
if core_id:
|
|
309
|
+
urls.append(f'{core.work_url(core_id)}/download')
|
|
310
|
+
last_error = 'no CORE download URL found'
|
|
311
|
+
for candidate in dict.fromkeys(urls):
|
|
312
|
+
ok, error = _download_url_to_pdf(candidate, filepath, headers=core.request_headers())
|
|
313
|
+
if ok:
|
|
314
|
+
return True, candidate
|
|
315
|
+
last_error = error
|
|
316
|
+
return False, last_error
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _openalex_identifier(paper: Mapping[str, Any]) -> str | None:
|
|
320
|
+
"""Resolve an identifier accepted by the OpenAlex works endpoint.
|
|
321
|
+
|
|
322
|
+
Parameters
|
|
323
|
+
----------
|
|
324
|
+
paper : Mapping[str, Any]
|
|
325
|
+
Corpus paper row containing a DOI or an ``openalex:`` paper ID.
|
|
326
|
+
|
|
327
|
+
Returns
|
|
328
|
+
-------
|
|
329
|
+
str or None
|
|
330
|
+
A DOI-qualified identifier or OpenAlex work ID, or ``None`` when the
|
|
331
|
+
paper cannot be looked up through OpenAlex.
|
|
332
|
+
"""
|
|
333
|
+
doi = paper.get('doi')
|
|
334
|
+
paper_id = str(paper.get('paper_id') or '')
|
|
335
|
+
if _has_value(doi):
|
|
336
|
+
return f'doi:{str(doi).strip()}'
|
|
337
|
+
if paper_id.startswith('openalex:'):
|
|
338
|
+
return paper_id.split(':', 1)[1]
|
|
339
|
+
return None
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _download_openalex_pdf(
|
|
343
|
+
paper: Mapping[str, Any],
|
|
344
|
+
filepath: str | PathLike[str],
|
|
345
|
+
) -> tuple[bool, str]:
|
|
346
|
+
"""Use OpenAlex metadata to locate and download an open-access PDF."""
|
|
347
|
+
identifier = _openalex_identifier(paper)
|
|
348
|
+
if identifier is None:
|
|
349
|
+
return False, 'missing DOI'
|
|
350
|
+
try:
|
|
351
|
+
work = openalex.get_work(identifier, api_key=openalex.configured_api_key())
|
|
352
|
+
except RuntimeError as e:
|
|
353
|
+
return False, str(e)
|
|
354
|
+
if not work:
|
|
355
|
+
return False, f'no OpenAlex work found for {identifier}'
|
|
356
|
+
last_error = 'no OpenAlex PDF URL found'
|
|
357
|
+
for url in openalex.pdf_candidates(work):
|
|
358
|
+
ok, error = _download_url_to_pdf(url, filepath)
|
|
359
|
+
if ok:
|
|
360
|
+
return True, url
|
|
361
|
+
last_error = error
|
|
362
|
+
return False, last_error
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _pubmed_identifier(paper: Mapping[str, Any]) -> str | None:
|
|
366
|
+
"""Resolve a stored PubMed identifier for a paper row.
|
|
367
|
+
|
|
368
|
+
Only values already held in the corpus are considered, so this never issues
|
|
369
|
+
a request. Rows without a PMID can still be resolved from their DOI by
|
|
370
|
+
:func:`paperminertoolkit.providers.pubmed.resolve_pmid`, at the cost of one lookup.
|
|
371
|
+
|
|
372
|
+
Parameters
|
|
373
|
+
----------
|
|
374
|
+
paper : Mapping[str, Any]
|
|
375
|
+
Corpus paper row containing a PMID or a ``pmid:`` paper ID.
|
|
376
|
+
|
|
377
|
+
Returns
|
|
378
|
+
-------
|
|
379
|
+
str or None
|
|
380
|
+
Bare PMID digits, or ``None`` when the row stores no PubMed identifier.
|
|
381
|
+
"""
|
|
382
|
+
pmid = pubmed.normalize_pmid(paper.get('pmid')) if _has_value(paper.get('pmid')) else ''
|
|
383
|
+
if pmid:
|
|
384
|
+
return pmid
|
|
385
|
+
paper_id = str(paper.get('paper_id') or '')
|
|
386
|
+
if paper_id.startswith('pmid:'):
|
|
387
|
+
return pubmed.normalize_pmid(paper_id.split(':', 1)[1]) or None
|
|
388
|
+
return None
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _pubmed_credentials() -> tuple[str | None, str]:
|
|
392
|
+
"""Return the configured NCBI API key and contact address.
|
|
393
|
+
|
|
394
|
+
Returns
|
|
395
|
+
-------
|
|
396
|
+
tuple[str or None, str]
|
|
397
|
+
API key, which may be ``None``, and contact address, which may be empty.
|
|
398
|
+
"""
|
|
399
|
+
settings = load_settings()
|
|
400
|
+
return pubmed.configured_api_key(settings), pubmed.configured_email(settings)
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _download_pubmed_pdf(
|
|
404
|
+
paper: Mapping[str, Any],
|
|
405
|
+
filepath: str | PathLike[str],
|
|
406
|
+
) -> tuple[bool, str]:
|
|
407
|
+
"""Download an open-access PDF through the PubMed Central OA service.
|
|
408
|
+
|
|
409
|
+
Only the open-access subset is redistributable, so a paper outside it
|
|
410
|
+
reports that no PDF is offered rather than failing.
|
|
411
|
+
|
|
412
|
+
Parameters
|
|
413
|
+
----------
|
|
414
|
+
paper : Mapping[str, Any]
|
|
415
|
+
Corpus paper row.
|
|
416
|
+
filepath : str or os.PathLike[str]
|
|
417
|
+
Destination path for the downloaded PDF.
|
|
418
|
+
|
|
419
|
+
Returns
|
|
420
|
+
-------
|
|
421
|
+
tuple[bool, str]
|
|
422
|
+
Success flag, and the source URL or a failure reason.
|
|
423
|
+
"""
|
|
424
|
+
api_key, email = _pubmed_credentials()
|
|
425
|
+
try:
|
|
426
|
+
pmcid = pubmed.resolve_pmcid(paper, api_key=api_key, email=email)
|
|
427
|
+
except RuntimeError as e:
|
|
428
|
+
return False, str(e)
|
|
429
|
+
if not pmcid:
|
|
430
|
+
return False, 'missing PMC ID'
|
|
431
|
+
try:
|
|
432
|
+
urls = pubmed.oa_package_urls(pmcid, api_key=api_key, email=email)
|
|
433
|
+
except RuntimeError as e:
|
|
434
|
+
return False, str(e)
|
|
435
|
+
last_error = f'no open-access PDF offered for {pmcid}'
|
|
436
|
+
for url in urls:
|
|
437
|
+
if not url.lower().endswith('.pdf'):
|
|
438
|
+
continue
|
|
439
|
+
ok, error = _download_url_to_pdf(url, filepath)
|
|
440
|
+
if ok:
|
|
441
|
+
return True, url
|
|
442
|
+
last_error = error
|
|
443
|
+
return False, last_error
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _should_try_pmc_text(paper: Mapping[str, Any]) -> bool:
|
|
447
|
+
"""Return whether a paper row can be looked up in PubMed Central.
|
|
448
|
+
|
|
449
|
+
Parameters
|
|
450
|
+
----------
|
|
451
|
+
paper : Mapping[str, Any]
|
|
452
|
+
Corpus paper row.
|
|
453
|
+
|
|
454
|
+
Returns
|
|
455
|
+
-------
|
|
456
|
+
bool
|
|
457
|
+
Whether the row carries a PMC ID, PMID, or DOI to resolve from.
|
|
458
|
+
"""
|
|
459
|
+
return any(_has_value(paper.get(column)) for column in ['pmcid', 'pmid', 'doi'])
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def _download_pmc_text(
|
|
463
|
+
paper: Mapping[str, Any],
|
|
464
|
+
filepath: str | PathLike[str],
|
|
465
|
+
) -> tuple[bool, str]:
|
|
466
|
+
"""Write PubMed Central open-access full text for one paper row.
|
|
467
|
+
|
|
468
|
+
Parameters
|
|
469
|
+
----------
|
|
470
|
+
paper : Mapping[str, Any]
|
|
471
|
+
Corpus paper row.
|
|
472
|
+
filepath : str or os.PathLike[str]
|
|
473
|
+
Destination path for the extracted text.
|
|
474
|
+
|
|
475
|
+
Returns
|
|
476
|
+
-------
|
|
477
|
+
tuple[bool, str]
|
|
478
|
+
Success flag, and an empty string or a failure reason.
|
|
479
|
+
|
|
480
|
+
Raises
|
|
481
|
+
------
|
|
482
|
+
OSError
|
|
483
|
+
If the text cannot be written.
|
|
484
|
+
"""
|
|
485
|
+
api_key, email = _pubmed_credentials()
|
|
486
|
+
try:
|
|
487
|
+
pmcid = pubmed.resolve_pmcid(paper, api_key=api_key, email=email)
|
|
488
|
+
if not pmcid:
|
|
489
|
+
return False, 'missing PMC ID'
|
|
490
|
+
text = pubmed.pmc_full_text(pmcid, api_key=api_key, email=email)
|
|
491
|
+
except RuntimeError as e:
|
|
492
|
+
return False, str(e)
|
|
493
|
+
if not text:
|
|
494
|
+
return False, f'no open-access full text for {pmcid}'
|
|
495
|
+
with open(filepath, 'w', encoding='utf-8') as out_file:
|
|
496
|
+
out_file.write(text)
|
|
497
|
+
return True, ''
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def _download_pubmed_abstract(
|
|
501
|
+
paper: MutableMapping[str, Any],
|
|
502
|
+
) -> tuple[bool, str, str]:
|
|
503
|
+
"""Fetch and return a PubMed abstract for one paper row.
|
|
504
|
+
|
|
505
|
+
A stored PMID is used directly. A row that has only a DOI is resolved
|
|
506
|
+
through the PMC ID converter, and the resolved identifier is recorded on
|
|
507
|
+
``paper`` so the corpus keeps it and later runs take the direct path.
|
|
508
|
+
|
|
509
|
+
Parameters
|
|
510
|
+
----------
|
|
511
|
+
paper : MutableMapping[str, Any]
|
|
512
|
+
Corpus paper row containing a PMID or a DOI. A resolved PMID is stored
|
|
513
|
+
back into this mapping.
|
|
514
|
+
|
|
515
|
+
Returns
|
|
516
|
+
-------
|
|
517
|
+
tuple[bool, str, str]
|
|
518
|
+
Success flag, provider name or failure reason, and normalized abstract
|
|
519
|
+
text. The text is empty when retrieval fails.
|
|
520
|
+
"""
|
|
521
|
+
api_key, email = _pubmed_credentials()
|
|
522
|
+
try:
|
|
523
|
+
pmid = pubmed.resolve_pmid(paper, api_key=api_key, email=email)
|
|
524
|
+
if not pmid:
|
|
525
|
+
return False, 'missing PMID', ''
|
|
526
|
+
paper['pmid'] = pmid
|
|
527
|
+
articles = pubmed.parse_articles(
|
|
528
|
+
pubmed.efetch_ids([pmid], api_key=api_key, email=email)
|
|
529
|
+
)
|
|
530
|
+
except RuntimeError as e:
|
|
531
|
+
return False, str(e), ''
|
|
532
|
+
if not articles:
|
|
533
|
+
return False, f'no PubMed record found for {pmid}', ''
|
|
534
|
+
abstract = _clean_abstract(articles[0].get('abstract'))
|
|
535
|
+
if abstract:
|
|
536
|
+
return True, 'pubmed', abstract
|
|
537
|
+
return False, f'no PubMed abstract found for {pmid}', ''
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def _medrxiv_identifier(paper: Mapping[str, Any]) -> str | None:
|
|
541
|
+
"""Resolve a stored medRxiv DOI for a paper row.
|
|
542
|
+
|
|
543
|
+
Only values already held in the corpus are considered, so this never issues
|
|
544
|
+
a request. medRxiv publishes no title search, so there is no lookup to fall
|
|
545
|
+
back on for a row that carries neither a medRxiv DOI nor a medRxiv URL.
|
|
546
|
+
|
|
547
|
+
Parameters
|
|
548
|
+
----------
|
|
549
|
+
paper : Mapping[str, Any]
|
|
550
|
+
Corpus paper row containing a medRxiv DOI, a medRxiv paper ID, or a
|
|
551
|
+
medRxiv content URL.
|
|
552
|
+
|
|
553
|
+
Returns
|
|
554
|
+
-------
|
|
555
|
+
str or None
|
|
556
|
+
Bare medRxiv DOI, or ``None`` when the row stores none.
|
|
557
|
+
"""
|
|
558
|
+
return medrxiv.resolve_medrxiv_doi(paper) or None
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def _medrxiv_record(paper: Mapping[str, Any]) -> tuple[Mapping[str, Any] | None, str]:
|
|
562
|
+
"""Fetch the newest posted version of a row's medRxiv preprint.
|
|
563
|
+
|
|
564
|
+
Parameters
|
|
565
|
+
----------
|
|
566
|
+
paper : Mapping[str, Any]
|
|
567
|
+
Corpus paper row carrying a medRxiv DOI.
|
|
568
|
+
|
|
569
|
+
Returns
|
|
570
|
+
-------
|
|
571
|
+
tuple[Mapping[str, Any] or None, str]
|
|
572
|
+
Normalized record, or ``None`` and a failure reason.
|
|
573
|
+
"""
|
|
574
|
+
identifier = _medrxiv_identifier(paper)
|
|
575
|
+
if identifier is None:
|
|
576
|
+
return None, 'missing medRxiv DOI'
|
|
577
|
+
try:
|
|
578
|
+
entry = medrxiv.fetch_doi(identifier)
|
|
579
|
+
except RuntimeError as e:
|
|
580
|
+
return None, str(e)
|
|
581
|
+
if entry is None:
|
|
582
|
+
return None, f'no medRxiv record found for {identifier}'
|
|
583
|
+
return entry, ''
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def _download_medrxiv_pdf(
|
|
587
|
+
paper: Mapping[str, Any],
|
|
588
|
+
filepath: str | PathLike[str],
|
|
589
|
+
) -> tuple[bool, str]:
|
|
590
|
+
"""Download a paper's PDF from medRxiv.
|
|
591
|
+
|
|
592
|
+
The version is read from the record rather than assumed, because a
|
|
593
|
+
preprint's PDF is served per posted version and the newest one is the
|
|
594
|
+
document the corpus row describes. medRxiv fronts these files with a bot
|
|
595
|
+
challenge that can refuse a client outright; a refusal is reported as the
|
|
596
|
+
failure reason rather than worked around, and full text remains reachable
|
|
597
|
+
through the medRxiv text source when it happens.
|
|
598
|
+
|
|
599
|
+
Parameters
|
|
600
|
+
----------
|
|
601
|
+
paper : Mapping[str, Any]
|
|
602
|
+
Corpus paper row carrying a medRxiv DOI.
|
|
603
|
+
filepath : str or os.PathLike[str]
|
|
604
|
+
Destination path for the downloaded PDF.
|
|
605
|
+
|
|
606
|
+
Returns
|
|
607
|
+
-------
|
|
608
|
+
tuple[bool, str]
|
|
609
|
+
Success flag, and the source URL or a failure reason.
|
|
610
|
+
"""
|
|
611
|
+
entry, error = _medrxiv_record(paper)
|
|
612
|
+
if entry is None:
|
|
613
|
+
return False, error
|
|
614
|
+
url = medrxiv.pdf_url(str(entry.get('medrxiv_doi') or ''), str(entry.get('version') or ''))
|
|
615
|
+
if not url:
|
|
616
|
+
return False, 'missing medRxiv DOI'
|
|
617
|
+
ok, error = _download_url_to_pdf(url, filepath, headers=medrxiv.request_headers())
|
|
618
|
+
return (True, url) if ok else (False, error)
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
def _download_medrxiv_text(
|
|
622
|
+
paper: Mapping[str, Any],
|
|
623
|
+
filepath: str | PathLike[str],
|
|
624
|
+
) -> tuple[bool, str]:
|
|
625
|
+
"""Write medRxiv JATS full text for one paper row.
|
|
626
|
+
|
|
627
|
+
Parameters
|
|
628
|
+
----------
|
|
629
|
+
paper : Mapping[str, Any]
|
|
630
|
+
Corpus paper row carrying a medRxiv DOI.
|
|
631
|
+
filepath : str or os.PathLike[str]
|
|
632
|
+
Destination path for the extracted text.
|
|
633
|
+
|
|
634
|
+
Returns
|
|
635
|
+
-------
|
|
636
|
+
tuple[bool, str]
|
|
637
|
+
Success flag, and an empty string or a failure reason.
|
|
638
|
+
|
|
639
|
+
Raises
|
|
640
|
+
------
|
|
641
|
+
OSError
|
|
642
|
+
If the text cannot be written.
|
|
643
|
+
"""
|
|
644
|
+
entry, error = _medrxiv_record(paper)
|
|
645
|
+
if entry is None:
|
|
646
|
+
return False, error
|
|
647
|
+
try:
|
|
648
|
+
text = medrxiv.full_text(entry)
|
|
649
|
+
except RuntimeError as e:
|
|
650
|
+
return False, str(e)
|
|
651
|
+
if not text:
|
|
652
|
+
return False, f'no medRxiv full text for {entry.get("medrxiv_doi")}'
|
|
653
|
+
with open(filepath, 'w', encoding='utf-8') as out_file:
|
|
654
|
+
out_file.write(text)
|
|
655
|
+
return True, ''
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
def _download_medrxiv_abstract(
|
|
659
|
+
paper: Mapping[str, Any],
|
|
660
|
+
) -> tuple[bool, str, str]:
|
|
661
|
+
"""Fetch and return a medRxiv abstract for one paper row.
|
|
662
|
+
|
|
663
|
+
Parameters
|
|
664
|
+
----------
|
|
665
|
+
paper : Mapping[str, Any]
|
|
666
|
+
Corpus paper row carrying a medRxiv DOI.
|
|
667
|
+
|
|
668
|
+
Returns
|
|
669
|
+
-------
|
|
670
|
+
tuple[bool, str, str]
|
|
671
|
+
Success flag, provider name or failure reason, and normalized abstract
|
|
672
|
+
text. The text is empty when retrieval fails.
|
|
673
|
+
"""
|
|
674
|
+
entry, error = _medrxiv_record(paper)
|
|
675
|
+
if entry is None:
|
|
676
|
+
return False, error, ''
|
|
677
|
+
abstract = _clean_abstract(entry.get('abstract'))
|
|
678
|
+
if abstract:
|
|
679
|
+
return True, 'medrxiv', abstract
|
|
680
|
+
return False, f'no medRxiv abstract found for {entry.get("medrxiv_doi")}', ''
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
def _biorxiv_identifier(paper: Mapping[str, Any]) -> str | None:
|
|
684
|
+
"""Resolve a stored bioRxiv DOI for a paper row.
|
|
685
|
+
|
|
686
|
+
Only values already held in the corpus are considered, so this never issues
|
|
687
|
+
a request. bioRxiv publishes no title search, so there is no lookup to fall
|
|
688
|
+
back on for a row that carries neither a bioRxiv DOI nor a bioRxiv URL.
|
|
689
|
+
|
|
690
|
+
Parameters
|
|
691
|
+
----------
|
|
692
|
+
paper : Mapping[str, Any]
|
|
693
|
+
Corpus paper row containing a bioRxiv DOI, a bioRxiv paper ID, or a
|
|
694
|
+
bioRxiv content URL.
|
|
695
|
+
|
|
696
|
+
Returns
|
|
697
|
+
-------
|
|
698
|
+
str or None
|
|
699
|
+
Bare bioRxiv DOI, or ``None`` when the row stores none.
|
|
700
|
+
"""
|
|
701
|
+
return biorxiv.resolve_biorxiv_doi(paper) or None
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
def _biorxiv_record(paper: Mapping[str, Any]) -> tuple[Mapping[str, Any] | None, str]:
|
|
705
|
+
"""Fetch the newest posted version of a row's bioRxiv preprint.
|
|
706
|
+
|
|
707
|
+
Parameters
|
|
708
|
+
----------
|
|
709
|
+
paper : Mapping[str, Any]
|
|
710
|
+
Corpus paper row carrying a bioRxiv DOI.
|
|
711
|
+
|
|
712
|
+
Returns
|
|
713
|
+
-------
|
|
714
|
+
tuple[Mapping[str, Any] or None, str]
|
|
715
|
+
Normalized record, or ``None`` and a failure reason.
|
|
716
|
+
"""
|
|
717
|
+
identifier = _biorxiv_identifier(paper)
|
|
718
|
+
if identifier is None:
|
|
719
|
+
return None, 'missing bioRxiv DOI'
|
|
720
|
+
try:
|
|
721
|
+
entry = biorxiv.fetch_doi(identifier)
|
|
722
|
+
except RuntimeError as e:
|
|
723
|
+
return None, str(e)
|
|
724
|
+
if entry is None:
|
|
725
|
+
return None, f'no bioRxiv record found for {identifier}'
|
|
726
|
+
return entry, ''
|
|
727
|
+
|
|
728
|
+
|
|
729
|
+
def _download_biorxiv_pdf(
|
|
730
|
+
paper: Mapping[str, Any],
|
|
731
|
+
filepath: str | PathLike[str],
|
|
732
|
+
) -> tuple[bool, str]:
|
|
733
|
+
"""Download a paper's PDF from bioRxiv.
|
|
734
|
+
|
|
735
|
+
The version is read from the record rather than assumed, because a
|
|
736
|
+
preprint's PDF is served per posted version and the newest one is the
|
|
737
|
+
document the corpus row describes. bioRxiv fronts these files with the same
|
|
738
|
+
bot challenge medRxiv uses, and it can refuse a client outright; a refusal
|
|
739
|
+
is reported as the failure reason rather than worked around, and full text
|
|
740
|
+
remains reachable through the bioRxiv text source when it happens.
|
|
741
|
+
|
|
742
|
+
Parameters
|
|
743
|
+
----------
|
|
744
|
+
paper : Mapping[str, Any]
|
|
745
|
+
Corpus paper row carrying a bioRxiv DOI.
|
|
746
|
+
filepath : str or os.PathLike[str]
|
|
747
|
+
Destination path for the downloaded PDF.
|
|
748
|
+
|
|
749
|
+
Returns
|
|
750
|
+
-------
|
|
751
|
+
tuple[bool, str]
|
|
752
|
+
Success flag, and the source URL or a failure reason.
|
|
753
|
+
"""
|
|
754
|
+
entry, error = _biorxiv_record(paper)
|
|
755
|
+
if entry is None:
|
|
756
|
+
return False, error
|
|
757
|
+
url = biorxiv.pdf_url(str(entry.get('biorxiv_doi') or ''), str(entry.get('version') or ''))
|
|
758
|
+
if not url:
|
|
759
|
+
return False, 'missing bioRxiv DOI'
|
|
760
|
+
ok, error = _download_url_to_pdf(url, filepath, headers=biorxiv.request_headers())
|
|
761
|
+
return (True, url) if ok else (False, error)
|
|
762
|
+
|
|
763
|
+
|
|
764
|
+
def _download_biorxiv_text(
|
|
765
|
+
paper: Mapping[str, Any],
|
|
766
|
+
filepath: str | PathLike[str],
|
|
767
|
+
) -> tuple[bool, str]:
|
|
768
|
+
"""Write bioRxiv JATS full text for one paper row.
|
|
769
|
+
|
|
770
|
+
Parameters
|
|
771
|
+
----------
|
|
772
|
+
paper : Mapping[str, Any]
|
|
773
|
+
Corpus paper row carrying a bioRxiv DOI.
|
|
774
|
+
filepath : str or os.PathLike[str]
|
|
775
|
+
Destination path for the extracted text.
|
|
776
|
+
|
|
777
|
+
Returns
|
|
778
|
+
-------
|
|
779
|
+
tuple[bool, str]
|
|
780
|
+
Success flag, and an empty string or a failure reason.
|
|
781
|
+
|
|
782
|
+
Raises
|
|
783
|
+
------
|
|
784
|
+
OSError
|
|
785
|
+
If the text cannot be written.
|
|
786
|
+
"""
|
|
787
|
+
entry, error = _biorxiv_record(paper)
|
|
788
|
+
if entry is None:
|
|
789
|
+
return False, error
|
|
790
|
+
try:
|
|
791
|
+
text = biorxiv.full_text(entry)
|
|
792
|
+
except RuntimeError as e:
|
|
793
|
+
return False, str(e)
|
|
794
|
+
if not text:
|
|
795
|
+
return False, f'no bioRxiv full text for {entry.get("biorxiv_doi")}'
|
|
796
|
+
with open(filepath, 'w', encoding='utf-8') as out_file:
|
|
797
|
+
out_file.write(text)
|
|
798
|
+
return True, ''
|
|
799
|
+
|
|
800
|
+
|
|
801
|
+
def _download_biorxiv_abstract(
|
|
802
|
+
paper: Mapping[str, Any],
|
|
803
|
+
) -> tuple[bool, str, str]:
|
|
804
|
+
"""Fetch and return a bioRxiv abstract for one paper row.
|
|
805
|
+
|
|
806
|
+
Parameters
|
|
807
|
+
----------
|
|
808
|
+
paper : Mapping[str, Any]
|
|
809
|
+
Corpus paper row carrying a bioRxiv DOI.
|
|
810
|
+
|
|
811
|
+
Returns
|
|
812
|
+
-------
|
|
813
|
+
tuple[bool, str, str]
|
|
814
|
+
Success flag, provider name or failure reason, and normalized abstract
|
|
815
|
+
text. The text is empty when retrieval fails.
|
|
816
|
+
"""
|
|
817
|
+
entry, error = _biorxiv_record(paper)
|
|
818
|
+
if entry is None:
|
|
819
|
+
return False, error, ''
|
|
820
|
+
abstract = _clean_abstract(entry.get('abstract'))
|
|
821
|
+
if abstract:
|
|
822
|
+
return True, 'biorxiv', abstract
|
|
823
|
+
return False, f'no bioRxiv abstract found for {entry.get("biorxiv_doi")}', ''
|
|
824
|
+
|
|
825
|
+
|
|
826
|
+
def _chemrxiv_identifier(paper: Mapping[str, Any]) -> str | None:
|
|
827
|
+
"""Resolve a stored chemRxiv DOI for a paper row.
|
|
828
|
+
|
|
829
|
+
Only values already held in the corpus are considered, so this never issues
|
|
830
|
+
a request. chemRxiv does publish a title search, but it is not used here:
|
|
831
|
+
it costs a request per row and can return a different preprint with a
|
|
832
|
+
similar title, which would attach the wrong document to the row.
|
|
833
|
+
|
|
834
|
+
Parameters
|
|
835
|
+
----------
|
|
836
|
+
paper : Mapping[str, Any]
|
|
837
|
+
Corpus paper row containing a chemRxiv DOI, a chemRxiv paper ID, or a
|
|
838
|
+
chemRxiv content URL.
|
|
839
|
+
|
|
840
|
+
Returns
|
|
841
|
+
-------
|
|
842
|
+
str or None
|
|
843
|
+
chemRxiv DOI as registered, or ``None`` when the row stores none.
|
|
844
|
+
"""
|
|
845
|
+
return chemrxiv.resolve_chemrxiv_doi(paper) or None
|
|
846
|
+
|
|
847
|
+
|
|
848
|
+
def _chemrxiv_record(paper: Mapping[str, Any]) -> tuple[Mapping[str, Any] | None, str]:
|
|
849
|
+
"""Fetch the newest posted version of a row's chemRxiv preprint.
|
|
850
|
+
|
|
851
|
+
Parameters
|
|
852
|
+
----------
|
|
853
|
+
paper : Mapping[str, Any]
|
|
854
|
+
Corpus paper row carrying a chemRxiv DOI.
|
|
855
|
+
|
|
856
|
+
Returns
|
|
857
|
+
-------
|
|
858
|
+
tuple[Mapping[str, Any] or None, str]
|
|
859
|
+
Normalized record, or ``None`` and a failure reason.
|
|
860
|
+
"""
|
|
861
|
+
identifier = _chemrxiv_identifier(paper)
|
|
862
|
+
if identifier is None:
|
|
863
|
+
return None, 'missing chemRxiv DOI'
|
|
864
|
+
try:
|
|
865
|
+
entry = chemrxiv.fetch_doi(identifier)
|
|
866
|
+
except RuntimeError as e:
|
|
867
|
+
return None, str(e)
|
|
868
|
+
if entry is None:
|
|
869
|
+
return None, f'no chemRxiv record found for {identifier}'
|
|
870
|
+
return entry, ''
|
|
871
|
+
|
|
872
|
+
|
|
873
|
+
def _download_chemrxiv_pdf(
|
|
874
|
+
paper: Mapping[str, Any],
|
|
875
|
+
filepath: str | PathLike[str],
|
|
876
|
+
) -> tuple[bool, str]:
|
|
877
|
+
"""Download a paper's PDF from chemRxiv.
|
|
878
|
+
|
|
879
|
+
The location is derived from the DOI, which is what the registry currently
|
|
880
|
+
records; the record's own asset URL is tried second, because chemRxiv
|
|
881
|
+
changed hosting platforms and older records still name the previous one.
|
|
882
|
+
|
|
883
|
+
chemrxiv.org fronts these files with a bot challenge that can refuse a
|
|
884
|
+
client outright. A refusal is reported as the failure reason rather than
|
|
885
|
+
worked around, and the paper stays reachable through the other open-access
|
|
886
|
+
PDF sources when it happens.
|
|
887
|
+
|
|
888
|
+
Parameters
|
|
889
|
+
----------
|
|
890
|
+
paper : Mapping[str, Any]
|
|
891
|
+
Corpus paper row carrying a chemRxiv DOI.
|
|
892
|
+
filepath : str or os.PathLike[str]
|
|
893
|
+
Destination path for the downloaded PDF.
|
|
894
|
+
|
|
895
|
+
Returns
|
|
896
|
+
-------
|
|
897
|
+
tuple[bool, str]
|
|
898
|
+
Success flag, and the source URL on success or a failure reason.
|
|
899
|
+
"""
|
|
900
|
+
entry, error = _chemrxiv_record(paper)
|
|
901
|
+
if entry is None:
|
|
902
|
+
return False, error
|
|
903
|
+
identifier = str(entry.get('chemrxiv_doi') or '')
|
|
904
|
+
candidates = [chemrxiv.pdf_url(identifier), str(entry.get('asset_url') or '')]
|
|
905
|
+
errors = []
|
|
906
|
+
for url in [candidate for candidate in candidates if candidate]:
|
|
907
|
+
ok, failure = _download_url_to_pdf(url, filepath, headers=chemrxiv.request_headers())
|
|
908
|
+
if ok:
|
|
909
|
+
return True, url
|
|
910
|
+
errors.append(failure)
|
|
911
|
+
if not errors:
|
|
912
|
+
return False, 'missing chemRxiv DOI'
|
|
913
|
+
return False, '; '.join(errors)
|
|
914
|
+
|
|
915
|
+
|
|
916
|
+
def _download_chemrxiv_abstract(
|
|
917
|
+
paper: Mapping[str, Any],
|
|
918
|
+
) -> tuple[bool, str, str]:
|
|
919
|
+
"""Fetch and return a chemRxiv abstract for one paper row.
|
|
920
|
+
|
|
921
|
+
Parameters
|
|
922
|
+
----------
|
|
923
|
+
paper : Mapping[str, Any]
|
|
924
|
+
Corpus paper row carrying a chemRxiv DOI.
|
|
925
|
+
|
|
926
|
+
Returns
|
|
927
|
+
-------
|
|
928
|
+
tuple[bool, str, str]
|
|
929
|
+
Success flag, provider name or failure reason, and normalized abstract
|
|
930
|
+
text. The text is empty when retrieval fails.
|
|
931
|
+
"""
|
|
932
|
+
entry, error = _chemrxiv_record(paper)
|
|
933
|
+
if entry is None:
|
|
934
|
+
return False, error, ''
|
|
935
|
+
abstract = _clean_abstract(entry.get('abstract'))
|
|
936
|
+
if abstract:
|
|
937
|
+
return True, 'chemrxiv', abstract
|
|
938
|
+
return False, f'no chemRxiv abstract found for {entry.get("chemrxiv_doi")}', ''
|
|
939
|
+
|
|
940
|
+
|
|
941
|
+
def _arxiv_identifier(paper: Mapping[str, Any]) -> str | None:
|
|
942
|
+
"""Resolve a stored arXiv identifier for a paper row.
|
|
943
|
+
|
|
944
|
+
Only values already held in the corpus are considered, so this never issues
|
|
945
|
+
a request. arXiv has no DOI lookup, so the only alternative would be a
|
|
946
|
+
title search, which costs one paced request per paper and can match the
|
|
947
|
+
wrong record; :func:`paperminertoolkit.providers.arxiv.resolve_arxiv_id` offers that
|
|
948
|
+
deliberately as an opt-in rather than running it on every download.
|
|
949
|
+
|
|
950
|
+
Parameters
|
|
951
|
+
----------
|
|
952
|
+
paper : Mapping[str, Any]
|
|
953
|
+
Corpus paper row containing an arXiv ID, an ``arxiv:`` paper ID, or an
|
|
954
|
+
arXiv PDF URL.
|
|
955
|
+
|
|
956
|
+
Returns
|
|
957
|
+
-------
|
|
958
|
+
str or None
|
|
959
|
+
Bare arXiv identifier, or ``None`` when the row stores none.
|
|
960
|
+
"""
|
|
961
|
+
identifier = arxiv.normalize_arxiv_id(paper.get('arxiv_id')) if _has_value(paper.get('arxiv_id')) else ''
|
|
962
|
+
if identifier:
|
|
963
|
+
return identifier
|
|
964
|
+
paper_id = str(paper.get('paper_id') or '')
|
|
965
|
+
if paper_id.startswith('arxiv:'):
|
|
966
|
+
identifier = arxiv.normalize_arxiv_id(paper_id.split(':', 1)[1])
|
|
967
|
+
if identifier:
|
|
968
|
+
return identifier
|
|
969
|
+
url = str(paper.get('pdf_url') or '')
|
|
970
|
+
if 'arxiv.org' in url.lower():
|
|
971
|
+
return arxiv.normalize_arxiv_id(url) or None
|
|
972
|
+
return None
|
|
973
|
+
|
|
974
|
+
|
|
975
|
+
def _download_arxiv_pdf(
|
|
976
|
+
paper: Mapping[str, Any],
|
|
977
|
+
filepath: str | PathLike[str],
|
|
978
|
+
) -> tuple[bool, str]:
|
|
979
|
+
"""Download a paper's PDF from arXiv.
|
|
980
|
+
|
|
981
|
+
Parameters
|
|
982
|
+
----------
|
|
983
|
+
paper : Mapping[str, Any]
|
|
984
|
+
Corpus paper row carrying an arXiv identifier.
|
|
985
|
+
filepath : str or os.PathLike[str]
|
|
986
|
+
Destination path for the downloaded PDF.
|
|
987
|
+
|
|
988
|
+
Returns
|
|
989
|
+
-------
|
|
990
|
+
tuple[bool, str]
|
|
991
|
+
Success flag, and the source URL or a failure reason.
|
|
992
|
+
"""
|
|
993
|
+
identifier = _arxiv_identifier(paper)
|
|
994
|
+
if identifier is None:
|
|
995
|
+
return False, 'missing arXiv ID'
|
|
996
|
+
url = f'{arxiv.PDF_URL}/{quote(identifier, safe="/")}'
|
|
997
|
+
ok, error = _download_url_to_pdf(url, filepath, headers=arxiv.request_headers())
|
|
998
|
+
return (True, url) if ok else (False, error)
|
|
999
|
+
|
|
1000
|
+
|
|
1001
|
+
def _download_arxiv_abstract(
|
|
1002
|
+
paper: Mapping[str, Any],
|
|
1003
|
+
) -> tuple[bool, str, str]:
|
|
1004
|
+
"""Fetch and return an arXiv abstract for one paper row.
|
|
1005
|
+
|
|
1006
|
+
Parameters
|
|
1007
|
+
----------
|
|
1008
|
+
paper : Mapping[str, Any]
|
|
1009
|
+
Corpus paper row carrying an arXiv identifier.
|
|
1010
|
+
|
|
1011
|
+
Returns
|
|
1012
|
+
-------
|
|
1013
|
+
tuple[bool, str, str]
|
|
1014
|
+
Success flag, provider name or failure reason, and normalized abstract
|
|
1015
|
+
text. The text is empty when retrieval fails.
|
|
1016
|
+
"""
|
|
1017
|
+
identifier = _arxiv_identifier(paper)
|
|
1018
|
+
if identifier is None:
|
|
1019
|
+
return False, 'missing arXiv ID', ''
|
|
1020
|
+
try:
|
|
1021
|
+
entries = arxiv.parse_entries(arxiv.fetch_ids([identifier]))
|
|
1022
|
+
except RuntimeError as e:
|
|
1023
|
+
return False, str(e), ''
|
|
1024
|
+
if not entries:
|
|
1025
|
+
return False, f'no arXiv record found for {identifier}', ''
|
|
1026
|
+
abstract = _clean_abstract(entries[0].get('abstract'))
|
|
1027
|
+
if abstract:
|
|
1028
|
+
return True, 'arxiv', abstract
|
|
1029
|
+
return False, f'no arXiv abstract found for {identifier}', ''
|
|
1030
|
+
|
|
1031
|
+
|
|
1032
|
+
def _download_openalex_abstract(
|
|
1033
|
+
paper: Mapping[str, Any],
|
|
1034
|
+
) -> tuple[bool, str, str]:
|
|
1035
|
+
"""Fetch and reconstruct an abstract from OpenAlex work metadata.
|
|
1036
|
+
|
|
1037
|
+
Parameters
|
|
1038
|
+
----------
|
|
1039
|
+
paper : Mapping[str, Any]
|
|
1040
|
+
Corpus paper row containing a DOI or OpenAlex work identifier.
|
|
1041
|
+
|
|
1042
|
+
Returns
|
|
1043
|
+
-------
|
|
1044
|
+
tuple[bool, str, str]
|
|
1045
|
+
Success flag, provider name or failure reason, and normalized abstract
|
|
1046
|
+
text. The text is empty when retrieval fails or no abstract is stored.
|
|
1047
|
+
"""
|
|
1048
|
+
identifier = _openalex_identifier(paper)
|
|
1049
|
+
if identifier is None:
|
|
1050
|
+
return False, 'missing DOI or OpenAlex ID', ''
|
|
1051
|
+
try:
|
|
1052
|
+
work = openalex.get_work(identifier, api_key=openalex.configured_api_key())
|
|
1053
|
+
except RuntimeError as error:
|
|
1054
|
+
return False, str(error), ''
|
|
1055
|
+
if not work:
|
|
1056
|
+
return False, f'no OpenAlex work found for {identifier}', ''
|
|
1057
|
+
abstract = _clean_abstract(
|
|
1058
|
+
openalex.reconstruct_abstract(work.get('abstract_inverted_index'))
|
|
1059
|
+
)
|
|
1060
|
+
if abstract:
|
|
1061
|
+
return True, 'openalex', abstract
|
|
1062
|
+
return False, 'no OpenAlex abstract found', ''
|
|
1063
|
+
|
|
1064
|
+
|
|
1065
|
+
def _clean_abstract(value: object) -> str:
|
|
1066
|
+
"""Normalize provider abstract text to compact plain text."""
|
|
1067
|
+
if not _has_value(value):
|
|
1068
|
+
return ''
|
|
1069
|
+
if isinstance(value, list):
|
|
1070
|
+
value = ' '.join(str(part) for part in value if _has_value(part))
|
|
1071
|
+
text = html.unescape(str(value))
|
|
1072
|
+
text = re.sub(r'<[^>]+>', ' ', text)
|
|
1073
|
+
text = re.sub(r'\s+', ' ', text).strip()
|
|
1074
|
+
return text
|
|
1075
|
+
|
|
1076
|
+
|
|
1077
|
+
def _abstract_from_mapping(value: object) -> str:
|
|
1078
|
+
"""Return the first abstract-like text from a nested provider mapping."""
|
|
1079
|
+
if isinstance(value, dict):
|
|
1080
|
+
for key in ['abstract', 'dc:description', 'description', 'dcDescription']:
|
|
1081
|
+
abstract = _clean_abstract(value.get(key))
|
|
1082
|
+
if abstract:
|
|
1083
|
+
return abstract
|
|
1084
|
+
for child in value.values():
|
|
1085
|
+
abstract = _abstract_from_mapping(child)
|
|
1086
|
+
if abstract:
|
|
1087
|
+
return abstract
|
|
1088
|
+
elif isinstance(value, list):
|
|
1089
|
+
for child in value:
|
|
1090
|
+
abstract = _abstract_from_mapping(child)
|
|
1091
|
+
if abstract:
|
|
1092
|
+
return abstract
|
|
1093
|
+
return ''
|
|
1094
|
+
|
|
1095
|
+
|
|
1096
|
+
def _download_core_abstract(paper: Mapping[str, Any]) -> tuple[bool, str, str]:
|
|
1097
|
+
"""Fetch and return a CORE abstract for one paper row.
|
|
1098
|
+
|
|
1099
|
+
Parameters
|
|
1100
|
+
----------
|
|
1101
|
+
paper : Mapping[str, Any]
|
|
1102
|
+
Corpus paper row.
|
|
1103
|
+
|
|
1104
|
+
Returns
|
|
1105
|
+
-------
|
|
1106
|
+
tuple[bool, str, str]
|
|
1107
|
+
Success flag, provider name or failure reason, and the abstract text.
|
|
1108
|
+
"""
|
|
1109
|
+
core_id = core.resolve_core_id(paper)
|
|
1110
|
+
if not core_id:
|
|
1111
|
+
return False, 'missing CORE ID', ''
|
|
1112
|
+
try:
|
|
1113
|
+
work = core.get_work(core_id)
|
|
1114
|
+
except RuntimeError as e:
|
|
1115
|
+
return False, str(e), ''
|
|
1116
|
+
abstract = _abstract_from_mapping(work) if work else ''
|
|
1117
|
+
if abstract:
|
|
1118
|
+
return True, 'core', abstract
|
|
1119
|
+
return False, 'no CORE abstract found', ''
|
|
1120
|
+
|
|
1121
|
+
|
|
1122
|
+
def _elsevier_abstract_urls(paper: Mapping[str, Any]) -> list[str]:
|
|
1123
|
+
"""Build Elsevier abstract endpoint candidates for a paper row."""
|
|
1124
|
+
urls = []
|
|
1125
|
+
link = paper.get('elsevier_link')
|
|
1126
|
+
for value in _link_values(link):
|
|
1127
|
+
if isinstance(value, dict):
|
|
1128
|
+
href = value.get('@href') or value.get('href') or value.get('url') or ''
|
|
1129
|
+
ref = str(value.get('@ref') or value.get('ref') or '').lower()
|
|
1130
|
+
if href and ('abstract' in ref or '/content/abstract/' in str(href).lower()):
|
|
1131
|
+
urls.append(str(href))
|
|
1132
|
+
elif isinstance(value, str) and '/content/abstract/' in value.lower():
|
|
1133
|
+
urls.append(value)
|
|
1134
|
+
paper_id = str(paper.get('paper_id') or '')
|
|
1135
|
+
if paper_id.startswith('SCOPUS_ID:'):
|
|
1136
|
+
urls.append(f'https://api.elsevier.com/content/abstract/scopus_id/{quote(paper_id.split(":", 1)[1])}')
|
|
1137
|
+
doi = paper.get('doi')
|
|
1138
|
+
if _has_value(doi):
|
|
1139
|
+
urls.append(f'https://api.elsevier.com/content/abstract/doi/{quote(str(doi).strip(), safe="")}')
|
|
1140
|
+
return list(dict.fromkeys(urls))
|
|
1141
|
+
|
|
1142
|
+
|
|
1143
|
+
def _download_elsevier_abstract(paper: Mapping[str, Any]) -> tuple[bool, str, str]:
|
|
1144
|
+
"""Fetch and return an Elsevier abstract for one paper row."""
|
|
1145
|
+
urls = _elsevier_abstract_urls(paper)
|
|
1146
|
+
if not urls:
|
|
1147
|
+
return False, 'missing Elsevier abstract URL', ''
|
|
1148
|
+
api_key = elsevier.configured_api_key()
|
|
1149
|
+
last_error = 'no Elsevier abstract found'
|
|
1150
|
+
for url in urls:
|
|
1151
|
+
try:
|
|
1152
|
+
response = elsevier.get_content(api_key, url, accept='application/json', params={'httpAccept': 'application/json'})
|
|
1153
|
+
abstract = _abstract_from_mapping(response.json())
|
|
1154
|
+
if abstract:
|
|
1155
|
+
return True, 'elsevier', abstract
|
|
1156
|
+
last_error = f'no abstract in response from {url}'
|
|
1157
|
+
except requests.HTTPError as e:
|
|
1158
|
+
response = getattr(e, 'response', None)
|
|
1159
|
+
status_code = response.status_code if response is not None else 'HTTP error'
|
|
1160
|
+
last_error = f'{status_code} from {url}'
|
|
1161
|
+
except requests.RequestException as e:
|
|
1162
|
+
last_error = str(e)
|
|
1163
|
+
return False, last_error, ''
|
|
1164
|
+
|
|
1165
|
+
|
|
1166
|
+
def _reachable(answer: object) -> bool:
|
|
1167
|
+
"""Read an identifier helper's answer as a yes or a no.
|
|
1168
|
+
|
|
1169
|
+
Parameters
|
|
1170
|
+
----------
|
|
1171
|
+
answer : object
|
|
1172
|
+
Either a bool from a reachability predicate, or an identifier -- or
|
|
1173
|
+
``None`` -- from one of the ``_<source>_identifier`` helpers.
|
|
1174
|
+
|
|
1175
|
+
Returns
|
|
1176
|
+
-------
|
|
1177
|
+
bool
|
|
1178
|
+
Whether the source can be asked about this paper.
|
|
1179
|
+
"""
|
|
1180
|
+
return answer is not False and answer is not None
|
|
1181
|
+
|
|
1182
|
+
|
|
1183
|
+
def _source_reachable(name: str, capability: str, paper: Mapping[str, Any]) -> bool:
|
|
1184
|
+
"""Report whether a registered source can be asked for one paper asset."""
|
|
1185
|
+
predicate = registry.resolve_reachability(name, capability)
|
|
1186
|
+
return predicate is None or _reachable(predicate(paper))
|
|
1187
|
+
|
|
1188
|
+
|
|
1189
|
+
def _pubmed_abstract_reachable(paper: Mapping[str, Any]) -> bool:
|
|
1190
|
+
"""Report whether PubMed can be asked for this paper's abstract.
|
|
1191
|
+
|
|
1192
|
+
Parameters
|
|
1193
|
+
----------
|
|
1194
|
+
paper : Mapping[str, Any]
|
|
1195
|
+
Corpus paper row.
|
|
1196
|
+
|
|
1197
|
+
Returns
|
|
1198
|
+
-------
|
|
1199
|
+
bool
|
|
1200
|
+
Whether the row carries a PubMed identifier or a DOI to resolve one
|
|
1201
|
+
from.
|
|
1202
|
+
"""
|
|
1203
|
+
return _pubmed_identifier(paper) is not None or _has_value(paper.get('doi'))
|
|
1204
|
+
|
|
1205
|
+
|
|
1206
|
+
def _core_abstract_reachable(paper: Mapping[str, Any]) -> bool:
|
|
1207
|
+
"""Report whether CORE can be asked for this paper's abstract.
|
|
1208
|
+
|
|
1209
|
+
Parameters
|
|
1210
|
+
----------
|
|
1211
|
+
paper : Mapping[str, Any]
|
|
1212
|
+
Corpus paper row.
|
|
1213
|
+
|
|
1214
|
+
Returns
|
|
1215
|
+
-------
|
|
1216
|
+
bool
|
|
1217
|
+
Whether the row carries a CORE identifier.
|
|
1218
|
+
"""
|
|
1219
|
+
return _has_value(paper.get('core_id'))
|
|
1220
|
+
|
|
1221
|
+
|
|
1222
|
+
def _elsevier_abstract_reachable(paper: Mapping[str, Any]) -> bool:
|
|
1223
|
+
"""Report whether Elsevier can be asked for this paper's abstract.
|
|
1224
|
+
|
|
1225
|
+
Parameters
|
|
1226
|
+
----------
|
|
1227
|
+
paper : Mapping[str, Any]
|
|
1228
|
+
Corpus paper row. Unused; Elsevier is reachable for any row once a key
|
|
1229
|
+
is configured, because the lookup goes by DOI.
|
|
1230
|
+
|
|
1231
|
+
Returns
|
|
1232
|
+
-------
|
|
1233
|
+
bool
|
|
1234
|
+
Whether an Elsevier API key is configured.
|
|
1235
|
+
"""
|
|
1236
|
+
return _elsevier_configured()
|
|
1237
|
+
|
|
1238
|
+
|
|
1239
|
+
def _download_abstract(paper: MutableMapping[str, Any],
|
|
1240
|
+
sources: Iterable[str] | None = None) -> tuple[bool, str, str]:
|
|
1241
|
+
"""Fetch abstract text from the requested metadata providers.
|
|
1242
|
+
|
|
1243
|
+
Sources are tried in the registry's abstract order, skipping any the row
|
|
1244
|
+
cannot reach and any the caller did not ask for. Until now the caller's
|
|
1245
|
+
``--source`` selection was ignored here entirely, so a run scoped to one
|
|
1246
|
+
provider still queried all eight.
|
|
1247
|
+
|
|
1248
|
+
A PubMed identifier resolved from a DOI is recorded on ``paper`` so the
|
|
1249
|
+
corpus keeps it after the caller upserts the row.
|
|
1250
|
+
|
|
1251
|
+
Parameters
|
|
1252
|
+
----------
|
|
1253
|
+
paper : MutableMapping[str, Any]
|
|
1254
|
+
Corpus paper row.
|
|
1255
|
+
sources : Iterable[str] or None, optional
|
|
1256
|
+
Resolved provider names for this run. Defaults to every source that
|
|
1257
|
+
serves abstracts.
|
|
1258
|
+
|
|
1259
|
+
Returns
|
|
1260
|
+
-------
|
|
1261
|
+
tuple[bool, str, str]
|
|
1262
|
+
Success flag, provider name or joined failure reasons, and the abstract
|
|
1263
|
+
text.
|
|
1264
|
+
"""
|
|
1265
|
+
requested = set(sources) if sources is not None else set(registry.names(registry.ABSTRACT))
|
|
1266
|
+
errors = []
|
|
1267
|
+
for name in registry.names(registry.ABSTRACT):
|
|
1268
|
+
if name not in requested:
|
|
1269
|
+
continue
|
|
1270
|
+
if not _source_reachable(name, registry.ABSTRACT, paper):
|
|
1271
|
+
continue
|
|
1272
|
+
downloader = registry.resolve_handler(name, registry.ABSTRACT)
|
|
1273
|
+
ok, source, abstract = downloader(paper)
|
|
1274
|
+
if ok:
|
|
1275
|
+
return ok, source, abstract
|
|
1276
|
+
errors.append(f'{name}: {source}')
|
|
1277
|
+
return False, '; '.join(errors) or 'no abstract source available', ''
|
|
1278
|
+
|
|
1279
|
+
|
|
1280
|
+
def _configured_sources(requested: Iterable[str] | None) -> list[str]:
|
|
1281
|
+
"""Resolve requested download sources, dropping ones with no credential.
|
|
1282
|
+
|
|
1283
|
+
An unscoped run skips a source whose credential is not configured, because
|
|
1284
|
+
a request it cannot authenticate is a wasted round trip. An explicitly
|
|
1285
|
+
named source is kept whatever its credential, so the failure says what is
|
|
1286
|
+
missing rather than silently doing nothing.
|
|
1287
|
+
|
|
1288
|
+
Parameters
|
|
1289
|
+
----------
|
|
1290
|
+
requested : Iterable[str] or None
|
|
1291
|
+
Requested source names, or ``None`` for every configured source.
|
|
1292
|
+
|
|
1293
|
+
Returns
|
|
1294
|
+
-------
|
|
1295
|
+
list[str]
|
|
1296
|
+
Source names in the registry's download order.
|
|
1297
|
+
|
|
1298
|
+
Raises
|
|
1299
|
+
------
|
|
1300
|
+
ValueError
|
|
1301
|
+
If a requested name is not a download source.
|
|
1302
|
+
"""
|
|
1303
|
+
asked = list(requested or [])
|
|
1304
|
+
resolved = registry.resolve_names(asked, registry.PDF, preserve_order=True,
|
|
1305
|
+
label='download')
|
|
1306
|
+
if asked and 'all' not in {str(name).strip().lower() for name in asked}:
|
|
1307
|
+
return resolved
|
|
1308
|
+
settings = load_settings()
|
|
1309
|
+
return [name for name in resolved if _source_configured(name, settings)]
|
|
1310
|
+
|
|
1311
|
+
|
|
1312
|
+
def _source_configured(name: str, settings: Mapping[str, str]) -> bool:
|
|
1313
|
+
"""Report whether a source that needs a credential has one.
|
|
1314
|
+
|
|
1315
|
+
Only a required credential gates a source. OpenAlex and PubMed both answer
|
|
1316
|
+
without a key -- the key buys a larger budget -- so an unscoped run still
|
|
1317
|
+
asks them.
|
|
1318
|
+
|
|
1319
|
+
Parameters
|
|
1320
|
+
----------
|
|
1321
|
+
name : str
|
|
1322
|
+
Registry source name.
|
|
1323
|
+
settings : Mapping[str, str]
|
|
1324
|
+
Loaded PaperMinerToolkit settings.
|
|
1325
|
+
|
|
1326
|
+
Returns
|
|
1327
|
+
-------
|
|
1328
|
+
bool
|
|
1329
|
+
Whether the source can be used without further configuration.
|
|
1330
|
+
"""
|
|
1331
|
+
entry = registry.SOURCES[name]
|
|
1332
|
+
if not entry.credential_required:
|
|
1333
|
+
return True
|
|
1334
|
+
return bool(settings.get(entry.credential) or os.environ.get(entry.credential_env))
|
|
1335
|
+
|
|
1336
|
+
|
|
1337
|
+
def _elsevier_configured() -> bool:
|
|
1338
|
+
"""Return whether an Elsevier API key is available for downloads."""
|
|
1339
|
+
return bool(load_settings().get('elsevier_api_key'))
|
|
1340
|
+
|
|
1341
|
+
|
|
1342
|
+
def _download_elsevier_pdf(
|
|
1343
|
+
paper: Mapping[str, Any],
|
|
1344
|
+
filepath: str | PathLike[str],
|
|
1345
|
+
) -> tuple[bool, str]:
|
|
1346
|
+
"""Fetch a paper's PDF through the Elsevier article route.
|
|
1347
|
+
|
|
1348
|
+
Parameters
|
|
1349
|
+
----------
|
|
1350
|
+
paper : Mapping[str, Any]
|
|
1351
|
+
Corpus paper row.
|
|
1352
|
+
filepath : str or os.PathLike[str]
|
|
1353
|
+
Destination path for the downloaded PDF.
|
|
1354
|
+
|
|
1355
|
+
Returns
|
|
1356
|
+
-------
|
|
1357
|
+
tuple[bool, str]
|
|
1358
|
+
Success flag, and the failure reason when unsuccessful.
|
|
1359
|
+
"""
|
|
1360
|
+
return _download_pdf(paper, filepath), 'Elsevier PDF download failed'
|
|
1361
|
+
|
|
1362
|
+
|
|
1363
|
+
def _pdf_downloader(source: str) -> Callable[..., tuple[bool, str]]:
|
|
1364
|
+
"""Return the PDF downloader for one source.
|
|
1365
|
+
|
|
1366
|
+
Parameters
|
|
1367
|
+
----------
|
|
1368
|
+
source : str
|
|
1369
|
+
Registry source name.
|
|
1370
|
+
|
|
1371
|
+
Returns
|
|
1372
|
+
-------
|
|
1373
|
+
Callable[..., tuple[bool, str]]
|
|
1374
|
+
Downloader taking a paper row and a destination path.
|
|
1375
|
+
"""
|
|
1376
|
+
return registry.resolve_handler(source, registry.PDF)
|
|
1377
|
+
|
|
1378
|
+
|
|
1379
|
+
def _download_pdf_from_sources(
|
|
1380
|
+
paper: Mapping[str, Any],
|
|
1381
|
+
filepath: str | PathLike[str],
|
|
1382
|
+
sources: Iterable[str],
|
|
1383
|
+
) -> tuple[bool, str, str]:
|
|
1384
|
+
"""Try configured PDF sources in order and return success/source details."""
|
|
1385
|
+
errors = []
|
|
1386
|
+
for source in sources:
|
|
1387
|
+
downloader = _pdf_downloader(source)
|
|
1388
|
+
try:
|
|
1389
|
+
ok, detail = downloader(paper, filepath)
|
|
1390
|
+
except Exception as e:
|
|
1391
|
+
ok, detail = False, str(e)
|
|
1392
|
+
if ok:
|
|
1393
|
+
return True, source, detail
|
|
1394
|
+
errors.append(f'{source}: {detail}')
|
|
1395
|
+
return False, '; '.join(errors), ''
|
|
1396
|
+
|
|
1397
|
+
|
|
1398
|
+
def _download_elsevier_text(paper: Mapping[str, Any],
|
|
1399
|
+
filepath: str | PathLike[str]) -> tuple[bool, str]:
|
|
1400
|
+
"""Fetch a paper's full text through the Elsevier article route.
|
|
1401
|
+
|
|
1402
|
+
Parameters
|
|
1403
|
+
----------
|
|
1404
|
+
paper : Mapping[str, Any]
|
|
1405
|
+
Corpus paper row.
|
|
1406
|
+
filepath : str or os.PathLike[str]
|
|
1407
|
+
Destination path for the downloaded text.
|
|
1408
|
+
|
|
1409
|
+
Returns
|
|
1410
|
+
-------
|
|
1411
|
+
tuple[bool, str]
|
|
1412
|
+
Success flag, and the failure reason when unsuccessful.
|
|
1413
|
+
"""
|
|
1414
|
+
if os.path.isfile(filepath) or _download_text(paper, filepath):
|
|
1415
|
+
return True, ''
|
|
1416
|
+
return False, 'Elsevier text download failed'
|
|
1417
|
+
|
|
1418
|
+
|
|
1419
|
+
def _download_text_from_sources(
|
|
1420
|
+
paper: Mapping[str, Any],
|
|
1421
|
+
filepath: str | PathLike[str],
|
|
1422
|
+
sources: Iterable[str],
|
|
1423
|
+
) -> tuple[bool, str, str]:
|
|
1424
|
+
"""Try each requested full-text source in order and report the outcome.
|
|
1425
|
+
|
|
1426
|
+
Elsevier is one of these sources rather than a separate flag threaded
|
|
1427
|
+
through three call sites, so ``--source elsevier --format text`` means what
|
|
1428
|
+
it says and ``--source pubmed`` no longer also tries Elsevier.
|
|
1429
|
+
|
|
1430
|
+
Parameters
|
|
1431
|
+
----------
|
|
1432
|
+
paper : Mapping[str, Any]
|
|
1433
|
+
Corpus paper row.
|
|
1434
|
+
filepath : str or os.PathLike[str]
|
|
1435
|
+
Destination path for the downloaded text.
|
|
1436
|
+
sources : Iterable[str]
|
|
1437
|
+
Resolved provider names for this run.
|
|
1438
|
+
|
|
1439
|
+
Returns
|
|
1440
|
+
-------
|
|
1441
|
+
tuple[bool, str, str]
|
|
1442
|
+
Success flag, provider name or joined failure reasons, and an empty
|
|
1443
|
+
string reserved for a source URL.
|
|
1444
|
+
"""
|
|
1445
|
+
requested = set(sources)
|
|
1446
|
+
errors = []
|
|
1447
|
+
for name in registry.names(registry.TEXT):
|
|
1448
|
+
if name not in requested:
|
|
1449
|
+
continue
|
|
1450
|
+
if not _source_reachable(name, registry.TEXT, paper):
|
|
1451
|
+
continue
|
|
1452
|
+
try:
|
|
1453
|
+
downloader = registry.resolve_handler(name, registry.TEXT)
|
|
1454
|
+
ok, detail = downloader(paper, filepath)
|
|
1455
|
+
if ok:
|
|
1456
|
+
return True, name, ''
|
|
1457
|
+
errors.append(f'{name}: {detail}')
|
|
1458
|
+
except Exception as e:
|
|
1459
|
+
errors.append(f'{name}: {e}')
|
|
1460
|
+
return False, '; '.join(errors) or 'no full-text source available', ''
|
|
1461
|
+
|
|
1462
|
+
|
|
1463
|
+
def _should_try_elsevier_text(paper: Mapping[str, Any]) -> bool:
|
|
1464
|
+
"""Return whether a paper row advertises Elsevier full text."""
|
|
1465
|
+
return _full_text_uri(paper) is not None
|
|
1466
|
+
|
|
1467
|
+
|
|
1468
|
+
def _should_try_medrxiv_text(paper: Mapping[str, Any]) -> bool:
|
|
1469
|
+
"""Return whether a paper row can be looked up on medRxiv.
|
|
1470
|
+
|
|
1471
|
+
Parameters
|
|
1472
|
+
----------
|
|
1473
|
+
paper : Mapping[str, Any]
|
|
1474
|
+
Corpus paper row.
|
|
1475
|
+
|
|
1476
|
+
Returns
|
|
1477
|
+
-------
|
|
1478
|
+
bool
|
|
1479
|
+
Whether the row carries a medRxiv DOI to fetch a JATS document with.
|
|
1480
|
+
"""
|
|
1481
|
+
return _medrxiv_identifier(paper) is not None
|
|
1482
|
+
|
|
1483
|
+
|
|
1484
|
+
def _should_try_biorxiv_text(paper: Mapping[str, Any]) -> bool:
|
|
1485
|
+
"""Return whether a paper row can be looked up on bioRxiv.
|
|
1486
|
+
|
|
1487
|
+
Parameters
|
|
1488
|
+
----------
|
|
1489
|
+
paper : Mapping[str, Any]
|
|
1490
|
+
Corpus paper row.
|
|
1491
|
+
|
|
1492
|
+
Returns
|
|
1493
|
+
-------
|
|
1494
|
+
bool
|
|
1495
|
+
Whether the row carries a bioRxiv DOI to fetch a JATS document with.
|
|
1496
|
+
"""
|
|
1497
|
+
return _biorxiv_identifier(paper) is not None
|
|
1498
|
+
|
|
1499
|
+
|
|
1500
|
+
def _store_downloaded_asset(
|
|
1501
|
+
conn: sqlite3.Connection,
|
|
1502
|
+
paper: Mapping[str, Any],
|
|
1503
|
+
filepath: str | PathLike[str],
|
|
1504
|
+
role: str,
|
|
1505
|
+
source: str,
|
|
1506
|
+
) -> None:
|
|
1507
|
+
"""Store a downloaded text or PDF file in the corpus blob store."""
|
|
1508
|
+
if role in {'text', 'abstract'}:
|
|
1509
|
+
kind = 'text'
|
|
1510
|
+
mime_type = 'text/plain'
|
|
1511
|
+
elif role == 'pdf':
|
|
1512
|
+
kind = 'pdf'
|
|
1513
|
+
mime_type = 'application/pdf'
|
|
1514
|
+
else:
|
|
1515
|
+
raise ValueError('role must be text, abstract, or pdf')
|
|
1516
|
+
add_asset(
|
|
1517
|
+
conn,
|
|
1518
|
+
paper,
|
|
1519
|
+
Path(filepath),
|
|
1520
|
+
role=role,
|
|
1521
|
+
kind=kind,
|
|
1522
|
+
mime_type=mime_type,
|
|
1523
|
+
source=source,
|
|
1524
|
+
original_filename=os.path.basename(filepath),
|
|
1525
|
+
)
|
|
1526
|
+
|
|
1527
|
+
|
|
1528
|
+
def download_papers(db_path: str | PathLike[str] = 'papers.db',
|
|
1529
|
+
download_format: str = 'text',
|
|
1530
|
+
sources: Iterable[str] | None = None,
|
|
1531
|
+
download_abstract: bool = True,
|
|
1532
|
+
force: bool = False) -> None:
|
|
1533
|
+
"""Download paper assets and update a corpus in place.
|
|
1534
|
+
|
|
1535
|
+
Parameters
|
|
1536
|
+
----------
|
|
1537
|
+
db_path : str or os.PathLike[str], default='papers.db'
|
|
1538
|
+
Path to the SQLite paper corpus.
|
|
1539
|
+
download_format : {'abstract', 'both', 'pdf', 'text'}, default='text'
|
|
1540
|
+
Primary asset types to download.
|
|
1541
|
+
sources : Iterable[str] or None, optional
|
|
1542
|
+
Ordered content providers to try. ``all`` expands to the configured
|
|
1543
|
+
providers. The selection orders PDF retrieval and also decides whether
|
|
1544
|
+
PubMed Central is consulted for full text.
|
|
1545
|
+
download_abstract : bool, default=True
|
|
1546
|
+
Whether to retrieve and store abstracts.
|
|
1547
|
+
force : bool, default=False
|
|
1548
|
+
Redownload requested asset types even when they are already stored.
|
|
1549
|
+
|
|
1550
|
+
Returns
|
|
1551
|
+
-------
|
|
1552
|
+
None
|
|
1553
|
+
Assets and status fields are written directly to the corpus.
|
|
1554
|
+
|
|
1555
|
+
Raises
|
|
1556
|
+
------
|
|
1557
|
+
ValueError
|
|
1558
|
+
If the format or source is invalid, or required provider configuration
|
|
1559
|
+
is unavailable.
|
|
1560
|
+
"""
|
|
1561
|
+
download_format = download_format.lower()
|
|
1562
|
+
if download_format not in DOWNLOAD_FORMATS:
|
|
1563
|
+
raise ValueError(f'download_format must be one of: {", ".join(sorted(DOWNLOAD_FORMATS))}')
|
|
1564
|
+
sources = _configured_sources(sources or ['all'])
|
|
1565
|
+
with connect(db_path) as conn:
|
|
1566
|
+
papers = paper_rows(conn)
|
|
1567
|
+
if download_format == 'text' and not TEXT_SOURCES.intersection(sources):
|
|
1568
|
+
missing_text = force or any(
|
|
1569
|
+
get_asset_metadata(conn, paper['paper_id'], 'text') is None
|
|
1570
|
+
for paper in papers
|
|
1571
|
+
)
|
|
1572
|
+
if missing_text:
|
|
1573
|
+
raise ValueError(
|
|
1574
|
+
'Text download requires an Elsevier API key, the pubmed source, or a '
|
|
1575
|
+
'preprint-server source. Run pmt config elsevier-key first, pass --source pubmed '
|
|
1576
|
+
'for PubMed Central open-access full text, or pass --source medrxiv or '
|
|
1577
|
+
'--source biorxiv for preprint JATS full text.'
|
|
1578
|
+
)
|
|
1579
|
+
if download_format in {'pdf', 'both'} and not sources:
|
|
1580
|
+
missing_pdf = force or any(
|
|
1581
|
+
get_asset_metadata(conn, paper['paper_id'], 'pdf') is None
|
|
1582
|
+
for paper in papers
|
|
1583
|
+
)
|
|
1584
|
+
if missing_pdf:
|
|
1585
|
+
raise ValueError(
|
|
1586
|
+
'No PDF download sources are configured. Set an Unpaywall email, '
|
|
1587
|
+
'CORE API key, or Elsevier API key.'
|
|
1588
|
+
)
|
|
1589
|
+
summary = {
|
|
1590
|
+
'texts': 0,
|
|
1591
|
+
'pdfs': 0,
|
|
1592
|
+
'abstracts': 0,
|
|
1593
|
+
'texts_skipped': 0,
|
|
1594
|
+
'pdfs_skipped': 0,
|
|
1595
|
+
'abstracts_skipped': 0,
|
|
1596
|
+
}
|
|
1597
|
+
with tempfile.TemporaryDirectory(prefix='paperminertoolkit-download-') as download_dir:
|
|
1598
|
+
with tqdm(total=len(papers), desc='Downloading Papers', colour='#A020F0') as pbar:
|
|
1599
|
+
for paper in papers:
|
|
1600
|
+
paper_summary = _download_paper(conn,
|
|
1601
|
+
paper,
|
|
1602
|
+
download_dir,
|
|
1603
|
+
download_format,
|
|
1604
|
+
sources,
|
|
1605
|
+
download_abstract=download_abstract,
|
|
1606
|
+
force=force)
|
|
1607
|
+
for key, value in paper_summary.items():
|
|
1608
|
+
summary[key] += value
|
|
1609
|
+
pbar.update(1)
|
|
1610
|
+
print(
|
|
1611
|
+
f"Download complete: {summary['texts']} text files, "
|
|
1612
|
+
f"{summary['pdfs']} PDFs, {summary['abstracts']} abstracts downloaded."
|
|
1613
|
+
)
|
|
1614
|
+
skipped = summary['texts_skipped'] + summary['pdfs_skipped'] + summary['abstracts_skipped']
|
|
1615
|
+
if skipped:
|
|
1616
|
+
print(
|
|
1617
|
+
f"Skipped existing corpus assets: {summary['texts_skipped']} text files, "
|
|
1618
|
+
f"{summary['pdfs_skipped']} PDFs, {summary['abstracts_skipped']} abstracts. "
|
|
1619
|
+
"Use --force to redownload them."
|
|
1620
|
+
)
|
|
1621
|
+
|
|
1622
|
+
|
|
1623
|
+
def _download_paper(
|
|
1624
|
+
conn: sqlite3.Connection,
|
|
1625
|
+
paper: _Paper,
|
|
1626
|
+
download_dir: str | PathLike[str],
|
|
1627
|
+
download_format: str,
|
|
1628
|
+
sources: Iterable[str],
|
|
1629
|
+
download_abstract: bool = True,
|
|
1630
|
+
force: bool = False,
|
|
1631
|
+
) -> dict[str, int]:
|
|
1632
|
+
"""Download requested assets for one corpus paper row."""
|
|
1633
|
+
filename = _safe_filename(paper)
|
|
1634
|
+
summary = {
|
|
1635
|
+
'texts': 0,
|
|
1636
|
+
'pdfs': 0,
|
|
1637
|
+
'abstracts': 0,
|
|
1638
|
+
'texts_skipped': 0,
|
|
1639
|
+
'pdfs_skipped': 0,
|
|
1640
|
+
'abstracts_skipped': 0,
|
|
1641
|
+
}
|
|
1642
|
+
existing_assets = {
|
|
1643
|
+
role: get_asset_metadata(conn, paper.get('paper_id'), role)
|
|
1644
|
+
for role in ['abstract', 'text', 'pdf']
|
|
1645
|
+
}
|
|
1646
|
+
text_requested = download_format in {'text', 'both'}
|
|
1647
|
+
pdf_requested = download_format in {'pdf', 'both'}
|
|
1648
|
+
requested = set(sources)
|
|
1649
|
+
text_available = any(
|
|
1650
|
+
name in requested and _source_reachable(name, registry.TEXT, paper)
|
|
1651
|
+
for name in registry.names(registry.TEXT)
|
|
1652
|
+
)
|
|
1653
|
+
text_attempt_needed = (
|
|
1654
|
+
text_requested
|
|
1655
|
+
and text_available
|
|
1656
|
+
and (force or existing_assets['text'] is None)
|
|
1657
|
+
)
|
|
1658
|
+
pdf_attempt_needed = pdf_requested and (force or existing_assets['pdf'] is None)
|
|
1659
|
+
pdf_succeeded_from_oa = False
|
|
1660
|
+
|
|
1661
|
+
if download_abstract:
|
|
1662
|
+
existing_abstract = existing_assets['abstract']
|
|
1663
|
+
if existing_abstract is not None and not force:
|
|
1664
|
+
paper['abstract_source'] = existing_abstract.get('source') or paper.get('abstract_source')
|
|
1665
|
+
_set_status(paper, 'abstract_download_status', 'succeeded')
|
|
1666
|
+
summary['abstracts_skipped'] += 1
|
|
1667
|
+
else:
|
|
1668
|
+
abstract_filepath = os.path.join(download_dir, f'{filename}-abstract.txt')
|
|
1669
|
+
try:
|
|
1670
|
+
ok, source_or_error, abstract = _download_abstract(paper, sources)
|
|
1671
|
+
if not ok:
|
|
1672
|
+
_set_status(paper, 'abstract_download_status', 'failed', source_or_error)
|
|
1673
|
+
abstract = ''
|
|
1674
|
+
if abstract:
|
|
1675
|
+
with open(abstract_filepath, 'w', encoding='utf-8') as out_file:
|
|
1676
|
+
out_file.write(abstract)
|
|
1677
|
+
paper['abstract_source'] = source_or_error
|
|
1678
|
+
_set_status(paper, 'abstract_download_status', 'succeeded')
|
|
1679
|
+
_store_downloaded_asset(conn, paper, abstract_filepath, role='abstract', source=source_or_error)
|
|
1680
|
+
summary['abstracts'] += 1
|
|
1681
|
+
except Exception as e:
|
|
1682
|
+
_set_status(paper, 'abstract_download_status', 'failed', str(e))
|
|
1683
|
+
|
|
1684
|
+
if text_requested and existing_assets['text'] is not None and not force:
|
|
1685
|
+
paper['text_source'] = existing_assets['text'].get('source') or paper.get('text_source')
|
|
1686
|
+
_set_status(paper, 'text_download_status', 'succeeded')
|
|
1687
|
+
summary['texts_skipped'] += 1
|
|
1688
|
+
|
|
1689
|
+
if text_attempt_needed:
|
|
1690
|
+
text_filepath = os.path.join(download_dir, f'{filename}.txt')
|
|
1691
|
+
try:
|
|
1692
|
+
ok, text_source_or_error, _ = _download_text_from_sources(
|
|
1693
|
+
paper, text_filepath, sources)
|
|
1694
|
+
if ok:
|
|
1695
|
+
paper['text_path'] = ''
|
|
1696
|
+
paper['text_source'] = text_source_or_error
|
|
1697
|
+
_set_status(paper, 'text_download_status', 'succeeded')
|
|
1698
|
+
_store_downloaded_asset(conn, paper, text_filepath, role='text',
|
|
1699
|
+
source=text_source_or_error)
|
|
1700
|
+
summary['texts'] += 1
|
|
1701
|
+
else:
|
|
1702
|
+
_set_status(paper, 'text_download_status', 'failed', text_source_or_error)
|
|
1703
|
+
except Exception as e:
|
|
1704
|
+
_set_status(paper, 'text_download_status', 'failed', str(e))
|
|
1705
|
+
|
|
1706
|
+
if pdf_requested and existing_assets['pdf'] is not None and not force:
|
|
1707
|
+
paper['pdf_source'] = existing_assets['pdf'].get('source') or paper.get('pdf_source')
|
|
1708
|
+
_set_status(paper, 'pdf_download_status', 'succeeded')
|
|
1709
|
+
summary['pdfs_skipped'] += 1
|
|
1710
|
+
|
|
1711
|
+
if pdf_attempt_needed:
|
|
1712
|
+
pdf_filepath = os.path.join(download_dir, f'{filename}.pdf')
|
|
1713
|
+
try:
|
|
1714
|
+
ok, source_or_error, source_url = _download_pdf_from_sources(paper, pdf_filepath, sources)
|
|
1715
|
+
if ok:
|
|
1716
|
+
paper['pdf_path'] = ''
|
|
1717
|
+
paper['pdf_source'] = source_or_error
|
|
1718
|
+
if source_or_error in registry.open_access_names() and source_url:
|
|
1719
|
+
paper['pdf_url'] = source_url
|
|
1720
|
+
_set_status(paper, 'pdf_download_status', 'succeeded')
|
|
1721
|
+
_store_downloaded_asset(conn, paper, pdf_filepath, role='pdf', source=source_or_error)
|
|
1722
|
+
summary['pdfs'] += 1
|
|
1723
|
+
pdf_succeeded_from_oa = source_or_error in registry.open_access_names()
|
|
1724
|
+
else:
|
|
1725
|
+
_set_status(paper, 'pdf_download_status', 'failed', source_or_error)
|
|
1726
|
+
except Exception as e:
|
|
1727
|
+
_set_status(paper, 'pdf_download_status', 'failed', str(e))
|
|
1728
|
+
|
|
1729
|
+
if (
|
|
1730
|
+
pdf_succeeded_from_oa
|
|
1731
|
+
and download_format == 'pdf'
|
|
1732
|
+
and not text_attempt_needed
|
|
1733
|
+
and existing_assets['text'] is None
|
|
1734
|
+
and 'elsevier' in requested
|
|
1735
|
+
and _should_try_elsevier_text(paper)
|
|
1736
|
+
):
|
|
1737
|
+
text_filepath = os.path.join(download_dir, f'{filename}.txt')
|
|
1738
|
+
try:
|
|
1739
|
+
if os.path.isfile(text_filepath) or _download_text(paper, text_filepath):
|
|
1740
|
+
paper['text_path'] = ''
|
|
1741
|
+
paper['text_source'] = 'elsevier'
|
|
1742
|
+
_set_status(paper, 'text_download_status', 'succeeded')
|
|
1743
|
+
_store_downloaded_asset(conn, paper, text_filepath, role='text', source='elsevier')
|
|
1744
|
+
summary['texts'] += 1
|
|
1745
|
+
except Exception as e:
|
|
1746
|
+
_set_status(paper, 'text_download_status', 'failed', str(e))
|
|
1747
|
+
upsert_paper(conn, paper)
|
|
1748
|
+
return summary
|