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,1542 @@
1
+ """Store a compressed SQLite corpus of downloaded papers.
2
+
3
+ This module provides a small standalone corpus layer for PaperMinerToolkit. It stores
4
+ paper metadata, pipeline state, deduplicated text/PDF blobs, and paper-to-blob
5
+ links in SQLite without including the extracted materials table.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import gzip
11
+ import hashlib
12
+ import json
13
+ import math
14
+ import re
15
+ import sqlite3
16
+ from collections.abc import Iterable, Mapping
17
+ from datetime import datetime, timezone
18
+ from os import PathLike
19
+ from pathlib import Path
20
+ from typing import Any, TypeAlias
21
+
22
+
23
+ SCHEMA_VERSION = 10
24
+ SUPPORTED_COMPRESSIONS = {'none', 'gzip'}
25
+ PAPER_COLUMNS = [
26
+ 'paper_id',
27
+ 'doi',
28
+ 'title',
29
+ 'journal',
30
+ 'publication_date',
31
+ 'authors',
32
+ 'sources',
33
+ 'core_id',
34
+ 'pdf_url',
35
+ 'pdf_source',
36
+ 'text_source',
37
+ 'abstract_source',
38
+ 'elsevier_link',
39
+ 'pmid',
40
+ 'pmcid',
41
+ 'arxiv_id',
42
+ 'medrxiv_doi',
43
+ 'biorxiv_doi',
44
+ 'chemrxiv_doi',
45
+ ]
46
+ PIPELINE_COLUMNS = {
47
+ 'metadata_status': 'pending',
48
+ 'abstract_download_status': 'pending',
49
+ 'text_download_status': 'pending',
50
+ 'pdf_download_status': 'pending',
51
+ 'text_scrape_status': 'pending',
52
+ 'abstract_scrape_status': 'pending',
53
+ 'image_scrape_status': 'pending',
54
+ 'store_status': 'pending',
55
+ 'enrichment_status': 'pending',
56
+ 'text_path': '',
57
+ 'pdf_path': '',
58
+ 'image_dir': '',
59
+ 'num_images': 0,
60
+ 'num_text_materials': 0,
61
+ 'num_abstract_materials': 0,
62
+ 'num_image_materials': 0,
63
+ 'num_text_chunks': None,
64
+ 'num_abstract_chunks': None,
65
+ 'last_error': '',
66
+ }
67
+ PAPER_FIELDS = PAPER_COLUMNS + [column for column in PIPELINE_COLUMNS if column not in PAPER_COLUMNS]
68
+ ENRICHMENT_COLUMNS = {
69
+ 'openalex_id': 'TEXT',
70
+ 'publisher': 'TEXT',
71
+ 'work_type': 'TEXT',
72
+ 'volume': 'TEXT',
73
+ 'issue': 'TEXT',
74
+ 'pages': 'TEXT',
75
+ 'issn': 'TEXT',
76
+ 'issn_l': 'TEXT',
77
+ 'language': 'TEXT',
78
+ 'is_oa': 'INTEGER',
79
+ 'oa_status': 'TEXT',
80
+ 'license': 'TEXT',
81
+ 'is_retracted': 'INTEGER',
82
+ 'cited_by_count': 'INTEGER',
83
+ 'referenced_works_count': 'INTEGER',
84
+ 'enrichment_sources': 'TEXT',
85
+ 'enrichment_json': 'TEXT',
86
+ 'enriched_at': 'TEXT',
87
+ }
88
+ ENRICHMENT_FILL_COLUMNS = ['doi', 'title', 'journal', 'publication_date', 'authors',
89
+ 'pmid', 'pmcid', 'arxiv_id', 'medrxiv_doi', 'biorxiv_doi',
90
+ 'chemrxiv_doi']
91
+ AUTHOR_COLUMNS = [
92
+ 'paper_id', 'author_position', 'affiliation_rank', 'position_label', 'display_name',
93
+ 'given_name', 'family_name', 'orcid', 'is_corresponding', 'affiliation',
94
+ 'institution_name', 'institution_ror', 'institution_country', 'openalex_author_id', 'source',
95
+ ]
96
+ SUBJECT_COLUMNS = [
97
+ 'paper_id', 'scheme', 'subject_id', 'display_name', 'score', 'subject_rank',
98
+ 'level', 'is_primary', 'parent_field', 'parent_domain', 'source',
99
+ ]
100
+ REFERENCE_COLUMNS = [
101
+ 'paper_id', 'source', 'reference_rank', 'referenced_doi', 'referenced_openalex_id',
102
+ 'referenced_paper_id', 'referenced_title', 'unstructured',
103
+ ]
104
+ ENRICHMENT_CHILD_TABLES = {
105
+ 'paper_authors': AUTHOR_COLUMNS,
106
+ 'paper_subjects': SUBJECT_COLUMNS,
107
+ 'paper_references': REFERENCE_COLUMNS,
108
+ }
109
+ ENRICHMENT_STATUSES = frozenset({
110
+ 'pending',
111
+ 'succeeded',
112
+ 'partial',
113
+ 'not_found',
114
+ 'unresolved',
115
+ 'failed',
116
+ })
117
+ _Paper: TypeAlias = dict[str, Any]
118
+ _PaperInput: TypeAlias = Mapping[str, Any]
119
+ _BlobContent: TypeAlias = str | bytes | Path | Iterable[int]
120
+ _Asset: TypeAlias = dict[str, Any]
121
+
122
+
123
+ def utc_now() -> str:
124
+ """Return the current UTC timestamp.
125
+
126
+ Returns
127
+ -------
128
+ str
129
+ ISO-8601 timestamp with second precision.
130
+ """
131
+ return datetime.now(timezone.utc).isoformat(timespec='seconds')
132
+
133
+
134
+ def connect(db_path: str | PathLike[str]) -> sqlite3.Connection:
135
+ """Open and initialize a corpus database.
136
+
137
+ Parameters
138
+ ----------
139
+ db_path : str or os.PathLike[str]
140
+ SQLite database path.
141
+
142
+ Returns
143
+ -------
144
+ sqlite3.Connection
145
+ Configured connection with dictionary-like rows.
146
+
147
+ Raises
148
+ ------
149
+ RuntimeError
150
+ If the database schema is newer than this package supports.
151
+ """
152
+ conn = sqlite3.connect(db_path)
153
+ conn.row_factory = sqlite3.Row
154
+ init_corpus(conn)
155
+ return conn
156
+
157
+
158
+ def init_corpus(conn: sqlite3.Connection) -> None:
159
+ """Create or migrate the corpus schema.
160
+
161
+ Parameters
162
+ ----------
163
+ conn : sqlite3.Connection
164
+ Open corpus connection to initialize.
165
+
166
+ Raises
167
+ ------
168
+ RuntimeError
169
+ If the stored schema version is newer than the supported version.
170
+ """
171
+ conn.execute('PRAGMA foreign_keys = ON')
172
+ current_version = conn.execute('PRAGMA user_version').fetchone()[0]
173
+ if current_version > SCHEMA_VERSION:
174
+ raise RuntimeError(
175
+ f'Corpus schema version {current_version} is newer than supported version {SCHEMA_VERSION}.'
176
+ )
177
+ paper_columns = ',\n '.join(
178
+ f'{column} {column_type}' for column, column_type in _expected_paper_columns().items()
179
+ )
180
+ conn.executescript(
181
+ f"""
182
+ CREATE TABLE IF NOT EXISTS papers (
183
+ paper_id TEXT PRIMARY KEY,
184
+ {paper_columns},
185
+ metadata_json TEXT,
186
+ created_at TEXT NOT NULL,
187
+ updated_at TEXT NOT NULL
188
+ );
189
+
190
+ CREATE TABLE IF NOT EXISTS blobs (
191
+ blob_id TEXT PRIMARY KEY,
192
+ sha256 TEXT NOT NULL UNIQUE,
193
+ kind TEXT NOT NULL,
194
+ mime_type TEXT NOT NULL,
195
+ compression TEXT NOT NULL,
196
+ original_size INTEGER NOT NULL,
197
+ stored_size INTEGER NOT NULL,
198
+ content BLOB NOT NULL,
199
+ created_at TEXT NOT NULL
200
+ );
201
+
202
+ CREATE TABLE IF NOT EXISTS paper_assets (
203
+ paper_id TEXT NOT NULL,
204
+ blob_id TEXT NOT NULL,
205
+ role TEXT NOT NULL,
206
+ source TEXT,
207
+ original_filename TEXT,
208
+ created_at TEXT NOT NULL,
209
+ PRIMARY KEY (paper_id, role, source, original_filename),
210
+ FOREIGN KEY (paper_id) REFERENCES papers(paper_id) ON DELETE CASCADE,
211
+ FOREIGN KEY (blob_id) REFERENCES blobs(blob_id) ON DELETE CASCADE
212
+ );
213
+
214
+ CREATE INDEX IF NOT EXISTS idx_papers_doi ON papers(doi);
215
+ CREATE INDEX IF NOT EXISTS idx_blobs_sha256 ON blobs(sha256);
216
+ CREATE INDEX IF NOT EXISTS idx_assets_paper_role ON paper_assets(paper_id, role);
217
+
218
+ CREATE TABLE IF NOT EXISTS corpus_filters (
219
+ filter_id INTEGER PRIMARY KEY AUTOINCREMENT,
220
+ name TEXT NOT NULL UNIQUE,
221
+ method TEXT NOT NULL,
222
+ description TEXT NOT NULL DEFAULT '',
223
+ definition_json TEXT NOT NULL,
224
+ stack_position INTEGER NOT NULL,
225
+ join_operator TEXT,
226
+ created_at TEXT NOT NULL,
227
+ updated_at TEXT NOT NULL,
228
+ CHECK (join_operator IS NULL OR join_operator IN ('and', 'or'))
229
+ );
230
+
231
+ CREATE TABLE IF NOT EXISTS paper_filter_results (
232
+ filter_id INTEGER NOT NULL,
233
+ paper_id TEXT NOT NULL,
234
+ status TEXT NOT NULL,
235
+ evidence_json TEXT NOT NULL,
236
+ unavailable_reason TEXT NOT NULL DEFAULT '',
237
+ evaluated_at TEXT NOT NULL,
238
+ PRIMARY KEY (filter_id, paper_id),
239
+ FOREIGN KEY (filter_id) REFERENCES corpus_filters(filter_id) ON DELETE CASCADE,
240
+ FOREIGN KEY (paper_id) REFERENCES papers(paper_id) ON DELETE CASCADE,
241
+ CHECK (status IN ('included', 'excluded', 'unavailable'))
242
+ );
243
+
244
+ CREATE TABLE IF NOT EXISTS paper_filter_state (
245
+ paper_id TEXT PRIMARY KEY,
246
+ status TEXT NOT NULL,
247
+ expression TEXT NOT NULL,
248
+ updated_at TEXT NOT NULL,
249
+ FOREIGN KEY (paper_id) REFERENCES papers(paper_id) ON DELETE CASCADE,
250
+ CHECK (status IN ('included', 'excluded', 'unavailable'))
251
+ );
252
+
253
+ CREATE INDEX IF NOT EXISTS idx_corpus_filters_position
254
+ ON corpus_filters(stack_position);
255
+ CREATE INDEX IF NOT EXISTS idx_filter_results_status
256
+ ON paper_filter_results(filter_id, status);
257
+ CREATE INDEX IF NOT EXISTS idx_filter_state_status
258
+ ON paper_filter_state(status);
259
+
260
+ CREATE TABLE IF NOT EXISTS topic_models (
261
+ model_id TEXT PRIMARY KEY,
262
+ name TEXT NOT NULL UNIQUE,
263
+ artifact_path TEXT NOT NULL,
264
+ artifact_version INTEGER NOT NULL,
265
+ config_json TEXT NOT NULL,
266
+ training_corpus_fingerprint TEXT NOT NULL,
267
+ prediction_corpus_fingerprint TEXT NOT NULL,
268
+ text_fields_json TEXT NOT NULL,
269
+ created_at TEXT NOT NULL,
270
+ updated_at TEXT NOT NULL
271
+ );
272
+
273
+ CREATE TABLE IF NOT EXISTS topic_definitions (
274
+ model_id TEXT NOT NULL,
275
+ topic_id INTEGER NOT NULL,
276
+ topic_name TEXT NOT NULL DEFAULT '',
277
+ top_terms_json TEXT NOT NULL,
278
+ PRIMARY KEY (model_id, topic_id),
279
+ FOREIGN KEY (model_id) REFERENCES topic_models(model_id) ON DELETE CASCADE
280
+ );
281
+
282
+ CREATE TABLE IF NOT EXISTS paper_topic_predictions (
283
+ model_id TEXT NOT NULL,
284
+ paper_id TEXT NOT NULL,
285
+ status TEXT NOT NULL,
286
+ dominant_topic_id INTEGER,
287
+ document_fingerprint TEXT NOT NULL,
288
+ predicted_at TEXT NOT NULL,
289
+ PRIMARY KEY (model_id, paper_id),
290
+ FOREIGN KEY (model_id) REFERENCES topic_models(model_id) ON DELETE CASCADE,
291
+ FOREIGN KEY (paper_id) REFERENCES papers(paper_id) ON DELETE CASCADE,
292
+ CHECK (status IN ('predicted', 'no_vocabulary_terms'))
293
+ );
294
+
295
+ CREATE TABLE IF NOT EXISTS paper_topic_scores (
296
+ model_id TEXT NOT NULL,
297
+ paper_id TEXT NOT NULL,
298
+ topic_id INTEGER NOT NULL,
299
+ probability REAL NOT NULL,
300
+ PRIMARY KEY (model_id, paper_id, topic_id),
301
+ FOREIGN KEY (model_id, paper_id)
302
+ REFERENCES paper_topic_predictions(model_id, paper_id) ON DELETE CASCADE,
303
+ FOREIGN KEY (model_id, topic_id)
304
+ REFERENCES topic_definitions(model_id, topic_id) ON DELETE CASCADE,
305
+ CHECK (probability >= 0.0 AND probability <= 1.0)
306
+ );
307
+
308
+ CREATE INDEX IF NOT EXISTS idx_topic_predictions_status
309
+ ON paper_topic_predictions(model_id, status);
310
+ CREATE INDEX IF NOT EXISTS idx_topic_scores_topic_probability
311
+ ON paper_topic_scores(model_id, topic_id, probability);
312
+
313
+ CREATE TABLE IF NOT EXISTS paper_authors (
314
+ paper_id TEXT NOT NULL,
315
+ author_position INTEGER NOT NULL,
316
+ affiliation_rank INTEGER NOT NULL DEFAULT 0,
317
+ position_label TEXT NOT NULL DEFAULT '',
318
+ display_name TEXT NOT NULL DEFAULT '',
319
+ given_name TEXT NOT NULL DEFAULT '',
320
+ family_name TEXT NOT NULL DEFAULT '',
321
+ orcid TEXT NOT NULL DEFAULT '',
322
+ is_corresponding INTEGER NOT NULL DEFAULT 0,
323
+ affiliation TEXT NOT NULL DEFAULT '',
324
+ institution_name TEXT NOT NULL DEFAULT '',
325
+ institution_ror TEXT NOT NULL DEFAULT '',
326
+ institution_country TEXT NOT NULL DEFAULT '',
327
+ openalex_author_id TEXT NOT NULL DEFAULT '',
328
+ source TEXT NOT NULL,
329
+ PRIMARY KEY (paper_id, author_position, affiliation_rank),
330
+ FOREIGN KEY (paper_id) REFERENCES papers(paper_id) ON DELETE CASCADE
331
+ );
332
+
333
+ CREATE TABLE IF NOT EXISTS paper_subjects (
334
+ paper_id TEXT NOT NULL,
335
+ scheme TEXT NOT NULL,
336
+ subject_id TEXT NOT NULL,
337
+ display_name TEXT NOT NULL DEFAULT '',
338
+ score REAL,
339
+ subject_rank INTEGER NOT NULL DEFAULT 0,
340
+ level INTEGER,
341
+ is_primary INTEGER NOT NULL DEFAULT 0,
342
+ parent_field TEXT NOT NULL DEFAULT '',
343
+ parent_domain TEXT NOT NULL DEFAULT '',
344
+ source TEXT NOT NULL DEFAULT 'openalex',
345
+ PRIMARY KEY (paper_id, scheme, subject_id),
346
+ FOREIGN KEY (paper_id) REFERENCES papers(paper_id) ON DELETE CASCADE
347
+ );
348
+
349
+ CREATE TABLE IF NOT EXISTS paper_references (
350
+ paper_id TEXT NOT NULL,
351
+ source TEXT NOT NULL,
352
+ reference_rank INTEGER NOT NULL,
353
+ referenced_doi TEXT NOT NULL DEFAULT '',
354
+ referenced_openalex_id TEXT NOT NULL DEFAULT '',
355
+ referenced_paper_id TEXT NOT NULL DEFAULT '',
356
+ referenced_title TEXT NOT NULL DEFAULT '',
357
+ unstructured TEXT NOT NULL DEFAULT '',
358
+ PRIMARY KEY (paper_id, source, reference_rank),
359
+ FOREIGN KEY (paper_id) REFERENCES papers(paper_id) ON DELETE CASCADE
360
+ );
361
+
362
+ CREATE INDEX IF NOT EXISTS idx_paper_authors_orcid ON paper_authors(orcid);
363
+ CREATE INDEX IF NOT EXISTS idx_paper_authors_ror ON paper_authors(institution_ror);
364
+ CREATE INDEX IF NOT EXISTS idx_paper_subjects_subject ON paper_subjects(scheme, subject_id);
365
+ CREATE INDEX IF NOT EXISTS idx_paper_references_doi ON paper_references(referenced_doi);
366
+ CREATE INDEX IF NOT EXISTS idx_paper_references_openalex
367
+ ON paper_references(referenced_openalex_id);
368
+ """
369
+ )
370
+ existing_columns = {
371
+ row['name'] if isinstance(row, sqlite3.Row) else row[1]
372
+ for row in conn.execute('PRAGMA table_info(papers)').fetchall()
373
+ }
374
+ added_columns = []
375
+ for column, column_type in _expected_paper_columns().items():
376
+ if column in existing_columns:
377
+ continue
378
+ conn.execute(f'ALTER TABLE papers ADD COLUMN {column} {column_type}')
379
+ added_columns.append(column)
380
+ if 'enrichment_status' in added_columns:
381
+ conn.execute(
382
+ "UPDATE papers SET enrichment_status = 'pending' WHERE enrichment_status IS NULL"
383
+ )
384
+ conn.execute('CREATE INDEX IF NOT EXISTS idx_papers_enrichment ON papers(enrichment_status)')
385
+ conn.execute(f'PRAGMA user_version = {SCHEMA_VERSION}')
386
+ conn.commit()
387
+
388
+
389
+ def _paper_column_type(column: str) -> str:
390
+ """Resolve the SQLite type for a paper column.
391
+
392
+ Parameters
393
+ ----------
394
+ column : str
395
+ Paper metadata or pipeline-state column name.
396
+
397
+ Returns
398
+ -------
399
+ str
400
+ SQLite type name.
401
+ """
402
+ if column in {
403
+ 'num_images',
404
+ 'num_text_materials',
405
+ 'num_abstract_materials',
406
+ 'num_image_materials',
407
+ 'num_text_chunks',
408
+ 'num_abstract_chunks',
409
+ }:
410
+ return 'INTEGER'
411
+ return 'TEXT'
412
+
413
+
414
+ def _expected_paper_columns() -> dict[str, str]:
415
+ """Map every column the papers table must have to its SQLite type.
416
+
417
+ The mapping drives both the ``CREATE TABLE`` statement and the migration
418
+ that reconciles an existing database, so a new metadata or enrichment
419
+ column is added in one place only.
420
+
421
+ Returns
422
+ -------
423
+ dict[str, str]
424
+ Column name to declared SQLite type, excluding the primary key.
425
+ """
426
+ columns = {column: _paper_column_type(column) for column in PAPER_FIELDS if column != 'paper_id'}
427
+ columns.update(ENRICHMENT_COLUMNS)
428
+ return columns
429
+
430
+
431
+ def _has_value(value: object) -> bool:
432
+ """Check whether a value contains meaningful content.
433
+
434
+ Parameters
435
+ ----------
436
+ value : object
437
+ Candidate scalar value.
438
+
439
+ Returns
440
+ -------
441
+ bool
442
+ ``True`` for non-empty, non-NaN values.
443
+ """
444
+ if value is None:
445
+ return False
446
+ try:
447
+ if math.isnan(value):
448
+ return False
449
+ except (TypeError, ValueError):
450
+ pass
451
+ return str(value).strip() != ''
452
+
453
+
454
+ def _clean_doi(value: object) -> str:
455
+ """Normalize a DOI-like value for matching.
456
+
457
+ Parameters
458
+ ----------
459
+ value : object
460
+ DOI, DOI URL, or prefixed DOI value.
461
+
462
+ Returns
463
+ -------
464
+ str
465
+ Lower-case bare DOI, or an empty string.
466
+ """
467
+ if not _has_value(value):
468
+ return ''
469
+ doi = str(value).strip()
470
+ if doi.lower().startswith('doi:'):
471
+ doi = doi[4:]
472
+ if doi.lower().startswith('https://doi.org/'):
473
+ doi = doi[16:]
474
+ return doi.strip().rstrip('.').lower()
475
+
476
+
477
+ def _title_key(value: object) -> str:
478
+ """Create a comparable paper-title key.
479
+
480
+ Parameters
481
+ ----------
482
+ value : object
483
+ Paper title value.
484
+
485
+ Returns
486
+ -------
487
+ str
488
+ Normalized lower-case title key.
489
+ """
490
+ if not _has_value(value):
491
+ return ''
492
+ return re.sub(r'\W+', ' ', str(value).lower()).strip()
493
+
494
+
495
+ def _year(value: object) -> str:
496
+ """Extract a year from a date-like value.
497
+
498
+ Parameters
499
+ ----------
500
+ value : object
501
+ Date-like input value.
502
+
503
+ Returns
504
+ -------
505
+ str
506
+ First four-digit year, or an empty string.
507
+ """
508
+ if not _has_value(value):
509
+ return ''
510
+ match = re.search(r'\d{4}', str(value))
511
+ return match.group(0) if match else ''
512
+
513
+
514
+ def _merge_sources(current: object, incoming: object) -> str:
515
+ """Combine semicolon-separated source names.
516
+
517
+ Parameters
518
+ ----------
519
+ current : object
520
+ Existing source names.
521
+ incoming : object
522
+ New source names to merge.
523
+
524
+ Returns
525
+ -------
526
+ str
527
+ Deduplicated sources in first-seen order.
528
+ """
529
+ values = []
530
+ for value in [current, incoming]:
531
+ if not _has_value(value):
532
+ continue
533
+ values.extend(part.strip() for part in str(value).split(';') if part.strip())
534
+ return ';'.join(dict.fromkeys(values))
535
+
536
+
537
+ def _fallback_paper_id(paper: _PaperInput) -> str:
538
+ """Build a stable fallback paper identifier.
539
+
540
+ Parameters
541
+ ----------
542
+ paper : _PaperInput
543
+ Normalized paper metadata.
544
+
545
+ Returns
546
+ -------
547
+ str
548
+ DOI-, PubMed-, arXiv-, medRxiv-, bioRxiv-, chemRxiv-, CORE-, or
549
+ content-derived paper identifier.
550
+ """
551
+ doi = _clean_doi(paper.get('doi'))
552
+ if doi:
553
+ return f'doi:{doi}'
554
+ pmid = paper.get('pmid')
555
+ if _has_value(pmid):
556
+ return f'pmid:{pmid}'
557
+ arxiv_id = paper.get('arxiv_id')
558
+ if _has_value(arxiv_id):
559
+ return f'arxiv:{arxiv_id}'
560
+ medrxiv_doi = paper.get('medrxiv_doi')
561
+ if _has_value(medrxiv_doi):
562
+ return f'doi:{_clean_doi(medrxiv_doi) or medrxiv_doi}'
563
+ biorxiv_doi = paper.get('biorxiv_doi')
564
+ if _has_value(biorxiv_doi):
565
+ return f'doi:{_clean_doi(biorxiv_doi) or biorxiv_doi}'
566
+ chemrxiv_doi = paper.get('chemrxiv_doi')
567
+ if _has_value(chemrxiv_doi):
568
+ return f'doi:{_clean_doi(chemrxiv_doi) or chemrxiv_doi}'
569
+ core_id = paper.get('core_id')
570
+ if _has_value(core_id):
571
+ return f'core:{core_id}'
572
+ seed = '|'.join(str(paper.get(column) or '') for column in ['title', 'publication_date', 'authors'])
573
+ return f'paper:{hashlib.sha1(seed.encode("utf-8")).hexdigest()}'
574
+
575
+
576
+ def normalize_paper(paper: _PaperInput) -> _Paper:
577
+ """Normalize a paper mapping to the corpus schema.
578
+
579
+ Parameters
580
+ ----------
581
+ paper : _PaperInput
582
+ Provider or user-supplied paper metadata.
583
+
584
+ Returns
585
+ -------
586
+ _Paper
587
+ Complete normalized paper row with pipeline defaults.
588
+ """
589
+ normalized = {column: '' for column in PAPER_COLUMNS}
590
+ normalized.update(PIPELINE_COLUMNS)
591
+ for column in PAPER_FIELDS:
592
+ value = paper.get(column)
593
+ if _has_value(value):
594
+ normalized[column] = int(value) if _paper_column_type(column) == 'INTEGER' else str(value)
595
+ if not _has_value(normalized['paper_id']):
596
+ normalized['paper_id'] = _fallback_paper_id(normalized)
597
+ return normalized
598
+
599
+
600
+ def _merge_paper(existing: _PaperInput, incoming: _PaperInput) -> _Paper:
601
+ """Merge incoming metadata into an existing paper row.
602
+
603
+ Parameters
604
+ ----------
605
+ existing : _PaperInput
606
+ Existing corpus paper row.
607
+ incoming : _PaperInput
608
+ Incoming paper metadata.
609
+
610
+ Returns
611
+ -------
612
+ _Paper
613
+ Merged paper row that preserves established values.
614
+ """
615
+ merged = normalize_paper(existing)
616
+ incoming = normalize_paper(incoming)
617
+ merged['paper_id'] = existing['paper_id']
618
+ if _has_value(existing.get('metadata_json')):
619
+ merged['metadata_json'] = existing.get('metadata_json')
620
+ elif _has_value(incoming.get('metadata_json')):
621
+ merged['metadata_json'] = incoming.get('metadata_json')
622
+ for column, value in incoming.items():
623
+ if column == 'paper_id' or not _has_value(value):
624
+ continue
625
+ current = merged.get(column)
626
+ if column == 'sources':
627
+ merged[column] = _merge_sources(current, value)
628
+ elif _paper_column_type(column) == 'INTEGER':
629
+ if int(current or 0) == 0:
630
+ merged[column] = int(value)
631
+ elif column.endswith('_status'):
632
+ if not _has_value(current) or current == 'pending':
633
+ merged[column] = value
634
+ elif column == 'last_error':
635
+ if _has_value(value) and not _has_value(current):
636
+ merged[column] = value
637
+ elif not _has_value(current):
638
+ merged[column] = value
639
+ return merged
640
+
641
+
642
+ def _papers_match(existing: _PaperInput, incoming: _PaperInput) -> bool:
643
+ """Check whether two rows describe the same publication.
644
+
645
+ Parameters
646
+ ----------
647
+ existing : _PaperInput
648
+ Existing corpus paper row.
649
+ incoming : _PaperInput
650
+ Incoming paper metadata.
651
+
652
+ Returns
653
+ -------
654
+ bool
655
+ Whether stable identifiers or title and year match.
656
+ """
657
+ existing_doi = _clean_doi(existing.get('doi'))
658
+ incoming_doi = _clean_doi(incoming.get('doi'))
659
+ if existing_doi and incoming_doi and existing_doi == incoming_doi:
660
+ return True
661
+ for column in ['paper_id', 'core_id', 'pmid', 'pmcid', 'arxiv_id', 'medrxiv_doi',
662
+ 'biorxiv_doi', 'chemrxiv_doi']:
663
+ if _has_value(existing.get(column)) and str(existing.get(column)) == str(incoming.get(column)):
664
+ return True
665
+ existing_title = _title_key(existing.get('title'))
666
+ incoming_title = _title_key(incoming.get('title'))
667
+ existing_year = _year(existing.get('publication_date'))
668
+ incoming_year = _year(incoming.get('publication_date'))
669
+ return bool(existing_title and incoming_title and existing_title == incoming_title
670
+ and existing_year and incoming_year and existing_year == incoming_year)
671
+
672
+
673
+ def _find_existing_paper(conn: sqlite3.Connection, paper: _PaperInput) -> _Paper | None:
674
+ """Find the first corpus row matching a paper.
675
+
676
+ Parameters
677
+ ----------
678
+ conn : sqlite3.Connection
679
+ Open corpus connection.
680
+ paper : _PaperInput
681
+ Paper metadata to match.
682
+
683
+ Returns
684
+ -------
685
+ _Paper or None
686
+ Matching corpus row, or ``None``.
687
+ """
688
+ incoming = normalize_paper(paper)
689
+ for existing in paper_rows(conn):
690
+ if _papers_match(existing, incoming):
691
+ return existing
692
+ return None
693
+
694
+
695
+ def find_paper(conn: sqlite3.Connection, paper: _PaperInput) -> _Paper | None:
696
+ """Find a corpus paper matching supplied metadata.
697
+
698
+ Parameters
699
+ ----------
700
+ conn : sqlite3.Connection
701
+ Open corpus connection.
702
+ paper : _PaperInput
703
+ Paper metadata to match.
704
+
705
+ Returns
706
+ -------
707
+ _Paper or None
708
+ Matching corpus row, or ``None``.
709
+ """
710
+ return _find_existing_paper(conn, paper)
711
+
712
+
713
+ def _json_dumps(value: Any) -> str:
714
+ """Serialize metadata as deterministic JSON text.
715
+
716
+ Parameters
717
+ ----------
718
+ value : object
719
+ Metadata mapping, existing JSON text, or empty value.
720
+
721
+ Returns
722
+ -------
723
+ str
724
+ Serialized JSON text.
725
+ """
726
+ if value is None or value == '':
727
+ return '{}'
728
+ if isinstance(value, str):
729
+ return value
730
+ return json.dumps(value, sort_keys=True)
731
+
732
+
733
+ def upsert_paper(conn: sqlite3.Connection, paper: _PaperInput) -> str:
734
+ """Insert or update one paper row.
735
+
736
+ Parameters
737
+ ----------
738
+ conn : sqlite3.Connection
739
+ Open corpus connection.
740
+ paper : _PaperInput
741
+ Paper metadata and optional pipeline state.
742
+
743
+ Returns
744
+ -------
745
+ str
746
+ Identifier of the inserted or updated paper.
747
+ """
748
+ now = utc_now()
749
+ metadata = paper.get('metadata') if 'metadata' in paper else paper.get('metadata_json')
750
+ paper = normalize_paper(paper)
751
+ paper_id = str(paper['paper_id'])
752
+ existing = conn.execute('SELECT created_at FROM papers WHERE paper_id = ?', (paper_id,)).fetchone()
753
+ created_at = existing['created_at'] if existing else now
754
+ insert_columns = PAPER_FIELDS + ['metadata_json', 'created_at', 'updated_at']
755
+ update_columns = [column for column in insert_columns if column not in {'paper_id', 'created_at'}]
756
+ placeholders = ', '.join('?' for _ in insert_columns)
757
+ column_sql = ', '.join(insert_columns)
758
+ update_sql = ', '.join(f'{column} = excluded.{column}' for column in update_columns)
759
+ values = [paper.get(column) for column in PAPER_FIELDS]
760
+ values.extend([_json_dumps(metadata), created_at, now])
761
+ conn.execute(
762
+ f"""
763
+ INSERT INTO papers ({column_sql})
764
+ VALUES ({placeholders})
765
+ ON CONFLICT(paper_id) DO UPDATE SET
766
+ {update_sql}
767
+ """,
768
+ values,
769
+ )
770
+ conn.commit()
771
+ return paper_id
772
+
773
+
774
+ def upsert_papers(conn: sqlite3.Connection, papers: Iterable[_PaperInput]) -> tuple[int, int]:
775
+ """Merge multiple papers into the corpus.
776
+
777
+ Parameters
778
+ ----------
779
+ conn : sqlite3.Connection
780
+ Open corpus connection.
781
+ papers : Iterable[_PaperInput]
782
+ Paper mappings to insert or merge.
783
+
784
+ Returns
785
+ -------
786
+ tuple[int, int]
787
+ Counts of added and updated papers.
788
+ """
789
+ added = 0
790
+ updated = 0
791
+ for paper in papers:
792
+ incoming = normalize_paper(paper)
793
+ existing = _find_existing_paper(conn, incoming)
794
+ if existing is None:
795
+ upsert_paper(conn, incoming)
796
+ added += 1
797
+ else:
798
+ upsert_paper(conn, _merge_paper(existing, incoming))
799
+ updated += 1
800
+ return added, updated
801
+
802
+
803
+ def paper_rows(conn: sqlite3.Connection) -> list[_Paper]:
804
+ """Load corpus paper rows in insertion order.
805
+
806
+ Parameters
807
+ ----------
808
+ conn : sqlite3.Connection
809
+ Open corpus connection.
810
+
811
+ Returns
812
+ -------
813
+ list[_Paper]
814
+ Paper rows in their stored representation.
815
+ """
816
+ return [
817
+ dict(row)
818
+ for row in conn.execute('SELECT * FROM papers ORDER BY rowid').fetchall()
819
+ ]
820
+
821
+
822
+ def _enrichment_update_sql() -> str:
823
+ """Build the parameterized UPDATE statement used to write enrichment values.
824
+
825
+ Core bibliographic columns are filled only when currently empty, mirroring
826
+ the fill-if-empty rule in :func:`_merge_paper`. Enrichment columns are
827
+ overwritten because citation counts and retraction flags change over time.
828
+
829
+ Returns
830
+ -------
831
+ str
832
+ UPDATE statement using named parameters.
833
+ """
834
+ assignments = [f"{column} = COALESCE(NULLIF({column}, ''), :{column})"
835
+ for column in ENRICHMENT_FILL_COLUMNS]
836
+ assignments.extend(f'{column} = :{column}' for column in ENRICHMENT_COLUMNS)
837
+ assignments.append('enrichment_status = :enrichment_status')
838
+ assignments.append('updated_at = :updated_at')
839
+ return f"UPDATE papers SET {', '.join(assignments)} WHERE paper_id = :paper_id"
840
+
841
+
842
+ def enrichment_update_fields() -> list[str]:
843
+ """List every named parameter the enrichment UPDATE statement expects.
844
+
845
+ Returns
846
+ -------
847
+ list[str]
848
+ Parameter names, including ``paper_id`` and ``updated_at``.
849
+ """
850
+ return (ENRICHMENT_FILL_COLUMNS + list(ENRICHMENT_COLUMNS)
851
+ + ['enrichment_status', 'updated_at', 'paper_id'])
852
+
853
+
854
+ def enrichment_candidates(conn: sqlite3.Connection,
855
+ statuses: Iterable[str] = ('pending',),
856
+ after_rowid: int = 0,
857
+ limit: int = 100,
858
+ refreshed_before: str = '') -> list[_Paper]:
859
+ """Return the next page of papers needing enrichment.
860
+
861
+ Results are keyset-paginated by ``rowid`` so an interrupted run resumes
862
+ without extra state and terminates even when a selected status is unchanged
863
+ by the run.
864
+
865
+ Parameters
866
+ ----------
867
+ conn : sqlite3.Connection
868
+ Open corpus connection.
869
+ statuses : Iterable[str], default=('pending',)
870
+ Enrichment statuses selected for processing.
871
+ after_rowid : int, default=0
872
+ Exclusive lower bound on the ``rowid`` of returned rows.
873
+ limit : int, default=100
874
+ Maximum number of rows to return.
875
+ refreshed_before : str, default=''
876
+ Also select succeeded rows enriched before this ISO-8601 timestamp.
877
+
878
+ Returns
879
+ -------
880
+ list[_Paper]
881
+ Candidate rows including their ``rowid``.
882
+ """
883
+ statuses = list(statuses)
884
+ placeholders = ', '.join('?' for _ in statuses) or "''"
885
+ rows = conn.execute(
886
+ f"""
887
+ SELECT rowid AS rowid, paper_id, doi, title, journal, publication_date, authors,
888
+ openalex_id, pmid, pmcid, arxiv_id, medrxiv_doi, biorxiv_doi,
889
+ chemrxiv_doi,
890
+ enrichment_status, enriched_at
891
+ FROM papers
892
+ WHERE rowid > ?
893
+ AND (enrichment_status IN ({placeholders})
894
+ OR (? <> ''
895
+ AND enrichment_status = 'succeeded'
896
+ AND enriched_at IS NOT NULL
897
+ AND enriched_at <> ''
898
+ AND enriched_at < ?))
899
+ ORDER BY rowid
900
+ LIMIT ?
901
+ """,
902
+ [after_rowid, *statuses, refreshed_before, refreshed_before, limit],
903
+ ).fetchall()
904
+ return [dict(row) for row in rows]
905
+
906
+
907
+ def _child_column_defaults(conn: sqlite3.Connection, table: str) -> dict[str, Any]:
908
+ """Read the declared default for every column of an enrichment child table.
909
+
910
+ Defaults are read from the live schema so a caller may omit any column
911
+ without tripping its ``NOT NULL`` constraint, and so this helper cannot
912
+ drift from the table definition.
913
+
914
+ Parameters
915
+ ----------
916
+ conn : sqlite3.Connection
917
+ Open corpus connection.
918
+ table : str
919
+ Enrichment child table name.
920
+
921
+ Returns
922
+ -------
923
+ dict[str, Any]
924
+ Column name to the value used when a row omits that column.
925
+ """
926
+ defaults = {}
927
+ for row in conn.execute(f'PRAGMA table_info({table})').fetchall():
928
+ name = row['name'] if isinstance(row, sqlite3.Row) else row[1]
929
+ not_null = row['notnull'] if isinstance(row, sqlite3.Row) else row[3]
930
+ declared = row['dflt_value'] if isinstance(row, sqlite3.Row) else row[4]
931
+ if declared is None:
932
+ defaults[name] = None if not not_null else ''
933
+ continue
934
+ declared = str(declared)
935
+ if declared.startswith("'") and declared.endswith("'"):
936
+ defaults[name] = declared[1:-1]
937
+ else:
938
+ try:
939
+ defaults[name] = int(declared)
940
+ except ValueError:
941
+ defaults[name] = declared
942
+ return defaults
943
+
944
+
945
+ def write_enrichment(conn: sqlite3.Connection,
946
+ updates: Iterable[_PaperInput],
947
+ authors: Iterable[_PaperInput] = (),
948
+ subjects: Iterable[_PaperInput] = (),
949
+ references: Iterable[_PaperInput] = (),
950
+ sources: Iterable[str] = ()) -> int:
951
+ """Write one batch of enrichment updates and child rows in a transaction.
952
+
953
+ Child rows are replaced per paper rather than merged, so re-running
954
+ enrichment cannot leave stale authors, subjects, or references behind. The
955
+ replacement is scoped to ``sources`` so enriching from one provider leaves
956
+ another provider's rows for the same paper intact.
957
+
958
+ Parameters
959
+ ----------
960
+ conn : sqlite3.Connection
961
+ Open corpus connection.
962
+ updates : Iterable[_PaperInput]
963
+ One mapping per paper containing every enrichment update parameter.
964
+ authors : Iterable[_PaperInput], optional
965
+ Rows for the ``paper_authors`` table.
966
+ subjects : Iterable[_PaperInput], optional
967
+ Rows for the ``paper_subjects`` table.
968
+ references : Iterable[_PaperInput], optional
969
+ Rows for the ``paper_references`` table.
970
+ sources : Iterable[str], optional
971
+ Providers these rows came from. Only their rows are replaced; an empty
972
+ value replaces every child row for the papers being updated.
973
+
974
+ Returns
975
+ -------
976
+ int
977
+ Number of papers updated.
978
+ """
979
+ updates = [dict(update) for update in updates]
980
+ if not updates:
981
+ return 0
982
+ child_rows = {
983
+ 'paper_authors': [dict(row) for row in authors],
984
+ 'paper_subjects': [dict(row) for row in subjects],
985
+ 'paper_references': [dict(row) for row in references],
986
+ }
987
+ scoped = [str(source) for source in sources if str(source)]
988
+ if scoped:
989
+ placeholders = ', '.join('?' for _ in scoped)
990
+ delete_clause = f'WHERE paper_id = ? AND source IN ({placeholders})'
991
+ delete_parameters = [(str(update['paper_id']), *scoped) for update in updates]
992
+ else:
993
+ delete_clause = 'WHERE paper_id = ?'
994
+ delete_parameters = [(str(update['paper_id']),) for update in updates]
995
+ try:
996
+ conn.execute('BEGIN')
997
+ conn.executemany(_enrichment_update_sql(), updates)
998
+ for table, rows in child_rows.items():
999
+ conn.executemany(f'DELETE FROM {table} {delete_clause}', delete_parameters)
1000
+ columns = ENRICHMENT_CHILD_TABLES[table]
1001
+ defaults = _child_column_defaults(conn, table)
1002
+ placeholders = ', '.join(f':{column}' for column in columns)
1003
+ conn.executemany(
1004
+ f"INSERT INTO {table} ({', '.join(columns)}) VALUES ({placeholders})",
1005
+ [
1006
+ {
1007
+ column: defaults[column] if row.get(column) is None else row[column]
1008
+ for column in columns
1009
+ }
1010
+ for row in rows
1011
+ ],
1012
+ )
1013
+ conn.commit()
1014
+ except Exception:
1015
+ conn.rollback()
1016
+ raise
1017
+ return len(updates)
1018
+
1019
+
1020
+ def set_enrichment_status(conn: sqlite3.Connection,
1021
+ paper_ids: Iterable[str],
1022
+ status: str) -> int:
1023
+ """Set the enrichment status for papers that produced no enrichment payload.
1024
+
1025
+ Parameters
1026
+ ----------
1027
+ conn : sqlite3.Connection
1028
+ Open corpus connection.
1029
+ paper_ids : Iterable[str]
1030
+ Papers to update.
1031
+ status : str
1032
+ Enrichment status to store.
1033
+
1034
+ Returns
1035
+ -------
1036
+ int
1037
+ Number of papers updated.
1038
+
1039
+ Raises
1040
+ ------
1041
+ ValueError
1042
+ If ``status`` is not a supported enrichment status.
1043
+ """
1044
+ if status not in ENRICHMENT_STATUSES:
1045
+ raise ValueError(f'enrichment status must be one of: {", ".join(sorted(ENRICHMENT_STATUSES))}')
1046
+ paper_ids = [(status, utc_now(), str(paper_id)) for paper_id in paper_ids]
1047
+ if not paper_ids:
1048
+ return 0
1049
+ conn.executemany(
1050
+ 'UPDATE papers SET enrichment_status = ?, updated_at = ? WHERE paper_id = ?',
1051
+ paper_ids,
1052
+ )
1053
+ conn.commit()
1054
+ return len(paper_ids)
1055
+
1056
+
1057
+ def paper_authors(conn: sqlite3.Connection, paper_id: str) -> list[_Paper]:
1058
+ """Return one paper's structured authors.
1059
+
1060
+ Parameters
1061
+ ----------
1062
+ conn : sqlite3.Connection
1063
+ Open corpus connection.
1064
+ paper_id : str
1065
+ Paper identifier to read.
1066
+
1067
+ Returns
1068
+ -------
1069
+ list[_Paper]
1070
+ Author rows ordered by position and affiliation rank.
1071
+ """
1072
+ rows = conn.execute(
1073
+ 'SELECT * FROM paper_authors WHERE paper_id = ? ORDER BY author_position, affiliation_rank',
1074
+ (paper_id,),
1075
+ ).fetchall()
1076
+ return [dict(row) for row in rows]
1077
+
1078
+
1079
+ def paper_subjects(conn: sqlite3.Connection, paper_id: str, scheme: str = '') -> list[_Paper]:
1080
+ """Return one paper's subjects.
1081
+
1082
+ Parameters
1083
+ ----------
1084
+ conn : sqlite3.Connection
1085
+ Open corpus connection.
1086
+ paper_id : str
1087
+ Paper identifier to read.
1088
+ scheme : str, default=''
1089
+ Restrict results to a single subject scheme when non-empty.
1090
+
1091
+ Returns
1092
+ -------
1093
+ list[_Paper]
1094
+ Subject rows ordered by scheme and rank.
1095
+ """
1096
+ query = 'SELECT * FROM paper_subjects WHERE paper_id = ?'
1097
+ params: list[Any] = [paper_id]
1098
+ if scheme:
1099
+ query += ' AND scheme = ?'
1100
+ params.append(scheme)
1101
+ rows = conn.execute(f'{query} ORDER BY scheme, subject_rank', params).fetchall()
1102
+ return [dict(row) for row in rows]
1103
+
1104
+
1105
+ def paper_references(conn: sqlite3.Connection, paper_id: str, source: str = '') -> list[_Paper]:
1106
+ """Return one paper's references.
1107
+
1108
+ Parameters
1109
+ ----------
1110
+ conn : sqlite3.Connection
1111
+ Open corpus connection.
1112
+ paper_id : str
1113
+ Paper identifier to read.
1114
+ source : str, default=''
1115
+ Restrict results to one provider when non-empty.
1116
+
1117
+ Returns
1118
+ -------
1119
+ list[_Paper]
1120
+ Reference rows ordered by source and rank.
1121
+ """
1122
+ query = 'SELECT * FROM paper_references WHERE paper_id = ?'
1123
+ params: list[Any] = [paper_id]
1124
+ if source:
1125
+ query += ' AND source = ?'
1126
+ params.append(source)
1127
+ rows = conn.execute(f'{query} ORDER BY source, reference_rank', params).fetchall()
1128
+ return [dict(row) for row in rows]
1129
+
1130
+
1131
+ def enrichment_stats(conn: sqlite3.Connection) -> dict[str, int]:
1132
+ """Summarize enrichment progress and stored enrichment rows.
1133
+
1134
+ Parameters
1135
+ ----------
1136
+ conn : sqlite3.Connection
1137
+ Open corpus connection.
1138
+
1139
+ Returns
1140
+ -------
1141
+ dict[str, int]
1142
+ Per-status paper counts and child-table row totals.
1143
+ """
1144
+ stats = {
1145
+ f'papers_{status}': conn.execute(
1146
+ 'SELECT COUNT(*) FROM papers WHERE enrichment_status = ?', (status,)
1147
+ ).fetchone()[0]
1148
+ for status in sorted(ENRICHMENT_STATUSES)
1149
+ }
1150
+ stats['papers_open_access'] = conn.execute('SELECT COUNT(*) FROM papers WHERE is_oa = 1').fetchone()[0]
1151
+ stats['papers_retracted'] = conn.execute(
1152
+ 'SELECT COUNT(*) FROM papers WHERE is_retracted = 1').fetchone()[0]
1153
+ stats['author_records'] = conn.execute('SELECT COUNT(*) FROM paper_authors').fetchone()[0]
1154
+ stats['authors_with_orcid'] = conn.execute(
1155
+ "SELECT COUNT(*) FROM paper_authors WHERE orcid <> ''").fetchone()[0]
1156
+ stats['subject_records'] = conn.execute('SELECT COUNT(*) FROM paper_subjects').fetchone()[0]
1157
+ stats['reference_records'] = conn.execute('SELECT COUNT(*) FROM paper_references').fetchone()[0]
1158
+ return stats
1159
+
1160
+
1161
+ def _prepare_content(content: _BlobContent) -> bytes:
1162
+ """Convert supported content inputs to bytes.
1163
+
1164
+ Parameters
1165
+ ----------
1166
+ content : str, bytes, pathlib.Path, or Iterable[int]
1167
+ Text, raw bytes, file path, or byte-like iterable.
1168
+
1169
+ Returns
1170
+ -------
1171
+ bytes
1172
+ Prepared binary content.
1173
+ """
1174
+ if isinstance(content, bytes):
1175
+ return content
1176
+ if isinstance(content, str):
1177
+ return content.encode('utf-8')
1178
+ if isinstance(content, Path):
1179
+ return content.read_bytes()
1180
+ return bytes(content)
1181
+
1182
+
1183
+ def _compress(content: bytes, compression: str) -> bytes:
1184
+ """Compress content with a corpus storage codec.
1185
+
1186
+ Parameters
1187
+ ----------
1188
+ content : bytes
1189
+ Raw content to compress.
1190
+ compression : str
1191
+ Compression codec name.
1192
+
1193
+ Returns
1194
+ -------
1195
+ bytes
1196
+ Stored content bytes.
1197
+
1198
+ Raises
1199
+ ------
1200
+ ValueError
1201
+ If the codec is unsupported.
1202
+ """
1203
+ if compression not in SUPPORTED_COMPRESSIONS:
1204
+ raise ValueError(f'compression must be one of: {", ".join(sorted(SUPPORTED_COMPRESSIONS))}')
1205
+ if compression == 'gzip':
1206
+ return gzip.compress(content)
1207
+ return content
1208
+
1209
+
1210
+ def _decompress(content: bytes, compression: str) -> bytes:
1211
+ """Decompress stored corpus content.
1212
+
1213
+ Parameters
1214
+ ----------
1215
+ content : bytes
1216
+ Stored content bytes.
1217
+ compression : str
1218
+ Compression codec name.
1219
+
1220
+ Returns
1221
+ -------
1222
+ bytes
1223
+ Decompressed content.
1224
+
1225
+ Raises
1226
+ ------
1227
+ ValueError
1228
+ If the codec is unsupported.
1229
+ """
1230
+ if compression == 'gzip':
1231
+ return gzip.decompress(content)
1232
+ if compression == 'none':
1233
+ return content
1234
+ raise ValueError(f'Unsupported blob compression: {compression}')
1235
+
1236
+
1237
+ def store_blob(conn: sqlite3.Connection,
1238
+ content: _BlobContent,
1239
+ kind: str,
1240
+ mime_type: str,
1241
+ compression: str = 'gzip') -> str:
1242
+ """Store a deduplicated content blob.
1243
+
1244
+ Parameters
1245
+ ----------
1246
+ conn : sqlite3.Connection
1247
+ Open corpus connection.
1248
+ content : _BlobContent
1249
+ Content accepted by :func:`_prepare_content`.
1250
+ kind : str
1251
+ Logical content kind, such as ``"text"`` or ``"pdf"``.
1252
+ mime_type : str
1253
+ MIME type of the uncompressed content.
1254
+ compression : str, optional
1255
+ Storage compression codec.
1256
+
1257
+ Returns
1258
+ -------
1259
+ str
1260
+ Stable content-addressed blob identifier.
1261
+
1262
+ Raises
1263
+ ------
1264
+ ValueError
1265
+ If the compression codec is unsupported.
1266
+ """
1267
+ raw = _prepare_content(content)
1268
+ sha256 = hashlib.sha256(raw).hexdigest()
1269
+ existing = conn.execute('SELECT blob_id FROM blobs WHERE sha256 = ?', (sha256,)).fetchone()
1270
+ if existing:
1271
+ return existing['blob_id']
1272
+ stored = _compress(raw, compression)
1273
+ blob_id = f'{kind}:{sha256}'
1274
+ conn.execute(
1275
+ """
1276
+ INSERT INTO blobs (
1277
+ blob_id, sha256, kind, mime_type, compression, original_size,
1278
+ stored_size, content, created_at
1279
+ )
1280
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
1281
+ """,
1282
+ (
1283
+ blob_id,
1284
+ sha256,
1285
+ kind,
1286
+ mime_type,
1287
+ compression,
1288
+ len(raw),
1289
+ len(stored),
1290
+ stored,
1291
+ utc_now(),
1292
+ ),
1293
+ )
1294
+ conn.commit()
1295
+ return blob_id
1296
+
1297
+
1298
+ def link_asset(conn: sqlite3.Connection,
1299
+ paper_id: str,
1300
+ blob_id: str,
1301
+ role: str,
1302
+ source: str = '',
1303
+ original_filename: str = '') -> None:
1304
+ """Link a stored blob to a paper asset role.
1305
+
1306
+ Parameters
1307
+ ----------
1308
+ conn : sqlite3.Connection
1309
+ Open corpus connection.
1310
+ paper_id : str
1311
+ Identifier of the owning paper.
1312
+ blob_id : str
1313
+ Identifier of the stored content blob.
1314
+ role : str
1315
+ Asset role, such as ``"abstract"``, ``"text"``, or ``"pdf"``.
1316
+ source : str, optional
1317
+ Provider or acquisition source.
1318
+ original_filename : str, optional
1319
+ Original asset filename.
1320
+ """
1321
+ conn.execute(
1322
+ """
1323
+ INSERT OR REPLACE INTO paper_assets (
1324
+ paper_id, blob_id, role, source, original_filename, created_at
1325
+ )
1326
+ VALUES (?, ?, ?, ?, ?, ?)
1327
+ """,
1328
+ (paper_id, blob_id, role, source, original_filename, utc_now()),
1329
+ )
1330
+ conn.commit()
1331
+
1332
+
1333
+ def add_asset(conn: sqlite3.Connection,
1334
+ paper: _PaperInput,
1335
+ content: _BlobContent,
1336
+ role: str,
1337
+ kind: str,
1338
+ mime_type: str,
1339
+ source: str = '',
1340
+ original_filename: str = '',
1341
+ compression: str = 'gzip') -> str:
1342
+ """Store and link an asset for a paper.
1343
+
1344
+ Parameters
1345
+ ----------
1346
+ conn : sqlite3.Connection
1347
+ Open corpus connection.
1348
+ paper : _PaperInput
1349
+ Owning paper metadata.
1350
+ content : _BlobContent
1351
+ Asset content accepted by :func:`_prepare_content`.
1352
+ role : str
1353
+ Asset role within the paper.
1354
+ kind : str
1355
+ Logical content kind.
1356
+ mime_type : str
1357
+ MIME type of the uncompressed content.
1358
+ source : str, optional
1359
+ Provider or acquisition source.
1360
+ original_filename : str, optional
1361
+ Original asset filename.
1362
+ compression : str, optional
1363
+ Storage compression codec.
1364
+
1365
+ Returns
1366
+ -------
1367
+ str
1368
+ Identifier of the linked content blob.
1369
+ """
1370
+ paper_id = upsert_paper(conn, paper)
1371
+ blob_id = store_blob(conn, content, kind=kind, mime_type=mime_type, compression=compression)
1372
+ link_asset(conn, paper_id, blob_id, role=role, source=source, original_filename=original_filename)
1373
+ return blob_id
1374
+
1375
+
1376
+ def get_asset(conn: sqlite3.Connection, paper_id: str, role: str) -> _Asset | None:
1377
+ """Load the newest asset for a paper role.
1378
+
1379
+ Parameters
1380
+ ----------
1381
+ conn : sqlite3.Connection
1382
+ Open corpus connection.
1383
+ paper_id : str
1384
+ Owning paper identifier.
1385
+ role : str
1386
+ Asset role to retrieve.
1387
+
1388
+ Returns
1389
+ -------
1390
+ _Asset or None
1391
+ Asset metadata with decompressed ``content``, or ``None``.
1392
+ """
1393
+ row = conn.execute(
1394
+ """
1395
+ SELECT
1396
+ p.paper_id, p.doi, p.title, a.role, a.source, a.original_filename,
1397
+ b.blob_id, b.kind, b.mime_type, b.compression, b.original_size,
1398
+ b.stored_size, b.content
1399
+ FROM paper_assets AS a
1400
+ JOIN papers AS p ON p.paper_id = a.paper_id
1401
+ JOIN blobs AS b ON b.blob_id = a.blob_id
1402
+ WHERE a.paper_id = ? AND a.role = ?
1403
+ ORDER BY a.created_at DESC, a.rowid DESC
1404
+ LIMIT 1
1405
+ """,
1406
+ (paper_id, role),
1407
+ ).fetchone()
1408
+ if row is None:
1409
+ return None
1410
+ data = dict(row)
1411
+ data['content'] = _decompress(data['content'], data['compression'])
1412
+ return data
1413
+
1414
+
1415
+ def get_asset_metadata(
1416
+ conn: sqlite3.Connection,
1417
+ paper_id: str,
1418
+ role: str,
1419
+ ) -> _Asset | None:
1420
+ """Load metadata for the newest linked asset without its content.
1421
+
1422
+ Parameters
1423
+ ----------
1424
+ conn : sqlite3.Connection
1425
+ Open corpus connection.
1426
+ paper_id : str
1427
+ Owning paper identifier.
1428
+ role : str
1429
+ Asset role to retrieve.
1430
+
1431
+ Returns
1432
+ -------
1433
+ _Asset or None
1434
+ Asset metadata, or ``None`` when the role has not been stored.
1435
+ """
1436
+ row = conn.execute(
1437
+ """
1438
+ SELECT
1439
+ p.paper_id, p.doi, p.title, a.role, a.source, a.original_filename,
1440
+ b.blob_id, b.kind, b.mime_type, b.original_size, b.stored_size,
1441
+ a.created_at
1442
+ FROM paper_assets AS a
1443
+ JOIN papers AS p ON p.paper_id = a.paper_id
1444
+ JOIN blobs AS b ON b.blob_id = a.blob_id
1445
+ WHERE a.paper_id = ? AND a.role = ?
1446
+ ORDER BY a.created_at DESC, a.rowid DESC
1447
+ LIMIT 1
1448
+ """,
1449
+ (paper_id, role),
1450
+ ).fetchone()
1451
+ return dict(row) if row is not None else None
1452
+
1453
+
1454
+ def latest_assets(
1455
+ conn: sqlite3.Connection,
1456
+ roles: Iterable[str],
1457
+ ) -> dict[tuple[str, str], _Asset]:
1458
+ """Load the newest requested assets in bulk.
1459
+
1460
+ Parameters
1461
+ ----------
1462
+ conn : sqlite3.Connection
1463
+ Open corpus connection.
1464
+ roles : Iterable[str]
1465
+ Asset roles to retrieve.
1466
+
1467
+ Returns
1468
+ -------
1469
+ dict[tuple[str, str], _Asset]
1470
+ ``(paper_id, role)`` keys mapped to decompressed asset rows.
1471
+ """
1472
+ roles = tuple(dict.fromkeys(roles))
1473
+ if not roles:
1474
+ return {}
1475
+ placeholders = ', '.join('?' for _ in roles)
1476
+ rows = conn.execute(
1477
+ f"""
1478
+ SELECT paper_id, role, source, original_filename, compression, content
1479
+ FROM (
1480
+ SELECT
1481
+ a.paper_id, a.role, a.source, a.original_filename,
1482
+ a.created_at, a.rowid AS asset_rowid,
1483
+ b.compression, b.content,
1484
+ ROW_NUMBER() OVER (
1485
+ PARTITION BY a.paper_id, a.role
1486
+ ORDER BY a.created_at DESC, a.rowid DESC
1487
+ ) AS asset_rank
1488
+ FROM paper_assets AS a
1489
+ JOIN blobs AS b ON b.blob_id = a.blob_id
1490
+ WHERE a.role IN ({placeholders})
1491
+ )
1492
+ WHERE asset_rank = 1
1493
+ """,
1494
+ roles,
1495
+ ).fetchall()
1496
+ assets = {}
1497
+ for row in rows:
1498
+ asset = dict(row)
1499
+ asset['content'] = _decompress(asset['content'], asset.pop('compression'))
1500
+ assets[(asset['paper_id'], asset['role'])] = asset
1501
+ return assets
1502
+
1503
+
1504
+ def corpus_stats(conn: sqlite3.Connection) -> dict[str, int | float]:
1505
+ """Calculate corpus storage statistics.
1506
+
1507
+ Parameters
1508
+ ----------
1509
+ conn : sqlite3.Connection
1510
+ Open corpus connection.
1511
+
1512
+ Returns
1513
+ -------
1514
+ dict[str, int or float]
1515
+ Paper, asset, blob-size, and compression-savings statistics.
1516
+ """
1517
+ paper_count = conn.execute('SELECT COUNT(*) FROM papers').fetchone()[0]
1518
+ blob_count = conn.execute('SELECT COUNT(*) FROM blobs').fetchone()[0]
1519
+ asset_counts = {
1520
+ role: conn.execute(
1521
+ 'SELECT COUNT(DISTINCT paper_id) FROM paper_assets WHERE role = ?',
1522
+ (role,),
1523
+ ).fetchone()[0]
1524
+ for role in ['abstract', 'text', 'pdf']
1525
+ }
1526
+ sizes = conn.execute('SELECT COALESCE(SUM(original_size), 0), COALESCE(SUM(stored_size), 0) FROM blobs').fetchone()
1527
+ chunked_text = conn.execute('SELECT COUNT(*) FROM papers WHERE num_text_chunks > 1').fetchone()[0]
1528
+ chunked_abstracts = conn.execute('SELECT COUNT(*) FROM papers WHERE num_abstract_chunks > 1').fetchone()[0]
1529
+ original_size, stored_size = sizes
1530
+ savings = 0 if original_size == 0 else 1 - (stored_size / original_size)
1531
+ return {
1532
+ 'papers': paper_count,
1533
+ 'papers_with_abstract': asset_counts['abstract'],
1534
+ 'papers_with_text': asset_counts['text'],
1535
+ 'papers_with_pdf': asset_counts['pdf'],
1536
+ 'papers_with_chunked_text': chunked_text,
1537
+ 'papers_with_chunked_abstracts': chunked_abstracts,
1538
+ 'blobs': blob_count,
1539
+ 'original_size': original_size,
1540
+ 'stored_size': stored_size,
1541
+ 'savings_fraction': savings,
1542
+ }