paperminertoolkit 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. paperminertoolkit/__init__.py +10 -0
  2. paperminertoolkit/_version.py +11 -0
  3. paperminertoolkit/cli.py +1053 -0
  4. paperminertoolkit/corpus/__init__.py +1 -0
  5. paperminertoolkit/corpus/database.py +1542 -0
  6. paperminertoolkit/corpus/documents.py +313 -0
  7. paperminertoolkit/corpus/filtering.py +1390 -0
  8. paperminertoolkit/corpus/metadata.py +532 -0
  9. paperminertoolkit/extraction/__init__.py +1 -0
  10. paperminertoolkit/extraction/compression.py +486 -0
  11. paperminertoolkit/extraction/extract.py +573 -0
  12. paperminertoolkit/extraction/models.py +784 -0
  13. paperminertoolkit/extraction/recipes.py +241 -0
  14. paperminertoolkit/extraction/scrape.py +737 -0
  15. paperminertoolkit/extraction/store.py +244 -0
  16. paperminertoolkit/extraction/tokenizer.py +313 -0
  17. paperminertoolkit/providers/__init__.py +1 -0
  18. paperminertoolkit/providers/arxiv.py +760 -0
  19. paperminertoolkit/providers/base.py +514 -0
  20. paperminertoolkit/providers/biorxiv.py +561 -0
  21. paperminertoolkit/providers/chemrxiv.py +1115 -0
  22. paperminertoolkit/providers/core.py +423 -0
  23. paperminertoolkit/providers/crossref.py +649 -0
  24. paperminertoolkit/providers/elsevier.py +455 -0
  25. paperminertoolkit/providers/medrxiv.py +548 -0
  26. paperminertoolkit/providers/openalex.py +471 -0
  27. paperminertoolkit/providers/pubmed.py +1272 -0
  28. paperminertoolkit/providers/registry.py +521 -0
  29. paperminertoolkit/providers/rxiv.py +936 -0
  30. paperminertoolkit/providers/unpaywall.py +162 -0
  31. paperminertoolkit/resources/recipes.json +1670 -0
  32. paperminertoolkit/settings.py +661 -0
  33. paperminertoolkit/workflows/__init__.py +1 -0
  34. paperminertoolkit/workflows/download.py +1748 -0
  35. paperminertoolkit/workflows/enrichment.py +1906 -0
  36. paperminertoolkit/workflows/imports.py +121 -0
  37. paperminertoolkit/workflows/search.py +877 -0
  38. paperminertoolkit/workflows/topics.py +2837 -0
  39. paperminertoolkit/workflows/utilities.py +73 -0
  40. paperminertoolkit-1.0.0.dist-info/METADATA +126 -0
  41. paperminertoolkit-1.0.0.dist-info/RECORD +45 -0
  42. paperminertoolkit-1.0.0.dist-info/WHEEL +5 -0
  43. paperminertoolkit-1.0.0.dist-info/entry_points.txt +2 -0
  44. paperminertoolkit-1.0.0.dist-info/licenses/LICENSE +21 -0
  45. paperminertoolkit-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,455 @@
1
+ """Small request helpers for the Elsevier APIs used by PaperMinerToolkit.
2
+
3
+ This module centralizes Elsevier HTTP details so the rest of the package does
4
+ not depend on the unsupported ``elsapy`` wrapper, and maps Elsevier search
5
+ records onto PaperMinerToolkit's paper schema.
6
+
7
+ A key is required, and it travels in the ``X-ELS-APIKey`` header rather than as
8
+ a query parameter -- the only header-authenticated source here apart from CORE.
9
+ Entitlement is tied to the subscribing institution, so what a key can retrieve
10
+ depends on where the request comes from as much as on the key itself: a search
11
+ may return a record whose full text the same key cannot fetch.
12
+
13
+ Elsevier pages a search by handing back a link rather than by an offset the
14
+ caller computes, which is why :func:`next_page_url` exists and why there is no
15
+ cursor helper.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ from collections.abc import Mapping, Sequence
22
+ from typing import Any
23
+ from urllib.parse import quote_plus
24
+
25
+ import requests
26
+
27
+ from paperminertoolkit.providers import base as provider
28
+ from paperminertoolkit.corpus.metadata import clean_doi
29
+
30
+ BASE_URL = 'https://api.elsevier.com/content'
31
+ ELSEVIER_MIN_INTERVAL = 0.2
32
+ LIMITER = provider.RateLimiter(ELSEVIER_MIN_INTERVAL)
33
+
34
+
35
+ def api_headers(api_key: str, accept: str = 'application/json') -> dict[str, str]:
36
+ """Build standard Elsevier API headers.
37
+
38
+ Parameters
39
+ ----------
40
+ api_key : str
41
+ Configured Elsevier API key.
42
+ accept : str, default='application/json'
43
+ Media type requested from Elsevier.
44
+
45
+ Returns
46
+ -------
47
+ dict[str, str]
48
+ Headers containing the API key, media type, and user agent.
49
+ """
50
+ return {
51
+ 'X-ELS-APIKey': api_key,
52
+ 'Accept': accept,
53
+ 'User-Agent': provider.USER_AGENT,
54
+ }
55
+
56
+
57
+ def get_json(
58
+ api_key: str,
59
+ url: str,
60
+ params: Mapping[str, object] | None = None,
61
+ timeout: float = provider.DEFAULT_TIMEOUT,
62
+ ) -> dict[str, Any]:
63
+ """Request and decode an Elsevier JSON endpoint.
64
+
65
+ Parameters
66
+ ----------
67
+ api_key : str
68
+ Configured Elsevier API key.
69
+ url : str
70
+ Endpoint URL to request.
71
+ params : Mapping[str, object] or None, optional
72
+ Query parameters for the request.
73
+ timeout : float, default=60.0
74
+ Request timeout in seconds.
75
+
76
+ Returns
77
+ -------
78
+ dict[str, Any]
79
+ Decoded JSON response body.
80
+
81
+ Raises
82
+ ------
83
+ requests.RequestException
84
+ If the request fails or the response has an error status.
85
+ """
86
+ response = requests.get(url, headers=api_headers(api_key), params=params or {}, timeout=timeout)
87
+ response.raise_for_status()
88
+ return response.json()
89
+
90
+
91
+ def get_content(api_key: str,
92
+ url: str,
93
+ accept: str,
94
+ params: Mapping[str, object] | None = None,
95
+ timeout: float = provider.DEFAULT_TIMEOUT) -> requests.Response:
96
+ """Request raw content from an Elsevier endpoint.
97
+
98
+ Parameters
99
+ ----------
100
+ api_key : str
101
+ Configured Elsevier API key.
102
+ url : str
103
+ Endpoint URL to request.
104
+ accept : str
105
+ Media type requested from Elsevier.
106
+ params : dict or None, optional
107
+ Query parameters for the request.
108
+ timeout : float, default=60.0
109
+ Request timeout in seconds.
110
+
111
+ Returns
112
+ -------
113
+ requests.Response
114
+ Status-validated raw response.
115
+
116
+ Raises
117
+ ------
118
+ requests.RequestException
119
+ If the request fails or the response has an error status.
120
+ """
121
+ response = requests.get(url, headers=api_headers(api_key, accept=accept), params=params or {}, timeout=timeout)
122
+ response.raise_for_status()
123
+ return response
124
+
125
+
126
+ def search_url(index: str, query: str, count: int, search_fields: str) -> str:
127
+ """Build an Elsevier search URL.
128
+
129
+ Parameters
130
+ ----------
131
+ index : str
132
+ Elsevier index to search, such as ``scopus``.
133
+ query : str
134
+ Search expression.
135
+ count : int
136
+ Number of records requested per page.
137
+ search_fields : str
138
+ Elsevier field expression that wraps ``query``.
139
+
140
+ Returns
141
+ -------
142
+ str
143
+ Encoded Elsevier search URL.
144
+ """
145
+ index = index.lower()
146
+ provider_query = f'{search_fields}({query})'
147
+ url = f'{BASE_URL}/search/{index}?query={quote_plus(provider_query)}&count={count}'
148
+ if index == 'scopus':
149
+ url += '&cursor=*'
150
+ return url
151
+
152
+
153
+ def article_url_from_doi(doi: str) -> str:
154
+ """Build an Elsevier article retrieval URL.
155
+
156
+ Parameters
157
+ ----------
158
+ doi : str
159
+ DOI identifying the article.
160
+
161
+ Returns
162
+ -------
163
+ str
164
+ Encoded Elsevier article URL.
165
+ """
166
+ return f'{BASE_URL}/article/doi/{quote_plus(str(doi))}'
167
+
168
+ def configured_api_key(settings: Mapping[str, str] | None = None) -> str:
169
+ """Return the configured Elsevier API key.
170
+
171
+ Parameters
172
+ ----------
173
+ settings : Mapping[str, str] or None, optional
174
+ Loaded PaperMinerToolkit settings. Read from disk when omitted.
175
+
176
+ Returns
177
+ -------
178
+ str
179
+ API key.
180
+
181
+ Raises
182
+ ------
183
+ ValueError
184
+ If no key is configured.
185
+ """
186
+ from paperminertoolkit.settings import load_settings
187
+ settings = settings if settings is not None else load_settings()
188
+ api_key = settings.get('elsevier_api_key') or os.environ.get('ELSEVIER_API_KEY')
189
+ if not api_key:
190
+ raise ValueError('Elsevier API key is not configured. Run pmt config elsevier-key first.')
191
+ return str(api_key)
192
+
193
+
194
+ def request(url: str,
195
+ api_key: str,
196
+ accept: str = 'application/json',
197
+ params: Mapping[str, object] | None = None,
198
+ session: provider.HTTPClient | None = None,
199
+ timeout: float = provider.DEFAULT_TIMEOUT,
200
+ attempts: int = provider.DEFAULT_ATTEMPTS) -> provider.ResponseLike | None:
201
+ """Request an Elsevier endpoint with courtesy pacing and bounded retries.
202
+
203
+ Parameters
204
+ ----------
205
+ url : str
206
+ Endpoint URL to request.
207
+ api_key : str
208
+ Configured Elsevier API key.
209
+ accept : str, default='application/json'
210
+ Media type requested from Elsevier.
211
+ params : Mapping[str, object] or None, optional
212
+ Query parameters for the request.
213
+ session : provider.HTTPClient or None, optional
214
+ HTTP client exposing a ``get`` method. Defaults to :mod:`requests`.
215
+ timeout : float, default=60.0
216
+ Request timeout in seconds.
217
+ attempts : int, default=4
218
+ Maximum number of request attempts.
219
+
220
+ Returns
221
+ -------
222
+ provider.ResponseLike or None
223
+ Successful response, or ``None`` for a 404 response.
224
+
225
+ Raises
226
+ ------
227
+ RuntimeError
228
+ If the request is rejected, or all request attempts fail.
229
+ """
230
+ return provider.request(url, label='Elsevier', limiter=LIMITER, params=params,
231
+ headers=api_headers(api_key, accept=accept), session=session,
232
+ timeout=timeout, attempts=attempts)
233
+
234
+
235
+ def request_json(url: str,
236
+ api_key: str,
237
+ params: Mapping[str, object] | None = None,
238
+ session: provider.HTTPClient | None = None,
239
+ timeout: float = provider.DEFAULT_TIMEOUT,
240
+ attempts: int = provider.DEFAULT_ATTEMPTS) -> dict[str, Any] | None:
241
+ """Request an Elsevier endpoint and decode its JSON payload.
242
+
243
+ Parameters
244
+ ----------
245
+ url : str
246
+ Endpoint URL to request.
247
+ api_key : str
248
+ Configured Elsevier API key.
249
+ params : Mapping[str, object] or None, optional
250
+ Query parameters for the request.
251
+ session : provider.HTTPClient or None, optional
252
+ HTTP client exposing a ``get`` method.
253
+ timeout : float, default=60.0
254
+ Request timeout in seconds.
255
+ attempts : int, default=4
256
+ Maximum number of request attempts.
257
+
258
+ Returns
259
+ -------
260
+ dict[str, Any] or None
261
+ Decoded payload, or ``None`` for a 404 response.
262
+
263
+ Raises
264
+ ------
265
+ RuntimeError
266
+ If the request is rejected, or the body is not a JSON object.
267
+ """
268
+ return provider.request_mapping(url, label='Elsevier', limiter=LIMITER, params=params,
269
+ headers=api_headers(api_key), session=session,
270
+ timeout=timeout, attempts=attempts)
271
+
272
+
273
+ def next_page_url(payload: Mapping[str, Any] | None) -> str:
274
+ """Return the next-page link an Elsevier search payload carries.
275
+
276
+ Elsevier pages by handing back a link rather than by an offset the caller
277
+ computes, so a walk follows this rather than incrementing anything.
278
+
279
+ Parameters
280
+ ----------
281
+ payload : Mapping[str, Any] or None
282
+ Decoded Elsevier search payload.
283
+
284
+ Returns
285
+ -------
286
+ str
287
+ Next-page URL, or an empty string when this is the last page.
288
+ """
289
+ results = (payload or {}).get('search-results') or {}
290
+ for link in results.get('link') or []:
291
+ if isinstance(link, Mapping) and link.get('@ref') == 'next':
292
+ return str(link.get('@href') or '')
293
+ return ''
294
+
295
+
296
+ def total_results(payload: Mapping[str, Any] | None) -> int:
297
+ """Read the total hit count an Elsevier search payload reports.
298
+
299
+ Parameters
300
+ ----------
301
+ payload : Mapping[str, Any] or None
302
+ Decoded Elsevier search payload.
303
+
304
+ Returns
305
+ -------
306
+ int
307
+ Total matching records, or ``0`` when the payload reports none.
308
+ """
309
+ results = (payload or {}).get('search-results') or {}
310
+ try:
311
+ return max(int(results.get('opensearch:totalResults')), 0)
312
+ except (TypeError, ValueError):
313
+ return 0
314
+
315
+
316
+ def parse_records(payload: Mapping[str, Any] | None) -> list[dict[str, Any]]:
317
+ """Return the entries an Elsevier search payload carries.
318
+
319
+ Parameters
320
+ ----------
321
+ payload : Mapping[str, Any] or None
322
+ Decoded Elsevier search payload.
323
+
324
+ Returns
325
+ -------
326
+ list[dict[str, Any]]
327
+ Search entries in payload order.
328
+ """
329
+ results = (payload or {}).get('search-results') or {}
330
+ entries = results.get('entry') or []
331
+ return [dict(entry) for entry in entries if isinstance(entry, Mapping)]
332
+
333
+
334
+ def full_text_uri(record: Mapping[str, Any]) -> str:
335
+ """Return the article endpoint a search record advertises full text at.
336
+
337
+ Parameters
338
+ ----------
339
+ record : Mapping[str, Any]
340
+ Elsevier search record or corpus paper row.
341
+
342
+ Returns
343
+ -------
344
+ str
345
+ Article retrieval URL, or an empty string when the record names none.
346
+ """
347
+ for value in _link_values(record.get('link') or record.get('elsevier_link')):
348
+ text = str(value or '')
349
+ if text.startswith(f'{BASE_URL}/article/'):
350
+ return text
351
+ return ''
352
+
353
+
354
+ def _link_values(link: object) -> list[Any]:
355
+ """Flatten the several shapes Elsevier uses for a link field.
356
+
357
+ Parameters
358
+ ----------
359
+ link : object
360
+ Raw link value: a string, a mapping, or a list of either.
361
+
362
+ Returns
363
+ -------
364
+ list[Any]
365
+ Candidate link values.
366
+ """
367
+ if link is None:
368
+ return []
369
+ if isinstance(link, str):
370
+ return [link]
371
+ if isinstance(link, Mapping):
372
+ return [link.get('@href') or link.get('href')]
373
+ if isinstance(link, Sequence):
374
+ values = []
375
+ for entry in link:
376
+ values.extend(_link_values(entry))
377
+ return values
378
+ return []
379
+
380
+
381
+ def record_to_paper(record: Mapping[str, Any]) -> dict[str, Any]:
382
+ """Map one Elsevier search record onto PaperMinerToolkit's paper schema.
383
+
384
+ Parameters
385
+ ----------
386
+ record : Mapping[str, Any]
387
+ Elsevier search record.
388
+
389
+ Returns
390
+ -------
391
+ dict[str, Any]
392
+ Normalized paper metadata plus the ``abstract`` extra that the corpus
393
+ schema does not store directly.
394
+ """
395
+ return {
396
+ 'paper_id': str(record.get('dc:identifier') or record.get('eid') or ''),
397
+ 'doi': clean_doi(record.get('prism:doi')),
398
+ 'title': provider.clean_text(record.get('dc:title')),
399
+ 'journal': provider.clean_text(record.get('prism:publicationName')),
400
+ 'publication_date': provider.clean_text(record.get('prism:coverDate')),
401
+ 'authors': provider.clean_text(record.get('dc:creator') or record.get('creator')),
402
+ 'sources': 'elsevier',
403
+ 'elsevier_link': full_text_uri(record),
404
+ 'metadata_status': 'retrieved',
405
+ 'abstract': provider.clean_text(record.get('dc:description')
406
+ or record.get('prism:teaser')),
407
+ }
408
+
409
+
410
+ def check_api_key(api_key: str, session: provider.HTTPClient | None = None) -> bool:
411
+ """Validate an Elsevier API key with a minimal Scopus search.
412
+
413
+ This lives here rather than in :mod:`paperminertoolkit.settings` so that settings
414
+ need not import a source module: every other source module imports settings,
415
+ and the one edge in the other direction was the reason this one could not.
416
+
417
+ Parameters
418
+ ----------
419
+ api_key : str
420
+ Elsevier API key to validate.
421
+ session : provider.HTTPClient or None, optional
422
+ HTTP client exposing a ``get`` method.
423
+
424
+ Returns
425
+ -------
426
+ bool
427
+ Whether Elsevier accepted the key.
428
+ """
429
+ try:
430
+ request_json(search_url('scopus', 'Test', 1, 'TITLE-ABS-KEY'), api_key, session=session)
431
+ except (RuntimeError, requests.RequestException):
432
+ return False
433
+ return True
434
+
435
+
436
+ def full_text(payload: Mapping[str, Any] | None) -> str:
437
+ """Read the original text out of an Elsevier full-text payload.
438
+
439
+ Parameters
440
+ ----------
441
+ payload : Mapping[str, Any] or None
442
+ Decoded article-retrieval payload.
443
+
444
+ Returns
445
+ -------
446
+ str
447
+ Article text, or an empty string when the payload carries none or
448
+ carries it as structured XML rather than as text.
449
+ """
450
+ if not payload:
451
+ return ''
452
+ text = payload.get('originalText')
453
+ if text is None:
454
+ text = (payload.get('full-text-retrieval-response') or {}).get('originalText')
455
+ return text if isinstance(text, str) else ''