Add PaddleOCR-VL-1.6 script (vLLM, image-mode)

#12
by davanstrien HF Staff - opened
Files changed (1) hide show
  1. paddleocr-vl-1.6.py +794 -0
paddleocr-vl-1.6.py ADDED
@@ -0,0 +1,794 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "datasets>=4.0.0",
5
+ # "huggingface-hub",
6
+ # "pillow",
7
+ # "vllm>=0.15.1",
8
+ # "tqdm",
9
+ # "toolz",
10
+ # "torch",
11
+ # "pyarrow",
12
+ # "transformers",
13
+ # ]
14
+ # ///
15
+
16
+ """
17
+ Convert document images to text/tables/formulas using PaddleOCR-VL-1.6 with vLLM.
18
+
19
+ PaddleOCR-VL-1.6 is a compact 0.9B OCR model that reaches a new SOTA of 96.33% on
20
+ OmniDocBench v1.6. It combines a NaViT-style dynamic resolution visual encoder with
21
+ the ERNIE-4.5-0.3B language model and is a plug-and-play upgrade of PaddleOCR-VL-1.5.
22
+
23
+ Features:
24
+ - 🎯 SOTA: 96.33% on OmniDocBench v1.6 (0.9B params, smallest top-tier OCR model)
25
+ - 📝 OCR mode: General text extraction to markdown
26
+ - 📊 Table mode: HTML table recognition and extraction
27
+ - 📐 Formula mode: LaTeX mathematical notation
28
+ - 📈 Chart mode: Structured chart analysis
29
+ - 🔍 Spotting mode: Text spotting with localization
30
+ - 🔖 Seal mode: Seal/stamp recognition
31
+ - 🌍 Multilingual support (en/zh + more)
32
+ - 🔧 Based on ERNIE-4.5 (different from Qwen-based models)
33
+
34
+ Model: PaddlePaddle/PaddleOCR-VL-1.6
35
+ Backend: vLLM offline (batch inference)
36
+
37
+ HF Jobs note: PaddleOCR-VL-1.6 is supported by stable vLLM, but on HF Jobs you must run
38
+ with the pre-built vLLM image so flashinfer's CUDA kernels are reused. The default
39
+ uv-script image has the CUDA runtime but no `nvcc`, so vLLM's flashinfer sampler crashes
40
+ at warmup with "Could not find nvcc". Use image-mode (see the example at the bottom):
41
+ --image vllm/vllm-openai:latest --flavor a100-large
42
+ --python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages
43
+ This is the same image-mode pattern as nuextract3.py. Verified end-to-end on a100-large
44
+ (2026-06-01): 5/5 clean markdown on davanstrien/ufo-ColPali, ~194 tok/s, 0 errors.
45
+ """
46
+
47
+ import argparse
48
+ import base64
49
+ import io
50
+ import json
51
+ import logging
52
+ import math
53
+ import os
54
+ import sys
55
+ import time
56
+ from typing import Any, Dict, List, Union
57
+ from datetime import datetime
58
+
59
+ import torch
60
+ from datasets import load_dataset
61
+ from huggingface_hub import DatasetCard, login
62
+ from PIL import Image
63
+ from toolz import partition_all
64
+ from tqdm.auto import tqdm
65
+ from vllm import LLM, SamplingParams
66
+
67
+ logging.basicConfig(level=logging.INFO)
68
+ logger = logging.getLogger(__name__)
69
+
70
+ MODEL_ID = "PaddlePaddle/PaddleOCR-VL-1.6"
71
+
72
+ # Task mode configurations from official PaddleOCR-VL documentation
73
+ TASK_MODES = {
74
+ "ocr": "OCR:",
75
+ "table": "Table Recognition:",
76
+ "formula": "Formula Recognition:",
77
+ "chart": "Chart Recognition:",
78
+ "spotting": "Spotting:",
79
+ "seal": "Seal Recognition:",
80
+ }
81
+
82
+ # Task descriptions for dataset card
83
+ TASK_DESCRIPTIONS = {
84
+ "ocr": "General text extraction to markdown format",
85
+ "table": "Table extraction to HTML format",
86
+ "formula": "Mathematical formula recognition to LaTeX",
87
+ "chart": "Chart and diagram analysis",
88
+ "spotting": "Text spotting with localization",
89
+ "seal": "Seal and stamp recognition",
90
+ }
91
+
92
+
93
+ def check_cuda_availability():
94
+ """Check if CUDA is available and exit if not."""
95
+ if not torch.cuda.is_available():
96
+ logger.error("CUDA is not available. This script requires a GPU.")
97
+ logger.error("Please run on a machine with a CUDA-capable GPU.")
98
+ sys.exit(1)
99
+ else:
100
+ logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
101
+
102
+
103
+ def smart_resize(
104
+ height: int,
105
+ width: int,
106
+ factor: int = 28,
107
+ min_pixels: int = 28 * 28 * 130,
108
+ max_pixels: int = 28 * 28 * 1280,
109
+ ) -> tuple[int, int]:
110
+ """
111
+ PaddleOCR-VL's intelligent resize logic.
112
+
113
+ Rescales the image so that:
114
+ 1. Both dimensions are divisible by 'factor' (28)
115
+ 2. Total pixels are within [min_pixels, max_pixels]
116
+ 3. Aspect ratio is maintained as closely as possible
117
+
118
+ Args:
119
+ height: Original image height
120
+ width: Original image width
121
+ factor: Dimension divisibility factor (default: 28)
122
+ min_pixels: Minimum total pixels (default: 100,880)
123
+ max_pixels: Maximum total pixels (default: 1,003,520)
124
+
125
+ Returns:
126
+ Tuple of (new_height, new_width)
127
+ """
128
+ if height < factor:
129
+ width = round((width * factor) / height)
130
+ height = factor
131
+
132
+ if width < factor:
133
+ height = round((height * factor) / width)
134
+ width = factor
135
+
136
+ if max(height, width) / min(height, width) > 200:
137
+ logger.warning(
138
+ f"Extreme aspect ratio detected: {max(height, width) / min(height, width):.1f}"
139
+ )
140
+ # Continue anyway, but warn about potential issues
141
+
142
+ h_bar = round(height / factor) * factor
143
+ w_bar = round(width / factor) * factor
144
+
145
+ if h_bar * w_bar > max_pixels:
146
+ beta = math.sqrt((height * width) / max_pixels)
147
+ h_bar = math.floor(height / beta / factor) * factor
148
+ w_bar = math.floor(width / beta / factor) * factor
149
+ elif h_bar * w_bar < min_pixels:
150
+ beta = math.sqrt(min_pixels / (height * width))
151
+ h_bar = math.ceil(height * beta / factor) * factor
152
+ w_bar = math.ceil(width * beta / factor) * factor
153
+
154
+ return h_bar, w_bar
155
+
156
+
157
+ def make_ocr_message(
158
+ image: Union[Image.Image, Dict[str, Any], str],
159
+ task_mode: str = "ocr",
160
+ apply_smart_resize: bool = True,
161
+ ) -> List[Dict]:
162
+ """
163
+ Create chat message for PaddleOCR-VL processing.
164
+
165
+ PaddleOCR-VL expects a specific format with the task prefix after the image.
166
+ """
167
+ # Convert to PIL Image if needed
168
+ if isinstance(image, Image.Image):
169
+ pil_img = image
170
+ elif isinstance(image, dict) and "bytes" in image:
171
+ pil_img = Image.open(io.BytesIO(image["bytes"]))
172
+ elif isinstance(image, str):
173
+ pil_img = Image.open(image)
174
+ else:
175
+ raise ValueError(f"Unsupported image type: {type(image)}")
176
+
177
+ # Convert to RGB
178
+ pil_img = pil_img.convert("RGB")
179
+
180
+ # Apply smart resize if requested. Spotting benefits from higher resolution
181
+ # (per the model card), so allow more pixels in that mode.
182
+ if apply_smart_resize:
183
+ original_size = pil_img.size
184
+ max_pixels = 28 * 28 * (2048 if task_mode == "spotting" else 1280)
185
+ new_height, new_width = smart_resize(
186
+ pil_img.height, pil_img.width, max_pixels=max_pixels
187
+ )
188
+ if (new_width, new_height) != (pil_img.width, pil_img.height):
189
+ pil_img = pil_img.resize((new_width, new_height), Image.Resampling.LANCZOS)
190
+ logger.debug(f"Resized image from {original_size} to {pil_img.size}")
191
+
192
+ # Convert to base64 data URI
193
+ buf = io.BytesIO()
194
+ pil_img.save(buf, format="PNG")
195
+ data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
196
+
197
+ # PaddleOCR-VL message format: image first, then task prefix
198
+ return [
199
+ {
200
+ "role": "user",
201
+ "content": [
202
+ {"type": "image_url", "image_url": {"url": data_uri}},
203
+ {"type": "text", "text": TASK_MODES[task_mode]},
204
+ ],
205
+ }
206
+ ]
207
+
208
+
209
+ def create_dataset_card(
210
+ source_dataset: str,
211
+ model: str,
212
+ task_mode: str,
213
+ num_samples: int,
214
+ processing_time: str,
215
+ batch_size: int,
216
+ max_model_len: int,
217
+ max_tokens: int,
218
+ gpu_memory_utilization: float,
219
+ temperature: float,
220
+ apply_smart_resize: bool,
221
+ image_column: str = "image",
222
+ split: str = "train",
223
+ ) -> str:
224
+ """Create a dataset card documenting the OCR process."""
225
+ task_description = TASK_DESCRIPTIONS[task_mode]
226
+
227
+ return f"""---
228
+ tags:
229
+ - ocr
230
+ - document-processing
231
+ - paddleocr-vl
232
+ - paddleocr-vl-1.6
233
+ - {task_mode}
234
+ - uv-script
235
+ - generated
236
+ ---
237
+
238
+ # Document Processing using PaddleOCR-VL-1.6 ({task_mode.upper()} mode)
239
+
240
+ This dataset contains {task_mode.upper()} results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using PaddleOCR-VL-1.6, an ultra-compact 0.9B OCR model (96.33% SOTA on OmniDocBench v1.6).
241
+
242
+ ## Processing Details
243
+
244
+ - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
245
+ - **Model**: [{model}](https://huggingface.co/{model})
246
+ - **Task Mode**: `{task_mode}` - {task_description}
247
+ - **Number of Samples**: {num_samples:,}
248
+ - **Processing Time**: {processing_time}
249
+ - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
250
+
251
+ ### Configuration
252
+
253
+ - **Image Column**: `{image_column}`
254
+ - **Output Column**: `markdown`
255
+ - **Dataset Split**: `{split}`
256
+ - **Batch Size**: {batch_size}
257
+ - **Smart Resize**: {"Enabled" if apply_smart_resize else "Disabled"}
258
+ - **Max Model Length**: {max_model_len:,} tokens
259
+ - **Max Output Tokens**: {max_tokens:,}
260
+ - **Temperature**: {temperature}
261
+ - **GPU Memory Utilization**: {gpu_memory_utilization:.1%}
262
+
263
+ ## Model Information
264
+
265
+ PaddleOCR-VL-1.6 is a state-of-the-art, resource-efficient model tailored for document parsing:
266
+ - 🎯 **SOTA** - 96.33% on OmniDocBench v1.6
267
+ - 🧩 **Ultra-compact** - Only 0.9B parameters
268
+ - 📝 **OCR mode** - General text extraction
269
+ - 📊 **Table mode** - HTML table recognition
270
+ - 📐 **Formula mode** - LaTeX mathematical notation
271
+ - 📈 **Chart mode** - Structured chart analysis
272
+ - 🔍 **Spotting mode** - Text spotting with localization
273
+ - 🔖 **Seal mode** - Seal/stamp recognition
274
+ - 🌍 **Multilingual** - Support for multiple languages
275
+ - 🔧 **ERNIE-4.5 based** - Different architecture from Qwen models
276
+
277
+ ### Task Modes
278
+
279
+ - **OCR**: Extract text content to markdown format
280
+ - **Table Recognition**: Extract tables to HTML format
281
+ - **Formula Recognition**: Extract mathematical formulas to LaTeX
282
+ - **Chart Recognition**: Analyze and describe charts/diagrams
283
+ - **Spotting**: Text spotting with localization
284
+ - **Seal Recognition**: Seal and stamp recognition
285
+
286
+ ## Dataset Structure
287
+
288
+ The dataset contains all original columns plus:
289
+ - `markdown`: The extracted content based on task mode
290
+ - `inference_info`: JSON list tracking all OCR models applied to this dataset
291
+
292
+ ## Usage
293
+
294
+ ```python
295
+ from datasets import load_dataset
296
+ import json
297
+
298
+ # Load the dataset
299
+ dataset = load_dataset("{{output_dataset_id}}", split="{split}")
300
+
301
+ # Access the extracted content
302
+ for example in dataset:
303
+ print(example["markdown"])
304
+ break
305
+
306
+ # View all OCR models applied to this dataset
307
+ inference_info = json.loads(dataset[0]["inference_info"])
308
+ for info in inference_info:
309
+ print(f"Task: {{info['task_mode']}} - Model: {{info['model_id']}}")
310
+ ```
311
+
312
+ ## Reproduction
313
+
314
+ This dataset was generated using the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) PaddleOCR-VL-1.6 script.
315
+ On HF Jobs, run with the pre-built vLLM image (image-mode) so flashinfer kernels are reused:
316
+
317
+ ```bash
318
+ hf jobs uv run \\
319
+ --image vllm/vllm-openai:latest --flavor a100-large \\
320
+ --python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\
321
+ -s HF_TOKEN \\
322
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl-1.6.py \\
323
+ {source_dataset} \\
324
+ <output-dataset> \\
325
+ --task-mode {task_mode} \\
326
+ --image-column {image_column} \\
327
+ --batch-size {batch_size} \\
328
+ --max-model-len {max_model_len} \\
329
+ --max-tokens {max_tokens} \\
330
+ --gpu-memory-utilization {gpu_memory_utilization}
331
+ ```
332
+
333
+ ## Performance
334
+
335
+ - **Model Size**: 0.9B parameters (smallest among top-tier OCR models)
336
+ - **Processing Speed**: ~{num_samples / (float(processing_time.split()[0]) * 60):.2f} images/second
337
+ - **Architecture**: NaViT visual encoder + ERNIE-4.5-0.3B language model
338
+
339
+ Generated with 🤖 [UV Scripts](https://huggingface.co/uv-scripts)
340
+ """
341
+
342
+
343
+ def main(
344
+ input_dataset: str,
345
+ output_dataset: str,
346
+ image_column: str = "image",
347
+ batch_size: int = 16,
348
+ task_mode: str = "ocr",
349
+ max_model_len: int = 8192,
350
+ max_tokens: int = 4096,
351
+ temperature: float = 0.0,
352
+ gpu_memory_utilization: float = 0.8,
353
+ apply_smart_resize: bool = True,
354
+ hf_token: str = None,
355
+ split: str = "train",
356
+ max_samples: int = None,
357
+ private: bool = False,
358
+ shuffle: bool = False,
359
+ seed: int = 42,
360
+ output_column: str = None,
361
+ config: str = None,
362
+ create_pr: bool = False,
363
+ verbose: bool = False,
364
+ ):
365
+ """Process images from HF dataset through PaddleOCR-VL-1.6 model."""
366
+
367
+ # Check CUDA availability first
368
+ check_cuda_availability()
369
+
370
+ # Track processing start time
371
+ start_time = datetime.now()
372
+
373
+ # Enable high-performance Xet downloads
374
+ os.environ["HF_XET_HIGH_PERFORMANCE"] = "1"
375
+
376
+ # Login to HF if token provided
377
+ HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
378
+ if HF_TOKEN:
379
+ login(token=HF_TOKEN)
380
+
381
+ # Validate task mode
382
+ if task_mode not in TASK_MODES:
383
+ raise ValueError(
384
+ f"Invalid task_mode '{task_mode}'. Choose from: {list(TASK_MODES.keys())}"
385
+ )
386
+
387
+ # Default output column is 'markdown' for consistency across scripts
388
+ if output_column is None:
389
+ output_column = "markdown"
390
+
391
+ logger.info(f"Using task mode: {task_mode} - {TASK_DESCRIPTIONS[task_mode]}")
392
+ logger.info(f"Output will be written to column: {output_column}")
393
+
394
+ # Load dataset
395
+ logger.info(f"Loading dataset: {input_dataset}")
396
+ dataset = load_dataset(input_dataset, split=split)
397
+
398
+ # Validate image column
399
+ if image_column not in dataset.column_names:
400
+ raise ValueError(
401
+ f"Column '{image_column}' not found. Available: {dataset.column_names}"
402
+ )
403
+
404
+ # Shuffle if requested
405
+ if shuffle:
406
+ logger.info(f"Shuffling dataset with seed {seed}")
407
+ dataset = dataset.shuffle(seed=seed)
408
+
409
+ # Limit samples if requested
410
+ if max_samples:
411
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
412
+ logger.info(f"Limited to {len(dataset)} samples")
413
+
414
+ # Initialize vLLM model
415
+ logger.info(f"Initializing vLLM with {MODEL_ID}")
416
+ logger.info("This may take a minute on first run (model is only 0.9B)...")
417
+
418
+ try:
419
+ llm = LLM(
420
+ model=MODEL_ID,
421
+ trust_remote_code=True,
422
+ max_model_len=max_model_len,
423
+ gpu_memory_utilization=gpu_memory_utilization,
424
+ limit_mm_per_prompt={"image": 1},
425
+ max_num_batched_tokens=16384,
426
+ enable_prefix_caching=False,
427
+ enforce_eager=True,
428
+ )
429
+ except Exception as e:
430
+ logger.error(f"Failed to initialize PaddleOCR-VL-1.6 with vLLM: {e}")
431
+ logger.error(
432
+ "On HF Jobs, run with the pre-built vLLM image so flashinfer kernels are "
433
+ "reused (the default uv-script image has no nvcc):"
434
+ )
435
+ logger.error(
436
+ " --image vllm/vllm-openai:latest --flavor a100-large "
437
+ "--python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages"
438
+ )
439
+ sys.exit(1)
440
+
441
+ # Sampling parameters - deterministic for OCR
442
+ sampling_params = SamplingParams(
443
+ temperature=temperature,
444
+ max_tokens=max_tokens,
445
+ )
446
+
447
+ logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
448
+ if apply_smart_resize:
449
+ logger.info("Smart resize enabled (PaddleOCR-VL's adaptive resolution)")
450
+
451
+ # Process images in batches
452
+ all_outputs = []
453
+
454
+ for batch_indices in tqdm(
455
+ partition_all(batch_size, range(len(dataset))),
456
+ total=(len(dataset) + batch_size - 1) // batch_size,
457
+ desc=f"PaddleOCR-VL-1.6 {task_mode.upper()} processing",
458
+ ):
459
+ batch_indices = list(batch_indices)
460
+ batch_images = [dataset[i][image_column] for i in batch_indices]
461
+
462
+ try:
463
+ # Create messages for batch with task-specific prefix
464
+ batch_messages = [
465
+ make_ocr_message(
466
+ img, task_mode=task_mode, apply_smart_resize=apply_smart_resize
467
+ )
468
+ for img in batch_images
469
+ ]
470
+
471
+ # Process with vLLM
472
+ outputs = llm.chat(batch_messages, sampling_params)
473
+
474
+ # Extract outputs
475
+ for output in outputs:
476
+ text = output.outputs[0].text.strip()
477
+ all_outputs.append(text)
478
+
479
+ except Exception as e:
480
+ logger.error(f"Error processing batch: {e}")
481
+ # Add error placeholders for failed batch
482
+ all_outputs.extend([f"[{task_mode.upper()} ERROR]"] * len(batch_images))
483
+
484
+ # Calculate processing time
485
+ processing_duration = datetime.now() - start_time
486
+ processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
487
+
488
+ # Add output column to dataset
489
+ logger.info(f"Adding '{output_column}' column to dataset")
490
+ dataset = dataset.add_column(output_column, all_outputs)
491
+
492
+ # Handle inference_info tracking (for multi-model comparisons)
493
+ inference_entry = {
494
+ "model_id": MODEL_ID,
495
+ "model_name": "PaddleOCR-VL-1.6",
496
+ "model_size": "0.9B",
497
+ "task_mode": task_mode,
498
+ "column_name": output_column,
499
+ "timestamp": datetime.now().isoformat(),
500
+ "temperature": temperature,
501
+ "max_tokens": max_tokens,
502
+ "smart_resize": apply_smart_resize,
503
+ "backend": "vllm",
504
+ }
505
+
506
+ if "inference_info" in dataset.column_names:
507
+ # Append to existing inference info
508
+ logger.info("Updating existing inference_info column")
509
+
510
+ def update_inference_info(example):
511
+ try:
512
+ existing_info = (
513
+ json.loads(example["inference_info"])
514
+ if example["inference_info"]
515
+ else []
516
+ )
517
+ except (json.JSONDecodeError, TypeError):
518
+ existing_info = []
519
+
520
+ existing_info.append(inference_entry)
521
+ return {"inference_info": json.dumps(existing_info)}
522
+
523
+ dataset = dataset.map(update_inference_info)
524
+ else:
525
+ # Create new inference_info column
526
+ logger.info("Creating new inference_info column")
527
+ inference_list = [json.dumps([inference_entry])] * len(dataset)
528
+ dataset = dataset.add_column("inference_info", inference_list)
529
+
530
+ # Push to hub with retry and XET fallback
531
+ logger.info(f"Pushing to {output_dataset}")
532
+ max_retries = 3
533
+ for attempt in range(1, max_retries + 1):
534
+ try:
535
+ if attempt > 1:
536
+ logger.warning("Disabling XET (fallback to HTTP upload)")
537
+ os.environ["HF_HUB_DISABLE_XET"] = "1"
538
+ dataset.push_to_hub(
539
+ output_dataset,
540
+ private=private,
541
+ token=HF_TOKEN,
542
+ max_shard_size="500MB",
543
+ **({"config_name": config} if config else {}),
544
+ create_pr=create_pr,
545
+ commit_message=f"Add {MODEL_ID} OCR results ({len(dataset)} samples)"
546
+ + (f" [{config}]" if config else ""),
547
+ )
548
+ break
549
+ except Exception as e:
550
+ logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
551
+ if attempt < max_retries:
552
+ delay = 30 * (2 ** (attempt - 1))
553
+ logger.info(f"Retrying in {delay}s...")
554
+ time.sleep(delay)
555
+ else:
556
+ logger.error("All upload attempts failed. OCR results are lost.")
557
+ sys.exit(1)
558
+
559
+ # Create and push dataset card (skip when creating a PR to avoid touching main)
560
+ if not create_pr:
561
+ logger.info("Creating dataset card")
562
+ card_content = create_dataset_card(
563
+ source_dataset=input_dataset,
564
+ model=MODEL_ID,
565
+ task_mode=task_mode,
566
+ num_samples=len(dataset),
567
+ processing_time=processing_time_str,
568
+ batch_size=batch_size,
569
+ max_model_len=max_model_len,
570
+ max_tokens=max_tokens,
571
+ gpu_memory_utilization=gpu_memory_utilization,
572
+ temperature=temperature,
573
+ apply_smart_resize=apply_smart_resize,
574
+ image_column=image_column,
575
+ split=split,
576
+ )
577
+
578
+ card = DatasetCard(card_content)
579
+ card.push_to_hub(output_dataset, token=HF_TOKEN)
580
+
581
+ logger.info("✅ PaddleOCR-VL-1.6 processing complete!")
582
+ logger.info(
583
+ f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
584
+ )
585
+ logger.info(f"Processing time: {processing_time_str}")
586
+ logger.info(f"Task mode: {task_mode} - {TASK_DESCRIPTIONS[task_mode]}")
587
+
588
+ if verbose:
589
+ import importlib.metadata
590
+
591
+ logger.info("--- Resolved package versions ---")
592
+ for pkg in ["vllm", "transformers", "torch", "datasets", "pyarrow", "pillow"]:
593
+ try:
594
+ logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
595
+ except importlib.metadata.PackageNotFoundError:
596
+ logger.info(f" {pkg}: not installed")
597
+ logger.info("--- End versions ---")
598
+
599
+
600
+ if __name__ == "__main__":
601
+ # Show example usage if no arguments
602
+ if len(sys.argv) == 1:
603
+ print("=" * 80)
604
+ print("PaddleOCR-VL-1.6 Document Processing")
605
+ print("=" * 80)
606
+ print("\nUltra-compact 0.9B OCR model (96.33% SOTA on OmniDocBench v1.6)")
607
+ print("\nFeatures:")
608
+ print("- 🎯 SOTA - 96.33% on OmniDocBench v1.6 (0.9B params)")
609
+ print("- 📝 OCR mode - General text extraction")
610
+ print("- 📊 Table mode - HTML table recognition")
611
+ print("- 📐 Formula mode - LaTeX mathematical notation")
612
+ print("- 📈 Chart mode - Structured chart analysis")
613
+ print("- 🔍 Spotting mode - Text spotting with localization")
614
+ print("- 🔖 Seal mode - Seal/stamp recognition")
615
+ print("- 🌍 Multilingual support")
616
+ print("- 🔧 Based on ERNIE-4.5 (unique architecture)")
617
+ print("\nTask Modes:")
618
+ for mode, description in TASK_DESCRIPTIONS.items():
619
+ print(f" {mode:8} - {description}")
620
+ print("\nExample usage:")
621
+ print("\n1. Basic OCR (default mode):")
622
+ print(" uv run paddleocr-vl-1.6.py input-dataset output-dataset")
623
+ print("\n2. Table extraction:")
624
+ print(" uv run paddleocr-vl-1.6.py docs tables-extracted --task-mode table")
625
+ print("\n3. Formula recognition:")
626
+ print(
627
+ " uv run paddleocr-vl-1.6.py papers formulas --task-mode formula --batch-size 32"
628
+ )
629
+ print("\n4. Chart analysis:")
630
+ print(" uv run paddleocr-vl-1.6.py diagrams charts-analyzed --task-mode chart")
631
+ print("\n5. Test with small sample:")
632
+ print(" uv run paddleocr-vl-1.6.py dataset test --max-samples 10 --shuffle")
633
+ print("\n6. Running on HF Jobs (image-mode required — see note below):")
634
+ print(" hf jobs uv run \\")
635
+ print(" --image vllm/vllm-openai:latest --flavor a100-large \\")
636
+ print(
637
+ " --python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\"
638
+ )
639
+ print(" -s HF_TOKEN \\")
640
+ print(
641
+ " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl-1.6.py \\"
642
+ )
643
+ print(" input-dataset output-dataset --task-mode ocr")
644
+ print("\n NOTE: the default uv-script image has no nvcc, so vLLM's flashinfer")
645
+ print(" sampler crashes at warmup. The vllm/vllm-openai image ships the kernels.")
646
+ print("\n" + "=" * 80)
647
+ print("\nFor full help, run: uv run paddleocr-vl-1.6.py --help")
648
+ sys.exit(0)
649
+
650
+ parser = argparse.ArgumentParser(
651
+ description="Document processing using PaddleOCR-VL-1.6 (0.9B SOTA OCR model)",
652
+ formatter_class=argparse.RawDescriptionHelpFormatter,
653
+ epilog="""
654
+ Task Modes:
655
+ ocr General text extraction to markdown (default)
656
+ table Table extraction to HTML format
657
+ formula Mathematical formula recognition to LaTeX
658
+ chart Chart and diagram analysis
659
+ spotting Text spotting with localization
660
+ seal Seal and stamp recognition
661
+
662
+ Examples:
663
+ # Basic text OCR
664
+ uv run paddleocr-vl-1.6.py my-docs analyzed-docs
665
+
666
+ # Extract tables from documents
667
+ uv run paddleocr-vl-1.6.py papers tables --task-mode table
668
+
669
+ # Recognize mathematical formulas
670
+ uv run paddleocr-vl-1.6.py textbooks formulas --task-mode formula
671
+
672
+ # Analyze charts and diagrams
673
+ uv run paddleocr-vl-1.6.py reports charts --task-mode chart
674
+
675
+ # Test with random sampling
676
+ uv run paddleocr-vl-1.6.py large-dataset test --max-samples 50 --shuffle --task-mode ocr
677
+
678
+ # Disable smart resize for original resolution
679
+ uv run paddleocr-vl-1.6.py images output --no-smart-resize
680
+ """,
681
+ )
682
+
683
+ parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
684
+ parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
685
+ parser.add_argument(
686
+ "--image-column",
687
+ default="image",
688
+ help="Column containing images (default: image)",
689
+ )
690
+ parser.add_argument(
691
+ "--batch-size",
692
+ type=int,
693
+ default=16,
694
+ help="Batch size for processing (default: 16)",
695
+ )
696
+ parser.add_argument(
697
+ "--task-mode",
698
+ choices=list(TASK_MODES.keys()),
699
+ default="ocr",
700
+ help="Task type: ocr (default), table, formula, chart, spotting, or seal",
701
+ )
702
+ parser.add_argument(
703
+ "--max-model-len",
704
+ type=int,
705
+ default=8192,
706
+ help="Maximum model context length (default: 8192)",
707
+ )
708
+ parser.add_argument(
709
+ "--max-tokens",
710
+ type=int,
711
+ default=4096,
712
+ help="Maximum tokens to generate (default: 4096)",
713
+ )
714
+ parser.add_argument(
715
+ "--temperature",
716
+ type=float,
717
+ default=0.0,
718
+ help="Sampling temperature (default: 0.0 for deterministic)",
719
+ )
720
+ parser.add_argument(
721
+ "--gpu-memory-utilization",
722
+ type=float,
723
+ default=0.8,
724
+ help="GPU memory utilization (default: 0.8)",
725
+ )
726
+ parser.add_argument(
727
+ "--no-smart-resize",
728
+ action="store_true",
729
+ help="Disable PaddleOCR-VL's smart resize, use original image size",
730
+ )
731
+ parser.add_argument("--hf-token", help="Hugging Face API token")
732
+ parser.add_argument(
733
+ "--split", default="train", help="Dataset split to use (default: train)"
734
+ )
735
+ parser.add_argument(
736
+ "--max-samples",
737
+ type=int,
738
+ help="Maximum number of samples to process (for testing)",
739
+ )
740
+ parser.add_argument(
741
+ "--private", action="store_true", help="Make output dataset private"
742
+ )
743
+ parser.add_argument(
744
+ "--shuffle", action="store_true", help="Shuffle dataset before processing"
745
+ )
746
+ parser.add_argument(
747
+ "--seed",
748
+ type=int,
749
+ default=42,
750
+ help="Random seed for shuffling (default: 42)",
751
+ )
752
+ parser.add_argument(
753
+ "--output-column",
754
+ help="Column name for output (default: markdown)",
755
+ )
756
+ parser.add_argument(
757
+ "--config",
758
+ help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
759
+ )
760
+ parser.add_argument(
761
+ "--create-pr",
762
+ action="store_true",
763
+ help="Create a pull request instead of pushing directly (for parallel benchmarking)",
764
+ )
765
+ parser.add_argument(
766
+ "--verbose",
767
+ action="store_true",
768
+ help="Log resolved package versions after processing (useful for pinning deps)",
769
+ )
770
+
771
+ args = parser.parse_args()
772
+
773
+ main(
774
+ input_dataset=args.input_dataset,
775
+ output_dataset=args.output_dataset,
776
+ image_column=args.image_column,
777
+ batch_size=args.batch_size,
778
+ task_mode=args.task_mode,
779
+ max_model_len=args.max_model_len,
780
+ max_tokens=args.max_tokens,
781
+ temperature=args.temperature,
782
+ gpu_memory_utilization=args.gpu_memory_utilization,
783
+ apply_smart_resize=not args.no_smart_resize,
784
+ hf_token=args.hf_token,
785
+ split=args.split,
786
+ max_samples=args.max_samples,
787
+ private=args.private,
788
+ shuffle=args.shuffle,
789
+ seed=args.seed,
790
+ output_column=args.output_column,
791
+ config=args.config,
792
+ create_pr=args.create_pr,
793
+ verbose=args.verbose,
794
+ )