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,548 @@
1
+ """Request helpers for the medRxiv API used by PaperMinerToolkit.
2
+
3
+ This module gives medRxiv its own names and constants over the shared
4
+ bioRxiv-family client in :mod:`paperminertoolkit.providers.rxiv`, which documents the paging,
5
+ error, and versioning rules the two archives have in common. What follows is
6
+ what is particular to medRxiv.
7
+
8
+ The service needs neither an API key nor a contact address, so there is nothing
9
+ to configure before using it. It publishes no rate limit either, so requests
10
+ are paced through one module-level limiter at a rate chosen to be unobtrusive
11
+ rather than to satisfy a documented rule.
12
+
13
+ medRxiv opened in June 2019, so an unscoped walk reaches back only that
14
+ far -- shorter than bioRxiv's, and correspondingly cheaper.
15
+
16
+ medRxiv DOIs carry the ``10.1101`` prefix up to late 2025 and ``10.64898``
17
+ afterwards. Both prefixes are shared with bioRxiv, so a prefix says nothing
18
+ about which archive holds a preprint; what separates them is the accession
19
+ number, which runs eight digits here -- a two-digit year in front of a
20
+ six-digit counter -- against bioRxiv's six. Identifiers are therefore
21
+ recognized by the shape of the DOI suffix rather than by a prefix list, so a
22
+ further prefix change does not strand the older content or need a code change
23
+ to accept the newer, and a bioRxiv DOI is not mistaken for one this API can
24
+ answer.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import re
30
+ from collections.abc import Iterator, Mapping, Sequence
31
+ from typing import Any, TypeAlias
32
+
33
+ from paperminertoolkit.providers import base as provider, rxiv as _rxiv
34
+
35
+ BASE_URL = _rxiv.BASE_URL
36
+ CATEGORY_BASE_URL = _rxiv.CATEGORY_BASE_URL
37
+ WEB_URL = 'https://www.medrxiv.org'
38
+ SERVER = 'medrxiv'
39
+ PAGE_SIZE = _rxiv.PAGE_SIZE
40
+ CATEGORY_PAGE_SIZE = _rxiv.CATEGORY_PAGE_SIZE
41
+ CORPUS_START = '2019-06-01'
42
+ MEDRXIV_MIN_INTERVAL = _rxiv.RXIV_MIN_INTERVAL
43
+ MAX_SCAN_RECORDS = _rxiv.MAX_SCAN_RECORDS
44
+ QUERY_PREFIXES = _rxiv.QUERY_PREFIXES
45
+ OK_STATUS = _rxiv.OK_STATUS
46
+ EMPTY_STATUSES = _rxiv.EMPTY_STATUSES
47
+ # A medRxiv accession number is eight digits, against bioRxiv's six, which is
48
+ # the only part of the DOI that tells the two archives apart. The upper bound
49
+ # leaves room for a ninth digit without reaching down to bioRxiv's width, and
50
+ # the trailing lookahead stops a shorter run from matching inside a longer one.
51
+ _MEDRXIV_DOI = re.compile(
52
+ r'(?P<doi>10\.\d{4,9}/\d{4}\.\d{2}\.\d{2}\.\d{8,9}(?!\d))(?:v(?P<version>\d+))?',
53
+ re.IGNORECASE,
54
+ )
55
+ _MedrxivRecord: TypeAlias = dict[str, Any]
56
+ LIMITER = provider.RateLimiter(MEDRXIV_MIN_INTERVAL)
57
+ SERVER_CONFIG = _rxiv.RxivServer(
58
+ name=SERVER,
59
+ label='medRxiv',
60
+ web_url=WEB_URL,
61
+ web_host='medrxiv.org',
62
+ corpus_start=CORPUS_START,
63
+ doi_pattern=_MEDRXIV_DOI,
64
+ limiter=LIMITER,
65
+ max_scan_records=MAX_SCAN_RECORDS,
66
+ )
67
+
68
+
69
+ def request_headers() -> dict[str, str]:
70
+ """Build medRxiv request headers.
71
+
72
+ Returns
73
+ -------
74
+ dict[str, str]
75
+ Headers containing the PaperMinerToolkit user agent.
76
+ """
77
+ return provider.default_headers()
78
+
79
+
80
+ def details_url(doi: str, version: str = 'na') -> str:
81
+ """Build the URL for a medRxiv details request.
82
+
83
+ Parameters
84
+ ----------
85
+ doi : str
86
+ Bare medRxiv DOI.
87
+ version : str, default='na'
88
+ Posted version to request, or ``'na'`` for every version.
89
+
90
+ Returns
91
+ -------
92
+ str
93
+ Details endpoint URL.
94
+ """
95
+ return _rxiv.details_url(SERVER_CONFIG, doi, version)
96
+
97
+
98
+ def endpoint(category: str = '') -> tuple[str, int]:
99
+ """Choose the interval host for a scan and report its page length.
100
+
101
+ See :func:`paperminertoolkit.providers.rxiv.endpoint` for why the two hosts differ and
102
+ which is cheaper for which scan.
103
+
104
+ Parameters
105
+ ----------
106
+ category : str, default=''
107
+ medRxiv subject category the scan is restricted to, if any.
108
+
109
+ Returns
110
+ -------
111
+ tuple[str, int]
112
+ Base URL to walk, and the number of records that host returns per page.
113
+ """
114
+ return _rxiv.endpoint(category)
115
+
116
+
117
+ def page_size(payload: Mapping[str, Any] | None, default: int = PAGE_SIZE) -> int:
118
+ """Read how many records a medRxiv payload actually returned.
119
+
120
+ Parameters
121
+ ----------
122
+ payload : Mapping[str, Any] or None
123
+ Parsed medRxiv payload.
124
+ default : int, default=PAGE_SIZE
125
+ Page length assumed when the payload reports none.
126
+
127
+ Returns
128
+ -------
129
+ int
130
+ Records on this page, or ``default`` when the payload reports none.
131
+ """
132
+ return _rxiv.page_size(payload, default)
133
+
134
+
135
+ def interval_url(start_date: str, end_date: str, cursor: int = 0, category: str = '') -> str:
136
+ """Build the URL for one page of a medRxiv date interval.
137
+
138
+ Parameters
139
+ ----------
140
+ start_date : str
141
+ Inclusive interval start as ``YYYY-MM-DD``.
142
+ end_date : str
143
+ Inclusive interval end as ``YYYY-MM-DD``.
144
+ cursor : int, default=0
145
+ Zero-based index of the first record requested.
146
+ category : str, default=''
147
+ medRxiv subject category the scan is restricted to, if any.
148
+
149
+ Returns
150
+ -------
151
+ str
152
+ Interval endpoint URL.
153
+
154
+ Raises
155
+ ------
156
+ ValueError
157
+ If either bound is not an ISO ``YYYY-MM-DD`` date.
158
+ """
159
+ return _rxiv.interval_url(SERVER_CONFIG, start_date, end_date, cursor, category)
160
+
161
+
162
+ def pdf_url(doi: str, version: str = '') -> str:
163
+ """Build the public PDF location for a medRxiv preprint.
164
+
165
+ Parameters
166
+ ----------
167
+ doi : str
168
+ medRxiv DOI, with or without a version suffix.
169
+ version : str, default=''
170
+ Posted version number. Defaults to the version carried by ``doi``, and
171
+ then to the first version.
172
+
173
+ Returns
174
+ -------
175
+ str
176
+ PDF URL, or an empty string when no DOI is present.
177
+ """
178
+ return _rxiv.pdf_url(SERVER_CONFIG, doi, version)
179
+
180
+
181
+ def request(
182
+ url: str,
183
+ params: Mapping[str, object] | None = None,
184
+ session: provider.HTTPClient | None = None,
185
+ timeout: float = provider.DEFAULT_TIMEOUT,
186
+ attempts: int = provider.DEFAULT_ATTEMPTS,
187
+ ) -> provider.ResponseLike | None:
188
+ """Request a medRxiv endpoint with courtesy pacing and bounded retries.
189
+
190
+ Parameters
191
+ ----------
192
+ url : str
193
+ medRxiv endpoint URL.
194
+ params : Mapping[str, object] or None, optional
195
+ Query parameters for the request.
196
+ session : provider.HTTPClient or None, optional
197
+ HTTP client exposing a ``get`` method. Defaults to :mod:`requests`.
198
+ timeout : float, default=60.0
199
+ Request timeout in seconds.
200
+ attempts : int, default=4
201
+ Maximum number of request attempts.
202
+
203
+ Returns
204
+ -------
205
+ provider.ResponseLike or None
206
+ Successful response, or ``None`` for a 404 response.
207
+
208
+ Raises
209
+ ------
210
+ RuntimeError
211
+ If the request is rejected, or all request attempts fail.
212
+ """
213
+ return _rxiv.request(SERVER_CONFIG, url, params=params, session=session,
214
+ timeout=timeout, attempts=attempts)
215
+
216
+
217
+ def request_json(
218
+ url: str,
219
+ params: Mapping[str, object] | None = None,
220
+ session: provider.HTTPClient | None = None,
221
+ timeout: float = provider.DEFAULT_TIMEOUT,
222
+ attempts: int = provider.DEFAULT_ATTEMPTS,
223
+ ) -> _MedrxivRecord | None:
224
+ """Request a medRxiv endpoint and parse its JSON payload.
225
+
226
+ Parameters
227
+ ----------
228
+ url : str
229
+ medRxiv endpoint URL.
230
+ params : Mapping[str, object] or None, optional
231
+ Query parameters for the request.
232
+ session : provider.HTTPClient or None, optional
233
+ HTTP client exposing a ``get`` method.
234
+ timeout : float, default=60.0
235
+ Request timeout in seconds.
236
+ attempts : int, default=4
237
+ Maximum number of request attempts.
238
+
239
+ Returns
240
+ -------
241
+ dict[str, Any] or None
242
+ Parsed payload, or ``None`` when medRxiv holds no matching records.
243
+
244
+ Raises
245
+ ------
246
+ RuntimeError
247
+ If the request fails, the payload is not well-formed JSON, or medRxiv
248
+ reports the request as invalid.
249
+ """
250
+ return _rxiv.request_json(SERVER_CONFIG, url, params=params, session=session,
251
+ timeout=timeout, attempts=attempts)
252
+
253
+
254
+ def total_results(payload: Mapping[str, Any] | None) -> int:
255
+ """Read the total record count a medRxiv interval payload reports.
256
+
257
+ Parameters
258
+ ----------
259
+ payload : Mapping[str, Any] or None
260
+ Parsed medRxiv payload.
261
+
262
+ Returns
263
+ -------
264
+ int
265
+ Total number of records in the interval, or ``0`` when none is
266
+ reported.
267
+ """
268
+ return _rxiv.total_results(payload)
269
+
270
+
271
+ def normalize_medrxiv_doi(value: object) -> str:
272
+ """Normalize a medRxiv identifier to its bare, unversioned DOI.
273
+
274
+ A DOI, a ``doi:`` or ``medrxiv:`` paper identifier, a resolver URL, and a
275
+ medRxiv content or PDF URL are all accepted. Case is
276
+ folded, because DOIs are case-insensitive and the corpus compares them as
277
+ strings. A bioRxiv DOI is rejected rather than returned, because it names
278
+ a preprint this API cannot answer for.
279
+
280
+ Parameters
281
+ ----------
282
+ value : object
283
+ medRxiv DOI, paper identifier, or content URL.
284
+
285
+ Returns
286
+ -------
287
+ str
288
+ Bare medRxiv DOI, or an empty string when none is present.
289
+ """
290
+ return _rxiv.normalize_doi(SERVER_CONFIG, value)
291
+
292
+
293
+ def medrxiv_version(value: object) -> str:
294
+ """Extract the posted version number from a versioned medRxiv identifier.
295
+
296
+ Parameters
297
+ ----------
298
+ value : object
299
+ medRxiv DOI or content URL, such as ``10.1101/2024.03.01.24303596v2``.
300
+
301
+ Returns
302
+ -------
303
+ str
304
+ Version number such as ``2``, or an empty string when unversioned.
305
+ """
306
+ return _rxiv.version_of(SERVER_CONFIG, value)
307
+
308
+
309
+ def record_to_paper(record: Mapping[str, Any]) -> _MedrxivRecord:
310
+ """Map one medRxiv API record onto PaperMinerToolkit's paper schema.
311
+
312
+ Parameters
313
+ ----------
314
+ record : Mapping[str, Any]
315
+ medRxiv API record.
316
+
317
+ Returns
318
+ -------
319
+ dict[str, Any]
320
+ Normalized paper metadata plus the ``abstract``, ``categories``,
321
+ ``category``, ``primary_category``, ``license``, ``version``,
322
+ ``published_doi``, and ``jatsxml`` extras that the corpus schema does
323
+ not store directly.
324
+ """
325
+ return _rxiv.record_to_paper(SERVER_CONFIG, record)
326
+
327
+
328
+ def parse_records(payload: Mapping[str, Any] | None) -> list[_MedrxivRecord]:
329
+ """Map every record in a medRxiv payload onto the paper schema.
330
+
331
+ Parameters
332
+ ----------
333
+ payload : Mapping[str, Any] or None
334
+ Parsed medRxiv payload, or ``None``.
335
+
336
+ Returns
337
+ -------
338
+ list[dict[str, Any]]
339
+ Normalized paper metadata, one mapping per record, in payload order.
340
+ """
341
+ return _rxiv.parse_records(SERVER_CONFIG, payload)
342
+
343
+
344
+ def latest_versions(entries: Sequence[Mapping[str, Any]]) -> list[_MedrxivRecord]:
345
+ """Reduce parsed medRxiv records to one entry per preprint, newest kept.
346
+
347
+ Parameters
348
+ ----------
349
+ entries : Sequence[Mapping[str, Any]]
350
+ Parsed records from :func:`parse_records`.
351
+
352
+ Returns
353
+ -------
354
+ list[dict[str, Any]]
355
+ One record per preprint, in first-appearance order.
356
+ """
357
+ return _rxiv.latest_versions(SERVER_CONFIG, entries)
358
+
359
+
360
+ def page_cursors(total: int, step: int = PAGE_SIZE) -> Iterator[int]:
361
+ """Yield medRxiv interval page cursors newest first.
362
+
363
+ Parameters
364
+ ----------
365
+ total : int
366
+ Total record count the interval reports.
367
+ step : int, default=PAGE_SIZE
368
+ Records per page, from :func:`page_size`.
369
+
370
+ Yields
371
+ ------
372
+ int
373
+ Zero-based cursor of each page, from the last page down to zero.
374
+ """
375
+ yield from _rxiv.page_cursors(total, step)
376
+
377
+
378
+ def interval_page(start_date: str,
379
+ end_date: str,
380
+ cursor: int = 0,
381
+ category: str = '',
382
+ session: provider.HTTPClient | None = None) -> _MedrxivRecord | None:
383
+ """Fetch one page of medRxiv records posted within a date interval.
384
+
385
+ Parameters
386
+ ----------
387
+ start_date : str
388
+ Inclusive interval start as ``YYYY-MM-DD``.
389
+ end_date : str
390
+ Inclusive interval end as ``YYYY-MM-DD``.
391
+ cursor : int, default=0
392
+ Zero-based index of the first record requested.
393
+ category : str, default=''
394
+ medRxiv subject category to restrict the interval to.
395
+ session : provider.HTTPClient or None, optional
396
+ HTTP client exposing a ``get`` method.
397
+
398
+ Returns
399
+ -------
400
+ dict[str, Any] or None
401
+ Parsed payload, or ``None`` once the cursor is past the last record.
402
+
403
+ Raises
404
+ ------
405
+ ValueError
406
+ If either bound is not an ISO ``YYYY-MM-DD`` date.
407
+ RuntimeError
408
+ If the request cannot be completed or medRxiv rejects the interval.
409
+ """
410
+ return _rxiv.interval_page(SERVER_CONFIG, start_date, end_date, cursor, category,
411
+ session=session)
412
+
413
+
414
+ def details(doi: str,
415
+ version: str = 'na',
416
+ session: provider.HTTPClient | None = None) -> _MedrxivRecord | None:
417
+ """Fetch the posted versions of one medRxiv preprint.
418
+
419
+ Parameters
420
+ ----------
421
+ doi : str
422
+ medRxiv DOI, with or without a version suffix.
423
+ version : str, default='na'
424
+ Posted version to request, or ``'na'`` for every version.
425
+ session : provider.HTTPClient or None, optional
426
+ HTTP client exposing a ``get`` method.
427
+
428
+ Returns
429
+ -------
430
+ dict[str, Any] or None
431
+ Parsed payload, or ``None`` when medRxiv holds no such preprint.
432
+
433
+ Raises
434
+ ------
435
+ RuntimeError
436
+ If the request cannot be completed or medRxiv rejects the DOI.
437
+ """
438
+ return _rxiv.details(SERVER_CONFIG, doi, version, session=session)
439
+
440
+
441
+ def fetch_doi(doi: str, session: provider.HTTPClient | None = None) -> _MedrxivRecord | None:
442
+ """Fetch the newest posted version of one medRxiv preprint.
443
+
444
+ Parameters
445
+ ----------
446
+ doi : str
447
+ medRxiv DOI, with or without a version suffix.
448
+ session : provider.HTTPClient or None, optional
449
+ HTTP client exposing a ``get`` method.
450
+
451
+ Returns
452
+ -------
453
+ dict[str, Any] or None
454
+ Normalized paper metadata, or ``None`` when medRxiv holds no such
455
+ preprint.
456
+
457
+ Raises
458
+ ------
459
+ RuntimeError
460
+ If the request cannot be completed or medRxiv rejects the DOI.
461
+ """
462
+ return _rxiv.fetch_doi(SERVER_CONFIG, doi, session=session)
463
+
464
+
465
+ def resolve_medrxiv_doi(paper: Mapping[str, Any]) -> str:
466
+ """Resolve one paper row's medRxiv DOI from values it already holds.
467
+
468
+ This never issues a request. medRxiv publishes no title search, so a row
469
+ that carries neither a medRxiv DOI nor a medRxiv URL cannot be reached at
470
+ all; a published DOI on the row belongs to the journal version and is not
471
+ a medRxiv identifier.
472
+
473
+ Parameters
474
+ ----------
475
+ paper : Mapping[str, Any]
476
+ Corpus paper row.
477
+
478
+ Returns
479
+ -------
480
+ str
481
+ Bare medRxiv DOI, or an empty string when the row stores none.
482
+ """
483
+ return _rxiv.resolve_doi(SERVER_CONFIG, paper)
484
+
485
+
486
+ def full_text(entry: Mapping[str, Any], session: provider.HTTPClient | None = None) -> str:
487
+ """Fetch and flatten a medRxiv preprint's JATS full text.
488
+
489
+ Parameters
490
+ ----------
491
+ entry : Mapping[str, Any]
492
+ Normalized record from :func:`record_to_paper`.
493
+ session : provider.HTTPClient or None, optional
494
+ HTTP client exposing a ``get`` method.
495
+
496
+ Returns
497
+ -------
498
+ str
499
+ Article text, or an empty string when no body is available.
500
+
501
+ Raises
502
+ ------
503
+ RuntimeError
504
+ If the request cannot be completed or the payload is not well-formed.
505
+ """
506
+ return _rxiv.full_text(SERVER_CONFIG, entry, session=session)
507
+
508
+
509
+ def parse_query(query: str) -> tuple[list[str], dict[str, str]]:
510
+ """Split a medRxiv search phrase into match terms and interval scope.
511
+
512
+ Parameters
513
+ ----------
514
+ query : str
515
+ Search phrase, optionally carrying ``category:``, ``from:``, or ``to:``
516
+ scope terms.
517
+
518
+ Returns
519
+ -------
520
+ tuple[list[str], dict[str, str]]
521
+ Match terms, and the scope mapping with ``category``, ``from``, and
522
+ ``to`` keys for whichever were supplied.
523
+
524
+ Raises
525
+ ------
526
+ ValueError
527
+ If ``from:`` or ``to:`` is not an ISO ``YYYY-MM-DD`` date.
528
+ """
529
+ return _rxiv.parse_query(query)
530
+
531
+
532
+ def matches(entry: Mapping[str, Any], terms: Sequence[str]) -> bool:
533
+ """Report whether a medRxiv record matches every term of a query.
534
+
535
+ Parameters
536
+ ----------
537
+ entry : Mapping[str, Any]
538
+ Normalized record from :func:`record_to_paper`.
539
+ terms : Sequence[str]
540
+ Match terms from :func:`parse_query`. An empty sequence matches every
541
+ record.
542
+
543
+ Returns
544
+ -------
545
+ bool
546
+ Whether the record matches all terms.
547
+ """
548
+ return _rxiv.matches(entry, terms)