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,486 @@
|
|
|
1
|
+
"""Configure and apply optional Headroom context compression.
|
|
2
|
+
|
|
3
|
+
This module keeps Headroom integration behind small helper functions so scrape
|
|
4
|
+
and model code can decide when to compress without depending on Headroom's
|
|
5
|
+
objects directly.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import math
|
|
11
|
+
from collections.abc import Sequence
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from os import PathLike
|
|
14
|
+
from typing import Any, Protocol
|
|
15
|
+
|
|
16
|
+
from paperminertoolkit.extraction.tokenizer import _ModelConfigSource, count_text_tokens, prompt_token_reserve, usable_input_token_limit
|
|
17
|
+
|
|
18
|
+
COMPRESSION_SCOPES = {'none', 'text', 'images', 'both'}
|
|
19
|
+
COMPRESSION_MODES = {'auto', 'always'}
|
|
20
|
+
FALLBACK_IMAGE_TOKEN_ESTIMATE = 1000
|
|
21
|
+
MIN_COMPRESSION_RATIO = 0.05
|
|
22
|
+
AUTO_RATIO_SAFETY_FACTOR = 0.95
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class _CompressorLike(Protocol):
|
|
26
|
+
"""Structural interface implemented by Headroom compressors."""
|
|
27
|
+
|
|
28
|
+
def compress(self, content: Any) -> Any:
|
|
29
|
+
"""Compress a provider payload."""
|
|
30
|
+
...
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class CompressionConfig:
|
|
35
|
+
"""Store Headroom compression settings for a scrape run.
|
|
36
|
+
|
|
37
|
+
Attributes
|
|
38
|
+
----------
|
|
39
|
+
scope : str
|
|
40
|
+
Content to compress: ``"none"``, ``"text"``, ``"images"``, or
|
|
41
|
+
``"both"``.
|
|
42
|
+
mode : str
|
|
43
|
+
Compression policy, either ``"auto"`` or ``"always"``.
|
|
44
|
+
ratio : float or str
|
|
45
|
+
Target compression ratio, or ``"auto"`` to derive one from the token
|
|
46
|
+
budget.
|
|
47
|
+
content_detection : bool
|
|
48
|
+
Whether Headroom should detect content types with Magika.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
scope: str = 'none'
|
|
52
|
+
mode: str = 'auto'
|
|
53
|
+
ratio: float | str = 'auto'
|
|
54
|
+
content_detection: bool = True
|
|
55
|
+
|
|
56
|
+
def __post_init__(self) -> None:
|
|
57
|
+
"""Normalize and validate compression options after initialization.
|
|
58
|
+
|
|
59
|
+
Raises
|
|
60
|
+
------
|
|
61
|
+
ValueError
|
|
62
|
+
If the scope, mode, or compression ratio is invalid.
|
|
63
|
+
"""
|
|
64
|
+
scope = (self.scope or 'none').lower()
|
|
65
|
+
mode = (self.mode or 'auto').lower()
|
|
66
|
+
ratio = self.ratio
|
|
67
|
+
if scope not in COMPRESSION_SCOPES:
|
|
68
|
+
raise ValueError(f'compression_scope must be one of: {", ".join(sorted(COMPRESSION_SCOPES))}')
|
|
69
|
+
if mode not in COMPRESSION_MODES:
|
|
70
|
+
raise ValueError(f'compression_mode must be one of: {", ".join(sorted(COMPRESSION_MODES))}')
|
|
71
|
+
if isinstance(ratio, str):
|
|
72
|
+
ratio = ratio.strip().lower()
|
|
73
|
+
if ratio != 'auto':
|
|
74
|
+
ratio = float(ratio)
|
|
75
|
+
if ratio != 'auto':
|
|
76
|
+
ratio = float(ratio)
|
|
77
|
+
if ratio <= 0 or ratio > 1:
|
|
78
|
+
raise ValueError('compression_ratio must be "auto" or a number greater than 0 and less than or equal to 1.')
|
|
79
|
+
object.__setattr__(self, 'scope', scope)
|
|
80
|
+
object.__setattr__(self, 'mode', mode)
|
|
81
|
+
object.__setattr__(self, 'ratio', ratio)
|
|
82
|
+
object.__setattr__(self, 'content_detection', bool(self.content_detection))
|
|
83
|
+
|
|
84
|
+
def includes_text(self) -> bool:
|
|
85
|
+
"""Return whether paper text or text context should be compressed.
|
|
86
|
+
|
|
87
|
+
Returns
|
|
88
|
+
-------
|
|
89
|
+
bool
|
|
90
|
+
Whether the configured scope includes text.
|
|
91
|
+
"""
|
|
92
|
+
return self.scope in {'text', 'both'}
|
|
93
|
+
|
|
94
|
+
def includes_images(self) -> bool:
|
|
95
|
+
"""Return whether image payloads should be compressed.
|
|
96
|
+
|
|
97
|
+
Returns
|
|
98
|
+
-------
|
|
99
|
+
bool
|
|
100
|
+
Whether the configured scope includes images.
|
|
101
|
+
"""
|
|
102
|
+
return self.scope in {'images', 'both'}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def compression_config(scope: str = 'none',
|
|
106
|
+
mode: str = 'auto',
|
|
107
|
+
ratio: float | str = 'auto',
|
|
108
|
+
content_detection: bool = True) -> CompressionConfig:
|
|
109
|
+
"""Build a normalized compression configuration.
|
|
110
|
+
|
|
111
|
+
Parameters
|
|
112
|
+
----------
|
|
113
|
+
scope : str, optional
|
|
114
|
+
Content to compress.
|
|
115
|
+
mode : str, optional
|
|
116
|
+
Compression policy.
|
|
117
|
+
ratio : float or str, optional
|
|
118
|
+
Target compression ratio, or ``"auto"``.
|
|
119
|
+
content_detection : bool, optional
|
|
120
|
+
Whether to enable Headroom content detection.
|
|
121
|
+
|
|
122
|
+
Returns
|
|
123
|
+
-------
|
|
124
|
+
CompressionConfig
|
|
125
|
+
Validated compression settings.
|
|
126
|
+
|
|
127
|
+
Raises
|
|
128
|
+
------
|
|
129
|
+
ValueError
|
|
130
|
+
If any option is invalid.
|
|
131
|
+
"""
|
|
132
|
+
return CompressionConfig(scope=scope, mode=mode, ratio=ratio, content_detection=content_detection)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _request_token_budget(prompt: str, model_config: _ModelConfigSource | None) -> int:
|
|
136
|
+
"""Calculate the input budget remaining after prompt reservation.
|
|
137
|
+
|
|
138
|
+
Parameters
|
|
139
|
+
----------
|
|
140
|
+
prompt : str
|
|
141
|
+
Prompt that shares the model context window with the content.
|
|
142
|
+
model_config : _ModelConfigSource or None
|
|
143
|
+
Model configuration used to determine token limits.
|
|
144
|
+
|
|
145
|
+
Returns
|
|
146
|
+
-------
|
|
147
|
+
int
|
|
148
|
+
Number of tokens available for content.
|
|
149
|
+
"""
|
|
150
|
+
reserve_tokens = prompt_token_reserve(prompt, model_config=model_config, buffer_tokens=500)
|
|
151
|
+
return usable_input_token_limit(model_config, reserve_tokens=reserve_tokens)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def ideal_compression_ratio(input_tokens: int, token_budget: int, config: CompressionConfig) -> float:
|
|
155
|
+
"""Calculate the target compression ratio for a request.
|
|
156
|
+
|
|
157
|
+
Parameters
|
|
158
|
+
----------
|
|
159
|
+
input_tokens : int
|
|
160
|
+
Estimated number of input tokens.
|
|
161
|
+
token_budget : int
|
|
162
|
+
Number of tokens available for input content.
|
|
163
|
+
config : CompressionConfig
|
|
164
|
+
Compression settings.
|
|
165
|
+
|
|
166
|
+
Returns
|
|
167
|
+
-------
|
|
168
|
+
float
|
|
169
|
+
Configured or automatically calculated compression ratio.
|
|
170
|
+
"""
|
|
171
|
+
if config.ratio != 'auto':
|
|
172
|
+
return config.ratio
|
|
173
|
+
if input_tokens <= 0:
|
|
174
|
+
return 1.0
|
|
175
|
+
ratio = (token_budget / input_tokens) * AUTO_RATIO_SAFETY_FACTOR
|
|
176
|
+
return max(MIN_COMPRESSION_RATIO, min(1.0, ratio))
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def should_compress_text(
|
|
180
|
+
text: object,
|
|
181
|
+
prompt: str,
|
|
182
|
+
model_config: _ModelConfigSource | None,
|
|
183
|
+
config: CompressionConfig,
|
|
184
|
+
) -> bool:
|
|
185
|
+
"""Determine whether text should be compressed before analysis.
|
|
186
|
+
|
|
187
|
+
Parameters
|
|
188
|
+
----------
|
|
189
|
+
text : object
|
|
190
|
+
Candidate text content.
|
|
191
|
+
prompt : str
|
|
192
|
+
Prompt that accompanies the content.
|
|
193
|
+
model_config : _ModelConfigSource or None
|
|
194
|
+
Model configuration used for token estimation.
|
|
195
|
+
config : CompressionConfig
|
|
196
|
+
Compression settings.
|
|
197
|
+
|
|
198
|
+
Returns
|
|
199
|
+
-------
|
|
200
|
+
bool
|
|
201
|
+
Whether the text should be compressed.
|
|
202
|
+
"""
|
|
203
|
+
if not config.includes_text() or not isinstance(text, str) or text == '':
|
|
204
|
+
return False
|
|
205
|
+
if config.mode == 'always':
|
|
206
|
+
return True
|
|
207
|
+
return count_text_tokens(text, model_config=model_config) > _request_token_budget(prompt, model_config)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def should_compress_images(
|
|
211
|
+
image_paths: Sequence[str | PathLike[str]],
|
|
212
|
+
prompt: str,
|
|
213
|
+
context: str | None,
|
|
214
|
+
model_config: _ModelConfigSource | None,
|
|
215
|
+
config: CompressionConfig,
|
|
216
|
+
) -> bool:
|
|
217
|
+
"""Determine whether an image request should be compressed.
|
|
218
|
+
|
|
219
|
+
Parameters
|
|
220
|
+
----------
|
|
221
|
+
image_paths : Sequence[str or os.PathLike[str]]
|
|
222
|
+
Local image paths included in the request.
|
|
223
|
+
prompt : str
|
|
224
|
+
Prompt that accompanies the images.
|
|
225
|
+
context : str or None
|
|
226
|
+
Optional text context included in the request.
|
|
227
|
+
model_config : _ModelConfigSource or None
|
|
228
|
+
Model configuration used for token estimation.
|
|
229
|
+
config : CompressionConfig
|
|
230
|
+
Compression settings.
|
|
231
|
+
|
|
232
|
+
Returns
|
|
233
|
+
-------
|
|
234
|
+
bool
|
|
235
|
+
Whether the image request should be compressed.
|
|
236
|
+
"""
|
|
237
|
+
if not config.includes_images() or not image_paths:
|
|
238
|
+
return False
|
|
239
|
+
if config.mode == 'always':
|
|
240
|
+
return True
|
|
241
|
+
text_tokens = count_text_tokens(context or '', model_config=model_config)
|
|
242
|
+
image_tokens = estimate_image_tokens(image_paths, model_config)
|
|
243
|
+
return text_tokens + image_tokens > _request_token_budget(prompt, model_config)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _image_size(image_path: str | PathLike[str]) -> tuple[int, int] | None:
|
|
247
|
+
"""Read the dimensions of a local image.
|
|
248
|
+
|
|
249
|
+
Parameters
|
|
250
|
+
----------
|
|
251
|
+
image_path : str or path-like
|
|
252
|
+
Path to an image file.
|
|
253
|
+
|
|
254
|
+
Returns
|
|
255
|
+
-------
|
|
256
|
+
tuple[int, int] or None
|
|
257
|
+
Image width and height, or ``None`` when dimensions cannot be read.
|
|
258
|
+
"""
|
|
259
|
+
try:
|
|
260
|
+
from PIL import Image
|
|
261
|
+
with Image.open(image_path) as image:
|
|
262
|
+
return image.size
|
|
263
|
+
except Exception:
|
|
264
|
+
pass
|
|
265
|
+
try:
|
|
266
|
+
with open(image_path, 'rb') as image_file:
|
|
267
|
+
header = image_file.read(24)
|
|
268
|
+
if header.startswith(b'\x89PNG\r\n\x1a\n') and header[12:16] == b'IHDR':
|
|
269
|
+
return int.from_bytes(header[16:20], 'big'), int.from_bytes(header[20:24], 'big')
|
|
270
|
+
except Exception:
|
|
271
|
+
return None
|
|
272
|
+
return None
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def estimate_image_tokens(
|
|
276
|
+
image_paths: Sequence[str | PathLike[str]],
|
|
277
|
+
model_config: _ModelConfigSource | None = None,
|
|
278
|
+
) -> int:
|
|
279
|
+
"""Estimate image input tokens for a model provider.
|
|
280
|
+
|
|
281
|
+
Parameters
|
|
282
|
+
----------
|
|
283
|
+
image_paths : Sequence[str or os.PathLike[str]]
|
|
284
|
+
Local image paths included in the request.
|
|
285
|
+
model_config : _ModelConfigSource or None, optional
|
|
286
|
+
Model configuration identifying the provider.
|
|
287
|
+
|
|
288
|
+
Returns
|
|
289
|
+
-------
|
|
290
|
+
int
|
|
291
|
+
Estimated number of image input tokens.
|
|
292
|
+
"""
|
|
293
|
+
provider = str(getattr(model_config, 'provider', '') or '').lower().replace('_', '-')
|
|
294
|
+
total = 0
|
|
295
|
+
for image_path in image_paths or []:
|
|
296
|
+
size = _image_size(image_path)
|
|
297
|
+
if not size:
|
|
298
|
+
total += FALLBACK_IMAGE_TOKEN_ESTIMATE
|
|
299
|
+
continue
|
|
300
|
+
width, height = size
|
|
301
|
+
if provider == 'anthropic':
|
|
302
|
+
total += max(1, math.ceil(width * height / 750))
|
|
303
|
+
elif provider in {'openai', 'local'}:
|
|
304
|
+
tiles = math.ceil(width / 512) * math.ceil(height / 512)
|
|
305
|
+
total += 85 + 170 * tiles
|
|
306
|
+
else:
|
|
307
|
+
total += max(FALLBACK_IMAGE_TOKEN_ESTIMATE, math.ceil(width * height / 750))
|
|
308
|
+
return total
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _compressed_content(result: Any) -> Any:
|
|
312
|
+
"""Extract content from common Headroom result shapes.
|
|
313
|
+
|
|
314
|
+
Parameters
|
|
315
|
+
----------
|
|
316
|
+
result : Any
|
|
317
|
+
Value returned by a Headroom compressor.
|
|
318
|
+
|
|
319
|
+
Returns
|
|
320
|
+
-------
|
|
321
|
+
Any
|
|
322
|
+
Extracted compressed content, or the string form of an unknown result.
|
|
323
|
+
"""
|
|
324
|
+
if isinstance(result, (str, list, tuple)):
|
|
325
|
+
return result
|
|
326
|
+
for name in ['compressed', 'content', 'text', 'output']:
|
|
327
|
+
value = getattr(result, name, None)
|
|
328
|
+
if value is not None:
|
|
329
|
+
return value
|
|
330
|
+
if isinstance(result, dict):
|
|
331
|
+
for name in ['compressed', 'content', 'text', 'output']:
|
|
332
|
+
value = result.get(name)
|
|
333
|
+
if value is not None:
|
|
334
|
+
return value
|
|
335
|
+
return str(result)
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _universal_compressor(
|
|
339
|
+
compression_ratio: float = 0.5,
|
|
340
|
+
content_detection: bool = True,
|
|
341
|
+
) -> _CompressorLike:
|
|
342
|
+
"""Create a Headroom compressor with safe defaults.
|
|
343
|
+
|
|
344
|
+
Parameters
|
|
345
|
+
----------
|
|
346
|
+
compression_ratio : float, optional
|
|
347
|
+
Target output-to-input size ratio.
|
|
348
|
+
content_detection : bool, optional
|
|
349
|
+
Whether Headroom should detect content types with Magika.
|
|
350
|
+
|
|
351
|
+
Returns
|
|
352
|
+
-------
|
|
353
|
+
_CompressorLike
|
|
354
|
+
Configured universal compressor.
|
|
355
|
+
|
|
356
|
+
Raises
|
|
357
|
+
------
|
|
358
|
+
RuntimeError
|
|
359
|
+
If the optional ``headroom-ai`` package is unavailable.
|
|
360
|
+
"""
|
|
361
|
+
try:
|
|
362
|
+
from headroom.compression import UniversalCompressor, UniversalCompressorConfig
|
|
363
|
+
except ImportError as e:
|
|
364
|
+
raise RuntimeError('Headroom universal compression requires the headroom-ai package.') from e
|
|
365
|
+
config = UniversalCompressorConfig(
|
|
366
|
+
compression_ratio_target=compression_ratio,
|
|
367
|
+
use_magika=content_detection,
|
|
368
|
+
use_entropy_preservation=True,
|
|
369
|
+
ccr_enabled=False,
|
|
370
|
+
)
|
|
371
|
+
return UniversalCompressor(config)
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def compress_content(
|
|
375
|
+
content: Any,
|
|
376
|
+
prompt: str = '',
|
|
377
|
+
compression_ratio: float = 0.5,
|
|
378
|
+
content_detection: bool = True,
|
|
379
|
+
) -> Any:
|
|
380
|
+
"""Compress content with Headroom's universal compressor.
|
|
381
|
+
|
|
382
|
+
Parameters
|
|
383
|
+
----------
|
|
384
|
+
content : Any
|
|
385
|
+
Text or provider-shaped message payload to compress.
|
|
386
|
+
prompt : str, optional
|
|
387
|
+
Prompt associated with the content. Reserved for compressor adapters.
|
|
388
|
+
compression_ratio : float, optional
|
|
389
|
+
Target output-to-input size ratio.
|
|
390
|
+
content_detection : bool, optional
|
|
391
|
+
Whether Headroom should detect content types with Magika.
|
|
392
|
+
|
|
393
|
+
Returns
|
|
394
|
+
-------
|
|
395
|
+
Any
|
|
396
|
+
Compressed content, or the original content when compression is empty.
|
|
397
|
+
|
|
398
|
+
Raises
|
|
399
|
+
------
|
|
400
|
+
RuntimeError
|
|
401
|
+
If the optional ``headroom-ai`` package is unavailable.
|
|
402
|
+
"""
|
|
403
|
+
compressor = _universal_compressor(
|
|
404
|
+
compression_ratio=compression_ratio,
|
|
405
|
+
content_detection=content_detection,
|
|
406
|
+
)
|
|
407
|
+
result = compressor.compress(content)
|
|
408
|
+
compressed = _compressed_content(result)
|
|
409
|
+
return compressed if compressed else content
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def maybe_compress_text(
|
|
413
|
+
text: str,
|
|
414
|
+
prompt: str,
|
|
415
|
+
model_config: _ModelConfigSource | None,
|
|
416
|
+
config: CompressionConfig,
|
|
417
|
+
) -> Any:
|
|
418
|
+
"""Apply compression to text when required by the configured policy.
|
|
419
|
+
|
|
420
|
+
Parameters
|
|
421
|
+
----------
|
|
422
|
+
text : str
|
|
423
|
+
Text to evaluate and optionally compress.
|
|
424
|
+
prompt : str
|
|
425
|
+
Prompt that accompanies the text.
|
|
426
|
+
model_config : _ModelConfigSource or None
|
|
427
|
+
Model configuration used for token estimation.
|
|
428
|
+
config : CompressionConfig
|
|
429
|
+
Compression settings.
|
|
430
|
+
|
|
431
|
+
Returns
|
|
432
|
+
-------
|
|
433
|
+
Any
|
|
434
|
+
Compressed content or the original text.
|
|
435
|
+
"""
|
|
436
|
+
if should_compress_text(text, prompt, model_config, config):
|
|
437
|
+
input_tokens = count_text_tokens(text, model_config=model_config)
|
|
438
|
+
token_budget = _request_token_budget(prompt, model_config)
|
|
439
|
+
ratio = ideal_compression_ratio(input_tokens, token_budget, config)
|
|
440
|
+
return compress_content(text,
|
|
441
|
+
prompt=prompt,
|
|
442
|
+
compression_ratio=ratio,
|
|
443
|
+
content_detection=config.content_detection)
|
|
444
|
+
return text
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def maybe_compress_image_messages(messages: list[dict[str, Any]],
|
|
448
|
+
image_paths: Sequence[str | PathLike[str]],
|
|
449
|
+
prompt: str,
|
|
450
|
+
context: str | None,
|
|
451
|
+
model_config: _ModelConfigSource | None,
|
|
452
|
+
config: CompressionConfig | None) -> Any:
|
|
453
|
+
"""Apply compression to image messages when required by policy.
|
|
454
|
+
|
|
455
|
+
Parameters
|
|
456
|
+
----------
|
|
457
|
+
messages : list[dict[str, Any]]
|
|
458
|
+
Provider-shaped messages containing image content.
|
|
459
|
+
image_paths : Sequence[str or os.PathLike[str]]
|
|
460
|
+
Local paths for images represented in ``messages``.
|
|
461
|
+
prompt : str
|
|
462
|
+
Prompt that accompanies the images.
|
|
463
|
+
context : str or None
|
|
464
|
+
Optional text context included in the request.
|
|
465
|
+
model_config : _ModelConfigSource or None
|
|
466
|
+
Model configuration used for token estimation.
|
|
467
|
+
config : CompressionConfig or None
|
|
468
|
+
Compression settings, or ``None`` to disable compression.
|
|
469
|
+
|
|
470
|
+
Returns
|
|
471
|
+
-------
|
|
472
|
+
Any
|
|
473
|
+
Compressed messages or the original message list.
|
|
474
|
+
"""
|
|
475
|
+
if config is None or not should_compress_images(image_paths, prompt, context, model_config, config):
|
|
476
|
+
return messages
|
|
477
|
+
input_tokens = count_text_tokens(context or '', model_config=model_config) + estimate_image_tokens(
|
|
478
|
+
image_paths,
|
|
479
|
+
model_config,
|
|
480
|
+
)
|
|
481
|
+
token_budget = _request_token_budget(prompt, model_config)
|
|
482
|
+
ratio = ideal_compression_ratio(input_tokens, token_budget, config)
|
|
483
|
+
return compress_content(messages,
|
|
484
|
+
prompt=prompt,
|
|
485
|
+
compression_ratio=ratio,
|
|
486
|
+
content_detection=config.content_detection)
|