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,877 @@
1
+ """Search Elsevier/Scopus, CORE, OpenAlex, PubMed, arXiv, medRxiv, bioRxiv, and chemRxiv, then merge results into the paper corpus.
2
+
3
+ The functions here translate provider-specific API responses into PaperMinerToolkit's
4
+ small public paper schema and append or update rows without duplicating papers
5
+ that appear in multiple sources.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import datetime
11
+ import html
12
+ import sqlite3
13
+ from collections.abc import Callable, Iterable, Mapping
14
+ from types import ModuleType
15
+ from typing import Any
16
+ import pandas as pd
17
+ import re
18
+ from tqdm import tqdm
19
+
20
+ from paperminertoolkit.providers import (arxiv, biorxiv, chemrxiv, core, elsevier, medrxiv,
21
+ openalex, pubmed)
22
+ from paperminertoolkit.workflows.enrichment import enrich_papers
23
+ from paperminertoolkit.corpus.database import PAPER_FIELDS, add_asset, connect, find_paper, normalize_paper, upsert_paper, upsert_papers
24
+ from paperminertoolkit.providers import registry as sources
25
+
26
+ SEARCH_SOURCES = {'all', *sources.names(sources.SEARCH)}
27
+ SEARCH_FIELDS = PAPER_FIELDS + ['abstract']
28
+
29
+
30
+ def _recast_elsevier_records(records: Iterable[Mapping[str, Any]]) -> pd.DataFrame:
31
+ """Flatten common one-item Elsevier list fields into scalar DataFrame values."""
32
+ rows = []
33
+ for record in records:
34
+ row = {}
35
+ for key, value in record.items():
36
+ row[key] = value if key == 'link' else _first(value)
37
+ rows.append(row)
38
+ return pd.DataFrame(rows)
39
+
40
+
41
+ def _document_search(query: str,
42
+ index: str = 'scopus',
43
+ count: int = 200,
44
+ get_all: bool = True,
45
+ search_fields: str = 'TITLE-ABS-KEY') -> pd.DataFrame:
46
+ """Search Elsevier and return raw provider records.
47
+
48
+ This is a small replacement for the Elsapy search helper so PaperMinerToolkit can
49
+ control pagination and treat ``count`` as a hard result cap.
50
+
51
+ Parameters
52
+ ----------
53
+ query : str
54
+ Search expression.
55
+ index : str, default='scopus'
56
+ Elsevier index to search.
57
+ count : int, default=200
58
+ Maximum number of records to return.
59
+ get_all : bool, default=True
60
+ Whether to follow provider pagination links.
61
+ search_fields : str, default='TITLE-ABS-KEY'
62
+ Elsevier fields in which to evaluate ``query``.
63
+
64
+ Returns
65
+ -------
66
+ pandas.DataFrame
67
+ Raw Elsevier records capped at ``count`` rows.
68
+
69
+ Raises
70
+ ------
71
+ ValueError
72
+ If no Elsevier API key is configured.
73
+ RuntimeError
74
+ If an Elsevier request cannot be completed.
75
+ """
76
+ api_key = elsevier.configured_api_key()
77
+ max_results = max(int(count), 1)
78
+ page_size = min(max_results, 200)
79
+ index = index.lower()
80
+ url = elsevier.search_url(index, query, page_size, search_fields)
81
+ api_response = elsevier.request_json(url, api_key) or {}
82
+ tot_num_res = elsevier.total_results(api_response)
83
+ target_results = min(tot_num_res, max_results)
84
+ print('Document search is retrieving', target_results, 'of', tot_num_res, 'results.')
85
+ if tot_num_res == 0:
86
+ return pd.DataFrame()
87
+ results = elsevier.parse_records(api_response)
88
+ if get_all:
89
+ with tqdm(total=target_results, desc='Searching Scopus', colour='blue') as pbar:
90
+ pbar.update(min(len(results), target_results))
91
+ upper_limit_reached = False
92
+ while (len(results) < target_results) and not upper_limit_reached:
93
+ next_url = elsevier.next_page_url(api_response)
94
+ if not next_url:
95
+ break
96
+ api_response = elsevier.request_json(next_url, api_key) or {}
97
+ next_results = elsevier.parse_records(api_response)
98
+ remaining = target_results - len(results)
99
+ results += next_results[:remaining]
100
+ if len(results) >= 5000 and index != 'scopus':
101
+ upper_limit_reached = True
102
+ pbar.update(min(len(next_results), remaining))
103
+ else:
104
+ results = results[:target_results]
105
+ return _recast_elsevier_records(results)
106
+
107
+
108
+ def _first(value: object) -> object:
109
+ """Return the first item from a list-like provider value, or the value itself."""
110
+ if isinstance(value, list):
111
+ return value[0] if value else ''
112
+ return value or ''
113
+
114
+
115
+ def _elsevier_link(value: object) -> object:
116
+ """Return the full-text Elsevier link when present, otherwise the first link value."""
117
+ if isinstance(value, list):
118
+ for item in value:
119
+ if isinstance(item, dict):
120
+ ref = str(item.get('@ref') or item.get('ref') or '').lower()
121
+ href = item.get('@href') or item.get('href') or ''
122
+ if href and ('full-text' in ref or 'full-text' in str(href).lower()):
123
+ return href
124
+ return _elsevier_link(_first(value))
125
+ if isinstance(value, dict):
126
+ return value.get('@href') or value.get('href') or value.get('url') or ''
127
+ return value or ''
128
+
129
+
130
+ def _clean_search_abstract(value: object) -> str:
131
+ """Normalize a search-result abstract to compact plain text."""
132
+ if value is None:
133
+ return ''
134
+ if isinstance(value, list):
135
+ value = ' '.join(str(part) for part in value if part)
136
+ text = html.unescape(str(value))
137
+ text = re.sub(r'<[^>]+>', ' ', text)
138
+ text = re.sub(r'\s+', ' ', text).strip()
139
+ return text
140
+
141
+
142
+ def _abstract_from_search_record(record: Mapping[str, Any]) -> str:
143
+ """Extract an abstract-like field from one provider search record."""
144
+ for key in ['abstract', 'dc:description', 'description', 'dcDescription']:
145
+ abstract = _clean_search_abstract(record.get(key))
146
+ if abstract:
147
+ return abstract
148
+ return ''
149
+
150
+
151
+ def _elsevier_rows(results: pd.DataFrame) -> pd.DataFrame:
152
+ """Convert raw Elsevier search records into normalized paper rows."""
153
+ rows = []
154
+ for _, paper in results.iterrows():
155
+ row = {
156
+ 'paper_id': paper.get('dc:identifier') or paper.get('eid') or '',
157
+ 'doi': paper.get('prism:doi') or '',
158
+ 'title': paper.get('dc:title') or '',
159
+ 'journal': paper.get('prism:publicationName') or '',
160
+ 'publication_date': paper.get('prism:coverDate') or '',
161
+ 'authors': paper.get('dc:creator') or paper.get('creator') or '',
162
+ 'sources': 'elsevier',
163
+ 'elsevier_link': _elsevier_link(paper.get('link')),
164
+ 'metadata_status': 'retrieved',
165
+ }
166
+ normalized = normalize_paper(row)
167
+ normalized['abstract'] = _abstract_from_search_record(paper)
168
+ rows.append(normalized)
169
+ return pd.DataFrame(rows, columns=SEARCH_FIELDS)
170
+
171
+
172
+ def _core_rows(works: Iterable[Mapping[str, Any]]) -> pd.DataFrame:
173
+ """Convert CORE work records into normalized paper rows.
174
+
175
+ Parameters
176
+ ----------
177
+ works : Iterable[Mapping[str, Any]]
178
+ CORE work records.
179
+
180
+ Returns
181
+ -------
182
+ pandas.DataFrame
183
+ Normalized paper rows.
184
+ """
185
+ rows = []
186
+ for work in works:
187
+ record = core.work_to_paper(work)
188
+ normalized = normalize_paper(record)
189
+ normalized['abstract'] = _clean_search_abstract(record.get('abstract'))
190
+ rows.append(normalized)
191
+ return pd.DataFrame(rows, columns=SEARCH_FIELDS)
192
+
193
+
194
+ def core_search(query: str, count: int = 200) -> pd.DataFrame:
195
+ """Search CORE works.
196
+
197
+ CORE pages by offset and reports a total, so the walk stops at whichever
198
+ comes first: the caller's count, the reported total, or a short page.
199
+
200
+ Parameters
201
+ ----------
202
+ query : str
203
+ Search expression.
204
+ count : int, default=200
205
+ Maximum number of records to return.
206
+
207
+ Returns
208
+ -------
209
+ pandas.DataFrame
210
+ Normalized paper rows capped at ``count`` records.
211
+
212
+ Raises
213
+ ------
214
+ RuntimeError
215
+ If a CORE request cannot be completed.
216
+ """
217
+ api_key = core.configured_api_key()
218
+ works: list[Mapping[str, Any]] = []
219
+ offset = 0
220
+ with tqdm(total=count, desc='Searching CORE', colour='cyan') as pbar:
221
+ while len(works) < count:
222
+ payload = core.search_page(query, limit=min(core.PAGE_SIZE, count - len(works)),
223
+ offset=offset, api_key=api_key)
224
+ results = core.parse_records(payload)
225
+ if not results:
226
+ break
227
+ works.extend(results)
228
+ offset += len(results)
229
+ pbar.update(len(results))
230
+ total = core.total_results(payload)
231
+ if total and offset >= total:
232
+ break
233
+ if len(results) < min(core.PAGE_SIZE, count - len(works) + len(results)):
234
+ break
235
+ return _core_rows(works)
236
+
237
+
238
+ def _openalex_rows(works: Iterable[Mapping[str, Any]]) -> pd.DataFrame:
239
+ """Convert OpenAlex work records into normalized paper rows."""
240
+ rows = []
241
+ for work in works:
242
+ normalized = normalize_paper(openalex.work_to_paper(work))
243
+ abstract = openalex.reconstruct_abstract(work.get('abstract_inverted_index'))
244
+ normalized['abstract'] = _clean_search_abstract(abstract)
245
+ rows.append(normalized)
246
+ return pd.DataFrame(rows, columns=SEARCH_FIELDS)
247
+
248
+
249
+ def openalex_search(query: str, count: int = 200) -> pd.DataFrame:
250
+ """Search OpenAlex works.
251
+
252
+ Parameters
253
+ ----------
254
+ query : str
255
+ Search expression.
256
+ count : int, default=200
257
+ Maximum number of records to return.
258
+
259
+ Returns
260
+ -------
261
+ pandas.DataFrame
262
+ Normalized paper rows capped at ``count`` records.
263
+
264
+ Raises
265
+ ------
266
+ RuntimeError
267
+ If an OpenAlex request cannot be completed.
268
+ """
269
+ api_key = openalex.configured_api_key()
270
+ per_page = min(max(int(count), 1), 200)
271
+ params = {'search': query, 'per-page': per_page, 'cursor': '*'}
272
+ works = []
273
+ with tqdm(total=count, desc='Searching OpenAlex', colour='green') as pbar:
274
+ while len(works) < count:
275
+ params['per-page'] = min(per_page, count - len(works))
276
+ payload = openalex.request_json(openalex.WORKS_URL, params=params, api_key=api_key) or {}
277
+ results = payload.get('results') or []
278
+ if not results:
279
+ break
280
+ works.extend(results)
281
+ pbar.update(len(results))
282
+ next_cursor = (payload.get('meta') or {}).get('next_cursor')
283
+ if not next_cursor:
284
+ break
285
+ params['cursor'] = next_cursor
286
+ return _openalex_rows(works)
287
+
288
+
289
+ def _pubmed_rows(articles: Iterable[Mapping[str, Any]]) -> pd.DataFrame:
290
+ """Convert PubMed article records into normalized paper rows."""
291
+ rows = []
292
+ for article in articles:
293
+ normalized = normalize_paper(article)
294
+ normalized['abstract'] = _clean_search_abstract(article.get('abstract'))
295
+ rows.append(normalized)
296
+ return pd.DataFrame(rows, columns=SEARCH_FIELDS)
297
+
298
+
299
+ def pubmed_search(query: str, count: int = 200) -> pd.DataFrame:
300
+ """Search PubMed records.
301
+
302
+ PubMed exposes only the first 10000 matches for any query, so a larger
303
+ corpus needs the query split by date range. The shortfall is printed rather
304
+ than passed over silently.
305
+
306
+ Parameters
307
+ ----------
308
+ query : str
309
+ Search expression.
310
+ count : int, default=200
311
+ Maximum number of records to return.
312
+
313
+ Returns
314
+ -------
315
+ pandas.DataFrame
316
+ Normalized paper rows capped at ``count`` records.
317
+
318
+ Raises
319
+ ------
320
+ RuntimeError
321
+ If a PubMed request cannot be completed.
322
+ """
323
+ api_key = pubmed.configured_api_key()
324
+ email = pubmed.configured_email()
325
+ webenv, query_key, total = pubmed.esearch_history(query, api_key=api_key, email=email)
326
+ reachable = min(total, pubmed.MAX_SEARCH_RESULTS)
327
+ target = min(max(int(count), 0), reachable)
328
+ if total > pubmed.MAX_SEARCH_RESULTS:
329
+ print(f'PubMed matched {total} records but exposes only the first '
330
+ f'{pubmed.MAX_SEARCH_RESULTS}; narrow the query by date to reach the rest.')
331
+ if not target or not webenv or not query_key:
332
+ return _pubmed_rows([])
333
+ articles = []
334
+ with tqdm(total=target, desc='Searching PubMed', colour='magenta') as pbar:
335
+ while len(articles) < target:
336
+ page = pubmed.parse_articles(pubmed.efetch_history(
337
+ webenv,
338
+ query_key,
339
+ retstart=len(articles),
340
+ retmax=min(pubmed.EFETCH_BATCH_SIZE, target - len(articles)),
341
+ api_key=api_key,
342
+ email=email,
343
+ ))
344
+ if not page:
345
+ break
346
+ articles.extend(page)
347
+ pbar.update(len(page))
348
+ return _pubmed_rows(articles[:target])
349
+
350
+
351
+ def _arxiv_rows(entries: Iterable[Mapping[str, Any]]) -> pd.DataFrame:
352
+ """Convert arXiv entry records into normalized paper rows."""
353
+ rows = []
354
+ for entry in entries:
355
+ normalized = normalize_paper(entry)
356
+ normalized['abstract'] = _clean_search_abstract(entry.get('abstract'))
357
+ rows.append(normalized)
358
+ return pd.DataFrame(rows, columns=SEARCH_FIELDS)
359
+
360
+
361
+ def arxiv_search(query: str, count: int = 200) -> pd.DataFrame:
362
+ """Search arXiv records.
363
+
364
+ A plain phrase is translated into arXiv's fielded query language by
365
+ :func:`paperminertoolkit.providers.arxiv.query_expression`; a native arXiv expression is
366
+ used as written. Results are ordered by submission date rather than by
367
+ relevance so that paging is stable, because relevance ordering can shift
368
+ between the requests that make up one page walk. Entries are deduplicated
369
+ by identifier for the same reason: arXiv repeats records across page
370
+ boundaries often enough to inflate a naive count.
371
+
372
+ arXiv exposes only the first 30000 matches for any query, so a larger
373
+ corpus needs the query split by category or date. The shortfall is printed
374
+ rather than passed over silently.
375
+
376
+ Parameters
377
+ ----------
378
+ query : str
379
+ Search expression, either a plain phrase or a native arXiv query.
380
+ count : int, default=200
381
+ Maximum number of records to return.
382
+
383
+ Returns
384
+ -------
385
+ pandas.DataFrame
386
+ Normalized paper rows capped at ``count`` records.
387
+
388
+ Raises
389
+ ------
390
+ RuntimeError
391
+ If an arXiv request cannot be completed.
392
+ """
393
+ expression = arxiv.query_expression(query)
394
+ target = max(int(count), 0)
395
+ if not expression or not target:
396
+ return _arxiv_rows([])
397
+ entries: list[Mapping[str, Any]] = []
398
+ seen: set[str] = set()
399
+ offset = 0
400
+ reachable = 0
401
+ reported = False
402
+ with tqdm(total=target, desc='Searching arXiv', colour='yellow') as pbar:
403
+ while len(entries) < target:
404
+ root = arxiv.search_page(expression, start=offset,
405
+ max_results=min(arxiv.PAGE_SIZE, target - len(entries)))
406
+ page = arxiv.parse_entries(root)
407
+ if not reported:
408
+ total = arxiv.total_results(root)
409
+ if total > arxiv.MAX_SEARCH_RESULTS:
410
+ print(f'arXiv matched {total} records but exposes only the first '
411
+ f'{arxiv.MAX_SEARCH_RESULTS}; narrow the query by category or date '
412
+ f'to reach the rest.')
413
+ reachable = min(total, arxiv.MAX_SEARCH_RESULTS)
414
+ target = min(target, reachable)
415
+ pbar.total = target
416
+ reported = True
417
+ if not page:
418
+ break
419
+ # Advance by what arXiv returned, not by what survived deduplication,
420
+ # so a page of repeats still moves the cursor forward.
421
+ offset += len(page)
422
+ for entry in page:
423
+ identifier = str(entry.get('arxiv_id') or entry.get('paper_id') or '')
424
+ if identifier and identifier in seen:
425
+ continue
426
+ if identifier:
427
+ seen.add(identifier)
428
+ entries.append(entry)
429
+ pbar.update(1)
430
+ if len(entries) >= target:
431
+ break
432
+ # Stop once the walk has passed everything arXiv reports, so a run
433
+ # of duplicate pages cannot keep the loop going indefinitely.
434
+ if offset >= reachable:
435
+ break
436
+ return _arxiv_rows(entries[:target])
437
+
438
+
439
+ def _rxiv_rows(entries: Iterable[Mapping[str, Any]]) -> pd.DataFrame:
440
+ """Convert preprint-server records into normalized paper rows."""
441
+ rows = []
442
+ for entry in entries:
443
+ normalized = normalize_paper(entry)
444
+ normalized['abstract'] = _clean_search_abstract(entry.get('abstract'))
445
+ rows.append(normalized)
446
+ return pd.DataFrame(rows, columns=SEARCH_FIELDS)
447
+
448
+
449
+ def _medrxiv_rows(entries: Iterable[Mapping[str, Any]]) -> pd.DataFrame:
450
+ """Convert medRxiv records into normalized paper rows."""
451
+ return _rxiv_rows(entries)
452
+
453
+
454
+ def _biorxiv_rows(entries: Iterable[Mapping[str, Any]]) -> pd.DataFrame:
455
+ """Convert bioRxiv records into normalized paper rows."""
456
+ return _rxiv_rows(entries)
457
+
458
+
459
+ def _chemrxiv_rows(entries: Iterable[Mapping[str, Any]]) -> pd.DataFrame:
460
+ """Convert chemRxiv records into normalized paper rows."""
461
+ return _rxiv_rows(entries)
462
+
463
+
464
+ def _rxiv_search(provider: ModuleType,
465
+ label: str,
466
+ query: str,
467
+ count: int = 200,
468
+ today: str = '') -> pd.DataFrame:
469
+ """Answer a query by walking a preprint server's posting archive.
470
+
471
+ medRxiv and bioRxiv are one service answering under two names, with the
472
+ same endpoints, paging rules, record shape, and absence of a search route,
473
+ so one walk serves both and is parameterized by the provider module rather
474
+ than written twice. Everything server-specific -- the hosts, the page
475
+ widths, the archive start, and the scan limit -- is read off ``provider``.
476
+
477
+ Parameters
478
+ ----------
479
+ provider : types.ModuleType
480
+ :mod:`paperminertoolkit.providers.medrxiv` or :mod:`paperminertoolkit.providers.biorxiv`.
481
+ label : str
482
+ Server name as it should appear in progress and summary messages.
483
+ query : str
484
+ Search phrase, optionally carrying ``category:``, ``from:``, or ``to:``
485
+ scope terms.
486
+ count : int, default=200
487
+ Maximum number of records to return.
488
+ today : str, default=''
489
+ Interval end used when the query names none, as ``YYYY-MM-DD``.
490
+ Defaults to the current UTC date.
491
+
492
+ Returns
493
+ -------
494
+ pandas.DataFrame
495
+ Normalized paper rows capped at ``count`` records.
496
+
497
+ Raises
498
+ ------
499
+ ValueError
500
+ If a scope term in ``query`` is not an ISO ``YYYY-MM-DD`` date.
501
+ RuntimeError
502
+ If a request to the server cannot be completed.
503
+ """
504
+ terms, scope = provider.parse_query(query)
505
+ target = max(int(count), 0)
506
+ if not target:
507
+ return _rxiv_rows([])
508
+ category = scope.get('category', '')
509
+ start = scope.get('from', provider.CORPUS_START)
510
+ end = scope.get('to') or today or datetime.datetime.now(datetime.UTC).strftime('%Y-%m-%d')
511
+ first = provider.interval_page(start, end, category=category)
512
+ total = provider.total_results(first)
513
+ step = provider.page_size(first, provider.endpoint(category)[1])
514
+ if not total:
515
+ return _rxiv_rows([])
516
+ print(f'{label} has no search endpoint, so PaperMinerToolkit is reading the {total} postings '
517
+ f'between {start} and {end}'
518
+ f'{f" filed under {category}" if category else ""}, newest first, and matching them '
519
+ f'locally. Add category:, from:, or to: terms to the query to read fewer.')
520
+ matched: list[Mapping[str, Any]] = []
521
+ papers: list[Mapping[str, Any]] = []
522
+ scanned = 0
523
+ unread = 0
524
+ with tqdm(total=target, desc=f'Searching {label}', colour='yellow') as pbar:
525
+ for cursor in provider.page_cursors(total, step):
526
+ # The first page was already fetched to learn the record count, so
527
+ # it is reused rather than requested again when the walk reaches it.
528
+ payload = first if cursor == 0 else provider.interval_page(
529
+ start, end, cursor=cursor, category=category)
530
+ page = provider.parse_records(payload)
531
+ if not page:
532
+ continue
533
+ scanned += len(page)
534
+ # Pages run oldest first with no way to reverse them at the API, so
535
+ # each one is reversed as it arrives to keep the walk newest first.
536
+ matched.extend(entry for entry in reversed(page) if provider.matches(entry, terms))
537
+ # Versions of one preprint are separate records that can fall on
538
+ # different pages, so papers are collapsed against everything
539
+ # matched so far rather than within a page.
540
+ papers = provider.latest_versions(matched)
541
+ pbar.n = min(len(papers), target)
542
+ pbar.refresh()
543
+ if len(papers) >= target:
544
+ break
545
+ if scanned >= provider.MAX_SCAN_RECORDS:
546
+ # Cursors count records, so the cursor of the page that tripped
547
+ # the limit is exactly how many older postings go unread.
548
+ unread = cursor
549
+ break
550
+ print(f'{label} matched {len(papers)} papers in {scanned} postings read.')
551
+ if unread:
552
+ print(f'{unread} older postings in {start} to {end} were left unread after the '
553
+ f'{provider.MAX_SCAN_RECORDS}-posting scan limit; narrow the query with '
554
+ f'category:, from:, or to: terms to reach them.')
555
+ return _rxiv_rows(papers[:target])
556
+
557
+
558
+ def medrxiv_search(query: str, count: int = 200, today: str = '') -> pd.DataFrame:
559
+ """Search medRxiv records.
560
+
561
+ medRxiv publishes no search endpoint, so the query is answered by walking
562
+ the posting archive and matching each record locally. The walk runs newest
563
+ first and stops as soon as ``count`` papers match, which keeps an ordinary
564
+ query cheap; a term that matches nothing recent is what makes it expensive,
565
+ so the size of the archive being scanned is printed before the walk starts
566
+ rather than discovered as a hang.
567
+
568
+ The query string carries its own scope, because narrowing the walk is the
569
+ only way to bound it: ``category:``, ``from:``, and ``to:`` restrict the
570
+ archive that is read, and everything else is a match term. Terms are
571
+ combined with ``AND`` over each record's title, abstract, authors, and
572
+ category.
573
+
574
+ One search reads at most :data:`paperminertoolkit.providers.medrxiv.MAX_SCAN_RECORDS`
575
+ postings. That bound is what keeps ``--source all`` usable: a query aimed
576
+ at another provider's subject matter matches nothing here, and without a
577
+ stop it would read the entire archive before reporting nothing found. The
578
+ shortfall is printed rather than passed over silently.
579
+
580
+ Parameters
581
+ ----------
582
+ query : str
583
+ Search phrase, optionally carrying ``category:``, ``from:``, or ``to:``
584
+ scope terms.
585
+ count : int, default=200
586
+ Maximum number of records to return.
587
+ today : str, default=''
588
+ Interval end used when the query names none, as ``YYYY-MM-DD``.
589
+ Defaults to the current UTC date.
590
+
591
+ Returns
592
+ -------
593
+ pandas.DataFrame
594
+ Normalized paper rows capped at ``count`` records.
595
+
596
+ Raises
597
+ ------
598
+ ValueError
599
+ If a scope term in ``query`` is not an ISO ``YYYY-MM-DD`` date.
600
+ RuntimeError
601
+ If a medRxiv request cannot be completed.
602
+ """
603
+ return _rxiv_search(medrxiv, 'medRxiv', query, count=count, today=today)
604
+
605
+
606
+ def biorxiv_search(query: str, count: int = 200, today: str = '') -> pd.DataFrame:
607
+ """Search bioRxiv records.
608
+
609
+ bioRxiv answers a query exactly as medRxiv does, by the same archive walk
610
+ over the same endpoints, so :func:`medrxiv_search` describes the mechanism
611
+ and the ``category:``, ``from:``, and ``to:`` scope terms in full.
612
+
613
+ What differs is scale. bioRxiv has been accepting preprints since November
614
+ 2013 and holds several times what medRxiv does, so an unscoped walk is
615
+ correspondingly longer and the
616
+ :data:`paperminertoolkit.providers.biorxiv.MAX_SCAN_RECORDS` limit is correspondingly
617
+ likelier to be what ends it. Naming a category or a date range is the
618
+ difference between a search of a subject and a read of the archive.
619
+
620
+ Parameters
621
+ ----------
622
+ query : str
623
+ Search phrase, optionally carrying ``category:``, ``from:``, or ``to:``
624
+ scope terms.
625
+ count : int, default=200
626
+ Maximum number of records to return.
627
+ today : str, default=''
628
+ Interval end used when the query names none, as ``YYYY-MM-DD``.
629
+ Defaults to the current UTC date.
630
+
631
+ Returns
632
+ -------
633
+ pandas.DataFrame
634
+ Normalized paper rows capped at ``count`` records.
635
+
636
+ Raises
637
+ ------
638
+ ValueError
639
+ If a scope term in ``query`` is not an ISO ``YYYY-MM-DD`` date.
640
+ RuntimeError
641
+ If a bioRxiv request cannot be completed.
642
+ """
643
+ return _rxiv_search(biorxiv, 'bioRxiv', query, count=count, today=today)
644
+
645
+
646
+ def chemrxiv_search(query: str, count: int = 200) -> pd.DataFrame:
647
+ """Search chemRxiv records.
648
+
649
+ chemRxiv, unlike medRxiv and bioRxiv, publishes a search endpoint, so the
650
+ query is answered by the server rather than by reading the archive and
651
+ matching locally. Paging therefore works the way it does for arXiv: pages
652
+ are requested until ``count`` papers are held, and the cursor advances by
653
+ what the server returned rather than by what survived deduplication, so a
654
+ page of repeats still moves it forward.
655
+
656
+ The ``category:``, ``from:``, and ``to:`` scope terms are accepted with the
657
+ same spelling the other preprint sources use, but here they are forwarded
658
+ as ``categoryIds``, ``searchDateFrom``, and ``searchDateTo`` rather than
659
+ applied to records after reading them. Narrowing a chemRxiv query makes the
660
+ server do less work; it is not, as it is for the other two archives, the
661
+ only way to bound what gets read.
662
+
663
+ Each posted version of a chemRxiv preprint carries a DOI of its own, so
664
+ records are grouped by :func:`paperminertoolkit.providers.chemrxiv.chemrxiv_stem` and
665
+ reduced to the newest posting. That is done over everything read so far
666
+ rather than per page, because two versions of one preprint can fall on
667
+ either side of a page boundary.
668
+
669
+ chemRxiv exposes only the first
670
+ :data:`paperminertoolkit.providers.chemrxiv.MAX_SEARCH_RESULTS` matches for any query, so
671
+ a larger corpus needs the query split by category or date. The shortfall is
672
+ printed rather than passed over silently.
673
+
674
+ Parameters
675
+ ----------
676
+ query : str
677
+ Search phrase, optionally carrying ``category:``, ``from:``, or ``to:``
678
+ scope terms.
679
+ count : int, default=200
680
+ Maximum number of records to return.
681
+
682
+ Returns
683
+ -------
684
+ pandas.DataFrame
685
+ Normalized paper rows capped at ``count`` records.
686
+
687
+ Raises
688
+ ------
689
+ ValueError
690
+ If a scope term in ``query`` is not an ISO ``YYYY-MM-DD`` date, or
691
+ names a category chemRxiv does not file preprints under.
692
+ RuntimeError
693
+ If a chemRxiv request cannot be completed.
694
+ """
695
+ terms, scope = chemrxiv.parse_query(query)
696
+ target = max(int(count), 0)
697
+ if not target:
698
+ return _chemrxiv_rows([])
699
+ term = chemrxiv.search_terms(terms)
700
+ category = scope.get('category', '')
701
+ category_id = chemrxiv.category_ids([category])[0] if category else ''
702
+ entries: list[Mapping[str, Any]] = []
703
+ papers: list[Mapping[str, Any]] = []
704
+ seen: set[str] = set()
705
+ skip = 0
706
+ reachable = 0
707
+ reported = False
708
+ with tqdm(total=target, desc='Searching chemRxiv', colour='yellow') as pbar:
709
+ while len(papers) < target:
710
+ payload = chemrxiv.search_page(term=term, skip=skip,
711
+ limit=min(chemrxiv.PAGE_SIZE, target - len(papers)),
712
+ category_id=category_id,
713
+ date_from=scope.get('from', ''),
714
+ date_to=scope.get('to', ''))
715
+ page = chemrxiv.parse_records(payload)
716
+ if not reported:
717
+ total = chemrxiv.total_results(payload)
718
+ if total > chemrxiv.MAX_SEARCH_RESULTS:
719
+ print(f'chemRxiv matched {total} records but exposes only the first '
720
+ f'{chemrxiv.MAX_SEARCH_RESULTS}; narrow the query with category:, '
721
+ f'from:, or to: terms to reach the rest.')
722
+ reachable = min(total, chemrxiv.MAX_SEARCH_RESULTS)
723
+ target = min(target, reachable)
724
+ pbar.total = target
725
+ reported = True
726
+ if not page:
727
+ break
728
+ # Advance by what chemRxiv returned, not by what survived
729
+ # deduplication, so a page of repeats still moves the cursor.
730
+ skip += len(page)
731
+ for entry in page:
732
+ identifier = str(entry.get('paper_id') or entry.get('chemrxiv_doi') or '')
733
+ if identifier and identifier in seen:
734
+ continue
735
+ if identifier:
736
+ seen.add(identifier)
737
+ entries.append(entry)
738
+ papers = chemrxiv.latest_versions(entries)
739
+ pbar.n = min(len(papers), target)
740
+ pbar.refresh()
741
+ # Stop once the walk has passed everything chemRxiv reports, so a
742
+ # run of duplicate pages cannot keep the loop going indefinitely.
743
+ if skip >= reachable:
744
+ break
745
+ return _chemrxiv_rows(papers[:target])
746
+
747
+
748
+ def _elsevier_search(query: str, count: int = 200) -> pd.DataFrame:
749
+ """Search Elsevier and map its records onto normalized paper rows.
750
+
751
+ Parameters
752
+ ----------
753
+ query : str
754
+ Search expression.
755
+ count : int, default=200
756
+ Maximum number of records to return.
757
+
758
+ Returns
759
+ -------
760
+ pandas.DataFrame
761
+ Normalized paper rows capped at ``count`` records.
762
+ """
763
+ return _elsevier_rows(_document_search(query, count=count))
764
+
765
+
766
+ def _source_search(name: str) -> Callable[..., pd.DataFrame]:
767
+ """Return the search function for one source.
768
+
769
+ The registry resolves the function by name at call time, so replacing a
770
+ module-level search function -- which is how tests stand a provider in --
771
+ takes effect without maintaining a second dispatch table here.
772
+
773
+ Parameters
774
+ ----------
775
+ name : str
776
+ Registry source name.
777
+
778
+ Returns
779
+ -------
780
+ Callable[..., pandas.DataFrame]
781
+ Function answering a query for that source.
782
+ """
783
+ return sources.resolve_handler(name, sources.SEARCH)
784
+
785
+
786
+ def _store_search_abstracts(
787
+ conn: sqlite3.Connection,
788
+ papers: Iterable[dict[str, Any]],
789
+ ) -> int:
790
+ """Store search-result abstracts as corpus assets and return the stored count."""
791
+ stored = 0
792
+ for paper in papers:
793
+ abstract = _clean_search_abstract(paper.get('abstract'))
794
+ if not abstract:
795
+ continue
796
+ matched = find_paper(conn, paper) or paper
797
+ source = paper.get('sources') or 'search'
798
+ add_asset(conn,
799
+ matched,
800
+ abstract,
801
+ role='abstract',
802
+ kind='text',
803
+ mime_type='text/plain',
804
+ source=source,
805
+ original_filename='abstract.txt')
806
+ matched['abstract_source'] = source
807
+ matched['abstract_download_status'] = 'succeeded'
808
+ upsert_paper(conn, matched)
809
+ stored += 1
810
+ return stored
811
+
812
+
813
+ def search_for_papers(query: str,
814
+ db_path: str = 'papers.db',
815
+ source: str = 'all',
816
+ count: int = 200,
817
+ store_abstract: bool = False,
818
+ enrich: bool = False) -> None:
819
+ """Search providers and merge results into a corpus.
820
+
821
+ Parameters
822
+ ----------
823
+ query : str
824
+ Search expression.
825
+ db_path : str, default='papers.db'
826
+ Path to the SQLite paper corpus.
827
+ source : {'all', 'core', 'elsevier', 'openalex', 'pubmed', 'arxiv', 'medrxiv', 'biorxiv', 'chemrxiv'}, default='all'
828
+ Provider or provider set to search.
829
+ count : int, default=200
830
+ Maximum number of records requested from each provider.
831
+ store_abstract : bool, default=False
832
+ Whether to store search-result abstracts as corpus assets.
833
+ enrich : bool, default=False
834
+ Whether to supplement stored rows with metadata from the configured
835
+ enrichment providers.
836
+
837
+ Returns
838
+ -------
839
+ None
840
+ Results are written directly to ``db_path``.
841
+
842
+ Raises
843
+ ------
844
+ ValueError
845
+ If ``source`` is unsupported or required provider configuration is
846
+ missing.
847
+ Exception
848
+ Whatever the provider raised, when exactly one source was selected. A
849
+ run over several sources reports a failing one and carries on with the
850
+ rest, because a partial corpus is more useful than none.
851
+ """
852
+ requested = sources.resolve_names([source], sources.SEARCH)
853
+ frames = []
854
+ for name in requested:
855
+ try:
856
+ frames.append(_source_search(name)(query, count=count))
857
+ except Exception as e:
858
+ if len(requested) == 1:
859
+ raise
860
+ print(f'{sources.SOURCES[name].label} search skipped: {e}')
861
+
862
+ new_papers = pd.concat(frames, ignore_index=True) if frames else pd.DataFrame(columns=SEARCH_FIELDS)
863
+ if new_papers.empty:
864
+ print('Document search found 0 new results.')
865
+ return
866
+ with connect(db_path) as conn:
867
+ records = new_papers.to_dict('records')
868
+ added, updated = upsert_papers(conn, records)
869
+ abstract_count = _store_search_abstracts(conn, records) if store_abstract else 0
870
+ enrichment_summary = enrich_papers(conn, records) if enrich else {}
871
+ print(f'Document search found {added} new results and updated {updated} existing rows.')
872
+ if store_abstract:
873
+ print(f'Stored {abstract_count} search-time abstracts.')
874
+ if enrich:
875
+ print(f'Enriched {enrichment_summary.get("succeeded", 0)} papers '
876
+ f'({enrichment_summary.get("partial", 0)} partial, '
877
+ f'{enrichment_summary.get("not_found", 0)} not found).')