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,1272 @@
1
+ """Request helpers for the NCBI E-utilities API used by PaperMinerToolkit.
2
+
3
+ This module centralizes PubMed and PubMed Central HTTP details and the mapping
4
+ from PubMed article records onto PaperMinerToolkit's paper schema, so search,
5
+ download, and enrichment code can share one implementation. NCBI serves
6
+ unauthenticated clients at three requests per second and keyed clients at ten,
7
+ counted per IP address across every E-utilities endpoint, so all requests are
8
+ paced through one module-level limiter. An API key is optional but raises the
9
+ ceiling; a contact email lets NCBI warn before blocking an address.
10
+
11
+ Responses are parsed with :mod:`xml.etree.ElementTree`, which is documented as
12
+ vulnerable to entity-expansion attacks. NCBI over HTTPS is a trusted source and
13
+ the parser never resolves the external DTD PubMed declares, so this is safe
14
+ here; do not point these helpers at arbitrary user-supplied XML.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import os
20
+ import re
21
+ import xml.etree.ElementTree as ET
22
+ from collections.abc import Mapping, Sequence
23
+ from typing import Any, TypeAlias
24
+
25
+ from paperminertoolkit.providers import base as provider
26
+ from paperminertoolkit.corpus.metadata import clean_doi
27
+ from paperminertoolkit.settings import load_settings
28
+
29
+ BASE_URL = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils'
30
+ ESEARCH_URL = f'{BASE_URL}/esearch.fcgi'
31
+ EFETCH_URL = f'{BASE_URL}/efetch.fcgi'
32
+ OA_URL = 'https://www.ncbi.nlm.nih.gov/pmc/utils/oa/oa.fcgi'
33
+ FTP_PREFIX = 'ftp://ftp.ncbi.nlm.nih.gov/pub/pmc'
34
+ HTTPS_PREFIX = 'https://ftp.ncbi.nlm.nih.gov/pub/pmc'
35
+ TOOL_NAME = 'PaperMinerToolkit'
36
+ MAX_SEARCH_RESULTS = 10000
37
+ EFETCH_BATCH_SIZE = 200
38
+ NCBI_MIN_INTERVAL = 0.34
39
+ NCBI_KEYED_MIN_INTERVAL = 0.11
40
+ SORT_ORDERS = ('relevance', 'pub_date', 'Author', 'JournalName')
41
+ DATE_TYPES = ('pdat', 'mdat', 'edat')
42
+ JATS_SKIP_TAGS = frozenset({'table-wrap', 'fig', 'ref-list', 'supplementary-material',
43
+ 'table', 'graphic', 'inline-graphic', 'media'})
44
+ _MONTHS = {
45
+ 'jan': '01', 'feb': '02', 'mar': '03', 'apr': '04', 'may': '05', 'jun': '06',
46
+ 'jul': '07', 'aug': '08', 'sep': '09', 'oct': '10', 'nov': '11', 'dec': '12',
47
+ }
48
+ _PubMedRecord: TypeAlias = dict[str, Any]
49
+ LIMITER = provider.RateLimiter(NCBI_MIN_INTERVAL)
50
+
51
+
52
+ def configured_api_key(settings: Mapping[str, str] | None = None) -> str | None:
53
+ """Return the configured NCBI API key.
54
+
55
+ Parameters
56
+ ----------
57
+ settings : Mapping[str, str] or None, optional
58
+ Settings mapping to inspect before the environment.
59
+
60
+ Returns
61
+ -------
62
+ str or None
63
+ Configured API key, or ``None`` when no key is available.
64
+ """
65
+ settings = settings or load_settings()
66
+ return settings.get('ncbi_api_key') or os.environ.get('NCBI_API_KEY')
67
+
68
+
69
+ def configured_email(settings: Mapping[str, str] | None = None) -> str:
70
+ """Return the contact email address sent to NCBI.
71
+
72
+ The Crossref address is reused when no NCBI-specific address is configured,
73
+ so users who already identified themselves to Crossref need no new setup.
74
+
75
+ Parameters
76
+ ----------
77
+ settings : Mapping[str, str] or None, optional
78
+ Settings mapping to inspect before the environment.
79
+
80
+ Returns
81
+ -------
82
+ str
83
+ Contact address, or an empty string when none is configured.
84
+ """
85
+ settings = settings or load_settings()
86
+ return (settings.get('ncbi_email')
87
+ or os.environ.get('NCBI_EMAIL')
88
+ or settings.get('crossref_email')
89
+ or '')
90
+
91
+
92
+ def min_interval(api_key: str | None = None) -> float:
93
+ """Return the minimum seconds between NCBI requests for one credential.
94
+
95
+ Parameters
96
+ ----------
97
+ api_key : str or None, optional
98
+ NCBI API key used for the requests being paced.
99
+
100
+ Returns
101
+ -------
102
+ float
103
+ Delay honoring three requests per second, or ten with an API key.
104
+ """
105
+ return NCBI_KEYED_MIN_INTERVAL if api_key else NCBI_MIN_INTERVAL
106
+
107
+
108
+ def request_headers() -> dict[str, str]:
109
+ """Build E-utilities request headers.
110
+
111
+ Returns
112
+ -------
113
+ dict[str, str]
114
+ Headers containing the PaperMinerToolkit user agent.
115
+ """
116
+ return provider.default_headers()
117
+
118
+
119
+ def request_params(
120
+ params: Mapping[str, object] | None = None,
121
+ api_key: str | None = None,
122
+ email: str = '',
123
+ ) -> dict[str, object]:
124
+ """Copy query parameters and add the tool name, contact address, and key.
125
+
126
+ NCBI asks that clients identify themselves with ``tool`` and ``email`` so a
127
+ contact can be warned before an address is blocked. Neither the key nor the
128
+ address is ever invented; each is sent only when configured.
129
+
130
+ Parameters
131
+ ----------
132
+ params : Mapping[str, object] or None, optional
133
+ Query parameters to copy.
134
+ api_key : str or None, optional
135
+ NCBI API key to add.
136
+ email : str, default=''
137
+ Contact email address to add when non-empty.
138
+
139
+ Returns
140
+ -------
141
+ dict[str, object]
142
+ Copied parameters including ``tool`` and, when available, ``email`` and
143
+ ``api_key``.
144
+ """
145
+ merged = dict(params or {})
146
+ merged['tool'] = TOOL_NAME
147
+ if email:
148
+ merged['email'] = email
149
+ if api_key:
150
+ merged['api_key'] = api_key
151
+ return merged
152
+
153
+
154
+ def _error_text(payload: object) -> str:
155
+ """Extract an E-utilities error message from a decoded response body.
156
+
157
+ Parameters
158
+ ----------
159
+ payload : object
160
+ Decoded JSON payload or parsed XML element.
161
+
162
+ Returns
163
+ -------
164
+ str
165
+ Error message, or an empty string when the response reports no error.
166
+ """
167
+ if isinstance(payload, ET.Element):
168
+ error = payload.find('.//ERROR')
169
+ return _element_text(error) if error is not None else ''
170
+ if isinstance(payload, Mapping):
171
+ result = payload.get('esearchresult')
172
+ if isinstance(result, Mapping):
173
+ error = result.get('ERROR') or result.get('error')
174
+ if error:
175
+ return str(error)
176
+ error = payload.get('ERROR') or payload.get('error')
177
+ return str(error) if error else ''
178
+ return ''
179
+
180
+
181
+ def request(
182
+ url: str,
183
+ params: Mapping[str, object] | None = None,
184
+ api_key: str | None = None,
185
+ email: str = '',
186
+ session: provider.HTTPClient | None = None,
187
+ timeout: float = 60,
188
+ attempts: int = 4,
189
+ ) -> provider.ResponseLike | None:
190
+ """Request an E-utilities endpoint with NCBI pacing and bounded retries.
191
+
192
+ Unlike OpenAlex, a 429 from NCBI means the per-second limit was exceeded
193
+ rather than that a daily budget is gone, so it is retried rather than
194
+ treated as terminal. Every other client error is terminal and fails at
195
+ once, because retrying it would only spend more of the request budget.
196
+
197
+ Parameters
198
+ ----------
199
+ url : str
200
+ E-utilities endpoint URL.
201
+ params : Mapping[str, object] or None, optional
202
+ Query parameters for the request.
203
+ api_key : str or None, optional
204
+ NCBI API key to attach.
205
+ email : str, default=''
206
+ Contact email address sent with the request.
207
+ session : provider.HTTPClient or None, optional
208
+ HTTP client exposing a ``get`` method. Defaults to :mod:`requests`.
209
+ timeout : int or float, default=60
210
+ Request timeout in seconds.
211
+ attempts : int, default=4
212
+ Maximum number of request attempts.
213
+
214
+ Returns
215
+ -------
216
+ provider.ResponseLike or None
217
+ Successful response, or ``None`` for a 404 response.
218
+
219
+ Raises
220
+ ------
221
+ RuntimeError
222
+ If the request is rejected, or all request attempts fail.
223
+ """
224
+ return provider.request(url, label='NCBI', limiter=LIMITER,
225
+ params=request_params(params, api_key, email),
226
+ session=session, timeout=timeout, attempts=attempts,
227
+ interval=min_interval(api_key))
228
+
229
+
230
+ def request_json(
231
+ url: str,
232
+ params: Mapping[str, object] | None = None,
233
+ api_key: str | None = None,
234
+ email: str = '',
235
+ session: provider.HTTPClient | None = None,
236
+ timeout: float = 60,
237
+ attempts: int = 4,
238
+ ) -> _PubMedRecord | None:
239
+ """Request an E-utilities endpoint and decode its JSON payload.
240
+
241
+ E-utilities reports a rejected query as an error member of a ``200``
242
+ response rather than an unsuccessful status, so the body is inspected
243
+ before it is returned.
244
+
245
+ Parameters
246
+ ----------
247
+ url : str
248
+ E-utilities endpoint URL.
249
+ params : Mapping[str, object] or None, optional
250
+ Query parameters for the request.
251
+ api_key : str or None, optional
252
+ NCBI API key to attach.
253
+ email : str, default=''
254
+ Contact email address sent with the request.
255
+ session : provider.HTTPClient or None, optional
256
+ HTTP client exposing a ``get`` method.
257
+ timeout : int or float, default=60
258
+ Request timeout in seconds.
259
+ attempts : int, default=4
260
+ Maximum number of request attempts.
261
+
262
+ Returns
263
+ -------
264
+ _PubMedRecord or None
265
+ Decoded JSON payload, or ``None`` for a 404 response.
266
+
267
+ Raises
268
+ ------
269
+ RuntimeError
270
+ If the request fails or the payload reports an error.
271
+ """
272
+ response = request(url, params=params, api_key=api_key, email=email,
273
+ session=session, timeout=timeout, attempts=attempts)
274
+ if response is None:
275
+ return None
276
+ try:
277
+ payload = response.json()
278
+ except ValueError as error:
279
+ raise RuntimeError(f'NCBI returned an undecodable JSON payload: {error}') from error
280
+ error_text = _error_text(payload)
281
+ if error_text:
282
+ raise RuntimeError(f'NCBI rejected the request: {error_text}')
283
+ return payload
284
+
285
+
286
+ def request_xml(
287
+ url: str,
288
+ params: Mapping[str, object] | None = None,
289
+ api_key: str | None = None,
290
+ email: str = '',
291
+ session: provider.HTTPClient | None = None,
292
+ timeout: float = 60,
293
+ attempts: int = 4,
294
+ ) -> ET.Element | None:
295
+ """Request an E-utilities endpoint and parse its XML payload.
296
+
297
+ Parameters
298
+ ----------
299
+ url : str
300
+ E-utilities endpoint URL.
301
+ params : Mapping[str, object] or None, optional
302
+ Query parameters for the request.
303
+ api_key : str or None, optional
304
+ NCBI API key to attach.
305
+ email : str, default=''
306
+ Contact email address sent with the request.
307
+ session : provider.HTTPClient or None, optional
308
+ HTTP client exposing a ``get`` method.
309
+ timeout : int or float, default=60
310
+ Request timeout in seconds.
311
+ attempts : int, default=4
312
+ Maximum number of request attempts.
313
+
314
+ Returns
315
+ -------
316
+ xml.etree.ElementTree.Element or None
317
+ Parsed document root, or ``None`` for a 404 or empty response.
318
+
319
+ Raises
320
+ ------
321
+ RuntimeError
322
+ If the request fails, the payload is not well-formed, or it reports an
323
+ error.
324
+ """
325
+ response = request(url, params=params, api_key=api_key, email=email,
326
+ session=session, timeout=timeout, attempts=attempts)
327
+ if response is None:
328
+ return None
329
+ text = response.text or ''
330
+ if not text.strip():
331
+ return None
332
+ try:
333
+ root = ET.fromstring(text)
334
+ except ET.ParseError as error:
335
+ raise RuntimeError(f'NCBI returned malformed XML: {error}') from error
336
+ error_text = _error_text(root)
337
+ if error_text:
338
+ raise RuntimeError(f'NCBI rejected the request: {error_text}')
339
+ return root
340
+
341
+
342
+ def _search_params(term: str,
343
+ sort: str = 'relevance',
344
+ datetype: str = '',
345
+ mindate: str = '',
346
+ maxdate: str = '',
347
+ reldate: int = 0,
348
+ db: str = 'pubmed') -> dict[str, object]:
349
+ """Build the shared esearch query parameters.
350
+
351
+ Parameters
352
+ ----------
353
+ term : str
354
+ PubMed search expression.
355
+ sort : str, default='relevance'
356
+ Result ordering requested from PubMed.
357
+ datetype : str, default=''
358
+ Date field used by ``mindate``, ``maxdate``, and ``reldate``.
359
+ mindate : str, default=''
360
+ Earliest publication date, as ``YYYY``, ``YYYY/MM``, or ``YYYY/MM/DD``.
361
+ maxdate : str, default=''
362
+ Latest publication date, in the same formats as ``mindate``.
363
+ reldate : int, default=0
364
+ Restrict results to the last ``reldate`` days when positive.
365
+ db : str, default='pubmed'
366
+ Entrez database to search.
367
+
368
+ Returns
369
+ -------
370
+ dict[str, object]
371
+ Query parameters excluding paging and history options.
372
+
373
+ Raises
374
+ ------
375
+ ValueError
376
+ If ``sort`` or ``datetype`` is not one E-utilities accepts.
377
+ """
378
+ if sort and sort not in SORT_ORDERS:
379
+ raise ValueError(f'sort must be one of: {", ".join(SORT_ORDERS)}')
380
+ if datetype and datetype not in DATE_TYPES:
381
+ raise ValueError(f'datetype must be one of: {", ".join(DATE_TYPES)}')
382
+ params: dict[str, object] = {'db': db, 'term': term, 'retmode': 'json'}
383
+ if sort:
384
+ params['sort'] = sort
385
+ if datetype:
386
+ params['datetype'] = datetype
387
+ if mindate:
388
+ params['mindate'] = mindate
389
+ if maxdate:
390
+ params['maxdate'] = maxdate
391
+ if reldate:
392
+ params['reldate'] = int(reldate)
393
+ return params
394
+
395
+
396
+ def esearch(term: str,
397
+ retmax: int = 100,
398
+ retstart: int = 0,
399
+ sort: str = 'relevance',
400
+ datetype: str = '',
401
+ mindate: str = '',
402
+ maxdate: str = '',
403
+ reldate: int = 0,
404
+ db: str = 'pubmed',
405
+ api_key: str | None = None,
406
+ email: str = '',
407
+ session: provider.HTTPClient | None = None) -> tuple[list[str], int]:
408
+ """Run one esearch page and return its identifiers with the match count.
409
+
410
+ Parameters
411
+ ----------
412
+ term : str
413
+ PubMed search expression.
414
+ retmax : int, default=100
415
+ Maximum identifiers to return, capped at the E-utilities maximum.
416
+ retstart : int, default=0
417
+ Zero-based index of the first identifier to return.
418
+ sort : str, default='relevance'
419
+ Result ordering requested from PubMed.
420
+ datetype : str, default=''
421
+ Date field used by ``mindate``, ``maxdate``, and ``reldate``.
422
+ mindate : str, default=''
423
+ Earliest publication date.
424
+ maxdate : str, default=''
425
+ Latest publication date.
426
+ reldate : int, default=0
427
+ Restrict results to the last ``reldate`` days when positive.
428
+ db : str, default='pubmed'
429
+ Entrez database to search.
430
+ api_key : str or None, optional
431
+ NCBI API key to attach.
432
+ email : str, default=''
433
+ Contact email address sent with the request.
434
+ session : provider.HTTPClient or None, optional
435
+ HTTP client exposing a ``get`` method.
436
+
437
+ Returns
438
+ -------
439
+ tuple[list[str], int]
440
+ Identifiers on this page, and the total number of matches.
441
+
442
+ Raises
443
+ ------
444
+ RuntimeError
445
+ If the E-utilities request cannot be completed.
446
+ """
447
+ params = _search_params(term, sort, datetype, mindate, maxdate, reldate, db)
448
+ params['retmax'] = max(0, min(int(retmax), MAX_SEARCH_RESULTS))
449
+ params['retstart'] = max(0, int(retstart))
450
+ payload = request_json(ESEARCH_URL, params=params, api_key=api_key,
451
+ email=email, session=session) or {}
452
+ result = payload.get('esearchresult') or {}
453
+ identifiers = [str(value) for value in result.get('idlist') or []]
454
+ try:
455
+ total = int(result.get('count') or 0)
456
+ except (TypeError, ValueError):
457
+ total = 0
458
+ return identifiers, total
459
+
460
+
461
+ def esearch_history(term: str,
462
+ sort: str = 'relevance',
463
+ datetype: str = '',
464
+ mindate: str = '',
465
+ maxdate: str = '',
466
+ reldate: int = 0,
467
+ db: str = 'pubmed',
468
+ api_key: str | None = None,
469
+ email: str = '',
470
+ session: provider.HTTPClient | None = None) -> tuple[str, str, int]:
471
+ """Run esearch with history and return its stored-set handles.
472
+
473
+ Storing the result set server-side lets efetch page through it without
474
+ resending long identifier lists, which is what NCBI recommends and what
475
+ keeps request URLs within length limits.
476
+
477
+ Parameters
478
+ ----------
479
+ term : str
480
+ PubMed search expression.
481
+ sort : str, default='relevance'
482
+ Result ordering requested from PubMed.
483
+ datetype : str, default=''
484
+ Date field used by ``mindate``, ``maxdate``, and ``reldate``.
485
+ mindate : str, default=''
486
+ Earliest publication date.
487
+ maxdate : str, default=''
488
+ Latest publication date.
489
+ reldate : int, default=0
490
+ Restrict results to the last ``reldate`` days when positive.
491
+ db : str, default='pubmed'
492
+ Entrez database to search.
493
+ api_key : str or None, optional
494
+ NCBI API key to attach.
495
+ email : str, default=''
496
+ Contact email address sent with the request.
497
+ session : provider.HTTPClient or None, optional
498
+ HTTP client exposing a ``get`` method.
499
+
500
+ Returns
501
+ -------
502
+ tuple[str, str, int]
503
+ Web environment, query key, and the total number of matches.
504
+
505
+ Raises
506
+ ------
507
+ RuntimeError
508
+ If the E-utilities request cannot be completed.
509
+ """
510
+ params = _search_params(term, sort, datetype, mindate, maxdate, reldate, db)
511
+ params['usehistory'] = 'y'
512
+ params['retmax'] = 0
513
+ payload = request_json(ESEARCH_URL, params=params, api_key=api_key,
514
+ email=email, session=session) or {}
515
+ result = payload.get('esearchresult') or {}
516
+ try:
517
+ total = int(result.get('count') or 0)
518
+ except (TypeError, ValueError):
519
+ total = 0
520
+ return str(result.get('webenv') or ''), str(result.get('querykey') or ''), total
521
+
522
+
523
+ def efetch_history(webenv: str,
524
+ query_key: str,
525
+ retstart: int = 0,
526
+ retmax: int = EFETCH_BATCH_SIZE,
527
+ db: str = 'pubmed',
528
+ api_key: str | None = None,
529
+ email: str = '',
530
+ session: provider.HTTPClient | None = None) -> ET.Element | None:
531
+ """Fetch one page of records from a stored E-utilities history set.
532
+
533
+ Parameters
534
+ ----------
535
+ webenv : str
536
+ Web environment returned by :func:`esearch_history`.
537
+ query_key : str
538
+ Query key returned by :func:`esearch_history`.
539
+ retstart : int, default=0
540
+ Zero-based index of the first record to fetch.
541
+ retmax : int, default=200
542
+ Maximum records to fetch in this request.
543
+ db : str, default='pubmed'
544
+ Entrez database to fetch from.
545
+ api_key : str or None, optional
546
+ NCBI API key to attach.
547
+ email : str, default=''
548
+ Contact email address sent with the request.
549
+ session : provider.HTTPClient or None, optional
550
+ HTTP client exposing a ``get`` method.
551
+
552
+ Returns
553
+ -------
554
+ xml.etree.ElementTree.Element or None
555
+ Parsed record set, or ``None`` when the page is empty.
556
+
557
+ Raises
558
+ ------
559
+ RuntimeError
560
+ If the E-utilities request cannot be completed.
561
+ """
562
+ params = {
563
+ 'db': db,
564
+ 'WebEnv': webenv,
565
+ 'query_key': query_key,
566
+ 'retstart': max(0, int(retstart)),
567
+ 'retmax': max(1, int(retmax)),
568
+ 'retmode': 'xml',
569
+ }
570
+ return request_xml(EFETCH_URL, params=params, api_key=api_key, email=email, session=session)
571
+
572
+
573
+ def efetch_ids(identifiers: Sequence[str],
574
+ db: str = 'pubmed',
575
+ api_key: str | None = None,
576
+ email: str = '',
577
+ session: provider.HTTPClient | None = None) -> ET.Element | None:
578
+ """Fetch records for an explicit identifier list in one efetch request.
579
+
580
+ Parameters
581
+ ----------
582
+ identifiers : Sequence[str]
583
+ Entrez identifiers to fetch.
584
+ db : str, default='pubmed'
585
+ Entrez database to fetch from.
586
+ api_key : str or None, optional
587
+ NCBI API key to attach.
588
+ email : str, default=''
589
+ Contact email address sent with the request.
590
+ session : provider.HTTPClient or None, optional
591
+ HTTP client exposing a ``get`` method.
592
+
593
+ Returns
594
+ -------
595
+ xml.etree.ElementTree.Element or None
596
+ Parsed record set, or ``None`` when no identifiers were supplied.
597
+
598
+ Raises
599
+ ------
600
+ RuntimeError
601
+ If the E-utilities request cannot be completed.
602
+ """
603
+ wanted = [str(value).strip() for value in identifiers if str(value).strip()]
604
+ if not wanted:
605
+ return None
606
+ params = {'db': db, 'id': ','.join(wanted), 'retmode': 'xml'}
607
+ return request_xml(EFETCH_URL, params=params, api_key=api_key, email=email, session=session)
608
+
609
+
610
+ def normalize_pmid(value: object) -> str:
611
+ """Normalize a PubMed identifier to its bare digits.
612
+
613
+ Parameters
614
+ ----------
615
+ value : object
616
+ PMID, PubMed URL, or other identifier-like value.
617
+
618
+ Returns
619
+ -------
620
+ str
621
+ Bare PMID digits, or an empty string when none is present.
622
+ """
623
+ if value is None:
624
+ return ''
625
+ match = re.search(r'\d+', str(value))
626
+ return match.group(0) if match else ''
627
+
628
+
629
+ def normalize_pmcid(value: object) -> str:
630
+ """Normalize a PubMed Central identifier to its ``PMC`` form.
631
+
632
+ Parameters
633
+ ----------
634
+ value : object
635
+ PMCID, PMC URL, or other identifier-like value.
636
+
637
+ Returns
638
+ -------
639
+ str
640
+ Identifier as ``PMC`` followed by digits, or an empty string.
641
+ """
642
+ if value is None:
643
+ return ''
644
+ match = re.search(r'\d+', str(value))
645
+ return f'PMC{match.group(0)}' if match else ''
646
+
647
+
648
+ def _element_text(element: ET.Element | None) -> str:
649
+ """Flatten an element's text and inline markup into one plain string.
650
+
651
+ PubMed wraps formatting such as subscripts and italics in child elements,
652
+ so reading ``element.text`` alone would truncate a title at its first tag.
653
+
654
+ Parameters
655
+ ----------
656
+ element : xml.etree.ElementTree.Element or None
657
+ Element to flatten.
658
+
659
+ Returns
660
+ -------
661
+ str
662
+ Whitespace-collapsed text, or an empty string for a missing element.
663
+ """
664
+ if element is None:
665
+ return ''
666
+ return re.sub(r'\s+', ' ', ''.join(element.itertext())).strip()
667
+
668
+
669
+ def _abstract_text(parent: ET.Element) -> str:
670
+ """Join an abstract's sections, prefixing any section labels.
671
+
672
+ Structured abstracts arrive as sibling ``AbstractText`` elements carrying a
673
+ ``Label``. Only those elements are read, which also excludes the sibling
674
+ ``CopyrightInformation`` notice from the stored abstract.
675
+
676
+ Parameters
677
+ ----------
678
+ parent : xml.etree.ElementTree.Element
679
+ Element containing an ``Abstract``.
680
+
681
+ Returns
682
+ -------
683
+ str
684
+ Abstract text, or an empty string when the record has no abstract.
685
+ """
686
+ sections = []
687
+ for section in parent.findall('.//Abstract/AbstractText'):
688
+ text = _element_text(section)
689
+ if not text:
690
+ continue
691
+ label = (section.get('Label') or '').strip()
692
+ if label and label.upper() != 'UNLABELLED':
693
+ text = f'{label}: {text}'
694
+ sections.append(text)
695
+ return ' '.join(sections)
696
+
697
+
698
+ def _publication_date(article: ET.Element) -> str:
699
+ """Extract the best available publication date from an article element.
700
+
701
+ The electronic ``ArticleDate`` is preferred because it is already a
702
+ year/month/day triple. A free-text ``MedlineDate`` such as ``2019 Jan-Feb``
703
+ contributes only its year, since guessing a month would be worse than
704
+ omitting one.
705
+
706
+ Parameters
707
+ ----------
708
+ article : xml.etree.ElementTree.Element
709
+ ``Article`` or ``BookDocument`` element.
710
+
711
+ Returns
712
+ -------
713
+ str
714
+ Publication date as ``YYYY``, ``YYYY-MM``, or ``YYYY-MM-DD``.
715
+ """
716
+ for candidate in [article.find('./ArticleDate'), article.find('.//PubDate')]:
717
+ if candidate is None:
718
+ continue
719
+ year = _element_text(candidate.find('./Year'))
720
+ if year:
721
+ parts = [year]
722
+ month = _month_number(_element_text(candidate.find('./Month')))
723
+ if month:
724
+ parts.append(month)
725
+ day = _element_text(candidate.find('./Day'))
726
+ if day.isdigit():
727
+ parts.append(day.zfill(2))
728
+ return '-'.join(parts)
729
+ medline = _element_text(candidate.find('./MedlineDate'))
730
+ match = re.search(r'\d{4}', medline)
731
+ if match:
732
+ return match.group(0)
733
+ return ''
734
+
735
+
736
+ def _month_number(value: str) -> str:
737
+ """Normalize a PubMed month to two digits.
738
+
739
+ PubMed records a month as either an abbreviated name or a number, and both
740
+ forms occur in the same corpus.
741
+
742
+ Parameters
743
+ ----------
744
+ value : str
745
+ Month name or number.
746
+
747
+ Returns
748
+ -------
749
+ str
750
+ Two-digit month, or an empty string when the value is unusable.
751
+ """
752
+ value = value.strip()
753
+ if value.isdigit():
754
+ number = int(value)
755
+ return f'{number:02d}' if 1 <= number <= 12 else ''
756
+ return _MONTHS.get(value.lower()[:3], '')
757
+
758
+
759
+ def _author_name(author: ET.Element) -> str:
760
+ """Format one author element as a display name.
761
+
762
+ Parameters
763
+ ----------
764
+ author : xml.etree.ElementTree.Element
765
+ ``Author`` element.
766
+
767
+ Returns
768
+ -------
769
+ str
770
+ Personal or collective name, or an empty string when unusable.
771
+ """
772
+ collective = _element_text(author.find('./CollectiveName'))
773
+ if collective:
774
+ return collective
775
+ family = _element_text(author.find('./LastName'))
776
+ if not family:
777
+ return ''
778
+ given = _element_text(author.find('./ForeName')) or _element_text(author.find('./Initials'))
779
+ return f'{given} {family}'.strip()
780
+
781
+
782
+ def _authors(parent: ET.Element) -> str:
783
+ """Format an article's author list as a semicolon-separated string.
784
+
785
+ Parameters
786
+ ----------
787
+ parent : xml.etree.ElementTree.Element
788
+ Element containing an ``AuthorList``.
789
+
790
+ Returns
791
+ -------
792
+ str
793
+ Author names in record order.
794
+ """
795
+ names = []
796
+ for author in parent.findall('.//AuthorList/Author'):
797
+ if author.get('ValidYN') == 'N':
798
+ continue
799
+ name = _author_name(author)
800
+ if name:
801
+ names.append(name)
802
+ return '; '.join(names)
803
+
804
+
805
+ def _article_ids(record: ET.Element) -> dict[str, str]:
806
+ """Collect the DOI, PMID, and PMCID recorded for one article.
807
+
808
+ Parameters
809
+ ----------
810
+ record : xml.etree.ElementTree.Element
811
+ ``PubmedArticle`` or ``PubmedBookArticle`` element.
812
+
813
+ Returns
814
+ -------
815
+ dict[str, str]
816
+ Mapping with ``doi``, ``pmid``, and ``pmcid`` keys, empty when absent.
817
+ """
818
+ ids = {'doi': '', 'pmid': '', 'pmcid': ''}
819
+ # Scoped to the record's own identifier list: a PubmedArticle also carries
820
+ # an ArticleIdList inside every cited reference, and a '//' search would
821
+ # take a reference's DOI for any record that omits its own.
822
+ id_list = record.find('./PubmedData/ArticleIdList')
823
+ if id_list is None:
824
+ id_list = record.find('./PubmedBookData/ArticleIdList')
825
+ for article_id in (id_list if id_list is not None else []):
826
+ id_type = (article_id.get('IdType') or '').lower()
827
+ value = _element_text(article_id)
828
+ if not value:
829
+ continue
830
+ if id_type == 'doi' and not ids['doi']:
831
+ ids['doi'] = clean_doi(value)
832
+ elif id_type in {'pubmed', 'pmid'} and not ids['pmid']:
833
+ ids['pmid'] = normalize_pmid(value)
834
+ elif id_type == 'pmc' and not ids['pmcid']:
835
+ ids['pmcid'] = normalize_pmcid(value)
836
+ if not ids['pmid']:
837
+ ids['pmid'] = normalize_pmid(_element_text(record.find('.//PMID')))
838
+ return ids
839
+
840
+
841
+ def _mesh_terms(record: ET.Element) -> list[dict[str, str]]:
842
+ """Collect MeSH descriptors and qualifiers from one article.
843
+
844
+ Parameters
845
+ ----------
846
+ record : xml.etree.ElementTree.Element
847
+ ``PubmedArticle`` element.
848
+
849
+ Returns
850
+ -------
851
+ list[dict[str, str]]
852
+ Terms with ``scheme``, ``id``, ``name``, and ``is_primary`` keys.
853
+ """
854
+ terms = []
855
+ for heading in record.findall('.//MeshHeadingList/MeshHeading'):
856
+ for scheme, tag in [('mesh', 'DescriptorName'), ('mesh_qualifier', 'QualifierName')]:
857
+ for element in heading.findall(f'./{tag}'):
858
+ name = _element_text(element)
859
+ if not name:
860
+ continue
861
+ terms.append({
862
+ 'scheme': scheme,
863
+ 'id': element.get('UI') or name,
864
+ 'name': name,
865
+ 'is_primary': '1' if element.get('MajorTopicYN') == 'Y' else '0',
866
+ })
867
+ return terms
868
+
869
+
870
+ def _publication_types(record: ET.Element) -> list[dict[str, str]]:
871
+ """Collect the publication types recorded for one article.
872
+
873
+ Parameters
874
+ ----------
875
+ record : xml.etree.ElementTree.Element
876
+ ``PubmedArticle`` or ``PubmedBookArticle`` element.
877
+
878
+ Returns
879
+ -------
880
+ list[dict[str, str]]
881
+ Types with ``id`` and ``name`` keys.
882
+ """
883
+ types = []
884
+ for element in record.findall('.//PublicationTypeList/PublicationType'):
885
+ name = _element_text(element)
886
+ if name:
887
+ types.append({'id': element.get('UI') or name, 'name': name})
888
+ return types
889
+
890
+
891
+ def _keywords(record: ET.Element) -> list[str]:
892
+ """Collect author-supplied keywords from one article.
893
+
894
+ Parameters
895
+ ----------
896
+ record : xml.etree.ElementTree.Element
897
+ ``PubmedArticle`` or ``PubmedBookArticle`` element.
898
+
899
+ Returns
900
+ -------
901
+ list[str]
902
+ Keyword text in record order.
903
+ """
904
+ return [text for text in (_element_text(element)
905
+ for element in record.findall('.//KeywordList/Keyword')) if text]
906
+
907
+
908
+ def article_to_paper(record: ET.Element) -> _PubMedRecord:
909
+ """Map one PubMed record onto PaperMinerToolkit's paper schema.
910
+
911
+ Book records nest their metadata under ``BookDocument`` and have no
912
+ ``Article`` element, so they are read from a different path rather than
913
+ dropped; they carry PMIDs and appear in ordinary PubMed searches.
914
+
915
+ Parameters
916
+ ----------
917
+ record : xml.etree.ElementTree.Element
918
+ ``PubmedArticle`` or ``PubmedBookArticle`` element.
919
+
920
+ Returns
921
+ -------
922
+ _PubMedRecord
923
+ Normalized paper metadata plus the ``abstract``, ``mesh``,
924
+ ``keywords``, ``publication_types``, and ``article_type`` extras that
925
+ the corpus schema does not store directly.
926
+ """
927
+ is_book = record.tag == 'PubmedBookArticle'
928
+ article = record.find('.//BookDocument') if is_book else record.find('.//Article')
929
+ if article is None:
930
+ article = record
931
+ if is_book:
932
+ title = (_element_text(article.find('./ArticleTitle'))
933
+ or _element_text(article.find('./Book/BookTitle')))
934
+ journal = _element_text(article.find('./Book/BookTitle'))
935
+ else:
936
+ title = _element_text(article.find('./ArticleTitle'))
937
+ journal = (_element_text(article.find('./Journal/Title'))
938
+ or _element_text(article.find('./Journal/ISOAbbreviation')))
939
+ ids = _article_ids(record)
940
+ if ids['doi']:
941
+ paper_id = f'doi:{ids["doi"]}'
942
+ elif ids['pmid']:
943
+ paper_id = f'pmid:{ids["pmid"]}'
944
+ else:
945
+ paper_id = ''
946
+ return {
947
+ 'paper_id': paper_id,
948
+ 'doi': ids['doi'],
949
+ 'pmid': ids['pmid'],
950
+ 'pmcid': ids['pmcid'],
951
+ 'title': title,
952
+ 'journal': journal,
953
+ 'publication_date': _publication_date(article),
954
+ 'authors': _authors(article),
955
+ 'sources': 'pubmed',
956
+ 'metadata_status': 'retrieved',
957
+ 'abstract': _abstract_text(article),
958
+ 'mesh': _mesh_terms(record),
959
+ 'keywords': _keywords(record),
960
+ 'publication_types': _publication_types(record),
961
+ 'article_type': 'book' if is_book else 'article',
962
+ }
963
+
964
+
965
+ def parse_articles(root: ET.Element | None) -> list[_PubMedRecord]:
966
+ """Map every record in a PubMed record set onto the paper schema.
967
+
968
+ Parameters
969
+ ----------
970
+ root : xml.etree.ElementTree.Element or None
971
+ ``PubmedArticleSet`` root, or ``None``.
972
+
973
+ Returns
974
+ -------
975
+ list[_PubMedRecord]
976
+ Normalized paper metadata, one mapping per record.
977
+ """
978
+ if root is None:
979
+ return []
980
+ records = [child for child in root if child.tag in {'PubmedArticle', 'PubmedBookArticle'}]
981
+ if not records and root.tag in {'PubmedArticle', 'PubmedBookArticle'}:
982
+ records = [root]
983
+ return [article_to_paper(record) for record in records]
984
+
985
+
986
+ def find_pmid(doi: str,
987
+ api_key: str | None = None,
988
+ email: str = '',
989
+ session: provider.HTTPClient | None = None) -> str:
990
+ """Look up the PubMed identifier that PubMed records against a DOI.
991
+
992
+ The PMC ID converter service is not usable for this: it answers requests
993
+ with ``403``. Searching the ``AID`` article-identifier field stays on the
994
+ E-utilities endpoint that every other request already uses and shares its
995
+ pacing.
996
+
997
+ Parameters
998
+ ----------
999
+ doi : str
1000
+ DOI to look up.
1001
+ api_key : str or None, optional
1002
+ NCBI API key to attach.
1003
+ email : str, default=''
1004
+ Contact email address sent with the request.
1005
+ session : provider.HTTPClient or None, optional
1006
+ HTTP client exposing a ``get`` method.
1007
+
1008
+ Returns
1009
+ -------
1010
+ str
1011
+ Bare PMID digits, or an empty string when PubMed indexes no such DOI.
1012
+
1013
+ Raises
1014
+ ------
1015
+ RuntimeError
1016
+ If the E-utilities request cannot be completed.
1017
+ """
1018
+ doi = clean_doi(doi) if doi else ''
1019
+ if not doi:
1020
+ return ''
1021
+ identifiers, _ = esearch(f'{doi}[AID]', retmax=1, sort='', api_key=api_key,
1022
+ email=email, session=session)
1023
+ return normalize_pmid(identifiers[0]) if identifiers else ''
1024
+
1025
+
1026
+ def resolve_pmid(paper: Mapping[str, Any],
1027
+ api_key: str | None = None,
1028
+ email: str = '',
1029
+ session: provider.HTTPClient | None = None) -> str:
1030
+ """Resolve one paper row's PubMed identifier.
1031
+
1032
+ A stored PMID is returned without a request; otherwise the row's DOI is
1033
+ looked up in PubMed.
1034
+
1035
+ Parameters
1036
+ ----------
1037
+ paper : Mapping[str, Any]
1038
+ Corpus paper row.
1039
+ api_key : str or None, optional
1040
+ NCBI API key to attach.
1041
+ email : str, default=''
1042
+ Contact email address sent with the request.
1043
+ session : provider.HTTPClient or None, optional
1044
+ HTTP client exposing a ``get`` method.
1045
+
1046
+ Returns
1047
+ -------
1048
+ str
1049
+ Bare PMID digits, or an empty string when none can be resolved.
1050
+
1051
+ Raises
1052
+ ------
1053
+ RuntimeError
1054
+ If an E-utilities request cannot be completed.
1055
+ """
1056
+ pmid = normalize_pmid(paper.get('pmid'))
1057
+ if pmid:
1058
+ return pmid
1059
+ paper_id = str(paper.get('paper_id') or '')
1060
+ if paper_id.startswith('pmid:'):
1061
+ return normalize_pmid(paper_id.split(':', 1)[1])
1062
+ return find_pmid(str(paper.get('doi') or ''), api_key=api_key,
1063
+ email=email, session=session)
1064
+
1065
+
1066
+ def resolve_pmcid(paper: Mapping[str, Any],
1067
+ api_key: str | None = None,
1068
+ email: str = '',
1069
+ session: provider.HTTPClient | None = None) -> str:
1070
+ """Resolve one paper row's PubMed Central identifier.
1071
+
1072
+ A record's own identifier list already carries its PMCID, so the PMID is
1073
+ resolved first and the identifier is read from that record.
1074
+
1075
+ Parameters
1076
+ ----------
1077
+ paper : Mapping[str, Any]
1078
+ Corpus paper row.
1079
+ api_key : str or None, optional
1080
+ NCBI API key to attach.
1081
+ email : str, default=''
1082
+ Contact email address sent with the request.
1083
+ session : provider.HTTPClient or None, optional
1084
+ HTTP client exposing a ``get`` method.
1085
+
1086
+ Returns
1087
+ -------
1088
+ str
1089
+ Identifier as ``PMC`` followed by digits, or an empty string.
1090
+
1091
+ Raises
1092
+ ------
1093
+ RuntimeError
1094
+ If an E-utilities request cannot be completed.
1095
+ """
1096
+ pmcid = normalize_pmcid(paper.get('pmcid'))
1097
+ if pmcid:
1098
+ return pmcid
1099
+ pmid = resolve_pmid(paper, api_key=api_key, email=email, session=session)
1100
+ if not pmid:
1101
+ return ''
1102
+ root = efetch_ids([pmid], api_key=api_key, email=email, session=session)
1103
+ records = [child for child in (root if root is not None else [])
1104
+ if child.tag in {'PubmedArticle', 'PubmedBookArticle'}]
1105
+ return _article_ids(records[0])['pmcid'] if records else ''
1106
+
1107
+
1108
+ def _https_urls(url: str) -> list[str]:
1109
+ """Rewrite an NCBI FTP link to the HTTPS locations that may serve it.
1110
+
1111
+ The open-access service still advertises ``ftp://`` links, which the
1112
+ :mod:`requests`-based downloaders cannot fetch. NCBI moved the article
1113
+ datasets in 2026 and left the previous tree under a ``deprecated``
1114
+ directory that it has announced it will remove, so both the current path
1115
+ and that mirror are offered. Whichever one NCBI is serving answers; the
1116
+ other returns a cheap 404.
1117
+
1118
+ Parameters
1119
+ ----------
1120
+ url : str
1121
+ Link advertised by the open-access service.
1122
+
1123
+ Returns
1124
+ -------
1125
+ list[str]
1126
+ HTTPS candidates in the order they should be tried, or the original
1127
+ value alone when it is not an NCBI FTP link.
1128
+ """
1129
+ if not url.startswith(FTP_PREFIX):
1130
+ return [url]
1131
+ path = url[len(FTP_PREFIX):].lstrip('/')
1132
+ return [f'{HTTPS_PREFIX}/deprecated/{path}', f'{HTTPS_PREFIX}/{path}']
1133
+
1134
+
1135
+ def oa_package_urls(pmcid: str,
1136
+ session: provider.HTTPClient | None = None,
1137
+ api_key: str | None = None,
1138
+ email: str = '',
1139
+ timeout: float = 60) -> list[str]:
1140
+ """List the open-access service's links for a PubMed Central record.
1141
+
1142
+ Only the open-access subset is redistributable, so a record outside it
1143
+ yields no links rather than an error worth retrying.
1144
+
1145
+ Parameters
1146
+ ----------
1147
+ pmcid : str
1148
+ PubMed Central identifier.
1149
+ session : provider.HTTPClient or None, optional
1150
+ HTTP client exposing a ``get`` method.
1151
+ api_key : str or None, optional
1152
+ NCBI API key to attach.
1153
+ email : str, default=''
1154
+ Contact email address sent with the request.
1155
+ timeout : int or float, default=60
1156
+ Request timeout in seconds.
1157
+
1158
+ Returns
1159
+ -------
1160
+ list[str]
1161
+ HTTPS links, PDF links first, or an empty list when none are offered.
1162
+
1163
+ Raises
1164
+ ------
1165
+ RuntimeError
1166
+ If the open-access request cannot be completed.
1167
+ """
1168
+ identifier = normalize_pmcid(pmcid)
1169
+ if not identifier:
1170
+ return []
1171
+ root = request_xml(OA_URL, params={'id': identifier}, api_key=api_key,
1172
+ email=email, session=session, timeout=timeout)
1173
+ if root is None:
1174
+ return []
1175
+ pdfs, packages = [], []
1176
+ for link in root.findall('.//record/link'):
1177
+ href = (link.get('href') or '').strip()
1178
+ if not href:
1179
+ continue
1180
+ target = pdfs if (link.get('format') or '').lower() == 'pdf' else packages
1181
+ target.extend(_https_urls(href))
1182
+ return list(dict.fromkeys(pdfs + packages))
1183
+
1184
+
1185
+ def _jats_blocks(node: ET.Element, blocks: list[str]) -> None:
1186
+ """Collect prose blocks from a JATS subtree in document order.
1187
+
1188
+ Tables, figures, reference lists, and supplementary material are skipped
1189
+ whole so the stored text is prose rather than markup residue.
1190
+
1191
+ Parameters
1192
+ ----------
1193
+ node : xml.etree.ElementTree.Element
1194
+ Subtree to walk.
1195
+ blocks : list[str]
1196
+ Accumulator appended to in place.
1197
+
1198
+ Returns
1199
+ -------
1200
+ None
1201
+ Blocks are appended to ``blocks``.
1202
+ """
1203
+ for child in node:
1204
+ if child.tag in JATS_SKIP_TAGS:
1205
+ continue
1206
+ if child.tag in {'title', 'p'}:
1207
+ text = _element_text(child)
1208
+ if text:
1209
+ blocks.append(text)
1210
+ continue
1211
+ _jats_blocks(child, blocks)
1212
+
1213
+
1214
+ def _jats_body_text(root: ET.Element) -> str:
1215
+ """Flatten a JATS body into section and paragraph text.
1216
+
1217
+ Parameters
1218
+ ----------
1219
+ root : xml.etree.ElementTree.Element
1220
+ Parsed JATS article.
1221
+
1222
+ Returns
1223
+ -------
1224
+ str
1225
+ Section titles and paragraphs separated by blank lines.
1226
+ """
1227
+ body = root.find('.//body')
1228
+ if body is None:
1229
+ return ''
1230
+ blocks: list[str] = []
1231
+ _jats_blocks(body, blocks)
1232
+ return '\n\n'.join(blocks)
1233
+
1234
+
1235
+ def pmc_full_text(pmcid: str,
1236
+ api_key: str | None = None,
1237
+ email: str = '',
1238
+ session: provider.HTTPClient | None = None) -> str:
1239
+ """Fetch and flatten a PubMed Central open-access record to plain text.
1240
+
1241
+ Parameters
1242
+ ----------
1243
+ pmcid : str
1244
+ PubMed Central identifier.
1245
+ api_key : str or None, optional
1246
+ NCBI API key to attach.
1247
+ email : str, default=''
1248
+ Contact email address sent with the request.
1249
+ session : provider.HTTPClient or None, optional
1250
+ HTTP client exposing a ``get`` method.
1251
+
1252
+ Returns
1253
+ -------
1254
+ str
1255
+ Article text, or an empty string when no body is available.
1256
+
1257
+ Raises
1258
+ ------
1259
+ RuntimeError
1260
+ If the E-utilities request cannot be completed.
1261
+ """
1262
+ identifier = normalize_pmcid(pmcid)
1263
+ if not identifier:
1264
+ return ''
1265
+ root = efetch_ids([identifier[3:]], db='pmc', api_key=api_key, email=email, session=session)
1266
+ if root is None:
1267
+ return ''
1268
+ title = _element_text(root.find('.//article-title'))
1269
+ body = _jats_body_text(root)
1270
+ if not body:
1271
+ return ''
1272
+ return f'{title}\n\n{body}'.strip() if title else body