sparrow-parse 1.6.2__tar.gz → 1.6.3__tar.gz
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.
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/PKG-INFO +13 -13
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/setup.py +10 -10
- sparrow_parse-1.6.3/sparrow_parse/__init__.py +1 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse/extractors/vllm_extractor.py +4 -0
- sparrow_parse-1.6.3/sparrow_parse/test_extraction_mistral.py +277 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse/vlmb/inference_factory.py +4 -2
- sparrow_parse-1.6.3/sparrow_parse/vlmb/mistral_inference.py +517 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse.egg-info/PKG-INFO +13 -13
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse.egg-info/requires.txt +12 -12
- sparrow_parse-1.6.2/sparrow_parse/__init__.py +0 -1
- sparrow_parse-1.6.2/sparrow_parse/test_extraction_mistral.py +0 -164
- sparrow_parse-1.6.2/sparrow_parse/vlmb/mistral_inference.py +0 -354
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/README.md +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/setup.cfg +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse/__main__.py +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse/extractors/__init__.py +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse/helpers/__init__.py +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse/helpers/image_optimizer.py +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse/helpers/pdf_optimizer.py +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse/processors/__init__.py +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse/processors/table_structure_processor.py +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse/test_extraction_mlx.py +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse/test_extraction_ollama.py +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse/test_extraction_vllm.py +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse/vlmb/__init__.py +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse/vlmb/huggingface_inference.py +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse/vlmb/inference_base.py +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse/vlmb/local_gpu_inference.py +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse/vlmb/mlx_inference.py +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse/vlmb/ollama_inference.py +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse/vlmb/vllm_inference.py +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse.egg-info/SOURCES.txt +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse.egg-info/dependency_links.txt +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse.egg-info/entry_points.txt +0 -0
- {sparrow_parse-1.6.2 → sparrow_parse-1.6.3}/sparrow_parse.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: sparrow-parse
|
|
3
|
-
Version: 1.6.
|
|
3
|
+
Version: 1.6.3
|
|
4
4
|
Summary: Sparrow Parse is a Python package (part of Sparrow) for parsing and extracting information from documents.
|
|
5
5
|
Home-page: https://github.com/katanaml/sparrow/tree/main/sparrow-data/parse
|
|
6
6
|
Author: Andrej Baranovskij
|
|
@@ -15,37 +15,37 @@ Classifier: Programming Language :: Python :: 3.10
|
|
|
15
15
|
Requires-Python: >=3.12
|
|
16
16
|
Description-Content-Type: text/markdown
|
|
17
17
|
Requires-Dist: rich
|
|
18
|
-
Requires-Dist: sentence-transformers==6.
|
|
19
|
-
Requires-Dist: pypdf==7.1.
|
|
18
|
+
Requires-Dist: sentence-transformers==6.3.0
|
|
19
|
+
Requires-Dist: pypdf==7.1.1
|
|
20
20
|
Requires-Dist: gradio_client==2.7.2
|
|
21
21
|
Requires-Dist: pdf2image==1.17.0
|
|
22
22
|
Requires-Dist: ollama==0.6.3
|
|
23
23
|
Requires-Dist: addict==2.4.0
|
|
24
24
|
Requires-Dist: matplotlib==3.11.2
|
|
25
|
-
Requires-Dist: mistralai==3.
|
|
25
|
+
Requires-Dist: mistralai==3.9.0
|
|
26
26
|
Provides-Extra: mlx
|
|
27
27
|
Requires-Dist: transformers==5.14.0; extra == "mlx"
|
|
28
28
|
Requires-Dist: torch==2.15.0; extra == "mlx"
|
|
29
29
|
Requires-Dist: torchvision==0.29.2; extra == "mlx"
|
|
30
|
-
Requires-Dist: numpy==2.5.
|
|
31
|
-
Requires-Dist: mistralai==3.
|
|
32
|
-
Requires-Dist: mlx==0.32.
|
|
33
|
-
Requires-Dist: mlx-vlm==0.
|
|
30
|
+
Requires-Dist: numpy==2.5.5; extra == "mlx"
|
|
31
|
+
Requires-Dist: mistralai==3.9.0; extra == "mlx"
|
|
32
|
+
Requires-Dist: mlx==0.32.5; (sys_platform == "darwin" and platform_machine == "arm64") and extra == "mlx"
|
|
33
|
+
Requires-Dist: mlx-vlm==0.8.1; (sys_platform == "darwin" and platform_machine == "arm64") and extra == "mlx"
|
|
34
34
|
Provides-Extra: linux
|
|
35
35
|
Requires-Dist: transformers==5.9.0; extra == "linux"
|
|
36
36
|
Requires-Dist: torch==2.11.0; extra == "linux"
|
|
37
37
|
Requires-Dist: torchvision==0.26.0; extra == "linux"
|
|
38
38
|
Requires-Dist: numpy; extra == "linux"
|
|
39
|
-
Requires-Dist: mistralai==3.
|
|
39
|
+
Requires-Dist: mistralai==3.9.0; extra == "linux"
|
|
40
40
|
Requires-Dist: vllm==0.23.0; sys_platform == "linux" and extra == "linux"
|
|
41
41
|
Provides-Extra: all
|
|
42
42
|
Requires-Dist: transformers==5.14.0; extra == "all"
|
|
43
43
|
Requires-Dist: torch==2.15.0; extra == "all"
|
|
44
44
|
Requires-Dist: torchvision==0.29.2; extra == "all"
|
|
45
|
-
Requires-Dist: numpy==2.5.
|
|
46
|
-
Requires-Dist: mistralai==3.
|
|
47
|
-
Requires-Dist: mlx==0.32.
|
|
48
|
-
Requires-Dist: mlx-vlm==0.
|
|
45
|
+
Requires-Dist: numpy==2.5.5; extra == "all"
|
|
46
|
+
Requires-Dist: mistralai==3.9.0; extra == "all"
|
|
47
|
+
Requires-Dist: mlx==0.32.5; (sys_platform == "darwin" and platform_machine == "arm64") and extra == "all"
|
|
48
|
+
Requires-Dist: mlx-vlm==0.8.1; (sys_platform == "darwin" and platform_machine == "arm64") and extra == "all"
|
|
49
49
|
Requires-Dist: vllm==0.23.0; sys_platform == "linux" and extra == "all"
|
|
50
50
|
Dynamic: author
|
|
51
51
|
Dynamic: author-email
|
|
@@ -8,7 +8,7 @@ with open("requirements.txt", "r", encoding="utf-8") as fh:
|
|
|
8
8
|
|
|
9
9
|
setup(
|
|
10
10
|
name="sparrow-parse",
|
|
11
|
-
version="1.6.
|
|
11
|
+
version="1.6.3",
|
|
12
12
|
author="Andrej Baranovskij",
|
|
13
13
|
author_email="andrejus.baranovskis@gmail.com",
|
|
14
14
|
description="Sparrow Parse is a Python package (part of Sparrow) for parsing and extracting information from documents.",
|
|
@@ -30,27 +30,27 @@ setup(
|
|
|
30
30
|
"transformers==5.14.0",
|
|
31
31
|
"torch==2.15.0",
|
|
32
32
|
"torchvision==0.29.2",
|
|
33
|
-
"numpy==2.5.
|
|
34
|
-
"mistralai==3.
|
|
35
|
-
"mlx==0.32.
|
|
36
|
-
"mlx-vlm==0.
|
|
33
|
+
"numpy==2.5.5",
|
|
34
|
+
"mistralai==3.9.0",
|
|
35
|
+
"mlx==0.32.5; sys_platform == 'darwin' and platform_machine == 'arm64'",
|
|
36
|
+
"mlx-vlm==0.8.1; sys_platform == 'darwin' and platform_machine == 'arm64'",
|
|
37
37
|
],
|
|
38
38
|
"linux": [
|
|
39
39
|
"transformers==5.9.0",
|
|
40
40
|
"torch==2.11.0",
|
|
41
41
|
"torchvision==0.26.0",
|
|
42
42
|
"numpy",
|
|
43
|
-
"mistralai==3.
|
|
43
|
+
"mistralai==3.9.0",
|
|
44
44
|
"vllm==0.23.0; sys_platform == 'linux'",
|
|
45
45
|
],
|
|
46
46
|
"all": [
|
|
47
47
|
"transformers==5.14.0",
|
|
48
48
|
"torch==2.15.0",
|
|
49
49
|
"torchvision==0.29.2",
|
|
50
|
-
"numpy==2.5.
|
|
51
|
-
"mistralai==3.
|
|
52
|
-
"mlx==0.32.
|
|
53
|
-
"mlx-vlm==0.
|
|
50
|
+
"numpy==2.5.5",
|
|
51
|
+
"mistralai==3.9.0",
|
|
52
|
+
"mlx==0.32.5; sys_platform == 'darwin' and platform_machine == 'arm64'",
|
|
53
|
+
"mlx-vlm==0.8.1; sys_platform == 'darwin' and platform_machine == 'arm64'",
|
|
54
54
|
"vllm==0.23.0; sys_platform == 'linux'",
|
|
55
55
|
],
|
|
56
56
|
},
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = '1.6.3'
|
|
@@ -263,10 +263,14 @@ if __name__ == "__main__":
|
|
|
263
263
|
extractor = VLLMExtractor()
|
|
264
264
|
|
|
265
265
|
# # export HF_TOKEN="hf_"
|
|
266
|
+
# # export MISTRAL_API_KEY="..." (Mistral also reads MISTRAL_SERVER_URL, MISTRAL_SHOW_PROMPT, MISTRAL_SHOW_THINKING and MISTRAL_MAX_WORKERS, both optional)
|
|
266
267
|
# config = {
|
|
267
268
|
# "method": "mlx", # Could be 'huggingface', 'mlx', 'ollama', 'mistral' or 'local_gpu'
|
|
268
269
|
# # "model_name": "lmstudio-community/Mistral-Small-3.2-24B-Instruct-2506-MLX-8bit",
|
|
269
270
|
# "model_name": "mlx-community/Ministral-3-14B-Instruct-2512-8bit",
|
|
271
|
+
# # "model_name": "mistral-large-4",
|
|
272
|
+
# # "model_name": "mistral-ocr-4-1",
|
|
273
|
+
# # "ocr_model_name": "mistral-ocr-4-1",
|
|
270
274
|
# # "model_name": "deepseek-ocr:latest",
|
|
271
275
|
# # "model_name": "mlx-community/DeepSeek-OCR-2-bf16",
|
|
272
276
|
# # "model_name": "mlx-community/dots.ocr-bf16",
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import base64
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
import time
|
|
6
|
+
import mimetypes
|
|
7
|
+
from rich import print
|
|
8
|
+
from rich.markup import escape
|
|
9
|
+
from mistralai.client import Mistral
|
|
10
|
+
|
|
11
|
+
# Mistral OCR block type -> element category (edit as needed)
|
|
12
|
+
CATEGORY_MAP = {
|
|
13
|
+
"title": "Section-header",
|
|
14
|
+
"text": "Text",
|
|
15
|
+
"list": "List-item",
|
|
16
|
+
"table": "Table",
|
|
17
|
+
"image": "Picture",
|
|
18
|
+
"equation": "Formula",
|
|
19
|
+
"caption": "Caption",
|
|
20
|
+
"header": "Page-header",
|
|
21
|
+
"footer": "Page-footer",
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
DEFAULT_IMAGE = "images/bonds_table.png"
|
|
25
|
+
PROMPT = 'retrieve [{"instrument_name":"str", "valuation":"int"}]. return response in JSON format'
|
|
26
|
+
|
|
27
|
+
# Print the prompt before the chat call (debug)
|
|
28
|
+
SHOW_PROMPT = True
|
|
29
|
+
|
|
30
|
+
# Reasoning effort sent to the API. None = parameter not sent (the model default applies).
|
|
31
|
+
# Small 4: "none" or "high". Large 4: "low", "medium" or "high".
|
|
32
|
+
REASONING_EFFORT = "low"
|
|
33
|
+
# Print the model's thinking (only returned when reasoning is on)
|
|
34
|
+
SHOW_THINKING = True
|
|
35
|
+
|
|
36
|
+
# OCR + chat mode: also send the image to the chat model (False = the chat model gets the OCR text only)
|
|
37
|
+
OCR_CHAT_WITH_IMAGE = False
|
|
38
|
+
|
|
39
|
+
# Regional endpoint. Default is the EU endpoint; override with MISTRAL_SERVER_URL.
|
|
40
|
+
# Global (no location commitment): https://api.mistral.ai
|
|
41
|
+
SERVER_URL = os.environ.get("MISTRAL_SERVER_URL", "https://api.eu.mistral.ai")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def print_prompt(prompt):
|
|
45
|
+
"""Print the prompt before the chat call (debug)."""
|
|
46
|
+
print(f"=== PROMPT ({len(prompt)} characters) ===")
|
|
47
|
+
# escape(): the prompt contains square brackets, which rich would otherwise treat as markup
|
|
48
|
+
print(escape(prompt))
|
|
49
|
+
print("=== END OF PROMPT ===")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def encode_image(image_path):
|
|
53
|
+
"""Read an image file and return it as a base64 data URL."""
|
|
54
|
+
mime_type = mimetypes.guess_type(image_path)[0] or "image/png"
|
|
55
|
+
with open(image_path, "rb") as f:
|
|
56
|
+
image_data = base64.b64encode(f.read()).decode("utf-8")
|
|
57
|
+
return f"data:{mime_type};base64,{image_data}"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def normalize_table_html(html):
|
|
61
|
+
"""
|
|
62
|
+
Normalize Mistral table HTML:
|
|
63
|
+
<br/> and line breaks become spaces, header row goes into <thead>, the rest into <tbody>.
|
|
64
|
+
"""
|
|
65
|
+
html = re.sub(r"<br\s*/?>", " ", html)
|
|
66
|
+
html = re.sub(r"\s+", " ", html).strip()
|
|
67
|
+
match = re.match(r"^<table>(<tr>.*?</tr>)(.*)</table>$", html, re.DOTALL)
|
|
68
|
+
if match and "<th>" in match.group(1):
|
|
69
|
+
html = f"<table><thead>{match.group(1)}</thead><tbody>{match.group(2)}</tbody></table>"
|
|
70
|
+
return html
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def blocks_to_elements(page):
|
|
74
|
+
"""
|
|
75
|
+
Convert Mistral OCR blocks of one page into a list of elements:
|
|
76
|
+
{"category": ..., "text": ...}. Bounding boxes are not needed by the pipeline, so they are left out.
|
|
77
|
+
"""
|
|
78
|
+
elements = []
|
|
79
|
+
for block in page.blocks:
|
|
80
|
+
text = block.content
|
|
81
|
+
# With table_format="html", a table block's content is already the full table HTML
|
|
82
|
+
if block.type == "table" and text:
|
|
83
|
+
text = normalize_table_html(text)
|
|
84
|
+
elements.append({
|
|
85
|
+
"category": CATEGORY_MAP.get(block.type, block.type),
|
|
86
|
+
"text": text
|
|
87
|
+
})
|
|
88
|
+
return elements
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def run_ocr(client, model, data_url):
|
|
92
|
+
"""
|
|
93
|
+
Run Mistral OCR on the image and print the extracted elements, one list per page.
|
|
94
|
+
Returns the list of per-page element lists. No extraction step.
|
|
95
|
+
"""
|
|
96
|
+
ocr_response = client.ocr.process(
|
|
97
|
+
model=model,
|
|
98
|
+
document={
|
|
99
|
+
"type": "image_url",
|
|
100
|
+
"image_url": data_url
|
|
101
|
+
},
|
|
102
|
+
table_format="html",
|
|
103
|
+
extract_footer=True,
|
|
104
|
+
confidence_scores_granularity="page",
|
|
105
|
+
include_blocks=True
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
# OCR is billed per page, not per token. Print everything the API returns in usage_info
|
|
109
|
+
# (field names may differ by SDK version), so any token fields would show up here too.
|
|
110
|
+
usage_info = getattr(ocr_response, "usage_info", None)
|
|
111
|
+
if usage_info is not None:
|
|
112
|
+
print(f"OCR pages processed: {getattr(usage_info, 'pages_processed', 'n/a')}")
|
|
113
|
+
print(f"OCR usage_info: {usage_info}")
|
|
114
|
+
|
|
115
|
+
results = []
|
|
116
|
+
for page in ocr_response.pages:
|
|
117
|
+
if page.confidence_scores:
|
|
118
|
+
print(f"Page {page.index} confidence: {page.confidence_scores.average_page_confidence_score}")
|
|
119
|
+
|
|
120
|
+
if not page.blocks:
|
|
121
|
+
print(f"Page {page.index}: no blocks returned (needs OCR 4 or newer with include_blocks=True)")
|
|
122
|
+
continue
|
|
123
|
+
|
|
124
|
+
elements = blocks_to_elements(page)
|
|
125
|
+
results.append(elements)
|
|
126
|
+
|
|
127
|
+
print(f"=== EXTRACTED JSON, page {page.index + 1} ===")
|
|
128
|
+
print(json.dumps(elements, indent=2, ensure_ascii=False))
|
|
129
|
+
|
|
130
|
+
return results
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def split_content(content):
|
|
134
|
+
"""
|
|
135
|
+
Split message content into (answer_text, thinking_text).
|
|
136
|
+
Without reasoning the content is a plain string; with reasoning it is a list of chunks
|
|
137
|
+
(a thinking chunk and a text chunk).
|
|
138
|
+
"""
|
|
139
|
+
if isinstance(content, str):
|
|
140
|
+
return content, ""
|
|
141
|
+
answer, thinking = [], []
|
|
142
|
+
for chunk in content:
|
|
143
|
+
kind = getattr(chunk, "type", None)
|
|
144
|
+
if kind == "thinking":
|
|
145
|
+
for part in getattr(chunk, "thinking", None) or []:
|
|
146
|
+
thinking.append(getattr(part, "text", "") or "")
|
|
147
|
+
elif kind == "text":
|
|
148
|
+
answer.append(getattr(chunk, "text", "") or "")
|
|
149
|
+
return "".join(answer), "".join(thinking)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def run_chat(client, model, data_url, prompt):
|
|
153
|
+
"""
|
|
154
|
+
Send the prompt, and the image if data_url is given, to a Mistral chat model (e.g. Mistral Small).
|
|
155
|
+
With data_url=None the call is text-only. Returns the extracted JSON.
|
|
156
|
+
"""
|
|
157
|
+
content = [{"type": "text", "text": prompt}]
|
|
158
|
+
if data_url:
|
|
159
|
+
content.append({"type": "image_url", "image_url": data_url})
|
|
160
|
+
|
|
161
|
+
extra_params = {}
|
|
162
|
+
if REASONING_EFFORT:
|
|
163
|
+
extra_params["reasoning_effort"] = REASONING_EFFORT
|
|
164
|
+
|
|
165
|
+
chat_response = client.chat.complete(
|
|
166
|
+
model=model,
|
|
167
|
+
messages=[
|
|
168
|
+
{
|
|
169
|
+
"role": "user",
|
|
170
|
+
"content": content
|
|
171
|
+
}
|
|
172
|
+
],
|
|
173
|
+
response_format={"type": "json_object"},
|
|
174
|
+
temperature=0,
|
|
175
|
+
top_p=1, # Large 4 rejects temperature=0 unless top_p is 1 (greedy sampling)
|
|
176
|
+
**extra_params
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
# Token usage per call; prompt tokens include the image tokens
|
|
180
|
+
usage = chat_response.usage
|
|
181
|
+
print(f"Chat tokens: prompt={usage.prompt_tokens}, completion={usage.completion_tokens}")
|
|
182
|
+
|
|
183
|
+
answer, thinking = split_content(chat_response.choices[0].message.content)
|
|
184
|
+
if SHOW_THINKING and thinking:
|
|
185
|
+
print("=== THINKING ===")
|
|
186
|
+
print(escape(thinking))
|
|
187
|
+
result = json.loads(answer)
|
|
188
|
+
print("=== EXTRACTED JSON ===")
|
|
189
|
+
print(json.dumps(result, indent=2, ensure_ascii=False))
|
|
190
|
+
return result
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def run_ocr_then_chat(client, ocr_model, chat_model, data_url, prompt):
|
|
194
|
+
"""
|
|
195
|
+
Two steps: Mistral OCR reads the page, then a chat model extracts the JSON from the OCR text
|
|
196
|
+
(and from the image too, if OCR_CHAT_WITH_IMAGE is True). The prompt is sent unchanged,
|
|
197
|
+
the OCR text is appended after it. Returns the extracted JSON.
|
|
198
|
+
"""
|
|
199
|
+
# Step 1: OCR
|
|
200
|
+
ocr_start = time.perf_counter()
|
|
201
|
+
ocr_response = client.ocr.process(
|
|
202
|
+
model=ocr_model,
|
|
203
|
+
document={
|
|
204
|
+
"type": "image_url",
|
|
205
|
+
"image_url": data_url
|
|
206
|
+
},
|
|
207
|
+
table_format="html",
|
|
208
|
+
extract_footer=True,
|
|
209
|
+
confidence_scores_granularity="page",
|
|
210
|
+
include_blocks=True
|
|
211
|
+
)
|
|
212
|
+
ocr_elapsed = time.perf_counter() - ocr_start
|
|
213
|
+
|
|
214
|
+
elements = []
|
|
215
|
+
for page in ocr_response.pages:
|
|
216
|
+
if page.confidence_scores:
|
|
217
|
+
print(f"OCR page {page.index} confidence: {page.confidence_scores.average_page_confidence_score}")
|
|
218
|
+
if not page.blocks:
|
|
219
|
+
print(f"OCR page {page.index}: no blocks returned (needs OCR 4 or newer with include_blocks=True)")
|
|
220
|
+
continue
|
|
221
|
+
elements.extend(blocks_to_elements(page))
|
|
222
|
+
|
|
223
|
+
if not elements:
|
|
224
|
+
raise RuntimeError(f"OCR model {ocr_model} returned no text blocks, cannot run the chat step")
|
|
225
|
+
|
|
226
|
+
usage_info = getattr(ocr_response, "usage_info", None)
|
|
227
|
+
print(f"OCR: {len(elements)} blocks, pages processed: {getattr(usage_info, 'pages_processed', 'n/a')}, "
|
|
228
|
+
f"time: {ocr_elapsed:.2f} s")
|
|
229
|
+
|
|
230
|
+
ocr_text = json.dumps(elements, ensure_ascii=False)
|
|
231
|
+
if SHOW_PROMPT:
|
|
232
|
+
print("=== OCR TEXT SENT TO THE CHAT MODEL ===")
|
|
233
|
+
print(escape(json.dumps(elements, indent=2, ensure_ascii=False)))
|
|
234
|
+
print("=== END OF OCR TEXT ===")
|
|
235
|
+
|
|
236
|
+
# Step 2: chat model, with the OCR text appended after the prompt
|
|
237
|
+
chat_prompt = prompt + "\n\nDocument text extracted by OCR (JSON list of blocks):\n" + ocr_text
|
|
238
|
+
chat_start = time.perf_counter()
|
|
239
|
+
result = run_chat(client, chat_model, data_url if OCR_CHAT_WITH_IMAGE else None, chat_prompt)
|
|
240
|
+
chat_elapsed = time.perf_counter() - chat_start
|
|
241
|
+
print(f"Chat time: {chat_elapsed:.2f} s (image sent: {OCR_CHAT_WITH_IMAGE})")
|
|
242
|
+
return result
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def main():
|
|
246
|
+
# Model to run: an OCR model (e.g. "mistral-ocr-4-1") or a chat model (e.g. "mistral-small-2603", "mistral-large-4")
|
|
247
|
+
model = "mistral-large-4"
|
|
248
|
+
# Optional OCR model. If set together with a chat model, OCR runs first and the chat model gets its text
|
|
249
|
+
# (see OCR_CHAT_WITH_IMAGE). Set to None to send the image straight to the chat model.
|
|
250
|
+
ocr_model = "mistral-ocr-4-1"
|
|
251
|
+
image_path = DEFAULT_IMAGE
|
|
252
|
+
|
|
253
|
+
api_key = os.environ["MISTRAL_API_KEY"]
|
|
254
|
+
client = Mistral(api_key=api_key, server_url=SERVER_URL)
|
|
255
|
+
print(f"Using endpoint: {SERVER_URL}")
|
|
256
|
+
print(f"Model: {model}, OCR model: {ocr_model}, image: {image_path}, "
|
|
257
|
+
f"reasoning effort: {REASONING_EFFORT or 'API default'}")
|
|
258
|
+
|
|
259
|
+
data_url = encode_image(image_path)
|
|
260
|
+
|
|
261
|
+
# Time the inference call only (not client setup or image encoding)
|
|
262
|
+
start = time.perf_counter()
|
|
263
|
+
if "ocr" in model:
|
|
264
|
+
run_ocr(client, model, data_url)
|
|
265
|
+
else:
|
|
266
|
+
if SHOW_PROMPT:
|
|
267
|
+
print_prompt(PROMPT)
|
|
268
|
+
if ocr_model:
|
|
269
|
+
run_ocr_then_chat(client, ocr_model, model, data_url, PROMPT)
|
|
270
|
+
else:
|
|
271
|
+
run_chat(client, model, data_url, PROMPT)
|
|
272
|
+
elapsed = time.perf_counter() - start
|
|
273
|
+
print(f"Inference time: {elapsed:.2f} s")
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
if __name__ == "__main__":
|
|
277
|
+
main()
|
|
@@ -21,7 +21,9 @@ class InferenceFactory:
|
|
|
21
21
|
return VLLMInference(model_name=self.config["model_name"])
|
|
22
22
|
elif self.config["method"] == "mistral":
|
|
23
23
|
from sparrow_parse.vlmb.mistral_inference import MistralInference
|
|
24
|
-
|
|
24
|
+
# "ocr_model_name" is set only when two models were passed (OCR first, then the chat model)
|
|
25
|
+
return MistralInference(model_name=self.config["model_name"],
|
|
26
|
+
ocr_model_name=self.config.get("ocr_model_name"))
|
|
25
27
|
else:
|
|
26
28
|
raise ValueError(f"Unknown method: {self.config['method']}")
|
|
27
29
|
|
|
@@ -29,4 +31,4 @@ class InferenceFactory:
|
|
|
29
31
|
# Example: Load a PyTorch model (replace with actual loading code)
|
|
30
32
|
# model = torch.load('model.pth')
|
|
31
33
|
# return model
|
|
32
|
-
raise NotImplementedError("Model loading logic not implemented")
|
|
34
|
+
raise NotImplementedError("Model loading logic not implemented")
|