davanstrien HF Staff commited on
Commit
8c093f4
·
verified ·
1 Parent(s): 343d37f

Sync from GitHub via hub-sync

Browse files
Files changed (3) hide show
  1. CLAUDE.md +10 -0
  2. README.md +4 -2
  3. ovis-ocr2.py +682 -0
CLAUDE.md CHANGED
@@ -71,6 +71,7 @@ Legend: ✅ production-ready · ⚠️ works only with a required pinned image
71
  | `dots-ocr.py` | ✅ | vLLM (stable) | l4x1 | `--max-model-len` 32768; no internal resize |
72
  | `dots-ocr-1.5.py` | ✅ | vLLM 0.17.1 | l4x1 | see gotcha (`content_format`, mirror, bbox space) |
73
  | `glm-ocr.py` | ✅ | vLLM (nightly) | l4x1 | `VLLM_USE_DEEP_GEMM=0`; no pyarrow cap |
 
74
  | `glm-ocr-v2.py` | 🧪 | vLLM (nightly) | l4x1 | CommitScheduler incremental — on hold (see Deferred) |
75
  | `nanonets-ocr.py` | ✅ | vLLM | a10g-small | `--max-model-len` 32768 (`--max-tokens` 15000) |
76
  | `nanonets-ocr2.py` | ⚠️+image | vLLM `:v0.10.2` | a10g-small | Qwen2.5-VL ≥0.11 regression → pure `!` |
@@ -252,6 +253,11 @@ LightOnOCR-2's commentary style).
252
  - **Incremental uploads** — superseded by HF Buckets / `bucketbag` ([#67](https://github.com/davanstrien/uv-scripts-for-ai/issues/67));
253
  `glm-ocr-v2.py` keeps the older CommitScheduler resume path for very large jobs today (do not port it — on hold).
254
  - **Leaderboard Space** — public ELO/pointwise view fed by the benchmark datasets. Idea only.
 
 
 
 
 
255
 
256
  **Watch:** `deepseek-ocr2` / `glm-ocr` stay on nightly vLLM until their arch lands in a stable release.
257
  The nightly index (`https://wheels.vllm.ai/nightly`) occasionally has transient build issues (e.g. only
@@ -261,6 +267,10 @@ ARM wheels) — if a nightly-recipe install fails on resolution, wait and retry
261
 
262
  ## Change log
263
 
 
 
 
 
264
  - **2026-07-08** — HunyuanOCR upstream repo swap: pinned `hunyuan-ocr.py` to the last 1.0 revision +
265
  added `hunyuan-ocr-1.5.py` (12 task types, locked sampling); `transformers<5.13` cap in both for the
266
  stable-vLLM HunyuanVL register breakage (vllm#47872). See the hunyuan gotcha above.
 
71
  | `dots-ocr.py` | ✅ | vLLM (stable) | l4x1 | `--max-model-len` 32768; no internal resize |
72
  | `dots-ocr-1.5.py` | ✅ | vLLM 0.17.1 | l4x1 | see gotcha (`content_format`, mirror, bbox space) |
73
  | `glm-ocr.py` | ✅ | vLLM (nightly) | l4x1 | `VLLM_USE_DEEP_GEMM=0`; no pyarrow cap |
74
+ | `ovis-ocr2.py` | ✅ | vLLM (stable ≥0.22.1) | l4x1 / a10g-small | `gdn_prefill_backend="triton"` (card); card-exact prompt via `enable_thinking=False` template + `llm.generate`; `<img>` region tags filtered by default (`--keep-image-tags`) |
75
  | `glm-ocr-v2.py` | 🧪 | vLLM (nightly) | l4x1 | CommitScheduler incremental — on hold (see Deferred) |
76
  | `nanonets-ocr.py` | ✅ | vLLM | a10g-small | `--max-model-len` 32768 (`--max-tokens` 15000) |
77
  | `nanonets-ocr2.py` | ⚠️+image | vLLM `:v0.10.2` | a10g-small | Qwen2.5-VL ≥0.11 regression → pure `!` |
 
253
  - **Incremental uploads** — superseded by HF Buckets / `bucketbag` ([#67](https://github.com/davanstrien/uv-scripts-for-ai/issues/67));
254
  `glm-ocr-v2.py` keeps the older CommitScheduler resume path for very large jobs today (do not port it — on hold).
255
  - **Leaderboard Space** — public ELO/pointwise view fed by the benchmark datasets. Idea only.
256
+ - **MonkeyOCRv2 — evaluated, not added** (2026-07-14). `zenosai/MonkeyOCRv2-S-Parsing` (0.6B) needs the
257
+ [GitHub repo's](https://github.com/Yuliang-Liu/MonkeyOCRv2) custom multi-stage pipeline (`parsing/parse.py`,
258
+ structure detection) — not pip-packaged, pins `vllm==0.11.2`, and the card text says "academic research and
259
+ non-commercial use only" while the metadata tag says `apache-2.0` (conflicting license signals). Revisit if
260
+ it gets packaged / vLLM-native support or the license is clarified.
261
 
262
  **Watch:** `deepseek-ocr2` / `glm-ocr` stay on nightly vLLM until their arch lands in a stable release.
263
  The nightly index (`https://wheels.vllm.ai/nightly`) occasionally has transient build issues (e.g. only
 
267
 
268
  ## Change log
269
 
270
+ - **2026-07-14** — added `ovis-ocr2.py` (`ATH-MaaS/OvisOCR2`, 0.9B Qwen3.5, 96.58 OmniDocBench v1.6,
271
+ Apache-2.0; stable vLLM ≥0.22.1, `gdn_prefill_backend="triton"`, card-exact prompt/postprocessing).
272
+ Smoke-tested green on the default uv image, a10g-small, resolved vLLM 0.25.1 (5/5 pages, tags filtered,
273
+ stamp OK). Evaluated MonkeyOCRv2 alongside it — deferred (see Deferred / tracked).
274
  - **2026-07-08** — HunyuanOCR upstream repo swap: pinned `hunyuan-ocr.py` to the last 1.0 revision +
275
  added `hunyuan-ocr-1.5.py` (12 task types, locked sampling); `transformers<5.13` cap in both for the
276
  stable-vLLM HunyuanVL register breakage (vllm#47872). See the hunyuan gotcha above.
README.md CHANGED
@@ -37,7 +37,7 @@ The recipes here run as batch jobs. To call a model interactively, from an agent
37
 
38
  ## Models at a glance
39
 
40
- **Start here:** for a quick first run, try **`lighton-ocr2.py`** (1B, very fast) or **`paddleocr-vl-1.6.py`** (0.9B, current OmniDocBench SOTA); for the smallest footprint, **`falcon-ocr.py`** (0.3B, strong on tables). Reach for a 7–8B model only when quality demands it. Several of these models sit on the public [olmOCR-Bench](https://huggingface.co/datasets/allenai/olmOCR-bench) — pull the live ranking from your terminal in one command:
41
 
42
  ```bash
43
  hf datasets leaderboard allenai/olmOCR-bench
@@ -57,7 +57,8 @@ _Sorted by model size:_
57
  | [`glm-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/glm-ocr.py) | [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) | 0.9B | vLLM | 94.62% OmniDocBench V1.5 |
58
  | [`paddleocr-vl.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/paddleocr-vl.py) | [PaddleOCR-VL](https://huggingface.co/PaddlePaddle/PaddleOCR-VL) | 0.9B | vLLM | 4 task modes (ocr/table/formula/chart) |
59
  | [`paddleocr-vl-1.5.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/paddleocr-vl-1.5.py) | [PaddleOCR-VL-1.5](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.5) | 0.9B | Transformers | 94.5% OmniDocBench, 6 task modes |
60
- | [`paddleocr-vl-1.6.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/paddleocr-vl-1.6.py) | [PaddleOCR-VL-1.6](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.6) | 0.9B | vLLM | **96.33% OmniDocBench v1.6** (SOTA), drop-in upgrade of 1.5 |
 
61
  | [`lighton-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/lighton-ocr.py) | [LightOnOCR-1B](https://huggingface.co/lightonai/LightOnOCR-1B-1025) | 1B | vLLM | Fast, 3 vocab sizes |
62
  | [`lighton-ocr2.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/lighton-ocr2.py) | [LightOnOCR-2-1B](https://huggingface.co/lightonai/LightOnOCR-2-1B) | 1B | vLLM | 7× faster than v1, RLVR trained |
63
  | [`hunyuan-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/hunyuan-ocr.py) | [HunyuanOCR 1.0](https://huggingface.co/tencent/HunyuanOCR/tree/f6af82ee007fe6091b29fb3bb287b491ead41c82) | 1B | vLLM | Lightweight VLM. Pinned to the last 1.0 revision (repo root became 1.5 in-place on 2026-07-06). [Hunyuan Community License](https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE) (excludes EU/UK/KR) |
@@ -208,6 +209,7 @@ Beyond the shared flags, some models add their own. Run `--help` on any script f
208
  | [`surya-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/surya-ocr.py) | `--task ocr\|layout\|table`, `--table-mode full\|simple`, `--pdf-column`/`--page-range`, `--blocks-column` |
209
  | [`pp-ocrv6.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/pp-ocrv6.py) | `--model-tier tiny\|small\|medium` (1.5M–34.5M params) |
210
  | [`glm-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/glm-ocr.py) | `--task ocr\|formula\|table` |
 
211
  | [`paddleocr-vl.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/paddleocr-vl.py) | `--task-mode ocr\|table\|formula\|chart` |
212
  | [`paddleocr-vl-1.5.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/paddleocr-vl-1.5.py) | `--task-mode ocr\|table\|formula\|chart\|spotting\|seal` |
213
  | [`paddleocr-vl-1.6.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/paddleocr-vl-1.6.py) | `--task-mode ocr\|table\|formula` |
 
37
 
38
  ## Models at a glance
39
 
40
+ **Start here:** for a quick first run, try **`lighton-ocr2.py`** (1B, very fast), **`paddleocr-vl-1.6.py`** (0.9B, 96.33 OmniDocBench) or **`ovis-ocr2.py`** (0.9B, 96.58 OmniDocBench — current SOTA); for the smallest footprint, **`falcon-ocr.py`** (0.3B, strong on tables). Reach for a 7–8B model only when quality demands it. Several of these models sit on the public [olmOCR-Bench](https://huggingface.co/datasets/allenai/olmOCR-bench) — pull the live ranking from your terminal in one command:
41
 
42
  ```bash
43
  hf datasets leaderboard allenai/olmOCR-bench
 
57
  | [`glm-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/glm-ocr.py) | [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) | 0.9B | vLLM | 94.62% OmniDocBench V1.5 |
58
  | [`paddleocr-vl.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/paddleocr-vl.py) | [PaddleOCR-VL](https://huggingface.co/PaddlePaddle/PaddleOCR-VL) | 0.9B | vLLM | 4 task modes (ocr/table/formula/chart) |
59
  | [`paddleocr-vl-1.5.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/paddleocr-vl-1.5.py) | [PaddleOCR-VL-1.5](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.5) | 0.9B | Transformers | 94.5% OmniDocBench, 6 task modes |
60
+ | [`paddleocr-vl-1.6.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/paddleocr-vl-1.6.py) | [PaddleOCR-VL-1.6](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.6) | 0.9B | vLLM | **96.33% OmniDocBench v1.6**, drop-in upgrade of 1.5 |
61
+ | [`ovis-ocr2.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/ovis-ocr2.py) | [OvisOCR2](https://huggingface.co/ATH-MaaS/OvisOCR2) | 0.9B | vLLM | **96.58 OmniDocBench v1.6** (SOTA; first end-to-end model to top it). Qwen3.5 base; markdown + LaTeX + HTML tables. Apache 2.0 |
62
  | [`lighton-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/lighton-ocr.py) | [LightOnOCR-1B](https://huggingface.co/lightonai/LightOnOCR-1B-1025) | 1B | vLLM | Fast, 3 vocab sizes |
63
  | [`lighton-ocr2.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/lighton-ocr2.py) | [LightOnOCR-2-1B](https://huggingface.co/lightonai/LightOnOCR-2-1B) | 1B | vLLM | 7× faster than v1, RLVR trained |
64
  | [`hunyuan-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/hunyuan-ocr.py) | [HunyuanOCR 1.0](https://huggingface.co/tencent/HunyuanOCR/tree/f6af82ee007fe6091b29fb3bb287b491ead41c82) | 1B | vLLM | Lightweight VLM. Pinned to the last 1.0 revision (repo root became 1.5 in-place on 2026-07-06). [Hunyuan Community License](https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE) (excludes EU/UK/KR) |
 
209
  | [`surya-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/surya-ocr.py) | `--task ocr\|layout\|table`, `--table-mode full\|simple`, `--pdf-column`/`--page-range`, `--blocks-column` |
210
  | [`pp-ocrv6.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/pp-ocrv6.py) | `--model-tier tiny\|small\|medium` (1.5M–34.5M params) |
211
  | [`glm-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/glm-ocr.py) | `--task ocr\|formula\|table` |
212
+ | [`ovis-ocr2.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/ovis-ocr2.py) | `--keep-image-tags` (retain visual-region `<img>` bbox tags, filtered by default), `--min-pixels`/`--max-pixels` (processor bounds, card defaults 448²/2880²) |
213
  | [`paddleocr-vl.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/paddleocr-vl.py) | `--task-mode ocr\|table\|formula\|chart` |
214
  | [`paddleocr-vl-1.5.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/paddleocr-vl-1.5.py) | `--task-mode ocr\|table\|formula\|chart\|spotting\|seal` |
215
  | [`paddleocr-vl-1.6.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/paddleocr-vl-1.6.py) | `--task-mode ocr\|table\|formula` |
ovis-ocr2.py ADDED
@@ -0,0 +1,682 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "datasets>=4.0.0",
5
+ # "huggingface-hub",
6
+ # "pillow",
7
+ # "vllm>=0.22.1",
8
+ # "toolz",
9
+ # "torch",
10
+ # ]
11
+ # ///
12
+
13
+ """
14
+ Convert document images to markdown using OvisOCR2 with vLLM.
15
+
16
+ OvisOCR2 is a compact 0.9B end-to-end document parsing model (post-trained from
17
+ Qwen3.5-0.8B with SFT + RL + OPD). It scores 96.58 on OmniDocBench v1.6 — the
18
+ first end-to-end model to top that leaderboard — and 75.06 Avg3 on PureDocBench.
19
+ Outputs a single Markdown document in natural reading order: LaTeX formulas,
20
+ HTML tables, and (optionally) HTML <img> tags marking chart/image regions with
21
+ bounding boxes scaled to [0, 1000).
22
+
23
+ Model: ATH-MaaS/OvisOCR2 (Apache-2.0)
24
+ vLLM: stock Qwen3_5ForConditionalGeneration arch, in stable vLLM >= 0.22.1
25
+ (the version the model card installs); no trust_remote_code needed.
26
+
27
+ Features:
28
+ - 0.9B parameters (ultra-compact, runs on l4x1)
29
+ - Markdown output with LaTeX formulas + HTML tables
30
+ - Visual-region <img> tags filtered by default (upstream parser default);
31
+ keep them with --keep-image-tags for downstream crop extraction
32
+ - Upstream trailing-repeat cleanup applied to each output
33
+ """
34
+
35
+ import argparse
36
+ import io
37
+ import json
38
+ import logging
39
+ import os
40
+ import sys
41
+ import time
42
+ from datetime import datetime
43
+ from typing import Any, Dict, Union
44
+
45
+ import torch
46
+ from datasets import load_dataset
47
+ from huggingface_hub import DatasetCard, login
48
+ from PIL import Image
49
+ from toolz import partition_all
50
+
51
+ # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
52
+ # default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
53
+ # lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
54
+ os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
55
+ # DeepGEMM's init calls _find_cuda_home, which asserts on the nvcc-less base image — a
56
+ # non-fatal warning traceback that clutters the log (seen in the 2026-07-14 smoke run on
57
+ # vLLM 0.25.1). Greedy OCR doesn't need the DeepGEMM JIT path, so disable it explicitly.
58
+ os.environ.setdefault("VLLM_USE_DEEP_GEMM", "0")
59
+ from vllm import LLM, SamplingParams
60
+
61
+ logging.basicConfig(level=logging.INFO)
62
+ logger = logging.getLogger(__name__)
63
+
64
+ MODEL = "ATH-MaaS/OvisOCR2"
65
+
66
+ # Fixed instruction prompt, verbatim from the model card (including the leading newline).
67
+ # The card warns outputs are tuned to this exact wording — don't "improve" it.
68
+ OCR_PROMPT = (
69
+ "\nExtract all readable content from the image in natural human reading order "
70
+ "and output the result as a single Markdown document. For charts or images, "
71
+ 'represent them using an HTML image tag: <img src="images/bbox_{left}_{top}_'
72
+ '{right}_{bottom}.jpg" />, where left, top, right, bottom are bounding box '
73
+ "coordinates scaled to [0, 1000). Format formulas as LaTeX. Format tables as "
74
+ "HTML: <table>...</table>. Transcribe all other text as standard Markdown. "
75
+ "Preserve the original text without translation or paraphrasing."
76
+ )
77
+
78
+ # Image bounds from the model card's parser (passed per-request as images_kwargs).
79
+ DEFAULT_MIN_PIXELS = 448 * 448 # 200,704
80
+ DEFAULT_MAX_PIXELS = 2880 * 2880 # 8,294,400
81
+
82
+
83
+ def check_cuda_availability():
84
+ """Check if CUDA is available and exit if not."""
85
+ if not torch.cuda.is_available():
86
+ logger.error("CUDA is not available. This script requires a GPU.")
87
+ logger.error("Please run on a machine with a CUDA-capable GPU.")
88
+ sys.exit(1)
89
+ else:
90
+ logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
91
+
92
+
93
+ def ensure_output_columns_free(dataset, columns, overwrite=False):
94
+ """Fail fast if an output column would collide with an existing input column.
95
+
96
+ Adding a column that already exists silently overwrites it (e.g. a ground-truth
97
+ `text`/`markdown` column) or crashes on push with a duplicate-column error only
98
+ *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
99
+ column(s) here instead (logged) so the later add_column is clean.
100
+ """
101
+ clash = [c for c in columns if c in dataset.column_names]
102
+ if not clash:
103
+ return dataset
104
+ if overwrite:
105
+ logger.warning(f"--overwrite: replacing existing column(s) {clash}")
106
+ return dataset.remove_columns(clash)
107
+ logger.error(
108
+ f"Output column(s) {clash} already exist in the input dataset "
109
+ f"(columns: {dataset.column_names})."
110
+ )
111
+ logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
112
+ sys.exit(1)
113
+
114
+
115
+ def to_pil_image(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:
116
+ """Convert a dataset image cell (PIL image, bytes dict, or path) to RGB PIL."""
117
+ if isinstance(image, Image.Image):
118
+ pil_img = image
119
+ elif isinstance(image, dict) and "bytes" in image:
120
+ pil_img = Image.open(io.BytesIO(image["bytes"]))
121
+ elif isinstance(image, str):
122
+ pil_img = Image.open(image)
123
+ else:
124
+ raise ValueError(f"Unsupported image type: {type(image)}")
125
+ return pil_img.convert("RGB")
126
+
127
+
128
+ def clean_truncated_repeats(
129
+ text: str,
130
+ min_text_len: int = 8000,
131
+ max_period: int = 200,
132
+ min_period: int = 1,
133
+ min_repeat_chars: int = 100,
134
+ min_repeat_times: int = 5,
135
+ ) -> str:
136
+ """Trim degenerate trailing repetition (verbatim port of the model card's cleanup).
137
+
138
+ Long outputs that hit max_tokens can end in a repeated unit (a char, phrase, or
139
+ table row); this detects the shortest repeating tail unit and keeps one copy.
140
+ """
141
+ n = len(text)
142
+ if n < min_text_len:
143
+ return text
144
+
145
+ max_period = min(max_period, n - 1)
146
+ for unit_len in range(min_period, max_period + 1):
147
+ if text[n - 1] != text[n - 1 - unit_len]:
148
+ continue
149
+
150
+ match_len = 1
151
+ idx = n - 2
152
+ while idx >= unit_len and text[idx] == text[idx - unit_len]:
153
+ match_len += 1
154
+ idx -= 1
155
+
156
+ total_len = match_len + unit_len
157
+ repeat_times = total_len // unit_len
158
+ tail_len = total_len % unit_len
159
+
160
+ if repeat_times >= min_repeat_times and total_len >= min_repeat_chars:
161
+ return text[: n - total_len + unit_len] + text[n - tail_len :]
162
+
163
+ return text
164
+
165
+
166
+ def filter_image_tags(text: str) -> str:
167
+ """Drop visual-region <img> blocks (upstream parser's default behaviour)."""
168
+ return "\n\n".join(
169
+ block
170
+ for block in text.split("\n\n")
171
+ if not block.strip().startswith('<img src="images/bbox_')
172
+ )
173
+
174
+
175
+ def postprocess_output(text: str, keep_image_tags: bool) -> str:
176
+ text = text.strip()
177
+ if not keep_image_tags:
178
+ text = filter_image_tags(text)
179
+ return clean_truncated_repeats(text)
180
+
181
+
182
+ def create_dataset_card(
183
+ source_dataset: str,
184
+ model: str,
185
+ num_samples: int,
186
+ processing_time: str,
187
+ batch_size: int,
188
+ max_model_len: int,
189
+ max_tokens: int,
190
+ gpu_memory_utilization: float,
191
+ keep_image_tags: bool,
192
+ image_column: str = "image",
193
+ split: str = "train",
194
+ ) -> str:
195
+ """Create a dataset card documenting the OCR process."""
196
+ model_name = model.split("/")[-1]
197
+
198
+ # Canonical provenance stamp (see AGENTS.md): Jobs claim gated on JOB_ID, set by HF Jobs in-container.
199
+ on_jobs = os.environ.get("JOB_ID") is not None
200
+ hw = os.environ.get("ACCELERATOR") or ""
201
+ origin = (
202
+ "Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"
203
+ + (f" (`{hw}`)" if hw else "")
204
+ ) if on_jobs else "Generated"
205
+ jobs_tag = "\n- hf-jobs" if on_jobs else ""
206
+
207
+ return f"""---
208
+ tags:
209
+ - ocr
210
+ - document-processing
211
+ - ovis-ocr2
212
+ - markdown
213
+ - uv-script
214
+ - generated{jobs_tag}
215
+ ---
216
+
217
+ # Document OCR using {model_name}
218
+
219
+ This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using OvisOCR2, a compact 0.9B document parsing model (96.58 on OmniDocBench v1.6).
220
+
221
+ ## Processing Details
222
+
223
+ - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
224
+ - **Model**: [{model}](https://huggingface.co/{model})
225
+ - **Number of Samples**: {num_samples:,}
226
+ - **Processing Time**: {processing_time}
227
+ - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
228
+
229
+ ### Configuration
230
+
231
+ - **Image Column**: `{image_column}`
232
+ - **Dataset Split**: `{split}`
233
+ - **Batch Size**: {batch_size}
234
+ - **Max Model Length**: {max_model_len:,} tokens
235
+ - **Max Output Tokens**: {max_tokens:,}
236
+ - **Temperature**: 0.0 (greedy, per model card)
237
+ - **GPU Memory Utilization**: {gpu_memory_utilization:.1%}
238
+ - **Visual-region image tags**: {"kept" if keep_image_tags else "filtered (default)"}
239
+
240
+ ## Model Information
241
+
242
+ OvisOCR2 is a compact, high-performance document parsing model:
243
+ - 0.9B parameters (post-trained from Qwen3.5-0.8B with SFT + RL + OPD)
244
+ - 96.58 on OmniDocBench v1.6 (first end-to-end model to top the leaderboard)
245
+ - Markdown output in natural reading order
246
+ - LaTeX formula recognition, HTML table extraction
247
+ - Apache-2.0 licensed
248
+
249
+ ## Dataset Structure
250
+
251
+ The dataset contains all original columns plus:
252
+ - `markdown`: The extracted text in markdown format
253
+ - `inference_info`: JSON list tracking all OCR models applied to this dataset
254
+
255
+ ## Reproduction
256
+
257
+ {origin} with the [`ovis-ocr2.py`](https://huggingface.co/datasets/uv-scripts/ocr/raw/main/ovis-ocr2.py) recipe from [uv-scripts](https://huggingface.co/uv-scripts). Run it yourself:
258
+
259
+ ```bash
260
+ hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/ovis-ocr2.py \\
261
+ {source_dataset} \\
262
+ <output-dataset> \\
263
+ --image-column {image_column} \\
264
+ --batch-size {batch_size}
265
+ ```
266
+ """
267
+
268
+
269
+ def main(
270
+ input_dataset: str,
271
+ output_dataset: str,
272
+ image_column: str = "image",
273
+ batch_size: int = 16,
274
+ max_model_len: int = 32768,
275
+ max_tokens: int = 16384,
276
+ min_pixels: int = DEFAULT_MIN_PIXELS,
277
+ max_pixels: int = DEFAULT_MAX_PIXELS,
278
+ gpu_memory_utilization: float = 0.8,
279
+ keep_image_tags: bool = False,
280
+ hf_token: str = None,
281
+ split: str = "train",
282
+ max_samples: int = None,
283
+ private: bool = False,
284
+ shuffle: bool = False,
285
+ seed: int = 42,
286
+ output_column: str = "markdown",
287
+ overwrite: bool = False,
288
+ verbose: bool = False,
289
+ config: str = None,
290
+ create_pr: bool = False,
291
+ ):
292
+ """Process images from HF dataset through OvisOCR2."""
293
+
294
+ check_cuda_availability()
295
+
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
+ logger.info(f"Using model: {MODEL}")
303
+
304
+ # Load dataset
305
+ logger.info(f"Loading dataset: {input_dataset}")
306
+ dataset = load_dataset(input_dataset, split=split)
307
+
308
+ if image_column not in dataset.column_names:
309
+ raise ValueError(
310
+ f"Column '{image_column}' not found. Available: {dataset.column_names}"
311
+ )
312
+
313
+ # Fail fast if the output column would collide with an existing input column
314
+ dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
315
+
316
+ if shuffle:
317
+ logger.info(f"Shuffling dataset with seed {seed}")
318
+ dataset = dataset.shuffle(seed=seed)
319
+
320
+ if max_samples:
321
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
322
+ logger.info(f"Limited to {len(dataset)} samples")
323
+
324
+ # Initialize vLLM
325
+ logger.info("Initializing vLLM with OvisOCR2")
326
+ logger.info("This may take a few minutes on first run...")
327
+ # gdn_prefill_backend="triton" is from the model card: Qwen3.5 uses gated-delta-net
328
+ # linear attention, and the non-triton GDN prefill path needs a JIT/CUDA toolchain
329
+ # the bare uv image lacks (same class of problem as the FLASHINFER guard above).
330
+ llm = LLM(
331
+ model=MODEL,
332
+ max_model_len=max_model_len,
333
+ gpu_memory_utilization=gpu_memory_utilization,
334
+ limit_mm_per_prompt={"image": 1},
335
+ gdn_prefill_backend="triton",
336
+ )
337
+
338
+ # The model card builds the prompt once via the chat template with
339
+ # enable_thinking=False — Qwen3.5 templates can otherwise inject a thinking
340
+ # preamble, which is wrong for OCR. Mirror it exactly.
341
+ prompt = llm.get_tokenizer().apply_chat_template(
342
+ [
343
+ {
344
+ "role": "user",
345
+ "content": [
346
+ {"type": "image"},
347
+ {"type": "text", "text": OCR_PROMPT},
348
+ ],
349
+ }
350
+ ],
351
+ tokenize=False,
352
+ add_generation_prompt=True,
353
+ enable_thinking=False,
354
+ )
355
+
356
+ # Card-locked sampling: greedy, 16384 max tokens.
357
+ sampling_params = SamplingParams(temperature=0.0, max_tokens=max_tokens)
358
+
359
+ logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
360
+ logger.info(f"Output will be written to column: {output_column}")
361
+
362
+ all_outputs = []
363
+ total_batches = (len(dataset) + batch_size - 1) // batch_size
364
+ processed = 0
365
+
366
+ for batch_num, batch_indices in enumerate(
367
+ partition_all(batch_size, range(len(dataset))), 1
368
+ ):
369
+ batch_indices = list(batch_indices)
370
+ batch_images = [dataset[i][image_column] for i in batch_indices]
371
+
372
+ logger.info(
373
+ f"Batch {batch_num}/{total_batches} "
374
+ f"({processed}/{len(dataset)} images done)"
375
+ )
376
+
377
+ try:
378
+ # Per-request inputs exactly as the model card's parser builds them
379
+ # (PIL image + images_kwargs pixel bounds), via llm.generate not llm.chat
380
+ # so the enable_thinking=False prompt above is used verbatim.
381
+ vllm_inputs = [
382
+ {
383
+ "prompt": prompt,
384
+ "multi_modal_data": {"image": to_pil_image(img)},
385
+ "mm_processor_kwargs": {
386
+ "images_kwargs": {
387
+ "min_pixels": min_pixels,
388
+ "max_pixels": max_pixels,
389
+ }
390
+ },
391
+ }
392
+ for img in batch_images
393
+ ]
394
+
395
+ outputs = llm.generate(vllm_inputs, sampling_params)
396
+
397
+ for output in outputs:
398
+ text = output.outputs[0].text
399
+ all_outputs.append(postprocess_output(text, keep_image_tags))
400
+
401
+ processed += len(batch_images)
402
+
403
+ except Exception as e:
404
+ logger.error(f"Error processing batch: {e}")
405
+ all_outputs.extend(["[OCR ERROR]"] * len(batch_images))
406
+ processed += len(batch_images)
407
+
408
+ processing_duration = datetime.now() - start_time
409
+ processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
410
+
411
+ logger.info(f"Adding '{output_column}' column to dataset")
412
+ dataset = dataset.add_column(output_column, all_outputs)
413
+
414
+ # Inference info tracking
415
+ inference_entry = {
416
+ "model_id": MODEL,
417
+ "model_name": "OvisOCR2",
418
+ "column_name": output_column,
419
+ "timestamp": datetime.now().isoformat(),
420
+ "temperature": 0.0,
421
+ "max_tokens": max_tokens,
422
+ "min_pixels": min_pixels,
423
+ "max_pixels": max_pixels,
424
+ "keep_image_tags": keep_image_tags,
425
+ }
426
+
427
+ if "inference_info" in dataset.column_names:
428
+ logger.info("Updating existing inference_info column")
429
+
430
+ def update_inference_info(example):
431
+ try:
432
+ existing_info = (
433
+ json.loads(example["inference_info"])
434
+ if example["inference_info"]
435
+ else []
436
+ )
437
+ except (json.JSONDecodeError, TypeError):
438
+ existing_info = []
439
+ existing_info.append(inference_entry)
440
+ return {"inference_info": json.dumps(existing_info)}
441
+
442
+ dataset = dataset.map(update_inference_info)
443
+ else:
444
+ logger.info("Creating new inference_info column")
445
+ inference_list = [json.dumps([inference_entry])] * len(dataset)
446
+ dataset = dataset.add_column("inference_info", inference_list)
447
+
448
+ # Push to hub with retry and XET fallback
449
+ logger.info(f"Pushing to {output_dataset}")
450
+ max_retries = 3
451
+ for attempt in range(1, max_retries + 1):
452
+ try:
453
+ if attempt > 1:
454
+ logger.warning("Disabling XET (fallback to HTTP upload)")
455
+ os.environ["HF_HUB_DISABLE_XET"] = "1"
456
+ dataset.push_to_hub(
457
+ output_dataset,
458
+ private=private,
459
+ token=HF_TOKEN,
460
+ max_shard_size="500MB",
461
+ **({"config_name": config} if config else {}),
462
+ create_pr=create_pr,
463
+ commit_message=f"Add {MODEL} OCR results ({len(dataset)} samples)"
464
+ + (f" [{config}]" if config else ""),
465
+ )
466
+ break
467
+ except Exception as e:
468
+ logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
469
+ if attempt < max_retries:
470
+ delay = 30 * (2 ** (attempt - 1))
471
+ logger.info(f"Retrying in {delay}s...")
472
+ time.sleep(delay)
473
+ else:
474
+ logger.error("All upload attempts failed. OCR results are lost.")
475
+ sys.exit(1)
476
+
477
+ # Create and push dataset card
478
+ logger.info("Creating dataset card")
479
+ card_content = create_dataset_card(
480
+ source_dataset=input_dataset,
481
+ model=MODEL,
482
+ num_samples=len(dataset),
483
+ processing_time=processing_time_str,
484
+ batch_size=batch_size,
485
+ max_model_len=max_model_len,
486
+ max_tokens=max_tokens,
487
+ gpu_memory_utilization=gpu_memory_utilization,
488
+ keep_image_tags=keep_image_tags,
489
+ image_column=image_column,
490
+ split=split,
491
+ )
492
+
493
+ card = DatasetCard(card_content)
494
+ card.push_to_hub(output_dataset, token=HF_TOKEN)
495
+
496
+ logger.info("Done! OvisOCR2 processing complete.")
497
+ logger.info(
498
+ f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
499
+ )
500
+ logger.info(f"Processing time: {processing_time_str}")
501
+ logger.info(
502
+ f"Processing speed: {len(dataset) / processing_duration.total_seconds():.2f} images/sec"
503
+ )
504
+
505
+ if verbose:
506
+ import importlib.metadata
507
+
508
+ logger.info("--- Resolved package versions ---")
509
+ for pkg in ["vllm", "transformers", "torch", "datasets", "pyarrow", "pillow"]:
510
+ try:
511
+ logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
512
+ except importlib.metadata.PackageNotFoundError:
513
+ logger.info(f" {pkg}: not installed")
514
+ logger.info("--- End versions ---")
515
+
516
+
517
+ if __name__ == "__main__":
518
+ if len(sys.argv) == 1:
519
+ print("=" * 70)
520
+ print("OvisOCR2 Document Processing")
521
+ print("=" * 70)
522
+ print("\n0.9B document parsing model - 96.58 on OmniDocBench v1.6")
523
+ print("\nOutputs markdown in natural reading order:")
524
+ print(" - LaTeX formulas, HTML tables")
525
+ print(" - Visual-region <img> tags filtered by default")
526
+ print(" (--keep-image-tags to retain them)")
527
+ print("\nExamples:")
528
+ print("\n1. Basic OCR:")
529
+ print(" uv run ovis-ocr2.py input-dataset output-dataset")
530
+ print("\n2. Keep visual-region image tags:")
531
+ print(" uv run ovis-ocr2.py docs results --keep-image-tags")
532
+ print("\n3. Test with small sample:")
533
+ print(" uv run ovis-ocr2.py large-dataset test --max-samples 10 --shuffle")
534
+ print("\n4. Running on HF Jobs:")
535
+ print(" hf jobs uv run --flavor l4x1 \\")
536
+ print(" -s HF_TOKEN \\")
537
+ print(
538
+ " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/ovis-ocr2.py \\"
539
+ )
540
+ print(" input-dataset output-dataset --batch-size 16")
541
+ print("\nFor full help: uv run ovis-ocr2.py --help")
542
+ sys.exit(0)
543
+
544
+ parser = argparse.ArgumentParser(
545
+ description="Document OCR using OvisOCR2 (0.9B, 96.58 OmniDocBench v1.6)",
546
+ formatter_class=argparse.RawDescriptionHelpFormatter,
547
+ epilog="""
548
+ Examples:
549
+ uv run ovis-ocr2.py my-docs analyzed-docs
550
+ uv run ovis-ocr2.py docs results --keep-image-tags
551
+ uv run ovis-ocr2.py large-dataset test --max-samples 50 --shuffle
552
+ """,
553
+ )
554
+
555
+ parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
556
+ parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
557
+ parser.add_argument(
558
+ "--image-column",
559
+ default="image",
560
+ help="Column containing images (default: image)",
561
+ )
562
+ parser.add_argument(
563
+ "--batch-size",
564
+ type=int,
565
+ default=16,
566
+ help="Batch size for processing (default: 16)",
567
+ )
568
+ parser.add_argument(
569
+ "--max-model-len",
570
+ type=int,
571
+ default=32768,
572
+ help="Maximum model context length (default: 32768; model supports 262144)",
573
+ )
574
+ parser.add_argument(
575
+ "--max-tokens",
576
+ type=int,
577
+ default=16384,
578
+ help="Maximum tokens to generate (default: 16384, the model card value)",
579
+ )
580
+ parser.add_argument(
581
+ "--min-pixels",
582
+ type=int,
583
+ default=DEFAULT_MIN_PIXELS,
584
+ help=f"Minimum image pixels for the processor (default: {DEFAULT_MIN_PIXELS}, "
585
+ "= 448*448, the model card value)",
586
+ )
587
+ parser.add_argument(
588
+ "--max-pixels",
589
+ type=int,
590
+ default=DEFAULT_MAX_PIXELS,
591
+ help=f"Maximum image pixels for the processor; larger images are downscaled "
592
+ f"internally (default: {DEFAULT_MAX_PIXELS}, = 2880*2880, the model card value)",
593
+ )
594
+ parser.add_argument(
595
+ "--gpu-memory-utilization",
596
+ type=float,
597
+ default=0.8,
598
+ help="GPU memory utilization (default: 0.8)",
599
+ )
600
+ parser.add_argument(
601
+ "--keep-image-tags",
602
+ action="store_true",
603
+ help="Keep visual-region <img src=\"images/bbox_...\"> tags in the output "
604
+ "(default: filtered, matching the upstream parser)",
605
+ )
606
+ parser.add_argument("--hf-token", help="Hugging Face API token")
607
+ parser.add_argument(
608
+ "--split", default="train", help="Dataset split to use (default: train)"
609
+ )
610
+ parser.add_argument(
611
+ "--max-samples",
612
+ type=int,
613
+ help="Maximum number of samples to process (for testing)",
614
+ )
615
+ parser.add_argument(
616
+ "--private", action="store_true", help="Make output dataset private"
617
+ )
618
+ parser.add_argument(
619
+ "--config",
620
+ help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
621
+ )
622
+ parser.add_argument(
623
+ "--create-pr",
624
+ action="store_true",
625
+ help="Create a pull request instead of pushing directly (for parallel benchmarking)",
626
+ )
627
+ parser.add_argument(
628
+ "--shuffle", action="store_true", help="Shuffle dataset before processing"
629
+ )
630
+ parser.add_argument(
631
+ "--seed",
632
+ type=int,
633
+ default=42,
634
+ help="Random seed for shuffling (default: 42)",
635
+ )
636
+ parser.add_argument(
637
+ "--output-column",
638
+ default="markdown",
639
+ help="Column name for output text (default: markdown)",
640
+ )
641
+ parser.add_argument(
642
+ "--overwrite",
643
+ action="store_true",
644
+ help="Replace the output column if it already exists in the input dataset "
645
+ "(default: error out to avoid clobbering an existing column).",
646
+ )
647
+ parser.add_argument(
648
+ "--verbose",
649
+ action="store_true",
650
+ help="Log resolved package versions after processing (useful for pinning deps)",
651
+ )
652
+
653
+ args = parser.parse_args()
654
+
655
+ if args.max_tokens > args.max_model_len:
656
+ parser.error(
657
+ f"--max-tokens ({args.max_tokens}) must be <= --max-model-len ({args.max_model_len})"
658
+ )
659
+
660
+ main(
661
+ input_dataset=args.input_dataset,
662
+ output_dataset=args.output_dataset,
663
+ image_column=args.image_column,
664
+ batch_size=args.batch_size,
665
+ max_model_len=args.max_model_len,
666
+ max_tokens=args.max_tokens,
667
+ min_pixels=args.min_pixels,
668
+ max_pixels=args.max_pixels,
669
+ gpu_memory_utilization=args.gpu_memory_utilization,
670
+ keep_image_tags=args.keep_image_tags,
671
+ hf_token=args.hf_token,
672
+ split=args.split,
673
+ max_samples=args.max_samples,
674
+ private=args.private,
675
+ shuffle=args.shuffle,
676
+ seed=args.seed,
677
+ output_column=args.output_column,
678
+ overwrite=args.overwrite,
679
+ verbose=args.verbose,
680
+ config=args.config,
681
+ create_pr=args.create_pr,
682
+ )