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,244 @@
1
+ """Store scraped material rows into the final materials CSV.
2
+
3
+ The storage step maps temporary scrape columns to recipe fields, optionally
4
+ converts units, appends accepted rows to the output file, and marks papers as
5
+ stored once their scrape results have been persisted.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import tempfile
12
+ from collections.abc import Collection
13
+ from os import PathLike
14
+ from pathlib import Path
15
+
16
+ import pandas as pd
17
+
18
+ from paperminertoolkit.corpus.database import connect, paper_rows, upsert_paper
19
+ from paperminertoolkit.extraction.extract import convert_units
20
+ from paperminertoolkit.extraction.models import ModelConfig
21
+ from paperminertoolkit.extraction.recipes import canonical_match, field_columns, load_recipe
22
+
23
+
24
+ def _temporary_path(directory: Path, prefix: str, suffix: str) -> str:
25
+ """Create and close a unique temporary file.
26
+
27
+ Parameters
28
+ ----------
29
+ directory : pathlib.Path
30
+ Directory in which to create the file.
31
+ prefix : str
32
+ Temporary filename prefix.
33
+ suffix : str
34
+ Temporary filename suffix.
35
+
36
+ Returns
37
+ -------
38
+ str
39
+ Path to the temporary file.
40
+
41
+ Raises
42
+ ------
43
+ OSError
44
+ If the temporary file cannot be created or its descriptor cannot be
45
+ closed.
46
+ """
47
+ descriptor, path = tempfile.mkstemp(dir=directory, prefix=prefix, suffix=suffix)
48
+ os.close(descriptor)
49
+ return path
50
+
51
+
52
+ def _write_csv_atomically(data: pd.DataFrame, output_path: Path) -> None:
53
+ """Write a CSV before atomically replacing its destination.
54
+
55
+ Parameters
56
+ ----------
57
+ data : pandas.DataFrame
58
+ Tabular data to serialize.
59
+ output_path : pathlib.Path
60
+ Destination CSV path.
61
+
62
+ Raises
63
+ ------
64
+ OSError
65
+ If the temporary CSV cannot be written or atomically moved into place.
66
+ """
67
+ temp_path = _temporary_path(output_path.parent, f'.{output_path.name}.', '.tmp')
68
+ try:
69
+ data.to_csv(temp_path)
70
+ os.replace(temp_path, output_path)
71
+ finally:
72
+ if os.path.exists(temp_path):
73
+ os.remove(temp_path)
74
+
75
+
76
+ def _stored_paper_ids(data: pd.DataFrame) -> set[str]:
77
+ """Extract non-empty paper identifiers from stored rows.
78
+
79
+ Parameters
80
+ ----------
81
+ data : pandas.DataFrame
82
+ Material rows that must contain a ``Paper id`` column.
83
+
84
+ Returns
85
+ -------
86
+ set[str]
87
+ Unique non-empty paper identifiers.
88
+
89
+ Raises
90
+ ------
91
+ ValueError
92
+ If the required column is missing or contains no non-empty identifiers.
93
+ """
94
+ if 'Paper id' not in data.columns:
95
+ raise ValueError('Scraped materials must contain a "Paper id" column.')
96
+ paper_ids = {
97
+ str(value).strip()
98
+ for value in data['Paper id']
99
+ if pd.notna(value) and str(value).strip()
100
+ }
101
+ if not paper_ids:
102
+ raise ValueError('Scraped materials must contain at least one non-empty "Paper id" value.')
103
+ return paper_ids
104
+
105
+
106
+ def _mark_stored_papers(
107
+ db_path: str | PathLike[str],
108
+ paper_ids: Collection[str],
109
+ ) -> None:
110
+ """Mark successfully scraped papers as stored.
111
+
112
+ Parameters
113
+ ----------
114
+ db_path : str or os.PathLike[str]
115
+ Corpus database to update.
116
+ paper_ids : Collection[str]
117
+ Paper identifiers represented by the stored batch.
118
+
119
+ Raises
120
+ ------
121
+ RuntimeError
122
+ If the corpus schema is newer than this package supports.
123
+ """
124
+ with connect(db_path) as conn:
125
+ for paper in paper_rows(conn):
126
+ if paper['paper_id'] not in paper_ids:
127
+ continue
128
+ if not any(
129
+ paper.get(column) == 'succeeded'
130
+ for column in ['abstract_scrape_status', 'text_scrape_status', 'image_scrape_status']
131
+ ):
132
+ continue
133
+ paper['store_status'] = 'stored'
134
+ upsert_paper(conn, paper)
135
+
136
+
137
+ def store_results(db_path: str | PathLike[str] = 'papers.db',
138
+ in_filepath: str | PathLike[str] = 'temp_scraped_materials.csv',
139
+ out_filepath: str | PathLike[str] = 'materials.csv',
140
+ unit_conversion: bool = True,
141
+ recipe: str = 'sse',
142
+ assume_yes: bool = False,
143
+ model_config: ModelConfig | None = None,
144
+ ) -> None:
145
+ """Convert and append temporary scrape results.
146
+
147
+ Parameters
148
+ ----------
149
+ db_path : str or os.PathLike[str], optional
150
+ Corpus database whose paper statuses should be updated.
151
+ in_filepath : str or os.PathLike[str], optional
152
+ Temporary scraped-materials CSV to consume.
153
+ out_filepath : str or os.PathLike[str], optional
154
+ Final materials CSV to create or append.
155
+ unit_conversion : bool, optional
156
+ Whether to convert recipe fields with configured units.
157
+ recipe : str, optional
158
+ Bundled recipe name or recipe JSON path.
159
+ assume_yes : bool, optional
160
+ Whether to accept conversions and skip unmatched columns without a prompt.
161
+ model_config : ModelConfig or None, optional
162
+ Model configuration forwarded to unit conversion.
163
+
164
+ Raises
165
+ ------
166
+ ValueError
167
+ If input and output paths match, the recipe is invalid, or stored paper
168
+ identifiers are invalid.
169
+ RuntimeError
170
+ If an unmatched column is encountered in interactive mode or the
171
+ corpus schema is newer than this package supports.
172
+ FileNotFoundError
173
+ If the bundled recipe resource or an output parent directory is
174
+ missing.
175
+ KeyError
176
+ If no bundled or standalone recipe matches ``recipe``.
177
+ OSError
178
+ If an input, preview, or output file cannot be accessed.
179
+ """
180
+ input_path = Path(in_filepath)
181
+ output_path = Path(out_filepath)
182
+ if input_path.resolve() == output_path.resolve():
183
+ raise ValueError('Input and output materials paths must be different.')
184
+ if not input_path.is_file():
185
+ print(f'No scraped materials file found at {in_filepath}. Nothing new to store.')
186
+ return
187
+ in_file = pd.read_csv(input_path, index_col=0)
188
+ if in_file.empty:
189
+ print(f'Scraped materials file {in_filepath} is empty. Nothing new to store.')
190
+ return
191
+ recipe = load_recipe(recipe)
192
+ if output_path.is_file():
193
+ out_file = pd.read_csv(output_path, index_col=0)
194
+ columns = list(out_file.keys())
195
+ else:
196
+ out_file = None
197
+ columns = field_columns(recipe)
198
+
199
+ out_data = pd.DataFrame()
200
+ for series_name, series in in_file.items():
201
+ match = canonical_match(series_name, columns, recipe)
202
+ if match is None:
203
+ if assume_yes:
204
+ print(f'Skipping unmatched column in noninteractive mode: {series_name}')
205
+ continue
206
+ raise RuntimeError(f'{series_name} did not match with a field in the recipe or output file.')
207
+ split_field = match.split(' [')
208
+ if len(split_field) == 2 and unit_conversion:
209
+ print(f'{series_name} column was matched with {match} and will be converted.')
210
+ split_field[1] = split_field[1].replace(']', '')
211
+ converted_series = convert_units(
212
+ series,
213
+ field=split_field[0],
214
+ unit=split_field[1],
215
+ model_config=model_config,
216
+ )
217
+ else:
218
+ print(f'{series_name} column was matched with {match} and will not be converted.')
219
+ converted_series = series
220
+ out_data[match] = converted_series
221
+
222
+ paper_ids = _stored_paper_ids(out_data)
223
+ preview_path = _temporary_path(output_path.parent, '.paperminertoolkit-converted-', '.csv')
224
+ try:
225
+ out_data.to_csv(preview_path)
226
+ if assume_yes:
227
+ decision = 'yes'
228
+ else:
229
+ print(f'\nOutput data has been saved to {preview_path} temporarily. Are you happy with these conversions?')
230
+ decision = input('Yes (Y) / No (N): ')
231
+ if decision.lower() not in {'y', 'yes'}:
232
+ return
233
+
234
+ if out_file is not None:
235
+ materials_df = pd.concat([out_file, out_data], ignore_index=True)
236
+ else:
237
+ materials_df = out_data.reset_index(drop=True)
238
+ materials_df.drop_duplicates(ignore_index=True, inplace=True)
239
+ _write_csv_atomically(materials_df, output_path)
240
+ _mark_stored_papers(db_path, paper_ids)
241
+ input_path.unlink()
242
+ finally:
243
+ if os.path.exists(preview_path):
244
+ os.remove(preview_path)
@@ -0,0 +1,313 @@
1
+ """Provider-aware token counting for model context management.
2
+
3
+ This module chooses the best available token counter for the configured model:
4
+ OpenAI models use ``tiktoken``, Anthropic models can use Claude's token counting
5
+ endpoint, local models use Hugging Face tokenizers, and all
6
+ paths fall back to a conservative character-based estimate.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import importlib
12
+ import math
13
+ from collections.abc import Mapping
14
+ from functools import lru_cache
15
+ from typing import Protocol, TypeAlias
16
+
17
+ import requests
18
+ import tiktoken
19
+
20
+ from paperminertoolkit.settings import DEFAULT_MODEL
21
+ from paperminertoolkit.settings import DEFAULT_INPUT_TOKEN_LIMIT
22
+
23
+ ANTHROPIC_VERSION = '2023-06-01'
24
+ DEFAULT_ANTHROPIC_BASE_URL = 'https://api.anthropic.com'
25
+
26
+
27
+ class _ModelConfigLike(Protocol):
28
+ """Structural type required by provider-aware token helpers."""
29
+
30
+ provider: str
31
+ name: str
32
+ api_key: str | None
33
+ base_url: str | None
34
+ input_token_limit: int
35
+
36
+
37
+ _ModelConfigSource: TypeAlias = _ModelConfigLike | Mapping[str, object]
38
+
39
+
40
+ class _TokenizerLike(Protocol):
41
+ """Structural type returned by dynamically loaded tokenizers."""
42
+
43
+ def encode(self, text: str, *, add_special_tokens: bool = False) -> list[int]:
44
+ """Encode text into integer token identifiers."""
45
+ ...
46
+
47
+
48
+ def _conservative_token_estimate(text: str) -> int:
49
+ """Estimate tokens when no model tokenizer is available.
50
+
51
+ Parameters
52
+ ----------
53
+ text : str
54
+ Text to estimate.
55
+
56
+ Returns
57
+ -------
58
+ int
59
+ Zero for missing or empty input; otherwise one token per three
60
+ characters, rounded up.
61
+ """
62
+ if not isinstance(text, str) or text == '':
63
+ return 0
64
+ return max(1, math.ceil(len(text) / 3))
65
+
66
+
67
+ def _provider_name(model_config: _ModelConfigSource | None = None, provider: str | None = None) -> str:
68
+ """Resolve and normalize a provider name.
69
+
70
+ Parameters
71
+ ----------
72
+ model_config : _ModelConfigSource or None, optional
73
+ Object that may expose a ``provider`` attribute.
74
+ provider : str, optional
75
+ Explicit provider name, which takes precedence over ``model_config``.
76
+
77
+ Returns
78
+ -------
79
+ str
80
+ Lowercase provider name with underscores replaced by hyphens.
81
+ """
82
+ value = provider or getattr(model_config, 'provider', '') or ''
83
+ return str(value).lower().replace('_', '-')
84
+
85
+
86
+ def _model_name(model_config: _ModelConfigSource | None = None, model: str | None = None) -> str:
87
+ """Resolve a model name from explicit input or configuration.
88
+
89
+ Parameters
90
+ ----------
91
+ model_config : _ModelConfigSource or None, optional
92
+ Object that may expose a ``name`` attribute.
93
+ model : str, optional
94
+ Explicit model name, which takes precedence over ``model_config``.
95
+
96
+ Returns
97
+ -------
98
+ str
99
+ Resolved model name, falling back to the package default.
100
+ """
101
+ return model or getattr(model_config, 'name', None) or DEFAULT_MODEL
102
+
103
+
104
+ def _openai_token_count(text: str, model: str | None = None) -> int:
105
+ """Count text tokens with an OpenAI tokenizer.
106
+
107
+ Parameters
108
+ ----------
109
+ text : str
110
+ Text to tokenize.
111
+ model : str, optional
112
+ OpenAI model used to select an encoding. Unknown models use
113
+ ``o200k_base``.
114
+
115
+ Returns
116
+ -------
117
+ int
118
+ Number of encoded tokens.
119
+ """
120
+ model = model or DEFAULT_MODEL
121
+ try:
122
+ encoding = tiktoken.encoding_for_model(model)
123
+ except Exception:
124
+ encoding = tiktoken.get_encoding('o200k_base')
125
+ return len(encoding.encode(text))
126
+
127
+
128
+ def _anthropic_token_count(text: str, model_config: _ModelConfigSource) -> int:
129
+ """Count text tokens with Anthropic's Messages API.
130
+
131
+ Parameters
132
+ ----------
133
+ text : str
134
+ Text to count as a single user message.
135
+ model_config : _ModelConfigSource
136
+ Configuration exposing model, API key, and optional base URL
137
+ attributes.
138
+
139
+ Returns
140
+ -------
141
+ int
142
+ Input token count reported by Anthropic.
143
+
144
+ Raises
145
+ ------
146
+ ValueError
147
+ If the configuration has no Anthropic API key.
148
+ requests.RequestException
149
+ If the token-counting request fails.
150
+ """
151
+ api_key = getattr(model_config, 'api_key', None)
152
+ if not api_key:
153
+ raise ValueError('Anthropic token counting requires an API key.')
154
+ model = _model_name(model_config)
155
+ base_url = getattr(model_config, 'base_url', None) or DEFAULT_ANTHROPIC_BASE_URL
156
+ payload = {
157
+ 'model': model,
158
+ 'messages': [{'role': 'user', 'content': text}],
159
+ }
160
+ headers = {
161
+ 'x-api-key': api_key,
162
+ 'anthropic-version': ANTHROPIC_VERSION,
163
+ 'content-type': 'application/json',
164
+ }
165
+ response = requests.post(
166
+ f'{base_url.rstrip("/")}/v1/messages/count_tokens',
167
+ headers=headers,
168
+ json=payload,
169
+ timeout=60,
170
+ )
171
+ response.raise_for_status()
172
+ return int(response.json()['input_tokens'])
173
+
174
+
175
+ @lru_cache(maxsize=16)
176
+ def _auto_tokenizer(model: str) -> _TokenizerLike:
177
+ """Load and cache a Hugging Face tokenizer.
178
+
179
+ Parameters
180
+ ----------
181
+ model : str
182
+ Hugging Face model identifier or local model path.
183
+
184
+ Returns
185
+ -------
186
+ _TokenizerLike
187
+ Loaded tokenizer instance.
188
+ """
189
+ transformers = importlib.import_module('transformers')
190
+ return transformers.AutoTokenizer.from_pretrained(model)
191
+
192
+
193
+ def _transformers_token_count(text: str, model: str) -> int:
194
+ """Count text tokens with a Hugging Face tokenizer.
195
+
196
+ Parameters
197
+ ----------
198
+ text : str
199
+ Text to tokenize.
200
+ model : str
201
+ Hugging Face model identifier or local model path.
202
+
203
+ Returns
204
+ -------
205
+ int
206
+ Number of encoded tokens, excluding special tokens.
207
+ """
208
+ tokenizer = _auto_tokenizer(model)
209
+ tokens = tokenizer.encode(text, add_special_tokens=False)
210
+ return len(tokens)
211
+
212
+
213
+ def count_text_tokens(
214
+ text: str,
215
+ model_config: _ModelConfigSource | None = None,
216
+ model: str | None = None,
217
+ provider: str | None = None,
218
+ ) -> int:
219
+ """Count text tokens with the best available provider tokenizer.
220
+
221
+ Parameters
222
+ ----------
223
+ text : str
224
+ Text to tokenize. Non-string values return zero.
225
+ model_config : _ModelConfigSource or None, optional
226
+ Model configuration used to resolve provider credentials and model
227
+ details.
228
+ model : str, optional
229
+ Explicit model name override.
230
+ provider : str, optional
231
+ Explicit provider override.
232
+
233
+ Returns
234
+ -------
235
+ int
236
+ Provider token count, or a conservative estimate when tokenization
237
+ fails or the provider is unknown.
238
+ """
239
+ if not isinstance(text, str):
240
+ return 0
241
+ provider_name = _provider_name(model_config, provider)
242
+ model_name = _model_name(model_config, model)
243
+ if provider_name in {'', 'openai'}:
244
+ try:
245
+ return _openai_token_count(text, model_name)
246
+ except Exception:
247
+ return _conservative_token_estimate(text)
248
+ if provider_name == 'anthropic':
249
+ try:
250
+ return _anthropic_token_count(text, model_config)
251
+ except Exception:
252
+ return _conservative_token_estimate(text)
253
+ if provider_name == 'local':
254
+ try:
255
+ return _transformers_token_count(text, model_name)
256
+ except Exception:
257
+ return _conservative_token_estimate(text)
258
+ return _conservative_token_estimate(text)
259
+
260
+
261
+ def usable_input_token_limit(
262
+ model_config: _ModelConfigSource | None = None,
263
+ reserve_tokens: int = 2000,
264
+ minimum: int = 1000,
265
+ ) -> int:
266
+ """Calculate the usable model input token budget.
267
+
268
+ Parameters
269
+ ----------
270
+ model_config : _ModelConfigSource or None, optional
271
+ Configuration that may expose an ``input_token_limit`` attribute.
272
+ reserve_tokens : int, default=2000
273
+ Tokens reserved for prompts, metadata, and output framing.
274
+ minimum : int, default=1000
275
+ Minimum budget returned after applying the reserve.
276
+
277
+ Returns
278
+ -------
279
+ int
280
+ Usable input token budget.
281
+ """
282
+ configured = getattr(model_config, 'input_token_limit', DEFAULT_INPUT_TOKEN_LIMIT)
283
+ try:
284
+ configured = int(configured)
285
+ except (TypeError, ValueError):
286
+ configured = DEFAULT_INPUT_TOKEN_LIMIT
287
+ return max(minimum, configured - int(reserve_tokens))
288
+
289
+
290
+ def prompt_token_reserve(prompt: str,
291
+ model_config: _ModelConfigSource | None = None,
292
+ buffer_tokens: int = 500,
293
+ minimum: int = 500) -> int:
294
+ """Calculate a token reserve for a static prompt.
295
+
296
+ Parameters
297
+ ----------
298
+ prompt : str
299
+ Static prompt text included with model input.
300
+ model_config : _ModelConfigSource or None, optional
301
+ Model configuration passed to provider-aware token counting.
302
+ buffer_tokens : int, default=500
303
+ Safety buffer added to the prompt token count.
304
+ minimum : int, default=500
305
+ Minimum reserve returned.
306
+
307
+ Returns
308
+ -------
309
+ int
310
+ Prompt token count plus the buffer, bounded by ``minimum``.
311
+ """
312
+ prompt_tokens = count_text_tokens(prompt or '', model_config=model_config)
313
+ return max(minimum, prompt_tokens + int(buffer_tokens))
@@ -0,0 +1 @@
1
+ """External scholarly-data provider clients and their registry."""