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.
- paperminertoolkit/__init__.py +10 -0
- paperminertoolkit/_version.py +11 -0
- paperminertoolkit/cli.py +1053 -0
- paperminertoolkit/corpus/__init__.py +1 -0
- paperminertoolkit/corpus/database.py +1542 -0
- paperminertoolkit/corpus/documents.py +313 -0
- paperminertoolkit/corpus/filtering.py +1390 -0
- paperminertoolkit/corpus/metadata.py +532 -0
- paperminertoolkit/extraction/__init__.py +1 -0
- paperminertoolkit/extraction/compression.py +486 -0
- paperminertoolkit/extraction/extract.py +573 -0
- paperminertoolkit/extraction/models.py +784 -0
- paperminertoolkit/extraction/recipes.py +241 -0
- paperminertoolkit/extraction/scrape.py +737 -0
- paperminertoolkit/extraction/store.py +244 -0
- paperminertoolkit/extraction/tokenizer.py +313 -0
- paperminertoolkit/providers/__init__.py +1 -0
- paperminertoolkit/providers/arxiv.py +760 -0
- paperminertoolkit/providers/base.py +514 -0
- paperminertoolkit/providers/biorxiv.py +561 -0
- paperminertoolkit/providers/chemrxiv.py +1115 -0
- paperminertoolkit/providers/core.py +423 -0
- paperminertoolkit/providers/crossref.py +649 -0
- paperminertoolkit/providers/elsevier.py +455 -0
- paperminertoolkit/providers/medrxiv.py +548 -0
- paperminertoolkit/providers/openalex.py +471 -0
- paperminertoolkit/providers/pubmed.py +1272 -0
- paperminertoolkit/providers/registry.py +521 -0
- paperminertoolkit/providers/rxiv.py +936 -0
- paperminertoolkit/providers/unpaywall.py +162 -0
- paperminertoolkit/resources/recipes.json +1670 -0
- paperminertoolkit/settings.py +661 -0
- paperminertoolkit/workflows/__init__.py +1 -0
- paperminertoolkit/workflows/download.py +1748 -0
- paperminertoolkit/workflows/enrichment.py +1906 -0
- paperminertoolkit/workflows/imports.py +121 -0
- paperminertoolkit/workflows/search.py +877 -0
- paperminertoolkit/workflows/topics.py +2837 -0
- paperminertoolkit/workflows/utilities.py +73 -0
- paperminertoolkit-1.0.0.dist-info/METADATA +126 -0
- paperminertoolkit-1.0.0.dist-info/RECORD +45 -0
- paperminertoolkit-1.0.0.dist-info/WHEEL +5 -0
- paperminertoolkit-1.0.0.dist-info/entry_points.txt +2 -0
- paperminertoolkit-1.0.0.dist-info/licenses/LICENSE +21 -0
- paperminertoolkit-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,573 @@
|
|
|
1
|
+
"""Build extraction prompts, call models, parse JSON, and convert units.
|
|
2
|
+
|
|
3
|
+
This module turns paper text or images into structured recipe-defined records.
|
|
4
|
+
It also reconciles text/image results and normalizes extracted units before
|
|
5
|
+
records are stored.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Iterable, Mapping
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
from os import PathLike
|
|
14
|
+
import re
|
|
15
|
+
from json import JSONDecodeError
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from paperminertoolkit.extraction.compression import CompressionConfig
|
|
19
|
+
from paperminertoolkit.extraction.models import ModelConfig, query_images, query_text
|
|
20
|
+
from paperminertoolkit.settings import DEFAULT_MODEL
|
|
21
|
+
from paperminertoolkit.extraction.tokenizer import _ModelConfigSource, count_text_tokens, prompt_token_reserve, usable_input_token_limit
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def token_length(
|
|
25
|
+
prompt: object,
|
|
26
|
+
model: str = DEFAULT_MODEL,
|
|
27
|
+
model_config: _ModelConfigSource | None = None,
|
|
28
|
+
provider: str | None = None,
|
|
29
|
+
) -> int | list[object]:
|
|
30
|
+
"""Estimate the token length of a prompt.
|
|
31
|
+
|
|
32
|
+
Parameters
|
|
33
|
+
----------
|
|
34
|
+
prompt : object
|
|
35
|
+
Text to measure. Non-string values return an empty list for backward
|
|
36
|
+
compatibility.
|
|
37
|
+
model : str, optional
|
|
38
|
+
Model name used for tokenizer selection.
|
|
39
|
+
model_config : _ModelConfigSource or None, optional
|
|
40
|
+
Model configuration used for provider-aware token counting.
|
|
41
|
+
provider : str | None, optional
|
|
42
|
+
Provider name used when ``model_config`` is not supplied.
|
|
43
|
+
|
|
44
|
+
Returns
|
|
45
|
+
-------
|
|
46
|
+
int or list[object]
|
|
47
|
+
Estimated token count, or an empty list for non-string input.
|
|
48
|
+
"""
|
|
49
|
+
if type(prompt) != str:
|
|
50
|
+
return []
|
|
51
|
+
return count_text_tokens(prompt, model_config=model_config, model=model, provider=provider)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _field_schema(recipe: Mapping[str, Any]) -> str:
|
|
55
|
+
"""Render recipe fields as a prompt-readable schema.
|
|
56
|
+
|
|
57
|
+
Parameters
|
|
58
|
+
----------
|
|
59
|
+
recipe : Mapping[str, Any]
|
|
60
|
+
Extraction recipe containing ``search fields`` definitions.
|
|
61
|
+
|
|
62
|
+
Returns
|
|
63
|
+
-------
|
|
64
|
+
str
|
|
65
|
+
Newline-delimited schema entries.
|
|
66
|
+
"""
|
|
67
|
+
lines = []
|
|
68
|
+
for field, config in recipe['search fields'].items():
|
|
69
|
+
lines.append(f'- "{field}": {config["prompt"]}')
|
|
70
|
+
return '\n'.join(lines)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _example_record(recipe: Mapping[str, Any]) -> str:
|
|
74
|
+
"""Build a JSON example from recipe values.
|
|
75
|
+
|
|
76
|
+
Parameters
|
|
77
|
+
----------
|
|
78
|
+
recipe : Mapping[str, Any]
|
|
79
|
+
Extraction recipe containing field examples.
|
|
80
|
+
|
|
81
|
+
Returns
|
|
82
|
+
-------
|
|
83
|
+
str
|
|
84
|
+
Pretty-printed JSON array containing one example record.
|
|
85
|
+
"""
|
|
86
|
+
record = {}
|
|
87
|
+
for field, config in recipe['search fields'].items():
|
|
88
|
+
record[field] = config['example']
|
|
89
|
+
return json.dumps([record], indent=2)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _base_extraction_prompt(recipe: Mapping[str, Any], source: str, source_rules: str) -> str:
|
|
93
|
+
"""Build the shared extraction prompt for a source type.
|
|
94
|
+
|
|
95
|
+
Parameters
|
|
96
|
+
----------
|
|
97
|
+
recipe : Mapping[str, Any]
|
|
98
|
+
Extraction recipe defining the record type and fields.
|
|
99
|
+
source : str
|
|
100
|
+
Human-readable source description for the prompt.
|
|
101
|
+
source_rules : str
|
|
102
|
+
Source-specific extraction instructions.
|
|
103
|
+
|
|
104
|
+
Returns
|
|
105
|
+
-------
|
|
106
|
+
str
|
|
107
|
+
Complete model system prompt.
|
|
108
|
+
"""
|
|
109
|
+
definition = recipe['record definition']
|
|
110
|
+
subject = definition['subject']
|
|
111
|
+
singular = definition['singular']
|
|
112
|
+
plural = definition['plural']
|
|
113
|
+
unit = definition['unit']
|
|
114
|
+
additional_prompts = recipe.get('additional prompts', '')
|
|
115
|
+
return f'''You extract structured records about {subject} from a scientific {source}.
|
|
116
|
+
|
|
117
|
+
Record definition:
|
|
118
|
+
- Each output object represents {unit}.
|
|
119
|
+
- The recipe terminology is "{singular}" for one record subject and "{plural}" for multiple record subjects.
|
|
120
|
+
|
|
121
|
+
Extraction rules:
|
|
122
|
+
- Use only information supported by the provided {source}. Do not infer missing values from general domain knowledge.
|
|
123
|
+
- Prefer explicit reported values over derived or assumed values. Preserve relevant conditions, methods, units, qualifiers, and uncertainties when they are part of the reported value.
|
|
124
|
+
- If multiple distinct {plural} are reported, return one record per {singular} according to the record definition. Do not duplicate records for repeated mentions of the same {singular}.
|
|
125
|
+
- If a field is not supported by the provided {source}, set that field to "None".
|
|
126
|
+
- Use lists only when multiple values are reported for the same field in the same record, unless the field or additional recipe instructions explicitly require a list.
|
|
127
|
+
- Keep values concise but complete enough to preserve scientific meaning.
|
|
128
|
+
{source_rules}
|
|
129
|
+
|
|
130
|
+
Schema. Use these keys exactly and do not add extra keys:
|
|
131
|
+
{_field_schema(recipe)}
|
|
132
|
+
|
|
133
|
+
Additional recipe instructions:
|
|
134
|
+
{additional_prompts}
|
|
135
|
+
|
|
136
|
+
Output contract:
|
|
137
|
+
- Return a JSON array of objects. Return [] if no relevant {plural} are present.
|
|
138
|
+
- Every object must contain every schema key exactly once.
|
|
139
|
+
- Return only JSON. Do not include markdown fences, comments, explanations, or prose.
|
|
140
|
+
|
|
141
|
+
Example output shape:
|
|
142
|
+
{_example_record(recipe)}'''
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def build_text_extraction_prompt(recipe: Mapping[str, Any]) -> str:
|
|
146
|
+
"""Build an extraction prompt for paper text.
|
|
147
|
+
|
|
148
|
+
Parameters
|
|
149
|
+
----------
|
|
150
|
+
recipe : Mapping[str, Any]
|
|
151
|
+
Extraction recipe defining the requested output.
|
|
152
|
+
|
|
153
|
+
Returns
|
|
154
|
+
-------
|
|
155
|
+
str
|
|
156
|
+
Text extraction system prompt.
|
|
157
|
+
"""
|
|
158
|
+
source_rules = '''- Treat abstracts, captions, tables, experimental sections, results, and supporting text as valid evidence.
|
|
159
|
+
- Do not use references, citations, or background discussion as evidence for the paper's own results or observations unless the text clearly states the information belongs to this work.'''
|
|
160
|
+
return _base_extraction_prompt(recipe, 'paper text', source_rules)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def build_image_extraction_prompt(recipe: Mapping[str, Any], with_context: bool = False) -> str:
|
|
164
|
+
"""Build an extraction prompt for paper images.
|
|
165
|
+
|
|
166
|
+
Parameters
|
|
167
|
+
----------
|
|
168
|
+
recipe : Mapping[str, Any]
|
|
169
|
+
Extraction recipe defining the requested output.
|
|
170
|
+
with_context : bool, optional
|
|
171
|
+
Whether accompanying paper text will be provided.
|
|
172
|
+
|
|
173
|
+
Returns
|
|
174
|
+
-------
|
|
175
|
+
str
|
|
176
|
+
Image extraction system prompt.
|
|
177
|
+
"""
|
|
178
|
+
context_rule = '- You may use the supplied paper text as context, but values should still be tied to the image, caption, table, plot labels, legend, or nearby visual evidence.' if with_context else '- Use only information visible in the supplied image or images, including captions, tables, plot labels, axes, legends, annotations, and readable text.'
|
|
179
|
+
source_rules = f'''{context_rule}
|
|
180
|
+
- Actively inspect figures and tables in the image for the requested properties, including captions, table headers, table rows, plot axes, legends, labels, annotations, and inset text.
|
|
181
|
+
- For plots, report values only when they can be read from labels, annotations, tables, or clearly interpretable plotted data.
|
|
182
|
+
- If several images are supplied together, combine evidence across them only when they clearly describe the same record subject or observation.
|
|
183
|
+
- If the supplied image or images are decorative, unreadable, or irrelevant to the schema, return [].'''
|
|
184
|
+
return _base_extraction_prompt(recipe, 'paper image', source_rules)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def build_scrape_prompt(
|
|
188
|
+
recipe: Mapping[str, Any],
|
|
189
|
+
source: str = 'text',
|
|
190
|
+
with_context: bool = False,
|
|
191
|
+
) -> str:
|
|
192
|
+
"""Select an extraction prompt for a source type.
|
|
193
|
+
|
|
194
|
+
Parameters
|
|
195
|
+
----------
|
|
196
|
+
recipe : Mapping[str, Any]
|
|
197
|
+
Extraction recipe defining the requested output.
|
|
198
|
+
source : str, optional
|
|
199
|
+
Source type. ``"image"`` selects the image prompt; all other values
|
|
200
|
+
select the text prompt.
|
|
201
|
+
with_context : bool, optional
|
|
202
|
+
Whether image extraction will include paper text context.
|
|
203
|
+
|
|
204
|
+
Returns
|
|
205
|
+
-------
|
|
206
|
+
str
|
|
207
|
+
Source-specific extraction prompt.
|
|
208
|
+
"""
|
|
209
|
+
if source == 'image':
|
|
210
|
+
return build_image_extraction_prompt(recipe, with_context=with_context)
|
|
211
|
+
return build_text_extraction_prompt(recipe)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def query_model(messages: list[dict[str, Any]], model_config: ModelConfig | None = None) -> str:
|
|
215
|
+
"""Send extraction messages to a text model.
|
|
216
|
+
|
|
217
|
+
Parameters
|
|
218
|
+
----------
|
|
219
|
+
messages : list[dict[str, Any]]
|
|
220
|
+
Provider-neutral chat messages.
|
|
221
|
+
model_config : ModelConfig | None, optional
|
|
222
|
+
Model configuration. The text profile is used by default.
|
|
223
|
+
|
|
224
|
+
Returns
|
|
225
|
+
-------
|
|
226
|
+
str
|
|
227
|
+
Model response text.
|
|
228
|
+
"""
|
|
229
|
+
config = model_config or ModelConfig.from_profile('text')
|
|
230
|
+
return query_text(messages, config=config, max_output_tokens=10000)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _strip_fences(response: str) -> str:
|
|
234
|
+
"""Remove surrounding Markdown code fences from a response.
|
|
235
|
+
|
|
236
|
+
Parameters
|
|
237
|
+
----------
|
|
238
|
+
response : str
|
|
239
|
+
Raw model response.
|
|
240
|
+
|
|
241
|
+
Returns
|
|
242
|
+
-------
|
|
243
|
+
str
|
|
244
|
+
Response without an outer Markdown code fence.
|
|
245
|
+
"""
|
|
246
|
+
response = response.strip()
|
|
247
|
+
fence = chr(96) * 3
|
|
248
|
+
if response.startswith(fence):
|
|
249
|
+
response = re.sub(r'^' + fence + r'(?:json)?', '', response, flags=re.IGNORECASE).strip()
|
|
250
|
+
response = re.sub(fence + r'$', '', response).strip()
|
|
251
|
+
return response
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _json_decoder_scan(response: str) -> list[dict[str, Any]]:
|
|
255
|
+
"""Scan a mixed response for JSON objects and arrays.
|
|
256
|
+
|
|
257
|
+
Parameters
|
|
258
|
+
----------
|
|
259
|
+
response : str
|
|
260
|
+
Model response that may contain prose around JSON values.
|
|
261
|
+
|
|
262
|
+
Returns
|
|
263
|
+
-------
|
|
264
|
+
list[dict[str, Any]]
|
|
265
|
+
Object records decoded from the response.
|
|
266
|
+
"""
|
|
267
|
+
decoder = json.JSONDecoder()
|
|
268
|
+
data = []
|
|
269
|
+
index = 0
|
|
270
|
+
while index < len(response):
|
|
271
|
+
positions = [pos for pos in (response.find('{', index), response.find('[', index)) if pos != -1]
|
|
272
|
+
if not positions:
|
|
273
|
+
break
|
|
274
|
+
start = min(positions)
|
|
275
|
+
try:
|
|
276
|
+
parsed, end = decoder.raw_decode(response[start:])
|
|
277
|
+
except JSONDecodeError:
|
|
278
|
+
index = start + 1
|
|
279
|
+
continue
|
|
280
|
+
if isinstance(parsed, list):
|
|
281
|
+
data.extend(item for item in parsed if isinstance(item, dict))
|
|
282
|
+
elif isinstance(parsed, dict):
|
|
283
|
+
data.append(parsed)
|
|
284
|
+
index = start + end
|
|
285
|
+
return data
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _extract_json_objects(response: str) -> list[dict[str, Any]]:
|
|
289
|
+
"""Parse model output into JSON object records.
|
|
290
|
+
|
|
291
|
+
Parameters
|
|
292
|
+
----------
|
|
293
|
+
response : str
|
|
294
|
+
Raw model response.
|
|
295
|
+
|
|
296
|
+
Returns
|
|
297
|
+
-------
|
|
298
|
+
list[dict[str, Any]]
|
|
299
|
+
Parsed object records.
|
|
300
|
+
|
|
301
|
+
Raises
|
|
302
|
+
------
|
|
303
|
+
ValueError
|
|
304
|
+
If the response contains no valid JSON objects.
|
|
305
|
+
"""
|
|
306
|
+
response = _strip_fences(response)
|
|
307
|
+
try:
|
|
308
|
+
parsed = json.loads(response)
|
|
309
|
+
except JSONDecodeError:
|
|
310
|
+
parsed = None
|
|
311
|
+
if parsed == []:
|
|
312
|
+
return []
|
|
313
|
+
if isinstance(parsed, list):
|
|
314
|
+
return [item for item in parsed if isinstance(item, dict)]
|
|
315
|
+
if isinstance(parsed, dict):
|
|
316
|
+
return [parsed]
|
|
317
|
+
|
|
318
|
+
data = _json_decoder_scan(response)
|
|
319
|
+
if data:
|
|
320
|
+
return data
|
|
321
|
+
compact = response.replace('\n', '')
|
|
322
|
+
for material_json in re.findall(r'\{[^{}]*\}', compact, flags=re.DOTALL):
|
|
323
|
+
try:
|
|
324
|
+
data.append(json.loads(material_json))
|
|
325
|
+
except JSONDecodeError:
|
|
326
|
+
continue
|
|
327
|
+
if data:
|
|
328
|
+
return data
|
|
329
|
+
preview = response[:500].replace('\n', ' ')
|
|
330
|
+
raise ValueError(f'Model response did not contain valid JSON objects. Response preview: {preview}')
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def scrape_text(
|
|
334
|
+
text: str,
|
|
335
|
+
recipe: Mapping[str, Any],
|
|
336
|
+
model_config: ModelConfig | None = None,
|
|
337
|
+
) -> list[dict[str, Any]]:
|
|
338
|
+
"""Extract structured recipe-defined records from paper text.
|
|
339
|
+
|
|
340
|
+
Parameters
|
|
341
|
+
----------
|
|
342
|
+
text : str
|
|
343
|
+
Paper text to analyze.
|
|
344
|
+
recipe : Mapping[str, Any]
|
|
345
|
+
Extraction recipe defining the requested records.
|
|
346
|
+
model_config : ModelConfig | None, optional
|
|
347
|
+
Text model configuration.
|
|
348
|
+
|
|
349
|
+
Returns
|
|
350
|
+
-------
|
|
351
|
+
list[dict[str, Any]]
|
|
352
|
+
Extracted records.
|
|
353
|
+
"""
|
|
354
|
+
prompt = build_scrape_prompt(recipe, source='text')
|
|
355
|
+
messages = [
|
|
356
|
+
{'role': 'system', 'content': prompt},
|
|
357
|
+
{'role': 'user', 'content': text},
|
|
358
|
+
]
|
|
359
|
+
response = query_model(messages, model_config=model_config)
|
|
360
|
+
return _extract_json_objects(response)
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def scrape_images(
|
|
364
|
+
image_paths: list[str],
|
|
365
|
+
recipe: Mapping[str, Any],
|
|
366
|
+
model_config: ModelConfig | None = None,
|
|
367
|
+
context: str | None = None,
|
|
368
|
+
compression_config: CompressionConfig | None = None,
|
|
369
|
+
) -> list[dict[str, Any]]:
|
|
370
|
+
"""Extract structured recipe-defined records from paper images.
|
|
371
|
+
|
|
372
|
+
Parameters
|
|
373
|
+
----------
|
|
374
|
+
image_paths : list[str]
|
|
375
|
+
Local paths to images to analyze together.
|
|
376
|
+
recipe : Mapping[str, Any]
|
|
377
|
+
Extraction recipe defining the requested records.
|
|
378
|
+
model_config : ModelConfig | None, optional
|
|
379
|
+
Vision model configuration.
|
|
380
|
+
context : str | None, optional
|
|
381
|
+
Paper text supplied as additional context.
|
|
382
|
+
compression_config : CompressionConfig | None, optional
|
|
383
|
+
Compression policy for the model payload.
|
|
384
|
+
|
|
385
|
+
Returns
|
|
386
|
+
-------
|
|
387
|
+
list[dict[str, Any]]
|
|
388
|
+
Extracted records.
|
|
389
|
+
"""
|
|
390
|
+
config = model_config or ModelConfig.from_profile('vision')
|
|
391
|
+
prompt = build_scrape_prompt(recipe, source='image', with_context=context is not None)
|
|
392
|
+
response = query_images(prompt,
|
|
393
|
+
image_paths,
|
|
394
|
+
config=config,
|
|
395
|
+
context=context,
|
|
396
|
+
max_output_tokens=10000,
|
|
397
|
+
compression_config=compression_config)
|
|
398
|
+
return _extract_json_objects(response)
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def combine_material_records(
|
|
402
|
+
text_materials: list[dict[str, Any]],
|
|
403
|
+
image_materials: list[dict[str, Any]],
|
|
404
|
+
recipe: Mapping[str, Any],
|
|
405
|
+
model_config: ModelConfig | None = None,
|
|
406
|
+
) -> list[dict[str, Any]]:
|
|
407
|
+
"""Reconcile text-derived and image-derived recipe records.
|
|
408
|
+
|
|
409
|
+
Parameters
|
|
410
|
+
----------
|
|
411
|
+
text_materials : list[dict[str, Any]]
|
|
412
|
+
Records extracted from paper text.
|
|
413
|
+
image_materials : list[dict[str, Any]]
|
|
414
|
+
Records extracted from paper images.
|
|
415
|
+
recipe : Mapping[str, Any]
|
|
416
|
+
Extraction recipe defining the record schema.
|
|
417
|
+
model_config : ModelConfig | None, optional
|
|
418
|
+
Text model configuration used for reconciliation.
|
|
419
|
+
|
|
420
|
+
Returns
|
|
421
|
+
-------
|
|
422
|
+
list[dict[str, Any]]
|
|
423
|
+
Reconciled records.
|
|
424
|
+
"""
|
|
425
|
+
definition = recipe['record definition']
|
|
426
|
+
subject = definition['subject']
|
|
427
|
+
singular = definition['singular']
|
|
428
|
+
plural = definition['plural']
|
|
429
|
+
unit = definition['unit']
|
|
430
|
+
identity_fields = definition['identity fields']
|
|
431
|
+
additional_prompts = recipe.get('additional prompts', '')
|
|
432
|
+
identity_description = ', '.join(f'"{field}"' for field in identity_fields)
|
|
433
|
+
if not identity_description:
|
|
434
|
+
identity_description = 'No primary identity fields are configured; use the full record context.'
|
|
435
|
+
|
|
436
|
+
prompt = f'''You reconcile two sets of structured records about {subject} extracted from the same paper.
|
|
437
|
+
|
|
438
|
+
Each output object represents {unit}. The recipe terminology is "{singular}" for one record subject and "{plural}" for multiple record subjects.
|
|
439
|
+
Compare the text-derived and image-derived records and merge only records that refer to the same {singular}.
|
|
440
|
+
|
|
441
|
+
Primary identity fields:
|
|
442
|
+
{identity_description}
|
|
443
|
+
|
|
444
|
+
Rules:
|
|
445
|
+
- Use the recipe schema keys exactly. Do not add extra keys.
|
|
446
|
+
- Use compatible values in the primary identity fields as the strongest evidence that two records describe the same {singular}. Also consider the full record context and the configured record unit.
|
|
447
|
+
- If one record has a more specific identity than another, merge them only when the less-specific record clearly applies to that same {singular}.
|
|
448
|
+
- Keep records separate when their identity fields or defining context conflict.
|
|
449
|
+
- Do not merge records only because they share a reported value, method, source location, or broad category.
|
|
450
|
+
- Prefer explicit non-None values over None.
|
|
451
|
+
- If text and image records provide complementary fields for the same {singular}, combine them into one record.
|
|
452
|
+
- If text and image records conflict, keep the value that is more specific or better supported; if the conflict cannot be resolved, keep both values as a list.
|
|
453
|
+
- Keep genuinely distinct {plural} as separate records according to the configured record unit.
|
|
454
|
+
- Do not invent values. If neither source supports a field, use "None".
|
|
455
|
+
- Return a JSON array of reconciled records only. Do not include markdown, comments, or prose.
|
|
456
|
+
|
|
457
|
+
Additional recipe instructions:
|
|
458
|
+
{additional_prompts}
|
|
459
|
+
|
|
460
|
+
Schema. Use these keys exactly and do not add extra keys:
|
|
461
|
+
{_field_schema(recipe)}
|
|
462
|
+
|
|
463
|
+
Example output shape:
|
|
464
|
+
{_example_record(recipe)}'''
|
|
465
|
+
payload = {
|
|
466
|
+
'text_extracted_records': text_materials,
|
|
467
|
+
'image_extracted_records': image_materials,
|
|
468
|
+
}
|
|
469
|
+
messages = [
|
|
470
|
+
{'role': 'system', 'content': prompt},
|
|
471
|
+
{'role': 'user', 'content': json.dumps(payload, indent=2)},
|
|
472
|
+
]
|
|
473
|
+
response = query_model(messages, model_config=model_config)
|
|
474
|
+
return _extract_json_objects(response)
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def scrape_pdf(
|
|
478
|
+
filepath: str | PathLike[str],
|
|
479
|
+
recipe: Mapping[str, Any],
|
|
480
|
+
model_config: ModelConfig | None = None,
|
|
481
|
+
) -> list[dict[str, Any]]:
|
|
482
|
+
"""Extract recipe-defined records from a PDF file.
|
|
483
|
+
|
|
484
|
+
Parameters
|
|
485
|
+
----------
|
|
486
|
+
filepath : str | PathLike[str]
|
|
487
|
+
Path to the source PDF.
|
|
488
|
+
recipe : Mapping[str, Any]
|
|
489
|
+
Extraction recipe defining the requested records.
|
|
490
|
+
model_config : ModelConfig | None, optional
|
|
491
|
+
Text model configuration.
|
|
492
|
+
|
|
493
|
+
Returns
|
|
494
|
+
-------
|
|
495
|
+
list[dict[str, Any]]
|
|
496
|
+
Extracted records.
|
|
497
|
+
"""
|
|
498
|
+
from paperminertoolkit.corpus.documents import read_pdf_text
|
|
499
|
+
|
|
500
|
+
return scrape_text(read_pdf_text(filepath), recipe, model_config=model_config)
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def convert_units(
|
|
504
|
+
values: Iterable[object],
|
|
505
|
+
field: str,
|
|
506
|
+
unit: str,
|
|
507
|
+
model_config: ModelConfig | None = None,
|
|
508
|
+
) -> list[str | None]:
|
|
509
|
+
"""Convert extracted values into a target unit with a text model.
|
|
510
|
+
|
|
511
|
+
Parameters
|
|
512
|
+
----------
|
|
513
|
+
values : Iterable[object]
|
|
514
|
+
Extracted values to convert.
|
|
515
|
+
field : str
|
|
516
|
+
Name of the measured field.
|
|
517
|
+
unit : str
|
|
518
|
+
Desired output unit.
|
|
519
|
+
model_config : ModelConfig | None, optional
|
|
520
|
+
Text model configuration.
|
|
521
|
+
|
|
522
|
+
Returns
|
|
523
|
+
-------
|
|
524
|
+
list[str | None]
|
|
525
|
+
Converted values, with missing inputs represented by ``None``.
|
|
526
|
+
"""
|
|
527
|
+
prompt = f'Convert the following values of {field} to {unit}. Each result should be returned as a decimal on a separate line. If the input contains multiple values on one line, return the converted values as a python list on the same line. Only put values in square brackets if multiple values are provided on the line. Do not include the units. If you are unsure how to do the conversion, just return the original value. If a range is given, report this as two decimals with a hyphen/dash inbetween (For example: 1-10). If the value is already in the desired unit, just convert it to a decimal. Do not return "None". Do not return the value as an addition. If text is given and cannot be meaningfully converted, return the same text. Convert "RT" or "Room temperature" to the equivalent of 298.15K. Do not use quotation marks. Make sure that there are as many output values as input.'
|
|
528
|
+
values_str = ''
|
|
529
|
+
memory = []
|
|
530
|
+
for value in values:
|
|
531
|
+
if str(value) in ['nan', "['None']"]:
|
|
532
|
+
memory.append(0)
|
|
533
|
+
else:
|
|
534
|
+
memory.append(1)
|
|
535
|
+
values_str += f'{value}\n'
|
|
536
|
+
config = model_config or ModelConfig.from_profile('text')
|
|
537
|
+
reserve_tokens = prompt_token_reserve(prompt, model_config=config, buffer_tokens=500)
|
|
538
|
+
token_budget = usable_input_token_limit(config, reserve_tokens=reserve_tokens)
|
|
539
|
+
coeff = token_length(values_str, model_config=config) / token_budget
|
|
540
|
+
if coeff <= 1:
|
|
541
|
+
values_strs = [values_str]
|
|
542
|
+
else:
|
|
543
|
+
coeff = math.ceil(coeff)
|
|
544
|
+
char_per_split = math.ceil(len(values_str) / coeff)
|
|
545
|
+
values_strs = []
|
|
546
|
+
current = ''
|
|
547
|
+
for line in values_str.splitlines():
|
|
548
|
+
line = f'{line}\n'
|
|
549
|
+
if current and len(current) + len(line) > char_per_split:
|
|
550
|
+
values_strs.append(current)
|
|
551
|
+
current = ''
|
|
552
|
+
current += line
|
|
553
|
+
if current:
|
|
554
|
+
values_strs.append(current)
|
|
555
|
+
output = []
|
|
556
|
+
temp = []
|
|
557
|
+
if values_strs[0] != '':
|
|
558
|
+
for values_str in values_strs:
|
|
559
|
+
messages = [
|
|
560
|
+
{'role': 'system', 'content': prompt},
|
|
561
|
+
{'role': 'user', 'content': values_str},
|
|
562
|
+
]
|
|
563
|
+
converted_values = query_model(messages, model_config=config).splitlines()
|
|
564
|
+
for value in converted_values:
|
|
565
|
+
temp.append(value)
|
|
566
|
+
index = 0
|
|
567
|
+
for mem in memory:
|
|
568
|
+
if mem == 0:
|
|
569
|
+
output.append(None)
|
|
570
|
+
elif mem == 1:
|
|
571
|
+
output.append(temp[index])
|
|
572
|
+
index += 1
|
|
573
|
+
return output
|