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,471 @@
1
+ """Small request helpers for the OpenAlex API used by PaperMinerToolkit.
2
+
3
+ This module centralizes OpenAlex HTTP details and the mapping from OpenAlex
4
+ work records onto PaperMinerToolkit's paper schema so search and download code can
5
+ share one implementation. OpenAlex meters access against a daily credit budget;
6
+ requests without an API key still work but draw on a much smaller budget.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ from collections.abc import Mapping, Sequence
13
+ from typing import Any, TypeAlias
14
+ from urllib.parse import quote
15
+
16
+ from paperminertoolkit.providers import base as provider
17
+ from paperminertoolkit.corpus.metadata import clean_doi
18
+ from paperminertoolkit.settings import load_settings
19
+
20
+ BASE_URL = 'https://api.openalex.org'
21
+ WORKS_URL = f'{BASE_URL}/works'
22
+ RATE_LIMIT_URL = f'{BASE_URL}/rate-limit'
23
+ # OpenAlex documents ten requests a second; pacing at that rate keeps a long
24
+ # cursor walk inside the published limit instead of relying on it not noticing.
25
+ OPENALEX_MIN_INTERVAL = 0.1
26
+ MAX_FILTER_VALUES = 100
27
+ WORK_SELECT_FIELDS = (
28
+ 'id',
29
+ 'doi',
30
+ 'ids',
31
+ 'title',
32
+ 'display_name',
33
+ 'publication_date',
34
+ 'publication_year',
35
+ 'language',
36
+ 'type',
37
+ 'biblio',
38
+ 'primary_location',
39
+ 'best_oa_location',
40
+ 'open_access',
41
+ 'authorships',
42
+ 'is_authors_truncated',
43
+ 'cited_by_count',
44
+ 'referenced_works_count',
45
+ 'referenced_works',
46
+ 'is_retracted',
47
+ 'primary_topic',
48
+ 'topics',
49
+ 'keywords',
50
+ 'concepts',
51
+ 'sustainable_development_goals',
52
+ )
53
+ _OpenAlexRecord: TypeAlias = dict[str, Any]
54
+ LIMITER = provider.RateLimiter(OPENALEX_MIN_INTERVAL)
55
+
56
+
57
+ def configured_api_key(settings: Mapping[str, str] | None = None) -> str | None:
58
+ """Return the configured OpenAlex API key.
59
+
60
+ Parameters
61
+ ----------
62
+ settings : Mapping[str, str] or None, optional
63
+ Settings mapping to inspect before the environment.
64
+
65
+ Returns
66
+ -------
67
+ str or None
68
+ Configured API key, or ``None`` when no key is available.
69
+ """
70
+ settings = settings or load_settings()
71
+ return settings.get('openalex_api_key') or os.environ.get('OPENALEX_API_KEY')
72
+
73
+
74
+ def request_headers() -> dict[str, str]:
75
+ """Build OpenAlex request headers.
76
+
77
+ Returns
78
+ -------
79
+ dict[str, str]
80
+ Headers containing the PaperMinerToolkit user agent.
81
+ """
82
+ return provider.default_headers()
83
+
84
+
85
+ def request_params(
86
+ params: Mapping[str, object] | None = None,
87
+ api_key: str | None = None,
88
+ mailto: str = '',
89
+ ) -> dict[str, object]:
90
+ """Copy query parameters and add an API key and contact address.
91
+
92
+ Requests without a key are served from a much smaller daily credit budget,
93
+ so the key is attached whenever it is available but never invented. The
94
+ ``mailto`` address identifies the client; OpenAlex now meters access with
95
+ the daily credit budget rather than a polite pool, so only an API key
96
+ raises that budget.
97
+
98
+ Parameters
99
+ ----------
100
+ params : Mapping[str, object] or None, optional
101
+ Query parameters to copy.
102
+ api_key : str or None, optional
103
+ OpenAlex API key to add.
104
+ mailto : str, default=''
105
+ Contact email address to add when non-empty.
106
+
107
+ Returns
108
+ -------
109
+ dict[str, object]
110
+ Copied parameters, optionally including ``api_key`` and ``mailto``.
111
+ """
112
+ merged = dict(params or {})
113
+ if api_key:
114
+ merged['api_key'] = api_key
115
+ if mailto:
116
+ merged['mailto'] = mailto
117
+ return merged
118
+
119
+
120
+ def _budget_error(response: provider.ResponseLike) -> str:
121
+ """Describe an exhausted OpenAlex credit budget using the rate-limit headers.
122
+
123
+ Parameters
124
+ ----------
125
+ response : provider.ResponseLike
126
+ The rate-limited response, read for its reset header.
127
+
128
+ Returns
129
+ -------
130
+ str
131
+ Message naming the reset window when the header supplies one.
132
+ """
133
+ reset = response.headers.get('X-RateLimit-Reset')
134
+ try:
135
+ wait = f' Budget resets in {round(float(reset) / 3600, 1)} hours.' if reset else ''
136
+ except (TypeError, ValueError):
137
+ wait = ''
138
+ return ('OpenAlex daily credit budget is exhausted.'
139
+ f'{wait} Configure an API key with pmt config openalex-key or OPENALEX_API_KEY '
140
+ 'to raise the budget.')
141
+
142
+
143
+ def _terminal_error(response: provider.ResponseLike) -> str:
144
+ """Report the OpenAlex statuses that are pointless to retry.
145
+
146
+ A rejected key stays rejected, and a 429 here means the daily credit budget
147
+ is gone rather than that the client is going too fast, so neither is worth
148
+ another attempt. Every other client error takes the shared rule.
149
+
150
+ Parameters
151
+ ----------
152
+ response : provider.ResponseLike
153
+ Response to classify.
154
+
155
+ Returns
156
+ -------
157
+ str
158
+ Failure message, or an empty string to fall through to the shared rule.
159
+ """
160
+ if response.status_code == 401:
161
+ return ('OpenAlex rejected the API key. Set a valid key with pmt config openalex-key or '
162
+ 'OPENALEX_API_KEY, or unset it to use the smaller keyless budget.')
163
+ if response.status_code == 429:
164
+ return _budget_error(response)
165
+ return ''
166
+
167
+
168
+ def request_json(
169
+ url: str,
170
+ params: Mapping[str, object] | None = None,
171
+ api_key: str | None = None,
172
+ session: provider.HTTPClient | None = None,
173
+ timeout: float = 60,
174
+ attempts: int = 4,
175
+ mailto: str = '',
176
+ ) -> _OpenAlexRecord | None:
177
+ """Request an OpenAlex endpoint with bounded retry/backoff behavior.
178
+
179
+ Parameters
180
+ ----------
181
+ url : str
182
+ OpenAlex endpoint URL.
183
+ params : Mapping[str, object] or None, optional
184
+ Query parameters for the request.
185
+ api_key : str or None, optional
186
+ OpenAlex API key to attach.
187
+ session : provider.HTTPClient or None, optional
188
+ HTTP client exposing a ``get`` method. Defaults to :mod:`requests`.
189
+ timeout : int or float, default=60
190
+ Request timeout in seconds.
191
+ attempts : int, default=4
192
+ Maximum number of request attempts.
193
+ mailto : str, default=''
194
+ Contact email address sent with the request.
195
+
196
+ Returns
197
+ -------
198
+ _OpenAlexRecord or None
199
+ Decoded JSON payload, or ``None`` for a 404 response.
200
+
201
+ Raises
202
+ ------
203
+ RuntimeError
204
+ If the API key is rejected, the credit budget is exhausted, or all
205
+ request attempts fail.
206
+ """
207
+ return provider.request_mapping(url, label='OpenAlex', limiter=LIMITER,
208
+ params=request_params(params, api_key, mailto),
209
+ session=session, timeout=timeout, attempts=attempts,
210
+ client_error=_terminal_error)
211
+
212
+
213
+ def work_url(identifier: str) -> str:
214
+ """Build a single-work URL.
215
+
216
+ Parameters
217
+ ----------
218
+ identifier : str
219
+ OpenAlex W-identifier or ``doi:``-prefixed DOI.
220
+
221
+ Returns
222
+ -------
223
+ str
224
+ Encoded OpenAlex work URL.
225
+ """
226
+ return f'{WORKS_URL}/{quote(str(identifier), safe=":/")}'
227
+
228
+
229
+ def get_work(
230
+ identifier: str,
231
+ api_key: str | None = None,
232
+ session: provider.HTTPClient | None = None,
233
+ ) -> _OpenAlexRecord | None:
234
+ """Fetch one OpenAlex work record.
235
+
236
+ Parameters
237
+ ----------
238
+ identifier : str
239
+ OpenAlex W-identifier or ``doi:``-prefixed DOI.
240
+ api_key : str or None, optional
241
+ OpenAlex API key to attach.
242
+ session : provider.HTTPClient or None, optional
243
+ HTTP client exposing a ``get`` method.
244
+
245
+ Returns
246
+ -------
247
+ _OpenAlexRecord or None
248
+ Work record, or ``None`` when the work does not exist.
249
+
250
+ Raises
251
+ ------
252
+ RuntimeError
253
+ If the OpenAlex request cannot be completed.
254
+ """
255
+ return request_json(work_url(identifier), api_key=api_key, session=session)
256
+
257
+
258
+ def work_id(work: Mapping[str, Any]) -> str:
259
+ """Extract the short W-identifier from an OpenAlex work record.
260
+
261
+ Parameters
262
+ ----------
263
+ work : Mapping[str, Any]
264
+ OpenAlex work record.
265
+
266
+ Returns
267
+ -------
268
+ str
269
+ Short W-identifier, or an empty string when unavailable.
270
+ """
271
+ identifier = str(work.get('id') or '')
272
+ return identifier.rstrip('/').rsplit('/', 1)[-1] if identifier else ''
273
+
274
+
275
+ def reconstruct_abstract(inverted_index: Mapping[str, list[int]] | None) -> str:
276
+ """Rebuild abstract text from an OpenAlex inverted index.
277
+
278
+ Parameters
279
+ ----------
280
+ inverted_index : Mapping[str, list[int]] or None
281
+ Mapping of tokens to their positions in the abstract.
282
+
283
+ Returns
284
+ -------
285
+ str
286
+ Reconstructed abstract, or an empty string for a missing index.
287
+ """
288
+ if not isinstance(inverted_index, dict) or not inverted_index:
289
+ return ''
290
+ positions = [(position, token)
291
+ for token, indexes in inverted_index.items()
292
+ for position in indexes or []]
293
+ return ' '.join(token for _, token in sorted(positions))
294
+
295
+
296
+ def works_page(filter_value: str,
297
+ filter_name: str = 'doi',
298
+ select: Sequence[str] | None = WORK_SELECT_FIELDS,
299
+ per_page: int = MAX_FILTER_VALUES,
300
+ api_key: str | None = None,
301
+ session: provider.HTTPClient | None = None,
302
+ mailto: str = '') -> list[_OpenAlexRecord]:
303
+ """Request one OR-filtered page of OpenAlex works.
304
+
305
+ ``per_page`` must cover the number of OR-joined filter values, because the
306
+ endpoint otherwise returns only its default page size and silently drops
307
+ the remaining matches.
308
+
309
+ Parameters
310
+ ----------
311
+ filter_value : str
312
+ OR-joined filter values, already normalized.
313
+ filter_name : str, default='doi'
314
+ Filter key applied to the values, normally ``doi`` or ``ids.openalex``.
315
+ select : Sequence[str] or None, optional
316
+ Root-level fields to request. OpenAlex rejects dotted field paths.
317
+ per_page : int, default=100
318
+ Page size requested from OpenAlex.
319
+ api_key : str or None, optional
320
+ OpenAlex API key to attach.
321
+ session : provider.HTTPClient or None, optional
322
+ HTTP client exposing a ``get`` method.
323
+ mailto : str, default=''
324
+ Contact email address sent with the request.
325
+
326
+ Returns
327
+ -------
328
+ list[_OpenAlexRecord]
329
+ Work records returned for the filter, in OpenAlex's own order.
330
+
331
+ Raises
332
+ ------
333
+ RuntimeError
334
+ If the OpenAlex request cannot be completed.
335
+ """
336
+ params: dict[str, object] = {
337
+ 'filter': f'{filter_name}:{filter_value}',
338
+ 'per-page': max(1, min(int(per_page), MAX_FILTER_VALUES)),
339
+ }
340
+ if select:
341
+ params['select'] = ','.join(select)
342
+ payload = request_json(WORKS_URL, params=params, api_key=api_key,
343
+ session=session, mailto=mailto) or {}
344
+ return list(payload.get('results') or [])
345
+
346
+
347
+ def works_batch(identifiers: Sequence[str],
348
+ filter_name: str = 'doi',
349
+ select: Sequence[str] | None = WORK_SELECT_FIELDS,
350
+ api_key: str | None = None,
351
+ session: provider.HTTPClient | None = None,
352
+ batch_size: int = MAX_FILTER_VALUES,
353
+ mailto: str = '') -> dict[str, _OpenAlexRecord]:
354
+ """Look up many OpenAlex works and key the results by their identifier.
355
+
356
+ OpenAlex accepts at most 100 OR-joined values per filter, returns matches
357
+ in an arbitrary order, and omits identifiers it does not know, so results
358
+ are keyed rather than zipped back onto the request order.
359
+
360
+ Parameters
361
+ ----------
362
+ identifiers : Sequence[str]
363
+ Bare lowercase DOIs, or short ``W`` identifiers for ``ids.openalex``.
364
+ filter_name : str, default='doi'
365
+ Filter key applied to the identifiers.
366
+ select : Sequence[str] or None, optional
367
+ Root-level fields to request.
368
+ api_key : str or None, optional
369
+ OpenAlex API key to attach.
370
+ session : provider.HTTPClient or None, optional
371
+ HTTP client exposing a ``get`` method.
372
+ batch_size : int, default=100
373
+ Identifiers requested per page, capped at the OpenAlex maximum.
374
+ mailto : str, default=''
375
+ Contact email address sent with the request.
376
+
377
+ Returns
378
+ -------
379
+ dict[str, _OpenAlexRecord]
380
+ Work records keyed by cleaned DOI or short identifier.
381
+
382
+ Raises
383
+ ------
384
+ ValueError
385
+ If ``batch_size`` is not a positive integer.
386
+ RuntimeError
387
+ If an OpenAlex request cannot be completed.
388
+ """
389
+ if batch_size < 1:
390
+ raise ValueError('batch_size must be a positive integer.')
391
+ wanted = list(dict.fromkeys(identifier for identifier in identifiers if identifier))
392
+ batch_size = min(batch_size, MAX_FILTER_VALUES)
393
+ works = {}
394
+ for chunk in provider.chunked(wanted, batch_size):
395
+ results = works_page('|'.join(chunk),
396
+ filter_name=filter_name,
397
+ select=select,
398
+ per_page=len(chunk),
399
+ api_key=api_key,
400
+ session=session,
401
+ mailto=mailto)
402
+ for work in results:
403
+ key = clean_doi(work.get('doi')) if filter_name == 'doi' else work_id(work)
404
+ if key:
405
+ works[key] = work
406
+ return works
407
+
408
+
409
+ def work_to_paper(work: Mapping[str, Any]) -> dict[str, Any]:
410
+ """Map an OpenAlex work onto PaperMinerToolkit's paper schema.
411
+
412
+ Parameters
413
+ ----------
414
+ work : Mapping[str, Any]
415
+ OpenAlex work record.
416
+
417
+ Returns
418
+ -------
419
+ dict[str, Any]
420
+ Normalized paper metadata plus the ``abstract`` extra that the corpus
421
+ schema does not store directly. The abstract is empty unless the work
422
+ was fetched with ``abstract_inverted_index``, which
423
+ :data:`WORK_SELECT_FIELDS` deliberately omits.
424
+ """
425
+ doi = clean_doi(work.get('doi')) if work.get('doi') else ''
426
+ identifier = work_id(work)
427
+ if doi:
428
+ paper_id = f'doi:{doi}'
429
+ elif identifier:
430
+ paper_id = f'openalex:{identifier}'
431
+ else:
432
+ paper_id = ''
433
+ authors = '; '.join(
434
+ author for author in (
435
+ ((authorship or {}).get('author') or {}).get('display_name')
436
+ for authorship in work.get('authorships') or []
437
+ ) if author
438
+ )
439
+ journal = ((work.get('primary_location') or {}).get('source') or {}).get('display_name')
440
+ return {
441
+ 'paper_id': paper_id,
442
+ 'doi': doi,
443
+ 'title': work.get('title') or work.get('display_name') or '',
444
+ 'journal': journal or '',
445
+ 'publication_date': work.get('publication_date') or str(work.get('publication_year') or ''),
446
+ 'authors': authors,
447
+ 'sources': 'openalex',
448
+ 'pdf_url': (work.get('best_oa_location') or {}).get('pdf_url') or '',
449
+ 'metadata_status': 'retrieved',
450
+ 'abstract': reconstruct_abstract(work.get('abstract_inverted_index')),
451
+ }
452
+
453
+
454
+ def pdf_candidates(work: Mapping[str, Any]) -> list[str]:
455
+ """Return candidate PDF URLs for an OpenAlex work.
456
+
457
+ Parameters
458
+ ----------
459
+ work : Mapping[str, Any]
460
+ OpenAlex work record.
461
+
462
+ Returns
463
+ -------
464
+ list[str]
465
+ Deduplicated PDF candidates, most authoritative first.
466
+ """
467
+ candidates = [(work.get('best_oa_location') or {}).get('pdf_url')]
468
+ for location in work.get('locations') or []:
469
+ candidates.append((location or {}).get('pdf_url'))
470
+ candidates.append((work.get('open_access') or {}).get('oa_url'))
471
+ return list(dict.fromkeys(url for url in candidates if url))