Add NuExtract3: markdown OCR + structured JSON extraction

#11
by davanstrien HF Staff - opened
README.md CHANGED
@@ -7,7 +7,7 @@ tags: [uv-script, ocr, vision-language-model, document-processing, hf-jobs]
7
 
8
  > Part of [uv-scripts](https://huggingface.co/uv-scripts) - ready-to-run ML tools powered by UV and HuggingFace Jobs.
9
 
10
- 20 OCR scripts (text extraction) + 1 layout-detection script. Pick a model, point at your dataset, get markdown — no setup required. Layout-detection runs separately when you need bboxes for regions (text/title/table/figure/...) rather than the text itself.
11
 
12
  ## 🚀 Quick Start
13
 
@@ -49,6 +49,7 @@ That's it! The script will:
49
  | `deepseek-ocr-vllm.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | vLLM | 5 resolution + 5 prompt modes |
50
  | `deepseek-ocr.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | Transformers | Same model, Transformers backend |
51
  | `deepseek-ocr2-vllm.py` | [DeepSeek-OCR-2](https://huggingface.co/deepseek-ai/DeepSeek-OCR-2) | 3B | vLLM | Newer, requires nightly vLLM |
 
52
  | `qianfan-ocr.py` | [Qianfan-OCR](https://huggingface.co/baidu/Qianfan-OCR) | 4.7B | vLLM | #1 OmniDocBench v1.5 (93.12), Layout-as-Thought, 192 languages |
53
  | `olmocr2-vllm.py` | [olmOCR-2-7B](https://huggingface.co/allenai/olmOCR-2-7B-1025-FP8) | 7B | vLLM | 82.4% olmOCR-Bench |
54
  | `rolm-ocr.py` | [RolmOCR](https://huggingface.co/reducto/RolmOCR) | 7B | vLLM | Qwen2.5-VL based, general-purpose |
@@ -120,6 +121,54 @@ hf jobs uv run --flavor l4x1 -s HF_TOKEN \
120
  my-documents my-test --max-samples 10
121
  ```
122
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  <details><summary>Detailed per-model documentation</summary>
124
 
125
  ### PaddleOCR-VL-1.5 (`paddleocr-vl-1.5.py`) — 6 task modes
 
7
 
8
  > Part of [uv-scripts](https://huggingface.co/uv-scripts) - ready-to-run ML tools powered by UV and HuggingFace Jobs.
9
 
10
+ 21 OCR scripts (text extraction) + 1 layout-detection script. Pick a model, point at your dataset, get markdown — no setup required. Layout-detection runs separately when you need bboxes for regions (text/title/table/figure/...) rather than the text itself.
11
 
12
  ## 🚀 Quick Start
13
 
 
49
  | `deepseek-ocr-vllm.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | vLLM | 5 resolution + 5 prompt modes |
50
  | `deepseek-ocr.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | Transformers | Same model, Transformers backend |
51
  | `deepseek-ocr2-vllm.py` | [DeepSeek-OCR-2](https://huggingface.co/deepseek-ai/DeepSeek-OCR-2) | 3B | vLLM | Newer, requires nightly vLLM |
52
+ | `nuextract3.py` | [NuExtract3](https://huggingface.co/numind/NuExtract3) | 4B | vLLM | Markdown OCR **+ schema-guided JSON extraction** (template/Pydantic). Needs `vllm/vllm-openai` image |
53
  | `qianfan-ocr.py` | [Qianfan-OCR](https://huggingface.co/baidu/Qianfan-OCR) | 4.7B | vLLM | #1 OmniDocBench v1.5 (93.12), Layout-as-Thought, 192 languages |
54
  | `olmocr2-vllm.py` | [olmOCR-2-7B](https://huggingface.co/allenai/olmOCR-2-7B-1025-FP8) | 7B | vLLM | 82.4% olmOCR-Bench |
55
  | `rolm-ocr.py` | [RolmOCR](https://huggingface.co/reducto/RolmOCR) | 7B | vLLM | Qwen2.5-VL based, general-purpose |
 
121
  my-documents my-test --max-samples 10
122
  ```
123
 
124
+ ## Example: NuExtract3 (markdown OCR **+ structured extraction**)
125
+
126
+ [NuExtract3](https://huggingface.co/numind/NuExtract3) (4B, Apache-2.0) is the one script here that does both document-to-markdown OCR *and* schema-guided JSON extraction. Give it a template (or a JSON Schema / Pydantic model) and it returns JSON shaped to match.
127
+
128
+ > **Run it with the `vllm/vllm-openai` image.** NuExtract3's Qwen3.5 architecture needs the image's prebuilt CUDA kernels — the default uv-script image lacks `nvcc`, so flashinfer's JIT compile fails at engine warmup. Use `--image vllm/vllm-openai:latest --python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages` on `a100-large`.
129
+
130
+ ```bash
131
+ # Markdown OCR (default mode)
132
+ hf jobs uv run --flavor a100-large \
133
+ --image vllm/vllm-openai:latest \
134
+ --python /usr/bin/python3 \
135
+ -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \
136
+ -s HF_TOKEN \
137
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nuextract3.py \
138
+ my-documents my-markdown --max-samples 10
139
+
140
+ # Structured extraction with an inline template
141
+ hf jobs uv run --flavor a100-large \
142
+ --image vllm/vllm-openai:latest \
143
+ --python /usr/bin/python3 \
144
+ -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \
145
+ -s HF_TOKEN \
146
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nuextract3.py \
147
+ receipts extracted \
148
+ --template '{"store": "verbatim-string", "date": "date", "total": "number"}'
149
+ ```
150
+
151
+ **Templates** (`--template`) and **JSON Schemas** (`--schema`) each accept **inline JSON, a URL, or a file path**. So a schema can be hosted once and reused:
152
+
153
+ ```bash
154
+ # From a URL (e.g. an HF dataset's raw file)
155
+ ... nuextract3.py docs out --template https://huggingface.co/datasets/ORG/REPO/raw/main/card.json
156
+
157
+ # From a JSON Schema / Pydantic model — Model.model_json_schema() dumped to JSON,
158
+ # auto-converted via numind's convert_json_schema_to_nuextract_template
159
+ ... nuextract3.py docs out --schema invoice-schema.json
160
+
161
+ # From a mounted bucket (host configs in a bucket, mount read-only)
162
+ hf jobs uv run --flavor a100-large \
163
+ --image vllm/vllm-openai:latest --python /usr/bin/python3 \
164
+ -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages -s HF_TOKEN \
165
+ -v hf://buckets/USER/configs:/configs:ro \
166
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nuextract3.py \
167
+ docs out --template /configs/card.json
168
+ ```
169
+
170
+ Add `--enable-thinking` for harder layouts (slower; reasoning trace stored in a `<output-column>_reasoning` column). Template field names act as the model's extraction instructions, so name them descriptively — but note that overly leading names can prompt over-generation, so verify against a few examples.
171
+
172
  <details><summary>Detailed per-model documentation</summary>
173
 
174
  ### PaddleOCR-VL-1.5 (`paddleocr-vl-1.5.py`) — 6 task modes
examples/nls-index-card-v2.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "image_type": ["index_card", "verso", "cover", "blank", "other"],
3
+ "heading": "verbatim-string",
4
+ "heading_type": ["person", "family", "corporate", "geographic", "subject"],
5
+ "epithet": "string",
6
+ "entries": [
7
+ {
8
+ "ms_no": "verbatim-string",
9
+ "folios": ["verbatim-string"],
10
+ "description": "string"
11
+ }
12
+ ]
13
+ }
examples/nls-index-card-verbose.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "image_type": ["index_card", "verso", "cover", "blank", "other"],
3
+ "main_heading_name": "verbatim-string",
4
+ "heading_category": ["person", "family", "corporate", "geographic", "subject"],
5
+ "epithet_title_or_occupation": "string",
6
+ "manuscript_references": [
7
+ {
8
+ "manuscript_number": "verbatim-string",
9
+ "folio_references": ["verbatim-string"],
10
+ "entry_description_with_date": "string"
11
+ }
12
+ ]
13
+ }
nuextract3.py ADDED
@@ -0,0 +1,727 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "datasets>=3.1.0",
5
+ # "huggingface-hub",
6
+ # "pillow",
7
+ # "vllm",
8
+ # "toolz",
9
+ # "torch",
10
+ # "numind",
11
+ # ]
12
+ # ///
13
+
14
+ """
15
+ Convert document images to markdown OR extract structured JSON using NuExtract3 with vLLM.
16
+
17
+ NuExtract3 is a 4B Qwen3.5-based VLM for document understanding. It does two things:
18
+
19
+ 1. Document-to-Markdown OCR (default): images -> clean markdown with HTML tables,
20
+ LaTeX math, and <figure> tags.
21
+ 2. Schema-guided structured extraction: images + a JSON template -> JSON output
22
+ shaped exactly like the template. Useful for invoices, receipts, forms, contracts.
23
+
24
+ Modes are selected via flags:
25
+ - (no flags) -> markdown OCR
26
+ - --mode content -> plain-content extraction
27
+ - --template SOURCE -> structured extraction with a NuExtract template
28
+ - --schema SOURCE -> structured extraction with a JSON Schema
29
+ (auto-converted via numind.nuextract_utils)
30
+
31
+ --template / --schema each accept inline JSON, a URL, or a local file path, so a
32
+ schema can be hosted (e.g. on an HF dataset's raw URL) and reused across jobs:
33
+ --template https://huggingface.co/datasets/ORG/REPO/raw/main/card.json
34
+
35
+ HF Jobs invocation (recommended): use the vllm/vllm-openai:latest image so the
36
+ pre-built CUDA kernels (flashinfer etc.) are reused — the default uv-script
37
+ image lacks nvcc and flashinfer's JIT compile fails at engine warmup.
38
+
39
+ hf jobs uv run \\
40
+ --image vllm/vllm-openai:latest \\
41
+ --flavor a100-large \\
42
+ --python /usr/bin/python3 \\
43
+ -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\
44
+ -s HF_TOKEN \\
45
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nuextract3.py \\
46
+ INPUT_DATASET OUTPUT_DATASET --max-samples 5 --shuffle --seed 42
47
+
48
+ Model: numind/NuExtract3
49
+ License: Apache-2.0
50
+ """
51
+
52
+ import argparse
53
+ import base64
54
+ import io
55
+ import json
56
+ import logging
57
+ import os
58
+ import sys
59
+ import time
60
+ from datetime import datetime
61
+ from pathlib import Path
62
+ from typing import Any, Dict, List, Optional, Union
63
+
64
+ import torch
65
+ from datasets import load_dataset
66
+ from huggingface_hub import DatasetCard, login
67
+ from PIL import Image
68
+ from toolz import partition_all
69
+ from vllm import LLM, SamplingParams
70
+
71
+ logging.basicConfig(level=logging.INFO)
72
+ logger = logging.getLogger(__name__)
73
+
74
+ MODEL_DEFAULT = "numind/NuExtract3"
75
+ MODEL_NAME = "NuExtract3"
76
+
77
+
78
+ def check_cuda_availability():
79
+ """Check if CUDA is available and exit if not."""
80
+ if not torch.cuda.is_available():
81
+ logger.error("CUDA is not available. This script requires a GPU.")
82
+ logger.error("Please run on a machine with a CUDA-capable GPU.")
83
+ sys.exit(1)
84
+ else:
85
+ logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
86
+
87
+
88
+ def load_template_arg(value: Optional[str]) -> Optional[Dict[str, Any]]:
89
+ """Load a NuExtract template/JSON Schema from inline JSON, a URL, or a file path."""
90
+ if value is None:
91
+ return None
92
+ text = value
93
+ if value.startswith(("http://", "https://")):
94
+ import urllib.request
95
+
96
+ with urllib.request.urlopen(value) as resp: # noqa: S310
97
+ text = resp.read().decode("utf-8")
98
+ elif "{" not in value:
99
+ # Inline JSON often exceeds the OS filename limit, so only probe the
100
+ # filesystem when the value doesn't look like JSON; treat OSError as
101
+ # "not a path".
102
+ try:
103
+ candidate_path = Path(value)
104
+ if candidate_path.is_file():
105
+ text = candidate_path.read_text()
106
+ except OSError:
107
+ pass
108
+ try:
109
+ return json.loads(text)
110
+ except json.JSONDecodeError as e:
111
+ raise ValueError(
112
+ f"Could not parse template/schema as JSON (tried URL/path/inline): {e}"
113
+ ) from e
114
+
115
+
116
+ def resolve_template(
117
+ template_arg: Optional[str],
118
+ schema_arg: Optional[str],
119
+ ) -> Optional[Dict[str, Any]]:
120
+ """Resolve --template / --schema into a NuExtract template dict, or None."""
121
+ if template_arg and schema_arg:
122
+ raise ValueError("--template and --schema are mutually exclusive.")
123
+
124
+ if template_arg is not None:
125
+ return load_template_arg(template_arg)
126
+
127
+ if schema_arg is not None:
128
+ schema = load_template_arg(schema_arg)
129
+ try:
130
+ from numind.nuextract_utils import convert_json_schema_to_nuextract_template
131
+ except ImportError as e:
132
+ raise RuntimeError(
133
+ "--schema requires the `numind` package. "
134
+ "It should be listed in this script's PEP 723 dependencies."
135
+ ) from e
136
+ template, dropped = convert_json_schema_to_nuextract_template(schema)
137
+ if dropped:
138
+ logger.warning(
139
+ f"numind dropped {len(dropped)} unsupported branches from the JSON Schema: "
140
+ f"{dropped}"
141
+ )
142
+ return template
143
+
144
+ return None
145
+
146
+
147
+ def image_to_data_uri(image: Union[Image.Image, Dict[str, Any], str]) -> str:
148
+ """Normalize an HF dataset image cell to a PNG data URI."""
149
+ if isinstance(image, Image.Image):
150
+ pil_img = image
151
+ elif isinstance(image, dict) and "bytes" in image:
152
+ pil_img = Image.open(io.BytesIO(image["bytes"]))
153
+ elif isinstance(image, str):
154
+ pil_img = Image.open(image)
155
+ else:
156
+ raise ValueError(f"Unsupported image type: {type(image)}")
157
+
158
+ pil_img = pil_img.convert("RGB")
159
+ buf = io.BytesIO()
160
+ pil_img.save(buf, format="PNG")
161
+ return f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
162
+
163
+
164
+ def make_message(image: Union[Image.Image, Dict[str, Any], str]) -> List[Dict]:
165
+ """Build an OpenAI-format chat message containing one image."""
166
+ data_uri = image_to_data_uri(image)
167
+ return [
168
+ {
169
+ "role": "user",
170
+ "content": [
171
+ {"type": "image_url", "image_url": {"url": data_uri}},
172
+ ],
173
+ }
174
+ ]
175
+
176
+
177
+ def split_thinking(text: str) -> tuple[Optional[str], str]:
178
+ """Return (reasoning, answer) if <think>...</think> is present, else (None, text)."""
179
+ if "<think>" in text and "</think>" in text:
180
+ reasoning = text.split("<think>", 1)[1].split("</think>", 1)[0].strip()
181
+ answer = text.split("</think>", 1)[1].strip()
182
+ return reasoning, answer
183
+ return None, text.strip()
184
+
185
+
186
+ def parse_json_output(text: str) -> tuple[Optional[Any], bool]:
187
+ """Parse an extraction output; strip ``` fences as the model card describes.
188
+
189
+ Returns (parsed_value, parse_error). On failure, parsed_value is None.
190
+ """
191
+ stripped = text.strip()
192
+ if stripped.startswith("```"):
193
+ stripped = stripped.split("\n", 1)[-1] if "\n" in stripped else stripped[3:]
194
+ if stripped.endswith("```"):
195
+ stripped = stripped[:-3].rstrip()
196
+ try:
197
+ return json.loads(stripped), False
198
+ except json.JSONDecodeError:
199
+ return None, True
200
+
201
+
202
+ def create_dataset_card(
203
+ source_dataset: str,
204
+ model: str,
205
+ num_samples: int,
206
+ processing_time: str,
207
+ mode_label: str,
208
+ template: Optional[Dict[str, Any]],
209
+ enable_thinking: bool,
210
+ temperature: float,
211
+ output_column: str,
212
+ image_column: str,
213
+ split: str,
214
+ ) -> str:
215
+ """Create a dataset card documenting the NuExtract3 run."""
216
+ model_name = model.split("/")[-1]
217
+ template_block = ""
218
+ if template is not None:
219
+ template_block = (
220
+ "\n### Extraction Template\n\n```json\n"
221
+ + json.dumps(template, indent=2)
222
+ + "\n```\n"
223
+ )
224
+
225
+ return f"""---
226
+ tags:
227
+ - ocr
228
+ - structured-extraction
229
+ - document-processing
230
+ - nuextract3
231
+ - markdown
232
+ - uv-script
233
+ - generated
234
+ ---
235
+
236
+ # {model_name} on {source_dataset}
237
+
238
+ This dataset contains outputs from [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) processed with [NuExtract3](https://huggingface.co/{model}), a 4B vision-language model for document understanding.
239
+
240
+ ## Processing Details
241
+
242
+ - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
243
+ - **Model**: [{model}](https://huggingface.co/{model})
244
+ - **Mode**: {mode_label}
245
+ - **Number of Samples**: {num_samples:,}
246
+ - **Processing Time**: {processing_time}
247
+ - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
248
+
249
+ ### Configuration
250
+
251
+ - **Image Column**: `{image_column}`
252
+ - **Output Column**: `{output_column}`
253
+ - **Dataset Split**: `{split}`
254
+ - **Temperature**: {temperature}
255
+ - **Thinking Mode**: {"enabled" if enable_thinking else "disabled"}
256
+ {template_block}
257
+ ## Dataset Structure
258
+
259
+ Original columns plus:
260
+ - `{output_column}`: NuExtract3 output ({"JSON string" if template else "markdown"})
261
+ - `inference_info`: JSON list tracking models applied to this dataset
262
+ {"- `" + output_column + "_reasoning`: model's thinking trace (when enabled)" if enable_thinking else ""}
263
+
264
+ Generated with [UV Scripts](https://huggingface.co/uv-scripts)
265
+ """
266
+
267
+
268
+ def main(
269
+ input_dataset: str,
270
+ output_dataset: str,
271
+ image_column: str = "image",
272
+ batch_size: int = 16,
273
+ max_model_len: int = 16384,
274
+ max_tokens: int = 8192,
275
+ gpu_memory_utilization: float = 0.8,
276
+ mode: str = "markdown",
277
+ template_arg: Optional[str] = None,
278
+ schema_arg: Optional[str] = None,
279
+ enable_thinking: bool = False,
280
+ temperature: Optional[float] = None,
281
+ model: str = MODEL_DEFAULT,
282
+ hf_token: str = None,
283
+ split: str = "train",
284
+ max_samples: int = None,
285
+ private: bool = False,
286
+ shuffle: bool = False,
287
+ seed: int = 42,
288
+ output_column: Optional[str] = None,
289
+ verbose: bool = False,
290
+ config: str = None,
291
+ create_pr: bool = False,
292
+ ):
293
+ """Process images from an HF dataset through NuExtract3."""
294
+
295
+ check_cuda_availability()
296
+ start_time = datetime.now()
297
+
298
+ HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
299
+ if HF_TOKEN:
300
+ login(token=HF_TOKEN)
301
+
302
+ template = resolve_template(template_arg, schema_arg)
303
+ extraction_mode = template is not None
304
+ mode_label = "structured-extraction" if extraction_mode else mode
305
+
306
+ if output_column is None:
307
+ output_column = "extraction" if extraction_mode else "markdown"
308
+
309
+ if temperature is None:
310
+ temperature = 0.6 if enable_thinking else 0.2
311
+
312
+ logger.info(f"Using model: {model}")
313
+ logger.info(f"Mode: {mode_label}")
314
+ logger.info(f"Thinking: {enable_thinking} Temperature: {temperature}")
315
+ if extraction_mode:
316
+ logger.info(f"Template: {json.dumps(template, indent=2)}")
317
+
318
+ logger.info(f"Loading dataset: {input_dataset}")
319
+ dataset = load_dataset(input_dataset, split=split)
320
+
321
+ if image_column not in dataset.column_names:
322
+ raise ValueError(
323
+ f"Column '{image_column}' not found. Available: {dataset.column_names}"
324
+ )
325
+
326
+ if shuffle:
327
+ logger.info(f"Shuffling dataset with seed {seed}")
328
+ dataset = dataset.shuffle(seed=seed)
329
+
330
+ if max_samples:
331
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
332
+ logger.info(f"Limited to {len(dataset)} samples")
333
+
334
+ logger.info("Initializing vLLM with NuExtract3")
335
+ logger.info("This may take a few minutes on first run...")
336
+ llm = LLM(
337
+ model=model,
338
+ trust_remote_code=True,
339
+ max_model_len=max_model_len,
340
+ gpu_memory_utilization=gpu_memory_utilization,
341
+ limit_mm_per_prompt={"image": 1},
342
+ )
343
+
344
+ sampling_params = SamplingParams(
345
+ temperature=temperature,
346
+ max_tokens=max_tokens,
347
+ )
348
+
349
+ chat_template_kwargs: Dict[str, Any] = {"enable_thinking": enable_thinking}
350
+ if extraction_mode:
351
+ chat_template_kwargs["template"] = json.dumps(template, indent=4)
352
+ else:
353
+ chat_template_kwargs["mode"] = mode
354
+
355
+ logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
356
+ logger.info(f"Output will be written to column: {output_column}")
357
+
358
+ all_outputs: List[str] = []
359
+ all_reasoning: List[Optional[str]] = []
360
+ all_parse_errors: List[bool] = []
361
+ total_batches = (len(dataset) + batch_size - 1) // batch_size
362
+ processed = 0
363
+
364
+ for batch_num, batch_indices in enumerate(
365
+ partition_all(batch_size, range(len(dataset))), 1
366
+ ):
367
+ batch_indices = list(batch_indices)
368
+ batch_images = [dataset[i][image_column] for i in batch_indices]
369
+
370
+ logger.info(
371
+ f"Batch {batch_num}/{total_batches} "
372
+ f"({processed}/{len(dataset)} images done)"
373
+ )
374
+
375
+ try:
376
+ batch_messages = [make_message(img) for img in batch_images]
377
+ outputs = llm.chat(
378
+ batch_messages,
379
+ sampling_params,
380
+ chat_template_kwargs=chat_template_kwargs,
381
+ chat_template_content_format="openai",
382
+ )
383
+
384
+ for output in outputs:
385
+ raw_text = output.outputs[0].text
386
+ reasoning, answer = split_thinking(raw_text)
387
+
388
+ if extraction_mode:
389
+ parsed, parse_error = parse_json_output(answer)
390
+ stored = (
391
+ json.dumps(parsed, ensure_ascii=False)
392
+ if parsed is not None
393
+ else answer
394
+ )
395
+ all_outputs.append(stored)
396
+ all_parse_errors.append(parse_error)
397
+ else:
398
+ all_outputs.append(answer)
399
+ all_parse_errors.append(False)
400
+
401
+ all_reasoning.append(reasoning)
402
+
403
+ processed += len(batch_images)
404
+
405
+ except Exception as e:
406
+ logger.error(f"Error processing batch: {e}")
407
+ all_outputs.extend(["[NUEXTRACT3 ERROR]"] * len(batch_images))
408
+ all_reasoning.extend([None] * len(batch_images))
409
+ all_parse_errors.extend([True] * len(batch_images))
410
+ processed += len(batch_images)
411
+
412
+ processing_duration = datetime.now() - start_time
413
+ processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
414
+
415
+ logger.info(f"Adding '{output_column}' column to dataset")
416
+ dataset = dataset.add_column(output_column, all_outputs)
417
+
418
+ if enable_thinking and any(r is not None for r in all_reasoning):
419
+ reasoning_col = f"{output_column}_reasoning"
420
+ logger.info(f"Adding '{reasoning_col}' column to dataset")
421
+ dataset = dataset.add_column(reasoning_col, all_reasoning)
422
+
423
+ if extraction_mode:
424
+ parse_error_count = sum(all_parse_errors)
425
+ if parse_error_count:
426
+ logger.warning(
427
+ f"{parse_error_count}/{len(all_parse_errors)} extractions failed to parse as JSON"
428
+ )
429
+
430
+ inference_entry = {
431
+ "model_id": model,
432
+ "model_name": MODEL_NAME,
433
+ "column_name": output_column,
434
+ "timestamp": datetime.now().isoformat(),
435
+ "mode": mode_label,
436
+ "has_template": extraction_mode,
437
+ "enable_thinking": enable_thinking,
438
+ "temperature": temperature,
439
+ "max_tokens": max_tokens,
440
+ }
441
+ if extraction_mode:
442
+ inference_entry["parse_error_rate"] = (
443
+ sum(all_parse_errors) / len(all_parse_errors) if all_parse_errors else 0.0
444
+ )
445
+
446
+ if "inference_info" in dataset.column_names:
447
+ logger.info("Updating existing inference_info column")
448
+
449
+ def update_inference_info(example):
450
+ try:
451
+ existing_info = (
452
+ json.loads(example["inference_info"])
453
+ if example["inference_info"]
454
+ else []
455
+ )
456
+ except (json.JSONDecodeError, TypeError):
457
+ existing_info = []
458
+ existing_info.append(inference_entry)
459
+ return {"inference_info": json.dumps(existing_info)}
460
+
461
+ dataset = dataset.map(update_inference_info)
462
+ else:
463
+ logger.info("Creating new inference_info column")
464
+ inference_list = [json.dumps([inference_entry])] * len(dataset)
465
+ dataset = dataset.add_column("inference_info", inference_list)
466
+
467
+ logger.info(f"Pushing to {output_dataset}")
468
+ max_retries = 3
469
+ for attempt in range(1, max_retries + 1):
470
+ try:
471
+ if attempt > 1:
472
+ logger.warning("Disabling XET (fallback to HTTP upload)")
473
+ os.environ["HF_HUB_DISABLE_XET"] = "1"
474
+ dataset.push_to_hub(
475
+ output_dataset,
476
+ private=private,
477
+ token=HF_TOKEN,
478
+ max_shard_size="500MB",
479
+ **({"config_name": config} if config else {}),
480
+ create_pr=create_pr,
481
+ commit_message=f"Add {model} {mode_label} results ({len(dataset)} samples)"
482
+ + (f" [{config}]" if config else ""),
483
+ )
484
+ break
485
+ except Exception as e:
486
+ logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
487
+ if attempt < max_retries:
488
+ delay = 30 * (2 ** (attempt - 1))
489
+ logger.info(f"Retrying in {delay}s...")
490
+ time.sleep(delay)
491
+ else:
492
+ logger.error("All upload attempts failed. Results are lost.")
493
+ sys.exit(1)
494
+
495
+ logger.info("Creating dataset card")
496
+ card_content = create_dataset_card(
497
+ source_dataset=input_dataset,
498
+ model=model,
499
+ num_samples=len(dataset),
500
+ processing_time=processing_time_str,
501
+ mode_label=mode_label,
502
+ template=template,
503
+ enable_thinking=enable_thinking,
504
+ temperature=temperature,
505
+ output_column=output_column,
506
+ image_column=image_column,
507
+ split=split,
508
+ )
509
+ card = DatasetCard(card_content)
510
+ card.push_to_hub(output_dataset, token=HF_TOKEN)
511
+
512
+ logger.info("Done! NuExtract3 processing complete.")
513
+ logger.info(
514
+ f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
515
+ )
516
+ logger.info(f"Processing time: {processing_time_str}")
517
+ logger.info(
518
+ f"Processing speed: {len(dataset) / processing_duration.total_seconds():.2f} images/sec"
519
+ )
520
+
521
+ if verbose:
522
+ import importlib.metadata
523
+
524
+ logger.info("--- Resolved package versions ---")
525
+ for pkg in [
526
+ "vllm",
527
+ "transformers",
528
+ "torch",
529
+ "datasets",
530
+ "pyarrow",
531
+ "pillow",
532
+ "numind",
533
+ ]:
534
+ try:
535
+ logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
536
+ except importlib.metadata.PackageNotFoundError:
537
+ logger.info(f" {pkg}: not installed")
538
+ logger.info("--- End versions ---")
539
+
540
+
541
+ if __name__ == "__main__":
542
+ if len(sys.argv) == 1:
543
+ print("=" * 70)
544
+ print("NuExtract3 - Document-to-Markdown + Structured Extraction (4B)")
545
+ print("=" * 70)
546
+ print("\nModes:")
547
+ print(" markdown - Image -> markdown (default)")
548
+ print(" content - Image -> plain content")
549
+ print(" --template / --schema - Image -> JSON shaped like the template")
550
+ print("\nExamples:")
551
+ print("\n1. Markdown OCR:")
552
+ print(" uv run nuextract3.py input-dataset output-dataset")
553
+ print("\n2. Structured extraction with an inline template:")
554
+ print(" uv run nuextract3.py input output \\")
555
+ print(' --template \'{"title": "verbatim-string", "date": "date"}\'')
556
+ print("\n3. Structured extraction from a JSON Schema (e.g. Pydantic):")
557
+ print(" uv run nuextract3.py input output --schema schema.json")
558
+ print("\n (--template / --schema also accept a URL or a local file path)")
559
+ print("\n4. Reasoning mode for harder documents:")
560
+ print(" uv run nuextract3.py input output --enable-thinking")
561
+ print("\n5. Test with 10 samples:")
562
+ print(" uv run nuextract3.py large-ds test --max-samples 10 --shuffle")
563
+ print("\n6. Running on HF Jobs (use vllm/vllm-openai image for built kernels):")
564
+ print(" hf jobs uv run --flavor a100-large \\")
565
+ print(" --image vllm/vllm-openai:latest \\")
566
+ print(" --python /usr/bin/python3 \\")
567
+ print(" -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\")
568
+ print(" -s HF_TOKEN \\")
569
+ print(
570
+ " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nuextract3.py \\"
571
+ )
572
+ print(" input-dataset output-dataset --batch-size 16")
573
+ print("\nFor full help: uv run nuextract3.py --help")
574
+ sys.exit(0)
575
+
576
+ parser = argparse.ArgumentParser(
577
+ description="NuExtract3: document-to-markdown + schema-guided JSON extraction (4B VLM)",
578
+ formatter_class=argparse.RawDescriptionHelpFormatter,
579
+ epilog="""
580
+ Modes:
581
+ (default) Markdown OCR (image -> clean markdown)
582
+ --mode content
583
+ Plain-content extraction (less structured than markdown)
584
+ --template PATH_OR_JSON
585
+ Structured extraction with a NuExtract template
586
+ --schema PATH_OR_JSON
587
+ Structured extraction from a JSON Schema
588
+ (e.g. Pydantic Model.model_json_schema())
589
+
590
+ Examples:
591
+ uv run nuextract3.py my-docs analyzed-docs
592
+ uv run nuextract3.py receipts extracted \\
593
+ --template '{"store": "verbatim-string", "total": "number"}'
594
+ uv run nuextract3.py contracts extracted --schema contract_schema.json
595
+ uv run nuextract3.py hard-docs out --enable-thinking
596
+ """,
597
+ )
598
+
599
+ parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
600
+ parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
601
+ parser.add_argument(
602
+ "--image-column",
603
+ default="image",
604
+ help="Column containing images (default: image)",
605
+ )
606
+ parser.add_argument(
607
+ "--batch-size",
608
+ type=int,
609
+ default=16,
610
+ help="Batch size for processing (default: 16)",
611
+ )
612
+ parser.add_argument(
613
+ "--max-model-len",
614
+ type=int,
615
+ default=16384,
616
+ help="Maximum model context length (default: 16384)",
617
+ )
618
+ parser.add_argument(
619
+ "--max-tokens",
620
+ type=int,
621
+ default=8192,
622
+ help="Maximum tokens to generate (default: 8192)",
623
+ )
624
+ parser.add_argument(
625
+ "--gpu-memory-utilization",
626
+ type=float,
627
+ default=0.8,
628
+ help="GPU memory utilization (default: 0.8)",
629
+ )
630
+ parser.add_argument(
631
+ "--mode",
632
+ choices=["markdown", "content"],
633
+ default="markdown",
634
+ help="OCR mode when no template/schema is given (default: markdown)",
635
+ )
636
+ parser.add_argument(
637
+ "--template",
638
+ help="NuExtract template: inline JSON, a URL, or a file path",
639
+ )
640
+ parser.add_argument(
641
+ "--schema",
642
+ help="JSON Schema to auto-convert: inline JSON, a URL, or a file path",
643
+ )
644
+ parser.add_argument(
645
+ "--enable-thinking",
646
+ action="store_true",
647
+ help="Enable reasoning mode (slower, better on hard documents)",
648
+ )
649
+ parser.add_argument(
650
+ "--temperature",
651
+ type=float,
652
+ default=None,
653
+ help="Sampling temperature (default: 0.2 non-thinking, 0.6 thinking)",
654
+ )
655
+ parser.add_argument(
656
+ "--model",
657
+ default=MODEL_DEFAULT,
658
+ help=f"Model ID (default: {MODEL_DEFAULT})",
659
+ )
660
+ parser.add_argument("--hf-token", help="Hugging Face API token")
661
+ parser.add_argument(
662
+ "--split", default="train", help="Dataset split to use (default: train)"
663
+ )
664
+ parser.add_argument(
665
+ "--max-samples",
666
+ type=int,
667
+ help="Maximum number of samples to process (for testing)",
668
+ )
669
+ parser.add_argument(
670
+ "--private", action="store_true", help="Make output dataset private"
671
+ )
672
+ parser.add_argument(
673
+ "--config",
674
+ help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
675
+ )
676
+ parser.add_argument(
677
+ "--create-pr",
678
+ action="store_true",
679
+ help="Create a pull request instead of pushing directly (for parallel benchmarking)",
680
+ )
681
+ parser.add_argument(
682
+ "--shuffle", action="store_true", help="Shuffle dataset before processing"
683
+ )
684
+ parser.add_argument(
685
+ "--seed",
686
+ type=int,
687
+ default=42,
688
+ help="Random seed for shuffling (default: 42)",
689
+ )
690
+ parser.add_argument(
691
+ "--output-column",
692
+ default=None,
693
+ help="Column name for output (default: 'markdown' in OCR mode, 'extraction' in template mode)",
694
+ )
695
+ parser.add_argument(
696
+ "--verbose",
697
+ action="store_true",
698
+ help="Log resolved package versions after processing",
699
+ )
700
+
701
+ args = parser.parse_args()
702
+
703
+ main(
704
+ input_dataset=args.input_dataset,
705
+ output_dataset=args.output_dataset,
706
+ image_column=args.image_column,
707
+ batch_size=args.batch_size,
708
+ max_model_len=args.max_model_len,
709
+ max_tokens=args.max_tokens,
710
+ gpu_memory_utilization=args.gpu_memory_utilization,
711
+ mode=args.mode,
712
+ template_arg=args.template,
713
+ schema_arg=args.schema,
714
+ enable_thinking=args.enable_thinking,
715
+ temperature=args.temperature,
716
+ model=args.model,
717
+ hf_token=args.hf_token,
718
+ split=args.split,
719
+ max_samples=args.max_samples,
720
+ private=args.private,
721
+ shuffle=args.shuffle,
722
+ seed=args.seed,
723
+ output_column=args.output_column,
724
+ verbose=args.verbose,
725
+ config=args.config,
726
+ create_pr=args.create_pr,
727
+ )