This view is limited to 50 files because it contains too many changes. See the raw diff here.
AGENTS.md DELETED
@@ -1,109 +0,0 @@
1
- # For coding agents
2
-
3
- This repo is a curated collection of ready-to-run OCR scripts — each one self-contained
4
- via UV inline metadata, runnable over the network via `hf jobs uv run`. No clone, no
5
- install, no setup.
6
-
7
- ## Don't rely on this doc — discover the current state
8
-
9
- This file will go stale. Prefer these sources of truth:
10
-
11
- - `hf jobs uv run --help` — job submission flags (volumes, secrets, flavors, timeouts)
12
- - `hf jobs hardware` — current GPU flavors and pricing
13
- - `hf auth whoami` — check HF token is set
14
- - `hf jobs ps` / `hf jobs logs <id>` — monitor running jobs
15
- - `ls` the repo to see which scripts actually exist (bucket variants especially)
16
- - [README.md](./README.md) — the table of scripts with model sizes and notes
17
-
18
- ## Picking a script
19
-
20
- The [README.md](./README.md) table lists every script with model size, backend, and
21
- a short note. Axes that matter:
22
-
23
- - **Model size** vs accuracy vs GPU cost. Smaller = cheaper per doc.
24
- - **Backend**: vLLM scripts are usually fastest at scale. `transformers` and
25
- `falcon-perception` are alternatives for specific models.
26
- - **Task support**: most scripts do plain text; some expose `--task-mode`
27
- (table, formula, layout, etc.) — check the script's own docstring.
28
- - **Language coverage**: [`models.json`](./models.json) maps every script to its model,
29
- params, backend, required image pins, and what the model card claims about languages —
30
- with an `evidence` level (`per-language-benchmark` beats a bare `multilingual` tag).
31
- Human-readable version: [LANGUAGES.md](./LANGUAGES.md).
32
-
33
- For the authoritative benchmark numbers on any model in the table, query the model
34
- card programmatically — every OCR model publishes eval results on its card:
35
-
36
- from huggingface_hub import HfApi
37
- info = HfApi().model_info("tiiuae/Falcon-OCR", expand=["evalResults"])
38
- for r in info.eval_results:
39
- print(r.dataset_id, r.value)
40
-
41
- See the [leaderboard data guide](https://huggingface.co/docs/hub/en/leaderboard-data-guide)
42
- for the full API. This is more reliable than any markdown table that might drift.
43
-
44
- ## Getting help from a specific script
45
-
46
- Each script has a docstring at the top with a description and usage examples. To read it
47
- without downloading:
48
-
49
- curl -s https://huggingface.co/datasets/uv-scripts/ocr/raw/main/<script>.py | head -100
50
-
51
- Or open the URL in a browser. Running `uv run <url> --help` locally may fail if the
52
- script has GPU-only dependencies — reading the docstring is more reliable.
53
-
54
- ## The main pattern: dataset → dataset
55
-
56
- Most scripts take an input HF dataset ID and push results to an output HF dataset ID:
57
-
58
- hf jobs uv run --flavor l4x1 -s HF_TOKEN \
59
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/<script>.py \
60
- <input-dataset-id> <output-dataset-id> [--max-samples N] [--shuffle]
61
-
62
- The script adds a `markdown` column to the input dataset and pushes the merged result
63
- to the output dataset ID on the Hub.
64
-
65
- ## Alternative: directory → directory (bucket variants)
66
-
67
- A couple of scripts have `-bucket.py` variants (currently `falcon-ocr-bucket.py` and
68
- `glm-ocr-bucket.py`) that read from a mounted directory and write one `.md` per image
69
- (or per PDF page). Useful with HF Buckets via `-v`:
70
-
71
- hf jobs uv run --flavor l4x1 -s HF_TOKEN \
72
- -v hf://buckets/<user>/<input>:/input:ro \
73
- -v hf://buckets/<user>/<output>:/output \
74
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/<script>-bucket.py \
75
- /input /output
76
-
77
- `ls` the repo to check whether a `-bucket.py` variant exists for the model you want
78
- before assuming it's available.
79
-
80
- The `-v` source can also be a **local directory** (`huggingface_hub` ≥ 1.22) — the CLI
81
- syncs it to a private bucket and mounts it, so local images/PDFs need no upload step:
82
-
83
- hf jobs uv run --flavor l4x1 -s HF_TOKEN \
84
- -v ./pages:/input \
85
- -v hf://buckets/<user>/<output>:/output \
86
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/<script>-bucket.py \
87
- /input /output
88
-
89
- Re-runs only sync new/changed files. Local mounts are read-only by default; a local
90
- *output* dir works too with `:rw` — pull results back with the `hf buckets sync`
91
- command the CLI prints at launch.
92
-
93
- ## Common flags across dataset-mode scripts
94
-
95
- Most scripts support: `--max-samples`, `--shuffle`, `--seed`, `--split`, `--image-column`,
96
- `--output-column`, `--private`, `--config`, `--create-pr`, `--verbose`. Read the script's
97
- docstring for the authoritative list — individual scripts may add model-specific options
98
- like `--task-mode`.
99
-
100
- ## Gotchas
101
-
102
- - **Secrets**: pass `-s HF_TOKEN` to forward the user's token into the job.
103
- - **GPU required**: all scripts exit if CUDA isn't available. `l4x1` is the cheapest
104
- GPU flavor and works for models up to ~3B. Check `hf jobs hardware` for current options.
105
- - **First run is slow**: model download + `torch.compile` / vLLM warmup dominates small
106
- runs. Cost per doc drops sharply past a few hundred images — test with `--max-samples 10`
107
- first, then scale.
108
- - **Don't poll jobs**: jobs run async. Submit once, check status later with
109
- `hf jobs ps` or `hf jobs logs <id>`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
CLAUDE.md CHANGED
@@ -1,444 +1,213 @@
1
- # OCR Scripts — Development Notes
2
 
3
- Dev notes for the `ocr/` recipes: the **conventions** to follow, the **per-script gotchas** (the
4
- "why" behind each script's quirks), and the **internal tooling**. Runnable examples live in each
5
- script's docstring and `README.md`; benchmark result tables live in `OCR-BENCHMARK.md`.
6
 
7
- - [Conventions & invariants](#conventions--invariants) — read before adding/changing a recipe
8
- - [Script status](#script-status) · [Per-script gotchas](#per-script-gotchas)
9
- - [Internal tooling](#internal-tooling) · [Deferred / tracked](#deferred--tracked) · [Change log](#change-log)
 
 
10
 
11
- ---
12
-
13
- ## Conventions & invariants
14
-
15
- Read this before adding or changing a recipe. Each rule maps to a failure we've actually hit; the
16
- planned **self-review skill** (see [Deferred](#deferred--tracked)) just enforces this list.
17
-
18
- - **Catalog entry.** Adding or changing a recipe means updating [`models.json`](./models.json)
19
- (script → model, params, backend, image pins, language claim) and, if the language claim
20
- changed, [LANGUAGES.md](./LANGUAGES.md). Language fields record what the **model card claims**
21
- (with an evidence level), never inferred coverage. Hand-maintained for now; if drift becomes a
22
- problem, the follow-up is generating the README table from the JSON.
23
- - **Model-card fidelity.** Default prompts, sampling and processor settings come from the model
24
- card or official client — cite the exact source in a comment (e.g. `# glmocr/config.py
25
- PageLoaderConfig`), or say "card gives none" if upstream is silent. Upstream-locked values stay
26
- locked; expose only the knobs upstream sanctions. Deliberate deviations go in the docstring with
27
- the why. Benchmark before overriding a card value that looks wrong (e.g. hunyuan-1.5
28
- `repetition_penalty` on tables, [#85](https://github.com/davanstrien/uv-scripts/issues/85))
29
- — never silently "improve" it. Docstring/card claims (params, scores, languages) must match the
30
- card too.
31
- - **Self-contained single file.** Each recipe is one PEP 723 UV script runnable from a raw URL
32
- (`hf jobs uv run <url>`). No shared *importable local* module (the job env only gets the one file).
33
- Extra pip deps are fine — **pin them**. A heavy/stable/shared subsystem may become an opt-in *package*
34
- dep (e.g. bucket I/O → `bucketbag`, [#67](https://github.com/davanstrien/uv-scripts/issues/67)),
35
- never a local import. Recipes = inline; internal tooling may share freely.
36
- - **GPU + output.** Check `torch.cuda.is_available()` and exit clearly if absent. Write to the Hub
37
- (`push_to_hub`) or a bucket (`-v hf://…`), never bare local paths (Jobs disk is ephemeral; local *input*
38
- dirs mount via `-v ./dir:/mnt`, synced to a bucket automatically).
39
- - **vLLM image + fail-fast preflight.** If the model's arch isn't in a stable vLLM wheel, **omit
40
- `vllm`/`torch` from deps** and run on the pinned `vllm/vllm-openai` image via
41
- `--image … --python … -e PYTHONPATH=…`; add a preflight that `sys.exit(1)`s naming the exact flags
42
- (surya-class — see gotchas). Pinned-image scripts: `surya-ocr` (`:v0.20.1`, **site-packages**),
43
- `nanonets-ocr2` (`:v0.10.2`), `unlimited-ocr` (`:unlimited-ocr`), `deepseek-ocr2`/`glm-ocr` (nightly).
44
- - **Pins are temporary.** An image/version pin (`:v0.10.2`, `:v0.20.1`, a nightly, `surya-ocr==0.20.0`,
45
- …) is a workaround for a *current* ecosystem gap — a decode regression, an arch not yet in a stable
46
- wheel, a resolver backtrack. In the recipe, record **why** the pin exists and **what would loosen it**
47
- (e.g. "move back to the default image when a newer vLLM ships a Qwen2.5-VL decode fix"; "drop the
48
- nightly once the arch lands in a stable release"). Re-test periodically and relax when the gap closes —
49
- that's what the `maintain-recipes` skill is for; prefer floors over exact pins once you can.
50
- This applies to **active** recipes. **Frozen** recipes (superseded or little used) pin image digest,
51
- package cutoff and model revision on purpose and get fixes only when they break — see
52
- [MAINTAINING.md](https://github.com/davanstrien/uv-scripts/blob/main/MAINTAINING.md).
53
- - **Env guards on the bare image.** Set `VLLM_USE_FLASHINFER_SAMPLER=0` (and `VLLM_USE_DEEP_GEMM=0`
54
- for nightly vLLM) **before** importing `vllm` — both JIT paths need `nvcc`, which the bare uv image lacks.
55
- - **Context-length invariant.** `--max-tokens` ≤ `--max-model-len` ≤ the model's real max context
56
- (`config.json` `max_position_embeddings`; VLMs → `text_config`, mind `rope_scaling`). vLLM refuses to
57
- start if `max_model_len` is over (we don't set `VLLM_ALLOW_LONG_MAX_MODEL_LEN`); output can't fit if
58
- `max_tokens` > `max_model_len`. Check:
59
- `curl -s https://huggingface.co/<model>/raw/main/config.json | python -c "import json,sys;c=json.load(sys.stdin);t=c.get('text_config',c);print(t.get('max_position_embeddings'),t.get('rope_scaling'))"`.
60
- - **Output-column collision guard.** Every recipe that adds an output column calls
61
- `ensure_output_columns_free(dataset, [cols], overwrite)` (or the inline sink guard for pp-*) so it
62
- fails fast instead of duplicating/clobbering an input column; `--overwrite` opts into replacing it.
63
- Default `--output-column` is `markdown` (never a bare `text`). ([#66](https://github.com/davanstrien/uv-scripts/pull/66))
64
- - **Bound large images.** Full-page recipes cap input pixels / resize, or size `max_model_len` to fit —
65
- a 7–9 MP page is ~14k image tokens. Prefer bounding the input (deterministic) over a giant context;
66
- don't auto-size `max_model_len` from images (it's fixed at engine init, before images are seen).
67
- - **Dep sanity.** No stale version *caps* that drag a transitive lib back — e.g. `pyarrow<18` forced an
68
- old `datasets` lacking the `Json` feature → `load_dataset` crashed (the glm-ocr bug). Use floors, not ceilings.
69
- **Exception: image limits.** On a pinned image the image's copy of a shared package wins over uv's, so a
70
- cap that encodes what the image ships is correct (e.g. `datasets<5.1` because 5.1 needs
71
- `huggingface_hub>=1.31` and images before v0.30 ship older). Comment the reason next to the cap
72
- ([MAINTAINING.md](https://github.com/davanstrien/uv-scripts/blob/main/MAINTAINING.md), "Image-mode recipes").
73
- - **Error signalling (known gap).** Scripts currently write sentinels (`[OCR ERROR]`, `[SURYA GENERATE
74
- ERROR]`) *into* the output column, so partial failures are silent. A companion `ocr_error` status
75
- column is the deferred fix (see [Deferred](#deferred--tracked)).
76
 
77
- ---
78
 
79
- ## Script status
80
-
81
- Legend: ✅ production-ready · ⚠️ works only with a required pinned image · 🧪 experimental/on-hold.
82
- "+image" = needs a `--image vllm/vllm-openai:<tag>` override (not the default uv image).
83
-
84
- | Script | | Backend | Flavor | Note |
85
- |--------|--|---------|--------|------|
86
- | `deepseek-ocr-vllm.py` | ✅ | vLLM (stable) | l4x1 | `NGramPerReqLogitsProcessor` anti-repeat |
87
- | `deepseek-ocr2-vllm.py` | ✅ | vLLM (nightly) | l4x1 | arch needs nightly; `addict`+`matplotlib` deps |
88
- | `lighton-ocr2.py` | ✅ | vLLM | a100-large / l4x1 | resize 1540px; `--max-model-len` 16384 |
89
- | `lighton-ocr3-bucket.py` | ✅ | vLLM `:v0.30.0` | a10g-small | `hf://buckets/...` or dir → `.md` (+ `.json` blocks in grounding); bucket I/O via `bucketbag` v0.3.1 (no mount); `.jp2` via imagecodecs; resume-by-skip; failed pages write nothing |
90
- | `lighton-ocr3.py` | ✅ | vLLM `:v0.30.0` | a10g-small | 4B/0.8B Qwen3.5; resize 2048px; `--mode grounding` → `layout_blocks`; pinned upstream `lightonocr` client dep — see gotcha |
91
- | `paddleocr-vl-1.5.py` | ✅ | transformers | l4x1 | not vLLM (server-only upstream); single-image |
92
- | `paddleocr-vl-1.6.py` | ✅ | vLLM | l4x1 | smart-resize ~1M px; SOTA OmniDocBench |
93
- | `paddleocr-vl.py` | ✅ | vLLM | l4x1 | |
94
- | `dots-ocr.py` | ✅ | vLLM (stable) | l4x1 | `--max-model-len` 32768; no internal resize |
95
- | `dots-ocr-1.5.py` | ✅ | vLLM 0.17.1 | l4x1 | see gotcha (`content_format`, mirror, bbox space) |
96
- | `glm-ocr.py` | ✅ | vLLM (nightly) | l4x1 | `VLLM_USE_DEEP_GEMM=0`; no pyarrow cap |
97
- | `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`) |
98
- | `xiaomi-ocr-0-saturate.py` | ✅ | vLLM or SGLang + saturate | a10g-small / rtx-pro-6000 | single-stage only; OTSL→HTML + math delimiters vendored from upstream; `max_tokens` 12000 to fit the 16384 context; default `Auto()` window |
99
- | `glm-ocr-v2.py` | 🧪 | vLLM (nightly) | l4x1 | CommitScheduler incremental — on hold (see Deferred) |
100
- | `nanonets-ocr.py` | ✅ | vLLM | a10g-small | `--max-model-len` 32768 (`--max-tokens` 15000) |
101
- | `nanonets-ocr2.py` | ⚠️+image | vLLM `:v0.10.2` | a10g-small | Qwen2.5-VL ≥0.11 regression → pure `!` |
102
- | `unlimited-ocr-vllm.py` | ✅+image | vLLM `:unlimited-ocr` | l4x1 | single-image; multi-page → serve |
103
- | `unlimited-ocr2.py` | ✅+image | SGLang (Baidu wheel) on `lmsysorg/sglang:v0.5.20-cu130` | rtx-pro-6000 | 16-page windows; ≥48 GB GPU |
104
- | `unlimited-ocr2-saturate.py` | 🧪+image | same | rtx-pro-6000 | tuned/experimental: repair pass, JP2 fast decode, PDFs |
105
- | `unlimited-ocr2-live.py` | 🧪+image | same | rtx-pro-6000 | experimental: minimal script + `--live-port` dashboard (streams the page being read) |
106
- | `hpd-parsing-saturate.py` | 🧪+image | saturate + Paddle's vLLM fork on `cr.hf.co/davanstrien/hpd-parsing-vllm` (vendor image + uv) | l4x1 | `markdown` + `hpd_blocks` + `looped_blocks` — see gotcha |
107
- | `minicpm-ocr.py` | 🧪+image | in-job vLLM nightly + minicpm-ocr SDK on `cr.hf.co/davanstrien/minicpm-ocr` | a10g-large | vendor pipeline; custom public image; dataset **or** bucket I/O (bucketbag), `markdown_status` |
108
- | `surya-ocr.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | offline backend inject; site-packages PYTHONPATH |
109
- | `surya-ocr-bucket.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | bucket I/O; pin `surya-ocr==0.20.0` |
110
- | `lift-extract.py` | ✅ | hf / vLLM | a100-large | schema-constrained extraction; naming gotcha |
111
- | `nuextract3.py`, `lfm2-extract.py`, `lfm2-vl-extract.py` | ✅ | vLLM | l4x1 | structured extraction |
112
- | `hunyuan-ocr.py` | ✅ | vLLM | l4x1 | **1.0, revision-pinned** (root repo became 1.5 in-place); `transformers<5.13` cap — see gotcha |
113
- | `hunyuan-ocr-1.5.py` | ✅ | vLLM | l4x1 | tracks repo root (=1.5); task-locked prompts; `transformers<5.13` cap — see gotcha |
114
- | `rolm-ocr.py`, `smoldocling-ocr.py`, `numarkdown-ocr.py`, `qianfan-ocr.py`, `firered-ocr.py`, `abot-ocr.py`, `falcon-ocr.py`, `olmocr2-vllm.py`, `dots-mocr.py` | ✅ | vLLM | varies | see `README.md` for flags |
115
- | `pp-ocrv6.py`, `pp-doclayout.py` | ✅ | PaddleOCR / PaddleX | l4x1 | classical det+rec; dataset **or** bucket I/O |
116
-
117
- **License note:** Surya and `lift` ship code as Apache-2.0 but **weights under a modified OpenRAIL-M**
118
- (research/personal/<$5M, no competitive use vs Datalab's API) — surfaced in each docstring + card.
119
- HunyuanOCR (1.0 + 1.5) is under the [Tencent Hunyuan Community License](https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE)
120
- (territory excludes EU/UK/South Korea; standard across Tencent's Hunyuan releases) — surfaced in each docstring + card.
121
 
122
- ---
 
 
 
123
 
124
- ## Per-script gotchas
125
-
126
- Only the scripts with load-bearing quirks; the rest are unremarkable (`README.md` covers flags).
127
-
128
- ### `surya-ocr.py` / `surya-ocr-bucket.py` — pinned image + site-packages path
129
- Surya-2 (`datalab-to/surya-ocr-2`, 650M, `qwen3_5`) needs its **known-good** vLLM build, and the
130
- `:v0.20.1` image puts python at `/usr/local/bin/python3` and libs at
131
- **`/usr/local/lib/python3.12/site-packages`** (not the usual `dist-packages`) — wrong path →
132
- `No module named 'vllm'` → 0/5. It can't Docker-in-Docker Surya's normal server, so it **injects an
133
- in-process `OfflineVLLMBackend`** into `SuryaInferenceManager` (subclassing Surya's `Backend` ABC) and
134
- reuses Surya's own prompts/`scale_to_fit`/HTML+bbox parsing so the offline path matches the server.
135
- `mm_processor_kwargs={min_pixels:3136, max_pixels:6291456}`, `max_model_len=18000`, `logprobs=1` →
136
- per-block `confidence`. Writes two columns (`--output-column` markdown + `surya_blocks` JSON). Never
137
- name the file `surya.py` (shadows the package). The recipe now **fails fast** if `vllm` isn't importable,
138
- naming the required flags. **Bucket variant:** pin `surya-ocr==0.20.0` (loosening it, or adding
139
- `huggingface-hub>=1.6.0`, lets uv backtrack to a surya without `surya.inference`); **copy beats mount**
140
- for bucket reads (FUSE `rglob` is ~26× slower on a 38k-file bucket; mount also hit a transient CSI flake);
141
- `.jp2` via an `imagecodecs` fallback (Pillow lacks OpenJPEG); resume-by-skip on the output `.json`.
142
-
143
- ### `nanonets-ocr2.py` — pinned `:v0.10.2` image
144
- Nanonets-OCR2-3B is **Qwen2.5-VL**, which has a vLLM **≥0.11 decode regression** (outputs pure `!` on
145
- every page) — [vllm#27775](https://github.com/vllm-project/vllm/issues/27775). 0.9.2/0.10.1/**0.10.2**
146
- are known-good. Not context length (still `!` at 32768) and not torch.compile. Pip-pinning `vllm==0.10.2`
147
- clashes with modern `transformers` (old tokenizer API), so run on the **`:v0.10.2` image** (ships a
148
- consistent vLLM 0.10.2 + transformers 4.56.1); `vllm`/`torch` omitted from deps. `--max-model-len` 32768
149
- (the 15000 `--max-tokens` can't fit 8192). Re-test the default image when a newer vLLM ships a Qwen2.5-VL
150
- decode fix.
151
-
152
- ### `dots-ocr-1.5.py` — `content_format="string"` + resized-bbox space
153
- Must pass `chat_template_content_format="string"` to `llm.chat()` — the model's `tokenizer_config.json`
154
- template expects string content; without it you get ~1 token then EOS (empty output). The v1.5 weights
155
- aren't on HF from the authors — **mirrored to `davanstrien/dots.ocr-1.5`** from ModelScope (MIT-based).
156
- Layout bboxes are in the **resized** image space (`Qwen2VLImageProcessor.smart_resize`,
157
- `max_pixels=11,289,600`, `factor=28`); map back with:
158
- ```python
159
- import math
160
- def smart_resize(h, w, factor=28, min_pixels=3136, max_pixels=11289600):
161
- h_bar, w_bar = max(factor, round(h/factor)*factor), max(factor, round(w/factor)*factor)
162
- if h_bar*w_bar > max_pixels:
163
- beta = math.sqrt((h*w)/max_pixels); h_bar, w_bar = math.floor(h/beta/factor)*factor, math.floor(w/beta/factor)*factor
164
- elif h_bar*w_bar < min_pixels:
165
- beta = math.sqrt(min_pixels/(h*w)); h_bar, w_bar = math.ceil(h*beta/factor)*factor, math.ceil(w*beta/factor)*factor
166
- return h_bar, w_bar
167
- # orig_x = bbox_x * (orig_w / w_bar); orig_y = bbox_y * (orig_h / h_bar)
168
  ```
169
- (Same `smart_resize`/`max_pixels=11.29M` applies to `dots-ocr.py` v1's processor cap — but the
170
- `content_format="string"` fix does **not**: v1 works with the auto-detected `openai` chat format.)
171
-
172
- ### `unlimited-ocr-vllm.py` — dedicated image, single-image batch
173
- Baidu `baidu/Unlimited-OCR` (3.3B, DeepSeek-OCR descendant); arch is in **no stable vLLM wheel**, so it
174
- runs on **`vllm/vllm-openai:unlimited-ocr`** (`:unlimited-ocr-cu129` on Hopper), standard `/usr/bin/python3`
175
- + `dist-packages`. `NGramPerReqLogitsProcessor` (re-exported via `unlimited_ocr`), prompt
176
- `<image>document parsing.`, `limit_mm_per_prompt={"image":1}`, `--strip-grounding` drops `<|det|>`/`<|ref|>`.
177
- **Batch recipe stays single-image**; multi-page is finicky offline (one `<image>` per page; degrades on
178
- hard scans) and belongs to **serving** — both engines read clean multi-page docs, but **SGLang is more
179
- robust on hard/degraded scans**. Serving setup (SGLang pin `lmsysorg/sglang:v0.5.10.post1`, a100+flashinfer
180
- — HF `h200` nodes fail with `CUDA error 802`) is in `serving-unlimited-ocr.md`.
181
-
182
- ### `minicpm-ocr.py` — vendor SDK pipeline on a custom `cr.hf.co` image
183
- MiniCPM-OCR 1.0 is a region reader: OpenBMB's SDK runs PP-DocLayoutV3, crops regions, prompts each by
184
- type and assembles Markdown. The recipe runs that SDK unchanged (separate venv `/opt/sdk`, as OpenBMB
185
- require) against `vllm serve` started in the job. Measured/learned 2026-10-27:
186
- - `MiniCPMOcrForConditionalGeneration` is in vLLM main (18343393b4, 23 Oct) but not in v0.32.0, and
187
- OpenBMB's install builds vLLM from source (~40 min). The image uses nightly 5d35ce3 pinned by digest
188
- instead; Dockerfile + digest in `images/minicpm-ocr/`. Move to a stock tag when a release has the arch.
189
- - pip warns `transformers 5.21.0.dev0` (OpenBMB's pin 549e5b4) violates vLLM's `<5.21.0` (a pre-release
190
- of 5.21.0 is excluded by `<5.21.0`); vLLM serves the model anyway.
191
- - The SDK's default layout path is `${ASSETS_DIR}/PP-DocLayoutV3`, not the docs' `models/PP-DocLayoutV3_infer`;
192
- the recipe passes the baked path explicitly. The layout tar is sha256-checked at build time.
193
- - Built with kaniko on a `cpu-upgrade` Job (~20 min); container repo creation needed the stored `cli` token
194
- (the OAuth login gets 403). `l4x1` had no capacity on 27 Oct; smoke ran on `a10g-large`.
195
- - The SDK reads a folder: the recipe writes each batch as `{i:06d}.png` and reads `output/{i:06d}.md` back.
196
- - The SDK writes a `.md` even when regions fail (empty for a failed text region); the page status lives in
197
- `per_page_metrics.jsonl` (`ok` / `partial_failed` / `failed`). The recipe reads it: dataset mode keeps it in
198
- `markdown_status`; bucket mode writes only `ok` pages so a re-run retries the rest (Codex review, 27 Oct).
199
- - vLLM runs in its own process group and is terminated → killed → reaped on every exit path; one bad
200
- image or a failed SDK run marks its pages `error: ...` instead of losing finished batches.
201
-
202
- ### `hpd-parsing-saturate.py` — Paddle's vLLM fork, on their image plus uv
203
- `PaddlePaddle/HPD-Parsing` (1B, InternVL3.5 + Qwen3-0.6B) runs only on Paddle's **fork of vLLM**
204
- (`0.17.1+hpdparsing`), which adds the request forking its decoding needs. The fork ships only in
205
- `ccr-2vdh3abv-pub.cnc.bj.baidubce.com/paddlepaddle/hpd-parsing-vllm` (tags `latest-nvidia-gpu`, and
206
- `-offline` with weights baked in). It pulls anonymously; the recipe pins `latest-nvidia-gpu` by digest
207
- (`87496aa5…`, built 2026-07-16, unchanged as of 2026-11-05). ~11 GB. Job scheduling time (queue + pull) on
208
- 5 Nov: 7–27 min from Paddle's registry, 2.5 min for the same image from `cr.hf.co`.
209
- Inside: CUDA 12.8.1, python3.10 venv at `/home/hpd/venv` first on `PATH`, user `hpd`, FlashInfer.
210
- Measured 2026-07-27 and 2026-11-05:
211
- 1. **No `uv` in Paddle's image**, which `hf jobs uv run` needs. The header uses
212
- `cr.hf.co/davanstrien/hpd-parsing-vllm`: Paddle's image (digest-pinned) plus one layer with `uv`/`uvx`
213
- (`images/hpd-parsing/build.sh`, `crane append` on a CPU Job, ~7 min; public). To rebuild after a Paddle
214
- update, change `BASE_DIGEST` in `build.sh`. The docstring keeps a `hf jobs run … bash -lc 'pip install uv
215
- && uv run …'` command for Paddle's image directly.
216
- 2. `requires-python` includes 3.10 so uv uses the image's own Python instead of downloading one.
217
- 3. **Speculative head path:** the entrypoint's `"model": "PaddlePaddle/HPD-Parsing/P-MTP"` is a local
218
- directory in the `-offline` image only. The recipe downloads the `P-MTP/*` subfolder and passes its
219
- path. Expected log line, every run: `Error retrieving safetensors: Repo id must be in the form …`.
220
- 4. **`--enable-prefix-caching` stays ON** (forked children share the parent's prefix KV; 43.9–52.9% hit
221
- rate). `--attention-config '{"use_prefill_query_quantization":true}'` is fork-only. Both come from
222
- `/home/hpd/entrypoint.sh`. Works on `a100-large` (sm80) as well as `l4x1`.
223
- 5. **Bboxes are 0–1000 normalized**, not pixels (`px = v/1000 * width`), verified by overlay in July.
224
- The parser is the demo Space's bbox-preserving `parse_blocks`; the model repo's `eval/hpd_to_markdown.py`
225
- drops chart/seal blocks and bboxes. Re-parsing July's `hpd_raw` reproduced July's markdown on 34/34 pages.
226
- 6. saturate's readiness probe logs `The model 'readiness-probe' does not exist` (404) once; that is the
227
- "server is alive" signal, not an error.
228
-
229
- **Limits seen in testing: loops, and `max_tokens` does not bound a page.** Each forked child branch has
230
- its own `max_tokens` budget, so a page that fragments into hundreds of regions can emit far more than the
231
- cap (179k completion tokens for one page at `max_tokens` 8000). On 12 Chronicling America pages
232
- (1774–1809), 3 pages looped: 726,706 chars (July) / 544,120 (November) vs 24,907 in LoC's OCR on the
233
- worst. Those 3 ended with `finish_reason=length`, the other 9 with `stop`, and `looped_blocks` > 0 on
234
- exactly the same 3. One UFO page had a 26,675-char loop. `looped_blocks` counts blocks
235
- of ≥2000 bytes whose zlib ratio is ≥4 (≥10 for `table`): ordinary text compresses ~2×, loops 6–330×
236
- (a counting loop "of the 860th of the 861th …" is the 6× case), the most compressible real block was a
237
- 1.5 KB table at 5.3×. Calibrated on 345 blocks from the July outputs: 0 false positives. The text is
238
- kept as the model wrote it; filter rows on `looped_blocks == 0`. Accuracy (94.91 OmniDocBench v1.6) is
239
- below `ovis-ocr2`/`paddleocr-vl-1.6`; the recipe earns its place with the layout column. en/zh only.
240
-
241
- `hpd-parsing-server.py` (PR #95, July) is the hand-rolled driver for the same server; this recipe
242
- replaces it.
243
-
244
- ### `unlimited-ocr2.py` / `unlimited-ocr2-saturate.py` — Baidu SGLang wheel, multi-page windows
245
- v2 has no vLLM support; Baidu ships a custom SGLang wheel in the model repo. Its pins (torch 2.13.0,
246
- transformers 5.12.1, flashinfer 0.6.18 cu13) match **`lmsysorg/sglang:v0.5.20`** exactly → `-cu130` image,
247
- wheel installed `--no-deps` into the image's **`/opt/sglang` venv** (found on PATH past the uv venv). Move
248
- image and wheel together. Gotchas measured 2026-10-27 on 1771 Britannica:
249
- - The card's n-gram guard is a pure-Python logit processor run every decode step → decode is
250
- scheduler-CPU-bound (A100 at ~33% GPU util). Turning it off breaks windows (13/32 failed); window 128
251
- is 1.3x faster but loops more → keep 1024. The processor string is a fixed pickled global (no sglang
252
- or dill needed in the driver).
253
- - 16-page windows reach ~31k tokens of KV each: 24 GB GPUs thrash (retractions), l40s (48 GB) hits KV
254
- pressure; rtx-pro-6000 (96 GB, 23 vCPU) was 1.6x a100-large throughput at ~30% lower $/page.
255
- - ~2% of dense pages (mathematics) loop; the per-page token cap then forces a `<PAGE>` and shifts the next
256
- page's text by one. `-saturate` re-reads looping pages + empty neighbours alone in gundam mode (28/33 fixed).
257
- - Send pages at 1280 px in base mode (the model sees a 1024 view): 1600+ px bodies (~14 MB per window)
258
- stalled SGLang's HTTP front end past saturate's fixed 30 s connect/write timeouts.
259
- - saturate 0.2.0: `RETRY_BUDGET_S` (300 s) < one window, so retries always timed out → raised to 3600 in
260
- the scripts; `Auto` widens only on completions (start it at 32); `flush_every=4`. Pinned `==0.2.0`.
261
- - JP2 decode at a reduced level (`img.reduce`) failed intermittently in Jobs ("broken data stream", not
262
- reproducible on macOS) → fallback to a fuller decode.
263
-
264
- ### `lift-extract.py` — naming + backends
265
- Datalab `lift` (9B, Qwen3.5), schema-constrained image/PDF → JSON; the only recipe ingesting PDFs directly.
266
- **Must not be named `lift.py`** (shadows the installed `lift` package → ImportError). Two in-process backends
267
- via `--method`: `hf` (default image, plain `model.generate`) and `vllm` (needs the `vllm/vllm-openai` image;
268
- reproduces lift's own recipe: `mm_processor_kwargs={min_pixels:3136,max_pixels:861696}`, guided JSON schema,
269
- `temperature=0.0,top_p=0.1,max_tokens=12384`). Pin `--model datalab-to/lift` via the `MODEL_CHECKPOINT` env
270
- (settings read env at import).
271
-
272
- ### `deepseek-ocr-vllm.py` / `deepseek-ocr2-vllm.py`
273
- v1 uses the official offline pattern (`llm.generate()` + `NGramPerReqLogitsProcessor` for repetition).
274
- **Known bug** (hit on vLLM *nightly*, 2026-02-12; unverified on the stable wheels v1 now resolves):
275
- some aspect ratios trip `images_crop dim[2] expected 1024, got 640` (gundam-mode
276
- default vs a validator expecting 1024²) — hit 2/10 on `ufo-ColPali`, aspect-ratio dependent, no upstream
277
- issue filed ([vllm#28160](https://github.com/vllm-project/vllm/issues/28160) is the related request). v2
278
- needs **nightly** vLLM (`DeepseekOCR2ForCausalLM` not in stable) + `addict`/`matplotlib` (its HF custom
279
- code), plus `limit_mm_per_prompt={"image":1}`.
280
-
281
- ### `hunyuan-ocr.py` / `hunyuan-ocr-1.5.py` — upstream replaced the repo root in-place
282
- On 2026-07-06 Tencent pushed HunyuanOCR-1.5 **into the same repo** `tencent/HunyuanOCR` (1.5 at root,
283
- 1.0 archived under `v1.0/`, DFlash draft under `dflash/`, **no 1.0 tag or branch**). vLLM can't load a
284
- repo subfolder, so `hunyuan-ocr.py` pins the last 1.0 commit by `revision` (`f6af82ee…`) — that pin is
285
- the 1.0 *identity*, never loosen it to `main`; 1.5 is its own recipe (`hunyuan-ocr-1.5.py`, tracks root,
286
- has `--revision` as insurance against the next in-place swap). Separate breakage, both scripts: stable
287
- vLLM ≤0.24.0's `hunyuan_vl_image.py` does a string-key `AutoImageProcessor.register(...)` which
288
- transformers 5.13 rejects (`'str' object has no attribute '__module__'` → "architectures failed to be
289
- inspected" at engine init) — hence the `transformers<5.13` cap in both; drop it when the vllm#47872 fix
290
- ships in a stable wheel. 1.5 prompts are task-locked (12 types, Chinese wording, from the official
291
- client's `hunyuan_tasks.py`) and sampling is card-locked (temp 0.0, rep-penalty 1.08) — don't
292
- "improve" either; upstream observed hand-tweaked prompts silently degrade quality.
293
-
294
- ### `glm-ocr.py`
295
- Chatty on blank pages / can emit degenerate repeats — that's **model quality, not a crash**; don't
296
- re-debug it as a recipe bug. (The actual historical crash was the `pyarrow<18` cap — see Conventions.)
297
-
298
- ### `lighton-ocr3.py`
299
- Covers the two Qwen3.5 variants (`LightOnOCR-3-4B` default, `-0.8B`); **not** `LightOnOCR-3-1B`, which keeps
300
- the LightOnOCR-2 Pixtral arch (needs `transformers` ≤5.16 for `PixtralRotaryEmbedding`). Image pinned to
301
- **`vllm/vllm-openai:v0.30.0`** because upstream's `pyproject.toml` says vLLM 0.27.1 makes the models loop and
302
- 0.30.0 is tested — loosen after re-checking outputs on a newer tag. Imports parser, `fit` (2048px) and
303
- `fix_escaped_dollars` from LightOn's own client (`lightonocr`, not on PyPI) via a commit-pinned GitHub
304
- archive URL, so post-processing matches upstream byte for byte. Sampling = model card vLLM example
305
- (temp 0.2, **top_p 0.9**, max_tokens 4096); LightOn's client `models.py` uses top_p 1.0 instead. Grounding mode writes `to_markdown(blocks)`
306
- to the output column and the parsed blocks JSON to `--blocks-column`; the card says prompts other than
307
- `""`/`grounding` are out of distribution, so no custom prompt flag. Very small type after the 2048
308
- resize (≲15 px line height) can give empty or looping output; a higher `--longest-edge` helps some pages.
309
- **Bucket sibling** (`lighton-ocr3-bucket.py`): input/output are `hf://buckets/...` URLs (bucketbag: list → batched
310
- download → `put_files`) or directories. Use URLs for big buckets: a `-v` mount of `biglam/britannica` (~1 TB)
311
- sat in RUNNING with no log output for 21 min (2026-10-22), while the same pages via bucketbag ran fine.
312
- Prefixes get a trailing `/` and go to bucketbag as `prefix=` (it strips a slash from the URL and matches string prefixes, so `vol` would also list `vol2/`). `--max-samples` caps files after listing: bucketbag lists and sorts the whole prefix first, so point smoke tests at a narrow prefix. Directory writes go through a temp file + rename; PDF markers are written in a separate call after their pages. A PDF counts as done once its `.complete.<mode>` marker exists (written with its last page; grounding needs a grounding marker, plain takes either); a re-run without it OCRs only the missing pages. `--overwrite` does not delete anything first: a page that fails keeps its old output, and the run lists those inputs. Known limit: `--overwrite --mode plain` over grounding output leaves the old `.json` + `.complete.grounding`, so a later grounding run skips those pages; use one output prefix per mode. PDF pages render one at a time and go to vLLM in windows of `--batch-size` pages, so a long PDF never sits in memory.
313
-
314
- ### `lighton-ocr2.py`
315
- The original breakage was **not** vLLM — it was a dead `HF_HUB_ENABLE_HF_TRANSFER=1` (the `hf_transfer`
316
- package is gone), which surfaced as "Can't load image processor". Removed. Pixtral ViT + Qwen3, RLVR-trained,
317
- resize 1540px @200 DPI, `--max-model-len` 16384. `paddleocr-vl-1.5.py` uses the **transformers** backend
318
- (single-image) because PaddleOCR-VL only supports vLLM in server mode.
319
 
320
- ---
 
 
 
 
 
 
 
 
 
321
 
322
- ## Internal tooling
323
 
324
- Not user recipes — benchmark/eval infra. **Result tables + validation history → `OCR-BENCHMARK.md`.**
 
 
 
325
 
326
- ### `ocr-bench-run.py` — coordinator
327
- Launches N OCR models on the same dataset, each pushing to a shared repo as a separate config via
328
- `--config/--create-pr`. Eval separately with `ocr-vllm-judge.py` / `ocr-elo-bench.py`. Registry (4 models):
329
- `glm-ocr`, `deepseek-ocr` (auto `--prompt-mode free`), `lighton-ocr-2`, `dots-ocr`; each has a `default_args`.
330
  ```bash
331
- uv run ocr-bench-run.py source-dataset --output my-bench --max-samples 50
332
- uv run ocr-bench-run.py --list-models # registry table
333
- uv run ocr-bench-run.py ... --models glm-ocr dots-ocr --dry-run
334
- uv run ocr-elo-bench.py my-bench --from-prs --mode both # eval from PRs, no merge
 
335
  ```
336
 
337
- ### `ocr-vllm-judge.py` — offline vLLM jury judge
338
- Pairwise OCR-quality comparisons via vLLM offline `LLM()`; jury mode (multiple models vote, majority
339
- aggregation) with **0 parse failures** (structured output via the `StructuredOutputsParams` → `GuidedDecodingParams`
340
- → prompt shim). Prefer over the API judge (`ocr-jury-bench.py`) for batch eval — no rate limits, reproducible.
341
- `--from-prs` loads configs from open PRs without merging; `--save-results REPO` persists comparisons/leaderboard/metadata.
342
- A100 recommended for jury mode; L4 works for a single 7B judge.
343
- ```bash
344
- hf jobs uv run --flavor a100-large -s HF_TOKEN ocr-vllm-judge.py davanstrien/ocr-bench-nls-50 --from-prs \
345
- --judge-model Qwen/Qwen2.5-VL-7B-Instruct --judge-model Qwen/Qwen3-VL-8B-Instruct --max-samples 50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
  ```
347
 
348
- ### `ocr-human-eval.py` — blind human A/B
349
- Gradio app for blind A/B with ELO + optional agreement-vs-judge analysis (split-jury comparisons shown
350
- first; round-robin image variety). Resume-safe (atomic JSON per vote).
351
- ```bash
352
- uv run ocr-human-eval.py davanstrien/ocr-bench-rubenstein --from-prs \
353
- --judge-results davanstrien/ocr-bench-rubenstein-judge --max-samples 5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
354
  ```
355
 
356
- **Validation headline** (full tables in `OCR-BENCHMARK.md`): DeepSeek-OCR is consistently #1 across
357
- datasets and eval methods; middle-pack rankings are dataset-dependent; a jury of small models gives 0
358
- parse failures; **Kimi K2.5 (170B)** is the only judge matching the human's #1 (small judges overrate
359
- LightOnOCR-2's commentary style).
 
 
 
360
 
361
  ---
362
 
363
- ## Deferred / tracked
364
-
365
- - **bucketbag adoption** — evaluate adopting `bucketbag` for the bucket recipes (slim recipes / harden
366
- bucketbag / find other beneficiaries) → [#67](https://github.com/davanstrien/uv-scripts/issues/67).
367
- - **Self-review skill** (spark) — a dev-only skill (sibling to `maintain-recipes`) that reviews a recipe/diff
368
- against the [Conventions](#conventions--invariants) block: context-length, collision guard, vLLM-image +
369
- preflight, env guards, dep sanity, image bounding, optional Jobs smoke. Enforces that list; build after
370
- the current work.
371
- - **Error-signalling** — companion `ocr_error` status column (null cell + truncated exception) instead of
372
- sentinels in the output column, so "read nothing" ≠ "run errored". Touches ~all recipes; deferred.
373
- - **OCR smoke-test dataset** — a tiny curated set (~20–30 images across doc-type/quality/language/layout,
374
- ground truth where possible) for fast CI-style regression checks after dep bumps. Pairs with the skill.
375
- - **Multi-page batch (Unlimited-OCR)** — an SGLang-server-in-job recipe for robust multi-page at scale
376
- (single-image vLLM stays the batch default). Gated on a real corpus-scale need + the `h200`/`fa3` infra
377
- fix; see `serving-unlimited-ocr.md`.
378
- - **ALTO XML export** — from `surya_blocks` (block-level bbox→`HPOS/VPOS/…`, label→`TextBlock`/`Illustration`);
379
- the surya-ocr-bucket test bucket ships CA's own ALTO `.xml` as a diff target.
380
- - **Incremental uploads** — superseded by HF Buckets / `bucketbag` ([#67](https://github.com/davanstrien/uv-scripts/issues/67));
381
- `glm-ocr-v2.py` keeps the older CommitScheduler resume path for very large jobs today (do not port it — on hold).
382
- - **Leaderboard Space** — public ELO/pointwise view fed by the benchmark datasets. Idea only.
383
- - **MonkeyOCRv2 — evaluated, not added** (2026-07-14). `zenosai/MonkeyOCRv2-S-Parsing` (0.6B) needs the
384
- [GitHub repo's](https://github.com/Yuliang-Liu/MonkeyOCRv2) custom multi-stage pipeline (`parsing/parse.py`,
385
- structure detection) — not pip-packaged, pins `vllm==0.11.2`, and the card text says "academic research and
386
- non-commercial use only" while the metadata tag says `apache-2.0` (conflicting license signals). Revisit if
387
- it gets packaged / vLLM-native support or the license is clarified.
388
-
389
- **Watch:** `deepseek-ocr2` / `glm-ocr` stay on nightly vLLM until their arch lands in a stable release.
390
- The nightly index (`https://wheels.vllm.ai/nightly`) occasionally has transient build issues (e.g. only
391
- ARM wheels) — if a nightly-recipe install fails on resolution, wait and retry before debugging the recipe.
 
 
 
 
 
 
392
 
393
  ---
394
 
395
- ## Change log
396
-
397
- - **2026-11-05** — added `hpd-parsing-saturate.py` (experimental) for `PaddlePaddle/HPD-Parsing` (1B,
398
- Apache-2.0): the July server recipe's serve command and block parser, driven by saturate `==0.3.0`
399
- (`Engine(cmd=…)` for the vendor fork), plus a `looped_blocks` flag. Header image
400
- `cr.hf.co/davanstrien/hpd-parsing-vllm` = Paddle's image (pinned by digest) + uv (`images/hpd-parsing/`). Smoke-tested on HF Jobs: `a100-large`, 10 UFO pages, 10/10, 0
401
- error rows, 12 s pump time; `l4x1`, 12 Chronicling America pages in two runs to one repo (5, then 12:
402
- the second run skipped the 5 done rows), 12/12, 0 error rows; 9 clean pages within 1–5% of LoC's OCR
403
- length, 3 looping pages flagged. Header defaults on the public image (`l4x1`, published-path
404
- equivalent: local script, no flags but `--max-samples 5`): 5/5, 0 error rows, 153 s scheduling incl. pull.
405
-
406
- - **2026-11-02** — `xiaomi-ocr-0-saturate.py` moved to `core`. NASA demo: 7/7 in 31 s; checked pages read well, but a table lost one item and some cells lost separators. 16 multilingual historical newspaper pages: 16/16 with no error rows, but repetition loops on 2 small-print German Fraktur pages (lines about 10–13 px after the 2048 px fit), a partial loop on a third, and Chinese characters inserted on 3 pages. `finish_reason` stayed `stop` on all of them.
407
- - **2026-10-30** — added `xiaomi-ocr-0-saturate.py` for `xiaomi-research/Xiaomi-OCR-0` (0.8B, Qwen3.5 arch), on
408
- saturate `==0.3.0`. Do not set `max_limit` by copying older saturate recipes: on `rtx-pro-6000`, `Auto(max_limit=48)`
409
- gave 4.7 pages/s and the default `Auto()` with `prepare_workers` gave 9.7 (1,200 pages, 95% GPU, 0 failures).
410
- On `a10g-small`: 2.9 vs 3.4 pages/s. Output cost is about $0.08 per 1,000 pages on both, excluding boot.
411
-
412
- - **2026-10-27** — added `minicpm-ocr.py` (experimental) for `openbmb/MiniCPM-OCR-1.0`: OpenBMB's SDK
413
- pipeline on a public custom image `cr.hf.co/davanstrien/minicpm-ocr` (first recipe on the HF container
414
- registry; Dockerfile in `images/minicpm-ocr/`).
415
- - **2026-10-27** — added `unlimited-ocr2.py` (minimal) and `unlimited-ocr2-saturate.py` (tuned, experimental)
416
- for `baidu/Unlimited-OCR-2`: whole-document OCR in 16-page windows on Baidu's SGLang build, driven by
417
- saturate (pinned `==0.2.0`). First recipes whose unit of work is a document, not a page; input is a
418
- glob/folder of page files (Buckets), output one row per window with a `status` column. Header flavor
419
- `rtx-pro-6000` from a flavor sweep. Full 1771 Britannica (2,724 pages): 171 windows, 0 errors, 123
420
- pages re-read by the repair pass. New `support` level `experimental` in models.json.
421
-
422
- - **2026-07-29** — added the first two **`-saturate.py` companions**: `lighton-ocr2-saturate.py` and
423
- `ovis-ocr2-saturate.py`. Same model/prompt/sampling/post-processing as their `-server.py` siblings;
424
- the driver half (concurrency, retries, output, resume) is the `saturate` package (pinned `>=0.1.1`,
425
- the allowed *package*-dep pattern — no local imports). Each carries a `SERVING` dict at the top
426
- (serve flags + client sampling + context-math assert) as the machine-readable tuning prior — the
427
- runtime-consumed successor to the dropped `[tool.serving]` header idea. Output shape differs from
428
- `-server.py`: a NEW dataset repo of `{id, markdown, …, error}` parquet rows keyed by input id
429
- (resume = anti-join on id), not input+column push; failed pages become durable error rows
430
- (`--retry-errors` heals), NOT `[OCR ERROR]` sentinels — the first recipes closing the
431
- error-signalling gap noted in Conventions.
432
- - **2026-07-14** — added `ovis-ocr2.py` (`ATH-MaaS/OvisOCR2`, 0.9B Qwen3.5, 96.58 OmniDocBench v1.6,
433
- Apache-2.0; stable vLLM ≥0.22.1, `gdn_prefill_backend="triton"`, card-exact prompt/postprocessing).
434
- Smoke-tested green on the default uv image, a10g-small, resolved vLLM 0.25.1 (5/5 pages, tags filtered,
435
- stamp OK). Evaluated MonkeyOCRv2 alongside it — deferred (see Deferred / tracked).
436
- - **2026-07-08** — HunyuanOCR upstream repo swap: pinned `hunyuan-ocr.py` to the last 1.0 revision +
437
- added `hunyuan-ocr-1.5.py` (12 task types, locked sampling); `transformers<5.13` cap in both for the
438
- stable-vLLM HunyuanVL register breakage (vllm#47872). See the hunyuan gotcha above.
439
- - **2026-07-01** — large full-page scan fixes ([#65](https://github.com/davanstrien/uv-scripts/pull/65)):
440
- surya vLLM-missing preflight; `dots` 8192→32768 + `--max-pixels`; `lighton-ocr2` 8192→16384; `glm` dropped
441
- `pyarrow<18` (→ `datasets` `Json` load crash) + `VLLM_USE_DEEP_GEMM=0` + `--max-pixels`; `pp-ocrv6`
442
- `--output-column` + collision guard. Then the output-column collision-guard + `--overwrite` sweep across
443
- the recipes ([#66](https://github.com/davanstrien/uv-scripts/pull/66)); `nanonets-ocr` 8192→32768.
444
- - **Earlier** — per-script fixes are recorded in git history + the gotchas above; benchmark runs in `OCR-BENCHMARK.md`.
 
1
+ # OCR Scripts - Development Notes
2
 
3
+ ## Active Scripts
 
 
4
 
5
+ ### DeepSeek-OCR v1 (`deepseek-ocr-vllm.py`)
6
+ ✅ **Production Ready**
7
+ - Fully supported by vLLM
8
+ - Fast batch processing
9
+ - Tested and working on HF Jobs
10
 
11
+ ### LightOnOCR-2-1B (`lighton-ocr2.py`)
12
+ ✅ **Production Ready** (Fixed 2026-01-29)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ **Status:** Working with vLLM nightly
15
 
16
+ **What was fixed:**
17
+ - Root cause was NOT vLLM - it was the deprecated `HF_HUB_ENABLE_HF_TRANSFER=1` env var
18
+ - The script was setting this env var but `hf_transfer` package no longer exists
19
+ - This caused download failures that manifested as "Can't load image processor" errors
20
+ - Fix: Removed the `HF_HUB_ENABLE_HF_TRANSFER=1` setting from the script
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
+ **Test results (2026-01-29):**
23
+ - 10/10 samples processed successfully
24
+ - Clean markdown output with proper headers and paragraphs
25
+ - Output dataset: `davanstrien/lighton-ocr2-test-v4`
26
 
27
+ **Example usage:**
28
+ ```bash
29
+ hf jobs uv run --flavor a100-large \
30
+ -s HF_TOKEN \
31
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr2.py \
32
+ davanstrien/ufo-ColPali output-dataset \
33
+ --max-samples 10 --shuffle --seed 42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
+ **Model Info:**
37
+ - Model: `lightonai/LightOnOCR-2-1B`
38
+ - Architecture: Pixtral ViT encoder + Qwen3 LLM
39
+ - Training: RLVR (Reinforcement Learning with Verifiable Rewards)
40
+ - Performance: 83.2% on OlmOCR-Bench, 42.8 pages/sec on H100
41
+
42
+ ### PaddleOCR-VL-1.5 (`paddleocr-vl-1.5.py`)
43
+ ✅ **Production Ready** (Added 2026-01-30)
44
+
45
+ **Status:** Working with transformers
46
 
47
+ **Note:** Uses transformers backend (not vLLM) because PaddleOCR-VL only supports vLLM in server mode, which doesn't fit the single-command UV script pattern. Images are processed one at a time for stability.
48
 
49
+ **Test results (2026-01-30):**
50
+ - 10/10 samples processed successfully
51
+ - Processing time: ~50s per image on L4 GPU
52
+ - Output dataset: `davanstrien/paddleocr-vl15-final-test`
53
 
54
+ **Example usage:**
 
 
 
55
  ```bash
56
+ hf jobs uv run --flavor l4x1 \
57
+ -s HF_TOKEN \
58
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl-1.5.py \
59
+ davanstrien/ufo-ColPali output-dataset \
60
+ --max-samples 10 --shuffle --seed 42
61
  ```
62
 
63
+ **Task modes:**
64
+ - `ocr` (default): General text extraction to markdown
65
+ - `table`: Table extraction to HTML format
66
+ - `formula`: Mathematical formula recognition to LaTeX
67
+ - `chart`: Chart and diagram analysis
68
+ - `spotting`: Text spotting with localization (uses higher resolution)
69
+ - `seal`: Seal and stamp recognition
70
+
71
+ **Model Info:**
72
+ - Model: `PaddlePaddle/PaddleOCR-VL-1.5`
73
+ - Size: 0.9B parameters (ultra-compact)
74
+ - Performance: 94.5% SOTA on OmniDocBench v1.5
75
+ - Backend: Transformers (single image processing)
76
+ - Requires: `transformers>=5.0.0`
77
+
78
+ ## Pending Development
79
+
80
+ ### DeepSeek-OCR-2 (Visual Causal Flow Architecture)
81
+
82
+ **Status:** ⏳ Waiting for vLLM upstream support
83
+
84
+ **Context:**
85
+ DeepSeek-OCR-2 is the next generation OCR model (3B parameters) with Visual Causal Flow architecture offering improved quality. We attempted to create a UV script (`deepseek-ocr2-vllm.py`) but encountered a blocker.
86
+
87
+ **Blocker:**
88
+ vLLM does not yet support `DeepseekOCR2ForCausalLM` architecture in the official release.
89
+
90
+ **PR to Watch:**
91
+ 🔗 https://github.com/vllm-project/vllm/pull/33165
92
+
93
+ This PR adds DeepSeek-OCR-2 support but is currently:
94
+ - ⚠️ **Open** (not merged)
95
+ - Has unresolved review comments
96
+ - Pre-commit checks failing
97
+ - Issues: hardcoded parameters, device mismatch bugs, missing error handling
98
+
99
+ **What's Needed:**
100
+ 1. PR #33165 needs to be reviewed, fixed, and merged
101
+ 2. vLLM needs to release a version including the merge
102
+ 3. Then we can add these dependencies to our script:
103
+ ```python
104
+ # dependencies = [
105
+ # "datasets>=4.0.0",
106
+ # "huggingface-hub",
107
+ # "pillow",
108
+ # "vllm",
109
+ # "tqdm",
110
+ # "toolz",
111
+ # "torch",
112
+ # "addict",
113
+ # "matplotlib",
114
+ # ]
115
+ ```
116
+
117
+ **Implementation Progress:**
118
+ - ✅ Created `deepseek-ocr2-vllm.py` script
119
+ - ✅ Fixed dependency issues (pyarrow, datasets>=4.0.0)
120
+ - ✅ Tested script structure on HF Jobs
121
+ - ❌ Blocked: vLLM doesn't recognize architecture
122
+
123
+ **Partial Implementation:**
124
+ The file `deepseek-ocr2-vllm.py` exists in this repo but is **not functional** until vLLM support lands. Consider it a draft.
125
+
126
+ **Testing Evidence:**
127
+ When we ran on HF Jobs, we got:
128
+ ```
129
+ ValidationError: Model architectures ['DeepseekOCR2ForCausalLM'] are not supported for now.
130
+ Supported architectures: [...'DeepseekOCRForCausalLM'...]
131
  ```
132
 
133
+ **Next Steps (when PR merges):**
134
+ 1. Update `deepseek-ocr2-vllm.py` dependencies to include `addict` and `matplotlib`
135
+ 2. Test on HF Jobs with small dataset (10 samples)
136
+ 3. Verify output quality
137
+ 4. Update README.md with DeepSeek-OCR-2 section
138
+ 5. Document v1 vs v2 differences
139
+
140
+ **Alternative Approaches (if urgent):**
141
+ - Create transformers-based script (slower, no vLLM batching)
142
+ - Use DeepSeek's official repo setup (complex, not UV-script compatible)
143
+
144
+ **Model Information:**
145
+ - Model ID: `deepseek-ai/DeepSeek-OCR-2`
146
+ - Model Card: https://huggingface.co/deepseek-ai/DeepSeek-OCR-2
147
+ - GitHub: https://github.com/deepseek-ai/DeepSeek-OCR-2
148
+ - Parameters: 3B
149
+ - Resolution: (0-6)×768×768 + 1×1024×1024 patches
150
+ - Key improvement: Visual Causal Flow architecture
151
+
152
+ **Resolution Modes (for v2):**
153
+ ```python
154
+ RESOLUTION_MODES = {
155
+ "tiny": {"base_size": 512, "image_size": 512, "crop_mode": False},
156
+ "small": {"base_size": 640, "image_size": 640, "crop_mode": False},
157
+ "base": {"base_size": 1024, "image_size": 768, "crop_mode": False}, # v2 optimized
158
+ "large": {"base_size": 1280, "image_size": 1024, "crop_mode": False},
159
+ "gundam": {"base_size": 1024, "image_size": 768, "crop_mode": True}, # v2 optimized
160
+ }
161
  ```
162
 
163
+ ## Other OCR Scripts
164
+
165
+ ### Nanonets OCR (`nanonets-ocr.py`, `nanonets-ocr2.py`)
166
+ ✅ Both versions working
167
+
168
+ ### PaddleOCR-VL (`paddleocr-vl.py`)
169
+ ✅ Working
170
 
171
  ---
172
 
173
+ ## Future: OCR Smoke Test Dataset
174
+
175
+ **Status:** Idea (noted 2026-02-12)
176
+
177
+ Build a small curated dataset (`uv-scripts/ocr-smoke-test`?) with ~2-5 samples from diverse sources. Purpose: fast CI-style verification that scripts still work after dep updates, without downloading full datasets.
178
+
179
+ **Design goals:**
180
+ - Tiny (~20-30 images total) so download is seconds not minutes
181
+ - Covers the axes that break things: document type, image quality, language, layout complexity
182
+ - Has ground truth text where possible for quality regression checks
183
+ - All permissively licensed (CC0/CC-BY preferred)
184
+
185
+ **Candidate sources:**
186
+
187
+ | Source | What it covers | Why |
188
+ |--------|---------------|-----|
189
+ | `NationalLibraryOfScotland/medical-history-of-british-india` | Historical English, degraded scans | Has hand-corrected `text` column for comparison. CC0. Already tested with GLM-OCR. |
190
+ | `davanstrien/ufo-ColPali` | Mixed modern documents | Already used as our go-to test set. Varied layouts. |
191
+ | Something with **tables** | Structured data extraction | Tests `--task table` modes. Maybe a financial report or census page. |
192
+ | Something with **formulas/LaTeX** | Math notation | Tests `--task formula`. arXiv pages or textbook scans. |
193
+ | Something **multilingual** (CJK, Arabic, etc.) | Non-Latin scripts | GLM-OCR claims zh/ja/ko support. Good to verify. |
194
+ | Something **handwritten** | Handwriting recognition | Edge case that reveals model limits. |
195
+
196
+ **How it would work:**
197
+ ```bash
198
+ # Quick smoke test for any script
199
+ uv run glm-ocr.py uv-scripts/ocr-smoke-test smoke-out --max-samples 5
200
+ # Or a dedicated test runner that checks all scripts against it
201
+ ```
202
+
203
+ **Open questions:**
204
+ - Build as a proper HF dataset, or just a folder of images in the repo?
205
+ - Should we include expected output for regression testing (fragile if models change)?
206
+ - Could we add a `--smoke-test` flag to each script that auto-uses this dataset?
207
+ - Worth adding to HF Jobs scheduled runs for ongoing monitoring?
208
 
209
  ---
210
 
211
+ **Last Updated:** 2026-02-12
212
+ **Watch PRs:**
213
+ - DeepSeek-OCR-2: https://github.com/vllm-project/vllm/pull/33165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
LANGUAGES.md DELETED
@@ -1,40 +0,0 @@
1
- # Language support
2
-
3
- What each model's own card claims about language coverage — compiled from the model cards as of **2026-07-15**. Treat these as **claims, not guarantees**: only one model (Surya) publishes per-language scores, and a "multilingual" tag tells you very little. Machine-readable version (plus params, backend, image pins): [`models.json`](models.json).
4
-
5
- The fastest way to find out whether a model handles *your* language is to run it on a few of your own pages — `--max-samples 10` costs a few cents on a T4/L4:
6
-
7
- ```bash
8
- hf jobs uv run --flavor l4x1 -s HF_TOKEN \
9
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/surya-ocr.py \
10
- your-dataset your-output --max-samples 10
11
- ```
12
-
13
- _Sorted by strength of evidence, then coverage:_
14
-
15
- | Model | Card claim | Evidence |
16
- |-------|-----------|----------|
17
- | [Surya OCR 2](https://huggingface.co/datalab-to/surya-ocr-2) | **91 languages** | The only **per-language benchmark** published ([full table](https://github.com/datalab-to/surya/blob/master/static/docs/multilingual.md)): 38/91 score ≥90%, 76/91 ≥80%. Weakest of the top-15: Arabic 72.7%, Vietnamese 73.2% |
18
- | [dots.ocr](https://huggingface.co/rednote-hilab/dots.ocr) | 100 languages | Explicit **low-resource** claim, backed by an in-house benchmark (1,493 PDFs across 100 languages) — aggregate scores only, not per-language |
19
- | [Tesseract 5](https://github.com/tesseract-ocr/tesseract) | 125 traineddata packs (~100+ languages + script models) | Fully **enumerable** ([tessdata_best](https://github.com/tesseract-ocr/tessdata_best)) — the broadest *named* coverage here, incl. many low-resource languages; script models (Latin, Cyrillic, Devanagari, …) cover languages without a dedicated pack |
20
- | [Qianfan-OCR](https://huggingface.co/baidu/Qianfan-OCR) | 192 languages | Headline claim; no list or per-language numbers |
21
- | [PaddleOCR-VL](https://huggingface.co/PaddlePaddle/PaddleOCR-VL) / [1.5](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.5) / [1.6](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.6) | 109 languages; 1.5 adds Tibetan + Bengali | Names scripts (Cyrillic, Arabic, Devanagari, Thai) and claims handwriting + historical documents; no per-language numbers |
22
- | [PP-OCRv6](https://huggingface.co/collections/PaddlePaddle/pp-ocrv6) | 48 languages | Official card claim |
23
- | [MiniCPM-OCR 1.0](https://huggingface.co/openbmb/MiniCPM-OCR-1.0) | Chinese and English ("primary languages") | Card names two; no per-language numbers. Examples include historical scans |
24
- | [HPD-Parsing](https://huggingface.co/PaddlePaddle/HPD-Parsing) | 2 (en, zh) | Card metadata only. On degraded French scans our smoke runs (July and November 2026) produced stray Chinese characters mid-word, so treat languages other than en/zh as unsupported |
25
- | [Nanonets-OCR2-3B](https://huggingface.co/nanonets/Nanonets-OCR2-3B) | 11 named + "many more" (incl. Arabic + CJK) | Illustrative list, no benchmark — but the only card claiming multilingual **handwriting** |
26
- | [LightOnOCR-2-1B](https://huggingface.co/lightonai/LightOnOCR-2-1B) | 11 (9 European + zh/ja) | Declared, not benchmarked. [v1](https://huggingface.co/lightonai/LightOnOCR-1B-1025) is explicitly European/Latin-script only (9) |
27
- | [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) | 8 (zh en fr es ru de ja ko) | Declared in card metadata only; no per-language evidence in the card body |
28
- | [HunyuanOCR-1.5](https://huggingface.co/tencent/HunyuanOCR) | "Multilingual" | Nothing enumerated, but explicitly targets **low-resource + ancient-script OCR** as a design goal (new in 1.5; the pinned 1.0 revision doesn't claim this) |
29
- | [dots.mocr](https://huggingface.co/rednote-hilab/dots.mocr) · [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) / [-2](https://huggingface.co/deepseek-ai/DeepSeek-OCR-2) · [Unlimited-OCR](https://huggingface.co/baidu/Unlimited-OCR) · [NuExtract3](https://huggingface.co/numind/NuExtract3) | "Multilingual", unspecified | A tag or one-liner only — no count, list, or benchmark |
30
- | [olmOCR-2](https://huggingface.co/allenai/olmOCR-2-7B-1025-FP8) · [Nanonets-OCR-s](https://huggingface.co/nanonets/Nanonets-OCR-s) · [SmolDocling](https://huggingface.co/ds4sd/SmolDocling-256M-preview) · [LFM2.5-VL-Extract](https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-Extract) | English only | Stated on the card |
31
- | [Falcon-OCR](https://huggingface.co/tiiuae/Falcon-OCR) · [OvisOCR2](https://huggingface.co/ATH-MaaS/OvisOCR2) · [Xiaomi-OCR-0](https://huggingface.co/xiaomi-research/Xiaomi-OCR-0) · [LightOnOCR-3](https://huggingface.co/collections/lightonai/lightonocr-3) · [FireRed-OCR](https://huggingface.co/FireRedTeam/FireRed-OCR) · [ABot-OCR](https://huggingface.co/acvlab/ABot-OCR) · [RolmOCR](https://huggingface.co/reducto/RolmOCR) · [NuMarkdown-8B](https://huggingface.co/numind/NuMarkdown-8B-Thinking) · [lift](https://huggingface.co/datalab-to/lift) | Not stated | No language information on the card at all |
32
-
33
- Text-only extraction: [LFM2-1.2B-Extract](https://huggingface.co/LiquidAI/LFM2-1.2B-Extract) (chains after OCR) names 9 languages: English, Arabic, Chinese, French, German, Japanese, Korean, Portuguese, Spanish.
34
-
35
- ## Reading the table for low-resource work
36
-
37
- - **Only Surya lets you check your language before running anything** — its [benchmark table](https://github.com/datalab-to/surya/blob/master/static/docs/multilingual.md) has a row per language.
38
- - **Tesseract's coverage is enumerable** — if your language has a [traineddata pack](https://github.com/tesseract-ocr/tessdata_best), it's supported (quality varies; it's the legacy baseline, not the quality leader).
39
- - **dots.ocr and HunyuanOCR-1.5 are the VLMs that talk about low-resource languages at all**; PaddleOCR-VL-1.5 names Tibetan and Bengali specifically.
40
- - A big claimed number (192, 109) without a list or per-language scores means you're testing it yourself either way — which is cheap (see the command above).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
OCR-BENCHMARK.md DELETED
@@ -1,93 +0,0 @@
1
- # OCR Benchmark — results & history
2
-
3
- Result tables and validation history for the OCR benchmark tooling. **How to *run* the tools**
4
- (`ocr-bench-run.py`, `ocr-vllm-judge.py`, `ocr-human-eval.py`) lives in `CLAUDE.md` → "Internal
5
- tooling"; this file is the accumulated *evidence*.
6
-
7
- ## Model registry (as benchmarked)
8
-
9
- | Slug | Model | Size | GPU | Notes |
10
- |------|-------|------|-----|-------|
11
- | `glm-ocr` | `zai-org/GLM-OCR` | 0.9B | l4x1 | |
12
- | `deepseek-ocr` | `deepseek-ai/DeepSeek-OCR` | 4B | l4x1 | auto `--prompt-mode free` (no grounding tags) |
13
- | `lighton-ocr-2` | `lightonai/LightOnOCR-2-1B` | 1B | a100-large | |
14
- | `dots-ocr` | `rednote-hilab/dots.ocr` | 1.7B | l4x1 | stable vLLM (>=0.9.1) |
15
-
16
- ## Run 1 — NLS Medical History (2026-02-14, pilot)
17
-
18
- `NationalLibraryOfScotland/medical-history-of-british-india`, 10 samples, seed 42. Judge:
19
- `Qwen2.5-VL-72B` via Inference Providers. Historical English, degraded scans.
20
-
21
- - **ELO (pairwise, 5 samples):** DoTS 1540 (67%) · DeepSeek 1539 (57%) · LightOnOCR-2 1486 (50%) · GLM 1436 (29%)
22
- - **Pointwise (5):** DeepSeek 5.0 · GLM 4.6 · LightOnOCR-2 4.4 · DoTS 4.2
23
- - **Key finding:** DeepSeek's `--prompt-mode document` emits grounding tags (`<|ref|>`/`<|det|>`) the
24
- judge penalises heavily; switching to `--prompt-mode free` moved it last→top-2 (now the registry default).
25
- - **Caveat:** 5 samples is far too few for stable rankings.
26
-
27
- ## Run 2 — Rubenstein Manuscript Catalog (2026-02-15, first full run)
28
-
29
- `biglam/rubenstein-manuscript-catalog`, 50 samples, seed 42. Judge: jury of `Qwen2.5-VL-7B` +
30
- `Qwen3-VL-8B` on A100 (`ocr-vllm-judge.py`). ~48K typewritten + handwritten cards (Duke, CC0).
31
-
32
- **ELO (50 samples, 300 comparisons, 0 parse failures):**
33
-
34
- | Rank | Model | ELO | W | L | T | Win% |
35
- |------|-------|-----|---|---|---|------|
36
- | 1 | LightOnOCR-2-1B | 1595 | 100 | 50 | 0 | 67% |
37
- | 2 | DeepSeek-OCR | 1497 | 73 | 77 | 0 | 49% |
38
- | 3 | GLM-OCR | 1471 | 57 | 93 | 0 | 38% |
39
- | 4 | dots.ocr | 1437 | 70 | 80 | 0 | 47% |
40
-
41
- Job times (50 samples): dots 5.3 min (L4) · deepseek 5.6 (L4) · glm 5.7 (L4) · lighton 6.4 (A100).
42
-
43
- **Findings:** LightOnOCR-2 dominates on manuscript cards (very different from the NLS pilot) — rankings
44
- are **dataset-dependent**; a jury of small models works well (0 parse failures via vLLM structured output);
45
- 50 samples gives meaningful separation.
46
-
47
- ## Run 3 — UFO-ColPali (2026-02-15, cross-dataset validation)
48
-
49
- `davanstrien/ufo-ColPali`, 50 samples, seed 42. Judge: `Qwen3-VL-30B-A3B` on A100 (updated prompt).
50
- Mixed modern documents.
51
-
52
- **ELO (50 samples, 294 comparisons):**
53
-
54
- | Rank | Model | ELO | W | L | T | Win% |
55
- |------|-------|-----|---|---|---|------|
56
- | 1 | DeepSeek-OCR | 1827 | 130 | 17 | 0 | 88% |
57
- | 2 | dots.ocr | 1510 | 64 | 83 | 0 | 44% |
58
- | 3 | LightOnOCR-2-1B | 1368 | 77 | 70 | 0 | 52% |
59
- | 4 | GLM-OCR | 1294 | 23 | 124 | 0 | 16% |
60
-
61
- **Human validation (30 comparisons):** DeepSeek #1 (matches judge), LightOnOCR-2 #3 (matches). Middle
62
- pack (GLM, dots) shuffled between human and judge.
63
-
64
- ## Cross-dataset comparison (human-validated)
65
-
66
- | Model | Rubenstein Human | Rubenstein Kimi | UFO Human | UFO 30B |
67
- |-------|:---:|:---:|:---:|:---:|
68
- | DeepSeek-OCR | **#1** | **#1** | **#1** | **#1** |
69
- | GLM-OCR | #2 | #3 | #2 | #4 |
70
- | LightOnOCR-2 | #4 | #2 | #3 | #3 |
71
- | dots.ocr | #3 | #4 | #4 | #2 |
72
-
73
- **Conclusion:** DeepSeek-OCR is consistently #1 across datasets and eval methods; middle-pack rankings
74
- are dataset-dependent. (NLS pilot omitted — 5 samples / 72B API judge, not comparable with the newer
75
- methodology.)
76
-
77
- ## Judge validation — `ocr-vllm-judge.py` (2026-02-15)
78
-
79
- - **Test 1** (single judge, 1 sample, L4): `Qwen2.5-VL-7B`, 6/6 comparisons, 0 parse failures, ~3 min.
80
- - **Test 2** (jury of 2, 3 samples, A100): `Qwen2.5-VL-7B` + `Qwen3-VL-8B`, 15/15, 0 failures; GPU cleanup
81
- between models OK; majority-vote aggregation working (`[2/2]` unanimous, `[1/2]` split).
82
- - **Test 3** (full, 50 samples, A100, Rubenstein): 300/300 comparisons, 0 parse failures; clear ELO
83
- separation. First saved dataset: `davanstrien/ocr-bench-rubenstein-judge`.
84
-
85
- Structured output via a compatibility shim: `StructuredOutputsParams` (vLLM ≥0.12) → `GuidedDecodingParams`
86
- (older) → prompt-based fallback. Position bias mitigated by A/B randomisation. A100 recommended for jury mode.
87
-
88
- ## Human eval — `ocr-human-eval.py` first validation (Rubenstein, 30 annotations)
89
-
90
- Tested 3 judge configs against 30 human annotations. **Kimi K2.5 (170B) via Novita + the updated prompt**
91
- is the only judge to match the human's #1 (DeepSeek-OCR); it's now the default in `ocr-jury-bench.py`.
92
- Small models (7B/8B/30B) overrate LightOnOCR-2 (bias toward its commentary style); the updated prompt
93
- (faithfulness > completeness > accuracy) helps, but model size is the bigger factor.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README.md CHANGED
@@ -1,307 +1,647 @@
1
  ---
2
  viewer: false
3
- tags: [uv-script, ocr, extraction, vision-language-model, document-processing, hf-jobs]
4
  ---
5
 
6
  # OCR UV Scripts
7
 
8
- <a href="https://huggingface.co/uv-scripts"><picture><source media="(prefers-color-scheme: dark)" srcset="https://huggingface.co/datasets/huggingface/badges/resolve/main/follow-us-on-hf-md-dark.svg"><img src="https://huggingface.co/datasets/huggingface/badges/resolve/main/follow-us-on-hf-md.svg" alt="Follow uv-scripts on Hugging Face"></picture></a>
9
 
10
- > Part of [uv-scripts](https://huggingface.co/uv-scripts): self-contained UV scripts you run on Hugging Face Jobs in one command.
11
 
12
- One script per OCR model. Each script runs the model on a GPU with [Hugging Face Jobs](https://huggingface.co/docs/hub/jobs) and writes the text as markdown: as a new column in a Hub dataset, as `.md` files in a Bucket, or as resumable parquet parts (the `-saturate` recipes). A few scripts return JSON from a schema, detect layout regions, or compare the output of two models.
13
 
14
- ## Quick Start
15
 
16
- First, [install the `hf` CLI and sign in](https://huggingface.co/docs/hub/jobs-quickstart). Jobs needs pay-as-you-go credit.
 
 
 
 
 
 
 
17
 
18
- Run [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) on seven scanned pages from [NASA's *Food for Space Flight* booklet](https://huggingface.co/datasets/uv-scripts/ocr-demo). Replace `your-username` with your Hugging Face username:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  ```bash
21
- hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \
22
- uv-scripts/ocr-demo your-username/ocr-demo-results
23
  ```
24
 
25
- The Job adds a `markdown` column to all seven rows and saves them in `your-username/ocr-demo-results`. Dependency installation and model loading can take a few minutes before OCR starts. The [dataset card](https://huggingface.co/datasets/uv-scripts/ocr-demo) gives the source and licence.
26
 
27
- > **Note:** the command needs no flags because the script's [`[tool.hf-jobs]` header](https://huggingface.co/docs/hub/jobs-configuration#define-the-launch-config-in-the-script) sets the GPU, the Docker image and the `HF_TOKEN` secret. The `hf` CLI reads the header from version 1.32. `hf jobs uv run --dry-run <script>` shows the resolved settings. Flags override the header, for example `--timeout 1h` for a larger dataset or `--flavor` for other hardware. **Older CLIs ignore the header without a warning**, and the Job then fails on a CPU without your token. Check with `hf version` and upgrade. If you cannot upgrade, copy the header values from the top of the script (or from `jobs` in [`models.json`](models.json)) as flags. For `glm-ocr.py` that is `--flavor a10g-small --secrets HF_TOKEN --image vllm/vllm-openai:v0.30.0 --python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages`.
28
 
29
- ### Try the same pages as a PDF
 
 
 
 
30
 
31
- The [OCR demo Bucket](https://huggingface.co/buckets/uv-scripts/ocr-demo) holds the original PDF, a seven-page extract that matches the dataset, and the page images. Mount the `demo/` prefix to process only the extract, and create your own Bucket for the results. The header sets the GPU and image, but the `-v` mounts are always flags:
 
 
 
32
 
33
- ```bash
34
- hf buckets create your-username/ocr-output --private
35
- hf jobs uv run --timeout 15m \
36
- -v hf://buckets/uv-scripts/ocr-demo/demo:/input:ro \
37
- -v hf://buckets/your-username/ocr-output/pdf:/output:rw \
38
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr-bucket.py \
39
- /input /output
40
  ```
41
 
42
- This writes `food-for-space-flight/page_001.md` through `page_007.md` under the `pdf/` prefix of your output Bucket.
 
 
 
 
43
 
44
- ## Use your own documents
 
 
 
 
 
 
 
 
45
 
46
- **Images in a Hub dataset:** in the Quick Start command, replace the input dataset ID and choose a new output dataset ID. Start with `--max-samples 10`. This limits OCR, but loading the input dataset can still download more rows. The defaults expect a `train` split and an `image` column. Use `--split` and `--image-column` if yours differ. If the input already has a `markdown` column, choose a different `--output-column`, for example `glm_markdown`. Add `--private` for a private output dataset.
47
 
48
- **Scans or PDFs on your machine:** put a few images or a short PDF in `./my-scans` for the first run. The recipe processes every supported file in the folder and its subfolders, and every page of each PDF. Create the output folder before you start the Job:
 
 
 
 
 
 
 
49
 
50
  ```bash
51
- mkdir -p ./ocr-output
52
- hf jobs uv run --timeout 15m \
53
- -v ./my-scans:/input -v ./ocr-output:/output:rw \
54
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr-bucket.py \
55
- /input /output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  ```
57
 
58
- The CLI uploads the local folders to a private Bucket and mounts them in the Job. `:rw` lets the Job write output. The script saves one `.md` file per image, or per PDF page. See [mounting local data](https://huggingface.co/docs/huggingface_hub/en/guides/jobs#mount-local-data).
59
 
60
- ## Get and check your results
61
 
62
- The CLI prints a link to the Job page, which shows status and logs. From the terminal:
 
 
 
 
 
 
 
63
 
64
- ```bash
65
- hf jobs inspect JOB_ID
66
- hf jobs logs JOB_ID
67
- ```
68
 
69
- When the Job completes:
 
 
 
70
 
71
- - **Dataset output:** open `https://huggingface.co/datasets/your-username/ocr-demo-results` and compare the images with their `markdown` results.
72
- - **Bucket output:** browse the output Bucket, or download the files with `hf buckets sync hf://buckets/your-username/ocr-output/pdf ./ocr-output`.
73
- - **Local-folder output:** run the `hf buckets sync` command that the CLI printed at launch. The results are not synced back automatically. Images give files such as `page.md`. A PDF gives files such as `report/page_001.md`.
74
 
75
- A completed Job does not mean every page worked. Look for empty results and `[OCR ERROR]` markers, and compare a few outputs with their pages before you scale up. Check tables and reading order in particular. Each dataset run also writes a dataset card with the model settings and a command to reproduce the run.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
- ## Pick a model
78
 
79
- These are the maintained recipes. Each one has a tested `[tool.hf-jobs]` header, so the Quick Start command works with only the script name changed. The exception is `lift-extract.py`, which also needs `--schema`. The table is sorted by model size, smallest first. Scores are the model authors' own numbers. [OmniDocBench](https://github.com/opendatalab/OmniDocBench) scores document parsing of text, tables and formulas across varied PDF pages. [olmOCR-Bench](https://huggingface.co/datasets/allenai/olmOCR-bench) runs pass/fail unit tests on hard PDF pages.
80
 
81
- | Script | Model | Size | Good at | Licence | GPU |
82
- |--------|-------|------|---------|---------|-----|
83
- | [`tesseract-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/tesseract-ocr.py) | [Tesseract 5](https://github.com/tesseract-ocr/tesseract) | classical | Baseline plain text, no GPU, 100+ language packs (`--lang`) | Apache-2.0 | `cpu-upgrade` |
84
- | [`pp-ocrv6.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/pp-ocrv6.py) | [PP-OCRv6](https://huggingface.co/collections/PaddlePaddle/pp-ocrv6) | 1.5M–34.5M | Small detection + recognition pipeline, plain text, 48 languages | Apache-2.0 | `t4-small` |
85
- | [`surya-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/surya-ocr.py) | [Surya OCR 2](https://huggingface.co/datalab-to/surya-ocr-2) | 0.65B | Per-block HTML with boxes and reading order; layout and table tasks; PDFs | modified OpenRAIL-M | `a10g-small` |
86
- | [`lighton-ocr3.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/lighton-ocr3.py) | [LightOnOCR-3](https://huggingface.co/collections/lightonai/lightonocr-3) | 0.8B / 4B | 86.3 olmOCR-Bench (4B), 85.5 (0.8B); `--mode grounding` adds labelled layout boxes, image descriptions and chart tables | Apache-2.0 | `a10g-small` |
87
- | [`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 | 94.62 OmniDocBench v1.5 | MIT | `a10g-small` |
88
- | [`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 | 96.33 OmniDocBench v1.6; six task modes | Apache-2.0 | `a10g-small` |
89
- | [`ovis-ocr2.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/ovis-ocr2.py) | [OvisOCR2](https://huggingface.co/ATH-MaaS/OvisOCR2) | 0.9B | 96.58 OmniDocBench v1.6; LaTeX and HTML tables | Apache-2.0 | `a10g-small` |
90
- | [`xiaomi-ocr-0-saturate.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/xiaomi-ocr-0-saturate.py) | [Xiaomi-OCR-0](https://huggingface.co/xiaomi-research/Xiaomi-OCR-0) | 0.8B | Whole-page Markdown with LaTeX and HTML tables on vLLM or SGLang; the card's benchmark scores use a two-stage pipeline this recipe does not run; it can loop or insert Chinese characters on small-print historical newspapers | Apache-2.0 | `a10g-small` |
91
- | [`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 | 83.2 olmOCR-Bench | Apache-2.0 | `a10g-small` |
92
- | [`hunyuan-ocr-1.5.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/hunyuan-ocr-1.5.py) | [HunyuanOCR-1.5](https://huggingface.co/tencent/HunyuanOCR) | 1B | 12 task types, including spotting, charts and translation | [Hunyuan Community](https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE) (excludes EU, UK, South Korea) | `a10g-small` |
93
- | [`minicpm-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/minicpm-ocr.py) | [MiniCPM-OCR 1.0](https://huggingface.co/openbmb/MiniCPM-OCR-1.0) | 1.3B | OpenBMB's full pipeline: layout regions, per-region prompts, Markdown with HTML tables; Hub dataset or Bucket in/out; runs on a public [`cr.hf.co`](https://huggingface.co/containers/davanstrien/minicpm-ocr) image (experimental) | Apache-2.0 | `a10g-large` |
94
- | [`dots-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/dots-ocr.py) | [dots.ocr](https://huggingface.co/rednote-hilab/dots.ocr) | 1.7B | 100+ languages; layout modes | MIT | `a10g-small` |
95
- | [`dots-mocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/dots-mocr.py) | [dots.mocr](https://huggingface.co/rednote-hilab/dots.mocr) | 3B | Eight prompt modes, including SVG from charts | MIT | `a10g-small` |
96
- | [`deepseek-ocr2-vllm.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/deepseek-ocr2-vllm.py) | [DeepSeek-OCR-2](https://huggingface.co/deepseek-ai/DeepSeek-OCR-2) | 3B | Newer DeepSeek-OCR | Apache-2.0 | `a10g-small` |
97
- | [`unlimited-ocr2.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/unlimited-ocr2.py) | [Unlimited-OCR-2](https://huggingface.co/baidu/Unlimited-OCR-2) | 3.3B | Whole documents: 16 pages per request, paragraphs continue across page breaks; reads page folders or Buckets; resumable | MIT | `rtx-pro-6000` |
98
- | [`unlimited-ocr-vllm.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/unlimited-ocr-vllm.py) | [Unlimited-OCR](https://huggingface.co/baidu/Unlimited-OCR) | 3.3B | Markdown with layout boxes (`--strip-grounding` for clean text) | MIT | `a10g-small` |
99
- | [`deepseek-ocr-vllm.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/deepseek-ocr-vllm.py) | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | Five prompt modes, including figure description | MIT | `a10g-small` |
100
- | [`nuextract3.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/nuextract3.py) | [NuExtract3](https://huggingface.co/numind/NuExtract3) | 4B | Markdown, or JSON from a template ([below](#structured-extraction-and-layout)) | Apache-2.0 | `a10g-small` |
101
- | [`qianfan-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/qianfan-ocr.py) | [Qianfan-OCR](https://huggingface.co/baidu/Qianfan-OCR) | 4.7B | 93.12 OmniDocBench v1.5; optional reasoning (`--think`); key-information extraction | Apache-2.0 | `a10g-small` |
102
- | [`olmocr2-vllm.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/olmocr2-vllm.py) | [olmOCR-2-7B](https://huggingface.co/allenai/olmOCR-2-7B-1025-FP8) | 7B (FP8) | 82.4 olmOCR-Bench | Apache-2.0 | `a10g-small` |
103
- | [`lift-extract.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/lift-extract.py) | [lift](https://huggingface.co/datalab-to/lift) | 9B | JSON from a schema, from images or multi-page PDFs | modified OpenRAIL-M | `a100-large` |
104
 
105
- Start with a model under 2B. Use a larger model only if the output of a small one is not good enough. Check the licence before you use a model: Surya and lift use a modified OpenRAIL-M licence (free for research, personal use and startups under $5M; no competitive use against Datalab's API), and the Hunyuan licence excludes the EU, the UK and South Korea.
106
 
107
- **Variants and tools:** `glm-ocr-bucket.py`, `surya-ocr-bucket.py` and `lighton-ocr3-bucket.py` read images and PDFs from a Bucket and write one `.md` per page. `lighton-ocr3-bucket.py` also takes `hf://buckets/...` URLs for input and output directly, so it reads large buckets in batches through the Hub API without mounting them. It reads `.jp2`, skips pages that already have output (so a re-run resumes), and in `--mode grounding` writes a `.json` sidecar with the layout blocks. `surya-ocr-bucket.py` also writes a `.json` sidecar with the layout blocks, resumes from existing JSON, and can mount or copy its input (`--io-mode mount|copy`); the dataset version, `surya-ocr.py`, keeps the blocks in a `surya_blocks` column. `lighton-ocr3-saturate.py`, `lighton-ocr2-saturate.py`, `ovis-ocr2-saturate.py` and `xiaomi-ocr-0-saturate.py` are for large runs, and `ocr-vllm-judge.py` compares outputs ([Scaling up](#scaling-up)). `pp-doclayout.py` and `lfm2-extract.py` are described in [Structured extraction and layout](#structured-extraction-and-layout).
 
 
108
 
109
- Which model is best depends on your documents. The public olmOCR-Bench leaderboard is one command away:
110
 
111
  ```bash
112
- hf datasets leaderboard allenai/olmOCR-bench
113
- ```
 
 
 
 
114
 
115
- To rank models on your own collection, [ocr-bench](https://github.com/davanstrien/ocr-bench) builds a per-collection leaderboard (pairwise VLM judge, optional human checks) with these scripts. [LANGUAGES.md](LANGUAGES.md) lists the language coverage that each model card claims. [`models.json`](models.json) is the machine-readable catalogue: model, size, backend, licence, support level, tested launch config and languages for every script.
116
-
117
- ### Less supported and unsupported
118
-
119
- These scripts stay in the repo but have no header, so copy the complete launch command from each script's docstring, including any `--image`, `--python` and `-e` flags. If the docstring gives no hardware, `--flavor a10g-small --secrets HF_TOKEN` is a reasonable start. Status was checked on HF Jobs on 2026-09-23. The `support_note` field in [`models.json`](models.json) has details.
120
-
121
- | Script | Status | Use instead |
122
- |--------|--------|-------------|
123
- | `lighton-ocr.py`, `nanonets-ocr.py`, `paddleocr-vl.py` | works, older model | `lighton-ocr2.py`, `nanonets-ocr2.py`, `paddleocr-vl-1.6.py` |
124
- | `lighton-ocr2-server.py`, `ovis-ocr2-server.py` | works | the matching `-saturate.py` recipe |
125
- | `glm-ocr-v2.py` | works | `glm-ocr.py`, unless you need its resume support |
126
- | `lfm2-vl-extract.py` | works | `nuextract3.py` or `lift-extract.py` |
127
- | `nanonets-ocr2.py` | works on its pinned `vllm/vllm-openai:v0.10.2` image | |
128
- | `falcon-ocr.py`, `falcon-ocr-bucket.py` | works (Falcon-OCR v1; a v1.5 update is in progress) | |
129
- | `abot-ocr.py`, `firered-ocr.py`, `numarkdown-ocr.py` | works, little used | |
130
- | `deepseek-ocr.py` | broken: every row is `None` | `deepseek-ocr-vllm.py` |
131
- | `hunyuan-ocr.py` | broken on current vLLM | `hunyuan-ocr-1.5.py` |
132
- | `paddleocr-vl-1.5.py` | broken: every row is an `[OCR ERROR]` | `paddleocr-vl-1.6.py` |
133
- | `rolm-ocr.py` | broken: no room for the KV cache on a 24 GB GPU | `olmocr2-vllm.py` |
134
- | `jina-ocr-v1.py` | broken on vLLM 0.30 (CC-BY-NC-4.0 model) | |
135
- | `smoldocling-ocr.py` | broken: rows are raw DocTags, not markdown | |
136
-
137
- ## Common options
138
-
139
- Every dataset recipe takes `INPUT_DATASET OUTPUT_DATASET` as positional arguments, so you can usually switch models by changing the script URL. Defaults such as batch size and context length follow each model card. Run `--help`, or read the script source on the Hub, for the full list. Local `uv run <script-url> --help` installs the dependencies first.
140
-
141
- | Option | What it does | Notes |
142
- |--------|--------------|-------|
143
- | `--max-samples N` | Process only the first N rows | All recipes. The `-saturate.py` recipes also accept `--limit`. The three `-bucket.py` recipes count input files, not PDF pages |
144
- | `--shuffle`, `--seed` | Shuffle before `--max-samples` for a representative sample (seed default 42) | Not the `-saturate.py` recipes |
145
- | `--split` | Input split (default `train`) | |
146
- | `--image-column` | Input image column (default `image`) | |
147
- | `--output-column` | Output column (default `markdown`; `extraction` for lift and LFM2 extract) | Not the `-saturate.py` recipes or `pp-doclayout.py` (fixed `layout` column) |
148
- | `--overwrite` | Replace the output column if the input already has it. Without it the script stops | Not the `-saturate.py` recipes |
149
- | `--private` | Make the output dataset private | Not the `-saturate.py` recipes |
150
- | `--batch-size` | Images per batch (default 8 or 16 for the OCR recipes) | Not `tesseract-ocr.py`, `pp-ocrv6.py` or the `-saturate.py` recipes |
151
- | `--max-model-len`, `--max-tokens`, `--gpu-memory-utilization` | vLLM engine limits | Most vLLM recipes |
152
- | `--config NAME`, `--create-pr` | Push the output as a named config, as a pull request | Most dataset recipes. Used to compare models in one repo ([Scaling up](#scaling-up)). In `-saturate.py`, `--config` selects the input config |
153
- | `--verbose` | Log resolved package versions | Most recipes |
154
-
155
- To compare models on the same pages, run them into one dataset with a separate output column each:
156
 
157
- ```bash
158
- hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \
159
- my-dataset my-dataset --max-samples 100 --output-column glm_markdown
160
- hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr2.py \
161
- my-dataset my-dataset --max-samples 100 --output-column lighton_markdown
 
162
  ```
163
 
164
- Most dataset recipes also record the model and settings in an `inference_info` column. The `-saturate.py` recipes write a `model` column instead and keep run metadata under `data/completions/`.
165
-
166
- ### Model-specific flags
167
-
168
- | Script | Flags |
169
- |--------|-------|
170
- | `tesseract-ocr.py` | `--lang` (for example `eng+fra`), `--psm`, `--oem` |
171
- | `pp-ocrv6.py` | `--model-tier tiny\|small\|medium` |
172
- | `surya-ocr.py` | `--task ocr\|layout\|table`, `--table-mode full\|simple`, `--pdf-column`, `--page-range` |
173
- | `glm-ocr.py` | `--task ocr\|formula\|table` |
174
- | `paddleocr-vl-1.6.py` | `--task-mode ocr\|table\|formula\|chart\|spotting\|seal` |
175
- | `ovis-ocr2.py` | `--keep-image-tags`, `--min-pixels`, `--max-pixels` |
176
- | `lighton-ocr3.py` | `--model lightonai/LightOnOCR-3-4B\|lightonai/LightOnOCR-3-0.8B`, `--mode plain\|grounding`, `--blocks-column`, `--longest-edge` |
177
- | `hunyuan-ocr-1.5.py` | `--task-type` (12 types, default `doc_parse`), `--custom-prompt` |
178
- | `dots-ocr.py` | `--prompt-mode ocr\|layout-all\|layout-only` |
179
- | `dots-mocr.py` | `--prompt-mode` (8 modes). For SVG: `--model rednote-hilab/dots.mocr-svg --prompt-mode svg` |
180
- | `deepseek-ocr-vllm.py` | `--prompt-mode document\|image\|free\|figure\|describe` |
181
- | `deepseek-ocr2-vllm.py` | `--prompt-mode document\|free` |
182
- | `unlimited-ocr-vllm.py` | `--strip-grounding`, `--grounding-column` |
183
- | `qianfan-ocr.py` | `--prompt-mode ocr\|table\|formula\|chart\|scene\|kie`, `--think`. `kie` needs `--custom-prompt` |
184
-
185
- For example, key-information extraction with Qianfan-OCR:
186
 
187
- ```bash
188
- hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/qianfan-ocr.py \
189
- invoices extracted-fields \
190
- --prompt-mode kie --custom-prompt "Extract: name, date, total. Output as JSON."
191
- ```
192
 
193
- ## Structured extraction and layout
 
 
 
 
 
 
194
 
195
- These recipes return structured data instead of page text.
196
 
197
- **[NuExtract3](https://huggingface.co/numind/NuExtract3)** (`nuextract3.py`, 4B, Apache-2.0) does markdown OCR by default. Give it a `--template` or a JSON Schema (`--schema`) and it returns JSON in that shape. Both flags accept inline JSON, a URL or a file path, so you can host a schema once and reuse it. Template field names act as instructions to the model, so name them clearly and check the output on a few examples. `--enable-thinking` helps with hard layouts; it is slower and stores the reasoning in a `<output-column>_reasoning` column.
 
 
 
 
198
 
199
  ```bash
200
- hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nuextract3.py \
201
- receipts extracted \
202
- --template '{"store": "verbatim-string", "date": "date", "total": "number"}'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
  ```
204
 
205
- **[lift](https://huggingface.co/datalab-to/lift)** (`lift-extract.py`, 9B) returns JSON that matches a JSON Schema, which you must pass with `--schema` (inline JSON, a URL or a file path). It also reads multi-page PDFs (`--pdf-column`, `--page-range`) and extracts one result per document. The default Transformers backend (`--method hf`) is the tested path. Its weights use a modified OpenRAIL-M licence, so check the terms.
206
 
207
- **[LFM2-1.2B-Extract](https://huggingface.co/LiquidAI/LFM2-1.2B-Extract)** (`lfm2-extract.py`) works on a **text** column, so you can run it after an OCR recipe: OCR turns a page into `markdown`, then this recipe turns the markdown into fields. `--format` selects JSON, XML or YAML.
208
 
209
- ```bash
210
- hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lfm2-extract.py \
211
- your-username/ocr-demo-results your-username/ocr-demo-fields \
212
- --text-column markdown --schema '{"title": "the document title", "date": "any date shown"}'
213
- ```
 
 
 
214
 
215
- **[PP-DocLayout](https://huggingface.co/PaddlePaddle/PP-DocLayout-L)** (`pp-doclayout.py`, 123M) finds layout regions but does not read text. It writes a `layout` column with a box, a class (text, title, table, figure, formula, header, footer and more) and a score for each region. Use it to filter pages, crop regions for OCR, or prepare training data. `--model-name` selects the L, M, S or plus-L model. The input and output can each be a dataset or an `hf://buckets/...` path. Bucket output is written in resumable parquet shards.
216
 
217
  ```bash
218
- hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/pp-doclayout.py \
219
- your-dataset your-layout-output --max-samples 10
 
 
 
 
 
 
 
 
 
 
 
 
220
  ```
221
 
222
- **[HPD-Parsing](https://huggingface.co/PaddlePaddle/HPD-Parsing)** (`hpd-parsing-saturate.py`, 1B, Apache-2.0, experimental) reads text and layout in one pass. Next to the `markdown` it writes an `hpd_blocks` column with a type, a box and the text for each block, in reading order. The boxes are on a 0–1000 scale, not pixels. The model needs Paddle's own vLLM build; the script header picks an image with it ([`images/hpd-parsing/`](images/hpd-parsing/)).
223
 
224
- ```bash
225
- hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/hpd-parsing-saturate.py \
226
- your-dataset your-output --max-samples 5
227
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
 
229
- The image is about 11 GB, so a cold start takes several minutes. On dense pages with hundreds of blocks the model can repeat itself inside many blocks at once. The `looped_blocks` column counts those blocks; keep rows where it is 0. The model card lists English and Chinese only.
230
 
231
- ## Scaling up
232
 
233
- **Large datasets:** `lighton-ocr3-saturate.py`, `lighton-ocr2-saturate.py`, `ovis-ocr2-saturate.py` and `xiaomi-ocr-0-saturate.py` start a vLLM server in the Job (the Xiaomi recipe can use SGLang instead) and send pages to it with adaptive concurrency. They stream results to the output repo as parquet parts. If a run stops, run the same command again and it skips the rows that are done. A failed page is stored as an error row, and `--retry-errors` tries those rows again. The output layout is different from the other recipes; the script header explains how to read it. [SERVING.md](SERVING.md) compares server mode with offline batches (measured throughput and output parity). For LightOnOCR-3-0.8B, `lighton-ocr3-saturate.py` measured 2.2 pages/s on `a10g-small` and 10.0 pages/s on `rtx-pro-6000` (about $0.08 per 1,000 pages), against 0.90 and 1.27 pages/s for `lighton-ocr3.py` on `a10g-small` and `a100-large`.
 
 
 
 
 
 
 
234
 
235
- **Whole books and long documents:** `unlimited-ocr2.py` runs [Unlimited-OCR-2](https://huggingface.co/baidu/Unlimited-OCR-2) on Baidu's own SGLang build. It groups page images into documents and sends 16 consecutive pages per request, so a paragraph that runs over a page break comes back joined. Point it at a folder of pages, for example a Bucket:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
 
237
  ```bash
238
- hf jobs uv run --detach \
239
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/unlimited-ocr2.py \
240
- "hf://buckets/biglam/britannica/source/pages/1771EncyclopediaBritannicaNLS/*.jp2" \
241
- your-username/britannica-1771
 
242
  ```
243
 
244
- The header picks `rtx-pro-6000` (the fastest per dollar in our tests; 24 GB GPUs are too small for 16-page requests). Results are one row per 16-page window. About 2% of pages in 18th-century print (mostly mathematics) send the model into a loop; `unlimited-ocr2-saturate.py`, an experimental tuned version, reads those pages again one at a time and adds PDF input and Baidu's Markdown post-processing. `unlimited-ocr2-live.py`, also experimental, is the minimal script plus a live view you can open while the Job runs (add `--live-port 7860` and `--expose-public 7860`): the page being read with its text streaming in, finished pages, pages per minute and GPU load.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
 
246
  ```bash
247
- hf jobs uv run --detach --timeout 4h \
248
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3-saturate.py \
249
- your-dataset your-output
 
 
 
 
 
250
  ```
251
 
252
- **A live endpoint for an app or agent:** [Jobs serving](https://huggingface.co/docs/hub/jobs-serving) exposes a model server that stays up until you cancel the Job or it reaches its timeout. The [Unlimited-OCR walkthrough](serving-unlimited-ocr.md) covers setup, requests, and parsing several pages in one request.
253
 
254
- **Compare models:** run several recipes into one repo with `--config <name> --create-pr`, then judge the outputs pairwise with `ocr-vllm-judge.py` ([ocr-bench](https://github.com/davanstrien/ocr-bench) automates this):
255
 
256
  ```bash
257
- hf jobs uv run --timeout 1h \
258
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/ocr-vllm-judge.py \
259
- your-username/my-bench --from-prs --judge-model Qwen/Qwen3-VL-8B-Instruct --max-samples 50
 
 
260
  ```
261
 
262
- **Python API:** `run_uv_job` does not read the `[tool.hf-jobs]` header, so pass the header values yourself:
263
 
264
- ```python
265
- from huggingface_hub import get_token, run_uv_job
266
 
267
- job = run_uv_job(
268
- "https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py",
269
- script_args=["input-dataset", "output-dataset", "--max-samples", "10"],
270
- flavor="a10g-small",
271
- image="vllm/vllm-openai:v0.30.0",
272
- python="/usr/bin/python3",
273
- env={"PYTHONPATH": "/usr/local/lib/python3.12/dist-packages"},
274
- secrets={"HF_TOKEN": get_token()},
275
- )
276
- ```
277
 
278
- ## Troubleshooting
279
 
280
- **The Job runs on a CPU, or cannot push to the Hub.** Your `hf` CLI is older than 1.32 and ignored the header. Upgrade, or pass the header values as flags (see the [Quick Start](#quick-start) note).
281
 
282
- **A vLLM recipe crashes at startup with an `nvcc` or `nvrtc` error:**
283
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
284
  ```
285
- RuntimeError: Could not find nvcc and default cuda_home='/usr/local/cuda' doesn't exist
286
- nvrtc: error: failed to open libnvrtc-builtins.so...
 
 
 
 
 
 
 
 
 
287
  ```
288
 
289
- The Job ran on the default image, which has no CUDA toolkit. This happens with an older CLI, with a legacy recipe, or when you override `--image`. Run it on the `vllm/vllm-openai` image:
290
 
291
  ```bash
292
- --image vllm/vllm-openai:v0.30.0 --python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages
293
- ```
 
 
294
 
295
- Use the tag from the script's header. The Surya recipes use `/usr/local/bin/python3` and `site-packages` instead; copy their header exactly. `unlimited-ocr-vllm.py` needs Baidu's `vllm/vllm-openai:unlimited-ocr` image (`:unlimited-ocr-cu129` on H100 or H200).
 
 
296
 
297
- **The Job stops before it finishes.** Jobs stop at their timeout. Pass a longer `--timeout`, or use a `-saturate.py` recipe, which can resume.
 
 
 
298
 
299
- **Run locally on your own GPU.** Most recipes get vLLM from the Docker image, not from their dependencies. Add the vLLM version from the header tag:
 
 
 
 
 
300
 
301
- ```bash
302
- uv run --with vllm==0.29.0 \
303
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \
304
- input-dataset output-dataset --max-samples 10
305
  ```
306
 
307
- The Surya recipes need `vllm==0.20.1`. `unlimited-ocr-vllm.py` needs an architecture that no stable vLLM wheel has yet, so it runs only inside its image.
 
 
 
1
  ---
2
  viewer: false
3
+ tags: [uv-script, ocr, vision-language-model, document-processing, hf-jobs]
4
  ---
5
 
6
  # OCR UV Scripts
7
 
8
+ > Part of [uv-scripts](https://huggingface.co/uv-scripts) - ready-to-run ML tools powered by UV and HuggingFace Jobs.
9
 
10
+ 14 OCR models from 0.9B to 8B parameters. Pick a model, point at your dataset, get markdown — no setup required.
11
 
12
+ ## 🚀 Quick Start
13
 
14
+ Run OCR on any dataset without needing your own GPU:
15
 
16
+ ```bash
17
+ # Quick test with 10 samples
18
+ hf jobs uv run --flavor l4x1 \
19
+ --secrets HF_TOKEN \
20
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \
21
+ your-input-dataset your-output-dataset \
22
+ --max-samples 10
23
+ ```
24
 
25
+ That's it! The script will:
26
+
27
+ - Process first 10 images from your dataset
28
+ - Add OCR results as a new `markdown` column
29
+ - Push the results to a new dataset
30
+ - View results at: `https://huggingface.co/datasets/[your-output-dataset]`
31
+
32
+ <details><summary>All scripts at a glance (sorted by model size)</summary>
33
+
34
+ | Script | Model | Size | Backend | Notes |
35
+ |--------|-------|------|---------|-------|
36
+ | `smoldocling-ocr.py` | [SmolDocling](https://huggingface.co/ds4sd/SmolDocling-256M-preview) | 256M | Transformers | DocTags structured output |
37
+ | `glm-ocr.py` | [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) | 0.9B | vLLM | 94.62% OmniDocBench V1.5 |
38
+ | `paddleocr-vl.py` | [PaddleOCR-VL](https://huggingface.co/PaddlePaddle/PaddleOCR-VL) | 0.9B | Transformers | 4 task modes (ocr/table/formula/chart) |
39
+ | `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 |
40
+ | `lighton-ocr.py` | [LightOnOCR-1B](https://huggingface.co/lightonai/LightOnOCR-1B-1025) | 1B | vLLM | Fast, 3 vocab sizes |
41
+ | `lighton-ocr2.py` | [LightOnOCR-2-1B](https://huggingface.co/lightonai/LightOnOCR-2-1B) | 1B | vLLM | 7× faster than v1, RLVR trained |
42
+ | `hunyuan-ocr.py` | [HunyuanOCR](https://huggingface.co/tencent/HunyuanOCR) | 1B | vLLM | Lightweight VLM |
43
+ | `dots-ocr.py` | [DoTS.ocr](https://huggingface.co/Tencent/DoTS.ocr) | 1.7B | vLLM | 100+ languages |
44
+ | `firered-ocr.py` | [FireRed-OCR](https://huggingface.co/FireRedTeam/FireRed-OCR) | 2.1B | vLLM | Qwen3-VL fine-tune, Apache 2.0 |
45
+ | `nanonets-ocr.py` | [Nanonets-OCR-s](https://huggingface.co/nanonets/Nanonets-OCR-s) | 2B | vLLM | LaTeX, tables, forms |
46
+ | `dots-ocr-1.5.py` | [DoTS.ocr-1.5](https://huggingface.co/Tencent/DoTS.ocr-1.5) | 3B | vLLM | Updated multilingual model |
47
+ | `nanonets-ocr2.py` | [Nanonets-OCR2-3B](https://huggingface.co/nanonets/Nanonets-OCR2-s) | 3B | vLLM | Next-gen, Qwen2.5-VL base |
48
+ | `deepseek-ocr-vllm.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | vLLM | 5 resolution + 5 prompt modes |
49
+ | `deepseek-ocr.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | Transformers | Same model, Transformers backend |
50
+ | `deepseek-ocr2-vllm.py` | [DeepSeek-OCR-2](https://huggingface.co/deepseek-ai/DeepSeek-OCR-2) | 3B | vLLM | Newer, requires nightly vLLM |
51
+ | `olmocr2-vllm.py` | [olmOCR-2-7B](https://huggingface.co/allenai/olmOCR-2-7B-1025-FP8) | 7B | vLLM | 82.4% olmOCR-Bench |
52
+ | `rolm-ocr.py` | [RolmOCR](https://huggingface.co/reducto/RolmOCR) | 7B | vLLM | Qwen2.5-VL based, general-purpose |
53
+ | `numarkdown-ocr.py` | [NuMarkdown-8B](https://huggingface.co/numind/NuMarkdown-8B-Thinking) | 8B | vLLM | Reasoning-based OCR |
54
+
55
+ </details>
56
+
57
+ ## Common Options
58
+
59
+ All scripts accept the same core flags. Model-specific defaults (batch size, context length, temperature) are tuned per model based on model card recommendations and can be overridden.
60
+
61
+ | Option | Description |
62
+ |--------|-------------|
63
+ | `--image-column` | Column containing images (default: `image`) |
64
+ | `--output-column` | Output column name (default: `markdown`) |
65
+ | `--split` | Dataset split (default: `train`) |
66
+ | `--max-samples` | Limit number of samples (useful for testing) |
67
+ | `--private` | Make output dataset private |
68
+ | `--shuffle` | Shuffle dataset before processing |
69
+ | `--seed` | Random seed for shuffling (default: `42`) |
70
+ | `--batch-size` | Images per batch (default varies per model) |
71
+ | `--max-model-len` | Max context length (default varies per model) |
72
+ | `--max-tokens` | Max output tokens (default varies per model) |
73
+ | `--gpu-memory-utilization` | GPU memory fraction (default: `0.8`) |
74
+ | `--config` | Config name for Hub push (for benchmarking) |
75
+ | `--create-pr` | Push as PR instead of direct commit |
76
+ | `--verbose` | Log resolved package versions after run |
77
+
78
+ Every script supports `--help` to see all available options:
79
 
80
  ```bash
81
+ uv run glm-ocr.py --help
 
82
  ```
83
 
84
+ ## Example: GLM-OCR
85
 
86
+ [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) (0.9B) scores 94.62% on OmniDocBench V1.5 and supports OCR, formula, and table extraction:
87
 
88
+ ```bash
89
+ # Basic OCR
90
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN \
91
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \
92
+ my-documents my-ocr-output
93
 
94
+ # Table extraction
95
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN \
96
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \
97
+ my-documents my-tables --task table
98
 
99
+ # Test on 10 samples first
100
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN \
101
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \
102
+ my-documents my-test --max-samples 10
 
 
 
103
  ```
104
 
105
+ <details><summary>Detailed per-model documentation</summary>
106
+
107
+ ### PaddleOCR-VL-1.5 (`paddleocr-vl-1.5.py`) — 6 task modes
108
+
109
+ OCR using [PaddlePaddle/PaddleOCR-VL-1.5](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.5) with 94.5% accuracy:
110
 
111
+ - **94.5% on OmniDocBench v1.5** (0.9B parameters)
112
+ - 🧩 **Ultra-compact** - Only 0.9B parameters
113
+ - 📝 **OCR mode** - General text extraction to markdown
114
+ - 📊 **Table mode** - HTML table recognition
115
+ - 📐 **Formula mode** - LaTeX mathematical notation
116
+ - 📈 **Chart mode** - Chart and diagram analysis
117
+ - 🔍 **Spotting mode** - Text spotting with localization (higher resolution)
118
+ - 🔖 **Seal mode** - Seal and stamp recognition
119
+ - 🌍 **Multilingual** - Support for multiple languages
120
 
121
+ **Task Modes:**
122
 
123
+ - `ocr`: General text extraction (default)
124
+ - `table`: Table extraction to HTML
125
+ - `formula`: Mathematical formula to LaTeX
126
+ - `chart`: Chart and diagram analysis
127
+ - `spotting`: Text spotting with localization
128
+ - `seal`: Seal and stamp recognition
129
+
130
+ **Quick start:**
131
 
132
  ```bash
133
+ # Basic OCR mode
134
+ hf jobs uv run --flavor l4x1 \
135
+ -s HF_TOKEN \
136
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl-1.5.py \
137
+ your-input-dataset your-output-dataset \
138
+ --max-samples 100
139
+
140
+ # Table extraction
141
+ hf jobs uv run --flavor l4x1 \
142
+ -s HF_TOKEN \
143
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl-1.5.py \
144
+ documents tables-extracted \
145
+ --task-mode table
146
+
147
+ # Seal recognition
148
+ hf jobs uv run --flavor l4x1 \
149
+ -s HF_TOKEN \
150
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl-1.5.py \
151
+ documents seals-extracted \
152
+ --task-mode seal
153
  ```
154
 
155
+ ### PaddleOCR-VL (`paddleocr-vl.py`) 🎯 Smallest model with task-specific modes!
156
 
157
+ Ultra-compact OCR using [PaddlePaddle/PaddleOCR-VL](https://huggingface.co/PaddlePaddle/PaddleOCR-VL) with only 0.9B parameters:
158
 
159
+ - 🎯 **Smallest model** - Only 0.9B parameters (even smaller than LightOnOCR!)
160
+ - 📝 **OCR mode** - General text extraction to markdown
161
+ - 📊 **Table mode** - HTML table recognition and extraction
162
+ - 📐 **Formula mode** - LaTeX mathematical notation
163
+ - 📈 **Chart mode** - Structured chart and diagram analysis
164
+ - 🌍 **Multilingual** - Support for multiple languages
165
+ - ⚡ **Fast initialization** - Tiny model size for quick startup
166
+ - 🔧 **ERNIE-4.5 based** - Different architecture from Qwen models
167
 
168
+ **Task Modes:**
 
 
 
169
 
170
+ - `ocr`: General text extraction (default)
171
+ - `table`: Table extraction to HTML
172
+ - `formula`: Mathematical formula to LaTeX
173
+ - `chart`: Chart and diagram analysis
174
 
175
+ **Quick start:**
 
 
176
 
177
+ ```bash
178
+ # Basic OCR mode
179
+ hf jobs uv run --flavor l4x1 \
180
+ -s HF_TOKEN \
181
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl.py \
182
+ your-input-dataset your-output-dataset \
183
+ --max-samples 100
184
+
185
+ # Table extraction
186
+ hf jobs uv run --flavor l4x1 \
187
+ -s HF_TOKEN \
188
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl.py \
189
+ documents tables-extracted \
190
+ --task-mode table \
191
+ --batch-size 32
192
+ ```
193
 
194
+ ### GLM-OCR (`glm-ocr.py`) 🏆 SOTA on OmniDocBench V1.5!
195
 
196
+ Compact high-performance OCR using [zai-org/GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) with 0.9B parameters:
197
 
198
+ - 🏆 **94.62% on OmniDocBench V1.5** - #1 overall ranking
199
+ - 🧠 **Multi-Token Prediction** - MTP loss + stable full-task RL for quality
200
+ - 📝 **Text recognition** - Clean markdown output
201
+ - 📐 **Formula recognition** - LaTeX mathematical notation
202
+ - 📊 **Table recognition** - Structured table extraction
203
+ - 🌍 **Multilingual** - zh, en, fr, es, ru, de, ja, ko
204
+ - ⚡ **Compact** - Only 0.9B parameters, MIT licensed
205
+ - 🔧 **CogViT + GLM** - Visual encoder with efficient token downsampling
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
 
207
+ **Task Modes:**
208
 
209
+ - `ocr`: Text recognition (default)
210
+ - `formula`: LaTeX formula recognition
211
+ - `table`: Table extraction
212
 
213
+ **Quick start:**
214
 
215
  ```bash
216
+ # Basic OCR
217
+ hf jobs uv run --flavor l4x1 \
218
+ -s HF_TOKEN \
219
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \
220
+ your-input-dataset your-output-dataset \
221
+ --max-samples 100
222
 
223
+ # Formula recognition
224
+ hf jobs uv run --flavor l4x1 \
225
+ -s HF_TOKEN \
226
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \
227
+ scientific-papers formulas-extracted \
228
+ --task formula
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
 
230
+ # Table extraction
231
+ hf jobs uv run --flavor l4x1 \
232
+ -s HF_TOKEN \
233
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \
234
+ documents tables-extracted \
235
+ --task table
236
  ```
237
 
238
+ ### LightOnOCR (`lighton-ocr.py`) ⚡ Good one to test first since it's small and fast!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
 
240
+ Fast and compact OCR using [lightonai/LightOnOCR-1B-1025](https://huggingface.co/lightonai/LightOnOCR-1B-1025):
 
 
 
 
241
 
242
+ - ⚡ **Fastest**: 5.71 pages/sec on H100, ~6.25 images/sec on A100 with batch_size=4096
243
+ - 🎯 **Compact**: Only 1B parameters - quick to download and initialize
244
+ - 🌍 **Multilingual**: 3 vocabulary sizes for different use cases
245
+ - 📐 **LaTeX formulas**: Mathematical notation in LaTeX format
246
+ - 📊 **Table extraction**: Markdown table format
247
+ - 📝 **Document structure**: Preserves hierarchy and layout
248
+ - 🚀 **Production-ready**: 76.1% benchmark score, used in production
249
 
250
+ **Vocabulary sizes:**
251
 
252
+ - `151k`: Full vocabulary, all languages (default)
253
+ - `32k`: European languages, ~12% faster decoding
254
+ - `16k`: European languages, ~12% faster decoding
255
+
256
+ **Quick start:**
257
 
258
  ```bash
259
+ # Test on 100 samples with English text (32k vocab is fastest for European languages)
260
+ hf jobs uv run --flavor l4x1 \
261
+ -s HF_TOKEN \
262
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr.py \
263
+ your-input-dataset your-output-dataset \
264
+ --vocab-size 32k \
265
+ --batch-size 32 \
266
+ --max-samples 100
267
+
268
+ # Full production run on A100 (can handle huge batches!)
269
+ hf jobs uv run --flavor a100-large \
270
+ -s HF_TOKEN \
271
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr.py \
272
+ your-input-dataset your-output-dataset \
273
+ --vocab-size 32k \
274
+ --batch-size 4096 \
275
+ --temperature 0.0
276
  ```
277
 
278
+ ### LightOnOCR-2 (`lighton-ocr2.py`) ⚡ Fastest OCR model!
279
 
280
+ Next-generation fast OCR using [lightonai/LightOnOCR-2-1B](https://huggingface.co/lightonai/LightOnOCR-2-1B) with RLVR training:
281
 
282
+ - ⚡ **7× faster than v1**: 42.8 pages/sec on H100 (vs 5.71 for v1)
283
+ - 🎯 **Higher accuracy**: 83.2% on OlmOCR-Bench (+7.1% vs v1)
284
+ - 🧠 **RLVR trained**: Eliminates repetition loops and formatting errors
285
+ - 📚 **Better dataset**: 2.5× larger training data with cleaner annotations
286
+ - 🌍 **Multilingual**: Optimized for European languages
287
+ - 📐 **LaTeX formulas**: Mathematical notation support
288
+ - 📊 **Table extraction**: Markdown table format
289
+ - 💪 **Production-ready**: Outperforms models 9× larger
290
 
291
+ **Quick start:**
292
 
293
  ```bash
294
+ # Test on 100 samples
295
+ hf jobs uv run --flavor a100-large \
296
+ -s HF_TOKEN \
297
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr2.py \
298
+ your-input-dataset your-output-dataset \
299
+ --batch-size 32 \
300
+ --max-samples 100
301
+
302
+ # Full production run
303
+ hf jobs uv run --flavor a100-large \
304
+ -s HF_TOKEN \
305
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr2.py \
306
+ your-input-dataset your-output-dataset \
307
+ --batch-size 32
308
  ```
309
 
310
+ ### DeepSeek-OCR (`deepseek-ocr-vllm.py`)
311
 
312
+ Advanced document OCR using [deepseek-ai/DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) with visual-text compression:
313
+
314
+ - 📐 **LaTeX equations** - Mathematical formulas in LaTeX format
315
+ - 📊 **Tables** - Extracted as HTML/markdown
316
+ - 📝 **Document structure** - Headers, lists, formatting preserved
317
+ - 🖼️ **Image grounding** - Spatial layout with bounding boxes
318
+ - 🔍 **Complex layouts** - Multi-column and hierarchical structures
319
+ - 🌍 **Multilingual** - Multiple language support
320
+ - 🎚️ **Resolution modes** - 5 presets for speed/quality trade-offs
321
+ - 💬 **Prompt modes** - 5 presets for different OCR tasks
322
+ - ⚡ **Fast batch processing** - vLLM acceleration
323
+
324
+ **Resolution Modes:**
325
+
326
+ - `tiny` (512×512): Fast, 64 vision tokens
327
+ - `small` (640×640): Balanced, 100 vision tokens
328
+ - `base` (1024×1024): High quality, 256 vision tokens
329
+ - `large` (1280×1280): Maximum quality, 400 vision tokens
330
+ - `gundam` (dynamic): Adaptive multi-tile (default)
331
+
332
+ **Prompt Modes:**
333
+
334
+ - `document`: Convert to markdown with grounding (default)
335
+ - `image`: OCR any image with grounding
336
+ - `free`: Fast OCR without layout
337
+ - `figure`: Parse figures from documents
338
+ - `describe`: Detailed image descriptions
339
+
340
+ ### RolmOCR (`rolm-ocr.py`)
341
+
342
+ Fast general-purpose OCR using [reducto/RolmOCR](https://huggingface.co/reducto/RolmOCR) based on Qwen2.5-VL-7B:
343
+
344
+ - 🚀 **Fast extraction** - Optimized for speed and efficiency
345
+ - 📄 **Plain text output** - Clean, natural text representation
346
+ - 💪 **General-purpose** - Works well on various document types
347
+ - 🔥 **Large context** - Handles up to 16K tokens
348
+ - ⚡ **Batch optimized** - Efficient processing with vLLM
349
+
350
+ ### Nanonets OCR (`nanonets-ocr.py`)
351
+
352
+ State-of-the-art document OCR using [nanonets/Nanonets-OCR-s](https://huggingface.co/nanonets/Nanonets-OCR-s) that handles:
353
+
354
+ - 📐 **LaTeX equations** - Mathematical formulas preserved
355
+ - 📊 **Tables** - Extracted as HTML format
356
+ - 📝 **Document structure** - Headers, lists, formatting maintained
357
+ - 🖼️ **Images** - Captions and descriptions included
358
+ - ☑️ **Forms** - Checkboxes rendered as ☐/☑
359
 
360
+ ### Nanonets OCR2 (`nanonets-ocr2.py`)
361
 
362
+ Next-generation Nanonets OCR using [nanonets/Nanonets-OCR2-3B](https://huggingface.co/nanonets/Nanonets-OCR2-3B) with improved accuracy:
363
 
364
+ - 🎯 **Enhanced quality** - 3.75B parameters for superior OCR accuracy
365
+ - 📐 **LaTeX equations** - Mathematical formulas preserved in LaTeX format
366
+ - 📊 **Advanced tables** - Improved HTML table extraction
367
+ - 📝 **Document structure** - Headers, lists, formatting maintained
368
+ - 🖼️ **Smart image captions** - Intelligent descriptions and captions
369
+ - ☑️ **Forms** - Checkboxes rendered as ☐/☑
370
+ - 🌍 **Multilingual** - Enhanced language support
371
+ - 🔧 **Based on Qwen2.5-VL** - Built on state-of-the-art vision-language model
372
 
373
+ ### SmolDocling (`smoldocling-ocr.py`)
374
+
375
+ Ultra-compact document understanding using [ds4sd/SmolDocling-256M-preview](https://huggingface.co/ds4sd/SmolDocling-256M-preview) with only 256M parameters:
376
+
377
+ - 🏷️ **DocTags format** - Efficient XML-like representation
378
+ - 💻 **Code blocks** - Preserves indentation and syntax
379
+ - 🔢 **Formulas** - Mathematical expressions with layout
380
+ - 📊 **Tables & charts** - Structured data extraction
381
+ - 📐 **Layout preservation** - Bounding boxes and spatial info
382
+ - ⚡ **Ultra-fast** - Tiny model size for quick inference
383
+
384
+ ### NuMarkdown (`numarkdown-ocr.py`)
385
+
386
+ Advanced reasoning-based OCR using [numind/NuMarkdown-8B-Thinking](https://huggingface.co/numind/NuMarkdown-8B-Thinking) that analyzes documents before converting to markdown:
387
+
388
+ - 🧠 **Reasoning Process** - Thinks through document layout before generation
389
+ - 📊 **Complex Tables** - Superior table extraction and formatting
390
+ - 📐 **Mathematical Formulas** - Accurate LaTeX/math notation preservation
391
+ - 🔍 **Multi-column Layouts** - Handles complex document structures
392
+ - ✨ **Thinking Traces** - Optional inclusion of reasoning process with `--include-thinking`
393
+
394
+ ### DoTS.ocr (`dots-ocr.py`)
395
+
396
+ Compact multilingual OCR using [rednote-hilab/dots.ocr](https://huggingface.co/rednote-hilab/dots.ocr) with only 1.7B parameters:
397
+
398
+ - 🌍 **100+ Languages** - Extensive multilingual support
399
+ - 📝 **Simple OCR** - Clean text extraction (default mode)
400
+ - 📊 **Layout Analysis** - Optional structured output with bboxes and categories
401
+ - 📐 **Formula recognition** - LaTeX format support
402
+ - 🎯 **Compact** - Only 1.7B parameters, efficient on smaller GPUs
403
+ - 🔀 **Flexible prompts** - Switch between OCR, layout-all, and layout-only modes
404
+
405
+ ### FireRed-OCR (`firered-ocr.py`)
406
+
407
+ Document OCR using [FireRedTeam/FireRed-OCR](https://huggingface.co/FireRedTeam/FireRed-OCR), a 2.1B model fine-tuned from Qwen3-VL-2B-Instruct:
408
+
409
+ - 📝 **Structured Markdown** - Preserves headings, paragraphs, lists
410
+ - 📐 **LaTeX formulas** - Inline and block math support
411
+ - 📊 **HTML tables** - Table extraction with `<table>` tags
412
+ - 🪶 **Lightweight** - 2.1B parameters, runs on L4 GPU
413
+ - 📜 **Apache 2.0** - Permissive license
414
+
415
+ **Quick start:**
416
 
417
  ```bash
418
+ hf jobs uv run --flavor l4x1 \
419
+ -s HF_TOKEN \
420
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/firered-ocr.py \
421
+ your-input-dataset your-output-dataset \
422
+ --max-samples 100
423
  ```
424
 
425
+ ### olmOCR2 (`olmocr2-vllm.py`)
426
+
427
+ High-quality document OCR using [allenai/olmOCR-2-7B-1025-FP8](https://huggingface.co/allenai/olmOCR-2-7B-1025-FP8) optimized with GRPO reinforcement learning:
428
+
429
+ - 🎯 **High accuracy** - 82.4 ± 1.1 on olmOCR-Bench (84.9% on math)
430
+ - 📐 **LaTeX equations** - Mathematical formulas in LaTeX format
431
+ - 📊 **Table extraction** - Structured table recognition
432
+ - 📑 **Multi-column layouts** - Complex document structures
433
+ - 🗜️ **FP8 quantized** - Efficient 8B model for faster inference
434
+ - 📜 **Degraded scans** - Works well on old/historical documents
435
+ - 📝 **Long text extraction** - Headers, footers, and full document content
436
+ - 🧩 **YAML metadata** - Structured front matter (language, rotation, content type)
437
+ - 🚀 **Based on Qwen2.5-VL-7B** - Fine-tuned with reinforcement learning
438
+
439
+ ## 🆕 New Features
440
+
441
+ ### Multi-Model Comparison Support
442
+
443
+ All scripts now include `inference_info` tracking for comparing multiple OCR models:
444
 
445
  ```bash
446
+ # First model
447
+ uv run rolm-ocr.py my-dataset my-dataset --max-samples 100
448
+
449
+ # Second model (appends to same dataset)
450
+ uv run nanonets-ocr.py my-dataset my-dataset --max-samples 100
451
+
452
+ # View all models used
453
+ python -c "import json; from datasets import load_dataset; ds = load_dataset('my-dataset'); print(json.loads(ds[0]['inference_info']))"
454
  ```
455
 
456
+ ### Random Sampling
457
 
458
+ Get representative samples with the new `--shuffle` flag:
459
 
460
  ```bash
461
+ # Random 50 samples instead of first 50
462
+ uv run rolm-ocr.py ordered-dataset output --max-samples 50 --shuffle
463
+
464
+ # Reproducible random sampling
465
+ uv run nanonets-ocr.py dataset output --max-samples 100 --shuffle --seed 42
466
  ```
467
 
468
+ ### Automatic Dataset Cards
469
 
470
+ Every OCR run now generates comprehensive dataset documentation including:
 
471
 
472
+ - Model configuration and parameters
473
+ - Processing statistics
474
+ - Column descriptions
475
+ - Reproduction instructions
 
 
 
 
 
 
476
 
477
+ ## 💻 Usage Examples
478
 
479
+ ### Run on HuggingFace Jobs (Recommended)
480
 
481
+ No GPU? No problem! Run on HF infrastructure:
482
 
483
+ ```bash
484
+ # PaddleOCR-VL - Smallest model (0.9B) with task modes
485
+ hf jobs uv run --flavor l4x1 \
486
+ --secrets HF_TOKEN \
487
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl.py \
488
+ your-input-dataset your-output-dataset \
489
+ --task-mode ocr \
490
+ --max-samples 100
491
+
492
+ # PaddleOCR-VL - Extract tables from documents
493
+ hf jobs uv run --flavor l4x1 \
494
+ --secrets HF_TOKEN \
495
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl.py \
496
+ documents tables-dataset \
497
+ --task-mode table
498
+
499
+ # PaddleOCR-VL - Formula recognition
500
+ hf jobs uv run --flavor l4x1 \
501
+ --secrets HF_TOKEN \
502
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl.py \
503
+ scientific-papers formulas-extracted \
504
+ --task-mode formula \
505
+ --batch-size 32
506
+
507
+ # GLM-OCR - SOTA 0.9B model (94.62% OmniDocBench)
508
+ hf jobs uv run --flavor l4x1 \
509
+ -s HF_TOKEN \
510
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \
511
+ your-input-dataset your-output-dataset \
512
+ --batch-size 16 \
513
+ --max-samples 100
514
+
515
+ # DeepSeek-OCR - Real-world example (National Library of Scotland handbooks)
516
+ hf jobs uv run --flavor a100-large \
517
+ -s HF_TOKEN \
518
+ -e UV_TORCH_BACKEND=auto \
519
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr-vllm.py \
520
+ NationalLibraryOfScotland/Britain-and-UK-Handbooks-Dataset \
521
+ davanstrien/handbooks-deep-ocr \
522
+ --max-samples 100 \
523
+ --shuffle \
524
+ --resolution-mode large
525
+
526
+ # DeepSeek-OCR - Fast testing with tiny mode
527
+ hf jobs uv run --flavor l4x1 \
528
+ -s HF_TOKEN \
529
+ -e UV_TORCH_BACKEND=auto \
530
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr-vllm.py \
531
+ your-input-dataset your-output-dataset \
532
+ --max-samples 10 \
533
+ --resolution-mode tiny
534
+
535
+ # DeepSeek-OCR - Parse figures from scientific papers
536
+ hf jobs uv run --flavor a100-large \
537
+ -s HF_TOKEN \
538
+ -e UV_TORCH_BACKEND=auto \
539
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr-vllm.py \
540
+ scientific-papers figures-extracted \
541
+ --prompt-mode figure
542
+
543
+ # Basic OCR job with Nanonets
544
+ hf jobs uv run --flavor l4x1 \
545
+ --secrets HF_TOKEN \
546
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-ocr.py \
547
+ your-input-dataset your-output-dataset
548
+
549
+ # DoTS.ocr - Multilingual OCR with compact 1.7B model
550
+ hf jobs uv run --flavor a100-large \
551
+ --secrets HF_TOKEN \
552
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/dots-ocr.py \
553
+ davanstrien/ufo-ColPali \
554
+ your-username/ufo-ocr \
555
+ --batch-size 256 \
556
+ --max-samples 1000 \
557
+ --shuffle
558
+
559
+ # Real example with UFO dataset 🛸
560
+ hf jobs uv run \
561
+ --flavor a10g-large \
562
+ --secrets HF_TOKEN \
563
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-ocr.py \
564
+ davanstrien/ufo-ColPali \
565
+ your-username/ufo-ocr \
566
+ --image-column image \
567
+ --max-model-len 16384 \
568
+ --batch-size 128
569
+
570
+ # Nanonets OCR2 - Next-gen quality with 3B model
571
+ hf jobs uv run \
572
+ --flavor l4x1 \
573
+ --secrets HF_TOKEN \
574
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-ocr2.py \
575
+ your-input-dataset \
576
+ your-output-dataset \
577
+ --batch-size 16
578
+
579
+ # NuMarkdown with reasoning traces for complex documents
580
+ hf jobs uv run \
581
+ --flavor l4x4 \
582
+ --secrets HF_TOKEN \
583
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/numarkdown-ocr.py \
584
+ your-input-dataset your-output-dataset \
585
+ --max-samples 50 \
586
+ --include-thinking \
587
+ --shuffle
588
+
589
+ # olmOCR2 - High-quality OCR with YAML metadata
590
+ hf jobs uv run \
591
+ --flavor a100-large \
592
+ --secrets HF_TOKEN \
593
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/olmocr2-vllm.py \
594
+ your-input-dataset your-output-dataset \
595
+ --batch-size 16 \
596
+ --max-samples 100
597
+
598
+ # Private dataset with custom settings
599
+ hf jobs uv run --flavor l40sx1 \
600
+ --secrets HF_TOKEN \
601
+ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-ocr.py \
602
+ private-input private-output \
603
+ --private \
604
+ --batch-size 32
605
  ```
606
+
607
+ ### Python API
608
+
609
+ ```python
610
+ from huggingface_hub import run_uv_job
611
+
612
+ job = run_uv_job(
613
+ "https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-ocr.py",
614
+ args=["input-dataset", "output-dataset", "--batch-size", "16"],
615
+ flavor="l4x1"
616
+ )
617
  ```
618
 
619
+ ### Run Locally (Requires GPU)
620
 
621
  ```bash
622
+ # Clone and run
623
+ git clone https://huggingface.co/datasets/uv-scripts/ocr
624
+ cd ocr
625
+ uv run nanonets-ocr.py input-dataset output-dataset
626
 
627
+ # Or run directly from URL
628
+ uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-ocr.py \
629
+ input-dataset output-dataset
630
 
631
+ # PaddleOCR-VL for task-specific OCR (smallest model!)
632
+ uv run paddleocr-vl.py documents extracted --task-mode ocr
633
+ uv run paddleocr-vl.py papers tables --task-mode table # Extract tables
634
+ uv run paddleocr-vl.py textbooks formulas --task-mode formula # LaTeX formulas
635
 
636
+ # RolmOCR for fast text extraction
637
+ uv run rolm-ocr.py documents extracted-text
638
+ uv run rolm-ocr.py images texts --shuffle --max-samples 100 # Random sample
639
+
640
+ # Nanonets OCR2 for highest quality
641
+ uv run nanonets-ocr2.py documents ocr-results
642
 
 
 
 
 
643
  ```
644
 
645
+ </details>
646
+
647
+ Works with any HuggingFace dataset containing images — documents, forms, receipts, books, handwriting.
SERVING.md DELETED
@@ -1,111 +0,0 @@
1
- # Server-mode OCR: official support per model + the `-server.py` recipes
2
-
3
- The recipes in this folder come in two shapes:
4
-
5
- - **Offline batch** (`<model>.py`): the script owns the vLLM engine (`LLM.generate`)
6
- and processes the dataset in fixed-size batches. One `hf jobs uv run` command.
7
- - **Server + driver** (`<model>-server.py`): one job starts `vllm serve` in the
8
- background, then a lightweight driver (no torch/vllm deps — installs in seconds)
9
- posts images concurrently to the OpenAI-compatible endpoint on localhost.
10
-
11
- Why server mode? Two measured reasons (100-page historical-scan A/B on `l4x1`,
12
- same data, same sampling, driver concurrency 32):
13
-
14
- | Model | Offline (inference-only) | Server | Speedup | Output parity |
15
- |---|---|---|---|---|
16
- | OvisOCR2 0.9B | 0.83 img/s | 1.44 img/s | ~1.7× | 94/100 byte-identical, rest ≥0.978 similar |
17
- | LightOnOCR-2 1B | 0.33 img/s | 0.59 img/s | ~1.8× | 64/100 byte-identical at temp 0.2, rest median 0.998 |
18
- | Nanonets-OCR2 3B | 0.31 img/s (steady-state) | 0.36 img/s | ~1.2× | 52/100 byte-identical, median 0.999; 3 hard plate pages fork under greedy (worst case was the *offline* arm degenerating into a 22k-char repetition loop) |
19
-
20
- 1. **Throughput**: offline `llm.generate` drains at every batch boundary (GPU idles
21
- while the CPU decodes the next batch of images); a concurrent driver keeps vLLM's
22
- continuous batching fed. The speedup is a floor, not a ceiling — at concurrency 32
23
- the server's KV cache was <10% used.
24
- 2. **Failure isolation**: offline, one bad image (e.g. a None cell) fails its whole
25
- batch of 16; server mode fails that one request. On a real dataset where ~half the
26
- image cells were empty, the offline recipe produced 0 usable outputs and the server
27
- recipe produced all of the valid ones.
28
-
29
- **LightOnOCR-3-0.8B** (`lighton-ocr3.py` against `lighton-ocr3-saturate.py`, 600 pages: 350
30
- book pages from finebooks/bhl-impact-gt and 250 typed industry documents, 2026-11-05, steady
31
- state): `a10g-small` 0.90 → 2.2 pages/s, `a100-large` 1.27 → 7.2 pages/s. Most of the gain is
32
- pages in flight (the offline recipe sends batches of 16 and waits for the slowest page); on
33
- small flavors the window is capped by host memory, because each page in flight holds about
34
- 0.1 GiB of image data. On fast GPUs one vLLM API server cannot preprocess images quickly
35
- enough (128-256 pages in flight, 36-60 running in the engine, none waiting); 4 API servers
36
- (`--api-server-count 4`) gave +16% on `a100-large`, +9% on `rtx-pro-6000`, +10% on `a10g-large`. At temperature 0.2 the outputs of two server runs differ on about 40%
37
- of pages; the offline recipe differs from a server run by the same amount. The character
38
- error rate on the 282 book pages with at least 20 characters of ground truth (IMPACT) was
39
- 0.077 to 0.083 mean and 0.020 median in every 0.8B run, offline or server.
40
-
41
- The job command stays the standard `hf jobs uv run` shape: the driver spawns
42
- `vllm serve` itself as a subprocess when no server is reachable (flags live in the
43
- script's `SERVE_ARGS`, taken from the model's own card where they exist), so the only
44
- thing to get right is `--image vllm/vllm-openai:<tag>` — which provides the `vllm`
45
- binary. Without it the script fails fast, printing the exact correct command. Pass
46
- `--server URL` to use an already-running or remote endpoint instead (nothing is
47
- spawned when the server is reachable, so the moss-style explicit `bash -c` serve
48
- command keeps working too).
49
-
50
- For **interactive/agent** use (a live endpoint instead of a batch run), see
51
- [serving-unlimited-ocr.md](serving-unlimited-ocr.md) — `hf jobs run --expose` gives an
52
- OpenAI-compatible URL that outlives a single script.
53
-
54
- ## The recurring official serve pattern for OCR
55
-
56
- Three flags recur across independent vendors' official serve commands (DeepSeek's vLLM
57
- recipe, LightOn's card, Paddle's vLLM recipe, Unlimited-OCR's recipe):
58
-
59
- ```
60
- --no-enable-prefix-caching --mm-processor-cache-gb 0 --limit-mm-per-prompt '{"image": 1}'
61
- ```
62
-
63
- OCR workloads never reuse images, so prefix/multimodal caches only cost memory.
64
-
65
- **One exception: HPD-Parsing** (`hpd-parsing-saturate.py`). Its vendor entrypoint sets
66
- `--enable-prefix-caching` on purpose. Hierarchical parallel decoding forks a child branch per
67
- page region, and the children reuse the parent branch's prefix KV, so the cache does real work
68
- (hit rate 52.9% on 5 UFO pages in July 2026, 43.9% on 10 in November). Do not change it to
69
- `--no-enable-prefix-caching` in a sweep.
70
-
71
- ## Version pins carry over — via the image tag
72
-
73
- Where an offline recipe pins an engine version, the server variant needs the same pin
74
- as a `vllm/vllm-openai:<tag>` image (e.g. Nanonets-OCR2-3B uses `v0.10.2`, matching its
75
- offline recipe). [`models.json`](models.json) records the required image per script.
76
- When trying a new model/image combination, sanity-check the first few outputs before
77
- scaling: a mismatched combination can produce degenerate output while looking like
78
- normal load from the outside (full GPU utilisation, no errors).
79
-
80
- ## Which models document server mode themselves? (surveyed 2026-07-16)
81
-
82
- Server mode is the officially documented path for most models in this collection —
83
- for several of them it's the *only* documented vLLM path. Summary of each model's own
84
- card/docs (verbatim commands live in the linked sources):
85
-
86
- | Model | Official server example | Notes |
87
- |---|---|---|
88
- | lightonai/LightOnOCR-1B / 2-1B | ✅ vLLM | Card ships the serve command + client; ≥0.11.1 for v1; images longest-dim 1540px |
89
- | nanonets/OCR-s / OCR2-3B | ✅ vLLM | Bare `vllm serve` + client in card; **pin v0.10.2 for OCR2** (see above) |
90
- | rednote-hilab/dots.mocr | ✅ vLLM ≥0.11 | Direct from Hub id on `vllm/vllm-openai:v0.11.0`+ |
91
- | rednote-hilab/dots.ocr | ✅ (GitHub) | HF card shows a legacy pre-0.11 hack; GitHub README: integrated upstream since 0.11 |
92
- | tencent/HunyuanOCR | ✅ vLLM 0.18.1 | serve.sh in repo; nightly adds DFlash speculative decoding |
93
- | zai-org/GLM-OCR | ✅ vLLM + SGLang + Ollama | Only card here with an SGLang serve example; needs vLLM nightly |
94
- | numind/NuExtract3 | ✅ vLLM | Production-grade recipe: MTP speculative decoding, per-request `chat_template_kwargs` |
95
- | numind/NuMarkdown-8B-Thinking | ✅ vLLM | Thinking always on — parse `<think>`/`<answer>` |
96
- | baidu/Unlimited-OCR | ✅ vLLM + SGLang | Custom image / dev wheel; see [serving-unlimited-ocr.md](serving-unlimited-ocr.md) |
97
- | baidu/Qianfan-OCR | ✅ vLLM (minimal) | Needs `--hf-overrides '{"architectures": ["InternVLChatModel"]}'` |
98
- | PaddlePaddle/PaddleOCR-VL 1.x | ✅ paddle `genai_server` + vLLM recipe | Serves the 0.9B VLM only; raw serve skips the layout stage (official quality warning) |
99
- | deepseek-ai/DeepSeek-OCR / -2 | ⚠️ vLLM recipe pages only | docs.vllm.ai recipes; needs the DeepSeek n-gram logits processor flags |
100
- | allenai/olmOCR-2-7B-FP8 | ✅ (GitHub) | olmocr toolkit spawns `vllm serve` itself; YAML-front-matter prompt required |
101
- | reducto/RolmOCR | ✅ vLLM | Card serve + client (client's model string has a typo — pass `--served-model-name`) |
102
- | tiiuae/Falcon-OCR | ✅ vLLM in official Docker | `ghcr.io/tiiuae/falcon-ocr`; task-token prompts |
103
- | datalab-to/surya-ocr-2, lift | ⚠️ wrapper-mediated | Server-native but driven via their own managers (`SURYA_INFERENCE_URL`, `lift_vllm`) |
104
- | LiquidAI LFM2.5-VL-Extract | ⚠️ family docs | vLLM ≥0.23 + SGLang cookbooks, not Extract-specific |
105
- | ATH-MaaS/OvisOCR2 | ❌ offline vLLM only | `ovis-ocr2-server.py` is our translation of the card's offline args (parity-validated, table above) |
106
- | FireRedTeam/FireRed-OCR | ❌ transformers only | |
107
- | acvlab/ABot-OCR | ❌ offline script only | pinned vllm 0.18.0 |
108
-
109
- SGLang reality check: only GLM-OCR and Unlimited-OCR ship SGLang serve paths (olmOCR
110
- dropped SGLang for vLLM in v0.1.75). For this collection, "server mode" effectively
111
- means a vLLM OpenAI-compatible endpoint.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abot-ocr.py DELETED
@@ -1,600 +0,0 @@
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
- # ]
12
- #
13
- # ///
14
-
15
- """
16
- Convert document images to Markdown using ABot-OCR with vLLM.
17
-
18
- ABot-OCR (acvlab/ABot-OCR) is a compact Qwen3-VL-based document OCR model that
19
- converts PDF/document page images into structured Markdown, including:
20
- - Text with original document structure (headings, paragraphs, lists)
21
- - Mathematical formulas in LaTeX (inline \\( \\) and block \\[ \\])
22
- - Tables in HTML (<table>…</table>)
23
-
24
- Model: https://huggingface.co/acvlab/ABot-OCR
25
- Paper: https://arxiv.org/abs/2605.27978
26
- Code: https://github.com/amap-cvlab/ABot-OCR
27
-
28
- HF Jobs note: ABot-OCR (Qwen3-VL) uses vLLM's flashinfer sampler, which needs CUDA
29
- kernels the default uv-script image can't build ("Could not find nvcc"). Run on Jobs
30
- with the pre-built vLLM image so the kernels are reused (same image-mode pattern as
31
- nuextract3.py / paddleocr-vl-1.6.py):
32
- --image vllm/vllm-openai:latest
33
- --python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages
34
- """
35
-
36
- import argparse
37
- import base64
38
- import io
39
- import json
40
- import logging
41
- import os
42
- import sys
43
- from typing import Any, Dict, List, Union
44
- from datetime import datetime
45
-
46
- import torch
47
- from datasets import load_dataset
48
- from huggingface_hub import DatasetCard, login
49
- from PIL import Image
50
- from toolz import partition_all
51
- from tqdm.auto import tqdm
52
- # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
53
- # default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
54
- # lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
55
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
56
- from vllm import LLM, SamplingParams
57
-
58
- logging.basicConfig(level=logging.INFO)
59
- logger = logging.getLogger(__name__)
60
-
61
- # ABot-OCR's recommended document→Markdown prompt (from the model's reference
62
- # inference script; LaTeX delimiters de-mangled to proper \( \) and \[ \]).
63
- DEFAULT_PROMPT = r"""You are an AI assistant specialized in converting PDF images to Markdown format. Please follow these instructions for the conversion:
64
-
65
- 1. Text Processing:
66
- - Accurately recognize all text content in the PDF image without guessing or inferring.
67
- - Convert the recognized text into Markdown format.
68
- - Maintain the original document structure, including headings, paragraphs, lists, etc.
69
-
70
- 2. Mathematical Formula Processing:
71
- - Convert all mathematical formulas to LaTeX format.
72
- - Enclose inline formulas with \( \). For example: This is an inline formula \( E = mc^2 \)
73
- - Enclose block formulas with \[ \]. For example: \[ \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} \]
74
-
75
- 3. Table Processing:
76
- - Convert tables to HTML format.
77
- - Wrap the entire table with <table> and </table>.
78
-
79
- 4. Figure Handling:
80
- - Ignore figures content in the PDF image. Do not attempt to describe or convert images.
81
-
82
- 5. Output Format:
83
- - Ensure the output Markdown document has a clear structure with appropriate line breaks between elements.
84
- - For complex layouts, try to maintain the original document's structure and format as closely as possible.
85
-
86
- Please strictly follow these guidelines to ensure accuracy and consistency in the conversion. Your task is to accurately convert the content of the PDF image into Markdown format without adding any extra explanations or comments."""
87
-
88
-
89
- def check_cuda_availability():
90
- """Check if CUDA is available and exit if not."""
91
- if not torch.cuda.is_available():
92
- logger.error("CUDA is not available. This script requires a GPU.")
93
- logger.error("Please run on a machine with a CUDA-capable GPU.")
94
- sys.exit(1)
95
- else:
96
- logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
97
-
98
-
99
- def ensure_output_columns_free(dataset, columns, overwrite=False):
100
- """Fail fast if an output column would collide with an existing input column.
101
-
102
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
103
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
104
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
105
- column(s) here instead (logged) so the later add_column is clean.
106
- """
107
- clash = [c for c in columns if c in dataset.column_names]
108
- if not clash:
109
- return dataset
110
- if overwrite:
111
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
112
- return dataset.remove_columns(clash)
113
- logger.error(
114
- f"Output column(s) {clash} already exist in the input dataset "
115
- f"(columns: {dataset.column_names})."
116
- )
117
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
118
- sys.exit(1)
119
-
120
-
121
- def post_process_text(text: str, threshold: int = 8000) -> str:
122
- """Trim runaway repetition loops that VLM OCR can fall into on dense pages.
123
-
124
- Mirrors ABot-OCR's reference post-processing: if the tail of a long output
125
- repeats the same short substring many times, collapse it to a single copy.
126
- """
127
- n = len(text)
128
- if n < threshold:
129
- return text
130
- for length in range(2, n // 10 + 1):
131
- candidate = text[-length:]
132
- count = 0
133
- i = n - length
134
- while i >= 0 and text[i:i + length] == candidate:
135
- count += 1
136
- i -= length
137
- if count >= 10:
138
- return text[: n - length * (count - 1)]
139
- return text
140
-
141
-
142
- def make_ocr_message(
143
- image: Union[Image.Image, Dict[str, Any], str],
144
- prompt: str = DEFAULT_PROMPT,
145
- ) -> List[Dict]:
146
- """Create a vLLM chat message for OCR processing."""
147
- # Convert to PIL Image if needed
148
- if isinstance(image, Image.Image):
149
- pil_img = image
150
- elif isinstance(image, dict) and "bytes" in image:
151
- pil_img = Image.open(io.BytesIO(image["bytes"]))
152
- elif isinstance(image, str):
153
- pil_img = Image.open(image)
154
- else:
155
- raise ValueError(f"Unsupported image type: {type(image)}")
156
-
157
- if pil_img.mode != "RGB":
158
- pil_img = pil_img.convert("RGB")
159
-
160
- # Convert to base64 data URI
161
- buf = io.BytesIO()
162
- pil_img.save(buf, format="PNG")
163
- data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
164
-
165
- return [
166
- {
167
- "role": "user",
168
- "content": [
169
- {"type": "image_url", "image_url": {"url": data_uri}},
170
- {"type": "text", "text": prompt},
171
- ],
172
- }
173
- ]
174
-
175
-
176
- def create_dataset_card(
177
- source_dataset: str,
178
- model: str,
179
- num_samples: int,
180
- processing_time: str,
181
- batch_size: int,
182
- max_model_len: int,
183
- max_tokens: int,
184
- gpu_memory_utilization: float,
185
- image_column: str = "image",
186
- split: str = "train",
187
- ) -> str:
188
- """Create a dataset card documenting the OCR process."""
189
- model_name = model.split("/")[-1]
190
-
191
- return f"""---
192
- tags:
193
- - ocr
194
- - document-processing
195
- - abot
196
- - abot-ocr
197
- - markdown
198
- - uv-script
199
- - generated
200
- ---
201
-
202
- # Document OCR using {model_name}
203
-
204
- This dataset contains Markdown-formatted OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using [ABot-OCR](https://huggingface.co/{model}).
205
-
206
- ## Processing Details
207
-
208
- - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
209
- - **Model**: [{model}](https://huggingface.co/{model})
210
- - **Paper**: [arxiv.org/abs/2605.27978](https://arxiv.org/abs/2605.27978)
211
- - **Number of Samples**: {num_samples:,}
212
- - **Processing Time**: {processing_time}
213
- - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
214
-
215
- ### Configuration
216
-
217
- - **Image Column**: `{image_column}`
218
- - **Output Column**: `markdown`
219
- - **Dataset Split**: `{split}`
220
- - **Batch Size**: {batch_size}
221
- - **Max Model Length**: {max_model_len:,} tokens
222
- - **Max Output Tokens**: {max_tokens:,}
223
- - **GPU Memory Utilization**: {gpu_memory_utilization:.1%}
224
-
225
- ## Model Information
226
-
227
- ABot-OCR is a compact Qwen3-VL-based document OCR model that converts page images to Markdown:
228
- - 📐 **LaTeX equations** — inline `\\( \\)` and block `\\[ \\]`
229
- - 📊 **Tables** — extracted as HTML (`<table>…</table>`)
230
- - 📝 **Document structure** — headings, paragraphs, and lists preserved
231
-
232
- ## Dataset Structure
233
-
234
- The dataset contains all original columns plus:
235
- - `markdown`: The extracted text in Markdown format with preserved structure
236
- - `inference_info`: JSON list tracking all OCR models applied to this dataset
237
-
238
- ## Usage
239
-
240
- ```python
241
- from datasets import load_dataset
242
-
243
- dataset = load_dataset("{{{{output_dataset_id}}}}", split="{split}")
244
- for example in dataset:
245
- print(example["markdown"])
246
- break
247
- ```
248
-
249
- ## Reproduction
250
-
251
- This dataset was generated using the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) ABot-OCR script:
252
-
253
- ```bash
254
- uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/abot-ocr.py \\
255
- {source_dataset} \\
256
- <output-dataset> \\
257
- --image-column {image_column} \\
258
- --batch-size {batch_size} \\
259
- --max-model-len {max_model_len} \\
260
- --max-tokens {max_tokens} \\
261
- --gpu-memory-utilization {gpu_memory_utilization}
262
- ```
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
- model: str = "acvlab/ABot-OCR",
274
- max_model_len: int = 16384,
275
- max_tokens: int = 8192,
276
- gpu_memory_utilization: float = 0.8,
277
- hf_token: str = None,
278
- split: str = "train",
279
- max_samples: int = None,
280
- private: bool = False,
281
- shuffle: bool = False,
282
- seed: int = 42,
283
- output_column: str = "markdown",
284
- overwrite: bool = False,
285
- verbose: bool = False,
286
- ):
287
- """Process images from a HF dataset through the ABot-OCR model."""
288
-
289
- # Check CUDA availability first
290
- check_cuda_availability()
291
-
292
- # Track processing start time
293
- start_time = datetime.now()
294
-
295
- # Enable high-performance Xet downloads
296
- os.environ["HF_XET_HIGH_PERFORMANCE"] = "1"
297
-
298
- # Login to HF if token provided
299
- HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
300
- if HF_TOKEN:
301
- login(token=HF_TOKEN)
302
-
303
- # Load dataset
304
- logger.info(f"Loading dataset: {input_dataset}")
305
- dataset = load_dataset(input_dataset, split=split)
306
-
307
- # Validate image column
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
- # Shuffle if requested
317
- if shuffle:
318
- logger.info(f"Shuffling dataset with seed {seed}")
319
- dataset = dataset.shuffle(seed=seed)
320
-
321
- # Limit samples if requested
322
- if max_samples:
323
- dataset = dataset.select(range(min(max_samples, len(dataset))))
324
- logger.info(f"Limited to {len(dataset)} samples")
325
-
326
- # Initialize vLLM
327
- logger.info(f"Initializing vLLM with model: {model}")
328
- llm = LLM(
329
- model=model,
330
- trust_remote_code=True,
331
- max_model_len=max_model_len,
332
- gpu_memory_utilization=gpu_memory_utilization,
333
- limit_mm_per_prompt={"image": 1},
334
- enforce_eager=True, # avoid warmup kernel compilation (no nvcc in the image)
335
- )
336
-
337
- sampling_params = SamplingParams(
338
- temperature=0.0, # Deterministic for OCR
339
- max_tokens=max_tokens,
340
- )
341
-
342
- # Process images in batches
343
- all_markdown = []
344
-
345
- logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
346
-
347
- for batch_indices in tqdm(
348
- partition_all(batch_size, range(len(dataset))),
349
- total=(len(dataset) + batch_size - 1) // batch_size,
350
- desc="OCR processing",
351
- ):
352
- batch_indices = list(batch_indices)
353
- batch_images = [dataset[i][image_column] for i in batch_indices]
354
-
355
- try:
356
- batch_messages = [make_ocr_message(img) for img in batch_images]
357
- outputs = llm.chat(batch_messages, sampling_params)
358
- for output in outputs:
359
- markdown_text = post_process_text(output.outputs[0].text.strip())
360
- all_markdown.append(markdown_text)
361
- except Exception as e:
362
- logger.error(f"Error processing batch: {e}")
363
- all_markdown.extend(["[OCR FAILED]"] * len(batch_images))
364
-
365
- # Add output column to dataset
366
- logger.info(f"Adding '{output_column}' column to dataset")
367
- dataset = dataset.add_column(output_column, all_markdown)
368
-
369
- # Handle inference_info tracking
370
- logger.info("Updating inference_info...")
371
-
372
- inference_entry = {
373
- "model_id": model,
374
- "model_name": "ABot-OCR",
375
- "column_name": output_column,
376
- "timestamp": datetime.now().isoformat(),
377
- "batch_size": batch_size,
378
- "max_tokens": max_tokens,
379
- "gpu_memory_utilization": gpu_memory_utilization,
380
- "max_model_len": max_model_len,
381
- "script": "abot-ocr.py",
382
- "script_url": "https://huggingface.co/datasets/uv-scripts/ocr/raw/main/abot-ocr.py",
383
- }
384
-
385
- if "inference_info" in dataset.column_names:
386
- logger.info("Updating existing inference_info column")
387
-
388
- def update_inference_info(example):
389
- try:
390
- existing_info = (
391
- json.loads(example["inference_info"])
392
- if example["inference_info"]
393
- else []
394
- )
395
- except (json.JSONDecodeError, TypeError):
396
- existing_info = []
397
- existing_info.append(inference_entry)
398
- return {"inference_info": json.dumps(existing_info)}
399
-
400
- dataset = dataset.map(update_inference_info)
401
- else:
402
- logger.info("Creating new inference_info column")
403
- inference_list = [json.dumps([inference_entry])] * len(dataset)
404
- dataset = dataset.add_column("inference_info", inference_list)
405
-
406
- # Push to hub
407
- logger.info(f"Pushing to {output_dataset}")
408
- dataset.push_to_hub(output_dataset, private=private, token=HF_TOKEN)
409
-
410
- # Calculate processing time
411
- end_time = datetime.now()
412
- processing_duration = end_time - start_time
413
- processing_time = f"{processing_duration.total_seconds() / 60:.1f} minutes"
414
-
415
- # Create and push dataset card
416
- logger.info("Creating dataset card...")
417
- card_content = create_dataset_card(
418
- source_dataset=input_dataset,
419
- model=model,
420
- num_samples=len(dataset),
421
- processing_time=processing_time,
422
- batch_size=batch_size,
423
- max_model_len=max_model_len,
424
- max_tokens=max_tokens,
425
- gpu_memory_utilization=gpu_memory_utilization,
426
- image_column=image_column,
427
- split=split,
428
- )
429
-
430
- card = DatasetCard(card_content)
431
- card.push_to_hub(output_dataset, token=HF_TOKEN)
432
- logger.info("✅ Dataset card created and pushed!")
433
-
434
- logger.info("✅ OCR conversion complete!")
435
- logger.info(
436
- f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
437
- )
438
-
439
- if verbose:
440
- import importlib.metadata
441
-
442
- logger.info("--- Resolved package versions ---")
443
- for pkg in ["vllm", "transformers", "torch", "datasets", "pyarrow", "pillow"]:
444
- try:
445
- logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
446
- except importlib.metadata.PackageNotFoundError:
447
- logger.info(f" {pkg}: not installed")
448
- logger.info("--- End versions ---")
449
-
450
-
451
- if __name__ == "__main__":
452
- # Show example usage if no arguments
453
- if len(sys.argv) == 1:
454
- print("=" * 80)
455
- print("ABot-OCR to Markdown Converter")
456
- print("=" * 80)
457
- print("\nConverts document images to structured Markdown using the")
458
- print("ABot-OCR model (Qwen3-VL based) with vLLM acceleration.")
459
- print("\nFeatures:")
460
- print("- Document structure preserved (headings, paragraphs, lists)")
461
- print("- LaTeX equation recognition (inline \\( \\) and block \\[ \\])")
462
- print("- Table extraction as HTML")
463
- print("\nExample usage:")
464
- print("\n1. Basic OCR conversion:")
465
- print(" uv run abot-ocr.py document-images markdown-docs")
466
- print("\n2. Process a subset for testing:")
467
- print(" uv run abot-ocr.py large-dataset test-output --max-samples 10")
468
- print("\n3. Running on HF Jobs (use the pre-built vLLM image for flashinfer kernels):")
469
- print(" hf jobs uv run --flavor l4x1 \\")
470
- print(" --image vllm/vllm-openai:latest \\")
471
- print(
472
- " --python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\"
473
- )
474
- print(" -s HF_TOKEN \\")
475
- print(
476
- " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/abot-ocr.py \\"
477
- )
478
- print(" your-document-dataset \\")
479
- print(" your-markdown-output \\")
480
- print(" --max-samples 10")
481
- print("\n" + "=" * 80)
482
- print("\nFor full help, run: uv run abot-ocr.py --help")
483
- sys.exit(0)
484
-
485
- parser = argparse.ArgumentParser(
486
- description="OCR images to Markdown using ABot-OCR (Qwen3-VL)",
487
- formatter_class=argparse.RawDescriptionHelpFormatter,
488
- epilog="""
489
- Examples:
490
- # Basic usage
491
- uv run abot-ocr.py my-images-dataset ocr-results
492
-
493
- # With specific image column
494
- uv run abot-ocr.py documents extracted-text --image-column scan
495
-
496
- # Process subset for testing
497
- uv run abot-ocr.py large-dataset test-output --max-samples 100
498
-
499
- # Random sample from ordered dataset
500
- uv run abot-ocr.py ordered-dataset random-sample --max-samples 50 --shuffle
501
- """,
502
- )
503
-
504
- parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
505
- parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
506
- parser.add_argument(
507
- "--image-column",
508
- default="image",
509
- help="Column containing images (default: image)",
510
- )
511
- parser.add_argument(
512
- "--batch-size",
513
- type=int,
514
- default=16,
515
- help="Batch size for processing (default: 16)",
516
- )
517
- parser.add_argument(
518
- "--model",
519
- default="acvlab/ABot-OCR",
520
- help="Model to use (default: acvlab/ABot-OCR)",
521
- )
522
- parser.add_argument(
523
- "--max-model-len",
524
- type=int,
525
- default=16384,
526
- help="Maximum model context length (default: 16384)",
527
- )
528
- parser.add_argument(
529
- "--max-tokens",
530
- type=int,
531
- default=8192,
532
- help="Maximum tokens to generate (default: 8192)",
533
- )
534
- parser.add_argument(
535
- "--gpu-memory-utilization",
536
- type=float,
537
- default=0.8,
538
- help="GPU memory utilization (default: 0.8)",
539
- )
540
- parser.add_argument("--hf-token", help="Hugging Face API token")
541
- parser.add_argument(
542
- "--split", default="train", help="Dataset split to use (default: train)"
543
- )
544
- parser.add_argument(
545
- "--max-samples",
546
- type=int,
547
- help="Maximum number of samples to process (for testing)",
548
- )
549
- parser.add_argument(
550
- "--private", action="store_true", help="Make output dataset private"
551
- )
552
- parser.add_argument(
553
- "--shuffle",
554
- action="store_true",
555
- help="Shuffle the dataset before processing (useful for random sampling)",
556
- )
557
- parser.add_argument(
558
- "--seed",
559
- type=int,
560
- default=42,
561
- help="Random seed for shuffling (default: 42)",
562
- )
563
- parser.add_argument(
564
- "--output-column",
565
- default="markdown",
566
- help="Column name for the OCR output text (default: markdown)",
567
- )
568
- parser.add_argument(
569
- "--overwrite",
570
- action="store_true",
571
- help="Replace the output column if it already exists in the input dataset "
572
- "(default: error out to avoid clobbering an existing column).",
573
- )
574
- parser.add_argument(
575
- "--verbose",
576
- action="store_true",
577
- help="Log resolved package versions after processing (useful for pinning deps)",
578
- )
579
-
580
- args = parser.parse_args()
581
-
582
- main(
583
- input_dataset=args.input_dataset,
584
- output_dataset=args.output_dataset,
585
- image_column=args.image_column,
586
- batch_size=args.batch_size,
587
- model=args.model,
588
- max_model_len=args.max_model_len,
589
- max_tokens=args.max_tokens,
590
- gpu_memory_utilization=args.gpu_memory_utilization,
591
- hf_token=args.hf_token,
592
- split=args.split,
593
- max_samples=args.max_samples,
594
- private=args.private,
595
- shuffle=args.shuffle,
596
- seed=args.seed,
597
- output_column=args.output_column,
598
- overwrite=args.overwrite,
599
- verbose=args.verbose,
600
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deepseek-ocr-vllm.py CHANGED
@@ -1,19 +1,14 @@
1
  # /// script
2
  # requires-python = ">=3.11"
3
  # dependencies = [
4
- # "datasets>=4.0.0,<5.1", # 5.1 needs huggingface_hub>=1.31; the image ships an older 1.x on PYTHONPATH, which wins
5
  # "huggingface-hub",
6
  # "pillow",
 
7
  # "tqdm",
8
  # "toolz",
 
9
  # ]
10
- #
11
- # [tool.hf-jobs]
12
- # image = "vllm/vllm-openai:v0.29.0"
13
- # python = "/usr/bin/python3"
14
- # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
15
- # flavor = "a10g-small"
16
- # secrets = ["HF_TOKEN"]
17
  # ///
18
 
19
  """
@@ -26,11 +21,8 @@ Uses the official vLLM offline pattern: llm.generate() with PIL images
26
  and NGramPerReqLogitsProcessor to prevent repetition on complex documents.
27
  See: https://docs.vllm.ai/projects/recipes/en/latest/DeepSeek/DeepSeek-OCR.html
28
 
29
- Run on HF Jobs. vLLM and torch come from the vllm/vllm-openai:v0.29.0 image declared
30
- in the [tool.hf-jobs] header (`hf` CLI 1.32+), which also sets the hardware and the
31
- HF_TOKEN secret. The tag is pinned: vLLM 0.30 breaks the DeepEncoder Triton kernel
32
- (LOG2E NameError), and nightly wheels moved the logits-processor API. Pass --timeout
33
- for a long run. To run on your own GPU: `uv run --with vllm==0.29.0 deepseek-ocr-vllm.py ...`.
34
 
35
  Features:
36
  - LaTeX equation recognition
@@ -56,10 +48,6 @@ from huggingface_hub import DatasetCard, login
56
  from PIL import Image
57
  from toolz import partition_all
58
  from tqdm.auto import tqdm
59
- # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
60
- # default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
61
- # lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
62
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
63
  from vllm import LLM, SamplingParams
64
  from vllm.model_executor.models.deepseek_ocr import NGramPerReqLogitsProcessor
65
 
@@ -86,28 +74,6 @@ def check_cuda_availability():
86
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
87
 
88
 
89
- def ensure_output_columns_free(dataset, columns, overwrite=False):
90
- """Fail fast if an output column would collide with an existing input column.
91
-
92
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
93
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
94
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
95
- column(s) here instead (logged) so the later add_column is clean.
96
- """
97
- clash = [c for c in columns if c in dataset.column_names]
98
- if not clash:
99
- return dataset
100
- if overwrite:
101
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
102
- return dataset.remove_columns(clash)
103
- logger.error(
104
- f"Output column(s) {clash} already exist in the input dataset "
105
- f"(columns: {dataset.column_names})."
106
- )
107
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
108
- sys.exit(1)
109
-
110
-
111
  def to_pil(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:
112
  """Convert various image formats to PIL Image."""
113
  if isinstance(image, Image.Image):
@@ -241,8 +207,6 @@ def main(
241
  private: bool = False,
242
  shuffle: bool = False,
243
  seed: int = 42,
244
- output_column: str = "markdown",
245
- overwrite: bool = False,
246
  config: str = None,
247
  create_pr: bool = False,
248
  verbose: bool = False,
@@ -285,9 +249,6 @@ def main(
285
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
286
  )
287
 
288
- # Fail fast if the output column would collide with an existing input column
289
- dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
290
-
291
  # Shuffle if requested
292
  if shuffle:
293
  logger.info(f"Shuffling dataset with seed {seed}")
@@ -361,9 +322,9 @@ def main(
361
  processing_duration = datetime.now() - start_time
362
  processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
363
 
364
- # Add output column to dataset
365
- logger.info(f"Adding '{output_column}' column to dataset")
366
- dataset = dataset.add_column(output_column, all_markdown)
367
 
368
  # Handle inference_info tracking
369
  logger.info("Updating inference_info...")
@@ -371,7 +332,7 @@ def main(
371
  inference_entry = {
372
  "model_id": model,
373
  "model_name": "DeepSeek-OCR",
374
- "column_name": output_column,
375
  "timestamp": datetime.now().isoformat(),
376
  "prompt_mode": prompt_mode if prompt is None else "custom",
377
  "batch_size": batch_size,
@@ -481,8 +442,8 @@ if __name__ == "__main__":
481
  " uv run deepseek-ocr-vllm.py large-dataset test-output --max-samples 10"
482
  )
483
  print("\n5. Running on HF Jobs:")
484
- print(" (image, hardware and HF_TOKEN come from the script's [tool.hf-jobs] header)")
485
- print(" hf jobs uv run \\")
486
  print(
487
  " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr-vllm.py \\"
488
  )
@@ -520,7 +481,7 @@ Examples:
520
  uv run deepseek-ocr-vllm.py dataset output --batch-size 16 --max-model-len 16384
521
 
522
  # Running on HF Jobs
523
- hf jobs uv run \\
524
  https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr-vllm.py \\
525
  my-dataset my-output --max-samples 10
526
  """,
@@ -604,17 +565,6 @@ Examples:
604
  default=42,
605
  help="Random seed for shuffling (default: 42)",
606
  )
607
- parser.add_argument(
608
- "--output-column",
609
- default="markdown",
610
- help="Column name for the OCR output text (default: markdown)",
611
- )
612
- parser.add_argument(
613
- "--overwrite",
614
- action="store_true",
615
- help="Replace the output column if it already exists in the input dataset "
616
- "(default: error out to avoid clobbering an existing column).",
617
- )
618
  parser.add_argument(
619
  "--verbose",
620
  action="store_true",
@@ -640,8 +590,6 @@ Examples:
640
  private=args.private,
641
  shuffle=args.shuffle,
642
  seed=args.seed,
643
- output_column=args.output_column,
644
- overwrite=args.overwrite,
645
  config=args.config,
646
  create_pr=args.create_pr,
647
  verbose=args.verbose,
 
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
  # ]
 
 
 
 
 
 
 
12
  # ///
13
 
14
  """
 
21
  and NGramPerReqLogitsProcessor to prevent repetition on complex documents.
22
  See: https://docs.vllm.ai/projects/recipes/en/latest/DeepSeek/DeepSeek-OCR.html
23
 
24
+ NOTE: Uses vLLM nightly wheels. First run may take a few minutes to download
25
+ and install dependencies.
 
 
 
26
 
27
  Features:
28
  - LaTeX equation recognition
 
48
  from PIL import Image
49
  from toolz import partition_all
50
  from tqdm.auto import tqdm
 
 
 
 
51
  from vllm import LLM, SamplingParams
52
  from vllm.model_executor.models.deepseek_ocr import NGramPerReqLogitsProcessor
53
 
 
74
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
75
 
76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  def to_pil(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:
78
  """Convert various image formats to PIL Image."""
79
  if isinstance(image, Image.Image):
 
207
  private: bool = False,
208
  shuffle: bool = False,
209
  seed: int = 42,
 
 
210
  config: str = None,
211
  create_pr: bool = False,
212
  verbose: bool = False,
 
249
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
250
  )
251
 
 
 
 
252
  # Shuffle if requested
253
  if shuffle:
254
  logger.info(f"Shuffling dataset with seed {seed}")
 
322
  processing_duration = datetime.now() - start_time
323
  processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
324
 
325
+ # Add markdown column to dataset
326
+ logger.info("Adding markdown column to dataset")
327
+ dataset = dataset.add_column("markdown", all_markdown)
328
 
329
  # Handle inference_info tracking
330
  logger.info("Updating inference_info...")
 
332
  inference_entry = {
333
  "model_id": model,
334
  "model_name": "DeepSeek-OCR",
335
+ "column_name": "markdown",
336
  "timestamp": datetime.now().isoformat(),
337
  "prompt_mode": prompt_mode if prompt is None else "custom",
338
  "batch_size": batch_size,
 
442
  " uv run deepseek-ocr-vllm.py large-dataset test-output --max-samples 10"
443
  )
444
  print("\n5. Running on HF Jobs:")
445
+ print(" hf jobs uv run --flavor l4x1 \\")
446
+ print(" -s HF_TOKEN \\")
447
  print(
448
  " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr-vllm.py \\"
449
  )
 
481
  uv run deepseek-ocr-vllm.py dataset output --batch-size 16 --max-model-len 16384
482
 
483
  # Running on HF Jobs
484
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
485
  https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr-vllm.py \\
486
  my-dataset my-output --max-samples 10
487
  """,
 
565
  default=42,
566
  help="Random seed for shuffling (default: 42)",
567
  )
 
 
 
 
 
 
 
 
 
 
 
568
  parser.add_argument(
569
  "--verbose",
570
  action="store_true",
 
590
  private=args.private,
591
  shuffle=args.shuffle,
592
  seed=args.seed,
 
 
593
  config=args.config,
594
  create_pr=args.create_pr,
595
  verbose=args.verbose,
deepseek-ocr.py CHANGED
@@ -1,8 +1,8 @@
1
  # /// script
2
  # requires-python = ">=3.11"
3
  # dependencies = [
4
- # "datasets>=4.0.0",
5
- # "huggingface-hub",
6
  # "pillow",
7
  # "torch",
8
  # "torchvision",
@@ -18,8 +18,6 @@
18
  # ///
19
 
20
  """
21
- UNSUPPORTED: Broken (2026-09-23): every output row is the string 'None' (model.infer returns None). Use deepseek-ocr-vllm.py. See models.json (`support`).
22
-
23
  Convert document images to markdown using DeepSeek-OCR with Transformers.
24
 
25
  This script processes images through the DeepSeek-OCR model to extract
@@ -78,28 +76,6 @@ def check_cuda_availability():
78
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
79
 
80
 
81
- def ensure_output_columns_free(dataset, columns, overwrite=False):
82
- """Fail fast if an output column would collide with an existing input column.
83
-
84
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
85
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
86
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
87
- column(s) here instead (logged) so the later add_column is clean.
88
- """
89
- clash = [c for c in columns if c in dataset.column_names]
90
- if not clash:
91
- return dataset
92
- if overwrite:
93
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
94
- return dataset.remove_columns(clash)
95
- logger.error(
96
- f"Output column(s) {clash} already exist in the input dataset "
97
- f"(columns: {dataset.column_names})."
98
- )
99
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
100
- sys.exit(1)
101
-
102
-
103
  def create_dataset_card(
104
  source_dataset: str,
105
  model: str,
@@ -267,8 +243,6 @@ def main(
267
  private: bool = False,
268
  shuffle: bool = False,
269
  seed: int = 42,
270
- output_column: str = "markdown",
271
- overwrite: bool = False,
272
  ):
273
  """Process images from HF dataset through DeepSeek-OCR model."""
274
 
@@ -278,7 +252,8 @@ def main(
278
  # Track processing start time
279
  start_time = datetime.now()
280
 
281
-
 
282
 
283
  # Login to HF if token provided
284
  HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
@@ -320,9 +295,6 @@ def main(
320
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
321
  )
322
 
323
- # Fail fast if the output column would collide with an existing input column
324
- dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
325
-
326
  # Shuffle if requested
327
  if shuffle:
328
  logger.info(f"Shuffling dataset with seed {seed}")
@@ -408,12 +380,12 @@ def main(
408
  try:
409
  shutil.rmtree(temp_dir)
410
  shutil.rmtree(temp_output_dir)
411
- except Exception:
412
  pass
413
 
414
- # Add output column to dataset
415
- logger.info(f"Adding '{output_column}' column to dataset")
416
- dataset = dataset.add_column(output_column, all_markdown)
417
 
418
  # Handle inference_info tracking
419
  logger.info("Updating inference_info...")
@@ -432,7 +404,7 @@ def main(
432
 
433
  # Add new inference info
434
  new_info = {
435
- "column_name": output_column,
436
  "model_id": model,
437
  "processing_date": datetime.now().isoformat(),
438
  "resolution_mode": resolution_mode,
@@ -610,17 +582,6 @@ Examples:
610
  default=42,
611
  help="Random seed for shuffling (default: 42)",
612
  )
613
- parser.add_argument(
614
- "--output-column",
615
- default="markdown",
616
- help="Column name for the OCR output text (default: markdown)",
617
- )
618
- parser.add_argument(
619
- "--overwrite",
620
- action="store_true",
621
- help="Replace the output column if it already exists in the input dataset "
622
- "(default: error out to avoid clobbering an existing column).",
623
- )
624
 
625
  args = parser.parse_args()
626
 
@@ -640,6 +601,4 @@ Examples:
640
  private=args.private,
641
  shuffle=args.shuffle,
642
  seed=args.seed,
643
- output_column=args.output_column,
644
- overwrite=args.overwrite,
645
  )
 
1
  # /// script
2
  # requires-python = ">=3.11"
3
  # dependencies = [
4
+ # "datasets",
5
+ # "huggingface-hub[hf_transfer]",
6
  # "pillow",
7
  # "torch",
8
  # "torchvision",
 
18
  # ///
19
 
20
  """
 
 
21
  Convert document images to markdown using DeepSeek-OCR with Transformers.
22
 
23
  This script processes images through the DeepSeek-OCR model to extract
 
76
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
77
 
78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  def create_dataset_card(
80
  source_dataset: str,
81
  model: str,
 
243
  private: bool = False,
244
  shuffle: bool = False,
245
  seed: int = 42,
 
 
246
  ):
247
  """Process images from HF dataset through DeepSeek-OCR model."""
248
 
 
252
  # Track processing start time
253
  start_time = datetime.now()
254
 
255
+ # Enable HF_TRANSFER for faster downloads
256
+ os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
257
 
258
  # Login to HF if token provided
259
  HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
 
295
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
296
  )
297
 
 
 
 
298
  # Shuffle if requested
299
  if shuffle:
300
  logger.info(f"Shuffling dataset with seed {seed}")
 
380
  try:
381
  shutil.rmtree(temp_dir)
382
  shutil.rmtree(temp_output_dir)
383
+ except:
384
  pass
385
 
386
+ # Add markdown column to dataset
387
+ logger.info("Adding markdown column to dataset")
388
+ dataset = dataset.add_column("markdown", all_markdown)
389
 
390
  # Handle inference_info tracking
391
  logger.info("Updating inference_info...")
 
404
 
405
  # Add new inference info
406
  new_info = {
407
+ "column_name": "markdown",
408
  "model_id": model,
409
  "processing_date": datetime.now().isoformat(),
410
  "resolution_mode": resolution_mode,
 
582
  default=42,
583
  help="Random seed for shuffling (default: 42)",
584
  )
 
 
 
 
 
 
 
 
 
 
 
585
 
586
  args = parser.parse_args()
587
 
 
601
  private=args.private,
602
  shuffle=args.shuffle,
603
  seed=args.seed,
 
 
604
  )
deepseek-ocr2-vllm.py CHANGED
@@ -1,21 +1,22 @@
1
  # /// script
2
  # requires-python = ">=3.11"
3
  # dependencies = [
4
- # "datasets>=4.0.0,<5.1", # 5.1 needs huggingface_hub>=1.31; the image ships an older 1.x on PYTHONPATH, which wins
5
  # "huggingface-hub",
6
  # "pillow",
 
7
  # "tqdm",
8
  # "toolz",
 
9
  # "addict",
10
  # "matplotlib",
11
  # ]
12
  #
13
- # [tool.hf-jobs]
14
- # image = "vllm/vllm-openai:v0.29.0"
15
- # python = "/usr/bin/python3"
16
- # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
17
- # flavor = "a10g-small"
18
- # secrets = ["HF_TOKEN"]
19
  # ///
20
 
21
  """
@@ -29,11 +30,8 @@ Uses the official vLLM offline pattern: llm.generate() with PIL images
29
  and NGramPerReqLogitsProcessor to prevent repetition on complex documents.
30
  See: https://docs.vllm.ai/projects/recipes/en/latest/DeepSeek/DeepSeek-OCR.html
31
 
32
- Run on HF Jobs. vLLM and torch come from the vllm/vllm-openai:v0.29.0 image declared
33
- in the [tool.hf-jobs] header (`hf` CLI 1.32+), which also sets the hardware and the
34
- HF_TOKEN secret. The tag is pinned: vLLM 0.30 breaks the DeepEncoder Triton kernel
35
- (LOG2E NameError), and nightly wheels moved the logits-processor API. Pass --timeout
36
- for a long run. To run on your own GPU: `uv run --with vllm==0.29.0 deepseek-ocr2-vllm.py ...`.
37
 
38
  Features:
39
  - Visual Causal Flow architecture for enhanced visual encoding
@@ -61,10 +59,6 @@ from huggingface_hub import DatasetCard, login
61
  from PIL import Image
62
  from toolz import partition_all
63
  from tqdm.auto import tqdm
64
- # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
65
- # default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
66
- # lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
67
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
68
  from vllm import LLM, SamplingParams
69
  from vllm.model_executor.models.deepseek_ocr import NGramPerReqLogitsProcessor
70
 
@@ -88,28 +82,6 @@ def check_cuda_availability():
88
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
89
 
90
 
91
- def ensure_output_columns_free(dataset, columns, overwrite=False):
92
- """Fail fast if an output column would collide with an existing input column.
93
-
94
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
95
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
96
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
97
- column(s) here instead (logged) so the later add_column is clean.
98
- """
99
- clash = [c for c in columns if c in dataset.column_names]
100
- if not clash:
101
- return dataset
102
- if overwrite:
103
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
104
- return dataset.remove_columns(clash)
105
- logger.error(
106
- f"Output column(s) {clash} already exist in the input dataset "
107
- f"(columns: {dataset.column_names})."
108
- )
109
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
110
- sys.exit(1)
111
-
112
-
113
  def to_pil(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:
114
  """Convert various image formats to PIL Image."""
115
  if isinstance(image, Image.Image):
@@ -249,7 +221,6 @@ def main(
249
  shuffle: bool = False,
250
  seed: int = 42,
251
  output_column: str = "markdown",
252
- overwrite: bool = False,
253
  config: str = None,
254
  create_pr: bool = False,
255
  verbose: bool = False,
@@ -292,9 +263,6 @@ def main(
292
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
293
  )
294
 
295
- # Fail fast if the output column would collide with an existing input column
296
- dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
297
-
298
  # Shuffle if requested
299
  if shuffle:
300
  logger.info(f"Shuffling dataset with seed {seed}")
@@ -500,8 +468,8 @@ if __name__ == "__main__":
500
  " uv run deepseek-ocr2-vllm.py large-dataset test-output --max-samples 10"
501
  )
502
  print("\n4. Running on HF Jobs:")
503
- print(" (image, hardware and HF_TOKEN come from the script's [tool.hf-jobs] header)")
504
- print(" hf jobs uv run \\")
505
  print(
506
  " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr2-vllm.py \\"
507
  )
@@ -533,7 +501,7 @@ Examples:
533
  uv run deepseek-ocr2-vllm.py dataset output --batch-size 16 --max-model-len 16384
534
 
535
  # Running on HF Jobs
536
- hf jobs uv run \\
537
  https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr2-vllm.py \\
538
  my-dataset my-output --max-samples 10
539
  """,
@@ -602,12 +570,6 @@ Examples:
602
  default="markdown",
603
  help="Column name for OCR output (default: markdown). Use a different name to add alongside existing OCR.",
604
  )
605
- parser.add_argument(
606
- "--overwrite",
607
- action="store_true",
608
- help="Replace the output column if it already exists in the input dataset "
609
- "(default: error out to avoid clobbering an existing column).",
610
- )
611
  parser.add_argument(
612
  "--shuffle",
613
  action="store_true",
@@ -654,7 +616,6 @@ Examples:
654
  shuffle=args.shuffle,
655
  seed=args.seed,
656
  output_column=args.output_column,
657
- overwrite=args.overwrite,
658
  config=args.config,
659
  create_pr=args.create_pr,
660
  verbose=args.verbose,
 
1
  # /// script
2
  # requires-python = ">=3.11"
3
  # dependencies = [
4
+ # "datasets>=4.0.0",
5
  # "huggingface-hub",
6
  # "pillow",
7
+ # "vllm",
8
  # "tqdm",
9
  # "toolz",
10
+ # "torch",
11
  # "addict",
12
  # "matplotlib",
13
  # ]
14
  #
15
+ # [[tool.uv.index]]
16
+ # url = "https://wheels.vllm.ai/nightly/cu129"
17
+ #
18
+ # [tool.uv]
19
+ # prerelease = "allow"
 
20
  # ///
21
 
22
  """
 
30
  and NGramPerReqLogitsProcessor to prevent repetition on complex documents.
31
  See: https://docs.vllm.ai/projects/recipes/en/latest/DeepSeek/DeepSeek-OCR.html
32
 
33
+ NOTE: Uses vLLM nightly wheels. First run may take a few minutes to download
34
+ and install dependencies.
 
 
 
35
 
36
  Features:
37
  - Visual Causal Flow architecture for enhanced visual encoding
 
59
  from PIL import Image
60
  from toolz import partition_all
61
  from tqdm.auto import tqdm
 
 
 
 
62
  from vllm import LLM, SamplingParams
63
  from vllm.model_executor.models.deepseek_ocr import NGramPerReqLogitsProcessor
64
 
 
82
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
83
 
84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  def to_pil(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:
86
  """Convert various image formats to PIL Image."""
87
  if isinstance(image, Image.Image):
 
221
  shuffle: bool = False,
222
  seed: int = 42,
223
  output_column: str = "markdown",
 
224
  config: str = None,
225
  create_pr: bool = False,
226
  verbose: bool = False,
 
263
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
264
  )
265
 
 
 
 
266
  # Shuffle if requested
267
  if shuffle:
268
  logger.info(f"Shuffling dataset with seed {seed}")
 
468
  " uv run deepseek-ocr2-vllm.py large-dataset test-output --max-samples 10"
469
  )
470
  print("\n4. Running on HF Jobs:")
471
+ print(" hf jobs uv run --flavor l4x1 \\")
472
+ print(" -s HF_TOKEN \\")
473
  print(
474
  " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr2-vllm.py \\"
475
  )
 
501
  uv run deepseek-ocr2-vllm.py dataset output --batch-size 16 --max-model-len 16384
502
 
503
  # Running on HF Jobs
504
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
505
  https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr2-vllm.py \\
506
  my-dataset my-output --max-samples 10
507
  """,
 
570
  default="markdown",
571
  help="Column name for OCR output (default: markdown). Use a different name to add alongside existing OCR.",
572
  )
 
 
 
 
 
 
573
  parser.add_argument(
574
  "--shuffle",
575
  action="store_true",
 
616
  shuffle=args.shuffle,
617
  seed=args.seed,
618
  output_column=args.output_column,
 
619
  config=args.config,
620
  create_pr=args.create_pr,
621
  verbose=args.verbose,
demo.gif DELETED

Git LFS Details

  • SHA256: aaa256a45c4d81d5fa2784666c45c5e1276faae923aca26c93c85cbfd920774a
  • Pointer size: 132 Bytes
  • Size of remote file: 4.92 MB
dots-mocr.py → dots-ocr-1.5.py RENAMED
@@ -1,55 +1,35 @@
1
  # /// script
2
  # requires-python = ">=3.11"
3
  # dependencies = [
4
- # "datasets>=4.0.0",
5
  # "huggingface-hub",
6
  # "pillow",
 
7
  # "tqdm",
8
  # "toolz",
 
9
  # ]
10
  #
11
- # [tool.hf-jobs]
12
- # # >=v0.30.0: ships huggingface_hub>=1.31, which datasets>=5.1 imports (httpx). On v0.29.0,
13
- # # PYTHONPATH puts the image's older hub first and `import datasets` crashes.
14
- # image = "vllm/vllm-openai:v0.30.0"
15
- # python = "/usr/bin/python3"
16
- # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
17
- # flavor = "a10g-small"
18
- # secrets = ["HF_TOKEN"]
19
  # ///
20
 
21
  """
22
- Convert document images to markdown using dots.mocr with vLLM.
23
 
24
- dots.mocr is a 3B multilingual document parsing model with SOTA performance
25
- on 100+ languages. It excels at converting structured graphics (charts, UI
26
- layouts, scientific figures) directly into SVG code. Core capabilities include
27
- grounding, recognition, semantic understanding, and interactive dialogue.
28
 
29
  Features:
30
  - Multilingual support (100+ languages)
31
  - Table extraction and formatting
32
  - Formula recognition
33
  - Layout-aware text extraction
34
- - Web screen parsing
35
- - Scene text spotting
36
- - SVG code generation (use --prompt-mode svg, or --model rednote-hilab/dots.mocr-svg for best results)
37
 
38
- Model: rednote-hilab/dots.mocr
39
- SVG variant: rednote-hilab/dots.mocr-svg
40
- vLLM: Officially integrated since v0.11.0
41
- GitHub: https://github.com/rednote-hilab/dots.mocr
42
- Paper: https://arxiv.org/abs/2603.13032
43
-
44
- Run on HF Jobs (the [tool.hf-jobs] header sets image, flavor and secrets;
45
- needs the hf CLI 1.32+):
46
-
47
- hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/dots-mocr.py \
48
- input-dataset output-dataset
49
-
50
- On your own GPU, vLLM is not in the dependencies (the Jobs image provides it):
51
-
52
- uv run --with vllm==0.30.0 dots-mocr.py input-dataset output-dataset
53
  """
54
 
55
  import argparse
@@ -66,13 +46,9 @@ from typing import Any, Dict, List, Union
66
  import torch
67
  from datasets import load_dataset
68
  from huggingface_hub import DatasetCard, login
69
- from PIL import Image, UnidentifiedImageError
70
  from toolz import partition_all
71
  from tqdm.auto import tqdm
72
- # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
73
- # default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
74
- # lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
75
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
76
  from vllm import LLM, SamplingParams
77
 
78
  logging.basicConfig(level=logging.INFO)
@@ -80,8 +56,8 @@ logger = logging.getLogger(__name__)
80
 
81
 
82
  # ────────────────────────────────────────────────────────────────
83
- # dots.mocr Prompt Templates
84
- # Source: https://github.com/rednote-hilab/dots.mocr/blob/master/dots_mocr/utils/prompts.py
85
  # ────────────────────────────────────────────────────────────────
86
 
87
  PROMPT_TEMPLATES = {
@@ -104,19 +80,11 @@ PROMPT_TEMPLATES = {
104
 
105
  5. Final Output: The entire output must be a single JSON object.
106
  """,
107
- # NOTE: Bboxes from layout-all/layout-only are in the resized image coordinate
108
- # space (Qwen2VLImageProcessor smart_resize: max_pixels=11289600, factor=28),
109
- # NOT original image coordinates. To map back, compute:
110
- # resized_h, resized_w = smart_resize(orig_h, orig_w)
111
- # scale_x, scale_y = orig_w / resized_w, orig_h / resized_h
112
  "layout-only": """Please output the layout information from this PDF image, including each layout's bbox and its category. The bbox should be in the format [x1, y1, x2, y2]. The layout categories for the PDF document include ['Caption', 'Footnote', 'Formula', 'List-item', 'Page-footer', 'Page-header', 'Picture', 'Section-header', 'Table', 'Text', 'Title']. Do not output the corresponding text. The layout result should be in JSON format.""",
 
113
  "web-parsing": """Parsing the layout info of this webpage image with format json:\n""",
114
  "scene-spotting": """Detect and recognize the text in the image.""",
115
  "grounding-ocr": """Extract text from the given bounding box on the image (format: [x1, y1, x2, y2]).\nBounding Box:\n""",
116
- # SVG code generation — {width} and {height} are replaced with actual image dimensions.
117
- # For best results, use --model rednote-hilab/dots.mocr-svg
118
- # Uses higher temperature (0.9) and top_p (1.0) per official recommendation.
119
- "svg": """Please generate the SVG code based on the image. viewBox="0 0 {width} {height}" """,
120
  "general": """ """,
121
  }
122
 
@@ -131,28 +99,6 @@ def check_cuda_availability():
131
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
132
 
133
 
134
- def ensure_output_columns_free(dataset, columns, overwrite=False):
135
- """Fail fast if an output column would collide with an existing input column.
136
-
137
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
138
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
139
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
140
- column(s) here instead (logged) so the later add_column is clean.
141
- """
142
- clash = [c for c in columns if c in dataset.column_names]
143
- if not clash:
144
- return dataset
145
- if overwrite:
146
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
147
- return dataset.remove_columns(clash)
148
- logger.error(
149
- f"Output column(s) {clash} already exist in the input dataset "
150
- f"(columns: {dataset.column_names})."
151
- )
152
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
153
- sys.exit(1)
154
-
155
-
156
  def make_ocr_message(
157
  image: Union[Image.Image, Dict[str, Any], str],
158
  prompt: str = PROMPT_TEMPLATES["ocr"],
@@ -171,12 +117,6 @@ def make_ocr_message(
171
  # Convert to RGB
172
  pil_img = pil_img.convert("RGB")
173
 
174
- # For SVG mode, inject actual image dimensions into the prompt
175
- if "{width}" in prompt and "{height}" in prompt:
176
- prompt = prompt.replace("{width}", str(pil_img.width)).replace(
177
- "{height}", str(pil_img.height)
178
- )
179
-
180
  # Convert to base64 data URI
181
  buf = io.BytesIO()
182
  pil_img.save(buf, format="PNG")
@@ -214,7 +154,7 @@ def create_dataset_card(
214
  tags:
215
  - ocr
216
  - document-processing
217
- - dots-mocr
218
  - multilingual
219
  - markdown
220
  - uv-script
@@ -223,7 +163,7 @@ tags:
223
 
224
  # Document OCR using {model_name}
225
 
226
- This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using dots.mocr, a 3B multilingual model with SOTA document parsing and SVG generation.
227
 
228
  ## Processing Details
229
 
@@ -246,14 +186,13 @@ This dataset contains OCR results from images in [{source_dataset}](https://hugg
246
 
247
  ## Model Information
248
 
249
- dots.mocr is a 3B multilingual document parsing model that excels at:
250
  - 100+ Languages — Multilingual document support
251
  - Table extraction — Structured data recognition
252
  - Formulas — Mathematical notation preservation
253
  - Layout-aware — Reading order and structure preservation
254
  - Web screen parsing — Webpage layout analysis
255
  - Scene text spotting — Text detection in natural scenes
256
- - SVG code generation — Charts, UI layouts, scientific figures to SVG
257
 
258
  ## Dataset Structure
259
 
@@ -283,10 +222,10 @@ for info in inference_info:
283
 
284
  ## Reproduction
285
 
286
- This dataset was generated using the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) dots.mocr script:
287
 
288
  ```bash
289
- uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/dots-mocr.py \\
290
  {source_dataset} \\
291
  <output-dataset> \\
292
  --image-column {image_column} \\
@@ -306,7 +245,7 @@ def main(
306
  output_dataset: str,
307
  image_column: str = "image",
308
  batch_size: int = 16,
309
- model: str = "rednote-hilab/dots.mocr",
310
  max_model_len: int = 24000,
311
  max_tokens: int = 24000,
312
  gpu_memory_utilization: float = 0.9,
@@ -319,14 +258,13 @@ def main(
319
  prompt_mode: str = "ocr",
320
  custom_prompt: str = None,
321
  output_column: str = "markdown",
322
- overwrite: bool = False,
323
  config: str = None,
324
  create_pr: bool = False,
325
  temperature: float = 0.1,
326
  top_p: float = 0.9,
327
  verbose: bool = False,
328
  ):
329
- """Process images from HF dataset through dots.mocr model."""
330
 
331
  # Check CUDA availability first
332
  check_cuda_availability()
@@ -357,9 +295,6 @@ def main(
357
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
358
  )
359
 
360
- # Fail fast if the output column would collide with an existing input column
361
- dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
362
-
363
  # Shuffle if requested
364
  if shuffle:
365
  logger.info(f"Shuffling dataset with seed {seed}")
@@ -380,12 +315,6 @@ def main(
380
  gpu_memory_utilization=gpu_memory_utilization,
381
  )
382
 
383
- # SVG mode uses higher temperature/top_p per official recommendation
384
- if prompt_mode == "svg" and temperature == 0.1 and top_p == 0.9:
385
- logger.info("SVG mode: using recommended temperature=0.9, top_p=1.0")
386
- temperature = 0.9
387
- top_p = 1.0
388
-
389
  sampling_params = SamplingParams(
390
  temperature=temperature,
391
  top_p=top_p,
@@ -401,35 +330,17 @@ def main(
401
  for batch_indices in tqdm(
402
  partition_all(batch_size, range(len(dataset))),
403
  total=(len(dataset) + batch_size - 1) // batch_size,
404
- desc="dots.mocr processing",
405
  ):
406
  batch_indices = list(batch_indices)
407
-
408
- # Fetch images first, with per-batch fallback for unreadable files.
409
- # One corrupt image used to take down the entire run via the list
410
- # comprehension; now we mark the whole batch as skipped and continue.
411
- try:
412
- batch_images = [dataset[i][image_column] for i in batch_indices]
413
- except (UnidentifiedImageError, OSError) as e:
414
- logger.warning(
415
- f"Skipping batch of {len(batch_indices)} — unreadable image "
416
- f"in batch: {type(e).__name__}: {e}"
417
- )
418
- all_outputs.extend(
419
- ["[OCR SKIPPED — UNREADABLE IMAGE]"] * len(batch_indices)
420
- )
421
- continue
422
 
423
  try:
424
  # Create messages for batch
425
  batch_messages = [make_ocr_message(img, prompt) for img in batch_images]
426
 
427
- # Process with vLLM (dots.mocr needs "string" content format)
428
- outputs = llm.chat(
429
- batch_messages,
430
- sampling_params,
431
- chat_template_content_format="string",
432
- )
433
 
434
  # Extract outputs
435
  for output in outputs:
@@ -452,7 +363,7 @@ def main(
452
  # Handle inference_info tracking (for multi-model comparisons)
453
  inference_entry = {
454
  "model_id": model,
455
- "model_name": "dots.mocr",
456
  "column_name": output_column,
457
  "timestamp": datetime.now().isoformat(),
458
  "prompt_mode": prompt_mode if not custom_prompt else "custom",
@@ -533,7 +444,7 @@ def main(
533
  card = DatasetCard(card_content)
534
  card.push_to_hub(output_dataset, token=HF_TOKEN)
535
 
536
- logger.info("dots.mocr processing complete!")
537
  logger.info(
538
  f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
539
  )
@@ -555,83 +466,77 @@ if __name__ == "__main__":
555
  # Show example usage if no arguments
556
  if len(sys.argv) == 1:
557
  print("=" * 80)
558
- print("dots.mocr Document Processing")
559
  print("=" * 80)
560
- print("\n3B multilingual OCR model with SVG generation")
561
  print("\nFeatures:")
562
  print("- Multilingual support (100+ languages)")
563
  print("- Fast processing with vLLM")
564
  print("- Table extraction and formatting")
565
  print("- Formula recognition")
566
  print("- Layout-aware text extraction")
567
- print("- Web screen parsing")
568
- print("- Scene text spotting")
569
- print("- SVG code generation (charts, UI, figures)")
570
  print("\nPrompt modes:")
571
- print(" ocr - Text extraction (default)")
572
- print(" layout-all - Layout + bboxes + text (JSON)")
573
- print(" layout-only - Layout + bboxes only (JSON)")
574
- print(" web-parsing - Webpage layout analysis (JSON)")
575
  print(" scene-spotting - Scene text detection")
576
- print(" grounding-ocr - Text from bounding box region")
577
- print(" svg - SVG code generation")
578
- print(" general - Free-form (use with --custom-prompt)")
579
  print("\nExample usage:")
580
  print("\n1. Basic OCR:")
581
- print(" uv run --with vllm==0.30.0 dots-mocr.py input-dataset output-dataset")
582
- print("\n2. SVG generation:")
583
- print(
584
- " uv run --with vllm==0.30.0 dots-mocr.py charts svg-output --prompt-mode svg --model rednote-hilab/dots.mocr-svg"
585
- )
586
- print("\n3. Web screen parsing:")
587
- print(" uv run --with vllm==0.30.0 dots-mocr.py screenshots parsed --prompt-mode web-parsing")
588
  print("\n4. Layout analysis with structure:")
589
- print(" uv run --with vllm==0.30.0 dots-mocr.py papers analyzed --prompt-mode layout-all")
590
  print("\n5. Running on HF Jobs:")
591
- print(" # [tool.hf-jobs] header sets image/flavor/secrets (hf CLI 1.32+)")
592
- print(" hf jobs uv run \\")
593
  print(
594
- " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/dots-mocr.py \\"
595
  )
596
  print(" input-dataset output-dataset")
597
  print("\n" + "=" * 80)
598
- print("\nFor full help, run: uv run --with vllm==0.30.0 dots-mocr.py --help")
599
  sys.exit(0)
600
 
601
  parser = argparse.ArgumentParser(
602
- description="Document OCR using dots.mocr (3B multilingual model with SVG generation)",
603
  formatter_class=argparse.RawDescriptionHelpFormatter,
604
  epilog="""
605
- Prompt Modes (official dots.mocr prompts):
606
  ocr - Simple text extraction (default)
607
  layout-all - Layout analysis with bboxes, categories, and text (JSON output)
608
  layout-only - Layout detection with bboxes and categories only (JSON output)
609
- web-parsing - Webpage layout analysis (JSON output)
610
- scene-spotting - Scene text detection and recognition
611
- grounding-ocr - Extract text from bounding box region
612
- svg - SVG code generation (auto-injects image dimensions into viewBox)
613
- general - Free-form QA (use with --custom-prompt)
614
 
615
  SVG Code Generation:
616
- Use --prompt-mode svg for SVG output. For best results, combine with
617
- --model rednote-hilab/dots.mocr-svg (the SVG-optimized variant).
618
- SVG mode automatically uses temperature=0.9, top_p=1.0 unless overridden.
619
 
620
  Examples:
621
  # Basic text OCR (default)
622
- uv run --with vllm==0.30.0 dots-mocr.py my-docs analyzed-docs
623
-
624
- # SVG generation with optimized variant
625
- uv run --with vllm==0.30.0 dots-mocr.py charts svg-out --prompt-mode svg --model rednote-hilab/dots.mocr-svg
626
 
627
  # Web screen parsing
628
- uv run --with vllm==0.30.0 dots-mocr.py screenshots parsed --prompt-mode web-parsing
 
 
 
629
 
630
  # Full layout analysis with structure
631
- uv run --with vllm==0.30.0 dots-mocr.py papers structured --prompt-mode layout-all
632
 
633
  # Random sampling for testing
634
- uv run --with vllm==0.30.0 dots-mocr.py large-dataset test --max-samples 50 --shuffle
635
  """,
636
  )
637
 
@@ -650,8 +555,8 @@ Examples:
650
  )
651
  parser.add_argument(
652
  "--model",
653
- default="rednote-hilab/dots.mocr",
654
- help="Model to use (default: rednote-hilab/dots.mocr, or rednote-hilab/dots.mocr-svg for SVG)",
655
  )
656
  parser.add_argument(
657
  "--max-model-len",
@@ -707,12 +612,6 @@ Examples:
707
  default="markdown",
708
  help="Column name for output text (default: markdown)",
709
  )
710
- parser.add_argument(
711
- "--overwrite",
712
- action="store_true",
713
- help="Replace the output column if it already exists in the input dataset "
714
- "(default: error out to avoid clobbering an existing column).",
715
- )
716
  parser.add_argument(
717
  "--config",
718
  help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
@@ -760,7 +659,6 @@ Examples:
760
  prompt_mode=args.prompt_mode,
761
  custom_prompt=args.custom_prompt,
762
  output_column=args.output_column,
763
- overwrite=args.overwrite,
764
  config=args.config,
765
  create_pr=args.create_pr,
766
  temperature=args.temperature,
 
1
  # /// script
2
  # requires-python = ">=3.11"
3
  # dependencies = [
4
+ # "datasets",
5
  # "huggingface-hub",
6
  # "pillow",
7
+ # "vllm>=0.15.1",
8
  # "tqdm",
9
  # "toolz",
10
+ # "torch",
11
  # ]
12
  #
 
 
 
 
 
 
 
 
13
  # ///
14
 
15
  """
16
+ Convert document images to markdown using DoTS.ocr-1.5 with vLLM.
17
 
18
+ DoTS.ocr-1.5 is a 3B multilingual document parsing model with SOTA performance
19
+ on 100+ languages. Compared to v1 (1.7B), it adds web screen parsing, scene text
20
+ spotting, SVG code generation, and stronger multilingual document parsing.
 
21
 
22
  Features:
23
  - Multilingual support (100+ languages)
24
  - Table extraction and formatting
25
  - Formula recognition
26
  - Layout-aware text extraction
27
+ - Web screen parsing (NEW in v1.5)
28
+ - Scene text spotting (NEW in v1.5)
29
+ - SVG code generation (requires dots.ocr-1.5-svg variant)
30
 
31
+ Model: rednote-hilab/dots.ocr-1.5
32
+ vLLM: Officially supported (same DotsOCRForCausalLM architecture as v1)
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  """
34
 
35
  import argparse
 
46
  import torch
47
  from datasets import load_dataset
48
  from huggingface_hub import DatasetCard, login
49
+ from PIL import Image
50
  from toolz import partition_all
51
  from tqdm.auto import tqdm
 
 
 
 
52
  from vllm import LLM, SamplingParams
53
 
54
  logging.basicConfig(level=logging.INFO)
 
56
 
57
 
58
  # ────────────────────────────────────────────────────────────────
59
+ # DoTS OCR 1.5 Prompt Templates (from official dots.ocr repo)
60
+ # Source: https://github.com/rednote-hilab/dots.ocr/blob/master/dots_ocr/utils/prompts.py
61
  # ────────────────────────────────────────────────────────────────
62
 
63
  PROMPT_TEMPLATES = {
 
80
 
81
  5. Final Output: The entire output must be a single JSON object.
82
  """,
 
 
 
 
 
83
  "layout-only": """Please output the layout information from this PDF image, including each layout's bbox and its category. The bbox should be in the format [x1, y1, x2, y2]. The layout categories for the PDF document include ['Caption', 'Footnote', 'Formula', 'List-item', 'Page-footer', 'Page-header', 'Picture', 'Section-header', 'Table', 'Text', 'Title']. Do not output the corresponding text. The layout result should be in JSON format.""",
84
+ # NEW in v1.5:
85
  "web-parsing": """Parsing the layout info of this webpage image with format json:\n""",
86
  "scene-spotting": """Detect and recognize the text in the image.""",
87
  "grounding-ocr": """Extract text from the given bounding box on the image (format: [x1, y1, x2, y2]).\nBounding Box:\n""",
 
 
 
 
88
  "general": """ """,
89
  }
90
 
 
99
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
100
 
101
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  def make_ocr_message(
103
  image: Union[Image.Image, Dict[str, Any], str],
104
  prompt: str = PROMPT_TEMPLATES["ocr"],
 
117
  # Convert to RGB
118
  pil_img = pil_img.convert("RGB")
119
 
 
 
 
 
 
 
120
  # Convert to base64 data URI
121
  buf = io.BytesIO()
122
  pil_img.save(buf, format="PNG")
 
154
  tags:
155
  - ocr
156
  - document-processing
157
+ - dots-ocr-1.5
158
  - multilingual
159
  - markdown
160
  - uv-script
 
163
 
164
  # Document OCR using {model_name}
165
 
166
+ This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using DoTS.ocr-1.5, a 3B multilingual model with SOTA document parsing.
167
 
168
  ## Processing Details
169
 
 
186
 
187
  ## Model Information
188
 
189
+ DoTS.ocr-1.5 is a 3B multilingual document parsing model that excels at:
190
  - 100+ Languages — Multilingual document support
191
  - Table extraction — Structured data recognition
192
  - Formulas — Mathematical notation preservation
193
  - Layout-aware — Reading order and structure preservation
194
  - Web screen parsing — Webpage layout analysis
195
  - Scene text spotting — Text detection in natural scenes
 
196
 
197
  ## Dataset Structure
198
 
 
222
 
223
  ## Reproduction
224
 
225
+ This dataset was generated using the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) DoTS OCR 1.5 script:
226
 
227
  ```bash
228
+ uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/dots-ocr-1.5.py \\
229
  {source_dataset} \\
230
  <output-dataset> \\
231
  --image-column {image_column} \\
 
245
  output_dataset: str,
246
  image_column: str = "image",
247
  batch_size: int = 16,
248
+ model: str = "rednote-hilab/dots.ocr-1.5",
249
  max_model_len: int = 24000,
250
  max_tokens: int = 24000,
251
  gpu_memory_utilization: float = 0.9,
 
258
  prompt_mode: str = "ocr",
259
  custom_prompt: str = None,
260
  output_column: str = "markdown",
 
261
  config: str = None,
262
  create_pr: bool = False,
263
  temperature: float = 0.1,
264
  top_p: float = 0.9,
265
  verbose: bool = False,
266
  ):
267
+ """Process images from HF dataset through DoTS.ocr-1.5 model."""
268
 
269
  # Check CUDA availability first
270
  check_cuda_availability()
 
295
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
296
  )
297
 
 
 
 
298
  # Shuffle if requested
299
  if shuffle:
300
  logger.info(f"Shuffling dataset with seed {seed}")
 
315
  gpu_memory_utilization=gpu_memory_utilization,
316
  )
317
 
 
 
 
 
 
 
318
  sampling_params = SamplingParams(
319
  temperature=temperature,
320
  top_p=top_p,
 
330
  for batch_indices in tqdm(
331
  partition_all(batch_size, range(len(dataset))),
332
  total=(len(dataset) + batch_size - 1) // batch_size,
333
+ desc="DoTS.ocr-1.5 processing",
334
  ):
335
  batch_indices = list(batch_indices)
336
+ batch_images = [dataset[i][image_column] for i in batch_indices]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337
 
338
  try:
339
  # Create messages for batch
340
  batch_messages = [make_ocr_message(img, prompt) for img in batch_images]
341
 
342
+ # Process with vLLM
343
+ outputs = llm.chat(batch_messages, sampling_params)
 
 
 
 
344
 
345
  # Extract outputs
346
  for output in outputs:
 
363
  # Handle inference_info tracking (for multi-model comparisons)
364
  inference_entry = {
365
  "model_id": model,
366
+ "model_name": "DoTS.ocr-1.5",
367
  "column_name": output_column,
368
  "timestamp": datetime.now().isoformat(),
369
  "prompt_mode": prompt_mode if not custom_prompt else "custom",
 
444
  card = DatasetCard(card_content)
445
  card.push_to_hub(output_dataset, token=HF_TOKEN)
446
 
447
+ logger.info("DoTS.ocr-1.5 processing complete!")
448
  logger.info(
449
  f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
450
  )
 
466
  # Show example usage if no arguments
467
  if len(sys.argv) == 1:
468
  print("=" * 80)
469
+ print("DoTS.ocr-1.5 Document Processing")
470
  print("=" * 80)
471
+ print("\n3B multilingual OCR model supporting 100+ languages")
472
  print("\nFeatures:")
473
  print("- Multilingual support (100+ languages)")
474
  print("- Fast processing with vLLM")
475
  print("- Table extraction and formatting")
476
  print("- Formula recognition")
477
  print("- Layout-aware text extraction")
478
+ print("- Web screen parsing (NEW in v1.5)")
479
+ print("- Scene text spotting (NEW in v1.5)")
 
480
  print("\nPrompt modes:")
481
+ print(" ocr - Text extraction (default)")
482
+ print(" layout-all - Layout + bboxes + text (JSON)")
483
+ print(" layout-only - Layout + bboxes only (JSON)")
484
+ print(" web-parsing - Webpage layout analysis (JSON)")
485
  print(" scene-spotting - Scene text detection")
486
+ print(" grounding-ocr - Text from bounding box region")
487
+ print(" general - Free-form (use with --custom-prompt)")
 
488
  print("\nExample usage:")
489
  print("\n1. Basic OCR:")
490
+ print(" uv run dots-ocr-1.5.py input-dataset output-dataset")
491
+ print("\n2. Web screen parsing:")
492
+ print(" uv run dots-ocr-1.5.py screenshots parsed --prompt-mode web-parsing")
493
+ print("\n3. Scene text spotting:")
494
+ print(" uv run dots-ocr-1.5.py photos detected --prompt-mode scene-spotting")
 
 
495
  print("\n4. Layout analysis with structure:")
496
+ print(" uv run dots-ocr-1.5.py papers analyzed --prompt-mode layout-all")
497
  print("\n5. Running on HF Jobs:")
498
+ print(" hf jobs uv run --flavor l4x1 \\")
499
+ print(" -s HF_TOKEN \\")
500
  print(
501
+ " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/dots-ocr-1.5.py \\"
502
  )
503
  print(" input-dataset output-dataset")
504
  print("\n" + "=" * 80)
505
+ print("\nFor full help, run: uv run dots-ocr-1.5.py --help")
506
  sys.exit(0)
507
 
508
  parser = argparse.ArgumentParser(
509
+ description="Document OCR using DoTS.ocr-1.5 (3B multilingual model)",
510
  formatter_class=argparse.RawDescriptionHelpFormatter,
511
  epilog="""
512
+ Prompt Modes (official DoTS.ocr-1.5 prompts):
513
  ocr - Simple text extraction (default)
514
  layout-all - Layout analysis with bboxes, categories, and text (JSON output)
515
  layout-only - Layout detection with bboxes and categories only (JSON output)
516
+ web-parsing - Webpage layout analysis (JSON output) [NEW in v1.5]
517
+ scene-spotting - Scene text detection and recognition [NEW in v1.5]
518
+ grounding-ocr - Extract text from bounding box region [NEW in v1.5]
519
+ general - Free-form QA (use with --custom-prompt) [NEW in v1.5]
 
520
 
521
  SVG Code Generation:
522
+ For SVG output, use --model rednote-hilab/dots.ocr-1.5-svg with:
523
+ --custom-prompt 'Please generate the SVG code based on the image.'
 
524
 
525
  Examples:
526
  # Basic text OCR (default)
527
+ uv run dots-ocr-1.5.py my-docs analyzed-docs
 
 
 
528
 
529
  # Web screen parsing
530
+ uv run dots-ocr-1.5.py screenshots parsed --prompt-mode web-parsing
531
+
532
+ # Scene text spotting
533
+ uv run dots-ocr-1.5.py photos spotted --prompt-mode scene-spotting
534
 
535
  # Full layout analysis with structure
536
+ uv run dots-ocr-1.5.py papers structured --prompt-mode layout-all
537
 
538
  # Random sampling for testing
539
+ uv run dots-ocr-1.5.py large-dataset test --max-samples 50 --shuffle
540
  """,
541
  )
542
 
 
555
  )
556
  parser.add_argument(
557
  "--model",
558
+ default="rednote-hilab/dots.ocr-1.5",
559
+ help="Model to use (default: rednote-hilab/dots.ocr-1.5)",
560
  )
561
  parser.add_argument(
562
  "--max-model-len",
 
612
  default="markdown",
613
  help="Column name for output text (default: markdown)",
614
  )
 
 
 
 
 
 
615
  parser.add_argument(
616
  "--config",
617
  help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
 
659
  prompt_mode=args.prompt_mode,
660
  custom_prompt=args.custom_prompt,
661
  output_column=args.output_column,
 
662
  config=args.config,
663
  create_pr=args.create_pr,
664
  temperature=args.temperature,
dots-ocr.py CHANGED
@@ -1,21 +1,15 @@
1
  # /// script
2
  # requires-python = ">=3.11"
3
  # dependencies = [
4
- # "datasets>=4.0.0",
5
  # "huggingface-hub",
6
  # "pillow",
 
7
  # "tqdm",
8
  # "toolz",
 
9
  # ]
10
  #
11
- # [tool.hf-jobs]
12
- # # >=v0.30.0: ships huggingface_hub>=1.31, which datasets>=5.1 imports (httpx). On v0.29.0,
13
- # # PYTHONPATH puts the image's older hub first and `import datasets` crashes.
14
- # image = "vllm/vllm-openai:v0.30.0"
15
- # python = "/usr/bin/python3"
16
- # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
17
- # flavor = "a10g-small"
18
- # secrets = ["HF_TOKEN"]
19
  # ///
20
 
21
  """
@@ -33,16 +27,6 @@ Features:
33
 
34
  Model: rednote-hilab/dots.ocr
35
  vLLM: Officially tested with 0.9.1+ (native support via PR #24645)
36
-
37
- Run on HF Jobs (the [tool.hf-jobs] header sets image, flavor and secrets;
38
- needs `hf` CLI 1.32+):
39
-
40
- hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/dots-ocr.py \\
41
- input-dataset output-dataset
42
-
43
- Run on your own GPU (vLLM and torch come from the image on Jobs, so add them):
44
-
45
- uv run --with vllm==0.30.0 dots-ocr.py input-dataset output-dataset
46
  """
47
 
48
  import argparse
@@ -61,10 +45,6 @@ from huggingface_hub import DatasetCard, login
61
  from PIL import Image
62
  from toolz import partition_all
63
  from tqdm.auto import tqdm
64
- # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
65
- # default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
66
- # lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
67
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
68
  from vllm import LLM, SamplingParams
69
 
70
  logging.basicConfig(level=logging.INFO)
@@ -109,28 +89,6 @@ def check_cuda_availability():
109
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
110
 
111
 
112
- def ensure_output_columns_free(dataset, columns, overwrite=False):
113
- """Fail fast if an output column would collide with an existing input column.
114
-
115
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
116
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
117
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
118
- column(s) here instead (logged) so the later add_column is clean.
119
- """
120
- clash = [c for c in columns if c in dataset.column_names]
121
- if not clash:
122
- return dataset
123
- if overwrite:
124
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
125
- return dataset.remove_columns(clash)
126
- logger.error(
127
- f"Output column(s) {clash} already exist in the input dataset "
128
- f"(columns: {dataset.column_names})."
129
- )
130
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
131
- sys.exit(1)
132
-
133
-
134
  def make_ocr_message(
135
  image: Union[Image.Image, Dict[str, Any], str],
136
  prompt: str = PROMPT_TEMPLATES["ocr"],
@@ -277,8 +235,7 @@ def main(
277
  image_column: str = "image",
278
  batch_size: int = 16,
279
  model: str = "rednote-hilab/dots.ocr",
280
- max_model_len: int = 32768,
281
- max_pixels: int = None,
282
  max_tokens: int = 8192,
283
  gpu_memory_utilization: float = 0.8,
284
  hf_token: str = None,
@@ -290,7 +247,6 @@ def main(
290
  prompt_mode: str = "ocr",
291
  custom_prompt: str = None,
292
  output_column: str = "markdown",
293
- overwrite: bool = False,
294
  config: str = None,
295
  create_pr: bool = False,
296
  ):
@@ -325,9 +281,6 @@ def main(
325
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
326
  )
327
 
328
- # Fail fast if the output column would collide with an existing input column
329
- dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
330
-
331
  # Shuffle if requested
332
  if shuffle:
333
  logger.info(f"Shuffling dataset with seed {seed}")
@@ -341,17 +294,13 @@ def main(
341
  # Initialize vLLM model
342
  logger.info(f"Initializing vLLM with model: {model}")
343
  logger.info("This may take a few minutes on first run...")
344
- llm_kwargs = dict(
345
  model=model,
346
  trust_remote_code=True,
347
  max_model_len=max_model_len,
348
  gpu_memory_utilization=gpu_memory_utilization,
349
  limit_mm_per_prompt={"image": 1},
350
  )
351
- if max_pixels is not None:
352
- logger.info(f"Capping input images to max_pixels={max_pixels}")
353
- llm_kwargs["mm_processor_kwargs"] = {"max_pixels": max_pixels}
354
- llm = LLM(**llm_kwargs)
355
 
356
  sampling_params = SamplingParams(
357
  temperature=0.0, # Deterministic for OCR
@@ -490,25 +439,28 @@ if __name__ == "__main__":
490
  print("- 📝 Layout-aware text extraction")
491
  print("\nExample usage:")
492
  print("\n1. Basic OCR:")
493
- print(" uv run --with vllm==0.30.0 dots-ocr.py input-dataset output-dataset")
494
  print("\n2. With custom settings:")
495
  print(
496
- " uv run --with vllm==0.30.0 dots-ocr.py docs analyzed-docs --batch-size 20 --max-samples 100"
497
  )
498
  print("\n3. Layout analysis with structure:")
499
  print(
500
- " uv run --with vllm==0.30.0 dots-ocr.py papers analyzed-structure --prompt-mode layout-all"
501
  )
502
  print("\n4. Layout detection only (no text):")
503
- print(" uv run --with vllm==0.30.0 dots-ocr.py docs layout-info --prompt-mode layout-only")
504
- print("\n5. Running on HF Jobs (header sets image/flavor/secrets; hf CLI 1.32+):")
505
- print(" hf jobs uv run \\")
 
 
 
506
  print(
507
  " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/dots-ocr.py \\"
508
  )
509
  print(" input-dataset output-dataset")
510
  print("\n" + "=" * 80)
511
- print("\nFor full help, run: uv run --with vllm==0.30.0 dots-ocr.py --help")
512
  sys.exit(0)
513
 
514
  parser = argparse.ArgumentParser(
@@ -522,13 +474,13 @@ Prompt Modes (official DoTS.ocr prompts):
522
 
523
  Examples:
524
  # Basic text OCR (default)
525
- uv run --with vllm==0.30.0 dots-ocr.py my-docs analyzed-docs
526
 
527
  # Full layout analysis with structure
528
- uv run --with vllm==0.30.0 dots-ocr.py papers structured --prompt-mode layout-all
529
 
530
  # Random sampling for testing
531
- uv run --with vllm==0.30.0 dots-ocr.py large-dataset test --max-samples 50 --shuffle
532
  """,
533
  )
534
 
@@ -553,23 +505,8 @@ Examples:
553
  parser.add_argument(
554
  "--max-model-len",
555
  type=int,
556
- default=32768,
557
- help=(
558
- "Maximum model context length (default: 32768). dots.ocr does NOT resize "
559
- "input images, so a full page can reach ~14k image tokens (the model's "
560
- "11.29M-px processor cap); the old 8192 default rejected such requests and "
561
- "the row was written as '[OCR ERROR]'. Pair with --max-pixels to cap memory."
562
- ),
563
- )
564
- parser.add_argument(
565
- "--max-pixels",
566
- type=int,
567
- default=None,
568
- help=(
569
- "Optional cap on input image pixels (width*height) passed to vLLM's "
570
- "mm_processor. Lower this (e.g. 4000000) to bound image tokens and GPU "
571
- "memory on very large scans. Default: model's own cap (~11.29M px)."
572
- ),
573
  )
574
  parser.add_argument(
575
  "--max-tokens",
@@ -619,12 +556,6 @@ Examples:
619
  default="markdown",
620
  help="Column name for output text (default: markdown)",
621
  )
622
- parser.add_argument(
623
- "--overwrite",
624
- action="store_true",
625
- help="Replace the output column if it already exists in the input dataset "
626
- "(default: error out to avoid clobbering an existing column).",
627
- )
628
  parser.add_argument(
629
  "--config",
630
  help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
@@ -644,7 +575,6 @@ Examples:
644
  batch_size=args.batch_size,
645
  model=args.model,
646
  max_model_len=args.max_model_len,
647
- max_pixels=args.max_pixels,
648
  max_tokens=args.max_tokens,
649
  gpu_memory_utilization=args.gpu_memory_utilization,
650
  hf_token=args.hf_token,
@@ -656,7 +586,6 @@ Examples:
656
  prompt_mode=args.prompt_mode,
657
  custom_prompt=args.custom_prompt,
658
  output_column=args.output_column,
659
- overwrite=args.overwrite,
660
  config=args.config,
661
  create_pr=args.create_pr,
662
  )
 
1
  # /// script
2
  # requires-python = ">=3.11"
3
  # dependencies = [
4
+ # "datasets",
5
  # "huggingface-hub",
6
  # "pillow",
7
+ # "vllm>=0.15.1",
8
  # "tqdm",
9
  # "toolz",
10
+ # "torch",
11
  # ]
12
  #
 
 
 
 
 
 
 
 
13
  # ///
14
 
15
  """
 
27
 
28
  Model: rednote-hilab/dots.ocr
29
  vLLM: Officially tested with 0.9.1+ (native support via PR #24645)
 
 
 
 
 
 
 
 
 
 
30
  """
31
 
32
  import argparse
 
45
  from PIL import Image
46
  from toolz import partition_all
47
  from tqdm.auto import tqdm
 
 
 
 
48
  from vllm import LLM, SamplingParams
49
 
50
  logging.basicConfig(level=logging.INFO)
 
89
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
90
 
91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  def make_ocr_message(
93
  image: Union[Image.Image, Dict[str, Any], str],
94
  prompt: str = PROMPT_TEMPLATES["ocr"],
 
235
  image_column: str = "image",
236
  batch_size: int = 16,
237
  model: str = "rednote-hilab/dots.ocr",
238
+ max_model_len: int = 8192,
 
239
  max_tokens: int = 8192,
240
  gpu_memory_utilization: float = 0.8,
241
  hf_token: str = None,
 
247
  prompt_mode: str = "ocr",
248
  custom_prompt: str = None,
249
  output_column: str = "markdown",
 
250
  config: str = None,
251
  create_pr: bool = False,
252
  ):
 
281
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
282
  )
283
 
 
 
 
284
  # Shuffle if requested
285
  if shuffle:
286
  logger.info(f"Shuffling dataset with seed {seed}")
 
294
  # Initialize vLLM model
295
  logger.info(f"Initializing vLLM with model: {model}")
296
  logger.info("This may take a few minutes on first run...")
297
+ llm = LLM(
298
  model=model,
299
  trust_remote_code=True,
300
  max_model_len=max_model_len,
301
  gpu_memory_utilization=gpu_memory_utilization,
302
  limit_mm_per_prompt={"image": 1},
303
  )
 
 
 
 
304
 
305
  sampling_params = SamplingParams(
306
  temperature=0.0, # Deterministic for OCR
 
439
  print("- 📝 Layout-aware text extraction")
440
  print("\nExample usage:")
441
  print("\n1. Basic OCR:")
442
+ print(" uv run dots-ocr.py input-dataset output-dataset")
443
  print("\n2. With custom settings:")
444
  print(
445
+ " uv run dots-ocr.py docs analyzed-docs --batch-size 20 --max-samples 100"
446
  )
447
  print("\n3. Layout analysis with structure:")
448
  print(
449
+ " uv run dots-ocr.py papers analyzed-structure --prompt-mode layout-all"
450
  )
451
  print("\n4. Layout detection only (no text):")
452
+ print(" uv run dots-ocr.py docs layout-info --prompt-mode layout-only")
453
+ print("\n5. Running on HF Jobs:")
454
+ print(" hf jobs uv run --flavor l4x1 \\")
455
+ print(
456
+ ' -e HF_TOKEN=$(python3 -c "from huggingface_hub import get_token; print(get_token())") \\'
457
+ )
458
  print(
459
  " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/dots-ocr.py \\"
460
  )
461
  print(" input-dataset output-dataset")
462
  print("\n" + "=" * 80)
463
+ print("\nFor full help, run: uv run dots-ocr.py --help")
464
  sys.exit(0)
465
 
466
  parser = argparse.ArgumentParser(
 
474
 
475
  Examples:
476
  # Basic text OCR (default)
477
+ uv run dots-ocr.py my-docs analyzed-docs
478
 
479
  # Full layout analysis with structure
480
+ uv run dots-ocr.py papers structured --prompt-mode layout-all
481
 
482
  # Random sampling for testing
483
+ uv run dots-ocr.py large-dataset test --max-samples 50 --shuffle
484
  """,
485
  )
486
 
 
505
  parser.add_argument(
506
  "--max-model-len",
507
  type=int,
508
+ default=8192,
509
+ help="Maximum model context length (default: 8192)",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
510
  )
511
  parser.add_argument(
512
  "--max-tokens",
 
556
  default="markdown",
557
  help="Column name for output text (default: markdown)",
558
  )
 
 
 
 
 
 
559
  parser.add_argument(
560
  "--config",
561
  help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
 
575
  batch_size=args.batch_size,
576
  model=args.model,
577
  max_model_len=args.max_model_len,
 
578
  max_tokens=args.max_tokens,
579
  gpu_memory_utilization=args.gpu_memory_utilization,
580
  hf_token=args.hf_token,
 
586
  prompt_mode=args.prompt_mode,
587
  custom_prompt=args.custom_prompt,
588
  output_column=args.output_column,
 
589
  config=args.config,
590
  create_pr=args.create_pr,
591
  )
examples/nls-index-card-v2.json DELETED
@@ -1,13 +0,0 @@
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 DELETED
@@ -1,13 +0,0 @@
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
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
falcon-ocr-bucket.py DELETED
@@ -1,303 +0,0 @@
1
- # /// script
2
- # requires-python = ">=3.11"
3
- # dependencies = [
4
- # "pillow",
5
- # "pymupdf",
6
- # "torch>=2.5",
7
- # "torchvision",
8
- # "falcon-perception[ocr]",
9
- # ]
10
- # ///
11
-
12
- """
13
- OCR images and PDFs from a directory using Falcon OCR, writing markdown files.
14
-
15
- Designed to work with HF Buckets mounted as volumes via `hf jobs uv run -v ...`.
16
- Reads images/PDFs from INPUT_DIR, runs Falcon OCR via the optimized falcon-perception
17
- engine (CUDA graphs + paged inference), and writes one .md file per image (or per
18
- PDF page) to OUTPUT_DIR, preserving directory structure.
19
-
20
- Input: Output:
21
- /input/page1.png -> /output/page1.md
22
- /input/report.pdf -> /output/report/page_001.md
23
- (3 pages) /output/report/page_002.md
24
- /output/report/page_003.md
25
- /input/sub/photo.jpg -> /output/sub/photo.md
26
-
27
- Examples:
28
-
29
- # Local test
30
- uv run falcon-ocr-bucket.py ./test-images ./test-output
31
-
32
- # HF Jobs with bucket volumes
33
- hf jobs uv run --flavor l4x1 \\
34
- -s HF_TOKEN \\
35
- -v hf://buckets/user/ocr-input:/input:ro \\
36
- -v hf://buckets/user/ocr-output:/output \\
37
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/falcon-ocr-bucket.py \\
38
- /input /output
39
-
40
- Model: tiiuae/Falcon-OCR (0.3B, 80.3% olmOCR, Apache 2.0)
41
- Backend: falcon-perception (OCRInferenceEngine with CUDA graphs)
42
- """
43
-
44
- import argparse
45
- import logging
46
- import sys
47
- import time
48
- from pathlib import Path
49
-
50
- import torch
51
- from PIL import Image
52
-
53
- logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
54
- logger = logging.getLogger(__name__)
55
-
56
- MODEL_ID = "tiiuae/Falcon-OCR"
57
- IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".tiff", ".tif", ".bmp", ".webp"}
58
-
59
-
60
- def check_cuda_availability():
61
- if not torch.cuda.is_available():
62
- logger.error("CUDA is not available. This script requires a GPU.")
63
- sys.exit(1)
64
- logger.info(f"CUDA available. GPU: {torch.cuda.get_device_name(0)}")
65
-
66
-
67
- def discover_files(input_dir: Path, limit: int | None = None) -> list[Path]:
68
- """Discover image and PDF files under input_dir.
69
-
70
- Without `limit`, returns the full sorted list (deterministic order).
71
- With `limit`, stops scanning once `limit` matching files are found
72
- and returns them in filesystem order (much faster on huge mounted
73
- buckets, but ordering is not deterministic).
74
- """
75
- files = []
76
- iterator = (
77
- input_dir.rglob("*") if limit is not None else sorted(input_dir.rglob("*"))
78
- )
79
- for path in iterator:
80
- if not path.is_file():
81
- continue
82
- ext = path.suffix.lower()
83
- if ext in IMAGE_EXTENSIONS or ext == ".pdf":
84
- files.append(path)
85
- if limit is not None and len(files) >= limit:
86
- break
87
- return files
88
-
89
-
90
- def prepare_images(
91
- files: list[Path], input_dir: Path, output_dir: Path, pdf_dpi: int
92
- ) -> list[tuple[Image.Image, Path]]:
93
- import fitz # pymupdf
94
-
95
- items: list[tuple[Image.Image, Path]] = []
96
-
97
- for file_path in files:
98
- rel = file_path.relative_to(input_dir)
99
- ext = file_path.suffix.lower()
100
-
101
- if ext == ".pdf":
102
- pdf_output_dir = output_dir / rel.with_suffix("")
103
- try:
104
- doc = fitz.open(file_path)
105
- num_pages = len(doc)
106
- logger.info(f"PDF: {rel} ({num_pages} pages)")
107
- for page_num in range(num_pages):
108
- page = doc[page_num]
109
- zoom = pdf_dpi / 72.0
110
- mat = fitz.Matrix(zoom, zoom)
111
- pix = page.get_pixmap(matrix=mat)
112
- img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
113
- md_path = pdf_output_dir / f"page_{page_num + 1:03d}.md"
114
- items.append((img, md_path))
115
- doc.close()
116
- except Exception as e:
117
- logger.error(f"Failed to open PDF {rel}: {e}")
118
- else:
119
- try:
120
- img = Image.open(file_path).convert("RGB")
121
- md_path = output_dir / rel.with_suffix(".md")
122
- items.append((img, md_path))
123
- except Exception as e:
124
- logger.error(f"Failed to open image {rel}: {e}")
125
-
126
- return items
127
-
128
-
129
- def main():
130
- parser = argparse.ArgumentParser(
131
- description="OCR images/PDFs from a directory using Falcon OCR, output markdown files.",
132
- formatter_class=argparse.RawDescriptionHelpFormatter,
133
- epilog=__doc__,
134
- )
135
- parser.add_argument("input_dir", help="Directory containing images and/or PDFs")
136
- parser.add_argument("output_dir", help="Directory to write markdown output files")
137
- parser.add_argument(
138
- "--batch-size", type=int, default=8, help="Images per batch (default: 8)",
139
- )
140
- parser.add_argument(
141
- "--pdf-dpi", type=int, default=300,
142
- help="DPI for PDF page rendering (default: 300)",
143
- )
144
- parser.add_argument(
145
- "--no-compile", action="store_true", help="Disable torch.compile",
146
- )
147
- parser.add_argument(
148
- "--no-cudagraph", action="store_true", help="Disable CUDA graph capture",
149
- )
150
- parser.add_argument(
151
- "--max-samples", type=int, default=None,
152
- help="Limit number of input files to discover. Stops scanning early "
153
- "once the limit is reached (much faster on large mounted buckets). "
154
- "Applied before PDF page expansion. With --max-samples set, file "
155
- "ordering is filesystem-dependent rather than sorted.",
156
- )
157
- parser.add_argument(
158
- "--verbose", action="store_true", help="Print resolved package versions",
159
- )
160
-
161
- args = parser.parse_args()
162
-
163
- check_cuda_availability()
164
-
165
- input_dir = Path(args.input_dir)
166
- output_dir = Path(args.output_dir)
167
-
168
- if not input_dir.is_dir():
169
- logger.error(f"Input directory does not exist: {input_dir}")
170
- sys.exit(1)
171
-
172
- output_dir.mkdir(parents=True, exist_ok=True)
173
-
174
- start_time = time.time()
175
-
176
- # Discover files
177
- if args.max_samples is not None:
178
- logger.info(
179
- f"Scanning {input_dir} for up to {args.max_samples} images/PDFs "
180
- f"(early termination, --max-samples)..."
181
- )
182
- else:
183
- logger.info(f"Scanning {input_dir} for images and PDFs...")
184
- files = discover_files(input_dir, limit=args.max_samples)
185
- if not files:
186
- logger.error(f"No image or PDF files found in {input_dir}")
187
- sys.exit(1)
188
-
189
- pdf_count = sum(1 for f in files if f.suffix.lower() == ".pdf")
190
- img_count = len(files) - pdf_count
191
- logger.info(f"Found {img_count} image(s) and {pdf_count} PDF(s)")
192
-
193
- # Prepare images
194
- logger.info("Preparing images (rendering PDFs)...")
195
- items = prepare_images(files, input_dir, output_dir, args.pdf_dpi)
196
- if not items:
197
- logger.error("No processable images after preparation")
198
- sys.exit(1)
199
-
200
- logger.info(f"Total images to OCR: {len(items)}")
201
-
202
- # Load model
203
- logger.info(f"Loading {MODEL_ID} via falcon-perception engine...")
204
- from falcon_perception import load_and_prepare_model
205
- from falcon_perception.data import ImageProcessor
206
- from falcon_perception.paged_ocr_inference import OCRInferenceEngine
207
-
208
- do_compile = not args.no_compile
209
- do_cudagraph = not args.no_cudagraph
210
-
211
- model, tokenizer, model_args = load_and_prepare_model(
212
- hf_model_id=MODEL_ID,
213
- device="cuda",
214
- dtype="bfloat16",
215
- compile=do_compile,
216
- )
217
-
218
- image_processor = ImageProcessor(patch_size=16, merge_size=1)
219
- engine = OCRInferenceEngine(
220
- model, tokenizer, image_processor, capture_cudagraph=do_cudagraph
221
- )
222
- logger.info(f"Engine loaded. compile={do_compile}, cudagraph={do_cudagraph}")
223
-
224
- # Process in batches
225
- errors = 0
226
- processed = 0
227
- total = len(items)
228
- batch_size = args.batch_size
229
-
230
- for batch_start in range(0, total, batch_size):
231
- batch_end = min(batch_start + batch_size, total)
232
- batch = items[batch_start:batch_end]
233
- batch_num = batch_start // batch_size + 1
234
- total_batches = (total + batch_size - 1) // batch_size
235
-
236
- logger.info(f"Batch {batch_num}/{total_batches} ({processed}/{total} done)")
237
-
238
- try:
239
- batch_images = [img for img, _ in batch]
240
- texts = engine.generate_plain(images=batch_images, use_tqdm=False)
241
-
242
- for (_, md_path), text in zip(batch, texts):
243
- md_path.parent.mkdir(parents=True, exist_ok=True)
244
- md_path.write_text(text.strip(), encoding="utf-8")
245
- processed += 1
246
-
247
- except Exception as e:
248
- logger.error(f"Batch {batch_num} failed: {e}")
249
- for _, md_path in batch:
250
- md_path.parent.mkdir(parents=True, exist_ok=True)
251
- md_path.write_text(f"[OCR ERROR: {e}]", encoding="utf-8")
252
- errors += len(batch)
253
- processed += len(batch)
254
-
255
- elapsed = time.time() - start_time
256
- elapsed_str = f"{elapsed / 60:.1f} min" if elapsed > 60 else f"{elapsed:.1f}s"
257
-
258
- logger.info("=" * 50)
259
- logger.info(f"Done! Processed {total} images in {elapsed_str}")
260
- logger.info(f" Output: {output_dir}")
261
- logger.info(f" Errors: {errors}")
262
- if total > 0:
263
- logger.info(f" Speed: {total / elapsed:.2f} images/sec")
264
-
265
- if args.verbose:
266
- import importlib.metadata
267
-
268
- logger.info("--- Package versions ---")
269
- for pkg in ["falcon-perception", "torch", "pillow", "pymupdf"]:
270
- try:
271
- logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
272
- except importlib.metadata.PackageNotFoundError:
273
- logger.info(f" {pkg}: not installed")
274
-
275
-
276
- if __name__ == "__main__":
277
- if len(sys.argv) == 1:
278
- print("=" * 60)
279
- print("Falcon OCR Bucket Script")
280
- print("=" * 60)
281
- print(f"\nModel: {MODEL_ID} (0.3B, Apache 2.0)")
282
- print("OCR images/PDFs from a directory -> markdown files.")
283
- print("Designed for HF Buckets mounted as volumes.")
284
- print()
285
- print("Usage:")
286
- print(" uv run falcon-ocr-bucket.py INPUT_DIR OUTPUT_DIR")
287
- print()
288
- print("Examples:")
289
- print(" uv run falcon-ocr-bucket.py ./images ./output")
290
- print()
291
- print("HF Jobs with bucket volumes:")
292
- print(" hf jobs uv run --flavor l4x1 -s HF_TOKEN \\")
293
- print(" -v hf://buckets/user/ocr-input:/input:ro \\")
294
- print(" -v hf://buckets/user/ocr-output:/output \\")
295
- print(
296
- " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/falcon-ocr-bucket.py \\"
297
- )
298
- print(" /input /output")
299
- print()
300
- print("For full help: uv run falcon-ocr-bucket.py --help")
301
- sys.exit(0)
302
-
303
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
falcon-ocr.py DELETED
@@ -1,466 +0,0 @@
1
- # /// script
2
- # requires-python = ">=3.11"
3
- # dependencies = [
4
- # "datasets>=4.0.0",
5
- # "huggingface-hub",
6
- # "pillow",
7
- # "torch>=2.5",
8
- # "torchvision",
9
- # "falcon-perception",
10
- # ]
11
- # ///
12
-
13
- """
14
- Convert document images to text using Falcon OCR with the falcon-perception engine.
15
-
16
- Uses the optimized OCRInferenceEngine with CUDA graphs and paged inference
17
- for much faster throughput than the raw transformers API.
18
-
19
- Features:
20
- - Compact: Only 0.3B parameters
21
- - Fast: Optimized inference with CUDA graphs
22
- - Multi-format: Plain text, LaTeX formulas, HTML tables
23
- - Layout-aware: Optional 2-stage pipeline (layout detection + per-region OCR)
24
-
25
- Model: tiiuae/Falcon-OCR
26
- Backend: falcon-perception (OCRInferenceEngine)
27
- License: Apache 2.0
28
-
29
- Examples:
30
- # Basic text OCR
31
- uv run falcon-ocr.py input-dataset output-dataset
32
-
33
- # Test with small sample
34
- uv run falcon-ocr.py dataset test --max-samples 5 --shuffle
35
-
36
- # Run on HF Jobs with GPU
37
- hf jobs uv run --flavor l4x1 \\
38
- -s HF_TOKEN \\
39
- falcon-ocr.py \\
40
- input-dataset output-dataset --max-samples 10
41
- """
42
-
43
- import argparse
44
- import io
45
- import json
46
- import logging
47
- import os
48
- import sys
49
- import time
50
- from datetime import datetime
51
- from typing import Any, Dict, Union
52
-
53
- import torch
54
- from datasets import load_dataset
55
- from huggingface_hub import DatasetCard, login
56
- from PIL import Image
57
-
58
- logging.basicConfig(level=logging.INFO)
59
- logger = logging.getLogger(__name__)
60
-
61
- MODEL_ID = "tiiuae/Falcon-OCR"
62
-
63
- TASK_MODES = {
64
- "plain": "Full-page text extraction",
65
- }
66
-
67
-
68
- def check_cuda_availability():
69
- if not torch.cuda.is_available():
70
- logger.error("CUDA is not available. This script requires a GPU.")
71
- logger.error("For cloud execution, use HF Jobs with --flavor l4x1 or similar.")
72
- sys.exit(1)
73
- else:
74
- logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
75
-
76
-
77
- def ensure_output_columns_free(dataset, columns, overwrite=False):
78
- """Fail fast if an output column would collide with an existing input column.
79
-
80
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
81
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
82
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
83
- column(s) here instead (logged) so the later add_column is clean.
84
- """
85
- clash = [c for c in columns if c in dataset.column_names]
86
- if not clash:
87
- return dataset
88
- if overwrite:
89
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
90
- return dataset.remove_columns(clash)
91
- logger.error(
92
- f"Output column(s) {clash} already exist in the input dataset "
93
- f"(columns: {dataset.column_names})."
94
- )
95
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
96
- sys.exit(1)
97
-
98
-
99
- def prepare_image(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:
100
- if isinstance(image, Image.Image):
101
- pil_img = image
102
- elif isinstance(image, dict) and "bytes" in image:
103
- pil_img = Image.open(io.BytesIO(image["bytes"]))
104
- elif isinstance(image, str):
105
- pil_img = Image.open(image)
106
- else:
107
- raise ValueError(f"Unsupported image type: {type(image)}")
108
- return pil_img.convert("RGB")
109
-
110
-
111
- def create_dataset_card(
112
- source_dataset: str,
113
- task_mode: str,
114
- num_samples: int,
115
- processing_time: str,
116
- image_column: str = "image",
117
- split: str = "train",
118
- ) -> str:
119
- task_description = TASK_MODES[task_mode]
120
- return f"""---
121
- tags:
122
- - ocr
123
- - document-processing
124
- - falcon-ocr
125
- - {task_mode}
126
- - uv-script
127
- - generated
128
- ---
129
-
130
- # Document Processing using Falcon OCR ({task_mode} mode)
131
-
132
- This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using [Falcon OCR](https://huggingface.co/tiiuae/Falcon-OCR), a 0.3B early-fusion vision-language model.
133
-
134
- ## Processing Details
135
-
136
- - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
137
- - **Model**: [{MODEL_ID}](https://huggingface.co/{MODEL_ID})
138
- - **Task Mode**: `{task_mode}` - {task_description}
139
- - **Number of Samples**: {num_samples:,}
140
- - **Processing Time**: {processing_time}
141
- - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
142
- - **Backend**: falcon-perception (OCRInferenceEngine)
143
-
144
- ## Reproduction
145
-
146
- ```bash
147
- uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/falcon-ocr.py \\
148
- {source_dataset} \\
149
- <output-dataset> \\
150
- --task-mode {task_mode} \\
151
- --image-column {image_column}
152
- ```
153
-
154
- Generated with [UV Scripts](https://huggingface.co/uv-scripts)
155
- """
156
-
157
-
158
- def main(
159
- input_dataset: str,
160
- output_dataset: str,
161
- image_column: str = "image",
162
- task_mode: str = "plain",
163
- hf_token: str = None,
164
- split: str = "train",
165
- max_samples: int = None,
166
- private: bool = False,
167
- shuffle: bool = False,
168
- seed: int = 42,
169
- output_column: str = "markdown",
170
- overwrite: bool = False,
171
- config: str = None,
172
- create_pr: bool = False,
173
- compile: bool = True,
174
- cudagraph: bool = True,
175
- progress: bool = False,
176
- verbose: bool = False,
177
- ):
178
- check_cuda_availability()
179
- start_time = datetime.now()
180
-
181
- HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
182
- if HF_TOKEN:
183
- login(token=HF_TOKEN)
184
-
185
- if task_mode not in TASK_MODES:
186
- raise ValueError(
187
- f"Invalid task_mode '{task_mode}'. Choose from: {list(TASK_MODES.keys())}"
188
- )
189
-
190
- logger.info(f"Task mode: {task_mode} - {TASK_MODES[task_mode]}")
191
- logger.info(f"Output column: {output_column}")
192
-
193
- # Load dataset
194
- logger.info(f"Loading dataset: {input_dataset}")
195
- dataset = load_dataset(input_dataset, split=split)
196
-
197
- if image_column not in dataset.column_names:
198
- raise ValueError(
199
- f"Column '{image_column}' not found. Available: {dataset.column_names}"
200
- )
201
-
202
- # Fail fast if the output column would collide with an existing input column
203
- dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
204
-
205
- if shuffle:
206
- logger.info(f"Shuffling dataset with seed {seed}")
207
- dataset = dataset.shuffle(seed=seed)
208
-
209
- if max_samples:
210
- dataset = dataset.select(range(min(max_samples, len(dataset))))
211
- logger.info(f"Limited to {len(dataset)} samples")
212
-
213
- # Load model using falcon-perception
214
- logger.info(f"Loading model: {MODEL_ID} via falcon-perception engine")
215
- from falcon_perception import load_and_prepare_model
216
- from falcon_perception.data import ImageProcessor
217
- from falcon_perception.paged_ocr_inference import OCRInferenceEngine
218
-
219
- model, tokenizer, model_args = load_and_prepare_model(
220
- hf_model_id=MODEL_ID,
221
- device="cuda",
222
- dtype="bfloat16",
223
- compile=compile,
224
- )
225
-
226
- image_processor = ImageProcessor(patch_size=16, merge_size=1)
227
- engine = OCRInferenceEngine(
228
- model, tokenizer, image_processor, capture_cudagraph=cudagraph
229
- )
230
- logger.info(f"Engine loaded. compile={compile}, cudagraph={cudagraph}")
231
-
232
- # Prepare all images
233
- logger.info(f"Processing {len(dataset)} images...")
234
- all_outputs = []
235
-
236
- # Batch plain OCR for better throughput
237
- batch_size = 8
238
- total_batches = (len(dataset) + batch_size - 1) // batch_size
239
- for batch_idx, batch_start in enumerate(range(0, len(dataset), batch_size), 1):
240
- batch_end = min(batch_start + batch_size, len(dataset))
241
- logger.info(f"Batch {batch_idx}/{total_batches} ({batch_start}/{len(dataset)} done)")
242
- batch_images = []
243
- for i in range(batch_start, batch_end):
244
- try:
245
- batch_images.append(prepare_image(dataset[i][image_column]))
246
- except Exception as e:
247
- logger.error(f"Error preparing image {i}: {e}")
248
- batch_images.append(Image.new("RGB", (100, 100)))
249
-
250
- try:
251
- texts = engine.generate_plain(
252
- images=batch_images, use_tqdm=progress
253
- )
254
- all_outputs.extend(texts)
255
- except Exception as e:
256
- logger.error(f"Error processing batch {batch_start}-{batch_end}: {e}")
257
- all_outputs.extend(
258
- [f"[OCR ERROR: {str(e)[:200]}]"] * len(batch_images)
259
- )
260
-
261
- # Calculate processing time
262
- processing_duration = datetime.now() - start_time
263
- processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
264
-
265
- # Add output column
266
- logger.info(f"Adding '{output_column}' column to dataset")
267
- dataset = dataset.add_column(output_column, all_outputs)
268
-
269
- # Track inference info
270
- inference_entry = {
271
- "model_id": MODEL_ID,
272
- "model_name": "Falcon-OCR",
273
- "model_size": "0.3B",
274
- "task_mode": task_mode,
275
- "column_name": output_column,
276
- "timestamp": datetime.now().isoformat(),
277
- "backend": "falcon-perception",
278
- }
279
-
280
- if "inference_info" in dataset.column_names:
281
- def update_inference_info(example):
282
- try:
283
- existing_info = (
284
- json.loads(example["inference_info"])
285
- if example["inference_info"]
286
- else []
287
- )
288
- except (json.JSONDecodeError, TypeError):
289
- existing_info = []
290
- existing_info.append(inference_entry)
291
- return {"inference_info": json.dumps(existing_info)}
292
-
293
- dataset = dataset.map(update_inference_info)
294
- else:
295
- inference_list = [json.dumps([inference_entry])] * len(dataset)
296
- dataset = dataset.add_column("inference_info", inference_list)
297
-
298
- # Push to hub
299
- logger.info(f"Pushing to {output_dataset}")
300
- max_retries = 3
301
- for attempt in range(1, max_retries + 1):
302
- try:
303
- if attempt > 1:
304
- logger.warning("Disabling XET (fallback to HTTP upload)")
305
- os.environ["HF_HUB_DISABLE_XET"] = "1"
306
- dataset.push_to_hub(
307
- output_dataset,
308
- private=private,
309
- token=HF_TOKEN,
310
- max_shard_size="500MB",
311
- **({"config_name": config} if config else {}),
312
- create_pr=create_pr,
313
- commit_message=f"Add {MODEL_ID} OCR results ({len(dataset)} samples)"
314
- + (f" [{config}]" if config else ""),
315
- )
316
- break
317
- except Exception as e:
318
- logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
319
- if attempt < max_retries:
320
- delay = 30 * (2 ** (attempt - 1))
321
- logger.info(f"Retrying in {delay}s...")
322
- time.sleep(delay)
323
- else:
324
- logger.error("All upload attempts failed. OCR results are lost.")
325
- sys.exit(1)
326
-
327
- # Create and push dataset card
328
- logger.info("Creating dataset card")
329
- card_content = create_dataset_card(
330
- source_dataset=input_dataset,
331
- task_mode=task_mode,
332
- num_samples=len(dataset),
333
- processing_time=processing_time_str,
334
- image_column=image_column,
335
- split=split,
336
- )
337
- card = DatasetCard(card_content)
338
- card.push_to_hub(output_dataset, token=HF_TOKEN)
339
-
340
- logger.info("Falcon OCR processing complete!")
341
- logger.info(
342
- f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
343
- )
344
- logger.info(f"Processing time: {processing_time_str}")
345
- logger.info(
346
- f"Speed: {len(dataset) / processing_duration.total_seconds():.2f} images/sec"
347
- )
348
-
349
- if verbose:
350
- import importlib.metadata
351
-
352
- logger.info("--- Resolved package versions ---")
353
- for pkg in [
354
- "falcon-perception", "transformers", "torch", "datasets", "pillow"
355
- ]:
356
- try:
357
- logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
358
- except importlib.metadata.PackageNotFoundError:
359
- logger.info(f" {pkg}: not installed")
360
-
361
-
362
- if __name__ == "__main__":
363
- if len(sys.argv) == 1:
364
- print("=" * 70)
365
- print("Falcon OCR - 0.3B Document OCR (falcon-perception engine)")
366
- print("=" * 70)
367
- print(f"\nModel: {MODEL_ID}")
368
- print("License: Apache 2.0")
369
- print("\nTask Modes:")
370
- for mode, description in TASK_MODES.items():
371
- print(f" {mode:10} - {description}")
372
- print("\nExamples:")
373
- print(" uv run falcon-ocr.py input-dataset output-dataset")
374
- print(" uv run falcon-ocr.py dense-docs output --task-mode layout")
375
- print("\nFor full help: uv run falcon-ocr.py --help")
376
- sys.exit(0)
377
-
378
- parser = argparse.ArgumentParser(
379
- description="Document OCR using Falcon OCR (0.3B, falcon-perception engine)",
380
- formatter_class=argparse.RawDescriptionHelpFormatter,
381
- epilog=__doc__,
382
- )
383
-
384
- parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
385
- parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
386
- parser.add_argument(
387
- "--image-column", default="image",
388
- help="Column containing images (default: image)",
389
- )
390
- parser.add_argument(
391
- "--task-mode", choices=list(TASK_MODES.keys()), default="plain",
392
- help="Task type: plain (default), layout",
393
- )
394
- parser.add_argument("--hf-token", help="Hugging Face API token")
395
- parser.add_argument(
396
- "--split", default="train", help="Dataset split (default: train)",
397
- )
398
- parser.add_argument(
399
- "--max-samples", type=int,
400
- help="Maximum number of samples to process (for testing)",
401
- )
402
- parser.add_argument(
403
- "--private", action="store_true", help="Make output dataset private",
404
- )
405
- parser.add_argument(
406
- "--shuffle", action="store_true", help="Shuffle dataset before processing",
407
- )
408
- parser.add_argument(
409
- "--seed", type=int, default=42, help="Random seed for shuffling (default: 42)",
410
- )
411
- parser.add_argument(
412
- "--output-column", default="markdown",
413
- help="Column name for output text (default: markdown)",
414
- )
415
- parser.add_argument(
416
- "--overwrite",
417
- action="store_true",
418
- help="Replace the output column if it already exists in the input dataset "
419
- "(default: error out to avoid clobbering an existing column).",
420
- )
421
- parser.add_argument(
422
- "--config",
423
- help="Config/subset name for Hub (for benchmarking multiple models)",
424
- )
425
- parser.add_argument(
426
- "--create-pr", action="store_true",
427
- help="Create a pull request instead of pushing directly",
428
- )
429
- parser.add_argument(
430
- "--no-compile", action="store_true",
431
- help="Disable torch.compile",
432
- )
433
- parser.add_argument(
434
- "--no-cudagraph", action="store_true",
435
- help="Disable CUDA graph capture",
436
- )
437
- parser.add_argument(
438
- "--progress", action="store_true",
439
- help="Show per-image progress bar from the inference engine",
440
- )
441
- parser.add_argument(
442
- "--verbose", action="store_true", help="Log resolved package versions",
443
- )
444
-
445
- args = parser.parse_args()
446
-
447
- main(
448
- input_dataset=args.input_dataset,
449
- output_dataset=args.output_dataset,
450
- image_column=args.image_column,
451
- task_mode=args.task_mode,
452
- hf_token=args.hf_token,
453
- split=args.split,
454
- max_samples=args.max_samples,
455
- private=args.private,
456
- shuffle=args.shuffle,
457
- seed=args.seed,
458
- output_column=args.output_column,
459
- overwrite=args.overwrite,
460
- config=args.config,
461
- create_pr=args.create_pr,
462
- compile=not args.no_compile,
463
- cudagraph=not args.no_cudagraph,
464
- progress=args.progress,
465
- verbose=args.verbose,
466
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
firered-ocr.py CHANGED
@@ -1,7 +1,7 @@
1
  # /// script
2
  # requires-python = ">=3.11"
3
  # dependencies = [
4
- # "datasets>=4.0.0",
5
  # "huggingface-hub",
6
  # "pillow",
7
  # "vllm>=0.15.1",
@@ -39,10 +39,6 @@ from huggingface_hub import DatasetCard, login
39
  from PIL import Image
40
  from toolz import partition_all
41
  from tqdm.auto import tqdm
42
- # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
43
- # default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
44
- # lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
45
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
46
  from vllm import LLM, SamplingParams
47
 
48
  logging.basicConfig(level=logging.INFO)
@@ -90,28 +86,6 @@ def check_cuda_availability():
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 make_ocr_message(
116
  image: Union[Image.Image, Dict[str, Any], str],
117
  prompt: str = FIRERED_OCR_PROMPT,
@@ -130,10 +104,10 @@ def make_ocr_message(
130
  # Convert to RGB
131
  pil_img = pil_img.convert("RGB")
132
 
133
- # Convert to base64 data URI (JPEG is faster than PNG for encoding)
134
  buf = io.BytesIO()
135
- pil_img.save(buf, format="JPEG", quality=95)
136
- data_uri = f"data:image/jpeg;base64,{base64.b64encode(buf.getvalue()).decode()}"
137
 
138
  # Return message in vLLM format
139
  return [
@@ -254,7 +228,7 @@ def main(
254
  image_column: str = "image",
255
  batch_size: int = 16,
256
  model: str = "FireRedTeam/FireRed-OCR",
257
- max_model_len: int = 32768,
258
  max_tokens: int = 8192,
259
  gpu_memory_utilization: float = 0.8,
260
  hf_token: str = None,
@@ -264,7 +238,6 @@ def main(
264
  shuffle: bool = False,
265
  seed: int = 42,
266
  output_column: str = "markdown",
267
- overwrite: bool = False,
268
  config: str = None,
269
  create_pr: bool = False,
270
  ):
@@ -291,9 +264,6 @@ def main(
291
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
292
  )
293
 
294
- # Fail fast if the output column would collide with an existing input column
295
- dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
296
-
297
  # Shuffle if requested
298
  if shuffle:
299
  logger.info(f"Shuffling dataset with seed {seed}")
@@ -365,10 +335,7 @@ def main(
365
  processing_duration = datetime.now() - start_time
366
  processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
367
 
368
- # Add output column to dataset (remove existing column if present)
369
- if output_column in dataset.column_names:
370
- logger.info(f"Removing existing '{output_column}' column before adding new results")
371
- dataset = dataset.remove_columns([output_column])
372
  logger.info(f"Adding '{output_column}' column to dataset")
373
  dataset = dataset.add_column(output_column, all_outputs)
374
 
@@ -513,8 +480,8 @@ Examples:
513
  parser.add_argument(
514
  "--max-model-len",
515
  type=int,
516
- default=32768,
517
- help="Maximum model context length (default: 32768)",
518
  )
519
  parser.add_argument(
520
  "--max-tokens",
@@ -554,12 +521,6 @@ Examples:
554
  default="markdown",
555
  help="Column name for output text (default: markdown)",
556
  )
557
- parser.add_argument(
558
- "--overwrite",
559
- action="store_true",
560
- help="Replace the output column if it already exists in the input dataset "
561
- "(default: error out to avoid clobbering an existing column).",
562
- )
563
  parser.add_argument(
564
  "--config",
565
  help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
@@ -588,7 +549,6 @@ Examples:
588
  shuffle=args.shuffle,
589
  seed=args.seed,
590
  output_column=args.output_column,
591
- overwrite=args.overwrite,
592
  config=args.config,
593
  create_pr=args.create_pr,
594
  )
 
1
  # /// script
2
  # requires-python = ">=3.11"
3
  # dependencies = [
4
+ # "datasets",
5
  # "huggingface-hub",
6
  # "pillow",
7
  # "vllm>=0.15.1",
 
39
  from PIL import Image
40
  from toolz import partition_all
41
  from tqdm.auto import tqdm
 
 
 
 
42
  from vllm import LLM, SamplingParams
43
 
44
  logging.basicConfig(level=logging.INFO)
 
86
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
87
 
88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  def make_ocr_message(
90
  image: Union[Image.Image, Dict[str, Any], str],
91
  prompt: str = FIRERED_OCR_PROMPT,
 
104
  # Convert to RGB
105
  pil_img = pil_img.convert("RGB")
106
 
107
+ # Convert to base64 data URI
108
  buf = io.BytesIO()
109
+ pil_img.save(buf, format="PNG")
110
+ data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
111
 
112
  # Return message in vLLM format
113
  return [
 
228
  image_column: str = "image",
229
  batch_size: int = 16,
230
  model: str = "FireRedTeam/FireRed-OCR",
231
+ max_model_len: int = 8192,
232
  max_tokens: int = 8192,
233
  gpu_memory_utilization: float = 0.8,
234
  hf_token: str = None,
 
238
  shuffle: bool = False,
239
  seed: int = 42,
240
  output_column: str = "markdown",
 
241
  config: str = None,
242
  create_pr: bool = False,
243
  ):
 
264
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
265
  )
266
 
 
 
 
267
  # Shuffle if requested
268
  if shuffle:
269
  logger.info(f"Shuffling dataset with seed {seed}")
 
335
  processing_duration = datetime.now() - start_time
336
  processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
337
 
338
+ # Add output column to dataset
 
 
 
339
  logger.info(f"Adding '{output_column}' column to dataset")
340
  dataset = dataset.add_column(output_column, all_outputs)
341
 
 
480
  parser.add_argument(
481
  "--max-model-len",
482
  type=int,
483
+ default=8192,
484
+ help="Maximum model context length (default: 8192)",
485
  )
486
  parser.add_argument(
487
  "--max-tokens",
 
521
  default="markdown",
522
  help="Column name for output text (default: markdown)",
523
  )
 
 
 
 
 
 
524
  parser.add_argument(
525
  "--config",
526
  help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
 
549
  shuffle=args.shuffle,
550
  seed=args.seed,
551
  output_column=args.output_column,
 
552
  config=args.config,
553
  create_pr=args.create_pr,
554
  )
glm-ocr-bucket.py DELETED
@@ -1,394 +0,0 @@
1
- # /// script
2
- # requires-python = ">=3.11"
3
- # dependencies = [
4
- # "pillow",
5
- # "pymupdf",
6
- # ]
7
- #
8
- # [tool.hf-jobs]
9
- # image = "vllm/vllm-openai:v0.29.0"
10
- # python = "/usr/bin/python3"
11
- # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
12
- # flavor = "a10g-small"
13
- # secrets = ["HF_TOKEN"]
14
- # ///
15
-
16
- """
17
- OCR images and PDFs from a directory using GLM-OCR, writing markdown files.
18
-
19
- Designed to work with HF Buckets mounted as volumes via `hf jobs uv run -v ...`.
20
-
21
- The script reads images/PDFs from INPUT_DIR, runs GLM-OCR via vLLM, and writes
22
- one .md file per image (or per PDF page) to OUTPUT_DIR, preserving directory structure.
23
-
24
- Input: Output:
25
- /input/page1.png → /output/page1.md
26
- /input/report.pdf → /output/report/page_001.md
27
- (3 pages) /output/report/page_002.md
28
- /output/report/page_003.md
29
- /input/sub/photo.jpg → /output/sub/photo.md
30
-
31
- Examples:
32
-
33
- # Local test
34
- uv run --with vllm==0.29.0 glm-ocr-bucket.py ./test-images ./test-output
35
-
36
- # HF Jobs with bucket volumes (flavor + secrets come from the
37
- # [tool.hf-jobs] header; needs hf CLI 1.32+)
38
- hf jobs uv run \\
39
- -v hf://buckets/user/ocr-input:/input:ro \\
40
- -v hf://buckets/user/ocr-output:/output \\
41
- glm-ocr-bucket.py /input /output
42
-
43
- Model: zai-org/GLM-OCR (0.9B, 94.62% OmniDocBench V1.5, MIT licensed)
44
- """
45
-
46
- import argparse
47
- import base64
48
- import io
49
- import logging
50
- import sys
51
- import time
52
- from pathlib import Path
53
-
54
- import torch
55
- from PIL import Image
56
- import os
57
- # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
58
- # default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
59
- # lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
60
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
61
- from vllm import LLM, SamplingParams
62
-
63
- logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
64
- logger = logging.getLogger(__name__)
65
-
66
- MODEL = "zai-org/GLM-OCR"
67
-
68
- TASK_PROMPTS = {
69
- "ocr": "Text Recognition:",
70
- "formula": "Formula Recognition:",
71
- "table": "Table Recognition:",
72
- }
73
-
74
- IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".tiff", ".tif", ".bmp", ".webp"}
75
-
76
-
77
- def check_cuda_availability():
78
- if not torch.cuda.is_available():
79
- logger.error("CUDA is not available. This script requires a GPU.")
80
- sys.exit(1)
81
- logger.info(f"CUDA available. GPU: {torch.cuda.get_device_name(0)}")
82
-
83
-
84
- def make_ocr_message(image: Image.Image, task: str = "ocr") -> list[dict]:
85
- """Create chat message for GLM-OCR from a PIL Image."""
86
- image = image.convert("RGB")
87
- buf = io.BytesIO()
88
- image.save(buf, format="PNG")
89
- data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
90
-
91
- return [
92
- {
93
- "role": "user",
94
- "content": [
95
- {"type": "image_url", "image_url": {"url": data_uri}},
96
- {"type": "text", "text": TASK_PROMPTS.get(task, TASK_PROMPTS["ocr"])},
97
- ],
98
- }
99
- ]
100
-
101
-
102
- def discover_files(input_dir: Path, limit: int | None = None) -> list[Path]:
103
- """Discover image and PDF files under input_dir.
104
-
105
- Without `limit`, returns the full sorted list (deterministic order).
106
- With `limit`, stops scanning once `limit` matching files are found
107
- and returns them in filesystem order (much faster on huge mounted
108
- buckets, but ordering is not deterministic).
109
- """
110
- files = []
111
- iterator = (
112
- input_dir.rglob("*") if limit is not None else sorted(input_dir.rglob("*"))
113
- )
114
- for path in iterator:
115
- if not path.is_file():
116
- continue
117
- ext = path.suffix.lower()
118
- if ext in IMAGE_EXTENSIONS or ext == ".pdf":
119
- files.append(path)
120
- if limit is not None and len(files) >= limit:
121
- break
122
- return files
123
-
124
-
125
- def prepare_images(
126
- files: list[Path], input_dir: Path, output_dir: Path, pdf_dpi: int
127
- ) -> list[tuple[Image.Image, Path]]:
128
- """
129
- Convert discovered files into (PIL.Image, output_md_path) pairs.
130
-
131
- Images map 1:1. PDFs expand to one image per page in a subdirectory.
132
- """
133
- import fitz # pymupdf
134
-
135
- items: list[tuple[Image.Image, Path]] = []
136
-
137
- for file_path in files:
138
- rel = file_path.relative_to(input_dir)
139
- ext = file_path.suffix.lower()
140
-
141
- if ext == ".pdf":
142
- # PDF → one .md per page in a subdirectory named after the PDF
143
- pdf_output_dir = output_dir / rel.with_suffix("")
144
- try:
145
- doc = fitz.open(file_path)
146
- num_pages = len(doc)
147
- logger.info(f"PDF: {rel} ({num_pages} pages)")
148
- for page_num in range(num_pages):
149
- page = doc[page_num]
150
- # Render at specified DPI
151
- zoom = pdf_dpi / 72.0
152
- mat = fitz.Matrix(zoom, zoom)
153
- pix = page.get_pixmap(matrix=mat)
154
- img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
155
- md_path = pdf_output_dir / f"page_{page_num + 1:03d}.md"
156
- items.append((img, md_path))
157
- doc.close()
158
- except Exception as e:
159
- logger.error(f"Failed to open PDF {rel}: {e}")
160
- else:
161
- # Image → single .md
162
- try:
163
- img = Image.open(file_path).convert("RGB")
164
- md_path = output_dir / rel.with_suffix(".md")
165
- items.append((img, md_path))
166
- except Exception as e:
167
- logger.error(f"Failed to open image {rel}: {e}")
168
-
169
- return items
170
-
171
-
172
- def main():
173
- parser = argparse.ArgumentParser(
174
- description="OCR images/PDFs from a directory using GLM-OCR, output markdown files.",
175
- formatter_class=argparse.RawDescriptionHelpFormatter,
176
- epilog="""
177
- Task modes:
178
- ocr Text recognition to markdown (default)
179
- formula LaTeX formula recognition
180
- table Table extraction (HTML)
181
-
182
- Examples:
183
- uv run --with vllm==0.29.0 glm-ocr-bucket.py ./images ./output
184
- uv run --with vllm==0.29.0 glm-ocr-bucket.py /input /output --task table --pdf-dpi 200
185
-
186
- HF Jobs with bucket volumes (flavor + secrets from the [tool.hf-jobs] header; hf CLI 1.32+):
187
- hf jobs uv run \\
188
- -v hf://buckets/user/input-bucket:/input:ro \\
189
- -v hf://buckets/user/output-bucket:/output \\
190
- glm-ocr-bucket.py /input /output
191
- """,
192
- )
193
- parser.add_argument("input_dir", help="Directory containing images and/or PDFs")
194
- parser.add_argument("output_dir", help="Directory to write markdown output files")
195
- parser.add_argument(
196
- "--task",
197
- choices=["ocr", "formula", "table"],
198
- default="ocr",
199
- help="OCR task mode (default: ocr)",
200
- )
201
- parser.add_argument(
202
- "--batch-size", type=int, default=16, help="Batch size for vLLM (default: 16)"
203
- )
204
- parser.add_argument(
205
- "--max-model-len",
206
- type=int,
207
- default=8192,
208
- help="Max model context length (default: 8192)",
209
- )
210
- parser.add_argument(
211
- "--max-tokens",
212
- type=int,
213
- default=8192,
214
- help="Max output tokens (default: 8192)",
215
- )
216
- parser.add_argument(
217
- "--gpu-memory-utilization",
218
- type=float,
219
- default=0.8,
220
- help="GPU memory utilization (default: 0.8)",
221
- )
222
- parser.add_argument(
223
- "--pdf-dpi",
224
- type=int,
225
- default=300,
226
- help="DPI for PDF page rendering (default: 300)",
227
- )
228
- parser.add_argument(
229
- "--temperature",
230
- type=float,
231
- default=0.01,
232
- help="Sampling temperature (default: 0.01)",
233
- )
234
- parser.add_argument(
235
- "--top-p", type=float, default=0.00001, help="Top-p sampling (default: 0.00001)"
236
- )
237
- parser.add_argument(
238
- "--repetition-penalty",
239
- type=float,
240
- default=1.1,
241
- help="Repetition penalty (default: 1.1)",
242
- )
243
- parser.add_argument(
244
- "--max-samples",
245
- type=int,
246
- default=None,
247
- help="Limit the number of input files to process (files, not pages; "
248
- "a PDF still yields all its pages). Stops scanning early once the "
249
- "limit is reached; file order is then filesystem-dependent.",
250
- )
251
- parser.add_argument(
252
- "--verbose",
253
- action="store_true",
254
- help="Print resolved package versions",
255
- )
256
-
257
- args = parser.parse_args()
258
- if args.max_samples is not None and args.max_samples < 1:
259
- parser.error("--max-samples must be 1 or more")
260
-
261
- check_cuda_availability()
262
-
263
- input_dir = Path(args.input_dir)
264
- output_dir = Path(args.output_dir)
265
-
266
- if not input_dir.is_dir():
267
- logger.error(f"Input directory does not exist: {input_dir}")
268
- sys.exit(1)
269
-
270
- output_dir.mkdir(parents=True, exist_ok=True)
271
-
272
- # Discover and prepare
273
- start_time = time.time()
274
-
275
- if args.max_samples is not None:
276
- logger.info(
277
- f"Scanning {input_dir} for up to {args.max_samples} images/PDFs "
278
- f"(early termination, --max-samples)..."
279
- )
280
- else:
281
- logger.info(f"Scanning {input_dir} for images and PDFs...")
282
- files = discover_files(input_dir, limit=args.max_samples)
283
- if not files:
284
- logger.error(f"No image or PDF files found in {input_dir}")
285
- sys.exit(1)
286
-
287
- pdf_count = sum(1 for f in files if f.suffix.lower() == ".pdf")
288
- img_count = len(files) - pdf_count
289
- logger.info(f"Found {img_count} image(s) and {pdf_count} PDF(s)")
290
-
291
- logger.info("Preparing images (rendering PDFs)...")
292
- items = prepare_images(files, input_dir, output_dir, args.pdf_dpi)
293
- if not items:
294
- logger.error("No processable images after preparation")
295
- sys.exit(1)
296
-
297
- logger.info(f"Total images to OCR: {len(items)}")
298
-
299
- # Init vLLM
300
- logger.info(f"Initializing vLLM with {MODEL}...")
301
- llm = LLM(
302
- model=MODEL,
303
- trust_remote_code=True,
304
- max_model_len=args.max_model_len,
305
- gpu_memory_utilization=args.gpu_memory_utilization,
306
- limit_mm_per_prompt={"image": 1},
307
- )
308
-
309
- sampling_params = SamplingParams(
310
- temperature=args.temperature,
311
- top_p=args.top_p,
312
- max_tokens=args.max_tokens,
313
- repetition_penalty=args.repetition_penalty,
314
- )
315
-
316
- # Process in batches
317
- errors = 0
318
- processed = 0
319
- total = len(items)
320
-
321
- for batch_start in range(0, total, args.batch_size):
322
- batch_end = min(batch_start + args.batch_size, total)
323
- batch = items[batch_start:batch_end]
324
- batch_num = batch_start // args.batch_size + 1
325
- total_batches = (total + args.batch_size - 1) // args.batch_size
326
-
327
- logger.info(f"Batch {batch_num}/{total_batches} ({processed}/{total} done)")
328
-
329
- try:
330
- messages = [make_ocr_message(img, task=args.task) for img, _ in batch]
331
- outputs = llm.chat(messages, sampling_params)
332
-
333
- for (_, md_path), output in zip(batch, outputs):
334
- text = output.outputs[0].text.strip()
335
- md_path.parent.mkdir(parents=True, exist_ok=True)
336
- md_path.write_text(text, encoding="utf-8")
337
- processed += 1
338
-
339
- except Exception as e:
340
- logger.error(f"Batch {batch_num} failed: {e}")
341
- # Write error markers for failed batch
342
- for _, md_path in batch:
343
- md_path.parent.mkdir(parents=True, exist_ok=True)
344
- md_path.write_text(f"[OCR ERROR: {e}]", encoding="utf-8")
345
- errors += len(batch)
346
- processed += len(batch)
347
-
348
- elapsed = time.time() - start_time
349
- elapsed_str = f"{elapsed / 60:.1f} min" if elapsed > 60 else f"{elapsed:.1f}s"
350
-
351
- logger.info("=" * 50)
352
- logger.info(f"Done! Processed {total} images in {elapsed_str}")
353
- logger.info(f" Output: {output_dir}")
354
- logger.info(f" Errors: {errors}")
355
- if total > 0:
356
- logger.info(f" Speed: {total / elapsed:.2f} images/sec")
357
-
358
- if args.verbose:
359
- import importlib.metadata
360
-
361
- logger.info("--- Package versions ---")
362
- for pkg in ["vllm", "transformers", "torch", "pillow", "pymupdf"]:
363
- try:
364
- logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
365
- except importlib.metadata.PackageNotFoundError:
366
- logger.info(f" {pkg}: not installed")
367
-
368
-
369
- if __name__ == "__main__":
370
- if len(sys.argv) == 1:
371
- print("=" * 60)
372
- print("GLM-OCR Bucket Script")
373
- print("=" * 60)
374
- print("\nOCR images/PDFs from a directory → markdown files.")
375
- print("Designed for HF Buckets mounted as volumes.")
376
- print()
377
- print("Usage:")
378
- print(" uv run --with vllm==0.29.0 glm-ocr-bucket.py INPUT_DIR OUTPUT_DIR")
379
- print()
380
- print("Examples:")
381
- print(" uv run --with vllm==0.29.0 glm-ocr-bucket.py ./images ./output")
382
- print(" uv run --with vllm==0.29.0 glm-ocr-bucket.py /input /output --task table")
383
- print()
384
- print("HF Jobs with bucket volumes (flavor + secrets from the")
385
- print("[tool.hf-jobs] header; needs hf CLI 1.32+):")
386
- print(" hf jobs uv run \\")
387
- print(" -v hf://buckets/user/ocr-input:/input:ro \\")
388
- print(" -v hf://buckets/user/ocr-output:/output \\")
389
- print(" glm-ocr-bucket.py /input /output")
390
- print()
391
- print("For full help: uv run --with vllm==0.29.0 glm-ocr-bucket.py --help")
392
- sys.exit(0)
393
-
394
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
glm-ocr-v2.py CHANGED
@@ -69,10 +69,6 @@ from datasets import load_dataset
69
  from huggingface_hub import CommitScheduler, DatasetCard, HfApi, login
70
  from PIL import Image
71
  from toolz import partition_all
72
- # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
73
- # default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
74
- # lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
75
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
76
  from vllm import LLM, SamplingParams
77
 
78
  logging.basicConfig(level=logging.INFO)
@@ -136,28 +132,6 @@ def check_cuda_availability():
136
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
137
 
138
 
139
- def ensure_output_columns_free(dataset, columns, overwrite=False):
140
- """Fail fast if an output column would collide with an existing input column.
141
-
142
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
143
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
144
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
145
- column(s) here instead (logged) so the later add_column is clean.
146
- """
147
- clash = [c for c in columns if c in dataset.column_names]
148
- if not clash:
149
- return dataset
150
- if overwrite:
151
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
152
- return dataset.remove_columns(clash)
153
- logger.error(
154
- f"Output column(s) {clash} already exist in the input dataset "
155
- f"(columns: {dataset.column_names})."
156
- )
157
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
158
- sys.exit(1)
159
-
160
-
161
  def make_ocr_message(
162
  image: Union[Image.Image, Dict[str, Any], str],
163
  task: str = "ocr",
@@ -408,7 +382,6 @@ def main(
408
  shuffle: bool = False,
409
  seed: int = 42,
410
  output_column: str = "markdown",
411
- overwrite: bool = False,
412
  verbose: bool = False,
413
  config: str = None,
414
  create_pr: bool = False,
@@ -461,11 +434,6 @@ def main(
461
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
462
  )
463
 
464
- # Fail fast if the output column would collide with an existing input column.
465
- # The incremental path derives batch datasets via dataset.select(...), so dropping
466
- # it here (on --overwrite) also keeps those per-batch add_columns clean.
467
- dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
468
-
469
  if shuffle:
470
  logger.info(f"Shuffling dataset with seed {seed}")
471
  dataset = dataset.shuffle(seed=seed)
@@ -983,12 +951,6 @@ Examples:
983
  default="markdown",
984
  help="Column name for output text (default: markdown)",
985
  )
986
- parser.add_argument(
987
- "--overwrite",
988
- action="store_true",
989
- help="Replace the output column if it already exists in the input dataset "
990
- "(default: error out to avoid clobbering an existing column).",
991
- )
992
  parser.add_argument(
993
  "--verbose",
994
  action="store_true",
@@ -1033,7 +995,6 @@ Examples:
1033
  shuffle=args.shuffle,
1034
  seed=args.seed,
1035
  output_column=args.output_column,
1036
- overwrite=args.overwrite,
1037
  verbose=args.verbose,
1038
  config=args.config,
1039
  create_pr=args.create_pr,
 
69
  from huggingface_hub import CommitScheduler, DatasetCard, HfApi, login
70
  from PIL import Image
71
  from toolz import partition_all
 
 
 
 
72
  from vllm import LLM, SamplingParams
73
 
74
  logging.basicConfig(level=logging.INFO)
 
132
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
133
 
134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  def make_ocr_message(
136
  image: Union[Image.Image, Dict[str, Any], str],
137
  task: str = "ocr",
 
382
  shuffle: bool = False,
383
  seed: int = 42,
384
  output_column: str = "markdown",
 
385
  verbose: bool = False,
386
  config: str = None,
387
  create_pr: bool = False,
 
434
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
435
  )
436
 
 
 
 
 
 
437
  if shuffle:
438
  logger.info(f"Shuffling dataset with seed {seed}")
439
  dataset = dataset.shuffle(seed=seed)
 
951
  default="markdown",
952
  help="Column name for output text (default: markdown)",
953
  )
 
 
 
 
 
 
954
  parser.add_argument(
955
  "--verbose",
956
  action="store_true",
 
995
  shuffle=args.shuffle,
996
  seed=args.seed,
997
  output_column=args.output_column,
 
998
  verbose=args.verbose,
999
  config=args.config,
1000
  create_pr=args.create_pr,
glm-ocr.py CHANGED
@@ -1,20 +1,21 @@
1
  # /// script
2
  # requires-python = ">=3.11"
3
  # dependencies = [
4
- # "datasets>=4.0.0",
 
5
  # "huggingface-hub",
6
  # "pillow",
 
7
  # "toolz",
 
8
  # ]
9
  #
10
- # [tool.hf-jobs]
11
- # # >=v0.30.0: ships huggingface_hub>=1.31, which datasets>=5.1 imports (httpx). On v0.29.0,
12
- # # PYTHONPATH puts the image's older hub first and `import datasets` crashes.
13
- # image = "vllm/vllm-openai:v0.30.0"
14
- # python = "/usr/bin/python3"
15
- # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
16
- # flavor = "a10g-small"
17
- # secrets = ["HF_TOKEN"]
18
  # ///
19
 
20
  """
@@ -24,10 +25,10 @@ GLM-OCR is a compact 0.9B parameter OCR model achieving 94.62% on OmniDocBench V
24
  Uses CogViT visual encoder with GLM-0.5B language decoder and Multi-Token Prediction
25
  (MTP) loss for fast, accurate document parsing.
26
 
27
- NOTE: On Jobs, vLLM, torch and transformers come from the vllm/vllm-openai:v0.30.0
28
- image pinned in the [tool.hf-jobs] header (`hf` CLI 1.32+). GLM-OCR needs vLLM
29
- >=0.16.0 (PR #33005) and transformers>=5.1.0; the image has both. To run on your
30
- own GPU: `uv run --with vllm==0.30.0 glm-ocr.py ...`.
31
 
32
  Features:
33
  - 0.9B parameters (ultra-compact)
@@ -39,7 +40,7 @@ Features:
39
  - MIT licensed
40
 
41
  Model: zai-org/GLM-OCR
42
- vLLM: vllm/vllm-openai:v0.30.0 image (see the header)
43
  Performance: 94.62% on OmniDocBench V1.5
44
  """
45
 
@@ -52,21 +53,13 @@ import os
52
  import sys
53
  import time
54
  from datetime import datetime
55
- from typing import Any, Dict, List, Optional, Union
56
 
57
  import torch
58
  from datasets import load_dataset
59
  from huggingface_hub import DatasetCard, login
60
  from PIL import Image
61
  from toolz import partition_all
62
- # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
63
- # default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
64
- # lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
65
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
66
- # Same story for DeepGEMM: its init calls _find_cuda_home, which asserts on the
67
- # nvcc-less base image (a non-fatal warning that clutters the log and hides the real traceback).
68
- # Greedy OCR doesn't need the DeepGEMM JIT path, so disable it explicitly.
69
- os.environ.setdefault("VLLM_USE_DEEP_GEMM", "0")
70
  from vllm import LLM, SamplingParams
71
 
72
  logging.basicConfig(level=logging.INFO)
@@ -92,49 +85,9 @@ def check_cuda_availability():
92
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
93
 
94
 
95
- def ensure_output_columns_free(dataset, columns, overwrite=False):
96
- """Fail fast if an output column would collide with an existing input column.
97
-
98
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
99
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
100
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
101
- column(s) here instead (logged) so the later add_column is clean.
102
- """
103
- clash = [c for c in columns if c in dataset.column_names]
104
- if not clash:
105
- return dataset
106
- if overwrite:
107
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
108
- return dataset.remove_columns(clash)
109
- logger.error(
110
- f"Output column(s) {clash} already exist in the input dataset "
111
- f"(columns: {dataset.column_names})."
112
- )
113
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
114
- sys.exit(1)
115
-
116
-
117
- def downscale_to_max_pixels(img: Image.Image, max_pixels: Optional[int]) -> Image.Image:
118
- """Shrink an image so width*height <= max_pixels, preserving aspect ratio.
119
-
120
- GLM-OCR does no internal resizing and its card gives no resolution guidance. Capping
121
- input pixels bounds both image tokens and vision-encoder memory, a safety valve for very
122
- large (multi-MP) scans that can pressure GPU memory at high batch sizes. No-op when
123
- max_pixels is None or the image is already small enough (never upscales)."""
124
- if not max_pixels:
125
- return img
126
- w, h = img.size
127
- if w * h <= max_pixels:
128
- return img
129
- scale = (max_pixels / (w * h)) ** 0.5
130
- new_size = (max(1, int(w * scale)), max(1, int(h * scale)))
131
- return img.resize(new_size, Image.Resampling.LANCZOS)
132
-
133
-
134
  def make_ocr_message(
135
  image: Union[Image.Image, Dict[str, Any], str],
136
  task: str = "ocr",
137
- max_pixels: Optional[int] = None,
138
  ) -> List[Dict]:
139
  """
140
  Create chat message for OCR processing.
@@ -155,9 +108,6 @@ def make_ocr_message(
155
  # Convert to RGB
156
  pil_img = pil_img.convert("RGB")
157
 
158
- # Optionally cap resolution to protect the vision encoder from OOM on huge scans
159
- pil_img = downscale_to_max_pixels(pil_img, max_pixels)
160
-
161
  # Convert to base64 data URI
162
  buf = io.BytesIO()
163
  pil_img.save(buf, format="PNG")
@@ -176,75 +126,6 @@ def make_ocr_message(
176
  ]
177
 
178
 
179
- def jobs_flavor() -> str:
180
- """Return the HF Jobs hardware flavor this run is on, or "" when it cannot be told.
181
-
182
- HF Jobs sets ACCELERATOR to "cpu" or "gpu", not the flavor name, so the flavor is looked up
183
- in the public Jobs hardware list: first by GPU model and count, then by the CPU_CORES and
184
- MEMORY values that Jobs sets in the container (to tell a10g-small from a10g-large, or
185
- cpu-basic from cpu-upgrade). Any failure (no network, older huggingface_hub) returns "".
186
- """
187
- hardware = os.environ.get("ACCELERATOR") or ""
188
- if "-" in hardware or any(character.isdigit() for character in hardware):
189
- return hardware # already a flavor name
190
- try:
191
- from huggingface_hub import HfApi
192
-
193
- gpu_name, gpu_count = "", 0
194
- try:
195
- import torch
196
-
197
- if torch.cuda.is_available():
198
- gpu_name = torch.cuda.get_device_name(0)
199
- gpu_count = torch.cuda.device_count()
200
- except ImportError:
201
- # Torch-free drivers (e.g. the -server recipes): ask nvidia-smi instead.
202
- import subprocess
203
-
204
- try:
205
- listed = subprocess.run(
206
- ["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],
207
- capture_output=True, text=True, timeout=10, check=True,
208
- ).stdout
209
- names = [line.strip() for line in listed.splitlines() if line.strip()]
210
- if names:
211
- gpu_name, gpu_count = names[0], len(names)
212
- except (OSError, subprocess.SubprocessError):
213
- pass
214
- if gpu_count == 0 and hardware == "gpu":
215
- return "" # a GPU run whose GPU cannot be identified: do not guess a CPU flavor
216
-
217
- # Whole-word match, so "L4" does not match "NVIDIA L40S" ("NVIDIA A100-SXM4-80GB" -> A100).
218
- gpu_words = gpu_name.upper().replace("-", " ").split()
219
- candidates = []
220
- for flavor in HfApi(token=False).list_jobs_hardware():
221
- accelerator = flavor.accelerator
222
- if gpu_count == 0 and accelerator is None:
223
- candidates.append(flavor)
224
- elif (
225
- gpu_count > 0
226
- and accelerator is not None
227
- and accelerator.model.upper() in gpu_words
228
- and int(accelerator.quantity) == gpu_count
229
- ):
230
- candidates.append(flavor)
231
- if not candidates:
232
- return ""
233
-
234
- cores = float(os.environ.get("CPU_CORES") or 0)
235
- memory_gb = float((os.environ.get("MEMORY") or "0").upper().rstrip("GIB ") or 0)
236
-
237
- def distance(flavor) -> float:
238
- # Relative gap to the listed vCPUs and RAM; Jobs reports slightly different numbers.
239
- listed_cores = float(flavor.cpu.split()[0])
240
- listed_memory = float(flavor.ram.split()[0])
241
- return abs(listed_cores - cores) / listed_cores + abs(listed_memory - memory_gb) / listed_memory
242
-
243
- return min(candidates, key=distance).name
244
- except Exception:
245
- return ""
246
-
247
-
248
  def create_dataset_card(
249
  source_dataset: str,
250
  model: str,
@@ -268,15 +149,6 @@ def create_dataset_card(
268
  "table": "table recognition",
269
  }
270
 
271
- # Canonical provenance stamp (see AGENTS.md): Jobs claim gated on JOB_ID, set by HF Jobs in-container.
272
- on_jobs = os.environ.get("JOB_ID") is not None
273
- hw = jobs_flavor() # flavor name, e.g. "a10g-small"; "" on CPU
274
- origin = (
275
- "Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"
276
- + (f" (`{hw}`)" if hw else "")
277
- ) if on_jobs else "Generated"
278
- jobs_tag = "\n- hf-jobs" if on_jobs else ""
279
-
280
  return f"""---
281
  tags:
282
  - ocr
@@ -284,7 +156,7 @@ tags:
284
  - glm-ocr
285
  - markdown
286
  - uv-script
287
- - generated{jobs_tag}
288
  ---
289
 
290
  # Document OCR using {model_name}
@@ -330,16 +202,16 @@ The dataset contains all original columns plus:
330
 
331
  ## Reproduction
332
 
333
- {origin} with the [`glm-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py) recipe from [uv-scripts](https://huggingface.co/uv-scripts). Run it yourself:
334
-
335
  ```bash
336
- hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \\
337
  {source_dataset} \\
338
  <output-dataset> \\
339
  --image-column {image_column} \\
340
  --batch-size {batch_size} \\
341
  --task {task}
342
  ```
 
 
343
  """
344
 
345
 
@@ -349,7 +221,6 @@ def main(
349
  image_column: str = "image",
350
  batch_size: int = 16,
351
  max_model_len: int = 8192,
352
- max_pixels: Optional[int] = None,
353
  max_tokens: int = 8192,
354
  temperature: float = 0.01,
355
  top_p: float = 0.00001,
@@ -363,7 +234,6 @@ def main(
363
  shuffle: bool = False,
364
  seed: int = 42,
365
  output_column: str = "markdown",
366
- overwrite: bool = False,
367
  verbose: bool = False,
368
  config: str = None,
369
  create_pr: bool = False,
@@ -395,9 +265,6 @@ def main(
395
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
396
  )
397
 
398
- # Fail fast if the output column would collide with an existing input column
399
- dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
400
-
401
  if shuffle:
402
  logger.info(f"Shuffling dataset with seed {seed}")
403
  dataset = dataset.shuffle(seed=seed)
@@ -448,10 +315,7 @@ def main(
448
  )
449
 
450
  try:
451
- batch_messages = [
452
- make_ocr_message(img, task=task, max_pixels=max_pixels)
453
- for img in batch_images
454
- ]
455
 
456
  outputs = llm.chat(batch_messages, sampling_params)
457
 
@@ -589,20 +453,21 @@ if __name__ == "__main__":
589
  print(" table - Table extraction")
590
  print("\nExamples:")
591
  print("\n1. Basic OCR:")
592
- print(" uv run --with vllm==0.30.0 glm-ocr.py input-dataset output-dataset")
593
  print("\n2. Formula recognition:")
594
- print(" uv run --with vllm==0.30.0 glm-ocr.py docs results --task formula")
595
  print("\n3. Table extraction:")
596
- print(" uv run --with vllm==0.30.0 glm-ocr.py docs results --task table")
597
  print("\n4. Test with small sample:")
598
- print(" uv run --with vllm==0.30.0 glm-ocr.py large-dataset test --max-samples 10 --shuffle")
599
- print("\n5. Running on HF Jobs (hardware and HF_TOKEN come from the")
600
- print(" script's [tool.hf-jobs] header; --flavor/--timeout override it):")
 
601
  print(
602
- " hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \\"
603
  )
604
  print(" input-dataset output-dataset --batch-size 16")
605
- print("\nFor full help: uv run --with vllm==0.30.0 glm-ocr.py --help")
606
  sys.exit(0)
607
 
608
  parser = argparse.ArgumentParser(
@@ -615,9 +480,9 @@ Task modes:
615
  table Table extraction
616
 
617
  Examples:
618
- uv run --with vllm==0.30.0 glm-ocr.py my-docs analyzed-docs
619
- uv run --with vllm==0.30.0 glm-ocr.py docs results --task formula
620
- uv run --with vllm==0.30.0 glm-ocr.py large-dataset test --max-samples 50 --shuffle
621
  """,
622
  )
623
 
@@ -640,17 +505,6 @@ Examples:
640
  default=8192,
641
  help="Maximum model context length (default: 8192)",
642
  )
643
- parser.add_argument(
644
- "--max-pixels",
645
- type=int,
646
- default=None,
647
- help=(
648
- "Optional cap on input image pixels (width*height); larger scans are "
649
- "downscaled (aspect preserved) before OCR. GLM-OCR does no internal resizing, "
650
- "so this bounds vision-encoder memory on very large scans — set e.g. 4000000 "
651
- "if you hit a GPU OOM at high batch sizes on a big-page corpus. Default: no cap."
652
- ),
653
- )
654
  parser.add_argument(
655
  "--max-tokens",
656
  type=int,
@@ -722,12 +576,6 @@ Examples:
722
  default="markdown",
723
  help="Column name for output text (default: markdown)",
724
  )
725
- parser.add_argument(
726
- "--overwrite",
727
- action="store_true",
728
- help="Replace the output column if it already exists in the input dataset "
729
- "(default: error out to avoid clobbering an existing column).",
730
- )
731
  parser.add_argument(
732
  "--verbose",
733
  action="store_true",
@@ -742,7 +590,6 @@ Examples:
742
  image_column=args.image_column,
743
  batch_size=args.batch_size,
744
  max_model_len=args.max_model_len,
745
- max_pixels=args.max_pixels,
746
  max_tokens=args.max_tokens,
747
  temperature=args.temperature,
748
  top_p=args.top_p,
@@ -756,7 +603,6 @@ Examples:
756
  shuffle=args.shuffle,
757
  seed=args.seed,
758
  output_column=args.output_column,
759
- overwrite=args.overwrite,
760
  verbose=args.verbose,
761
  config=args.config,
762
  create_pr=args.create_pr,
 
1
  # /// script
2
  # requires-python = ">=3.11"
3
  # dependencies = [
4
+ # "datasets>=3.1.0",
5
+ # "pyarrow>=17.0.0,<18.0.0",
6
  # "huggingface-hub",
7
  # "pillow",
8
+ # "vllm",
9
  # "toolz",
10
+ # "torch",
11
  # ]
12
  #
13
+ # [[tool.uv.index]]
14
+ # url = "https://wheels.vllm.ai/nightly/cu129"
15
+ #
16
+ # [tool.uv]
17
+ # prerelease = "allow"
18
+ # override-dependencies = ["transformers>=5.1.0"]
 
 
19
  # ///
20
 
21
  """
 
25
  Uses CogViT visual encoder with GLM-0.5B language decoder and Multi-Token Prediction
26
  (MTP) loss for fast, accurate document parsing.
27
 
28
+ NOTE: Requires vLLM nightly wheels from cu129 variant (GLM-OCR added in v0.16.0,
29
+ PR #33005) and transformers>=5.1.0 (GLM-OCR support landed in stable release).
30
+ Uses https://wheels.vllm.ai/nightly/cu129 which has x86_64 wheels.
31
+ First run may take a few minutes to download and install dependencies.
32
 
33
  Features:
34
  - 0.9B parameters (ultra-compact)
 
40
  - MIT licensed
41
 
42
  Model: zai-org/GLM-OCR
43
+ vLLM: Requires vLLM nightly build + transformers>=5.1.0
44
  Performance: 94.62% on OmniDocBench V1.5
45
  """
46
 
 
53
  import sys
54
  import time
55
  from datetime import datetime
56
+ from typing import Any, Dict, List, Union
57
 
58
  import torch
59
  from datasets import load_dataset
60
  from huggingface_hub import DatasetCard, login
61
  from PIL import Image
62
  from toolz import partition_all
 
 
 
 
 
 
 
 
63
  from vllm import LLM, SamplingParams
64
 
65
  logging.basicConfig(level=logging.INFO)
 
85
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
86
 
87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  def make_ocr_message(
89
  image: Union[Image.Image, Dict[str, Any], str],
90
  task: str = "ocr",
 
91
  ) -> List[Dict]:
92
  """
93
  Create chat message for OCR processing.
 
108
  # Convert to RGB
109
  pil_img = pil_img.convert("RGB")
110
 
 
 
 
111
  # Convert to base64 data URI
112
  buf = io.BytesIO()
113
  pil_img.save(buf, format="PNG")
 
126
  ]
127
 
128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  def create_dataset_card(
130
  source_dataset: str,
131
  model: str,
 
149
  "table": "table recognition",
150
  }
151
 
 
 
 
 
 
 
 
 
 
152
  return f"""---
153
  tags:
154
  - ocr
 
156
  - glm-ocr
157
  - markdown
158
  - uv-script
159
+ - generated
160
  ---
161
 
162
  # Document OCR using {model_name}
 
202
 
203
  ## Reproduction
204
 
 
 
205
  ```bash
206
+ uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \\
207
  {source_dataset} \\
208
  <output-dataset> \\
209
  --image-column {image_column} \\
210
  --batch-size {batch_size} \\
211
  --task {task}
212
  ```
213
+
214
+ Generated with [UV Scripts](https://huggingface.co/uv-scripts)
215
  """
216
 
217
 
 
221
  image_column: str = "image",
222
  batch_size: int = 16,
223
  max_model_len: int = 8192,
 
224
  max_tokens: int = 8192,
225
  temperature: float = 0.01,
226
  top_p: float = 0.00001,
 
234
  shuffle: bool = False,
235
  seed: int = 42,
236
  output_column: str = "markdown",
 
237
  verbose: bool = False,
238
  config: str = None,
239
  create_pr: bool = False,
 
265
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
266
  )
267
 
 
 
 
268
  if shuffle:
269
  logger.info(f"Shuffling dataset with seed {seed}")
270
  dataset = dataset.shuffle(seed=seed)
 
315
  )
316
 
317
  try:
318
+ batch_messages = [make_ocr_message(img, task=task) for img in batch_images]
 
 
 
319
 
320
  outputs = llm.chat(batch_messages, sampling_params)
321
 
 
453
  print(" table - Table extraction")
454
  print("\nExamples:")
455
  print("\n1. Basic OCR:")
456
+ print(" uv run glm-ocr.py input-dataset output-dataset")
457
  print("\n2. Formula recognition:")
458
+ print(" uv run glm-ocr.py docs results --task formula")
459
  print("\n3. Table extraction:")
460
+ print(" uv run glm-ocr.py docs results --task table")
461
  print("\n4. Test with small sample:")
462
+ print(" uv run glm-ocr.py large-dataset test --max-samples 10 --shuffle")
463
+ print("\n5. Running on HF Jobs:")
464
+ print(" hf jobs uv run --flavor l4x1 \\")
465
+ print(" -s HF_TOKEN \\")
466
  print(
467
+ " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \\"
468
  )
469
  print(" input-dataset output-dataset --batch-size 16")
470
+ print("\nFor full help: uv run glm-ocr.py --help")
471
  sys.exit(0)
472
 
473
  parser = argparse.ArgumentParser(
 
480
  table Table extraction
481
 
482
  Examples:
483
+ uv run glm-ocr.py my-docs analyzed-docs
484
+ uv run glm-ocr.py docs results --task formula
485
+ uv run glm-ocr.py large-dataset test --max-samples 50 --shuffle
486
  """,
487
  )
488
 
 
505
  default=8192,
506
  help="Maximum model context length (default: 8192)",
507
  )
 
 
 
 
 
 
 
 
 
 
 
508
  parser.add_argument(
509
  "--max-tokens",
510
  type=int,
 
576
  default="markdown",
577
  help="Column name for output text (default: markdown)",
578
  )
 
 
 
 
 
 
579
  parser.add_argument(
580
  "--verbose",
581
  action="store_true",
 
590
  image_column=args.image_column,
591
  batch_size=args.batch_size,
592
  max_model_len=args.max_model_len,
 
593
  max_tokens=args.max_tokens,
594
  temperature=args.temperature,
595
  top_p=args.top_p,
 
603
  shuffle=args.shuffle,
604
  seed=args.seed,
605
  output_column=args.output_column,
 
606
  verbose=args.verbose,
607
  config=args.config,
608
  create_pr=args.create_pr,
hpd-parsing-saturate.py DELETED
@@ -1,558 +0,0 @@
1
- # /// script
2
- # requires-python = ">=3.10,<3.15"
3
- # dependencies = [
4
- # "saturate[hf]==0.3.0",
5
- # "pillow>=10",
6
- # ]
7
- #
8
- # [tool.hf-jobs]
9
- # image = "cr.hf.co/davanstrien/hpd-parsing-vllm:87496aa5-uv0.13.6"
10
- # flavor = "l4x1"
11
- # timeout = "2h"
12
- # secrets = ["HF_TOKEN"]
13
- # ///
14
- """
15
- Parse document images with HPD-Parsing via saturate.
16
-
17
- HPD-Parsing (1B, InternVL3.5-1B vision + Qwen3-0.6B) parses a page with
18
- *hierarchical parallel decoding*: a main layout branch emits `<BLOCK> <type>
19
- [bbox]` headers and forks a child branch per region (children reuse the parent's
20
- prefix KV), with a P-MTP medusa head drafting tokens inside each branch. Its
21
- output carries a type, a bbox and reading order for every block; this recipe keeps
22
- them in an `hpd_blocks` column next to the markdown.
23
-
24
- The server half is the vendor's own `vllm serve` command, started in the job. The
25
- driver half (concurrency, retries, output, resume) is the `saturate` library:
26
- adaptive concurrency, resumable parquet output and durable error rows.
27
-
28
- NEEDS PADDLE'S vLLM FORK. Forking is a scheduler feature of Paddle's vLLM fork
29
- (`0.17.1+hpdparsing`), which ships in their registry image. The [tool.hf-jobs]
30
- header above names `cr.hf.co/davanstrien/hpd-parsing-vllm`: Paddle's image
31
- (`latest-nvidia-gpu`, pinned by digest, built 2026-07-16) plus `uv`, which their
32
- image lacks. Build script and digest: images/hpd-parsing/ in the uv-scripts repo.
33
- Run on HF Jobs (`hf` CLI 1.32+ reads image, flavor, timeout and secrets from the
34
- header):
35
-
36
- hf jobs uv run --detach \\
37
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/hpd-parsing-saturate.py \\
38
- <input-dataset> <output-dataset>
39
-
40
- Smoke test first with --max-samples 5. Budget for an ~11 GB image pull on a cold
41
- node before anything runs. requires-python includes 3.10 so that uv uses the
42
- image's own Python (3.10) instead of downloading one.
43
-
44
- On Paddle's image directly (no uv in it), install uv in the job command:
45
-
46
- hf jobs run --detach --flavor l4x1 -s HF_TOKEN --timeout 2h \\
47
- ccr-2vdh3abv-pub.cnc.bj.baidubce.com/paddlepaddle/hpd-parsing-vllm@sha256:87496aa5dd702a7df6c70bb00c29d5bf8d1a0f0505d66b613fafa6f71cd72de2 \\
48
- -- bash -lc 'pip install -q uv==0.13.6 && uv run \\
49
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/hpd-parsing-saturate.py \\
50
- <input-dataset> <output-dataset>'
51
-
52
- Output: the output repo (created private if missing) holds `data/part-*.parquet`
53
- with rows `{id, markdown, hpd_blocks, raw, looped_blocks, finish_reason, model,
54
- prompt_tokens, completion_tokens, error}` keyed by the input row id
55
- (`--id-column`, or `<repo>:<config>:<split>:<000000000>` by default). Read it with
56
- `saturate.read_output`, which keeps one row per id (a success over an earlier
57
- error). `datasets.load_dataset(<output>, data_dir="data")` returns every record,
58
- so after a --retry-errors run it also holds the old error rows: drop rows with an
59
- `error` before you join back to the input on id. Re-running the same command
60
- skips finished rows; --retry-errors re-admits failed ones.
61
-
62
- - `hpd_blocks`: JSON list, one entry per region in the model's reading order:
63
- `{"type": "text|title|table|formula|figure|...", "bbox": [x1, y1, x2, y2], "text": "..."}`.
64
- BBOX SPACE: 0-1000 **normalized**, not pixels. Convert with
65
- `px = value / 1000 * width`. Container blocks (`list`, the `table` wrapper)
66
- and `chart`/`seal` regions carry a bbox with empty `text`.
67
- - `raw`: the model's untouched `<BLOCK>/<FORK>/<CHILD>` stream.
68
- - `looped_blocks`: number of blocks whose text is a repetition loop (see Limits).
69
-
70
- Model: PaddlePaddle/HPD-Parsing (Apache-2.0), paper arXiv:2607.18839
71
- - Card prompt `document parsing with fork.` (hierarchical parallel decoding);
72
- --no-fork sends the card's single-trajectory `document parsing.` for an A/B.
73
- - Image before text, greedy decoding, max_tokens 8000, context 16384: the card's
74
- values.
75
- - Block parsing and formula clean-up adapted from the model repo's Apache-2.0
76
- `eval/hpd_to_markdown.py`, via the bbox-preserving `parse_blocks` in
77
- multimodalart's demo Space (hugging-apps/hpd-parsing, `hpd_postprocess.py`).
78
-
79
- Limits seen in testing:
80
- - `max_tokens` bounds ONE decoding branch, not the page. A dense page that
81
- fragments into hundreds of blocks can loop inside many children at once: on 12
82
- Chronicling America pages (1774-1809), 3 pages looped, one emitting 544k
83
- characters against 24.9k in LoC's own OCR. Nothing errors. This recipe flags
84
- such blocks in `looped_blocks` and leaves the text as the model wrote it.
85
- Filter on `looped_blocks == 0`, or drop the looped blocks from `hpd_blocks`
86
- yourself. On those 12 pages the 3 looping pages also ended with
87
- `finish_reason` "length" and the other 9 with "stop".
88
- - Card languages are en and zh. A smoke run on degraded French scans produced
89
- stray CJK tokens.
90
-
91
- The SERVING dict below is the per-model tuning prior. Agents can `ast.literal_eval`
92
- it without running the script; the script itself consumes it.
93
- """
94
-
95
- import argparse
96
- import base64
97
- import io
98
- import json
99
- import math
100
- import os
101
- import re
102
- import shutil
103
- import subprocess
104
- import sys
105
- import zlib
106
-
107
- # Serving starting values for PaddlePaddle/HPD-Parsing. Per-value provenance:
108
- # - serve_args: the vendor image's own /home/hpd/entrypoint.sh, verbatim, except
109
- # for the speculative head path (see serve_command) and an added --revision pin.
110
- # Two flags look wrong and are not:
111
- # * --enable-prefix-caching contradicts the house OCR default (SERVING.md: OCR
112
- # never reuses images). Here the forked children share the parent branch's
113
- # prefix KV, so the cache is load-bearing (52.9% hit rate measured, 2026-07-27).
114
- # * --attention-config use_prefill_query_quantization is a fork-only flag.
115
- # - served_model_name / port 8118: the entrypoint's values; requests use the name.
116
- # - max_model_len 16384, max_tokens 8000, temperature 0.0: card values.
117
- # - max_pixels 0 (no client-side downscale): the model picks its 448 px tile grid
118
- # partly from image area (find_closest_aspect_ratio_optim), so pre-shrinking can
119
- # land a page on a smaller grid. Set --max-pixels only for huge payloads.
120
- # - image: Paddle's `latest-nvidia-gpu` tag pinned by digest on 2026-11-05
121
- # (base_image), plus uv (image; built by images/hpd-parsing/build.sh).
122
- SERVING = {
123
- "model": "PaddlePaddle/HPD-Parsing",
124
- "revision": "91de80054c23ab4238e3d7073fa2b83c2a7e301e",
125
- "served_model_name": "HPD-Parsing",
126
- "image": "cr.hf.co/davanstrien/hpd-parsing-vllm:87496aa5-uv0.13.6",
127
- "base_image": (
128
- "ccr-2vdh3abv-pub.cnc.bj.baidubce.com/paddlepaddle/hpd-parsing-vllm"
129
- "@sha256:87496aa5dd702a7df6c70bb00c29d5bf8d1a0f0505d66b613fafa6f71cd72de2"
130
- ),
131
- "port": 8118,
132
- "max_model_len": 16384,
133
- "serve_args": [
134
- "--trust-remote-code",
135
- "--host", "0.0.0.0",
136
- "--limit-mm-per-prompt", '{"image": 1}',
137
- "--gpu-memory-utilization", "0.9",
138
- "--attention-backend", "FLASHINFER",
139
- "--attention-config", '{"use_prefill_query_quantization":true}',
140
- "--enable-chunked-prefill",
141
- "--enable-prefix-caching",
142
- ],
143
- "num_speculative_tokens": 6,
144
- "max_tokens": 8000,
145
- "temperature": 0.0,
146
- "max_pixels": 0,
147
- } # fmt: skip
148
- assert SERVING["max_tokens"] < SERVING["max_model_len"], (
149
- "context math: max_tokens must leave room for the image tokens "
150
- "(input + output <= max_model_len, or every request 400s)"
151
- )
152
-
153
- # Card-verbatim prompts. Do not "improve" either.
154
- FORK_PROMPT = "document parsing with fork."
155
- PLAIN_PROMPT = "document parsing."
156
-
157
- RUN_COMMAND = (
158
- f"hf jobs uv run --detach --image {SERVING['image']} --flavor l4x1 -s HF_TOKEN \\\n"
159
- " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/hpd-parsing-saturate.py \\\n"
160
- " <input-dataset> <output-dataset>"
161
- )
162
-
163
-
164
- def to_pil(value):
165
- from PIL import Image
166
-
167
- if isinstance(value, Image.Image):
168
- return value
169
- if isinstance(value, dict) and value.get("bytes"):
170
- return Image.open(io.BytesIO(value["bytes"]))
171
- if isinstance(value, (bytes, bytearray)):
172
- return Image.open(io.BytesIO(value))
173
- raise ValueError(f"unsupported image value: {type(value)}")
174
-
175
-
176
- def encode_image(value, max_pixels: int) -> str:
177
- """RGB-convert, downscale only if max_pixels is set, return base64 JPEG q95."""
178
- from PIL import Image
179
-
180
- img = to_pil(value).convert("RGB")
181
- w, h = img.size
182
- if max_pixels and w * h > max_pixels:
183
- scale = math.sqrt(max_pixels / (w * h))
184
- img = img.resize((max(1, int(w * scale)), max(1, int(h * scale))), Image.LANCZOS)
185
- buf = io.BytesIO()
186
- img.save(buf, format="JPEG", quality=95)
187
- return base64.b64encode(buf.getvalue()).decode()
188
-
189
-
190
- # --- Formula cleaning (verbatim from the model repo's eval/hpd_to_markdown.py) ---
191
-
192
- _TALL = re.compile(
193
- r'\\d?frac|\\tfrac|\\cfrac|\\binom|\\sqrt'
194
- r'|\\sum|\\prod|\\coprod|\\int|\\iint|\\iiint|\\oint'
195
- r'|\\bigcup|\\bigcap|\\bigoplus|\\bigotimes|\\bigsqcup'
196
- r'|\\begin\{'
197
- r'|\\overbrace|\\underbrace|\\overset|\\underset|\\stackrel'
198
- r'|\\substack|\\atop|\\\\'
199
- )
200
-
201
-
202
- def _scan_delims(s):
203
- out = []
204
- for m in re.finditer(r'\\(left|right)\s*', s):
205
- dm = re.match(r'\\[a-zA-Z]+|\\.|.', s[m.end():])
206
- if not dm:
207
- continue
208
- out.append({'kind': m.group(1), 'delim': dm.group(0),
209
- 'start': m.start(), 'end': m.end() + dm.end()})
210
- return out
211
-
212
-
213
- def simplify_left_right(s: str) -> str:
214
- """Downgrade `\\left( ... \\right)` with no tall inner structure to plain `( )`."""
215
- if '\\left' not in s:
216
- return s
217
- stack, pairs = [], []
218
- for d in _scan_delims(s):
219
- if d['kind'] == 'left':
220
- stack.append(d)
221
- elif stack:
222
- pairs.append((stack.pop(), d))
223
- edits = []
224
- for L, R in pairs:
225
- if L['delim'] == '(' and R['delim'] == ')' and not _TALL.search(s[L['end']:R['start']]):
226
- edits.append((L['start'], L['end'], '('))
227
- edits.append((R['start'], R['end'], ')'))
228
- for st, en, rep in sorted(edits, key=lambda x: x[0], reverse=True):
229
- s = s[:st] + rep + s[en:]
230
- return s
231
-
232
-
233
- _ELLIPSIS = r'(?:\\dots|\\cdots|\\ldots|\\dotsb|\\dotsc)'
234
- _CLOSER = r'(?:\\right\s*[.\}\]\)]|\\end\s*\{(?:array|matrix|cases|bmatrix|pmatrix|vmatrix|smallmatrix)\})'
235
- _TAIL_WRAP = re.compile(r'^(?P<core>.*?)(?P<wrap>\s*(?:\\\]|\\\)|\$\$))?\s*$', re.DOTALL)
236
-
237
-
238
- def clean_formula_tail(s: str) -> str:
239
- """Strip degenerate formula tails (repeated/dangling ellipses, stray `\\quad`)."""
240
- if not s:
241
- return s
242
- m = _TAIL_WRAP.match(s)
243
- core, wrap = m.group('core'), m.group('wrap') or ''
244
- prev = None
245
- while prev != core:
246
- prev = core
247
- core = re.sub(r'(' + _ELLIPSIS + r')(?:\s*' + _ELLIPSIS + r')+', r'\1', core)
248
- core = re.sub(r'(?P<keep>' + _CLOSER + r')\s*(?:\\q?quad\s*)*' + _ELLIPSIS + r'\s*$',
249
- lambda mm: mm.group('keep'), core)
250
- core = re.sub(r'(?:\s*\\q?quad)+\s*' + _ELLIPSIS + r'\s*$', '', core)
251
- core = re.sub(r'(?:\s*\\q?quad)+\s*$', '', core)
252
- core = core.rstrip()
253
- return core + wrap
254
-
255
-
256
- _OP_MAP = {
257
- '≈': r'\approx', '≠': r'\neq', '≤': r'\leq', '≥': r'\geq', '×': r'\times',
258
- '÷': r'\div', '±': r'\pm', '∓': r'\mp', '·': r'\cdot', '∙': r'\cdot',
259
- '⋅': r'\cdot', '∗': '*', '−': '-', '≡': r'\equiv', '∝': r'\propto',
260
- '∞': r'\infty', '√': r'\sqrt', '→': r'\to', '≪': r'\ll', '≫': r'\gg',
261
- }
262
- _ARITH_ALLOWED = re.compile(r'^[0-9A-Za-z\s=+\-*/^_().,:;<>|%!\u4e00-\u9fff' + ''.join(_OP_MAP.keys()) + r']+$')
263
- _ARITH_HASOP = re.compile(r'[=+\-*/' + ''.join(_OP_MAP.keys()) + r']')
264
- _KNOWN_FUNCS = {'sin', 'cos', 'tan', 'cot', 'sec', 'csc', 'log', 'ln', 'exp',
265
- 'lim', 'max', 'min', 'det', 'mod', 'arcsin', 'arccos', 'arctan', 'sqrt'}
266
- _CJK_RUN = re.compile(r'[\u4e00-\u9fff]+')
267
- _MATH_SPAN = re.compile(r'(\\\[.*?\\\]|\$\$.*?\$\$|\\\(.*?\\\)|\$.*?\$)', re.DOTALL)
268
-
269
- WRAP_CJK_IN_ARITH = True
270
-
271
-
272
- def _convert_unicode_ops(s: str) -> str:
273
- for k, v in _OP_MAP.items():
274
- s = s.replace(k, (v + ' ') if v.startswith('\\') else v)
275
- if WRAP_CJK_IN_ARITH:
276
- s = _CJK_RUN.sub(lambda m: r'\text{' + m.group(0) + '}', s)
277
- return re.sub(r'[ \t]{2,}', ' ', s)
278
-
279
-
280
- def _is_pure_arith_line(line: str) -> bool:
281
- t = line.strip()
282
- if not t or '\\(' in t or '\\[' in t or '$' in t or '<' in t:
283
- return False
284
- if not WRAP_CJK_IN_ARITH and re.search(r'[\u4e00-\u9fff]', t):
285
- return False
286
- if not _ARITH_ALLOWED.match(t) or not _ARITH_HASOP.search(t):
287
- return False
288
- return all(w.lower() in _KNOWN_FUNCS for w in re.findall(r'[A-Za-z]{2,}', t))
289
-
290
-
291
- def normalize_arith(text: str) -> str:
292
- """Normalize Unicode operators to LaTeX and wrap pure-arithmetic lines as `\\( .. \\)`."""
293
- if not text:
294
- return text
295
- text = _MATH_SPAN.sub(lambda m: _convert_unicode_ops(m.group(0)), text)
296
- out = []
297
- for line in text.split('\n'):
298
- if _is_pure_arith_line(line):
299
- out.append('\\( ' + _convert_unicode_ops(line.strip()) + ' \\)')
300
- else:
301
- out.append(line)
302
- return '\n'.join(out)
303
-
304
-
305
- def clean_text(text: str) -> str:
306
- """Per-block cleaning, matching the official hpd_to_markdown.py steps."""
307
- text = text.strip()
308
- text = text.replace('The image is too blurry to recognize any text content.', '').strip()
309
- text = text.replace(
310
- "The image contains no text or characters. It is a graphical element (a horizontal "
311
- "line with a vertical line) and does not contain any chart, graph, or data points "
312
- "that can be extracted. Therefore, the correct OCR output is an empty string.", ""
313
- ).strip()
314
- if not text or text == '[Non-Text]':
315
- return ''
316
- if text.startswith('\\[') and not text.endswith('\n\\]'):
317
- text += '\n\\]'
318
- if text.startswith('<table>') and not text.endswith('</table>'):
319
- text += '</table>'
320
- if '\\[\n' in text and '\\\\' not in text:
321
- text = text.replace('\\[\n', '\\(').replace('\n\\]', '\\)')
322
- text = text.replace('\\) \\(', '\\)\n\n\\(')
323
- if '÷' in text and '\\(' not in text:
324
- text = '\\( ' + text + ' \\)'
325
- text = re.sub(r'\\tag\s*\{[^{}]*\}', '', text)
326
- text = text.replace('\\supset', '\\sqsupset')
327
- text = simplify_left_right(text)
328
- text = clean_formula_tail(text)
329
- return normalize_arith(text)
330
-
331
-
332
- # --- Block parsing (bbox-preserving; the official script discards bboxes) ---
333
-
334
- # type + [bbox], usually followed by <FORK|CHILD|BLOCK>. Container blocks such as
335
- # `list [x1,y1,x2,y2]` may have no trailing tag at all, so the tag is optional.
336
- _BLOCK_HEADER = re.compile(r'([a-zA-Z_]+)\s*\[\s*([-\d.,\s]+)\]\s*(?:<(?:FORK|CHILD|BLOCK)>)?')
337
- _NO_CONTENT_TYPES = {'chart', 'seal'}
338
-
339
-
340
- def parse_blocks(raw_text: str) -> list[dict]:
341
- """Parse the `<BLOCK> <type> [bbox] <CHILD> <content>` stream.
342
-
343
- Returns `[{"type": str, "bbox": [x1,y1,x2,y2] | None, "text": str}, ...]` in the
344
- model's own reading order. `bbox` is in the model's native 0-1000 NORMALIZED
345
- coordinate space, not pixels. `text` is empty for container blocks (e.g. `list`,
346
- the `table` wrapper) and for `chart`/`seal`, matching the official export.
347
- """
348
- blocks = []
349
- for seg in raw_text.split('<BLOCK>')[1:]:
350
- header_m = _BLOCK_HEADER.match(seg.strip())
351
- type_m = re.match(r'\s*([a-zA-Z_]+)', seg)
352
- block_type = type_m.group(1) if type_m else 'unknown'
353
-
354
- bbox = None
355
- if header_m:
356
- block_type = header_m.group(1)
357
- nums = [float(x) for x in re.split(r'[,\s]+', header_m.group(2).strip()) if x]
358
- if len(nums) == 4:
359
- bbox = nums
360
-
361
- text = ''
362
- if block_type.lower() not in _NO_CONTENT_TYPES:
363
- content_m = re.search(r'<CHILD>(.*)', seg, re.DOTALL)
364
- if content_m:
365
- # stop at the next control tag if any leaked through
366
- raw_content = re.split(r'<(?:FORK|CHILD|BLOCK)>', content_m.group(1))[0]
367
- text = clean_text(raw_content)
368
-
369
- blocks.append({'type': block_type, 'bbox': bbox, 'text': text})
370
- return blocks
371
-
372
-
373
- def blocks_to_markdown(blocks: list[dict]) -> str:
374
- """Join the non-empty block texts in reading order into one markdown string."""
375
- return '\n\n'.join(b['text'] for b in blocks if b['text']).strip()
376
-
377
-
378
- # --- Loop flag ---
379
-
380
- # Calibrated on the 2026-07-27 test outputs (ChronAm, OmniDocBench, UFO; 345 blocks of
381
- # 200+ bytes). Ordinary text blocks of 2000+ bytes compress about 2x with zlib; looping
382
- # blocks compressed 6x (a counting loop: "of the 860th of the 861th ...") to 330x. The
383
- # most compressible real block was a 1.5 KB table at 5.3x, so tables get a higher bar.
384
- LOOP_MIN_BYTES = 2000
385
- LOOP_MIN_RATIO = 4.0
386
- LOOP_MIN_RATIO_TABLE = 10.0
387
-
388
-
389
- def is_looped(block: dict) -> bool:
390
- """True when a block's text is long and highly repetitive (a decoding loop)."""
391
- data = block["text"].encode()
392
- if len(data) < LOOP_MIN_BYTES:
393
- return False
394
- ratio = len(data) / len(zlib.compress(data))
395
- threshold = LOOP_MIN_RATIO_TABLE if block["type"] == "table" else LOOP_MIN_RATIO
396
- return ratio >= threshold
397
-
398
-
399
- # --- Server ---
400
-
401
-
402
- def vendor_vllm() -> str:
403
- """Return the vendor fork's `vllm` binary, or exit with the command that provides it."""
404
- vllm = shutil.which("vllm")
405
- version = ""
406
- if vllm:
407
- out = subprocess.run([vllm, "--version"], capture_output=True, text=True, check=False)
408
- lines = out.stdout.strip().splitlines()
409
- version = lines[-1] if lines else ""
410
- if "hpdparsing" not in version:
411
- found = f"found vllm {version!r} at {vllm}" if vllm else "no `vllm` on PATH"
412
- sys.exit(
413
- f"HPD-Parsing needs Paddle's vLLM fork (0.17.1+hpdparsing); {found}. "
414
- f"Run the job on an image that has it:\n\n{RUN_COMMAND}"
415
- )
416
- print(f"vendor vllm {version} at {vllm}", file=sys.stderr)
417
- return vllm
418
-
419
-
420
- def resolve_spec_model() -> str:
421
- """Download the P-MTP speculative head and return its local directory.
422
-
423
- The vendor entrypoint passes `PaddlePaddle/HPD-Parsing/P-MTP`, a local directory in
424
- the image's offline variant (weights baked in). This image has no weights, so pull
425
- that subfolder (~644 MB) into the normal HF cache and pass its path.
426
- """
427
- from huggingface_hub import snapshot_download
428
-
429
- snapshot = snapshot_download(
430
- SERVING["model"], revision=SERVING["revision"], allow_patterns=["P-MTP/*"]
431
- )
432
- spec_dir = os.path.join(snapshot, "P-MTP")
433
- if not os.path.isfile(os.path.join(spec_dir, "config.json")):
434
- sys.exit(f"P-MTP head has no config.json under {spec_dir}")
435
- return spec_dir
436
-
437
-
438
- def serve_command(vllm: str, max_model_len: int) -> list[str]:
439
- """The vendor entrypoint's `vllm serve` command, with a local speculative head."""
440
- speculative = {
441
- "method": "medusa",
442
- "model": resolve_spec_model(),
443
- "num_speculative_tokens": SERVING["num_speculative_tokens"],
444
- }
445
- return [
446
- vllm, "serve", SERVING["model"],
447
- "--revision", SERVING["revision"],
448
- "--served-model-name", SERVING["served_model_name"],
449
- "--port", str(SERVING["port"]),
450
- "--max-model-len", str(max_model_len),
451
- *SERVING["serve_args"],
452
- "--speculative-config", json.dumps(speculative),
453
- ] # fmt: skip
454
-
455
-
456
- def main():
457
- ap = argparse.ArgumentParser(
458
- description="HPD-Parsing document parsing via saturate (vendor vLLM fork image only)"
459
- )
460
- ap.add_argument("input_dataset", help="Input dataset repo id (rows with an image column)")
461
- ap.add_argument("output_dataset", help="Output dataset repo id (created private if missing)")
462
- ap.add_argument("--image-column", default="image")
463
- ap.add_argument("--config", default=None, help="Dataset config name")
464
- ap.add_argument("--split", default="train")
465
- ap.add_argument("--id-column", default=None,
466
- help="Column to use as row id (default: split-index ids)")
467
- ap.add_argument("--max-samples", "--limit", dest="limit", type=int, default=None,
468
- help="Process only the first N rows (smoke test)")
469
- ap.add_argument("--max-tokens", type=int, default=SERVING["max_tokens"],
470
- help="Output cap PER DECODING BRANCH, not per page (card: 8000)")
471
- ap.add_argument("--max-pixels", type=int, default=SERVING["max_pixels"],
472
- help="Downscale images above this pixel count before upload (default 0 = off)")
473
- ap.add_argument("--no-fork", action="store_true",
474
- help="Send the single-trajectory prompt ('document parsing.') instead of "
475
- "hierarchical parallel decoding; for an A/B only")
476
- ap.add_argument("--retry-errors", action="store_true",
477
- help="Re-admit rows whose only record is an error row")
478
- args = ap.parse_args()
479
-
480
- if not 1 <= args.max_tokens < SERVING["max_model_len"]:
481
- ap.error(f"--max-tokens must be between 1 and {SERVING['max_model_len'] - 1}")
482
-
483
- vllm = vendor_vllm() # fail before the dataset is touched if this is the wrong image
484
-
485
- import pyarrow as pa
486
- from saturate import Engine, dataset_rows, pump
487
-
488
- if args.id_column is None:
489
- ids = "index"
490
- elif args.id_column in ("index", "content"):
491
- # saturate reads these two names as id strategies, so a column with one of them
492
- # needs a callable. It returns the raw value, so saturate still refuses a null id.
493
- ids = lambda example: example[args.id_column]
494
- else:
495
- ids = args.id_column
496
-
497
- rows = dataset_rows(
498
- args.input_dataset, config=args.config, split=args.split,
499
- columns=[args.image_column], ids=ids, limit=args.limit,
500
- )
501
- prompt = PLAIN_PROMPT if args.no_fork else FORK_PROMPT
502
-
503
- def to_request(row):
504
- b64 = encode_image(row[args.image_column], args.max_pixels)
505
- return {
506
- "model": SERVING["served_model_name"],
507
- "messages": [{"role": "user", "content": [
508
- # Image first, then text: the order of the card's example.
509
- {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64}"}},
510
- {"type": "text", "text": prompt},
511
- ]}],
512
- "temperature": SERVING["temperature"],
513
- "max_tokens": args.max_tokens,
514
- }
515
-
516
- # Declared, so a part holding only error rows has the same columns as the rest
517
- # (datasets.load_dataset reads every part with one schema).
518
- schema = pa.schema([
519
- ("id", pa.string()), ("error", pa.string()), ("markdown", pa.string()),
520
- ("hpd_blocks", pa.string()), ("raw", pa.string()), ("looped_blocks", pa.int64()),
521
- ("finish_reason", pa.string()), ("model", pa.string()),
522
- ("prompt_tokens", pa.int64()), ("completion_tokens", pa.int64()),
523
- ]) # fmt: skip
524
-
525
- def parse(row, body):
526
- choice = body["choices"][0]
527
- raw = choice["message"]["content"] or ""
528
- blocks = parse_blocks(raw)
529
- usage = body.get("usage") or {}
530
- return {
531
- "markdown": blocks_to_markdown(blocks),
532
- "hpd_blocks": json.dumps(blocks, ensure_ascii=False),
533
- "raw": raw,
534
- "looped_blocks": sum(is_looped(b) for b in blocks),
535
- "finish_reason": choice.get("finish_reason"),
536
- "model": SERVING["model"],
537
- "prompt_tokens": usage.get("prompt_tokens"),
538
- "completion_tokens": usage.get("completion_tokens"),
539
- }
540
-
541
- engine = Engine(
542
- SERVING["model"],
543
- port=SERVING["port"],
544
- cmd=serve_command(vllm, SERVING["max_model_len"]),
545
- )
546
- output = f"hf://datasets/{args.output_dataset}/data"
547
- with engine as endpoint:
548
- stats = pump(rows, to_request, parse, endpoint, output,
549
- prepare_workers=int(float(os.environ.get("CPU_CORES") or "4")),
550
- retry_errors=args.retry_errors, schema=schema)
551
-
552
- print(f"https://huggingface.co/datasets/{args.output_dataset} "
553
- f"({stats.rows_processed} ok, {stats.rows_failed} error rows)", file=sys.stderr)
554
- print("HPD_PARSING_SATURATE " + stats.to_json(), flush=True)
555
-
556
-
557
- if __name__ == "__main__":
558
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
hunyuan-ocr-1.5.py DELETED
@@ -1,890 +0,0 @@
1
- # /// script
2
- # requires-python = ">=3.11"
3
- # dependencies = [
4
- # "datasets>=4.0.0,<5.1", # 5.1 needs huggingface_hub>=1.31; the image ships an older 1.x on PYTHONPATH, which wins
5
- # "huggingface-hub",
6
- # "pillow",
7
- # "tqdm",
8
- # "toolz",
9
- # ]
10
- #
11
- # [tool.hf-jobs]
12
- # image = "vllm/vllm-openai:v0.24.0"
13
- # python = "/usr/bin/python3"
14
- # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
15
- # flavor = "a10g-small"
16
- # secrets = ["HF_TOKEN"]
17
- # ///
18
-
19
- """
20
- Convert document images to markdown using HunyuanOCR-1.5 with vLLM.
21
-
22
- HunyuanOCR-1.5 is a lightweight ~1B-parameter, end-to-end OCR-specialized VLM
23
- from Tencent. It keeps the validated 1.0 backbone but extends the max image
24
- resolution to 4K and the context window to 128K, and adds targeted long-tail
25
- capabilities (low-resource / ancient-script OCR, multi-image text QA). Per the
26
- technical report (arXiv:2607.04884) it is faster than dots.ocr / DeepSeek-OCR-2
27
- and top-tier on OmniDocBench v1.6. This script runs it offline via vLLM.
28
-
29
- Features:
30
- - 📝 End-to-end document parsing to markdown (tables → HTML, formulas → LaTeX)
31
- - 🧩 Structured / layout-aware parsing
32
- - 📍 Text spotting with coordinates (JSON or Hunyuan format)
33
- - 📐 Formula (LaTeX) and 📊 table (HTML) recognition
34
- - 📈 Chart parsing (Mermaid / Markdown)
35
- - 🌐 Document + general-scene translation (→ zh / → en)
36
- - 🎯 Compact model (~1B parameters)
37
-
38
- Model: tencent/HunyuanOCR
39
- On 2026-07-06 Tencent replaced the repo root in-place with HunyuanOCR-1.5
40
- (1.0 archived under `v1.0/`, no git tag). So the repo *root* — the default
41
- here — is now 1.5. The sibling recipe `hunyuan-ocr.py` pins the last 1.0
42
- commit by revision to keep the 1.0 behavior; this script deliberately tracks
43
- root (1.5).
44
-
45
- vLLM: 0.18.1 (release) is the first stable wheel with native
46
- `HunYuanVLForConditionalGeneration` support for autoregressive decoding — no
47
- nightly or patch needed for batch OCR. The [tool.hf-jobs] header pins the
48
- vllm/vllm-openai:v0.24.0 image (`hf` CLI 1.32+), which also sets the hardware
49
- and the HF_TOKEN secret. Newer stacks fail: unpinned vLLM with transformers
50
- >=5.13 does not recognise `hunyuan_vl`, and the v0.29.0 image fails at engine
51
- start ("Expected 4 multimodal RoPE channels"). To run on your own GPU:
52
- `uv run --with vllm==0.24.0 --with "transformers<5.13" ...`. The DFlash
53
- speculative-decoding draft (a per-request *latency* win that needs a vLLM
54
- nightly) is intentionally NOT implemented: it does not change offline batch
55
- throughput or output distribution.
56
-
57
- trust_remote_code=True per the model card (the processor ships custom code).
58
-
59
- License: Tencent Hunyuan Community License (territory excludes EU/UK/South Korea)
60
- https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE
61
-
62
- Note: batch_size defaults to 16 (untested on this arch as of writing — 1.5 on
63
- vLLM ≥0.18.1 should batch fine, unlike the 1.0 V1 batching issue; will be
64
- smoke-tested). Lower it if you hit engine errors.
65
-
66
- Post-processing note: only the shared tail-repetition cleanup
67
- (`clean_repeated_substrings`, byte-for-byte from the official toolkit) is
68
- ported. The upstream doc_parse-only markdown normalization (10 OmniDocBench
69
- GT-alignment regex passes in `hunyuan_utils.process_one`) is intentionally NOT
70
- ported — it is benchmark-GT alignment, not general OCR, and would bloat this
71
- self-contained recipe. For bench-exact output, use Tencent's toolkit directly.
72
- """
73
-
74
- import argparse
75
- import base64
76
- import io
77
- import json
78
- import logging
79
- import os
80
- import sys
81
- import time
82
- from datetime import datetime
83
- from typing import Any, Dict, List, Union
84
-
85
- import torch
86
- from datasets import load_dataset
87
- from huggingface_hub import DatasetCard, login
88
- from PIL import Image
89
- from toolz import partition_all
90
- from tqdm.auto import tqdm
91
-
92
- # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
93
- # default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
94
- # lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
95
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
96
- from vllm import LLM, SamplingParams
97
-
98
- logging.basicConfig(level=logging.INFO)
99
- logger = logging.getLogger(__name__)
100
-
101
-
102
- # ────────────────────────────────────────────────────────────────
103
- # HunyuanOCR-1.5 official task prompts.
104
- # Reproduced VERBATIM from the shipped client's `hunyuan_tasks.py`:
105
- # https://github.com/Tencent-Hunyuan/HunyuanOCR (inference/*/hunyuan_tasks.py)
106
- # The model card only prints the `doc_parse` prompt; the other 11 live only in
107
- # the client. Prompts are FIXED per task type — upstream deliberately does NOT
108
- # expose free-form prompt editing because hand-tweaked instructions were
109
- # observed to silently degrade quality (users pick a *task*, not a prompt).
110
- # All prompts are Chinese-language, including for English documents — this is
111
- # the officially recommended wording; the card provides no English variants.
112
- # ────────────────────────────────────────────────────────────────
113
-
114
- TASK_PROMPTS = {
115
- # 端到端文档解析
116
- "doc_parse": "提取文档图片中正文的所有信息用markdown格式表示,其中页眉、页脚部分忽略,"
117
- "表格用html格式表达,文档中公式用latex格式表示,按照阅读顺序组织进行解析。",
118
- # 结构化解析(古文、街景等非文档结构化场景)
119
- "structured_parse": "提取图中的文字。",
120
- # Spotting — JSON 格式
121
- "spotting_json": "检测并识别图中所有的文字行,请按从上到下、从左到右的阅读顺序进行识别。 "
122
- "输出格式为 JSON 数组,每个元素必须包含:"
123
- '"box": [xmin, ymin, xmax, ymax](坐标需归一化到 [0, 1000] 范围内);'
124
- '"text": "识别出的文字内容"。 '
125
- "注意:请直接输出 JSON 数组,不要包含任何多余的描述性文字。",
126
- # Spotting — Hunyuan 模式
127
- "spotting_hunyuan": "检测并识别图片中的文字,将文本坐标格式化输出。",
128
- # 版式分析
129
- "layout": "按照阅读顺序解析图中的版式信息。",
130
- # 版式分析 + 解析
131
- "layout_parse": "提取文档图片中所有内容用markdown格式表示,表格用html格式表达,"
132
- "文档中公式用latex格式表示,请按照阅读顺序组织进行全文解析,并输出版式分析信息。",
133
- # 图表解析
134
- "chart_parse": "解析图中的图表,对于流程图使用Mermaid格式表示,其他图表使用Markdown格式表示。",
135
- # 公式解析
136
- "formula": "识别图片中的公式,用LaTeX格式表示。",
137
- # 表格解析
138
- "table": "把图中的表格解析为HTML。",
139
- # 文档英译中
140
- "doc_trans_en2zh": "先解析文档,再将文档内容翻译为中文,其中页眉、页脚忽略,"
141
- "公式用latex格式表示,表格用html格式表示。",
142
- # 通用场景翻译 other2en
143
- "trans_other2en": "按照阅读顺序,提取图中文字,公式用latex格式表示,表格用markdown格式表示,"
144
- "再将文字内容翻译为英文。",
145
- # 通用场景翻译 other2zh
146
- "trans_other2zh": "按照阅读顺序,提取图中文字,公式用latex格式表示,表格用markdown格式表示,"
147
- "再将文字内容翻译为中文。",
148
- }
149
-
150
- # English glosses for --help / the no-args banner (upstream ships Chinese ones).
151
- TASK_DESCRIPTIONS = {
152
- "doc_parse": "End-to-end doc parse (body→markdown, tables→HTML, formulas→LaTeX, headers/footers ignored). Default.",
153
- "structured_parse": "Structured parse for non-document scenes (ancient scripts, street signs) — extract all text.",
154
- "spotting_json": "Text detect+recognize as a JSON array (box normalized to 0-1000 + text).",
155
- "spotting_hunyuan": "Text detect+recognize in Hunyuan coordinate format.",
156
- "layout": "Layout analysis in reading order.",
157
- "layout_parse": "Layout analysis + full-document parse (markdown/HTML/LaTeX).",
158
- "chart_parse": "Chart parsing (flowcharts→Mermaid, other charts→Markdown).",
159
- "formula": "Formula recognition → LaTeX.",
160
- "table": "Table parsing → HTML.",
161
- "doc_trans_en2zh": "Document translation to Chinese (parse then translate; formulas LaTeX, tables HTML).",
162
- "trans_other2en": "General-scene extraction + translation to English.",
163
- "trans_other2zh": "General-scene extraction + translation to Chinese.",
164
- }
165
-
166
- DEFAULT_TASK = "doc_parse"
167
-
168
- # Sampling params LOCKED by the model card across all official setups so outputs
169
- # are comparable: temperature=0.0, top_p=1.0, top_k=-1, repetition_penalty=1.08.
170
- # Only repetition_penalty is exposed as a flag (the others are fixed for
171
- # deterministic OCR); repetition_penalty is the model's built-in anti-repeat.
172
- DEFAULT_REPETITION_PENALTY = 1.08
173
-
174
-
175
- def clean_repeated_substrings(text: str, min_repeats: int = 10) -> str:
176
- """Trim a long repeated suffix as a final safety net against greedy-decoding
177
- degeneration. Byte-for-byte from the official `hunyuan_utils.py`.
178
- """
179
- n = len(text)
180
- if n < 2000:
181
- return text
182
- for length in range(2, n // min_repeats + 1):
183
- candidate = text[-length:]
184
- count = 0
185
- i = n - length
186
- while i >= 0 and text[i : i + length] == candidate:
187
- count += 1
188
- i -= length
189
- if count >= min_repeats:
190
- return text[: n - length * (count - 1)]
191
- return text
192
-
193
-
194
- def check_cuda_availability():
195
- """Check if CUDA is available and exit if not."""
196
- if not torch.cuda.is_available():
197
- logger.error("CUDA is not available. This script requires a GPU.")
198
- logger.error("Please run on a machine with a CUDA-capable GPU.")
199
- sys.exit(1)
200
- else:
201
- logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
202
-
203
-
204
- def ensure_output_columns_free(dataset, columns, overwrite=False):
205
- """Fail fast if an output column would collide with an existing input column.
206
-
207
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
208
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
209
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
210
- column(s) here instead (logged) so the later add_column is clean.
211
- """
212
- clash = [c for c in columns if c in dataset.column_names]
213
- if not clash:
214
- return dataset
215
- if overwrite:
216
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
217
- return dataset.remove_columns(clash)
218
- logger.error(
219
- f"Output column(s) {clash} already exist in the input dataset "
220
- f"(columns: {dataset.column_names})."
221
- )
222
- logger.error(
223
- "Choose a different --output-column, or pass --overwrite to replace them."
224
- )
225
- sys.exit(1)
226
-
227
-
228
- def get_prompt(task_type: str) -> str:
229
- """Return the official prompt for a task type."""
230
- if task_type not in TASK_PROMPTS:
231
- raise ValueError(
232
- f"Unknown task type: {task_type}. Available: {list(TASK_PROMPTS.keys())}"
233
- )
234
- return TASK_PROMPTS[task_type]
235
-
236
-
237
- def make_ocr_message(
238
- image: Union[Image.Image, Dict[str, Any], str],
239
- prompt: str,
240
- ) -> List[Dict]:
241
- """Create the chat messages for one image + prompt.
242
-
243
- Mirrors the official client: an empty system message followed by a user turn
244
- with the image *before* the text. The empty system content pins "no system
245
- prompt" (matching how the model is served) rather than letting the chat
246
- template inject a default.
247
- """
248
- # Convert to PIL Image if needed
249
- if isinstance(image, Image.Image):
250
- pil_img = image
251
- elif isinstance(image, dict) and "bytes" in image:
252
- pil_img = Image.open(io.BytesIO(image["bytes"]))
253
- elif isinstance(image, str):
254
- pil_img = Image.open(image)
255
- else:
256
- raise ValueError(f"Unsupported image type: {type(image)}")
257
-
258
- # Convert to RGB
259
- pil_img = pil_img.convert("RGB")
260
-
261
- # Convert to base64 data URI
262
- buf = io.BytesIO()
263
- pil_img.save(buf, format="PNG")
264
- data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
265
-
266
- return [
267
- {"role": "system", "content": ""},
268
- {
269
- "role": "user",
270
- "content": [
271
- {"type": "image_url", "image_url": {"url": data_uri}},
272
- {"type": "text", "text": prompt},
273
- ],
274
- },
275
- ]
276
-
277
-
278
- def create_dataset_card(
279
- source_dataset: str,
280
- model: str,
281
- num_samples: int,
282
- processing_time: str,
283
- batch_size: int,
284
- max_model_len: int,
285
- max_tokens: int,
286
- repetition_penalty: float,
287
- gpu_memory_utilization: float,
288
- image_column: str = "image",
289
- output_column: str = "markdown",
290
- split: str = "train",
291
- task_type: str = "doc_parse",
292
- ) -> str:
293
- """Create a dataset card documenting the OCR process."""
294
- model_name = model.split("/")[-1]
295
-
296
- return f"""---
297
- tags:
298
- - ocr
299
- - document-processing
300
- - hunyuan-ocr-1.5
301
- - multilingual
302
- - markdown
303
- - uv-script
304
- - generated
305
- ---
306
-
307
- # Document OCR using {model_name} (HunyuanOCR-1.5)
308
-
309
- This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using HunyuanOCR-1.5, a lightweight ~1B end-to-end OCR VLM from Tencent (128K context, 4K max image resolution).
310
-
311
- Model license: [Tencent Hunyuan Community License](https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE) (territory excludes EU/UK/South Korea).
312
-
313
- ## Processing Details
314
-
315
- - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
316
- - **Model**: [{model}](https://huggingface.co/{model})
317
- - **Number of Samples**: {num_samples:,}
318
- - **Processing Time**: {processing_time}
319
- - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
320
-
321
- ### Configuration
322
-
323
- - **Image Column**: `{image_column}`
324
- - **Output Column**: `{output_column}`
325
- - **Dataset Split**: `{split}`
326
- - **Task Type**: `{task_type}`
327
- - **Batch Size**: {batch_size}
328
- - **Max Model Length**: {max_model_len:,} tokens
329
- - **Max Output Tokens**: {max_tokens:,}
330
- - **Repetition Penalty**: {repetition_penalty}
331
- - **GPU Memory Utilization**: {gpu_memory_utilization:.1%}
332
-
333
- ## Model Information
334
-
335
- HunyuanOCR-1.5 is a lightweight end-to-end OCR VLM that excels at:
336
- - 📝 **Document Parsing** - Full markdown extraction in reading order
337
- - 🧩 **Structured / Layout Parsing** - Layout-aware full-document parse
338
- - 📊 **Table Extraction** - HTML format tables
339
- - 📐 **Formula Recognition** - LaTeX format formulas
340
- - 📈 **Chart Parsing** - Mermaid / Markdown format
341
- - 📍 **Text Spotting** - Detection with coordinates (JSON / Hunyuan)
342
- - 🌐 **Translation** - Document and general-scene translation (→ zh / → en)
343
-
344
- Per the technical report ([arXiv:2607.04884](https://arxiv.org/pdf/2607.04884)),
345
- 1.5 is faster than dots.ocr / DeepSeek-OCR-2 and top-tier on OmniDocBench v1.6.
346
-
347
- ## Task Types Available
348
-
349
- - `doc_parse` - End-to-end document parsing (default)
350
- - `structured_parse` - Non-document structured scenes (ancient scripts, street signs)
351
- - `spotting_json` - Text detection + recognition as JSON array (box 0-1000 + text)
352
- - `spotting_hunyuan` - Text detection + recognition, Hunyuan coordinate format
353
- - `layout` - Layout analysis in reading order
354
- - `layout_parse` - Layout analysis + full-document parse
355
- - `chart_parse` - Chart parsing (flowcharts → Mermaid, others → Markdown)
356
- - `formula` - Formula recognition → LaTeX
357
- - `table` - Table parsing → HTML
358
- - `doc_trans_en2zh` - Document translation to Chinese
359
- - `trans_other2en` - General-scene extraction + translation to English
360
- - `trans_other2zh` - General-scene extraction + translation to Chinese
361
-
362
- ## Dataset Structure
363
-
364
- The dataset contains all original columns plus:
365
- - `{output_column}`: The extracted text (markdown for `doc_parse`, else the task's format)
366
- - `inference_info`: JSON list tracking all OCR models applied to this dataset
367
-
368
- ## Usage
369
-
370
- ```python
371
- from datasets import load_dataset
372
- import json
373
-
374
- # Load the dataset
375
- dataset = load_dataset("{{output_dataset_id}}", split="{split}")
376
-
377
- # Access the extracted text
378
- for example in dataset:
379
- print(example["{output_column}"])
380
- break
381
-
382
- # View all OCR models applied to this dataset
383
- inference_info = json.loads(dataset[0]["inference_info"])
384
- for info in inference_info:
385
- print(f"Column: {{info['column_name']}} - Model: {{info['model_id']}}")
386
- ```
387
-
388
- ## Reproduction
389
-
390
- This dataset was generated using the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) HunyuanOCR-1.5 script:
391
-
392
- ```bash
393
- uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/hunyuan-ocr-1.5.py \\
394
- {source_dataset} \\
395
- <output-dataset> \\
396
- --image-column {image_column} \\
397
- --batch-size {batch_size} \\
398
- --task-type {task_type} \\
399
- --max-model-len {max_model_len} \\
400
- --max-tokens {max_tokens} \\
401
- --gpu-memory-utilization {gpu_memory_utilization}
402
- ```
403
-
404
- Generated with [UV Scripts](https://huggingface.co/uv-scripts)
405
- """
406
-
407
-
408
- def main(
409
- input_dataset: str,
410
- output_dataset: str,
411
- image_column: str = "image",
412
- batch_size: int = 16,
413
- model: str = "tencent/HunyuanOCR",
414
- revision: str = None,
415
- max_model_len: int = 32768,
416
- max_tokens: int = 8192,
417
- repetition_penalty: float = DEFAULT_REPETITION_PENALTY,
418
- gpu_memory_utilization: float = 0.8,
419
- hf_token: str = None,
420
- split: str = "train",
421
- max_samples: int = None,
422
- private: bool = False,
423
- shuffle: bool = False,
424
- seed: int = 42,
425
- task_type: str = DEFAULT_TASK,
426
- custom_prompt: str = None,
427
- output_column: str = "markdown",
428
- overwrite: bool = False,
429
- clean_output: bool = True,
430
- config: str = None,
431
- create_pr: bool = False,
432
- verbose: bool = False,
433
- ):
434
- """Process images from an HF dataset through HunyuanOCR-1.5."""
435
-
436
- # Check CUDA availability first
437
- check_cuda_availability()
438
-
439
- # Context-length invariant (config.json): text max_position_embeddings=131072;
440
- # the vision processor caps a single image at img_max_token_num=16384. So the
441
- # default budget holds without resizing: 16384 (image) + prompt + 8192 (output)
442
- # ≈ 25k ≤ 32768 (default max_model_len). Enforce max_tokens ≤ max_model_len ≤ 131072.
443
- if max_model_len > 131072:
444
- logger.error(
445
- f"--max-model-len {max_model_len} exceeds the model's max context (131072)."
446
- )
447
- sys.exit(1)
448
- if max_tokens > max_model_len:
449
- logger.error(
450
- f"--max-tokens ({max_tokens}) cannot exceed --max-model-len ({max_model_len})."
451
- )
452
- sys.exit(1)
453
-
454
- # Track processing start time
455
- start_time = datetime.now()
456
-
457
- # Login to HF if token provided
458
- HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
459
- if HF_TOKEN:
460
- login(token=HF_TOKEN)
461
-
462
- # Determine prompt to use
463
- if custom_prompt:
464
- prompt = custom_prompt
465
- logger.warning(
466
- "Using --custom-prompt. Note: upstream deliberately locks prompts per "
467
- "task type — hand-tweaked instructions can silently degrade quality."
468
- )
469
- logger.info(f"Custom prompt: {prompt[:60]}...")
470
- else:
471
- prompt = get_prompt(task_type)
472
- logger.info(f"Using task type: {task_type}")
473
-
474
- # Load dataset
475
- logger.info(f"Loading dataset: {input_dataset}")
476
- dataset = load_dataset(input_dataset, split=split)
477
-
478
- # Validate image column
479
- if image_column not in dataset.column_names:
480
- raise ValueError(
481
- f"Column '{image_column}' not found. Available: {dataset.column_names}"
482
- )
483
-
484
- # Fail fast if the output column would collide with an existing input column
485
- dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
486
-
487
- # Shuffle if requested
488
- if shuffle:
489
- logger.info(f"Shuffling dataset with seed {seed}")
490
- dataset = dataset.shuffle(seed=seed)
491
-
492
- # Limit samples if requested
493
- if max_samples:
494
- dataset = dataset.select(range(min(max_samples, len(dataset))))
495
- logger.info(f"Limited to {len(dataset)} samples")
496
-
497
- # Initialize vLLM model
498
- logger.info(f"Initializing vLLM with model: {model}")
499
- logger.info("This may take a few minutes on first run...")
500
-
501
- llm = LLM(
502
- model=model,
503
- revision=revision,
504
- trust_remote_code=True,
505
- max_model_len=max_model_len,
506
- gpu_memory_utilization=gpu_memory_utilization,
507
- limit_mm_per_prompt={"image": 1},
508
- # The encoder cache is sized from max_num_batched_tokens (8192 by default), but one
509
- # image can reach img_max_token_num=16384 tokens; a 2000 px scan already needs ~8.6k.
510
- max_num_batched_tokens=16384,
511
- )
512
-
513
- # Locked sampling per the model card (deterministic OCR); only repetition_penalty
514
- # is user-tunable.
515
- sampling_params = SamplingParams(
516
- temperature=0.0,
517
- top_p=1.0,
518
- top_k=-1,
519
- repetition_penalty=repetition_penalty,
520
- max_tokens=max_tokens,
521
- skip_special_tokens=True,
522
- )
523
-
524
- logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
525
- logger.info(f"Output will be written to column: {output_column}")
526
-
527
- # Process images in batches
528
- all_outputs = []
529
-
530
- for batch_indices in tqdm(
531
- partition_all(batch_size, range(len(dataset))),
532
- total=(len(dataset) + batch_size - 1) // batch_size,
533
- desc="HunyuanOCR-1.5 processing",
534
- ):
535
- batch_indices = list(batch_indices)
536
- batch_images = [dataset[i][image_column] for i in batch_indices]
537
-
538
- try:
539
- # Create messages for batch
540
- batch_messages = [make_ocr_message(img, prompt) for img in batch_images]
541
-
542
- # Process with vLLM
543
- outputs = llm.chat(batch_messages, sampling_params)
544
-
545
- # Extract outputs
546
- for output in outputs:
547
- text = output.outputs[0].text.strip()
548
- # Clean repeated substrings if enabled
549
- if clean_output:
550
- text = clean_repeated_substrings(text)
551
- all_outputs.append(text)
552
-
553
- except Exception as e:
554
- logger.error(f"Error processing batch: {e}")
555
- # Add error placeholders for failed batch
556
- all_outputs.extend(["[OCR ERROR]"] * len(batch_images))
557
-
558
- # Calculate processing time
559
- processing_duration = datetime.now() - start_time
560
- processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
561
-
562
- # Add output column to dataset
563
- logger.info(f"Adding '{output_column}' column to dataset")
564
- dataset = dataset.add_column(output_column, all_outputs)
565
-
566
- # Handle inference_info tracking (for multi-model comparisons)
567
- inference_entry = {
568
- "model_id": model,
569
- "model_name": "HunyuanOCR-1.5",
570
- "model_revision": revision or "main",
571
- "column_name": output_column,
572
- "timestamp": datetime.now().isoformat(),
573
- "task_type": task_type if not custom_prompt else "custom",
574
- "repetition_penalty": repetition_penalty,
575
- }
576
-
577
- if "inference_info" in dataset.column_names:
578
- # Append to existing inference info
579
- logger.info("Updating existing inference_info column")
580
-
581
- def update_inference_info(example):
582
- try:
583
- existing_info = (
584
- json.loads(example["inference_info"])
585
- if example["inference_info"]
586
- else []
587
- )
588
- except (json.JSONDecodeError, TypeError):
589
- existing_info = []
590
-
591
- existing_info.append(inference_entry)
592
- return {"inference_info": json.dumps(existing_info)}
593
-
594
- dataset = dataset.map(update_inference_info)
595
- else:
596
- # Create new inference_info column
597
- logger.info("Creating new inference_info column")
598
- inference_list = [json.dumps([inference_entry])] * len(dataset)
599
- dataset = dataset.add_column("inference_info", inference_list)
600
-
601
- # Push to hub with retry and XET fallback
602
- logger.info(f"Pushing to {output_dataset}")
603
- commit_msg = f"Add HunyuanOCR-1.5 OCR results ({len(dataset)} samples)" + (
604
- f" [{config}]" if config else ""
605
- )
606
- max_retries = 3
607
- for attempt in range(1, max_retries + 1):
608
- try:
609
- if attempt > 1:
610
- logger.warning("Disabling XET (fallback to HTTP upload)")
611
- os.environ["HF_HUB_DISABLE_XET"] = "1"
612
- dataset.push_to_hub(
613
- output_dataset,
614
- private=private,
615
- token=HF_TOKEN,
616
- max_shard_size="500MB",
617
- **({"config_name": config} if config else {}),
618
- create_pr=create_pr,
619
- commit_message=commit_msg,
620
- )
621
- break
622
- except Exception as e:
623
- logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
624
- if attempt < max_retries:
625
- delay = 30 * (2 ** (attempt - 1))
626
- logger.info(f"Retrying in {delay}s...")
627
- time.sleep(delay)
628
- else:
629
- logger.error("All upload attempts failed. OCR results are lost.")
630
- sys.exit(1)
631
-
632
- # Create and push dataset card (skip when creating PR to avoid conflicts)
633
- if not create_pr:
634
- logger.info("Creating dataset card")
635
- card_content = create_dataset_card(
636
- source_dataset=input_dataset,
637
- model=model,
638
- num_samples=len(dataset),
639
- processing_time=processing_time_str,
640
- batch_size=batch_size,
641
- max_model_len=max_model_len,
642
- max_tokens=max_tokens,
643
- repetition_penalty=repetition_penalty,
644
- gpu_memory_utilization=gpu_memory_utilization,
645
- image_column=image_column,
646
- output_column=output_column,
647
- split=split,
648
- task_type=task_type if not custom_prompt else "custom",
649
- )
650
-
651
- card = DatasetCard(card_content)
652
- card.push_to_hub(output_dataset, token=HF_TOKEN)
653
-
654
- logger.info("HunyuanOCR-1.5 processing complete!")
655
- logger.info(
656
- f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
657
- )
658
- logger.info(f"Processing time: {processing_time_str}")
659
-
660
- if verbose:
661
- import importlib.metadata
662
-
663
- logger.info("--- Resolved package versions ---")
664
- for pkg in [
665
- "vllm",
666
- "transformers",
667
- "torch",
668
- "datasets",
669
- "pyarrow",
670
- "pillow",
671
- ]:
672
- try:
673
- logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
674
- except importlib.metadata.PackageNotFoundError:
675
- logger.info(f" {pkg}: not installed")
676
- logger.info("--- End versions ---")
677
-
678
-
679
- if __name__ == "__main__":
680
- # Show example usage if no arguments
681
- if len(sys.argv) == 1:
682
- print("=" * 80)
683
- print("HunyuanOCR-1.5 Document Processing")
684
- print("=" * 80)
685
- print(
686
- "\nLightweight ~1B end-to-end OCR VLM from Tencent (128K context, 4K images)"
687
- )
688
- print("\nFeatures:")
689
- print("- 📝 End-to-end document parsing to markdown")
690
- print("- 📊 Table extraction (HTML format)")
691
- print("- 📐 Formula recognition (LaTeX format)")
692
- print("- 📍 Text spotting with coordinates (JSON / Hunyuan)")
693
- print("- 📈 Chart parsing (Mermaid / Markdown)")
694
- print("- 🌐 Document + general-scene translation (→ zh / → en)")
695
- print("\nExample usage:")
696
- print("\n1. Basic document parsing:")
697
- print(" uv run hunyuan-ocr-1.5.py input-dataset output-dataset")
698
- print("\n2. Formula extraction:")
699
- print(" uv run hunyuan-ocr-1.5.py math-docs formulas --task-type formula")
700
- print("\n3. Table extraction:")
701
- print(" uv run hunyuan-ocr-1.5.py docs tables --task-type table")
702
- print("\n4. Text spotting as JSON (box + text):")
703
- print(" uv run hunyuan-ocr-1.5.py images spotted --task-type spotting_json")
704
- print("\n5. Translate a document to Chinese:")
705
- print(
706
- " uv run hunyuan-ocr-1.5.py en-docs zh-docs --task-type doc_trans_en2zh"
707
- )
708
- print("\n6. Running on HF Jobs:")
709
- print(" (image, hardware and HF_TOKEN come from the script's [tool.hf-jobs] header)")
710
- print(" hf jobs uv run \\")
711
- print(
712
- " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/hunyuan-ocr-1.5.py \\"
713
- )
714
- print(" input-dataset output-dataset")
715
- print("\n" + "=" * 80)
716
- print("\nFor full help, run: uv run hunyuan-ocr-1.5.py --help")
717
- sys.exit(0)
718
-
719
- task_help = "\n".join(f" {k:18s}- {TASK_DESCRIPTIONS[k]}" for k in TASK_PROMPTS)
720
- parser = argparse.ArgumentParser(
721
- description="Document OCR using HunyuanOCR-1.5 (lightweight ~1B end-to-end OCR VLM)",
722
- formatter_class=argparse.RawDescriptionHelpFormatter,
723
- epilog=f"""
724
- Task Types (official HunyuanOCR-1.5 prompts, all Chinese-language):
725
- {task_help}
726
-
727
- Examples:
728
- # Basic document OCR (default)
729
- uv run hunyuan-ocr-1.5.py my-docs analyzed-docs
730
-
731
- # Extract formulas as LaTeX
732
- uv run hunyuan-ocr-1.5.py math-papers formulas --task-type formula
733
-
734
- # Extract tables as HTML
735
- uv run hunyuan-ocr-1.5.py reports tables --task-type table
736
-
737
- # Text spotting as JSON (box normalized 0-1000 + text)
738
- uv run hunyuan-ocr-1.5.py images spotted --task-type spotting_json
739
-
740
- # Translate documents to Chinese
741
- uv run hunyuan-ocr-1.5.py en-docs translated --task-type doc_trans_en2zh
742
-
743
- # Random sampling for testing
744
- uv run hunyuan-ocr-1.5.py large-dataset test --max-samples 50 --shuffle
745
- """,
746
- )
747
-
748
- parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
749
- parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
750
- parser.add_argument(
751
- "--image-column",
752
- default="image",
753
- help="Column containing images (default: image)",
754
- )
755
- parser.add_argument(
756
- "--batch-size",
757
- type=int,
758
- default=16,
759
- help="Batch size for processing (default: 16; lower it if you hit engine errors)",
760
- )
761
- parser.add_argument(
762
- "--model",
763
- default="tencent/HunyuanOCR",
764
- help="Model to use (default: tencent/HunyuanOCR — repo root is 1.5)",
765
- )
766
- parser.add_argument(
767
- "--revision",
768
- default=None,
769
- help="Model repo revision (default: main). Tencent has replaced this repo's "
770
- "root in-place before (1.0 → 1.5); pin a commit hash for reproducible runs.",
771
- )
772
- parser.add_argument(
773
- "--max-model-len",
774
- type=int,
775
- default=32768,
776
- help="Maximum model context length (default: 32768; max 131072). A single "
777
- "image is capped at ~16384 tokens by the vision processor, so 32768 fits "
778
- "image + 8192 output; raise for very long outputs.",
779
- )
780
- parser.add_argument(
781
- "--max-tokens",
782
- type=int,
783
- default=8192,
784
- help="Maximum tokens to generate (default: 8192; must be ≤ --max-model-len). "
785
- "Dense pages may need more — raise toward 32768.",
786
- )
787
- parser.add_argument(
788
- "--repetition-penalty",
789
- type=float,
790
- default=DEFAULT_REPETITION_PENALTY,
791
- help=f"Repetition penalty (default: {DEFAULT_REPETITION_PENALTY}, the model card's locked value)",
792
- )
793
- parser.add_argument(
794
- "--gpu-memory-utilization",
795
- type=float,
796
- default=0.8,
797
- help="GPU memory utilization (default: 0.8)",
798
- )
799
- parser.add_argument("--hf-token", help="Hugging Face API token")
800
- parser.add_argument(
801
- "--split", default="train", help="Dataset split to use (default: train)"
802
- )
803
- parser.add_argument(
804
- "--max-samples",
805
- type=int,
806
- help="Maximum number of samples to process (for testing)",
807
- )
808
- parser.add_argument(
809
- "--private", action="store_true", help="Make output dataset private"
810
- )
811
- parser.add_argument(
812
- "--shuffle", action="store_true", help="Shuffle dataset before processing"
813
- )
814
- parser.add_argument(
815
- "--seed",
816
- type=int,
817
- default=42,
818
- help="Random seed for shuffling (default: 42)",
819
- )
820
- parser.add_argument(
821
- "--task-type",
822
- choices=list(TASK_PROMPTS.keys()),
823
- default=DEFAULT_TASK,
824
- metavar="TASK",
825
- help=f"Official task type (default: {DEFAULT_TASK}). See the epilog for all types.",
826
- )
827
- parser.add_argument(
828
- "--custom-prompt",
829
- help="Custom prompt text (overrides --task-type; may degrade quality — upstream "
830
- "locks prompts per task)",
831
- )
832
- parser.add_argument(
833
- "--output-column",
834
- default="markdown",
835
- help="Column name for output text (default: markdown)",
836
- )
837
- parser.add_argument(
838
- "--overwrite",
839
- action="store_true",
840
- help="Replace the output column if it already exists in the input dataset "
841
- "(default: error out to avoid clobbering an existing column).",
842
- )
843
- parser.add_argument(
844
- "--no-clean-output",
845
- action="store_true",
846
- help="Disable cleaning of repeated substrings in output",
847
- )
848
- parser.add_argument(
849
- "--config",
850
- help="Dataset config name for multi-model benchmarks",
851
- )
852
- parser.add_argument(
853
- "--create-pr",
854
- action="store_true",
855
- help="Push results as a pull request instead of direct commit",
856
- )
857
- parser.add_argument(
858
- "--verbose",
859
- action="store_true",
860
- help="Log resolved package versions at the end of the run",
861
- )
862
-
863
- args = parser.parse_args()
864
-
865
- main(
866
- input_dataset=args.input_dataset,
867
- output_dataset=args.output_dataset,
868
- image_column=args.image_column,
869
- batch_size=args.batch_size,
870
- model=args.model,
871
- revision=args.revision,
872
- max_model_len=args.max_model_len,
873
- max_tokens=args.max_tokens,
874
- repetition_penalty=args.repetition_penalty,
875
- gpu_memory_utilization=args.gpu_memory_utilization,
876
- hf_token=args.hf_token,
877
- split=args.split,
878
- max_samples=args.max_samples,
879
- private=args.private,
880
- shuffle=args.shuffle,
881
- seed=args.seed,
882
- task_type=args.task_type,
883
- custom_prompt=args.custom_prompt,
884
- output_column=args.output_column,
885
- overwrite=args.overwrite,
886
- clean_output=not args.no_clean_output,
887
- config=args.config,
888
- create_pr=args.create_pr,
889
- verbose=args.verbose,
890
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
hunyuan-ocr.py CHANGED
@@ -5,9 +5,6 @@
5
  # "huggingface-hub",
6
  # "pillow",
7
  # "vllm>=0.15.1",
8
- # "transformers<5.13", # vLLM ≤0.24.0's HunyuanVL processor breaks on transformers 5.13
9
- # # (string-key AutoImageProcessor.register; fixed in vllm#47872).
10
- # # Drop this cap once that fix ships in a stable vLLM release.
11
  # "tqdm",
12
  # "toolz",
13
  # "torch",
@@ -15,20 +12,11 @@
15
  # ///
16
 
17
  """
18
- UNSUPPORTED: Broken (2026-09-23): the pinned 1.0 revision fails on current vLLM/transformers. Use hunyuan-ocr-1.5.py. See models.json (`support`).
19
-
20
- Convert document images to markdown using HunyuanOCR (v1.0) with vLLM.
21
 
22
  HunyuanOCR is a lightweight 1B parameter VLM from Tencent designed for complex
23
  multilingual document parsing. This script uses vLLM for processing.
24
 
25
- ⚠️ This recipe targets HunyuanOCR **1.0**. On 2026-07-06 Tencent pushed
26
- HunyuanOCR-1.5 into the *same* repo (new weights at root, 1.0 archived under
27
- `v1.0/`, no git tag), so loading `tencent/HunyuanOCR@main` now yields 1.5 —
28
- different context length, prompts, and transformers/vLLM requirements. We pin
29
- the last 1.0 commit by revision to keep this script's validated behavior.
30
- For 1.5, use the sibling `hunyuan-ocr-1.5.py`.
31
-
32
  Features:
33
  - 📝 Full document parsing to markdown
34
  - 📊 Table extraction (HTML format)
@@ -38,10 +26,8 @@ Features:
38
  - 🌐 Photo translation
39
  - 🎯 Compact model (1B parameters)
40
 
41
- Model: tencent/HunyuanOCR (pinned to the last 1.0 revision)
42
-
43
- License: Tencent Hunyuan Community License (territory excludes EU/UK/South Korea)
44
- https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE
45
 
46
  Note: Due to vLLM V1 engine batching issues with HunyuanOCR, batch_size defaults to 1.
47
  """
@@ -63,21 +49,11 @@ from huggingface_hub import DatasetCard, login
63
  from PIL import Image
64
  from toolz import partition_all
65
  from tqdm.auto import tqdm
66
- # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
67
- # default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
68
- # lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
69
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
70
  from vllm import LLM, SamplingParams
71
 
72
  logging.basicConfig(level=logging.INFO)
73
  logger = logging.getLogger(__name__)
74
 
75
- # Last commit where the repo root held the 1.0 weights (2026-01-13). Not a temporary
76
- # workaround pin: upstream replaced root with 1.5 in-place (2026-07-06) and left no
77
- # 1.0 tag/branch, so this revision IS the 1.0 identity. Never loosen to "main" here —
78
- # 1.5 lives in hunyuan-ocr-1.5.py. Override with --revision only to reproduce old runs.
79
- DEFAULT_REVISION = "f6af82ee007fe6091b29fb3bb287b491ead41c82"
80
-
81
 
82
  # ────────────────────────────────────────────────────────────────
83
  # HunyuanOCR Prompt Templates (from official README)
@@ -170,28 +146,6 @@ def check_cuda_availability():
170
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
171
 
172
 
173
- def ensure_output_columns_free(dataset, columns, overwrite=False):
174
- """Fail fast if an output column would collide with an existing input column.
175
-
176
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
177
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
178
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
179
- column(s) here instead (logged) so the later add_column is clean.
180
- """
181
- clash = [c for c in columns if c in dataset.column_names]
182
- if not clash:
183
- return dataset
184
- if overwrite:
185
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
186
- return dataset.remove_columns(clash)
187
- logger.error(
188
- f"Output column(s) {clash} already exist in the input dataset "
189
- f"(columns: {dataset.column_names})."
190
- )
191
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
192
- sys.exit(1)
193
-
194
-
195
  def get_prompt(
196
  prompt_mode: str,
197
  use_chinese: bool = False,
@@ -268,7 +222,6 @@ def make_ocr_message(
268
  def create_dataset_card(
269
  source_dataset: str,
270
  model: str,
271
- revision: str,
272
  num_samples: int,
273
  processing_time: str,
274
  batch_size: int,
@@ -298,13 +251,10 @@ tags:
298
 
299
  This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using HunyuanOCR, a lightweight 1B VLM from Tencent.
300
 
301
- Model license: [Tencent Hunyuan Community License](https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE) (territory excludes EU/UK/South Korea).
302
-
303
  ## Processing Details
304
 
305
  - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
306
  - **Model**: [{model}](https://huggingface.co/{model})
307
- - **Model Revision**: `{revision}` (HunyuanOCR 1.0 — the repo root holds 1.5 since 2026-07-06)
308
  - **Number of Samples**: {num_samples:,}
309
  - **Processing Time**: {processing_time}
310
  - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
@@ -396,7 +346,6 @@ def main(
396
  image_column: str = "image",
397
  batch_size: int = 1, # Default to 1 due to vLLM V1 batching issues with HunyuanOCR
398
  model: str = "tencent/HunyuanOCR",
399
- revision: str = None,
400
  max_model_len: int = 16384,
401
  max_tokens: int = 16384,
402
  gpu_memory_utilization: float = 0.8,
@@ -413,7 +362,6 @@ def main(
413
  use_chinese: bool = False,
414
  custom_prompt: str = None,
415
  output_column: str = "markdown",
416
- overwrite: bool = False,
417
  clean_output: bool = True,
418
  config: str = None,
419
  create_pr: bool = False,
@@ -457,9 +405,6 @@ def main(
457
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
458
  )
459
 
460
- # Fail fast if the output column would collide with an existing input column
461
- dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
462
-
463
  # Shuffle if requested
464
  if shuffle:
465
  logger.info(f"Shuffling dataset with seed {seed}")
@@ -470,21 +415,14 @@ def main(
470
  dataset = dataset.select(range(min(max_samples, len(dataset))))
471
  logger.info(f"Limited to {len(dataset)} samples")
472
 
473
- # Pin the 1.0 revision only for the default repo — a user-supplied --model
474
- # must not inherit a foreign commit hash.
475
- if revision is None and model == "tencent/HunyuanOCR":
476
- revision = DEFAULT_REVISION
477
- logger.info(f"Pinning tencent/HunyuanOCR to 1.0 revision {revision[:8]}")
478
-
479
  # Initialize vLLM model
480
- logger.info(f"Initializing vLLM: {model} (revision: {revision or 'main'})")
481
  logger.info("This may take a few minutes on first run...")
482
 
483
  # Note: HunyuanOCR has batching issues with vLLM V1 engine when batch_size > 1
484
  # Using limit_mm_per_prompt for stability
485
  llm = LLM(
486
  model=model,
487
- revision=revision,
488
  trust_remote_code=True,
489
  max_model_len=max_model_len,
490
  gpu_memory_utilization=gpu_memory_utilization,
@@ -543,7 +481,6 @@ def main(
543
  inference_entry = {
544
  "model_id": model,
545
  "model_name": "HunyuanOCR",
546
- "model_revision": revision or "main",
547
  "column_name": output_column,
548
  "timestamp": datetime.now().isoformat(),
549
  "prompt_mode": prompt_mode if not custom_prompt else "custom",
@@ -611,7 +548,6 @@ def main(
611
  card_content = create_dataset_card(
612
  source_dataset=input_dataset,
613
  model=model,
614
- revision=revision or "main",
615
  num_samples=len(dataset),
616
  processing_time=processing_time_str,
617
  batch_size=batch_size,
@@ -765,13 +701,6 @@ Examples:
765
  default="tencent/HunyuanOCR",
766
  help="Model to use (default: tencent/HunyuanOCR)",
767
  )
768
- parser.add_argument(
769
- "--revision",
770
- default=None,
771
- help="Model repo revision. Defaults to the last 1.0 commit when --model is "
772
- "tencent/HunyuanOCR (the repo root now holds 1.5 — see hunyuan-ocr-1.5.py); "
773
- "defaults to main for any other model.",
774
- )
775
  parser.add_argument(
776
  "--max-model-len",
777
  type=int,
@@ -853,12 +782,6 @@ Examples:
853
  default="markdown",
854
  help="Column name for output text (default: markdown)",
855
  )
856
- parser.add_argument(
857
- "--overwrite",
858
- action="store_true",
859
- help="Replace the output column if it already exists in the input dataset "
860
- "(default: error out to avoid clobbering an existing column).",
861
- )
862
  parser.add_argument(
863
  "--no-clean-output",
864
  action="store_true",
@@ -892,7 +815,6 @@ Examples:
892
  image_column=args.image_column,
893
  batch_size=args.batch_size,
894
  model=args.model,
895
- revision=args.revision,
896
  max_model_len=args.max_model_len,
897
  max_tokens=args.max_tokens,
898
  gpu_memory_utilization=args.gpu_memory_utilization,
@@ -909,7 +831,6 @@ Examples:
909
  use_chinese=args.use_chinese_prompts,
910
  custom_prompt=args.custom_prompt,
911
  output_column=args.output_column,
912
- overwrite=args.overwrite,
913
  clean_output=not args.no_clean_output,
914
  config=args.config,
915
  create_pr=args.create_pr,
 
5
  # "huggingface-hub",
6
  # "pillow",
7
  # "vllm>=0.15.1",
 
 
 
8
  # "tqdm",
9
  # "toolz",
10
  # "torch",
 
12
  # ///
13
 
14
  """
15
+ Convert document images to markdown using HunyuanOCR with vLLM.
 
 
16
 
17
  HunyuanOCR is a lightweight 1B parameter VLM from Tencent designed for complex
18
  multilingual document parsing. This script uses vLLM for processing.
19
 
 
 
 
 
 
 
 
20
  Features:
21
  - 📝 Full document parsing to markdown
22
  - 📊 Table extraction (HTML format)
 
26
  - 🌐 Photo translation
27
  - 🎯 Compact model (1B parameters)
28
 
29
+ Model: tencent/HunyuanOCR
30
+ vLLM: Requires nightly build (trust_remote_code=True)
 
 
31
 
32
  Note: Due to vLLM V1 engine batching issues with HunyuanOCR, batch_size defaults to 1.
33
  """
 
49
  from PIL import Image
50
  from toolz import partition_all
51
  from tqdm.auto import tqdm
 
 
 
 
52
  from vllm import LLM, SamplingParams
53
 
54
  logging.basicConfig(level=logging.INFO)
55
  logger = logging.getLogger(__name__)
56
 
 
 
 
 
 
 
57
 
58
  # ────────────────────────────────────────────────────────────────
59
  # HunyuanOCR Prompt Templates (from official README)
 
146
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
147
 
148
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  def get_prompt(
150
  prompt_mode: str,
151
  use_chinese: bool = False,
 
222
  def create_dataset_card(
223
  source_dataset: str,
224
  model: str,
 
225
  num_samples: int,
226
  processing_time: str,
227
  batch_size: int,
 
251
 
252
  This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using HunyuanOCR, a lightweight 1B VLM from Tencent.
253
 
 
 
254
  ## Processing Details
255
 
256
  - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
257
  - **Model**: [{model}](https://huggingface.co/{model})
 
258
  - **Number of Samples**: {num_samples:,}
259
  - **Processing Time**: {processing_time}
260
  - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
 
346
  image_column: str = "image",
347
  batch_size: int = 1, # Default to 1 due to vLLM V1 batching issues with HunyuanOCR
348
  model: str = "tencent/HunyuanOCR",
 
349
  max_model_len: int = 16384,
350
  max_tokens: int = 16384,
351
  gpu_memory_utilization: float = 0.8,
 
362
  use_chinese: bool = False,
363
  custom_prompt: str = None,
364
  output_column: str = "markdown",
 
365
  clean_output: bool = True,
366
  config: str = None,
367
  create_pr: bool = False,
 
405
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
406
  )
407
 
 
 
 
408
  # Shuffle if requested
409
  if shuffle:
410
  logger.info(f"Shuffling dataset with seed {seed}")
 
415
  dataset = dataset.select(range(min(max_samples, len(dataset))))
416
  logger.info(f"Limited to {len(dataset)} samples")
417
 
 
 
 
 
 
 
418
  # Initialize vLLM model
419
+ logger.info(f"Initializing vLLM with model: {model}")
420
  logger.info("This may take a few minutes on first run...")
421
 
422
  # Note: HunyuanOCR has batching issues with vLLM V1 engine when batch_size > 1
423
  # Using limit_mm_per_prompt for stability
424
  llm = LLM(
425
  model=model,
 
426
  trust_remote_code=True,
427
  max_model_len=max_model_len,
428
  gpu_memory_utilization=gpu_memory_utilization,
 
481
  inference_entry = {
482
  "model_id": model,
483
  "model_name": "HunyuanOCR",
 
484
  "column_name": output_column,
485
  "timestamp": datetime.now().isoformat(),
486
  "prompt_mode": prompt_mode if not custom_prompt else "custom",
 
548
  card_content = create_dataset_card(
549
  source_dataset=input_dataset,
550
  model=model,
 
551
  num_samples=len(dataset),
552
  processing_time=processing_time_str,
553
  batch_size=batch_size,
 
701
  default="tencent/HunyuanOCR",
702
  help="Model to use (default: tencent/HunyuanOCR)",
703
  )
 
 
 
 
 
 
 
704
  parser.add_argument(
705
  "--max-model-len",
706
  type=int,
 
782
  default="markdown",
783
  help="Column name for output text (default: markdown)",
784
  )
 
 
 
 
 
 
785
  parser.add_argument(
786
  "--no-clean-output",
787
  action="store_true",
 
815
  image_column=args.image_column,
816
  batch_size=args.batch_size,
817
  model=args.model,
 
818
  max_model_len=args.max_model_len,
819
  max_tokens=args.max_tokens,
820
  gpu_memory_utilization=args.gpu_memory_utilization,
 
831
  use_chinese=args.use_chinese_prompts,
832
  custom_prompt=args.custom_prompt,
833
  output_column=args.output_column,
 
834
  clean_output=not args.no_clean_output,
835
  config=args.config,
836
  create_pr=args.create_pr,
images/hpd-parsing/README.md DELETED
@@ -1,18 +0,0 @@
1
- # cr.hf.co/davanstrien/hpd-parsing-vllm
2
-
3
- Public. Built 2026-11-05. Public page: https://huggingface.co/containers/davanstrien/hpd-parsing-vllm
4
-
5
- Runtime image for [`../../hpd-parsing-saturate.py`](../../hpd-parsing-saturate.py): Paddle's
6
- HPD-Parsing image with `uv` added, so the recipe runs with `hf jobs uv run`.
7
-
8
- | Tag | Base (Paddle, pinned) | Digest |
9
- |---|---|---|
10
- | `87496aa5-uv0.13.6` (also `latest`) | `ccr-2vdh3abv-pub.cnc.bj.baidubce.com/paddlepaddle/hpd-parsing-vllm@sha256:87496aa5…` (`latest-nvidia-gpu`, built 2026-07-16) | `sha256:b7d3c561cc245572b11ec3bce0739fd359c564b890d8e848b53b1a8346a573c5` |
11
-
12
- Why a custom image: HPD-Parsing runs on Paddle's vLLM fork (`0.17.1+hpdparsing`, request
13
- forking + P-MTP speculative decoding), which ships in their registry image. That image has no
14
- `uv`, which `hf jobs uv run --image <image>` needs. This image adds one layer, `uv` and `uvx` (0.13.6, checksum-verified)
15
- in `/usr/local/bin`. User, venv, environment and entrypoint are unchanged.
16
-
17
- Built with [`build.sh`](build.sh) and `crane append` on an HF CPU Job (`cpu-upgrade`); no Docker
18
- daemon. Drop it when Paddle's image ships `uv`, or when request forking lands in an upstream vLLM release.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
images/hpd-parsing/build.sh DELETED
@@ -1,42 +0,0 @@
1
- #!/usr/bin/env bash
2
- # Build cr.hf.co/<namespace>/hpd-parsing-vllm: Paddle's HPD-Parsing image plus uv.
3
- #
4
- # Paddle's image (vendor vLLM fork 0.17.1+hpdparsing) has no `uv`, which
5
- # `hf jobs uv run --image <image>` needs. This adds one layer, the uv and uvx binaries in /usr/local/bin, to the
6
- # vendor image pinned by digest. Nothing else changes: same user (hpd), same venv,
7
- # same entrypoint. No Docker daemon is needed: `crane append` adds the layer and
8
- # pushes. Runs on a CPU Job (the base layers stream from Baidu's registry to cr.hf.co).
9
- #
10
- # Run (the container repo must exist; HF_TOKEN needs write on its namespace):
11
- #
12
- # hf jobs run --flavor cpu-upgrade -s HF_TOKEN --timeout 1h \
13
- # -v hf://datasets/uv-scripts/ocr:/recipe:ro \
14
- # python:3.12 -- bash /recipe/images/hpd-parsing/build.sh cr.hf.co/<namespace>/hpd-parsing-vllm
15
- set -euo pipefail
16
-
17
- REPO="${1:?usage: build.sh <cr.hf.co/namespace/name>}"
18
- BASE_DIGEST="sha256:87496aa5dd702a7df6c70bb00c29d5bf8d1a0f0505d66b613fafa6f71cd72de2"
19
- BASE="ccr-2vdh3abv-pub.cnc.bj.baidubce.com/paddlepaddle/hpd-parsing-vllm@${BASE_DIGEST}"
20
- UV_VERSION="0.13.6"
21
- CRANE_VERSION="v0.22.1"
22
- TAG="${BASE_DIGEST:7:8}-uv${UV_VERSION}"
23
-
24
- # 1. The layer: uv + uvx from the official release, checksum-verified.
25
- cd /tmp
26
- UV_TGZ="uv-x86_64-unknown-linux-gnu.tar.gz"
27
- curl -sSfLO "https://github.com/astral-sh/uv/releases/download/${UV_VERSION}/${UV_TGZ}"
28
- curl -sSfLO "https://github.com/astral-sh/uv/releases/download/${UV_VERSION}/${UV_TGZ}.sha256"
29
- sha256sum -c "${UV_TGZ}.sha256"
30
- tar -xzf "$UV_TGZ"
31
- mkdir -p layer/usr/local/bin
32
- install -m 755 uv-x86_64-unknown-linux-gnu/uv uv-x86_64-unknown-linux-gnu/uvx layer/usr/local/bin/
33
- tar -C layer --owner=0 --group=0 -cf layer.tar usr
34
- tar -tvf layer.tar
35
-
36
- # 2. Append it to the vendor image and push.
37
- curl -sSfL "https://github.com/google/go-containerregistry/releases/download/${CRANE_VERSION}/go-containerregistry_Linux_x86_64.tar.gz" \
38
- | tar -xz -C /usr/local/bin crane
39
- crane auth login cr.hf.co -u "${HF_USER:-user}" -p "$HF_TOKEN"
40
- crane append --platform linux/amd64 -b "$BASE" -f layer.tar -t "$REPO:$TAG"
41
- crane tag "$REPO:$TAG" latest
42
- echo "PUSHED $REPO:$TAG $(crane digest "$REPO:$TAG")"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
images/minicpm-ocr/Dockerfile DELETED
@@ -1,44 +0,0 @@
1
- # MiniCPM-OCR 1.0 runtime for Hugging Face Jobs: cr.hf.co/davanstrien/minicpm-ocr
2
- #
3
- # - vLLM nightly 5d35ce3 (27 Oct 2026). MiniCPMOcrForConditionalGeneration landed in vLLM main on
4
- # 23 Oct (18343393b4, the commit OpenBMB's install.sh builds from source) and is not in a
5
- # release yet; this nightly is newer and also has DSpark speculative decoding.
6
- # - transformers at OpenBMB's pin (549e5b4, "5.21.0.dev0"). pip reports it as outside the nightly's
7
- # transformers>=5.16.1,<5.21.0 (a pre-release of 5.21.0 is excluded by <5.21.0); vLLM serves the
8
- # model with it (smoke test, 27 Oct 2026).
9
- # - The minicpm-ocr SDK (layout, crops, assembly) in its own venv at /opt/sdk, as OpenBMB's docs
10
- # require (SDK and inference service in separate environments), with PaddlePaddle GPU for the
11
- # PP-DocLayoutV3 layout model.
12
- # - The layout model is baked in (sha256-checked) at $OCR_ASSETS_DIR, so a run never fetches it
13
- # from Paddle's CDN. Model weights are not baked in: pull a pinned revision at run time.
14
- FROM vllm/vllm-openai:nightly-5d35ce3934a7804b298559d2d99eec33792e1eb9@sha256:3431ebee919296f7a5f3604db353f639e1474a4c7ef37595e31de6699fd831a7
15
-
16
- ARG TRANSFORMERS_COMMIT=549e5b410733fb50e8efbbe4aa585cb89f6478ea
17
- ARG LAYOUT_URL=https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-DocLayoutV3_infer.tar
18
- ARG LAYOUT_SHA256=98b9bac88c80f6bc0fda7e0bfc2cae180020371c0b2edbb1eb498a70ace751b1
19
-
20
- RUN python3 -m pip install --no-cache-dir \
21
- "transformers @ https://github.com/huggingface/transformers/archive/${TRANSFORMERS_COMMIT}.tar.gz"
22
-
23
- # sdk-requirements.lock is `uv pip freeze` of /opt/sdk in the published image (digest in README.md),
24
- # so a rebuild installs the tested SDK environment rather than resolving it afresh.
25
- COPY sdk-requirements.lock /tmp/sdk-requirements.lock
26
- RUN python3 -m pip install --no-cache-dir uv==0.13.6 \
27
- && uv venv /opt/sdk --python 3.12 \
28
- && uv pip install --python /opt/sdk/bin/python --no-cache \
29
- --extra-index-url https://www.paddlepaddle.org.cn/packages/stable/cu129/ --index-strategy unsafe-best-match \
30
- -r /tmp/sdk-requirements.lock
31
-
32
- ENV OCR_ASSETS_DIR=/opt/minicpm-ocr-assets
33
- RUN mkdir -p ${OCR_ASSETS_DIR}/models \
34
- && curl -fsSL -o /tmp/layout.tar "${LAYOUT_URL}" \
35
- && echo "${LAYOUT_SHA256} /tmp/layout.tar" | sha256sum -c - \
36
- && tar -xf /tmp/layout.tar -C ${OCR_ASSETS_DIR}/models \
37
- && rm /tmp/layout.tar
38
-
39
- # The SDK CLI is on PATH as `minicpmvocr`; vLLM stays the image's `vllm`.
40
- RUN ln -s /opt/sdk/bin/minicpmvocr /usr/local/bin/minicpmvocr \
41
- && minicpmvocr --help > /dev/null
42
-
43
- ENTRYPOINT []
44
- CMD ["bash"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
images/minicpm-ocr/README.md DELETED
@@ -1,18 +0,0 @@
1
- # cr.hf.co/davanstrien/minicpm-ocr
2
-
3
- Runtime image for [`../../minicpm-ocr.py`](../../minicpm-ocr.py), public on the Hugging Face
4
- container registry: https://huggingface.co/containers/davanstrien/minicpm-ocr
5
-
6
- | Tag | Digest |
7
- |---|---|
8
- | `1.0-vllm-5d35ce3` (also `latest`) | `sha256:2fb9a09980abecb3102b99b0685b57b4ecde22702b3a441c03fab22e30239aea` |
9
-
10
- Built with kaniko on an HF CPU Job (`cpu-upgrade`, about 20 minutes),
11
- pushed to `cr.hf.co`. The published digest was built before `sdk-requirements.lock` existed;
12
- the lock is that image's `/opt/sdk` environment (`uv pip freeze`), so a rebuild reproduces it. Why a custom image: MiniCPM-OCR's architecture is in vLLM main but not in a
13
- vLLM release yet, and the SDK needs PaddlePaddle in its own environment. Drop it for a stock
14
- `vllm/vllm-openai` tag plus a pip-installed SDK once a vLLM release has the architecture.
15
-
16
- Build note: pip warns that `transformers 5.21.0.dev0` does not satisfy vLLM's
17
- `transformers<5.21.0` (a pre-release of 5.21.0 is excluded by `<5.21.0`). This is OpenBMB's pin;
18
- vLLM serves the model with it (smoke test, 27 Oct 2026).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
images/minicpm-ocr/sdk-requirements.lock DELETED
@@ -1,90 +0,0 @@
1
- aistudio-sdk==0.3.9
2
- annotated-types==0.8.0
3
- anyio==4.15.1
4
- bce-python-sdk==0.9.79
5
- beautifulsoup4==4.15.0
6
- certifi==2026.10.23
7
- cffi==2.1.1
8
- chardet==7.7.0
9
- charset-normalizer==3.5.2
10
- click==8.5.0
11
- colorlog==6.12.0
12
- crc32c==2.9.post0
13
- cryptography==50.0.2
14
- cuda-bindings==12.9.5
15
- cuda-pathfinder==1.3.3
16
- cuda-python==12.9.4
17
- filelock==4.2.4
18
- flatbuffers==25.12.19
19
- fsspec==2026.9.0
20
- future==1.0.0
21
- h11==0.16.0
22
- hf-xet==1.7.0
23
- httpcore==1.0.9
24
- httpcore2==2.16.0
25
- httpx==0.28.1
26
- httpx2==2.16.0
27
- huggingface-hub==2.3.0
28
- idna==3.20
29
- imagesize==2.0.1
30
- minicpm-ocr==1.0.1
31
- modelscope==1.40.2
32
- modelscope-hub==0.5.1
33
- networkx==3.7
34
- numpy==2.5.4
35
- nvidia-cublas-cu12==12.9.0.13
36
- nvidia-cuda-cccl-cu12==12.9.27
37
- nvidia-cuda-cupti-cu12==12.9.19
38
- nvidia-cuda-nvrtc-cu12==12.9.41
39
- nvidia-cuda-runtime-cu12==12.9.37
40
- nvidia-cudnn-cu12==9.9.0.52
41
- nvidia-cufft-cu12==11.4.0.6
42
- nvidia-cufile-cu12==1.14.0.30
43
- nvidia-curand-cu12==10.3.10.19
44
- nvidia-cusolver-cu12==11.7.4.40
45
- nvidia-cusparse-cu12==12.5.9.5
46
- nvidia-cusparselt-cu12==0.7.1
47
- nvidia-nccl-cu12==2.27.3
48
- nvidia-nvjitlink-cu12==12.9.41
49
- nvidia-nvtx-cu12==12.9.19
50
- onnxruntime==1.31.1
51
- opencv-contrib-python==4.10.0.84
52
- opt-einsum==3.3.0
53
- packaging==26.3
54
- paddleocr==3.4.1
55
- paddlepaddle-gpu==3.3.0
56
- paddlex==3.4.2
57
- pandas==3.1.0
58
- pillow==13.0.0
59
- prettytable==3.18.0
60
- protobuf==7.36.2
61
- psutil==7.2.2
62
- py-cpuinfo==9.0.0
63
- pyclipper==1.4.0
64
- pycparser==3.12
65
- pycryptodome==4.2.0
66
- pydantic==2.14.1
67
- pydantic-core==2.50.1
68
- pymupdf==2.0
69
- pymupdf-layout==2.0
70
- pymupdf4llm==2.0
71
- pypdfium2==5.14.0
72
- python-bidi==0.6.12
73
- python-dateutil==3.0.0
74
- pyyaml==6.0.2
75
- requests==2.34.2
76
- ruamel-yaml==0.19.1
77
- safetensors==0.7.0
78
- setuptools==84.2.1
79
- shapely==2.2.0
80
- six==1.17.0
81
- soupsieve==3.0.4
82
- tabulate==0.10.0
83
- tqdm==4.70.1
84
- truststore==0.10.5
85
- typing-extensions==4.16.0
86
- typing-inspection==0.4.4
87
- tzdata==2026.5
88
- ujson==6.0.0
89
- urllib3==2.8.0
90
- wcwidth==0.9.4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
jina-ocr-v1.py DELETED
@@ -1,448 +0,0 @@
1
- # /// script
2
- # requires-python = ">=3.11"
3
- # dependencies = [
4
- # "datasets>=4.0.0",
5
- # "huggingface-hub",
6
- # "pillow",
7
- # "vllm>=0.21",
8
- # "tqdm",
9
- # "toolz",
10
- # "torch",
11
- # ]
12
- #
13
- # [tool.hf-jobs]
14
- # flavor = "a10g-small"
15
- # secrets = ["HF_TOKEN"]
16
- # env = { UV_TORCH_BACKEND = "auto" }
17
- # ///
18
-
19
- """
20
- UNSUPPORTED: Broken (2026-09-23): vLLM 0.30 DeepEncoder kernel error; pinning vllm/vllm-openai:v0.29.0 likely fixes it (as for deepseek-ocr-vllm.py). CC-BY-NC-4.0 model. See models.json (`support`).
21
-
22
- Convert document images to markdown using jina-ocr-v1 with vLLM (offline batch).
23
-
24
- jina-ocr-v1 (Jina AI, 2026-09) is a DeepSeek-OCR fine-tune: the DeepEncoder vision
25
- tower plus a 3B mixture-of-experts decoder with ~570M active parameters, and a
26
- FastMTP speculative-decoding head (one draft block reused for K=3 steps). The
27
- card reports 91.14 on OmniDocBench v1.6 and 83.4 on olmOCR-Bench. Licence:
28
- CC-BY-NC-4.0 (non-commercial).
29
-
30
- The model ships its own vLLM glue in the checkpoint (`deepseek_ocr_mtp.py`):
31
- architecture registration, the speculative config, and an n-gram repetition
32
- stop built on vLLM's own `repetition_detection`. This recipe follows the card's
33
- offline pattern exactly: put the snapshot on the import path, `register()`
34
- once, then `LLM(**vllm_llm_kwargs(...))` and `llm.chat(...)`.
35
-
36
- Run on HF Jobs (hardware and the HF_TOKEN secret come from the script's
37
- [tool.hf-jobs] header; `hf` CLI 1.32+):
38
-
39
- hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/jina-ocr-v1.py \\
40
- <input-dataset> <output-dataset>
41
-
42
- Notes:
43
- - `--spec 0` disables speculative decoding (A/B it: FastMTP is a latency trick
44
- that helps most at low concurrency; at batch 16 the gain may be small).
45
- - `--no-repetition-stop` disables the card's n-gram stop.
46
- - Uses vLLM from PyPI on the default uv image; the first run spends a few
47
- minutes installing it. `--image vllm/vllm-openai:<tag>` skips that.
48
-
49
- Model: jinaai/jina-ocr-v1
50
- """
51
-
52
- import argparse
53
- import io
54
- import json
55
- import logging
56
- import os
57
- import sys
58
- from datetime import datetime
59
- from typing import Any, Dict, Union
60
-
61
- from datasets import load_dataset
62
- from huggingface_hub import DatasetCard, login, snapshot_download
63
- from PIL import Image
64
- from toolz import partition_all
65
- from tqdm.auto import tqdm
66
-
67
- # The default uv-script image has no nvcc; vLLM's FlashInfer sampler would JIT a
68
- # kernel and crash engine init. Greedy OCR does not need it. No-op on vllm images.
69
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
70
- # register() adds architectures to this process's ModelRegistry; the engine worker only
71
- # sees them if it is forked, not spawned. Nothing below initialises CUDA before LLM().
72
- os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "fork")
73
-
74
- logging.basicConfig(level=logging.INFO)
75
- logger = logging.getLogger(__name__)
76
-
77
- MODEL_ID = "jinaai/jina-ocr-v1"
78
- SCRIPT_NAME = "jina-ocr-v1.py"
79
- SCRIPT_URL = f"https://huggingface.co/datasets/uv-scripts/ocr/raw/main/{SCRIPT_NAME}"
80
-
81
-
82
- def check_cuda_availability():
83
- """GPU check WITHOUT initialising CUDA in this process.
84
-
85
- torch.cuda.is_available() would initialise CUDA here, and vLLM then forces the
86
- `spawn` start method for its engine worker. A spawned worker does not inherit the
87
- ModelRegistry entries that register() adds in this process, so the custom
88
- architecture is "not supported" in the worker (seen on the first smoke run).
89
- nvidia-smi answers the same question with no CUDA context.
90
- """
91
- import shutil
92
- import subprocess
93
-
94
- if shutil.which("nvidia-smi") is None:
95
- logger.error("nvidia-smi not found. This script requires a GPU.")
96
- sys.exit(1)
97
- try:
98
- out = subprocess.run(["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],
99
- capture_output=True, text=True, timeout=30, check=True).stdout.strip()
100
- except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
101
- logger.error(f"nvidia-smi failed: {e}. This script requires a GPU.")
102
- sys.exit(1)
103
- logger.info(f"GPU: {out.splitlines()[0] if out else 'unknown'}")
104
-
105
-
106
- def ensure_output_columns_free(dataset, columns, overwrite=False):
107
- """Fail fast if an output column would overwrite an existing input column."""
108
- clash = [c for c in columns if c in dataset.column_names]
109
- if not clash:
110
- return dataset
111
- if overwrite:
112
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
113
- return dataset.remove_columns(clash)
114
- logger.error(f"Output column(s) {clash} already exist in the input dataset (columns: {dataset.column_names}).")
115
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
116
- sys.exit(1)
117
-
118
-
119
- def to_pil(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:
120
- if isinstance(image, Image.Image):
121
- return image
122
- if isinstance(image, dict) and "bytes" in image:
123
- return Image.open(io.BytesIO(image["bytes"]))
124
- if isinstance(image, str):
125
- return Image.open(image)
126
- raise ValueError(f"Unsupported image type: {type(image)}")
127
-
128
-
129
- def load_model_glue(revision: str | None):
130
- """Download the checkpoint and import its vLLM helpers.
131
-
132
- vLLM v1 starts its engine core as a *spawned* process, which does not inherit
133
- sys.path edits, so the snapshot directory also goes into PYTHONPATH before LLM()
134
- is created. The architecture override points at `deepseek_ocr_mtp`, which the
135
- worker must be able to import.
136
- """
137
- snapshot = snapshot_download(MODEL_ID, revision=revision)
138
- os.environ["PYTHONPATH"] = snapshot + os.pathsep + os.environ.get("PYTHONPATH", "")
139
- sys.path.insert(0, snapshot)
140
- import deepseek_ocr_mtp # noqa: E402 (lives in the checkpoint)
141
-
142
- return snapshot, deepseek_ocr_mtp
143
-
144
-
145
- def jobs_flavor() -> str:
146
- """Return the HF Jobs hardware flavor this run is on, or "" when it cannot be told.
147
-
148
- HF Jobs sets ACCELERATOR to "cpu" or "gpu", not the flavor name, so the flavor is looked up
149
- in the public Jobs hardware list: first by GPU model and count, then by the CPU_CORES and
150
- MEMORY values that Jobs sets in the container (to tell a10g-small from a10g-large, or
151
- cpu-basic from cpu-upgrade). Any failure (no network, older huggingface_hub) returns "".
152
- """
153
- hardware = os.environ.get("ACCELERATOR") or ""
154
- if "-" in hardware or any(character.isdigit() for character in hardware):
155
- return hardware # already a flavor name
156
- try:
157
- from huggingface_hub import HfApi
158
-
159
- gpu_name, gpu_count = "", 0
160
- try:
161
- import torch
162
-
163
- if torch.cuda.is_available():
164
- gpu_name = torch.cuda.get_device_name(0)
165
- gpu_count = torch.cuda.device_count()
166
- except ImportError:
167
- # Torch-free drivers (e.g. the -server recipes): ask nvidia-smi instead.
168
- import subprocess
169
-
170
- try:
171
- listed = subprocess.run(
172
- ["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],
173
- capture_output=True, text=True, timeout=10, check=True,
174
- ).stdout
175
- names = [line.strip() for line in listed.splitlines() if line.strip()]
176
- if names:
177
- gpu_name, gpu_count = names[0], len(names)
178
- except (OSError, subprocess.SubprocessError):
179
- pass
180
- if gpu_count == 0 and hardware == "gpu":
181
- return "" # a GPU run whose GPU cannot be identified: do not guess a CPU flavor
182
-
183
- # Whole-word match, so "L4" does not match "NVIDIA L40S" ("NVIDIA A100-SXM4-80GB" -> A100).
184
- gpu_words = gpu_name.upper().replace("-", " ").split()
185
- candidates = []
186
- for flavor in HfApi(token=False).list_jobs_hardware():
187
- accelerator = flavor.accelerator
188
- if gpu_count == 0 and accelerator is None:
189
- candidates.append(flavor)
190
- elif (
191
- gpu_count > 0
192
- and accelerator is not None
193
- and accelerator.model.upper() in gpu_words
194
- and int(accelerator.quantity) == gpu_count
195
- ):
196
- candidates.append(flavor)
197
- if not candidates:
198
- return ""
199
-
200
- cores = float(os.environ.get("CPU_CORES") or 0)
201
- memory_gb = float((os.environ.get("MEMORY") or "0").upper().rstrip("GIB ") or 0)
202
-
203
- def distance(flavor) -> float:
204
- # Relative gap to the listed vCPUs and RAM; Jobs reports slightly different numbers.
205
- listed_cores = float(flavor.cpu.split()[0])
206
- listed_memory = float(flavor.ram.split()[0])
207
- return abs(listed_cores - cores) / listed_cores + abs(listed_memory - memory_gb) / listed_memory
208
-
209
- return min(candidates, key=distance).name
210
- except Exception:
211
- return ""
212
-
213
-
214
- def create_dataset_card(
215
- source_dataset: str,
216
- num_samples: int,
217
- processing_time: str,
218
- batch_size: int,
219
- max_model_len: int,
220
- max_tokens: int,
221
- spec: int,
222
- repetition_stop: bool,
223
- image_column: str,
224
- output_column: str,
225
- split: str,
226
- image_count_per_sec: float,
227
- ) -> str:
228
- on_jobs = os.environ.get("JOB_ID") is not None
229
- hw = jobs_flavor() # flavor name, e.g. "a10g-small"; "" on CPU
230
- origin = (
231
- "Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"
232
- + (f" (`{hw}`)" if hw else "")
233
- ) if on_jobs else "Generated"
234
- tags = ["ocr", "document-processing", "jina-ocr", "markdown", "uv-script", "generated"]
235
- if on_jobs:
236
- tags.append("hf-jobs")
237
- tag_lines = "\n".join(f"- {t}" for t in tags)
238
-
239
- return f"""---
240
- tags:
241
- {tag_lines}
242
- ---
243
-
244
- # Document OCR using jina-ocr-v1
245
-
246
- Markdown OCR of the images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
247
- using [{MODEL_ID}](https://huggingface.co/{MODEL_ID}) (DeepSeek-OCR fine-tune, ~570M active parameters,
248
- FastMTP speculative decoding). The model is released under CC-BY-NC-4.0; check that licence before
249
- reusing these outputs commercially.
250
-
251
- ## Processing Details
252
-
253
- - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
254
- - **Model**: [{MODEL_ID}](https://huggingface.co/{MODEL_ID})
255
- - **Number of Samples**: {num_samples:,}
256
- - **Processing Time**: {processing_time} (~{image_count_per_sec:.2f} images/second including model load)
257
- - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
258
-
259
- ### Configuration
260
-
261
- - **Image Column**: `{image_column}`
262
- - **Output Column**: `{output_column}`
263
- - **Dataset Split**: `{split}`
264
- - **Batch Size**: {batch_size}
265
- - **Max Model Length**: {max_model_len:,} tokens
266
- - **Max Output Tokens**: {max_tokens:,}
267
- - **Speculative decoding (FastMTP draft depth)**: {spec}
268
- - **N-gram repetition stop**: {"on" if repetition_stop else "off"}
269
-
270
- ## Dataset Structure
271
-
272
- All original columns plus:
273
- - `{output_column}`: the extracted text as markdown (HTML tables, LaTeX math)
274
- - `inference_info`: JSON list tracking the OCR models applied to this dataset
275
-
276
- ## Reproduction
277
-
278
- {origin} with the [`{SCRIPT_NAME}`]({SCRIPT_URL}) recipe from [uv-scripts](https://huggingface.co/uv-scripts). Run it yourself:
279
-
280
- ```bash
281
- hf jobs uv run {SCRIPT_URL} \\
282
- {source_dataset} \\
283
- <output-dataset> \\
284
- --image-column {image_column} \\
285
- --batch-size {batch_size} \\
286
- --spec {spec}
287
- ```
288
- """
289
-
290
-
291
- def main():
292
- ap = argparse.ArgumentParser(description="jina-ocr-v1 batch OCR with vLLM (offline)")
293
- ap.add_argument("input_dataset")
294
- ap.add_argument("output_dataset")
295
- ap.add_argument("--image-column", default="image")
296
- ap.add_argument("--output-column", default="markdown")
297
- ap.add_argument("--overwrite", action="store_true", help="Replace an existing output column")
298
- ap.add_argument("--split", default="train")
299
- ap.add_argument("--input-config", default=None, help="Config (subset) name of the input dataset")
300
- ap.add_argument("--config", default=None, help="Config name for the output dataset")
301
- ap.add_argument("--max-samples", type=int, default=None)
302
- ap.add_argument("--shuffle", action="store_true")
303
- ap.add_argument("--seed", type=int, default=42)
304
- ap.add_argument("--batch-size", type=int, default=16)
305
- ap.add_argument("--max-tokens", type=int, default=4096)
306
- ap.add_argument("--max-model-len", type=int, default=8192)
307
- ap.add_argument("--gpu-memory-utilization", type=float, default=0.85)
308
- ap.add_argument("--spec", type=int, default=3, help="FastMTP draft depth K; 0 disables speculative decoding")
309
- ap.add_argument("--no-repetition-stop", action="store_true", help="Disable the card's n-gram repetition stop")
310
- ap.add_argument("--prompt", default=None, help="Override the model's default OCR prompt")
311
- ap.add_argument("--revision", default=None, help="Model revision to pin")
312
- ap.add_argument("--private", action="store_true")
313
- ap.add_argument("--create-pr", action="store_true")
314
- ap.add_argument("--hf-token", default=None)
315
- ap.add_argument("--verbose", action="store_true", help="Log resolved package versions after the run")
316
- args = ap.parse_args()
317
-
318
- check_cuda_availability()
319
- start_time = datetime.now()
320
-
321
- hf_token = args.hf_token or os.environ.get("HF_TOKEN")
322
- if hf_token:
323
- login(token=hf_token)
324
-
325
- logger.info(f"Loading dataset: {args.input_dataset}")
326
- dataset = load_dataset(args.input_dataset, name=args.input_config, split=args.split)
327
- if args.image_column not in dataset.column_names:
328
- raise ValueError(f"Column '{args.image_column}' not found. Available: {dataset.column_names}")
329
- dataset = ensure_output_columns_free(dataset, [args.output_column], overwrite=args.overwrite)
330
- if args.shuffle:
331
- dataset = dataset.shuffle(seed=args.seed)
332
- if args.max_samples:
333
- dataset = dataset.select(range(min(args.max_samples, len(dataset))))
334
- logger.info(f"Limited to {len(dataset)} samples")
335
-
336
- # --- model: the checkpoint's own vLLM glue, in the card's order ---------------
337
- snapshot, glue = load_model_glue(args.revision)
338
- from vllm import LLM
339
-
340
- glue.register()
341
- llm_kwargs = glue.vllm_llm_kwargs(
342
- snapshot, num_speculative_tokens=args.spec, mtp_heads=1, mtp_recursive=True,
343
- )
344
- llm_kwargs.setdefault("max_model_len", args.max_model_len)
345
- llm_kwargs.setdefault("gpu_memory_utilization", args.gpu_memory_utilization)
346
- llm_kwargs.setdefault("enable_prefix_caching", False)
347
- llm_kwargs.setdefault("mm_processor_cache_gb", 0)
348
- llm_kwargs.setdefault("limit_mm_per_prompt", {"image": 1})
349
- logger.info(f"Initializing vLLM with {MODEL_ID} (spec={args.spec}); this can take a few minutes")
350
- llm = LLM(**llm_kwargs)
351
-
352
- sampling_kwargs = {"max_tokens": args.max_tokens}
353
- if args.no_repetition_stop:
354
- sampling_kwargs["repetition_detection"] = None
355
- sampling_params = glue.vllm_sampling_params(**sampling_kwargs)
356
- prompt = args.prompt or glue.DEFAULT_OCR_PROMPT
357
- logger.info(f"Prompt: {prompt}")
358
-
359
- # --- inference ------------------------------------------------------------------
360
- all_markdown = []
361
- n_batches = (len(dataset) + args.batch_size - 1) // args.batch_size
362
- for batch_indices in tqdm(partition_all(args.batch_size, range(len(dataset))), total=n_batches, desc="jina-ocr-v1"):
363
- batch_indices = list(batch_indices)
364
- batch_images = [dataset[i][args.image_column] for i in batch_indices]
365
- try:
366
- messages = []
367
- for img in batch_images:
368
- pil_img = to_pil(img).convert("RGB")
369
- messages.append([{"role": "user", "content": [
370
- {"type": "image_pil", "image_pil": pil_img},
371
- {"type": "text", "text": prompt},
372
- ]}])
373
- outputs = llm.chat(messages, sampling_params=sampling_params, use_tqdm=False)
374
- for output in outputs:
375
- all_markdown.append(output.outputs[0].text.strip())
376
- except Exception as e:
377
- logger.error(f"Error processing batch: {e}")
378
- all_markdown.extend(["[OCR FAILED]"] * len(batch_images))
379
-
380
- if args.spec > 0:
381
- glue.log_spec_stats(llm)
382
-
383
- processing_duration = datetime.now() - start_time
384
- processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
385
- images_per_sec = len(dataset) / max(1.0, processing_duration.total_seconds())
386
-
387
- # --- output dataset ---------------------------------------------------------------
388
- dataset = dataset.add_column(args.output_column, all_markdown)
389
- inference_entry = {
390
- "model_id": MODEL_ID,
391
- "model_name": "jina-ocr-v1",
392
- "column_name": args.output_column,
393
- "timestamp": datetime.now().isoformat(),
394
- "prompt": "custom" if args.prompt else "default",
395
- "batch_size": args.batch_size,
396
- "max_tokens": args.max_tokens,
397
- "max_model_len": args.max_model_len,
398
- "speculative_tokens": args.spec,
399
- "repetition_stop": not args.no_repetition_stop,
400
- "script": SCRIPT_NAME,
401
- "script_url": SCRIPT_URL,
402
- }
403
- if "inference_info" in dataset.column_names:
404
- def update_inference_info(example):
405
- try:
406
- existing = json.loads(example["inference_info"]) if example["inference_info"] else []
407
- except (json.JSONDecodeError, TypeError):
408
- existing = []
409
- existing.append(inference_entry)
410
- return {"inference_info": json.dumps(existing)}
411
- dataset = dataset.map(update_inference_info)
412
- else:
413
- dataset = dataset.add_column("inference_info", [json.dumps([inference_entry])] * len(dataset))
414
-
415
- logger.info(f"Pushing to {args.output_dataset}")
416
- dataset.push_to_hub(
417
- args.output_dataset,
418
- private=args.private,
419
- token=hf_token,
420
- **({"config_name": args.config} if args.config else {}),
421
- create_pr=args.create_pr,
422
- commit_message=f"Add {MODEL_ID} OCR results ({len(dataset)} samples)" + (f" [{args.config}]" if args.config else ""),
423
- )
424
- card = DatasetCard(create_dataset_card(
425
- source_dataset=args.input_dataset, num_samples=len(dataset), processing_time=processing_time_str,
426
- batch_size=args.batch_size, max_model_len=args.max_model_len, max_tokens=args.max_tokens,
427
- spec=args.spec, repetition_stop=not args.no_repetition_stop, image_column=args.image_column,
428
- output_column=args.output_column, split=args.split, image_count_per_sec=images_per_sec,
429
- ))
430
- card.push_to_hub(args.output_dataset, token=hf_token)
431
- logger.info(f"Dataset available at: https://huggingface.co/datasets/{args.output_dataset}")
432
- logger.info(f"Processing time: {processing_time_str}")
433
-
434
- failed = sum(1 for m in all_markdown if m == "[OCR FAILED]")
435
- if failed:
436
- logger.warning(f"{failed} of {len(all_markdown)} rows are [OCR FAILED] (a whole batch fails together in offline mode)")
437
-
438
- if args.verbose:
439
- import importlib.metadata
440
- for pkg in ["vllm", "transformers", "torch", "datasets", "pillow"]:
441
- try:
442
- logger.info(f"{pkg}=={importlib.metadata.version(pkg)}")
443
- except importlib.metadata.PackageNotFoundError:
444
- logger.info(f"{pkg}: not installed")
445
-
446
-
447
- if __name__ == "__main__":
448
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lfm2-extract.py DELETED
@@ -1,336 +0,0 @@
1
- # /// script
2
- # requires-python = ">=3.11"
3
- # dependencies = [
4
- # "datasets>=4.0.0,<5.1", # 5.1 needs huggingface_hub>=1.31; the image ships an older 1.x on PYTHONPATH, which wins
5
- # "huggingface-hub",
6
- # "transformers",
7
- # "tqdm",
8
- # "toolz",
9
- # ]
10
- #
11
- # [tool.hf-jobs]
12
- # image = "vllm/vllm-openai:v0.29.0"
13
- # python = "/usr/bin/python3"
14
- # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
15
- # flavor = "a10g-small"
16
- # secrets = ["HF_TOKEN"]
17
- # ///
18
- """
19
- Extract structured data (JSON / XML / YAML) from text using LiquidAI's LFM2-1.2B-Extract.
20
-
21
- LFM2-1.2B-Extract is a compact 1.2B text-only model purpose-built for turning unstructured
22
- documents into structured data: give it a schema, it returns JSON, XML, or YAML. It reports
23
- beating Gemma 3 27B (22x larger) on syntax validity / format accuracy / faithfulness, and
24
- is multilingual (en, ar, zh, fr, de, ja, ko, pt, es).
25
-
26
- This is the *text* counterpart to `lfm2-vl-extract.py` (which extracts from images). Pair them:
27
- OCR a page to markdown with one of the OCR recipes, then extract fields from that text here.
28
-
29
- Pass `--schema` as inline text/JSON, a URL, or a file path describing the structure to extract:
30
-
31
- --schema '{"invoice_number": "string", "total": "number", "line_items": "array"}'
32
-
33
- Model: https://huggingface.co/LiquidAI/LFM2-1.2B-Extract
34
- Docs: https://docs.liquid.ai/deployment/gpu-inference/vllm
35
-
36
- HF Jobs: the `[tool.hf-jobs]` header above pins the vLLM image (vLLM + torch come from the
37
- image, not the deps), the GPU flavor and the HF_TOKEN secret, so no flags are needed
38
- (requires `hf` CLI 1.32+):
39
-
40
- hf jobs uv run \
41
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lfm2-extract.py \
42
- INPUT OUTPUT --text-column text --schema '{"field": "description"}'
43
-
44
- On your own GPU, supply vLLM yourself:
45
-
46
- uv run --with vllm==0.29.0 lfm2-extract.py INPUT OUTPUT --schema '{"field": "description"}'
47
-
48
- FlashInfer sampling is disabled (see below) so the engine never JIT-compiles a kernel that
49
- needs nvcc.
50
- """
51
-
52
- import argparse
53
- import json
54
- import logging
55
- import os
56
- import sys
57
- from datetime import datetime, timezone
58
- from typing import List, Optional
59
- from urllib.request import urlopen
60
-
61
- # Disable vLLM's FlashInfer sampler before the engine starts: it JIT-compiles at warmup and
62
- # needs nvcc (absent from the default uv image). Harmless for greedy decoding.
63
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
64
-
65
- import torch
66
- from datasets import load_dataset
67
- from huggingface_hub import DatasetCard, login
68
- from toolz import partition_all
69
- from tqdm import tqdm
70
- from vllm import LLM, SamplingParams
71
-
72
- logging.basicConfig(level=logging.INFO)
73
- logger = logging.getLogger(__name__)
74
-
75
- DEFAULT_MODEL = "LiquidAI/LFM2-1.2B-Extract"
76
- FORMATS = {"json": "JSON", "xml": "XML", "yaml": "YAML"}
77
-
78
-
79
- def check_cuda_availability() -> None:
80
- if not torch.cuda.is_available():
81
- logger.error("CUDA is not available. This script requires a GPU.")
82
- logger.error("Run on Hugging Face Jobs with: hf jobs uv run lfm2-extract.py ...")
83
- sys.exit(1)
84
- logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name()}")
85
-
86
-
87
- def ensure_output_columns_free(dataset, columns, overwrite=False):
88
- """Fail fast if an output column would collide with an existing input column.
89
-
90
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
91
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
92
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
93
- column(s) here instead (logged) so the later add_column is clean.
94
- """
95
- clash = [c for c in columns if c in dataset.column_names]
96
- if not clash:
97
- return dataset
98
- if overwrite:
99
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
100
- return dataset.remove_columns(clash)
101
- logger.error(
102
- f"Output column(s) {clash} already exist in the input dataset "
103
- f"(columns: {dataset.column_names})."
104
- )
105
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
106
- sys.exit(1)
107
-
108
-
109
- def load_text_arg(value: str) -> str:
110
- """Resolve --schema (inline text/JSON, URL, or file path) into a string."""
111
- text = value.strip()
112
- if text.startswith("http://") or text.startswith("https://"):
113
- logger.info(f"Loading schema from URL: {text}")
114
- return urlopen(text).read().decode("utf-8").strip()
115
- if os.path.exists(text):
116
- logger.info(f"Loading schema from file: {text}")
117
- with open(text) as f:
118
- return f.read().strip()
119
- return text
120
-
121
-
122
- def build_system_prompt(schema_text: str, fmt: str) -> str:
123
- return f"Return data as a {FORMATS[fmt]} object with the following schema:\n\n{schema_text}"
124
-
125
-
126
- def parse_output(text: str, fmt: str) -> tuple[str, bool]:
127
- """Strip code fences; for JSON, validate. Returns (cleaned_text, is_valid)."""
128
- stripped = text.strip()
129
- if stripped.startswith("```"):
130
- stripped = stripped.split("\n", 1)[-1]
131
- if stripped.endswith("```"):
132
- stripped = stripped.rsplit("```", 1)[0]
133
- stripped = stripped.strip()
134
- if fmt == "json":
135
- try:
136
- return json.dumps(json.loads(stripped), ensure_ascii=False), True
137
- except (json.JSONDecodeError, ValueError):
138
- return stripped, False
139
- return stripped, True # xml/yaml: store as-is (no strict validator)
140
-
141
-
142
- def main(
143
- input_dataset: str,
144
- output_dataset: str,
145
- schema: str,
146
- text_column: str = "text",
147
- output_column: str = "extraction",
148
- overwrite: bool = False,
149
- output_format: str = "json",
150
- split: str = "train",
151
- max_samples: Optional[int] = None,
152
- shuffle: bool = False,
153
- seed: int = 42,
154
- batch_size: int = 32,
155
- model: str = DEFAULT_MODEL,
156
- max_model_len: int = 8192,
157
- max_tokens: int = 4096,
158
- private: bool = False,
159
- hf_token: Optional[str] = None,
160
- ) -> None:
161
- check_cuda_availability()
162
- if output_format not in FORMATS:
163
- logger.error(f"--format must be one of {list(FORMATS)}; got {output_format}")
164
- sys.exit(1)
165
-
166
- HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
167
- if HF_TOKEN:
168
- login(token=HF_TOKEN)
169
-
170
- schema_text = load_text_arg(schema)
171
- system_prompt = build_system_prompt(schema_text, output_format)
172
-
173
- logger.info(f"Loading dataset: {input_dataset} (split={split})")
174
- dataset = load_dataset(input_dataset, split=split)
175
-
176
- # Fail fast if the output column would collide with an existing input column
177
- dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
178
-
179
- if shuffle:
180
- dataset = dataset.shuffle(seed=seed)
181
- if max_samples:
182
- dataset = dataset.select(range(min(max_samples, len(dataset))))
183
- logger.info(f"Processing {len(dataset)} examples; format={output_format}")
184
-
185
- if text_column not in dataset.column_names:
186
- logger.error(f"Text column '{text_column}' not found. Columns: {dataset.column_names}")
187
- sys.exit(1)
188
-
189
- logger.info(f"Loading model: {model}")
190
- llm = LLM(model=model, max_model_len=max_model_len, enforce_eager=True)
191
- sampling_params = SamplingParams(temperature=0.0, max_tokens=max_tokens)
192
-
193
- all_outputs: List[str] = []
194
- n_valid = 0
195
- texts = dataset[text_column]
196
- for batch in tqdm(list(partition_all(batch_size, texts)), desc="Extracting"):
197
- batch_messages = [
198
- [
199
- {"role": "system", "content": system_prompt},
200
- {"role": "user", "content": str(doc)},
201
- ]
202
- for doc in batch
203
- ]
204
- outputs = llm.chat(batch_messages, sampling_params)
205
- for out in outputs:
206
- cleaned, ok = parse_output(out.outputs[0].text, output_format)
207
- n_valid += int(ok)
208
- all_outputs.append(cleaned)
209
-
210
- logger.info(f"Valid {output_format.upper()}: {n_valid}/{len(all_outputs)}")
211
- dataset = dataset.add_column(output_column, all_outputs)
212
-
213
- inference_entry = {
214
- "model": model,
215
- "column_name": output_column,
216
- "task": "structured extraction",
217
- "format": output_format,
218
- "timestamp": datetime.now(timezone.utc).isoformat(),
219
- "script": "lfm2-extract.py",
220
- }
221
- if "inference_info" in dataset.column_names:
222
- def update_info(example):
223
- try:
224
- existing = json.loads(example["inference_info"]) if example["inference_info"] else []
225
- except (json.JSONDecodeError, TypeError):
226
- existing = []
227
- existing.append(inference_entry)
228
- return {"inference_info": json.dumps(existing)}
229
- dataset = dataset.map(update_info)
230
- else:
231
- dataset = dataset.add_column(
232
- "inference_info", [json.dumps([inference_entry])] * len(dataset)
233
- )
234
-
235
- logger.info(f"Pushing to {output_dataset}")
236
- dataset.push_to_hub(output_dataset, private=private, token=HF_TOKEN)
237
-
238
- card_text = f"""---
239
- tags:
240
- - uv-script
241
- - extraction
242
- - lfm2
243
- - {output_format}
244
- ---
245
-
246
- # Structured extraction with LFM2-1.2B-Extract
247
-
248
- `{output_format.upper()}` extracted from the `{text_column}` column of
249
- [{input_dataset}](https://huggingface.co/datasets/{input_dataset})
250
- using [{model}](https://huggingface.co/{model}).
251
-
252
- - **Source**: `{input_dataset}` (split `{split}`, column `{text_column}`)
253
- - **Model**: `{model}`
254
- - **Format**: `{output_format}`
255
- - **Output column**: `{output_column}`
256
- - **Valid {output_format.upper()}**: {n_valid}/{len(all_outputs)}
257
- - **Date**: {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}
258
-
259
- Generated with the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) `lfm2-extract.py` script.
260
- """
261
- try:
262
- DatasetCard(card_text).push_to_hub(output_dataset, token=HF_TOKEN)
263
- except Exception as e:
264
- logger.warning(f"Could not push dataset card: {e}")
265
-
266
- logger.info("Done! Extraction complete.")
267
- logger.info(f"Dataset: https://huggingface.co/datasets/{output_dataset}")
268
-
269
-
270
- if __name__ == "__main__":
271
- if len(sys.argv) == 1:
272
- print("LFM2-1.2B-Extract — structured extraction (JSON/XML/YAML) from text")
273
- print("\nUsage:")
274
- print(" uv run --with vllm==0.29.0 lfm2-extract.py INPUT OUTPUT --schema SCHEMA [--text-column text] [--format json]")
275
- print("\nExample:")
276
- print(' uv run --with vllm==0.29.0 lfm2-extract.py my-docs my-fields \\')
277
- print(' --text-column markdown \\')
278
- print(' --schema \'{"title": "the title", "date": "any date", "summary": "one sentence"}\'')
279
- print("\n --schema accepts inline text/JSON, a URL, or a file path.")
280
- print("\nOn HF Jobs (hf CLI 1.32+; image/flavor/secrets come from the script header):")
281
- print(" hf jobs uv run lfm2-extract.py INPUT OUTPUT --schema SCHEMA")
282
- print("\nFor full help: uv run --with vllm==0.29.0 lfm2-extract.py --help")
283
- sys.exit(0)
284
-
285
- parser = argparse.ArgumentParser(
286
- description="Structured extraction (JSON/XML/YAML) from text using LFM2-1.2B-Extract",
287
- )
288
- parser.add_argument("input_dataset", help="Input dataset ID (with a text column)")
289
- parser.add_argument("output_dataset", help="Output dataset ID")
290
- parser.add_argument(
291
- "--schema", required=True,
292
- help="Structure to extract: inline text/JSON, a URL, or a file path",
293
- )
294
- parser.add_argument("--text-column", default="text", help="Text column (default: text)")
295
- parser.add_argument("--output-column", default="extraction", help="Output column (default: extraction)")
296
- parser.add_argument(
297
- "--overwrite",
298
- action="store_true",
299
- help="Replace the output column if it already exists in the input dataset "
300
- "(default: error out to avoid clobbering an existing column).",
301
- )
302
- parser.add_argument(
303
- "--format", dest="output_format", default="json", choices=list(FORMATS),
304
- help="Output format (default: json)",
305
- )
306
- parser.add_argument("--split", default="train", help="Dataset split (default: train)")
307
- parser.add_argument("--max-samples", type=int, help="Limit number of samples")
308
- parser.add_argument("--shuffle", action="store_true", help="Shuffle before sampling")
309
- parser.add_argument("--seed", type=int, default=42, help="Shuffle seed (default: 42)")
310
- parser.add_argument("--batch-size", type=int, default=32, help="Batch size (default: 32)")
311
- parser.add_argument("--model", default=DEFAULT_MODEL, help=f"Model (default: {DEFAULT_MODEL})")
312
- parser.add_argument("--max-model-len", type=int, default=8192, help="Max context length (default: 8192)")
313
- parser.add_argument("--max-tokens", type=int, default=4096, help="Max output tokens (default: 4096)")
314
- parser.add_argument("--private", action="store_true", help="Make output dataset private")
315
- parser.add_argument("--hf-token", help="HF token (or set HF_TOKEN)")
316
- args = parser.parse_args()
317
-
318
- main(
319
- input_dataset=args.input_dataset,
320
- output_dataset=args.output_dataset,
321
- schema=args.schema,
322
- text_column=args.text_column,
323
- output_column=args.output_column,
324
- overwrite=args.overwrite,
325
- output_format=args.output_format,
326
- split=args.split,
327
- max_samples=args.max_samples,
328
- shuffle=args.shuffle,
329
- seed=args.seed,
330
- batch_size=args.batch_size,
331
- model=args.model,
332
- max_model_len=args.max_model_len,
333
- max_tokens=args.max_tokens,
334
- private=args.private,
335
- hf_token=args.hf_token,
336
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lfm2-vl-extract.py DELETED
@@ -1,358 +0,0 @@
1
- # /// script
2
- # requires-python = ">=3.11"
3
- # dependencies = [
4
- # "datasets>=4.0.0",
5
- # "huggingface-hub",
6
- # "pillow",
7
- # "vllm",
8
- # "transformers",
9
- # "tqdm",
10
- # "toolz",
11
- # "torch",
12
- # ]
13
- # ///
14
- """
15
- Extract structured JSON from images using LiquidAI's LFM2.5-VL-1.6B-Extract with vLLM.
16
-
17
- LFM2.5-VL-1.6B-Extract (1.6B = LFM2 1.2B LM + SigLIP2 0.4B vision) is a compact
18
- vision-language model purpose-built for *schema-guided* extraction: you give it a
19
- list of fields, it returns a flat JSON object with those fields filled from the image.
20
- It reports 99.6 JSON-validity / F1 on its benchmark, beating similarly-sized VLMs.
21
-
22
- Unlike the markdown-OCR scripts here, this one needs a SCHEMA (a field list). Pass
23
- `--schema` as inline JSON, a URL, or a file path, mapping field names to short
24
- descriptions:
25
-
26
- --schema '{"invoice_number": "the invoice number", "total": "the total amount"}'
27
-
28
- Model: https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-Extract
29
- Docs: https://docs.liquid.ai/deployment/gpu-inference/vllm
30
-
31
- HF Jobs note: run on the vLLM image so the CUDA toolkit + prebuilt FlashInfer kernels
32
- are present and startup is fast (it reuses the image's CUDA-matched vLLM build):
33
-
34
- hf jobs uv run --flavor l4x1 --secrets HF_TOKEN \
35
- --image vllm/vllm-openai --python /usr/bin/python3 \
36
- -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \
37
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lfm2-vl-extract.py \
38
- INPUT OUTPUT --schema '{"title": "the document title", "date": "any date shown"}'
39
-
40
- It also runs on the default uv image, just with a slower first-time vLLM build. Deps are
41
- left unpinned so uv resolves a vLLM that supports the LFM2-VL (transformers 5) architecture,
42
- and FlashInfer sampling is disabled (VLLM_USE_FLASHINFER_SAMPLER=0, see below) so the engine
43
- never JIT-compiles a kernel that needs nvcc — absent from the default image.
44
- """
45
-
46
- import argparse
47
- import base64
48
- import io
49
- import json
50
- import logging
51
- import os
52
- import sys
53
- from datetime import datetime, timezone
54
- from typing import Any, Dict, List, Optional, Union
55
- from urllib.request import urlopen
56
-
57
- # Disable vLLM's FlashInfer top-k/top-p sampler before the engine starts: it JIT-compiles
58
- # at warmup and needs nvcc (absent from the default uv image). Harmless for greedy decoding.
59
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
60
-
61
- import torch
62
- from datasets import load_dataset
63
- from huggingface_hub import DatasetCard, login
64
- from PIL import Image
65
- from toolz import partition_all
66
- from tqdm import tqdm
67
- from vllm import LLM, SamplingParams
68
-
69
- logging.basicConfig(level=logging.INFO)
70
- logger = logging.getLogger(__name__)
71
-
72
- DEFAULT_MODEL = "LiquidAI/LFM2.5-VL-1.6B-Extract"
73
-
74
-
75
- def check_cuda_availability() -> None:
76
- if not torch.cuda.is_available():
77
- logger.error("CUDA is not available. This script requires a GPU.")
78
- logger.error("Run on Hugging Face Jobs with: hf jobs uv run --flavor l4x1 ...")
79
- sys.exit(1)
80
- logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name()}")
81
-
82
-
83
- def ensure_output_columns_free(dataset, columns, overwrite=False):
84
- """Fail fast if an output column would collide with an existing input column.
85
-
86
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
87
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
88
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
89
- column(s) here instead (logged) so the later add_column is clean.
90
- """
91
- clash = [c for c in columns if c in dataset.column_names]
92
- if not clash:
93
- return dataset
94
- if overwrite:
95
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
96
- return dataset.remove_columns(clash)
97
- logger.error(
98
- f"Output column(s) {clash} already exist in the input dataset "
99
- f"(columns: {dataset.column_names})."
100
- )
101
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
102
- sys.exit(1)
103
-
104
-
105
- def load_schema_arg(value: str) -> Dict[str, str]:
106
- """Resolve --schema (inline JSON, URL, or file path) into a {field: description} dict."""
107
- text = value.strip()
108
- if text.startswith("http://") or text.startswith("https://"):
109
- logger.info(f"Loading schema from URL: {text}")
110
- text = urlopen(text).read().decode("utf-8")
111
- elif not text.startswith("{") and not text.startswith("["):
112
- if os.path.exists(text):
113
- logger.info(f"Loading schema from file: {text}")
114
- with open(text) as f:
115
- text = f.read()
116
- parsed = json.loads(text)
117
- # Accept {"field": "description"} or ["field1", "field2"]
118
- if isinstance(parsed, list):
119
- return {str(field): "" for field in parsed}
120
- if isinstance(parsed, dict):
121
- return {str(k): str(v) for k, v in parsed.items()}
122
- raise ValueError("--schema must be a JSON object {field: description} or a JSON list of field names.")
123
-
124
-
125
- def build_system_prompt(schema: Dict[str, str]) -> str:
126
- """LFM2.5-VL-Extract prompt: a field list in the system message → flat JSON out."""
127
- lines = []
128
- for field, desc in schema.items():
129
- lines.append(f"{field}: {desc}" if desc else field)
130
- fields_block = "\n".join(lines)
131
- return (
132
- f"Extract the following from the image:\n\n{fields_block}\n\n"
133
- "Respond with only a JSON object."
134
- )
135
-
136
-
137
- def image_to_data_uri(image: Union[Image.Image, Dict[str, Any], str]) -> str:
138
- if isinstance(image, dict) and "bytes" in image:
139
- image = Image.open(io.BytesIO(image["bytes"]))
140
- elif isinstance(image, str):
141
- image = Image.open(image)
142
- if image.mode != "RGB":
143
- image = image.convert("RGB")
144
- buf = io.BytesIO()
145
- image.save(buf, format="PNG")
146
- return f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
147
-
148
-
149
- def make_message(image: Any, system_prompt: str) -> List[Dict]:
150
- data_uri = image_to_data_uri(image)
151
- return [
152
- {"role": "system", "content": system_prompt},
153
- {"role": "user", "content": [{"type": "image_url", "image_url": {"url": data_uri}}]},
154
- ]
155
-
156
-
157
- def parse_json_output(text: str) -> tuple[Optional[Any], bool]:
158
- """Return (parsed, ok). Strips ```json fences if present."""
159
- stripped = text.strip()
160
- if stripped.startswith("```"):
161
- stripped = stripped.split("\n", 1)[-1]
162
- if stripped.endswith("```"):
163
- stripped = stripped.rsplit("```", 1)[0]
164
- stripped = stripped.strip()
165
- try:
166
- return json.loads(stripped), True
167
- except (json.JSONDecodeError, ValueError):
168
- return None, False
169
-
170
-
171
- def main(
172
- input_dataset: str,
173
- output_dataset: str,
174
- schema: str,
175
- image_column: str = "image",
176
- output_column: str = "extraction",
177
- overwrite: bool = False,
178
- split: str = "train",
179
- max_samples: Optional[int] = None,
180
- shuffle: bool = False,
181
- seed: int = 42,
182
- batch_size: int = 16,
183
- model: str = DEFAULT_MODEL,
184
- max_model_len: int = 4096,
185
- max_tokens: int = 1024,
186
- private: bool = False,
187
- hf_token: Optional[str] = None,
188
- ) -> None:
189
- check_cuda_availability()
190
-
191
- HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
192
- if HF_TOKEN:
193
- login(token=HF_TOKEN)
194
-
195
- schema_dict = load_schema_arg(schema)
196
- system_prompt = build_system_prompt(schema_dict)
197
- logger.info(f"Extraction fields: {list(schema_dict.keys())}")
198
-
199
- logger.info(f"Loading dataset: {input_dataset} (split={split})")
200
- dataset = load_dataset(input_dataset, split=split)
201
-
202
- # Fail fast if the output column would collide with an existing input column
203
- dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
204
-
205
- if shuffle:
206
- dataset = dataset.shuffle(seed=seed)
207
- if max_samples:
208
- dataset = dataset.select(range(min(max_samples, len(dataset))))
209
- logger.info(f"Processing {len(dataset)} examples")
210
-
211
- if image_column not in dataset.column_names:
212
- logger.error(f"Image column '{image_column}' not found. Columns: {dataset.column_names}")
213
- sys.exit(1)
214
-
215
- logger.info(f"Loading model: {model}")
216
- llm = LLM(
217
- model=model,
218
- max_model_len=max_model_len,
219
- limit_mm_per_prompt={"image": 1},
220
- enforce_eager=True,
221
- )
222
- sampling_params = SamplingParams(temperature=0.0, max_tokens=max_tokens)
223
-
224
- all_outputs: List[str] = []
225
- n_valid = 0
226
- images = dataset[image_column]
227
- for batch in tqdm(list(partition_all(batch_size, images)), desc="Extracting"):
228
- batch_messages = [make_message(img, system_prompt) for img in batch]
229
- outputs = llm.chat(batch_messages, sampling_params)
230
- for out in outputs:
231
- text = out.outputs[0].text.strip()
232
- parsed, ok = parse_json_output(text)
233
- if ok:
234
- n_valid += 1
235
- all_outputs.append(json.dumps(parsed, ensure_ascii=False))
236
- else:
237
- all_outputs.append(text) # keep raw on parse failure
238
-
239
- logger.info(f"Valid JSON: {n_valid}/{len(all_outputs)}")
240
-
241
- dataset = dataset.add_column(output_column, all_outputs)
242
-
243
- inference_entry = {
244
- "model": model,
245
- "column_name": output_column,
246
- "task": "schema-guided extraction",
247
- "fields": list(schema_dict.keys()),
248
- "timestamp": datetime.now(timezone.utc).isoformat(),
249
- "script": "lfm2-vl-extract.py",
250
- }
251
- if "inference_info" in dataset.column_names:
252
- def update_info(example):
253
- try:
254
- existing = json.loads(example["inference_info"]) if example["inference_info"] else []
255
- except (json.JSONDecodeError, TypeError):
256
- existing = []
257
- existing.append(inference_entry)
258
- return {"inference_info": json.dumps(existing)}
259
- dataset = dataset.map(update_info)
260
- else:
261
- dataset = dataset.add_column(
262
- "inference_info", [json.dumps([inference_entry])] * len(dataset)
263
- )
264
-
265
- logger.info(f"Pushing to {output_dataset}")
266
- dataset.push_to_hub(output_dataset, private=private, token=HF_TOKEN)
267
-
268
- card_text = f"""---
269
- tags:
270
- - uv-script
271
- - extraction
272
- - lfm2-vl
273
- - json
274
- ---
275
-
276
- # Structured extraction with LFM2.5-VL-1.6B-Extract
277
-
278
- JSON fields extracted from images in [{input_dataset}](https://huggingface.co/datasets/{input_dataset})
279
- using [{model}](https://huggingface.co/{model}).
280
-
281
- - **Source**: `{input_dataset}` (split `{split}`)
282
- - **Model**: `{model}`
283
- - **Fields**: {", ".join(f"`{k}`" for k in schema_dict.keys())}
284
- - **Output column**: `{output_column}` (JSON string per row)
285
- - **Valid JSON**: {n_valid}/{len(all_outputs)}
286
- - **Date**: {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}
287
-
288
- Generated with the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) `lfm2-vl-extract.py` script.
289
- """
290
- try:
291
- card = DatasetCard(card_text)
292
- card.push_to_hub(output_dataset, token=HF_TOKEN)
293
- except Exception as e:
294
- logger.warning(f"Could not push dataset card: {e}")
295
-
296
- logger.info("Done! Extraction complete.")
297
- logger.info(f"Dataset: https://huggingface.co/datasets/{output_dataset}")
298
-
299
-
300
- if __name__ == "__main__":
301
- if len(sys.argv) == 1:
302
- print("LFM2.5-VL-1.6B-Extract — schema-guided JSON extraction from images")
303
- print("\nUsage:")
304
- print(" uv run lfm2-vl-extract.py INPUT OUTPUT --schema SCHEMA [options]")
305
- print("\nExample:")
306
- print(' uv run lfm2-vl-extract.py my-images my-extractions \\')
307
- print(' --schema \'{"title": "the document title", "date": "any date shown"}\'')
308
- print("\n --schema accepts inline JSON, a URL, or a file path.")
309
- print("\nFor full help: uv run lfm2-vl-extract.py --help")
310
- sys.exit(0)
311
-
312
- parser = argparse.ArgumentParser(
313
- description="Schema-guided JSON extraction from images using LFM2.5-VL-1.6B-Extract",
314
- )
315
- parser.add_argument("input_dataset", help="Input dataset ID (with images)")
316
- parser.add_argument("output_dataset", help="Output dataset ID")
317
- parser.add_argument(
318
- "--schema", required=True,
319
- help="Fields to extract: inline JSON {field: description}, a URL, or a file path",
320
- )
321
- parser.add_argument("--image-column", default="image", help="Image column (default: image)")
322
- parser.add_argument("--output-column", default="extraction", help="Output column (default: extraction)")
323
- parser.add_argument(
324
- "--overwrite",
325
- action="store_true",
326
- help="Replace the output column if it already exists in the input dataset "
327
- "(default: error out to avoid clobbering an existing column).",
328
- )
329
- parser.add_argument("--split", default="train", help="Dataset split (default: train)")
330
- parser.add_argument("--max-samples", type=int, help="Limit number of samples")
331
- parser.add_argument("--shuffle", action="store_true", help="Shuffle before sampling")
332
- parser.add_argument("--seed", type=int, default=42, help="Shuffle seed (default: 42)")
333
- parser.add_argument("--batch-size", type=int, default=16, help="Batch size (default: 16)")
334
- parser.add_argument("--model", default=DEFAULT_MODEL, help=f"Model (default: {DEFAULT_MODEL})")
335
- parser.add_argument("--max-model-len", type=int, default=4096, help="Max context length (default: 4096)")
336
- parser.add_argument("--max-tokens", type=int, default=1024, help="Max output tokens (default: 1024)")
337
- parser.add_argument("--private", action="store_true", help="Make output dataset private")
338
- parser.add_argument("--hf-token", help="HF token (or set HF_TOKEN)")
339
- args = parser.parse_args()
340
-
341
- main(
342
- input_dataset=args.input_dataset,
343
- output_dataset=args.output_dataset,
344
- schema=args.schema,
345
- image_column=args.image_column,
346
- output_column=args.output_column,
347
- overwrite=args.overwrite,
348
- split=args.split,
349
- max_samples=args.max_samples,
350
- shuffle=args.shuffle,
351
- seed=args.seed,
352
- batch_size=args.batch_size,
353
- model=args.model,
354
- max_model_len=args.max_model_len,
355
- max_tokens=args.max_tokens,
356
- private=args.private,
357
- hf_token=args.hf_token,
358
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lift-extract.py DELETED
@@ -1,855 +0,0 @@
1
- # /// script
2
- # requires-python = ">=3.12"
3
- # dependencies = [
4
- # "lift-pdf[hf]",
5
- # "datasets>=3.1.0",
6
- # "huggingface-hub",
7
- # "pillow",
8
- # "toolz",
9
- # "tqdm",
10
- # ]
11
- #
12
- # [tool.hf-jobs]
13
- # flavor = "a100-large"
14
- # secrets = ["HF_TOKEN"]
15
- # ///
16
- """
17
- Extract structured JSON from document images OR multi-page PDFs using Datalab's
18
- `lift` model (`datalab-to/lift`, 9B, Qwen3.5-based).
19
-
20
- Unlike the markdown-OCR scripts here, lift does *schema-constrained* extraction:
21
- you give it a JSON Schema, it returns a JSON object matching that schema. It
22
- natively handles multi-page documents — a whole PDF is collapsed into a single
23
- extraction.
24
-
25
- Two in-process backends, selected with `--method` (no server, single command):
26
-
27
- --method hf (default) Transformers via the `lift-pdf` package. Runs on the
28
- default uv image. Simplest path; best for small jobs.
29
- --method vllm vLLM's offline `LLM()` engine (`llm.chat`) with
30
- structured-output decoding — the fast batched path the
31
- other vLLM OCR scripts here use. Needs the
32
- `vllm/vllm-openai` image (which ships vLLM). Reproduces
33
- lift's own prompt + guided-JSON recipe against the
34
- offline engine. Wins on large jobs via continuous batching.
35
-
36
- Benchmark the two by pushing each to one repo with `--config hf` / `--config vllm`.
37
-
38
- Input is one document per row:
39
- --image-column COL (default `image`) one image per row -> one extraction
40
- --pdf-column COL PDF bytes per row -> one extraction
41
- (multi-page; respects --page-range)
42
-
43
- Pass `--schema` as inline JSON, a URL, or a file path (standard JSON Schema):
44
-
45
- --schema '{"type":"object","properties":{"invoice_number":{"type":"string"},
46
- "total":{"type":"number"}},"required":["invoice_number"]}'
47
-
48
- LICENSE NOTE: lift's *code* is Apache-2.0 but the *weights* are a modified
49
- OpenRAIL-M license — free for research, personal use, and startups under $5M
50
- funding/revenue, but restricted from competitive use against Datalab's API.
51
- Confirm you are within those terms before using it. https://huggingface.co/datalab-to/lift
52
-
53
- HF Jobs — HF backend. The [tool.hf-jobs] header above sets the flavor
54
- (a100-large; 9B needs a roomy GPU) and the HF_TOKEN secret, so no flags are
55
- needed (requires `hf` CLI 1.32+):
56
-
57
- hf jobs uv run \\
58
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lift-extract.py \\
59
- INPUT_DATASET OUTPUT_DATASET \\
60
- --schema '{"type":"object","properties":{"title":{"type":"string"}}}' \\
61
- --max-samples 5 --shuffle --seed 42
62
-
63
- HF Jobs — vLLM offline backend (use the vllm image so vLLM is present). The
64
- header does not cover this path: pass the image flags explicitly. This path is
65
- not tested with the header; treat it as unsupported for now:
66
-
67
- hf jobs uv run --flavor a100-large -s HF_TOKEN \\
68
- --image vllm/vllm-openai --python /usr/bin/python3 \\
69
- -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\
70
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lift-extract.py \\
71
- INPUT_DATASET OUTPUT_DATASET --method vllm \\
72
- --schema '{"type":"object","properties":{"title":{"type":"string"}}}' \\
73
- --max-samples 5
74
-
75
- Model: datalab-to/lift (package: lift-pdf, https://github.com/datalab-to/lift)
76
- """
77
-
78
- import argparse
79
- import base64
80
- import io
81
- import json
82
- import logging
83
- import os
84
- import sys
85
- import tempfile
86
- import time
87
- from datetime import datetime, timezone
88
- from typing import Any, Dict, List, Optional, Tuple
89
- from urllib.request import urlopen
90
-
91
- from datasets import load_dataset
92
- from huggingface_hub import DatasetCard, login
93
- from PIL import Image
94
- from toolz import partition_all
95
- from tqdm import tqdm
96
-
97
- logging.basicConfig(level=logging.INFO)
98
- logger = logging.getLogger(__name__)
99
-
100
- # The package default checkpoint drifts between releases (e.g. "datalab-to/lift-extract");
101
- # pin to the canonical card repo so the script is stable across lift-pdf versions.
102
- DEFAULT_MODEL = "datalab-to/lift"
103
- DEFAULT_MAX_TOKENS = 12384 # lift-pdf's own MAX_OUTPUT_TOKENS default
104
-
105
- # A processed document: (parsed JSON or None, error flag, raw model text).
106
- DocResult = Tuple[Optional[Any], bool, str]
107
-
108
-
109
- def check_cuda_availability() -> None:
110
- """Exit early with a clear message if there's no GPU."""
111
- import torch
112
-
113
- if not torch.cuda.is_available():
114
- logger.error("CUDA is not available. This script requires a GPU.")
115
- logger.error(
116
- "Run on Hugging Face Jobs with: hf jobs uv run lift-extract.py ... "
117
- "(the script header sets flavor a100-large; hf CLI 1.32+)"
118
- )
119
- sys.exit(1)
120
- logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
121
-
122
-
123
- def ensure_output_columns_free(dataset, columns, overwrite=False):
124
- """Fail fast if an output column would collide with an existing input column.
125
-
126
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
127
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
128
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
129
- column(s) here instead (logged) so the later add_column is clean.
130
- """
131
- clash = [c for c in columns if c in dataset.column_names]
132
- if not clash:
133
- return dataset
134
- if overwrite:
135
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
136
- return dataset.remove_columns(clash)
137
- logger.error(
138
- f"Output column(s) {clash} already exist in the input dataset "
139
- f"(columns: {dataset.column_names})."
140
- )
141
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
142
- sys.exit(1)
143
-
144
-
145
- def load_schema_arg(value: str) -> Dict[str, Any]:
146
- """Resolve --schema (inline JSON, a URL, or a file path) into a JSON Schema dict."""
147
- text = value.strip()
148
- if text.startswith(("http://", "https://")):
149
- logger.info(f"Loading schema from URL: {text}")
150
- text = urlopen(text).read().decode("utf-8") # noqa: S310
151
- elif not text.startswith("{"):
152
- # Looks like a path (inline JSON would start with "{"); read it if it exists.
153
- if os.path.isfile(text):
154
- logger.info(f"Loading schema from file: {text}")
155
- with open(text) as f:
156
- text = f.read()
157
- try:
158
- parsed = json.loads(text)
159
- except json.JSONDecodeError as e:
160
- raise ValueError(
161
- f"Could not parse --schema as JSON (tried URL/path/inline): {e}"
162
- ) from e
163
- if not isinstance(parsed, dict):
164
- raise ValueError("--schema must be a JSON object (a JSON Schema).")
165
- return parsed
166
-
167
-
168
- def cell_to_bytes(cell: Any) -> bytes:
169
- """Normalize an HF dataset cell (image or document) to raw file bytes.
170
-
171
- Handles decoded PIL images (Image feature), {"bytes"/"path"} dicts, raw bytes
172
- (e.g. a binary PDF column), and string paths/URLs.
173
- """
174
- if isinstance(cell, Image.Image):
175
- buf = io.BytesIO()
176
- cell.convert("RGB").save(buf, format="PNG")
177
- return buf.getvalue()
178
- if isinstance(cell, dict):
179
- if cell.get("bytes"):
180
- return cell["bytes"]
181
- if cell.get("path"):
182
- with open(cell["path"], "rb") as f:
183
- return f.read()
184
- raise ValueError(
185
- f"Unsupported image/document dict (no bytes/path): {list(cell)}"
186
- )
187
- if isinstance(cell, (bytes, bytearray)):
188
- return bytes(cell)
189
- if isinstance(cell, str):
190
- if cell.startswith(("http://", "https://")):
191
- return urlopen(cell).read() # noqa: S310
192
- with open(cell, "rb") as f:
193
- return f.read()
194
- raise ValueError(f"Unsupported cell type: {type(cell)}")
195
-
196
-
197
- def load_document_images(
198
- load_file, cell: Any, page_range: Optional[str]
199
- ) -> List[Image.Image]:
200
- """Render one dataset cell into the page images lift expects.
201
-
202
- Reuses lift's own `load_file`, which auto-detects PDF vs image by content
203
- (pypdfium2 for PDFs, with the model's DPI/min-dim and page-range handling).
204
- """
205
- data = cell_to_bytes(cell)
206
- # load_file detects type from content, so the temp file needs no extension.
207
- with tempfile.NamedTemporaryFile(delete=False) as tmp:
208
- tmp.write(data)
209
- path = tmp.name
210
- try:
211
- config = {"page_range": page_range} if page_range else {}
212
- return load_file(path, config)
213
- finally:
214
- os.unlink(path)
215
-
216
-
217
- def pil_to_data_uri(img: Image.Image) -> str:
218
- """PNG data URI for an OpenAI-format image content block."""
219
- if img.mode != "RGB":
220
- img = img.convert("RGB")
221
- buf = io.BytesIO()
222
- img.save(buf, format="PNG")
223
- return f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
224
-
225
-
226
- def parse_json_output(text: str) -> Tuple[Optional[Any], bool]:
227
- """Return (parsed, ok). Strips ```json fences if present."""
228
- stripped = text.strip()
229
- if stripped.startswith("```"):
230
- stripped = stripped.split("\n", 1)[-1] if "\n" in stripped else stripped[3:]
231
- if stripped.endswith("```"):
232
- stripped = stripped[:-3].rstrip()
233
- try:
234
- return json.loads(stripped), True
235
- except (json.JSONDecodeError, ValueError):
236
- return None, False
237
-
238
-
239
- # --- HF backend (lift-pdf package, in-process Transformers) ---
240
- def make_hf_processor(schema: Dict[str, Any], max_tokens: Optional[int]):
241
- """Load lift via the package's HF backend; return a batch-processing closure."""
242
- from lift.model import InferenceManager
243
- from lift.model.schema import BatchInputItem
244
-
245
- logger.info("Loading lift via Transformers (method=hf)...")
246
- manager = InferenceManager(method="hf")
247
-
248
- def process(image_lists: List[List[Image.Image]]) -> List[DocResult]:
249
- items = [
250
- BatchInputItem(images=imgs, schema=schema, prompt_type="direct")
251
- for imgs in image_lists
252
- ]
253
- results = manager.generate(items, max_output_tokens=max_tokens)
254
- return [(r.extraction, bool(r.error), r.raw) for r in results]
255
-
256
- return process
257
-
258
-
259
- # --- vLLM backend (offline LLM() engine + structured outputs) ---
260
- def build_guided_schema(schema: Dict[str, Any]) -> Dict[str, Any]:
261
- """Reproduce lift's vLLM guided-decoding schema: JSON Schema -> pydantic ->
262
- json_schema with every leaf made nullable (so absent fields can be null,
263
- matching lift's own server-side behavior)."""
264
- from json_schema_to_pydantic import create_model
265
- from lift.model.vllm import make_properties_nullable
266
-
267
- schema_model = create_model(schema)
268
- json_schema = schema_model.model_json_schema()
269
- make_properties_nullable(json_schema)
270
- return json_schema
271
-
272
-
273
- def make_sampling_params(json_schema: Dict[str, Any], max_tokens: int):
274
- """SamplingParams with structured JSON output, across vLLM API versions.
275
-
276
- lift uses greedy-ish decoding (temperature 0.0, top_p 0.1).
277
- """
278
- from vllm import SamplingParams
279
-
280
- # vLLM >= 0.12
281
- try:
282
- from vllm.sampling_params import StructuredOutputsParams
283
-
284
- return SamplingParams(
285
- temperature=0.0,
286
- top_p=0.1,
287
- max_tokens=max_tokens,
288
- structured_outputs=StructuredOutputsParams(json=json_schema),
289
- )
290
- except (ImportError, TypeError):
291
- pass
292
- # Older vLLM
293
- try:
294
- from vllm.sampling_params import GuidedDecodingParams
295
-
296
- return SamplingParams(
297
- temperature=0.0,
298
- top_p=0.1,
299
- max_tokens=max_tokens,
300
- guided_decoding=GuidedDecodingParams(json=json_schema),
301
- )
302
- except (ImportError, TypeError):
303
- pass
304
- logger.warning(
305
- "Structured output unavailable in this vLLM version; relying on lift's "
306
- "training to emit valid JSON."
307
- )
308
- return SamplingParams(temperature=0.0, top_p=0.1, max_tokens=max_tokens)
309
-
310
-
311
- def make_vllm_processor(
312
- schema: Dict[str, Any],
313
- model: str,
314
- max_tokens: Optional[int],
315
- max_model_len: int,
316
- gpu_memory_utilization: float,
317
- max_images_per_doc: int,
318
- ):
319
- """Load lift into vLLM's offline engine; return a batch-processing closure."""
320
- try:
321
- from vllm import LLM
322
- except ImportError as e:
323
- raise RuntimeError(
324
- "--method vllm needs vLLM. Run on the vllm/vllm-openai image: "
325
- "--image vllm/vllm-openai --python /usr/bin/python3 "
326
- "-e PYTHONPATH=/usr/local/lib/python3.12/dist-packages"
327
- ) from e
328
- from lift.model.util import scale_to_fit
329
- from lift.prompts import PROMPT_MAPPING
330
-
331
- json_schema = build_guided_schema(schema)
332
- prompt = PROMPT_MAPPING["direct"].replace("{schema}", json.dumps(schema, indent=2))
333
-
334
- logger.info("Loading lift via vLLM offline engine (method=vllm)...")
335
- llm = LLM(
336
- model=model,
337
- trust_remote_code=True,
338
- max_model_len=max_model_len,
339
- gpu_memory_utilization=gpu_memory_utilization,
340
- limit_mm_per_prompt={"image": max_images_per_doc},
341
- # lift's own server-side image bounds, applied by the offline processor too.
342
- mm_processor_kwargs={"min_pixels": 3136, "max_pixels": 861696},
343
- )
344
- sampling_params = make_sampling_params(
345
- json_schema, max_tokens or DEFAULT_MAX_TOKENS
346
- )
347
-
348
- def process(image_lists: List[List[Image.Image]]) -> List[DocResult]:
349
- messages = []
350
- for imgs in image_lists:
351
- content = [
352
- {
353
- "type": "image_url",
354
- "image_url": {"url": pil_to_data_uri(scale_to_fit(img))},
355
- }
356
- for img in imgs
357
- ]
358
- content.append({"type": "text", "text": prompt})
359
- messages.append([{"role": "user", "content": content}])
360
- outputs = llm.chat(
361
- messages, sampling_params, chat_template_content_format="openai"
362
- )
363
- results: List[DocResult] = []
364
- for o in outputs:
365
- raw = o.outputs[0].text
366
- parsed, ok = parse_json_output(raw)
367
- results.append((parsed if ok else None, not ok, raw))
368
- return results
369
-
370
- return process
371
-
372
-
373
- def create_dataset_card(
374
- source_dataset: str,
375
- model: str,
376
- method: str,
377
- schema: Dict[str, Any],
378
- num_samples: int,
379
- n_valid: int,
380
- source_column: str,
381
- is_pdf: bool,
382
- page_range: Optional[str],
383
- output_column: str,
384
- split: str,
385
- processing_time: str,
386
- ) -> str:
387
- """Build the output dataset card documenting the lift run."""
388
- schema_block = json.dumps(schema, indent=2)
389
- input_kind = "PDF documents" if is_pdf else "images"
390
- col_desc = "PDF" if is_pdf else "image"
391
- if page_range:
392
- col_desc += f", pages {page_range}"
393
- backend_desc = (
394
- "vLLM offline engine" if method == "vllm" else "Transformers (lift-pdf)"
395
- )
396
- return f"""---
397
- tags:
398
- - ocr
399
- - structured-extraction
400
- - document-processing
401
- - lift
402
- - json
403
- - uv-script
404
- - generated
405
- ---
406
-
407
- # lift structured extraction on {source_dataset}
408
-
409
- Schema-constrained JSON extracted from {input_kind} in
410
- [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using
411
- [lift](https://huggingface.co/{model}) (9B, Qwen3.5-based) by Datalab, via the
412
- [`lift-pdf`](https://github.com/datalab-to/lift) package.
413
-
414
- ## Processing Details
415
-
416
- - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
417
- - **Model**: [{model}](https://huggingface.co/{model})
418
- - **Backend**: `{method}` ({backend_desc})
419
- - **Input column**: `{source_column}` ({col_desc})
420
- - **Output column**: `{output_column}` (JSON string per row)
421
- - **Split**: `{split}`
422
- - **Samples**: {num_samples:,}
423
- - **Valid JSON**: {n_valid:,} / {num_samples:,}
424
- - **Processing time**: {processing_time}
425
- - **Date**: {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}
426
-
427
- ### Extraction Schema
428
-
429
- ```json
430
- {schema_block}
431
- ```
432
-
433
- ## License note
434
-
435
- lift's code is Apache-2.0, but the model **weights** use a modified OpenRAIL-M
436
- license: free for research, personal use, and startups under $5M funding/revenue,
437
- restricted from competitive use against Datalab's API. See the
438
- [model card](https://huggingface.co/{model}).
439
-
440
- ## Dataset Structure
441
-
442
- Original columns plus:
443
- - `{output_column}`: lift output (JSON string; raw text kept on parse failure)
444
- - `inference_info`: JSON list tracking models applied to this dataset
445
-
446
- Generated with [UV Scripts](https://huggingface.co/uv-scripts).
447
- """
448
-
449
-
450
- def main(
451
- input_dataset: str,
452
- output_dataset: str,
453
- schema_arg: str,
454
- image_column: str = "image",
455
- pdf_column: Optional[str] = None,
456
- output_column: str = "extraction",
457
- overwrite: bool = False,
458
- method: str = "hf",
459
- page_range: Optional[str] = None,
460
- split: str = "train",
461
- max_samples: Optional[int] = None,
462
- shuffle: bool = False,
463
- seed: int = 42,
464
- batch_size: int = 8,
465
- max_tokens: Optional[int] = None,
466
- max_model_len: int = 32768,
467
- gpu_memory_utilization: float = 0.9,
468
- max_images_per_doc: Optional[int] = None,
469
- model: str = DEFAULT_MODEL,
470
- private: bool = False,
471
- config: Optional[str] = None,
472
- create_pr: bool = False,
473
- hf_token: Optional[str] = None,
474
- verbose: bool = False,
475
- ) -> None:
476
- # Unlock full Xet bandwidth for the 9B (~19GB) model download (repo convention).
477
- os.environ["HF_XET_HIGH_PERFORMANCE"] = "1"
478
- check_cuda_availability()
479
- start_time = datetime.now(timezone.utc)
480
-
481
- HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
482
- if HF_TOKEN:
483
- login(token=HF_TOKEN)
484
-
485
- schema = load_schema_arg(schema_arg)
486
-
487
- # lift reads the checkpoint from env (pydantic-settings) at import time; set it first.
488
- os.environ["MODEL_CHECKPOINT"] = model
489
-
490
- # Import lift only after env is set so settings pick up the right checkpoint.
491
- from lift import resolve_schema
492
- from lift.input import load_file
493
-
494
- schema = resolve_schema(schema) # validates and normalizes
495
- fields = list(schema.get("properties", {}).keys())
496
-
497
- source_column = pdf_column or image_column
498
- is_pdf = pdf_column is not None
499
- # vLLM caps images per prompt at init; PDFs need headroom for multiple pages.
500
- if max_images_per_doc is None:
501
- max_images_per_doc = 30 if is_pdf else 1
502
-
503
- logger.info(f"Model: {model} Backend: {method}")
504
- logger.info(f"Schema top-level fields: {fields}")
505
-
506
- logger.info(f"Loading dataset: {input_dataset} (split={split})")
507
- dataset = load_dataset(input_dataset, split=split)
508
- if source_column not in dataset.column_names:
509
- logger.error(
510
- f"Column '{source_column}' not found. Available: {dataset.column_names}"
511
- )
512
- sys.exit(1)
513
-
514
- # Fail fast if the output column would collide with an existing input column
515
- dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
516
-
517
- if shuffle:
518
- dataset = dataset.shuffle(seed=seed)
519
- if max_samples:
520
- dataset = dataset.select(range(min(max_samples, len(dataset))))
521
- logger.info(f"Processing {len(dataset)} documents from column '{source_column}'")
522
-
523
- if method == "vllm":
524
- process_batch = make_vllm_processor(
525
- schema,
526
- model,
527
- max_tokens,
528
- max_model_len,
529
- gpu_memory_utilization,
530
- max_images_per_doc,
531
- )
532
- else:
533
- process_batch = make_hf_processor(schema, max_tokens)
534
-
535
- extractions: List[Optional[str]] = [None] * len(dataset)
536
- error_flags: List[bool] = [True] * len(dataset)
537
-
538
- chunks = list(partition_all(batch_size, range(len(dataset))))
539
- for chunk in tqdm(chunks, desc="Extracting"):
540
- chunk = list(chunk)
541
- rendered: Dict[int, List[Image.Image]] = {}
542
- for i in chunk:
543
- try:
544
- rendered[i] = load_document_images(
545
- load_file, dataset[i][source_column], page_range
546
- )
547
- except Exception as e:
548
- logger.warning(f"Row {i}: failed to load document: {e}")
549
- extractions[i] = f"[LIFT LOAD ERROR] {e}"
550
- error_flags[i] = True
551
- if not rendered:
552
- continue
553
-
554
- idxs = list(rendered.keys())
555
- try:
556
- results = process_batch([rendered[i] for i in idxs])
557
- except Exception as e:
558
- logger.error(f"Batch generate failed: {e}")
559
- for i in idxs:
560
- extractions[i] = "[LIFT GENERATE ERROR]"
561
- error_flags[i] = True
562
- continue
563
-
564
- for i, (parsed, err, raw) in zip(idxs, results):
565
- if parsed is not None and not err:
566
- extractions[i] = json.dumps(parsed, ensure_ascii=False)
567
- error_flags[i] = False
568
- else:
569
- extractions[i] = raw if raw else "[LIFT EMPTY OUTPUT]"
570
- error_flags[i] = True
571
-
572
- n_valid = sum(not f for f in error_flags)
573
- logger.info(f"Valid JSON: {n_valid}/{len(dataset)}")
574
-
575
- dataset = dataset.add_column(output_column, extractions)
576
-
577
- inference_entry = {
578
- "model": model,
579
- "model_name": "lift",
580
- "column_name": output_column,
581
- "task": "schema-constrained extraction",
582
- "backend": method,
583
- "fields": fields,
584
- "page_range": page_range,
585
- "parse_error_rate": (len(dataset) - n_valid) / len(dataset)
586
- if len(dataset)
587
- else 0.0,
588
- "timestamp": datetime.now(timezone.utc).isoformat(),
589
- "script": "lift-extract.py",
590
- }
591
- if "inference_info" in dataset.column_names:
592
-
593
- def update_info(example):
594
- try:
595
- existing = (
596
- json.loads(example["inference_info"])
597
- if example["inference_info"]
598
- else []
599
- )
600
- except (json.JSONDecodeError, TypeError):
601
- existing = []
602
- existing.append(inference_entry)
603
- return {"inference_info": json.dumps(existing)}
604
-
605
- dataset = dataset.map(update_info)
606
- else:
607
- dataset = dataset.add_column(
608
- "inference_info", [json.dumps([inference_entry])] * len(dataset)
609
- )
610
-
611
- processing_time = (
612
- f"{(datetime.now(timezone.utc) - start_time).total_seconds() / 60:.1f} min"
613
- )
614
-
615
- logger.info(f"Pushing to {output_dataset}")
616
- max_retries = 3
617
- for attempt in range(1, max_retries + 1):
618
- try:
619
- if attempt > 1:
620
- logger.warning("Disabling XET (fallback to HTTP upload)")
621
- os.environ["HF_HUB_DISABLE_XET"] = "1"
622
- dataset.push_to_hub(
623
- output_dataset,
624
- private=private,
625
- token=HF_TOKEN,
626
- max_shard_size="500MB",
627
- create_pr=create_pr,
628
- **({"config_name": config} if config else {}),
629
- commit_message=f"Add lift extraction results ({len(dataset)} samples)"
630
- + (f" [{config}]" if config else ""),
631
- )
632
- break
633
- except Exception as e:
634
- logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
635
- if attempt < max_retries:
636
- delay = 30 * (2 ** (attempt - 1))
637
- logger.info(f"Retrying in {delay}s...")
638
- time.sleep(delay)
639
- else:
640
- logger.error("All upload attempts failed. Results are lost.")
641
- sys.exit(1)
642
-
643
- try:
644
- card = DatasetCard(
645
- create_dataset_card(
646
- source_dataset=input_dataset,
647
- model=model,
648
- method=method,
649
- schema=schema,
650
- num_samples=len(dataset),
651
- n_valid=n_valid,
652
- source_column=source_column,
653
- is_pdf=is_pdf,
654
- page_range=page_range,
655
- output_column=output_column,
656
- split=split,
657
- processing_time=processing_time,
658
- )
659
- )
660
- card.push_to_hub(output_dataset, token=HF_TOKEN)
661
- except Exception as e:
662
- logger.warning(f"Could not push dataset card: {e}")
663
-
664
- logger.info("Done! lift extraction complete.")
665
- logger.info(f"Dataset: https://huggingface.co/datasets/{output_dataset}")
666
- logger.info(f"Processing time: {processing_time}")
667
-
668
- if verbose:
669
- import importlib.metadata
670
-
671
- logger.info("--- Resolved package versions ---")
672
- pkgs = ["lift-pdf", "transformers", "torch", "datasets", "pillow", "openai"]
673
- if method == "vllm":
674
- pkgs.append("vllm")
675
- for pkg in pkgs:
676
- try:
677
- logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
678
- except importlib.metadata.PackageNotFoundError:
679
- logger.info(f" {pkg}: not installed")
680
-
681
-
682
- if __name__ == "__main__":
683
- if len(sys.argv) == 1:
684
- print("lift — schema-constrained JSON extraction from images & PDFs (9B)")
685
- print("\nUsage:")
686
- print(" uv run lift-extract.py INPUT OUTPUT --schema SCHEMA [options]")
687
- print("\nExamples:")
688
- print(" # image column -> JSON")
689
- print(" uv run lift-extract.py my-images my-fields \\")
690
- print(
691
- ' --schema \'{"type":"object","properties":{"title":{"type":"string"}}}\''
692
- )
693
- print("\n # multi-page PDFs -> JSON (one extraction per document)")
694
- print(
695
- " uv run lift-extract.py my-pdfs my-fields --pdf-column pdf --page-range 0-5 \\"
696
- )
697
- print(" --schema schema.json")
698
- print("\n --schema accepts inline JSON, a URL, or a file path.")
699
- print(
700
- " --method hf (default) | vllm (offline LLM engine; needs the vllm image)"
701
- )
702
- print("\nFor full help: uv run lift-extract.py --help")
703
- sys.exit(0)
704
-
705
- parser = argparse.ArgumentParser(
706
- description="Schema-constrained JSON extraction from images & PDFs using datalab-to/lift",
707
- formatter_class=argparse.RawDescriptionHelpFormatter,
708
- epilog="""
709
- Backends (both in-process, single command):
710
- --method hf Transformers via lift-pdf (default). Simplest; default image.
711
- --method vllm vLLM offline LLM() engine with structured outputs. Faster on
712
- large jobs. Needs the vllm/vllm-openai image.
713
-
714
- Input (one document per row):
715
- --image-column COL one image per row (default: image)
716
- --pdf-column COL PDF bytes per row (multi-page; honors --page-range)
717
- """,
718
- )
719
- parser.add_argument(
720
- "input_dataset", help="Input dataset ID from the Hugging Face Hub"
721
- )
722
- parser.add_argument(
723
- "output_dataset", help="Output dataset ID for the Hugging Face Hub"
724
- )
725
- parser.add_argument(
726
- "--schema",
727
- required=True,
728
- help="JSON Schema: inline JSON, a URL, or a file path",
729
- )
730
- parser.add_argument(
731
- "--image-column", default="image", help="Image column (default: image)"
732
- )
733
- parser.add_argument(
734
- "--pdf-column",
735
- default=None,
736
- help="PDF column (bytes/path). Mutually exclusive with --image-column.",
737
- )
738
- parser.add_argument(
739
- "--output-column",
740
- default="extraction",
741
- help="Output column (default: extraction)",
742
- )
743
- parser.add_argument(
744
- "--overwrite",
745
- action="store_true",
746
- help="Replace the output column if it already exists in the input dataset "
747
- "(default: error out to avoid clobbering an existing column).",
748
- )
749
- parser.add_argument(
750
- "--method",
751
- choices=["hf", "vllm"],
752
- default="hf",
753
- help="Inference backend (default: hf)",
754
- )
755
- parser.add_argument(
756
- "--page-range",
757
- default=None,
758
- help="Pages to extract from PDFs, e.g. '0-5,7' (PDF column only)",
759
- )
760
- parser.add_argument(
761
- "--split", default="train", help="Dataset split (default: train)"
762
- )
763
- parser.add_argument(
764
- "--max-samples", type=int, help="Limit number of documents (for testing)"
765
- )
766
- parser.add_argument(
767
- "--shuffle", action="store_true", help="Shuffle before sampling"
768
- )
769
- parser.add_argument(
770
- "--seed", type=int, default=42, help="Shuffle seed (default: 42)"
771
- )
772
- parser.add_argument(
773
- "--batch-size",
774
- type=int,
775
- default=8,
776
- help="Documents per generate() call (default: 8; lower for big multi-page PDFs)",
777
- )
778
- parser.add_argument(
779
- "--max-tokens",
780
- type=int,
781
- default=None,
782
- help=f"Max output tokens (default: lift's {DEFAULT_MAX_TOKENS})",
783
- )
784
- parser.add_argument(
785
- "--max-model-len",
786
- type=int,
787
- default=32768,
788
- help="vLLM context length (default: 32768; raise for long multi-page PDFs)",
789
- )
790
- parser.add_argument(
791
- "--gpu-memory-utilization",
792
- type=float,
793
- default=0.9,
794
- help="vLLM GPU memory fraction (default: 0.9)",
795
- )
796
- parser.add_argument(
797
- "--max-images-per-doc",
798
- type=int,
799
- default=None,
800
- help="vLLM images-per-prompt cap (default: 1 for images, 30 for PDFs)",
801
- )
802
- parser.add_argument(
803
- "--model", default=DEFAULT_MODEL, help=f"Model ID (default: {DEFAULT_MODEL})"
804
- )
805
- parser.add_argument(
806
- "--private", action="store_true", help="Make output dataset private"
807
- )
808
- parser.add_argument(
809
- "--config",
810
- default=None,
811
- help="Config/subset name when pushing (for benchmarking backends in one repo)",
812
- )
813
- parser.add_argument(
814
- "--create-pr",
815
- action="store_true",
816
- help="Push as a pull request instead of directly (for parallel benchmarking)",
817
- )
818
- parser.add_argument("--hf-token", help="Hugging Face API token (or set HF_TOKEN)")
819
- parser.add_argument(
820
- "--verbose",
821
- action="store_true",
822
- help="Log resolved package versions after processing",
823
- )
824
-
825
- args = parser.parse_args()
826
-
827
- if args.pdf_column and args.image_column != "image":
828
- parser.error("--image-column and --pdf-column are mutually exclusive.")
829
-
830
- main(
831
- input_dataset=args.input_dataset,
832
- output_dataset=args.output_dataset,
833
- schema_arg=args.schema,
834
- image_column=args.image_column,
835
- pdf_column=args.pdf_column,
836
- output_column=args.output_column,
837
- overwrite=args.overwrite,
838
- method=args.method,
839
- page_range=args.page_range,
840
- split=args.split,
841
- max_samples=args.max_samples,
842
- shuffle=args.shuffle,
843
- seed=args.seed,
844
- batch_size=args.batch_size,
845
- max_tokens=args.max_tokens,
846
- max_model_len=args.max_model_len,
847
- gpu_memory_utilization=args.gpu_memory_utilization,
848
- max_images_per_doc=args.max_images_per_doc,
849
- model=args.model,
850
- private=args.private,
851
- config=args.config,
852
- create_pr=args.create_pr,
853
- hf_token=args.hf_token,
854
- verbose=args.verbose,
855
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lighton-ocr.py CHANGED
@@ -1,7 +1,7 @@
1
  # /// script
2
  # requires-python = ">=3.11"
3
  # dependencies = [
4
- # "datasets>=4.0.0",
5
  # "huggingface-hub",
6
  # "pillow",
7
  # "vllm",
@@ -57,10 +57,6 @@ from huggingface_hub import DatasetCard, login
57
  from PIL import Image
58
  from toolz import partition_all
59
  from tqdm.auto import tqdm
60
- # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
61
- # default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
62
- # lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
63
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
64
  from vllm import LLM, SamplingParams
65
 
66
  logging.basicConfig(level=logging.INFO)
@@ -85,28 +81,6 @@ def check_cuda_availability():
85
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
86
 
87
 
88
- def ensure_output_columns_free(dataset, columns, overwrite=False):
89
- """Fail fast if an output column would collide with an existing input column.
90
-
91
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
92
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
93
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
94
- column(s) here instead (logged) so the later add_column is clean.
95
- """
96
- clash = [c for c in columns if c in dataset.column_names]
97
- if not clash:
98
- return dataset
99
- if overwrite:
100
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
101
- return dataset.remove_columns(clash)
102
- logger.error(
103
- f"Output column(s) {clash} already exist in the input dataset "
104
- f"(columns: {dataset.column_names})."
105
- )
106
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
107
- sys.exit(1)
108
-
109
-
110
  def resize_image_to_target(image: Image.Image, target_size: int = 1540) -> Image.Image:
111
  """
112
  Resize image so longest dimension is target_size while maintaining aspect ratio.
@@ -317,7 +291,6 @@ def main(
317
  shuffle: bool = False,
318
  seed: int = 42,
319
  output_column: str = "markdown",
320
- overwrite: bool = False,
321
  ):
322
  """Process images from HF dataset through LightOnOCR model."""
323
 
@@ -350,9 +323,6 @@ def main(
350
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
351
  )
352
 
353
- # Fail fast if the output column would collide with an existing input column
354
- dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
355
-
356
  # Shuffle if requested
357
  if shuffle:
358
  logger.info(f"Shuffling dataset with seed {seed}")
@@ -651,12 +621,6 @@ Examples:
651
  default="markdown",
652
  help="Column name for output text (default: markdown)",
653
  )
654
- parser.add_argument(
655
- "--overwrite",
656
- action="store_true",
657
- help="Replace the output column if it already exists in the input dataset "
658
- "(default: error out to avoid clobbering an existing column).",
659
- )
660
 
661
  args = parser.parse_args()
662
 
@@ -680,5 +644,4 @@ Examples:
680
  shuffle=args.shuffle,
681
  seed=args.seed,
682
  output_column=args.output_column,
683
- overwrite=args.overwrite,
684
  )
 
1
  # /// script
2
  # requires-python = ">=3.11"
3
  # dependencies = [
4
+ # "datasets",
5
  # "huggingface-hub",
6
  # "pillow",
7
  # "vllm",
 
57
  from PIL import Image
58
  from toolz import partition_all
59
  from tqdm.auto import tqdm
 
 
 
 
60
  from vllm import LLM, SamplingParams
61
 
62
  logging.basicConfig(level=logging.INFO)
 
81
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
82
 
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  def resize_image_to_target(image: Image.Image, target_size: int = 1540) -> Image.Image:
85
  """
86
  Resize image so longest dimension is target_size while maintaining aspect ratio.
 
291
  shuffle: bool = False,
292
  seed: int = 42,
293
  output_column: str = "markdown",
 
294
  ):
295
  """Process images from HF dataset through LightOnOCR model."""
296
 
 
323
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
324
  )
325
 
 
 
 
326
  # Shuffle if requested
327
  if shuffle:
328
  logger.info(f"Shuffling dataset with seed {seed}")
 
621
  default="markdown",
622
  help="Column name for output text (default: markdown)",
623
  )
 
 
 
 
 
 
624
 
625
  args = parser.parse_args()
626
 
 
644
  shuffle=args.shuffle,
645
  seed=args.seed,
646
  output_column=args.output_column,
 
647
  )
lighton-ocr2-saturate.py DELETED
@@ -1,189 +0,0 @@
1
- # /// script
2
- # requires-python = ">=3.11"
3
- # dependencies = [
4
- # "saturate[hf]==0.3.0",
5
- # "pillow>=10",
6
- # ]
7
- #
8
- # [tool.hf-jobs]
9
- # image = "vllm/vllm-openai:v0.22.1"
10
- # flavor = "a10g-small"
11
- # timeout = "4h"
12
- # secrets = ["HF_TOKEN"]
13
- # ///
14
- """
15
- Convert document images to markdown using LightOnOCR-2 via saturate.
16
-
17
- Companion to `lighton-ocr2-server.py`: same model, same message shape, same
18
- sampling, same in-job `vllm serve` — but the driver half (concurrency, retries,
19
- output, resume) is the `saturate` library instead of hand-rolled code. What that
20
- buys over the -server recipe:
21
-
22
- - **Adaptive concurrency** — the window sizes itself from live engine signals
23
- (no `--concurrency` flag to tune).
24
- - **Crash-safe, resumable output** — results stream to the output repo as
25
- parquet parts while the run is hot; re-running the same command skips
26
- everything already done (exact anti-join on id). A 10k-page job that dies at
27
- 9k resumes at 9k.
28
- - **Durable error rows** — a failed page is recorded as `{id, error}` instead of
29
- an `[OCR ERROR]` string in the text column; `--retry-errors` re-admits only
30
- those rows on a later run.
31
-
32
- Run on HF Jobs. The script starts `vllm serve` itself; its [tool.hf-jobs] header
33
- declares the image that provides the `vllm` binary, the hardware and the HF_TOKEN
34
- secret (`hf` CLI 1.32+). Pass --timeout for a long run; flags override the header:
35
-
36
- hf jobs uv run --detach --timeout 4h \\
37
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr2-saturate.py \\
38
- <input-dataset> <output-dataset>
39
-
40
- Output layout (differs from the -server recipe, which pushes input+markdown):
41
- the output repo holds `data/part-*.parquet` with rows
42
- `{id, markdown, model, prompt_tokens, completion_tokens, error}` keyed by the
43
- input row id (`--id-column`, or `<split>-<index>` by default). Read it with
44
- `datasets.load_dataset(<output>, data_dir="data")` or `saturate.read_output`;
45
- join back to the input on id. Run metadata lands in `data/completions/`.
46
-
47
- Model: lightonai/LightOnOCR-2-1B (1B, Apache-2.0)
48
- - Message is the image ONLY (no text prompt) — LightOnOCR-2's trained format.
49
- - Images resized client-side so the longest dimension is 1540px (training
50
- resolution at 200 DPI), same as the offline recipe.
51
- - Sampling per the card: temperature 0.2, top_p 0.9, max_tokens 4096.
52
-
53
- The SERVING dict below is the per-model tuning prior (serve flags + client
54
- sampling + context math). Agents can `ast.literal_eval` it without running
55
- the script; the script itself consumes it, so it cannot drift from reality.
56
- """
57
-
58
- import argparse
59
- import base64
60
- import io
61
- import sys
62
-
63
- # Serving starting values for lightonai/LightOnOCR-2-1B. Per-value provenance:
64
- # - serve_args: the model card's own `vllm serve` command, verbatim (the three
65
- # cache/mm flags; OCR never reuses images, so those caches only cost memory).
66
- # - max_model_len 8192: NOT in the card's serve command (card default = native
67
- # 16384). House choice inherited from lighton-ocr2-server.py: halves the KV
68
- # allocation on 24GB and still fits a 1540px page (~2.5k image tokens) + 4096
69
- # output with headroom.
70
- # - max_tokens/temperature/top_p: card's sampling example, verbatim.
71
- # - target_size 1540: card's stated training resolution (200 DPI longest side).
72
- # Throughput receipt (a10g-small): 0.955 img/s at 1k pages incl. streaming.
73
- SERVING = {
74
- "model": "lightonai/LightOnOCR-2-1B",
75
- "image": "vllm/vllm-openai:v0.22.1",
76
- "max_model_len": 8192,
77
- "serve_args": [
78
- "--limit-mm-per-prompt", '{"image": 1}',
79
- "--mm-processor-cache-gb", "0",
80
- "--no-enable-prefix-caching",
81
- ],
82
- "max_tokens": 4096,
83
- "temperature": 0.2,
84
- "top_p": 0.9,
85
- "target_size": 1540,
86
- }
87
- assert SERVING["max_tokens"] < SERVING["max_model_len"], (
88
- "context math: max_tokens must leave room for the image tokens "
89
- "(input + output <= max_model_len, or every request 400s)"
90
- )
91
-
92
-
93
- def to_pil(value):
94
- from PIL import Image
95
-
96
- if isinstance(value, Image.Image):
97
- return value
98
- if isinstance(value, dict) and value.get("bytes"):
99
- return Image.open(io.BytesIO(value["bytes"]))
100
- if isinstance(value, (bytes, bytearray)):
101
- return Image.open(io.BytesIO(value))
102
- raise ValueError(f"unsupported image value: {type(value)}")
103
-
104
-
105
- def encode_image(value, target_size: int) -> str:
106
- """RGB-convert, resize longest dimension to target_size, return base64 PNG."""
107
- from PIL import Image
108
-
109
- img = to_pil(value).convert("RGB")
110
- if target_size:
111
- w, h = img.size
112
- if max(w, h) != target_size:
113
- scale = target_size / max(w, h)
114
- img = img.resize((round(w * scale), round(h * scale)), Image.LANCZOS)
115
- buf = io.BytesIO()
116
- img.save(buf, format="PNG")
117
- return base64.b64encode(buf.getvalue()).decode()
118
-
119
-
120
- def main():
121
- ap = argparse.ArgumentParser(description="LightOnOCR-2 batch OCR via saturate")
122
- ap.add_argument("input_dataset", help="Input dataset repo id (rows with an image column)")
123
- ap.add_argument("output_dataset", help="Output dataset repo id (created if missing)")
124
- ap.add_argument("--image-column", default="image")
125
- ap.add_argument("--config", default=None, help="Dataset config name")
126
- ap.add_argument("--split", default="train")
127
- ap.add_argument("--id-column", default=None,
128
- help="Column to use as row id (default: split-index ids)")
129
- ap.add_argument("--max-samples", "--limit", dest="limit", type=int, default=None,
130
- help="Process at most N rows (same name as the other OCR recipes; --limit still works)")
131
- ap.add_argument("--max-tokens", type=int, default=SERVING["max_tokens"])
132
- ap.add_argument("--temperature", type=float, default=SERVING["temperature"])
133
- ap.add_argument("--target-size", type=int, default=SERVING["target_size"])
134
- ap.add_argument("--no-resize", action="store_true")
135
- ap.add_argument("--retry-errors", action="store_true",
136
- help="Re-admit rows whose only record is an error row")
137
- args = ap.parse_args()
138
-
139
- import pyarrow as pa
140
- from saturate import Auto, Engine, dataset_rows, pump
141
-
142
- target_size = 0 if args.no_resize else args.target_size
143
- rows = dataset_rows(
144
- args.input_dataset, config=args.config, split=args.split,
145
- columns=[args.image_column], ids=args.id_column or "index", limit=args.limit,
146
- )
147
-
148
- def to_request(row):
149
- b64 = encode_image(row[args.image_column], target_size)
150
- return {
151
- "model": SERVING["model"],
152
- "messages": [{"role": "user", "content": [
153
- {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}},
154
- ]}],
155
- "temperature": args.temperature,
156
- "top_p": SERVING["top_p"],
157
- "max_tokens": args.max_tokens,
158
- }
159
-
160
- # Declared, so a part holding only error rows has the same columns as the rest
161
- # (datasets.load_dataset reads every part with one schema).
162
- schema = pa.schema([
163
- ("id", pa.string()), ("error", pa.string()), ("markdown", pa.string()),
164
- ("model", pa.string()), ("prompt_tokens", pa.int64()), ("completion_tokens", pa.int64()),
165
- ]) # fmt: skip
166
-
167
- def parse(row, body):
168
- usage = body.get("usage") or {}
169
- return {
170
- "markdown": body["choices"][0]["message"]["content"].strip(),
171
- "model": SERVING["model"],
172
- "prompt_tokens": usage.get("prompt_tokens"),
173
- "completion_tokens": usage.get("completion_tokens"),
174
- }
175
-
176
- extra = ["--max-model-len", str(SERVING["max_model_len"]), *SERVING["serve_args"]]
177
- output = f"hf://datasets/{args.output_dataset}/data"
178
- with Engine(SERVING["model"], engine="vllm", extra_args=extra) as endpoint:
179
- stats = pump(rows, to_request, parse, endpoint, output,
180
- window=Auto(initial=8, max_limit=48),
181
- retry_errors=args.retry_errors, schema=schema)
182
-
183
- print(f"https://huggingface.co/datasets/{args.output_dataset} "
184
- f"({stats.rows_processed} ok, {stats.rows_failed} error rows)", file=sys.stderr)
185
- print("LIGHTON_OCR2_SATURATE " + stats.to_json(), flush=True)
186
-
187
-
188
- if __name__ == "__main__":
189
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lighton-ocr2-server.py DELETED
@@ -1,720 +0,0 @@
1
- # /// script
2
- # requires-python = ">=3.11"
3
- # dependencies = [
4
- # "datasets>=4.0.0",
5
- # "huggingface-hub",
6
- # "pillow",
7
- # "requests",
8
- # ]
9
- # ///
10
-
11
- """
12
- Convert document images to markdown using LightOnOCR-2 via an in-job vLLM server.
13
-
14
- Same model, message shape, and sampling as lighton-ocr2.py, but serves the
15
- model behind `vllm serve` inside the job (the model card's own documented
16
- path) and posts images concurrently — continuous batching stays fed instead
17
- of draining at each offline batch barrier, and a bad image fails one request
18
- instead of a whole batch. Measured ~1.8x the offline recipe's inference
19
- throughput on a 100-page historical-scan smoke test (l4x1, concurrency 32).
20
-
21
- This script is the *driver* half: it expects the server on localhost
22
- (started by the job command below), loads the input dataset, posts images
23
- concurrently, and pushes the result dataset. The driver has no torch/vllm
24
- deps, so `uv run` starts in seconds while the server warms up in parallel.
25
-
26
- Run on HF Jobs (standard uv-run shape — the script starts `vllm serve` itself
27
- as a subprocess when no server is already reachable; the only thing to get
28
- right is the --image flag, which provides the `vllm` binary):
29
-
30
- hf jobs uv run --detach --flavor l4x1 -s HF_TOKEN --timeout 4h \\
31
- --image vllm/vllm-openai:v0.22.1 \\
32
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr2-server.py \\
33
- <input-dataset> <output-dataset>
34
-
35
- To use an already-running or remote endpoint instead, pass --server URL — the
36
- script only spawns a server when the (default localhost) URL is unreachable.
37
- The serve flags live in SERVE_ARGS below (the model card's own recommended
38
- command: `--limit-mm-per-prompt`, `--mm-processor-cache-gb 0`,
39
- `--no-enable-prefix-caching` — OCR never reuses images, so the caches only
40
- cost memory).
41
-
42
- Model: lightonai/LightOnOCR-2-1B (1B, Apache-2.0)
43
- - Message is the image ONLY (no text prompt) — LightOnOCR-2's trained format.
44
- - Images resized client-side so the longest dimension is 1540px (training
45
- resolution at 200 DPI), same as the offline recipe.
46
- - Sampling per the card: temperature 0.2, top_p 0.9, max_tokens 4096.
47
- """
48
-
49
- import argparse
50
- import atexit
51
- import base64
52
- import concurrent.futures
53
- import io
54
- import json
55
- import logging
56
- import os
57
- import shutil
58
- import subprocess
59
- import sys
60
- import threading
61
- import time
62
- from datetime import datetime
63
- from typing import Any, Dict, Union
64
- from urllib.parse import urlparse
65
-
66
- import requests
67
- from datasets import load_dataset
68
- from huggingface_hub import DatasetCard, login
69
- from PIL import Image
70
-
71
- logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
72
- logger = logging.getLogger(__name__)
73
-
74
- MODEL = "lightonai/LightOnOCR-2-1B"
75
-
76
- DEFAULT_TARGET_SIZE = 1540 # longest dimension; LightOnOCR-2 training resolution
77
-
78
- # The serve command this script spawns when no server is reachable — the model
79
- # card's own recommended flags; single source of truth for the serving config.
80
- SERVE_ARGS = [
81
- "vllm", "serve", MODEL,
82
- "--limit-mm-per-prompt", '{"image": 1}',
83
- "--mm-processor-cache-gb", "0",
84
- "--no-enable-prefix-caching",
85
- "--max-model-len", "8192",
86
- "--gpu-memory-utilization", "0.8",
87
- "--port", "8000",
88
- ]
89
-
90
- RUN_COMMAND = (
91
- "hf jobs uv run --detach --flavor l4x1 -s HF_TOKEN --timeout 4h \\\n"
92
- " --image vllm/vllm-openai:v0.22.1 \\\n"
93
- " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr2-server.py \\\n"
94
- " <input-dataset> <output-dataset>"
95
- )
96
-
97
-
98
- def ensure_output_columns_free(dataset, columns, overwrite=False):
99
- """Fail fast if an output column would collide with an existing input column.
100
-
101
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
102
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
103
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
104
- column(s) here instead (logged) so the later add_column is clean.
105
- """
106
- clash = [c for c in columns if c in dataset.column_names]
107
- if not clash:
108
- return dataset
109
- if overwrite:
110
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
111
- return dataset.remove_columns(clash)
112
- logger.error(
113
- f"Output column(s) {clash} already exist in the input dataset "
114
- f"(columns: {dataset.column_names})."
115
- )
116
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
117
- sys.exit(1)
118
-
119
-
120
- def to_pil_image(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:
121
- """Convert a dataset image cell (PIL image, bytes dict, or path) to RGB PIL."""
122
- if isinstance(image, Image.Image):
123
- pil_img = image
124
- elif isinstance(image, dict) and "bytes" in image:
125
- pil_img = Image.open(io.BytesIO(image["bytes"]))
126
- elif isinstance(image, str):
127
- pil_img = Image.open(image)
128
- else:
129
- raise ValueError(f"Unsupported image type: {type(image)}")
130
- return pil_img.convert("RGB")
131
-
132
-
133
- def encode_image(image, target_size: int) -> str:
134
- """RGB-convert, resize longest dimension to target_size, return base64 PNG."""
135
- img = to_pil_image(image)
136
- if target_size:
137
- w, h = img.size
138
- if max(w, h) != target_size:
139
- scale = target_size / max(w, h)
140
- img = img.resize(
141
- (max(1, int(w * scale)), max(1, int(h * scale))),
142
- Image.Resampling.LANCZOS,
143
- )
144
- buf = io.BytesIO()
145
- img.save(buf, format="PNG")
146
- return base64.b64encode(buf.getvalue()).decode()
147
-
148
-
149
- def server_alive(server: str) -> bool:
150
- try:
151
- return requests.get(f"{server}/health", timeout=5).status_code == 200
152
- except requests.RequestException:
153
- return False
154
-
155
-
156
- def wait_for_server(server: str, timeout_s: int, proc: "subprocess.Popen | None" = None):
157
- logger.info(f"Waiting for server at {server}...")
158
- deadline = time.time() + timeout_s
159
- while time.time() < deadline:
160
- if server_alive(server):
161
- logger.info("Server is ready")
162
- return
163
- if proc is not None and proc.poll() is not None:
164
- logger.error(f"Spawned vllm serve exited with code {proc.returncode} before becoming ready")
165
- sys.exit(1)
166
- time.sleep(10)
167
- logger.error(f"Server did not become ready within {timeout_s}s")
168
- sys.exit(1)
169
-
170
-
171
- def ensure_server(server: str, timeout_s: int = 1800):
172
- """Use a reachable server; otherwise spawn `vllm serve` ourselves; else fail fast.
173
-
174
- Spawning is only attempted for a localhost URL — a remote --server that is
175
- down is the user's to fix, not ours to shadow with a local model.
176
- """
177
- if server_alive(server):
178
- logger.info(f"Using already-running server at {server}")
179
- return
180
-
181
- host = urlparse(server).hostname or ""
182
- if host not in ("127.0.0.1", "localhost", "0.0.0.0"):
183
- logger.info(f"Remote server {server} not up yet — waiting for it")
184
- wait_for_server(server, timeout_s)
185
- return
186
-
187
- if shutil.which("vllm") is None:
188
- logger.error("No server is running and the `vllm` binary is not on PATH.")
189
- logger.error("Run this script on a vLLM image so it can start the server itself:\n")
190
- logger.error(RUN_COMMAND)
191
- logger.error("\n(or start `vllm serve` yourself / pass --server URL of a running endpoint)")
192
- sys.exit(1)
193
-
194
- logger.info(f"Starting server: {' '.join(SERVE_ARGS)}")
195
- proc = subprocess.Popen(SERVE_ARGS) # logs interleave with ours on stdout/stderr
196
- atexit.register(proc.terminate) # don't leave a GPU server behind on local runs
197
- wait_for_server(server, timeout_s, proc=proc)
198
-
199
-
200
- def ocr_one(
201
- server: str,
202
- image,
203
- target_size: int,
204
- max_tokens: int,
205
- temperature: float,
206
- top_p: float,
207
- timeout_s: int,
208
- retries: int = 2,
209
- ) -> str:
210
- """OCR a single image via the chat completions API. Returns raw model text."""
211
- b64 = encode_image(image, target_size)
212
- payload = {
213
- "model": MODEL,
214
- "messages": [
215
- {
216
- "role": "user",
217
- "content": [
218
- # Image ONLY — LightOnOCR-2 uses no text prompt.
219
- {
220
- "type": "image_url",
221
- "image_url": {"url": f"data:image/png;base64,{b64}"},
222
- },
223
- ],
224
- }
225
- ],
226
- "temperature": temperature,
227
- "top_p": top_p,
228
- "max_tokens": max_tokens,
229
- }
230
- last_err = None
231
- for attempt in range(retries + 1):
232
- try:
233
- resp = requests.post(
234
- f"{server}/v1/chat/completions", json=payload, timeout=timeout_s
235
- )
236
- resp.raise_for_status()
237
- return resp.json()["choices"][0]["message"]["content"]
238
- except Exception as e:
239
- last_err = e
240
- if attempt < retries:
241
- time.sleep(10 * (attempt + 1))
242
- raise RuntimeError(f"request failed after {retries + 1} attempts: {last_err}")
243
-
244
-
245
- def jobs_flavor() -> str:
246
- """Return the HF Jobs hardware flavor this run is on, or "" when it cannot be told.
247
-
248
- HF Jobs sets ACCELERATOR to "cpu" or "gpu", not the flavor name, so the flavor is looked up
249
- in the public Jobs hardware list: first by GPU model and count, then by the CPU_CORES and
250
- MEMORY values that Jobs sets in the container (to tell a10g-small from a10g-large, or
251
- cpu-basic from cpu-upgrade). Any failure (no network, older huggingface_hub) returns "".
252
- """
253
- hardware = os.environ.get("ACCELERATOR") or ""
254
- if "-" in hardware or any(character.isdigit() for character in hardware):
255
- return hardware # already a flavor name
256
- try:
257
- from huggingface_hub import HfApi
258
-
259
- gpu_name, gpu_count = "", 0
260
- try:
261
- import torch
262
-
263
- if torch.cuda.is_available():
264
- gpu_name = torch.cuda.get_device_name(0)
265
- gpu_count = torch.cuda.device_count()
266
- except ImportError:
267
- # Torch-free drivers (e.g. the -server recipes): ask nvidia-smi instead.
268
- import subprocess
269
-
270
- try:
271
- listed = subprocess.run(
272
- ["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],
273
- capture_output=True, text=True, timeout=10, check=True,
274
- ).stdout
275
- names = [line.strip() for line in listed.splitlines() if line.strip()]
276
- if names:
277
- gpu_name, gpu_count = names[0], len(names)
278
- except (OSError, subprocess.SubprocessError):
279
- pass
280
- if gpu_count == 0 and hardware == "gpu":
281
- return "" # a GPU run whose GPU cannot be identified: do not guess a CPU flavor
282
-
283
- # Whole-word match, so "L4" does not match "NVIDIA L40S" ("NVIDIA A100-SXM4-80GB" -> A100).
284
- gpu_words = gpu_name.upper().replace("-", " ").split()
285
- candidates = []
286
- for flavor in HfApi(token=False).list_jobs_hardware():
287
- accelerator = flavor.accelerator
288
- if gpu_count == 0 and accelerator is None:
289
- candidates.append(flavor)
290
- elif (
291
- gpu_count > 0
292
- and accelerator is not None
293
- and accelerator.model.upper() in gpu_words
294
- and int(accelerator.quantity) == gpu_count
295
- ):
296
- candidates.append(flavor)
297
- if not candidates:
298
- return ""
299
-
300
- cores = float(os.environ.get("CPU_CORES") or 0)
301
- memory_gb = float((os.environ.get("MEMORY") or "0").upper().rstrip("GIB ") or 0)
302
-
303
- def distance(flavor) -> float:
304
- # Relative gap to the listed vCPUs and RAM; Jobs reports slightly different numbers.
305
- listed_cores = float(flavor.cpu.split()[0])
306
- listed_memory = float(flavor.ram.split()[0])
307
- return abs(listed_cores - cores) / listed_cores + abs(listed_memory - memory_gb) / listed_memory
308
-
309
- return min(candidates, key=distance).name
310
- except Exception:
311
- return ""
312
-
313
-
314
- def create_dataset_card(
315
- source_dataset: str,
316
- model: str,
317
- num_samples: int,
318
- num_errors: int,
319
- processing_time: str,
320
- images_per_sec: float,
321
- concurrency: int,
322
- max_tokens: int,
323
- temperature: float,
324
- target_size: int,
325
- image_column: str = "image",
326
- split: str = "train",
327
- ) -> str:
328
- """Create a dataset card documenting the OCR process."""
329
- model_name = model.split("/")[-1]
330
-
331
- # Canonical provenance stamp (see AGENTS.md): Jobs claim gated on JOB_ID, set by HF Jobs in-container.
332
- on_jobs = os.environ.get("JOB_ID") is not None
333
- hw = jobs_flavor() # flavor name, e.g. "a10g-small"; "" on CPU
334
- origin = (
335
- "Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"
336
- + (f" (`{hw}`)" if hw else "")
337
- ) if on_jobs else "Generated"
338
- jobs_tag = "\n- hf-jobs" if on_jobs else ""
339
-
340
- return f"""---
341
- tags:
342
- - ocr
343
- - document-processing
344
- - lighton-ocr
345
- - markdown
346
- - uv-script
347
- - generated{jobs_tag}
348
- ---
349
-
350
- # Document OCR using {model_name} (server mode)
351
-
352
- This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using LightOnOCR-2 (1B), served behind an in-job vLLM server with concurrent requests (continuous batching).
353
-
354
- ## Processing Details
355
-
356
- - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
357
- - **Model**: [{model}](https://huggingface.co/{model})
358
- - **Number of Samples**: {num_samples:,}
359
- - **Failed Requests**: {num_errors:,} (marked `[OCR ERROR]`)
360
- - **Processing Time**: {processing_time}
361
- - **Throughput**: {images_per_sec:.2f} images/sec
362
- - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
363
-
364
- ### Configuration
365
-
366
- - **Mode**: vLLM server (`vllm serve`) + concurrent driver, {concurrency} concurrent requests
367
- - **Image Column**: `{image_column}`
368
- - **Dataset Split**: `{split}`
369
- - **Target Image Size**: {target_size}px (longest dimension)
370
- - **Max Output Tokens**: {max_tokens:,}
371
- - **Temperature**: {temperature}
372
-
373
- ## Dataset Structure
374
-
375
- The dataset contains all original columns plus:
376
- - `markdown`: The extracted text in markdown format
377
- - `inference_info`: JSON list tracking all OCR models applied to this dataset
378
-
379
- ## Reproduction
380
-
381
- {origin} with the [`lighton-ocr2-server.py`](https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr2-server.py) recipe from [uv-scripts](https://huggingface.co/uv-scripts) — see the script docstring for the single `hf jobs run` command that starts the server and driver together. The offline-vLLM sibling recipe is [`lighton-ocr2.py`](https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr2.py).
382
- """
383
-
384
-
385
- def main(
386
- input_dataset: str,
387
- output_dataset: str,
388
- image_column: str = "image",
389
- server: str = "http://127.0.0.1:8000",
390
- concurrency: int = 32,
391
- max_tokens: int = 4096,
392
- temperature: float = 0.2,
393
- top_p: float = 0.9,
394
- target_size: int = DEFAULT_TARGET_SIZE,
395
- request_timeout: int = 1800,
396
- hf_token: str = None,
397
- split: str = "train",
398
- max_samples: int = None,
399
- private: bool = False,
400
- shuffle: bool = False,
401
- seed: int = 42,
402
- output_column: str = "markdown",
403
- overwrite: bool = False,
404
- config: str = None,
405
- create_pr: bool = False,
406
- ):
407
- """Process images from HF dataset through a LightOnOCR-2 vLLM server."""
408
-
409
- start_time = datetime.now()
410
-
411
- HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
412
- if HF_TOKEN:
413
- login(token=HF_TOKEN)
414
-
415
- logger.info(f"Using model: {MODEL} via server {server}")
416
-
417
- logger.info(f"Loading dataset: {input_dataset}")
418
- dataset = load_dataset(input_dataset, split=split)
419
-
420
- if image_column not in dataset.column_names:
421
- raise ValueError(
422
- f"Column '{image_column}' not found. Available: {dataset.column_names}"
423
- )
424
-
425
- dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
426
-
427
- if shuffle:
428
- logger.info(f"Shuffling dataset with seed {seed}")
429
- dataset = dataset.shuffle(seed=seed)
430
-
431
- if max_samples:
432
- dataset = dataset.select(range(min(max_samples, len(dataset))))
433
- logger.info(f"Limited to {len(dataset)} samples")
434
-
435
- # Reuse a reachable server, else spawn `vllm serve` (needs the vllm binary,
436
- # i.e. a vllm/vllm-openai image), else fail fast with the correct command.
437
- ensure_server(server)
438
-
439
- n = len(dataset)
440
- logger.info(f"Processing {n} images, concurrency {concurrency}")
441
- all_outputs = [None] * n
442
- errors = 0
443
- done = 0
444
- inference_start = time.time()
445
- lock = threading.Lock()
446
-
447
- def worker(i: int) -> None:
448
- nonlocal errors, done
449
- try:
450
- text = ocr_one(
451
- server,
452
- dataset[i][image_column],
453
- target_size,
454
- max_tokens,
455
- temperature,
456
- top_p,
457
- request_timeout,
458
- )
459
- all_outputs[i] = text.strip()
460
- except Exception as e:
461
- logger.error(f"Image {i} failed: {e}")
462
- all_outputs[i] = "[OCR ERROR]"
463
- with lock:
464
- errors += 1
465
- with lock:
466
- done += 1
467
- if done % 25 == 0 or done == n:
468
- rate = done / max(time.time() - inference_start, 1e-9)
469
- logger.info(f"{done}/{n} done ({rate:.2f} img/s, {errors} errors)")
470
-
471
- with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as pool:
472
- list(pool.map(worker, range(n)))
473
-
474
- inference_secs = time.time() - inference_start
475
- processing_duration = datetime.now() - start_time
476
- processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
477
- images_per_sec = n / inference_secs if inference_secs else 0.0
478
-
479
- logger.info(f"Adding '{output_column}' column to dataset")
480
- dataset = dataset.add_column(output_column, all_outputs)
481
-
482
- # Inference info tracking
483
- inference_entry = {
484
- "model_id": MODEL,
485
- "model_name": "LightOnOCR-2-1B",
486
- "column_name": output_column,
487
- "timestamp": datetime.now().isoformat(),
488
- "temperature": temperature,
489
- "top_p": top_p,
490
- "max_tokens": max_tokens,
491
- "target_size": target_size,
492
- "mode": "vllm-server",
493
- "concurrency": concurrency,
494
- }
495
-
496
- if "inference_info" in dataset.column_names:
497
- logger.info("Updating existing inference_info column")
498
-
499
- def update_inference_info(example):
500
- try:
501
- existing_info = (
502
- json.loads(example["inference_info"])
503
- if example["inference_info"]
504
- else []
505
- )
506
- except (json.JSONDecodeError, TypeError):
507
- existing_info = []
508
- existing_info.append(inference_entry)
509
- return {"inference_info": json.dumps(existing_info)}
510
-
511
- dataset = dataset.map(update_inference_info)
512
- else:
513
- logger.info("Creating new inference_info column")
514
- inference_list = [json.dumps([inference_entry])] * len(dataset)
515
- dataset = dataset.add_column("inference_info", inference_list)
516
-
517
- # Push to hub with retry and XET fallback
518
- logger.info(f"Pushing to {output_dataset}")
519
- max_retries = 3
520
- for attempt in range(1, max_retries + 1):
521
- try:
522
- if attempt > 1:
523
- logger.warning("Disabling XET (fallback to HTTP upload)")
524
- os.environ["HF_HUB_DISABLE_XET"] = "1"
525
- dataset.push_to_hub(
526
- output_dataset,
527
- private=private,
528
- token=HF_TOKEN,
529
- max_shard_size="500MB",
530
- **({"config_name": config} if config else {}),
531
- create_pr=create_pr,
532
- commit_message=f"Add {MODEL} OCR results ({len(dataset)} samples, server mode)"
533
- + (f" [{config}]" if config else ""),
534
- )
535
- break
536
- except Exception as e:
537
- logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
538
- if attempt < max_retries:
539
- delay = 30 * (2 ** (attempt - 1))
540
- logger.info(f"Retrying in {delay}s...")
541
- time.sleep(delay)
542
- else:
543
- logger.error("All upload attempts failed. OCR results are lost.")
544
- sys.exit(1)
545
-
546
- logger.info("Creating dataset card")
547
- card_content = create_dataset_card(
548
- source_dataset=input_dataset,
549
- model=MODEL,
550
- num_samples=len(dataset),
551
- num_errors=errors,
552
- processing_time=processing_time_str,
553
- images_per_sec=images_per_sec,
554
- concurrency=concurrency,
555
- max_tokens=max_tokens,
556
- temperature=temperature,
557
- target_size=target_size,
558
- image_column=image_column,
559
- split=split,
560
- )
561
-
562
- card = DatasetCard(card_content)
563
- card.push_to_hub(output_dataset, token=HF_TOKEN)
564
-
565
- logger.info("Done! LightOnOCR-2 server-mode processing complete.")
566
- logger.info(
567
- f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
568
- )
569
- logger.info(f"Processing time: {processing_time_str}")
570
- logger.info(
571
- f"Throughput: {images_per_sec:.2f} images/sec "
572
- f"(inference only, excl. dataset load/push; {errors} errors)"
573
- )
574
-
575
-
576
- if __name__ == "__main__":
577
- if len(sys.argv) == 1:
578
- print("=" * 70)
579
- print("LightOnOCR-2 Document Processing (vLLM server mode)")
580
- print("=" * 70)
581
- print("\nSame model + outputs as lighton-ocr2.py, but drives an in-job")
582
- print("`vllm serve` with concurrent requests — no batch barriers,")
583
- print("per-image (not per-batch) failure isolation.")
584
- print("\nThe server must already be running (the job command starts")
585
- print("both — see the module docstring for the full `hf jobs run`).")
586
- print("\nExamples:")
587
- print("\n1. Basic OCR (server on localhost:8000):")
588
- print(" uv run lighton-ocr2-server.py input-dataset output-dataset")
589
- print("\n2. Test with a small sample:")
590
- print(" uv run lighton-ocr2-server.py large-dataset test --max-samples 10 --shuffle")
591
- print("\nFor full help: uv run lighton-ocr2-server.py --help")
592
- sys.exit(0)
593
-
594
- parser = argparse.ArgumentParser(
595
- description="Document OCR using LightOnOCR-2 via an in-job vLLM server",
596
- formatter_class=argparse.RawDescriptionHelpFormatter,
597
- epilog="""
598
- Examples:
599
- uv run lighton-ocr2-server.py my-docs analyzed-docs
600
- uv run lighton-ocr2-server.py large-dataset test --max-samples 50 --shuffle
601
- See the module docstring for the full `hf jobs run` command (server + driver in one job).
602
- """,
603
- )
604
-
605
- parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
606
- parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
607
- parser.add_argument(
608
- "--image-column",
609
- default="image",
610
- help="Column containing images (default: image)",
611
- )
612
- parser.add_argument(
613
- "--server",
614
- default="http://127.0.0.1:8000",
615
- help="vLLM server base URL (default: in-job localhost:8000)",
616
- )
617
- parser.add_argument(
618
- "--concurrency",
619
- type=int,
620
- default=32,
621
- help="Concurrent OCR requests (default: 32; vLLM queues excess internally, "
622
- "so this mainly needs to be high enough to keep continuous batching fed)",
623
- )
624
- parser.add_argument(
625
- "--max-tokens",
626
- type=int,
627
- default=4096,
628
- help="Maximum tokens to generate (default: 4096, the model card value)",
629
- )
630
- parser.add_argument(
631
- "--temperature",
632
- type=float,
633
- default=0.2,
634
- help="Sampling temperature (default: 0.2, the model card value)",
635
- )
636
- parser.add_argument(
637
- "--top-p",
638
- type=float,
639
- default=0.9,
640
- help="Top-p sampling (default: 0.9, the model card value)",
641
- )
642
- parser.add_argument(
643
- "--target-size",
644
- type=int,
645
- default=DEFAULT_TARGET_SIZE,
646
- help=f"Resize images so the longest dimension is this many pixels before upload "
647
- f"(default: {DEFAULT_TARGET_SIZE}, the model's training resolution); 0 disables",
648
- )
649
- parser.add_argument(
650
- "--request-timeout",
651
- type=int,
652
- default=1800,
653
- help="Per-request timeout in seconds (default: 1800)",
654
- )
655
- parser.add_argument("--hf-token", help="Hugging Face API token")
656
- parser.add_argument(
657
- "--split", default="train", help="Dataset split to use (default: train)"
658
- )
659
- parser.add_argument(
660
- "--max-samples",
661
- type=int,
662
- help="Maximum number of samples to process (for testing)",
663
- )
664
- parser.add_argument(
665
- "--private", action="store_true", help="Make output dataset private"
666
- )
667
- parser.add_argument(
668
- "--config",
669
- help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
670
- )
671
- parser.add_argument(
672
- "--create-pr",
673
- action="store_true",
674
- help="Create a pull request instead of pushing directly (for parallel benchmarking)",
675
- )
676
- parser.add_argument(
677
- "--shuffle", action="store_true", help="Shuffle dataset before processing"
678
- )
679
- parser.add_argument(
680
- "--seed",
681
- type=int,
682
- default=42,
683
- help="Random seed for shuffling (default: 42)",
684
- )
685
- parser.add_argument(
686
- "--output-column",
687
- default="markdown",
688
- help="Column name for output text (default: markdown)",
689
- )
690
- parser.add_argument(
691
- "--overwrite",
692
- action="store_true",
693
- help="Replace the output column if it already exists in the input dataset "
694
- "(default: error out to avoid clobbering an existing column).",
695
- )
696
-
697
- args = parser.parse_args()
698
-
699
- main(
700
- input_dataset=args.input_dataset,
701
- output_dataset=args.output_dataset,
702
- image_column=args.image_column,
703
- server=args.server,
704
- concurrency=args.concurrency,
705
- max_tokens=args.max_tokens,
706
- temperature=args.temperature,
707
- top_p=args.top_p,
708
- target_size=args.target_size,
709
- request_timeout=args.request_timeout,
710
- hf_token=args.hf_token,
711
- split=args.split,
712
- max_samples=args.max_samples,
713
- private=args.private,
714
- shuffle=args.shuffle,
715
- seed=args.seed,
716
- output_column=args.output_column,
717
- overwrite=args.overwrite,
718
- config=args.config,
719
- create_pr=args.create_pr,
720
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lighton-ocr2.py CHANGED
@@ -1,28 +1,14 @@
1
  # /// script
2
  # requires-python = ">=3.11"
3
  # dependencies = [
4
- # "datasets>=4.0.0,<5.1", # 5.1 needs huggingface_hub>=1.31; the image ships an older 1.x on PYTHONPATH, which wins
5
  # "huggingface-hub",
6
  # "pillow",
 
7
  # "tqdm",
8
  # "toolz",
 
9
  # ]
10
- #
11
- # [tool.uv]
12
- # exclude-newer = "2026-10-01T00:00:00Z" # frozen: resolve packages as on this date
13
- #
14
- # [tool.uv-scripts]
15
- # maintenance = "frozen"
16
- # frozen_on = "2026-11-06"
17
- # superseded_by = "lighton-ocr3.py"
18
- #
19
- # [tool.hf-jobs]
20
- # image = "vllm/vllm-openai@sha256:953d3a06d5e64ab582985cd7401289d3abf2a2c14ef2158e9a84313daeec77d7" # v0.22.1
21
- # python = "/usr/bin/python3"
22
- # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
23
- # flavor = "a10g-small"
24
- # timeout = "1h"
25
- # secrets = ["HF_TOKEN"]
26
  # ///
27
 
28
  """
@@ -32,20 +18,8 @@ LightOnOCR-2 is a compact 1B multilingual OCR model optimized for production spe
32
  Combines Pixtral ViT encoder with Qwen3 language model for efficient document parsing.
33
  Uses Reinforcement Learning with Verifiable Rewards (RLVR) for improved quality.
34
 
35
- Run on HF Jobs. vLLM and torch come from the vllm/vllm-openai:v0.22.1 image declared
36
- in the [tool.hf-jobs] header (`hf` CLI 1.32+), which also sets the hardware and the
37
- HF_TOKEN secret. The tag is pinned: unpinned vLLM 0.29/0.30 with current transformers
38
- fails to import LightOnOCR-2 (PixtralRotaryEmbedding). Pass --timeout for a long run:
39
-
40
- hf jobs uv run --timeout 1h \\
41
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr2.py \\
42
- <input-dataset> <output-dataset>
43
-
44
- To run on your own GPU, add the engine: `uv run --with vllm==0.22.1 lighton-ocr2.py ...`.
45
-
46
- Frozen on 2026-11-06 (superseded by lighton-ocr3.py): the image digest, the package
47
- resolution date and the model revision are pinned, and it gets fixes only when it breaks.
48
- See MAINTAINING.md in https://github.com/davanstrien/uv-scripts.
49
 
50
  Features:
51
  - ⚡ Fastest: 42.8 pages/sec on H100 GPU (7× faster than v1)
@@ -59,7 +33,7 @@ Features:
59
  - 💪 Production-ready: Outperforms models 9× larger
60
 
61
  Model: lightonai/LightOnOCR-2-1B
62
- vLLM: vllm/vllm-openai:v0.22.1 image (see the header)
63
  Performance: 83.2 ± 0.9% on OlmOCR-Bench
64
  """
65
 
@@ -75,14 +49,10 @@ from datetime import datetime
75
 
76
  import torch
77
  from datasets import load_dataset
78
- from huggingface_hub import DatasetCard
79
  from PIL import Image
80
  from toolz import partition_all
81
  from tqdm.auto import tqdm
82
- # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
83
- # default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
84
- # lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
85
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
86
  from vllm import LLM, SamplingParams
87
 
88
  logging.basicConfig(level=logging.INFO)
@@ -91,8 +61,6 @@ logger = logging.getLogger(__name__)
91
 
92
  # LightOnOCR-2 model (single variant)
93
  MODEL = "lightonai/LightOnOCR-2-1B"
94
- # Frozen: the revision tested on 2026-11-06 (main at that date).
95
- MODEL_REVISION = "be7c41313c30e940fe5571de59e5fabc779e00c8"
96
 
97
 
98
  def check_cuda_availability():
@@ -105,28 +73,6 @@ def check_cuda_availability():
105
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
106
 
107
 
108
- def ensure_output_columns_free(dataset, columns, overwrite=False):
109
- """Fail fast if an output column would collide with an existing input column.
110
-
111
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
112
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
113
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
114
- column(s) here instead (logged) so the later add_column is clean.
115
- """
116
- clash = [c for c in columns if c in dataset.column_names]
117
- if not clash:
118
- return dataset
119
- if overwrite:
120
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
121
- return dataset.remove_columns(clash)
122
- logger.error(
123
- f"Output column(s) {clash} already exist in the input dataset "
124
- f"(columns: {dataset.column_names})."
125
- )
126
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
127
- sys.exit(1)
128
-
129
-
130
  def resize_image_to_target(image: Image.Image, target_size: int = 1540) -> Image.Image:
131
  """
132
  Resize image so longest dimension is target_size while maintaining aspect ratio.
@@ -336,7 +282,6 @@ def main(
336
  shuffle: bool = False,
337
  seed: int = 42,
338
  output_column: str = "markdown",
339
- overwrite: bool = False,
340
  config: str = None,
341
  create_pr: bool = False,
342
  verbose: bool = False,
@@ -349,11 +294,10 @@ def main(
349
  # Track processing start time
350
  start_time = datetime.now()
351
 
352
- # Set the env var instead of login(): the old huggingface_hub in this image
353
- # raises KeyError on a Jobs token in login(). Hub calls read HF_TOKEN.
354
  HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
355
  if HF_TOKEN:
356
- os.environ["HF_TOKEN"] = HF_TOKEN
357
 
358
  logger.info(f"Using model: {MODEL}")
359
 
@@ -367,9 +311,6 @@ def main(
367
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
368
  )
369
 
370
- # Fail fast if the output column would collide with an existing input column
371
- dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
372
-
373
  # Shuffle if requested
374
  if shuffle:
375
  logger.info(f"Shuffling dataset with seed {seed}")
@@ -385,9 +326,6 @@ def main(
385
  logger.info("This may take a few minutes on first run...")
386
  llm = LLM(
387
  model=MODEL,
388
- revision=MODEL_REVISION,
389
- code_revision=MODEL_REVISION,
390
- tokenizer_revision=MODEL_REVISION,
391
  trust_remote_code=True,
392
  max_model_len=max_model_len,
393
  gpu_memory_utilization=gpu_memory_utilization,
@@ -562,8 +500,8 @@ if __name__ == "__main__":
562
  print("\n4. Original image size (no resize):")
563
  print(" uv run lighton-ocr2.py docs output --no-resize")
564
  print("\n5. Running on HF Jobs:")
565
- print(" (image, hardware and HF_TOKEN come from the script's [tool.hf-jobs] header)")
566
- print(" hf jobs uv run \\")
567
  print(
568
  " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr2.py \\"
569
  )
@@ -616,12 +554,8 @@ Examples:
616
  parser.add_argument(
617
  "--max-model-len",
618
  type=int,
619
- default=16384,
620
- help=(
621
- "Maximum model context length (default: 16384). A full page resized to "
622
- "1540px is ~6k image tokens; with --max-tokens 4096 output that overflows "
623
- "the old 8192 default at admission and vLLM rejects the request."
624
- ),
625
  )
626
  parser.add_argument(
627
  "--max-tokens",
@@ -693,12 +627,6 @@ Examples:
693
  default="markdown",
694
  help="Column name for output text (default: markdown)",
695
  )
696
- parser.add_argument(
697
- "--overwrite",
698
- action="store_true",
699
- help="Replace the output column if it already exists in the input dataset "
700
- "(default: error out to avoid clobbering an existing column).",
701
- )
702
  parser.add_argument(
703
  "--verbose",
704
  action="store_true",
@@ -726,7 +654,6 @@ Examples:
726
  shuffle=args.shuffle,
727
  seed=args.seed,
728
  output_column=args.output_column,
729
- overwrite=args.overwrite,
730
  config=args.config,
731
  create_pr=args.create_pr,
732
  verbose=args.verbose,
 
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
  # ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  # ///
13
 
14
  """
 
18
  Combines Pixtral ViT encoder with Qwen3 language model for efficient document parsing.
19
  Uses Reinforcement Learning with Verifiable Rewards (RLVR) for improved quality.
20
 
21
+ NOTE: Requires vLLM nightly wheels for LightOnOCR-2 support. First run may take
22
+ a few minutes to download and install dependencies.
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
  Features:
25
  - ⚡ Fastest: 42.8 pages/sec on H100 GPU (7× faster than v1)
 
33
  - 💪 Production-ready: Outperforms models 9× larger
34
 
35
  Model: lightonai/LightOnOCR-2-1B
36
+ vLLM: Requires vLLM nightly build
37
  Performance: 83.2 ± 0.9% on OlmOCR-Bench
38
  """
39
 
 
49
 
50
  import torch
51
  from datasets import load_dataset
52
+ from huggingface_hub import DatasetCard, login
53
  from PIL import Image
54
  from toolz import partition_all
55
  from tqdm.auto import tqdm
 
 
 
 
56
  from vllm import LLM, SamplingParams
57
 
58
  logging.basicConfig(level=logging.INFO)
 
61
 
62
  # LightOnOCR-2 model (single variant)
63
  MODEL = "lightonai/LightOnOCR-2-1B"
 
 
64
 
65
 
66
  def check_cuda_availability():
 
73
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
74
 
75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  def resize_image_to_target(image: Image.Image, target_size: int = 1540) -> Image.Image:
77
  """
78
  Resize image so longest dimension is target_size while maintaining aspect ratio.
 
282
  shuffle: bool = False,
283
  seed: int = 42,
284
  output_column: str = "markdown",
 
285
  config: str = None,
286
  create_pr: bool = False,
287
  verbose: bool = False,
 
294
  # Track processing start time
295
  start_time = datetime.now()
296
 
297
+ # Login to HF if token provided
 
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
 
 
311
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
312
  )
313
 
 
 
 
314
  # Shuffle if requested
315
  if shuffle:
316
  logger.info(f"Shuffling dataset with seed {seed}")
 
326
  logger.info("This may take a few minutes on first run...")
327
  llm = LLM(
328
  model=MODEL,
 
 
 
329
  trust_remote_code=True,
330
  max_model_len=max_model_len,
331
  gpu_memory_utilization=gpu_memory_utilization,
 
500
  print("\n4. Original image size (no resize):")
501
  print(" uv run lighton-ocr2.py docs output --no-resize")
502
  print("\n5. Running on HF Jobs:")
503
+ print(" hf jobs uv run --flavor l4x1 \\")
504
+ print(" -s HF_TOKEN \\")
505
  print(
506
  " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr2.py \\"
507
  )
 
554
  parser.add_argument(
555
  "--max-model-len",
556
  type=int,
557
+ default=8192,
558
+ help="Maximum model context length (default: 8192)",
 
 
 
 
559
  )
560
  parser.add_argument(
561
  "--max-tokens",
 
627
  default="markdown",
628
  help="Column name for output text (default: markdown)",
629
  )
 
 
 
 
 
 
630
  parser.add_argument(
631
  "--verbose",
632
  action="store_true",
 
654
  shuffle=args.shuffle,
655
  seed=args.seed,
656
  output_column=args.output_column,
 
657
  config=args.config,
658
  create_pr=args.create_pr,
659
  verbose=args.verbose,
lighton-ocr3-bucket.py DELETED
@@ -1,528 +0,0 @@
1
- # /// script
2
- # requires-python = ">=3.11"
3
- # dependencies = [
4
- # "pillow",
5
- # "imagecodecs",
6
- # "toolz",
7
- # "bucketbag @ https://github.com/davanstrien/bucketbag/archive/refs/tags/v0.3.1.tar.gz",
8
- # # LightOn's official client, pinned to a commit (not on PyPI). Used for its
9
- # # parser, page resize, PDF rendering and dollar-delimiter repair.
10
- # "lightonocr @ https://github.com/lightonai/LightOnOCR/archive/36755d461be079737860a5f03ae0c803501269e9.tar.gz",
11
- # ]
12
- #
13
- # [tool.hf-jobs]
14
- # image = "vllm/vllm-openai:v0.30.0"
15
- # python = "/usr/bin/python3"
16
- # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
17
- # flavor = "a10g-small"
18
- # secrets = ["HF_TOKEN"]
19
- # ///
20
-
21
- """
22
- OCR images and PDFs from an HF Bucket (or a directory) using LightOnOCR-3,
23
- writing markdown files.
24
-
25
- Bucket sibling of lighton-ocr3.py: same model, prompt, sampling and post-processing.
26
- Writes one .md per image (or per PDF page), preserving the key/directory structure.
27
- In grounding mode each .md gets a .json sidecar with the parsed layout blocks.
28
-
29
- INPUT and OUTPUT are each either
30
- - an `hf://buckets/<ns>/<bucket>[/<prefix>]` URL: read with bucketbag (list, then
31
- download one batch at a time to scratch, no mount) / written with one upload call
32
- per batch. Use this for large buckets: mounting a very large bucket can be slow.
33
- - a directory: a local folder, or a bucket mounted with `-v`.
34
-
35
- Input: Output:
36
- /input/page1.jp2 → /output/page1.md (+ page1.json with --mode grounding)
37
- /input/report.pdf → /output/report/page_001.md
38
- (3 pages) /output/report/page_002.md
39
- /output/report/page_003.md
40
- /output/report/.complete.plain
41
- /input/sub/photo.jpg → /output/sub/photo.md
42
-
43
- Pages that already have their output are skipped, so re-running the same command
44
- resumes a stopped run. A page that fails writes nothing and is retried on the next
45
- run. A PDF gets a `.complete.<mode>` marker in its output folder once every page is
46
- written; until then, a re-run OCRs only its missing pages. --overwrite redoes
47
- everything, replacing outputs as it goes: a page that fails keeps its previous output
48
- (the run lists those inputs), so re-run them with --overwrite or use a fresh output prefix.
49
- Keep plain and grounding runs in separate output prefixes.
50
-
51
- Examples:
52
-
53
- # Bucket to bucket on HF Jobs (image, flavor and HF_TOKEN come from the
54
- # [tool.hf-jobs] header; needs hf CLI 1.32+). One folder of a large bucket:
55
- hf jobs uv run \\
56
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3-bucket.py \\
57
- hf://buckets/biglam/britannica/source/pages/00070476bsb \\
58
- hf://buckets/user/ocr-output/britannica --mode grounding --max-samples 20
59
-
60
- # Mounted volumes work too (simplest for small buckets)
61
- hf jobs uv run \\
62
- -v hf://buckets/user/ocr-input:/input:ro \\
63
- -v hf://buckets/user/ocr-output:/output \\
64
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3-bucket.py \\
65
- /input /output
66
-
67
- # Own GPU (vLLM and torch come from the image on Jobs, so add them here)
68
- uv run --with vllm==0.30.0 lighton-ocr3-bucket.py ./images ./output
69
-
70
- Models: lightonai/LightOnOCR-3-4B (default) or lightonai/LightOnOCR-3-0.8B (Apache-2.0).
71
- See lighton-ocr3.py for the settings and why the vLLM image is pinned.
72
- """
73
-
74
- import argparse
75
- import json
76
- import logging
77
- import os
78
- import sys
79
- import time
80
- from pathlib import Path
81
- from typing import NamedTuple
82
-
83
- import torch
84
- from bucketbag import batched_files, iter_keys, put_files
85
- from lightonocr import (
86
- DEFAULT_LONGEST_EDGE,
87
- GROUNDING_PROMPT,
88
- fit,
89
- fix_escaped_dollars,
90
- parse_blocks,
91
- to_markdown,
92
- )
93
- from PIL import Image
94
- from toolz import partition_all
95
-
96
- # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
97
- # default uv-script image lacks (engine init then crashes). On the vllm/vllm-openai image it's
98
- # a harmless no-op.
99
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
100
- # DeepGEMM's init asserts on a missing nvcc (non-fatal traceback); OCR doesn't need it.
101
- os.environ.setdefault("VLLM_USE_DEEP_GEMM", "0")
102
- from vllm import LLM, SamplingParams
103
-
104
- logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
105
- logger = logging.getLogger(__name__)
106
-
107
- MODELS = ["lightonai/LightOnOCR-3-4B", "lightonai/LightOnOCR-3-0.8B"]
108
- DEFAULT_MODEL = MODELS[0]
109
-
110
- # Sampling from the model card's vLLM example (temperature 0.2, top_p 0.9, max_tokens 4096).
111
- DEFAULT_TEMPERATURE = 0.2
112
- DEFAULT_TOP_P = 0.9
113
- DEFAULT_MAX_TOKENS = 4096
114
-
115
- IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".tiff", ".tif", ".bmp", ".webp", ".jp2", ".j2k"}
116
- JP2_EXTENSIONS = {".jp2", ".j2k"}
117
- BUCKET_SCHEME = "hf://buckets/"
118
-
119
-
120
- def check_cuda_availability():
121
- if not torch.cuda.is_available():
122
- logger.error("CUDA is not available. This script requires a GPU.")
123
- sys.exit(1)
124
- logger.info(f"CUDA available. GPU: {torch.cuda.get_device_name(0)}")
125
-
126
-
127
- def is_bucket(location: str) -> bool:
128
- return location.startswith(BUCKET_SCHEME)
129
-
130
-
131
- def as_bucket_dir(url: str) -> tuple[str, str]:
132
- """Split a bucket URL into (bucket root URL, directory key prefix ending in "/").
133
-
134
- Pass the prefix to bucketbag explicitly: it strips a trailing slash from the URL and
135
- matches prefixes as strings, so `.../pages/00070476bsb` would also list
136
- `.../pages/00070476bsb2/...`.
137
- """
138
- parts = url[len(BUCKET_SCHEME):].strip("/").split("/", 2)
139
- if len(parts) < 2:
140
- raise ValueError(f"Not a bucket URL: {url} (expected hf://buckets/<ns>/<bucket>[/<prefix>])")
141
- prefix = parts[2] + "/" if len(parts) == 3 else ""
142
- return BUCKET_SCHEME + "/".join(parts[:2]), prefix
143
-
144
-
145
- def output_collisions(rels: list[str]) -> list[str]:
146
- """Inputs whose outputs would overwrite each other, e.g. scan.png + scan.jpg -> scan.md,
147
- or report.pdf (report/page_001.md) + report/page_001.png."""
148
- owners: dict[str, list[str]] = {}
149
- for rel in rels:
150
- # A PDF owns its whole output folder; an image owns one .md.
151
- key = str(Path(rel).with_suffix("")) + "/" if rel.lower().endswith(".pdf") else md_rel(rel)
152
- owners.setdefault(key, []).append(rel)
153
- clashes = [group for group in owners.values() if len(group) > 1]
154
- folders = {key for key in owners if key.endswith("/")}
155
- for key, group in owners.items():
156
- if not key.endswith("/") and any(key.startswith(folder) for folder in folders):
157
- clashes.append(group + owners[next(f for f in folders if key.startswith(f))])
158
- return [" + ".join(group) for group in clashes]
159
-
160
-
161
- def is_input_file(rel: str) -> bool:
162
- ext = Path(rel).suffix.lower()
163
- return ext in IMAGE_EXTENSIONS or ext == ".pdf"
164
-
165
-
166
- def list_inputs(source: str, include: str | None, limit: int | None) -> list[str]:
167
- """Relative paths of image/PDF inputs, sorted. With `limit`, stops early."""
168
- rels = []
169
- if is_bucket(source):
170
- url, prefix = as_bucket_dir(source)
171
- keys = iter_keys(url, prefix=prefix, include=f"{prefix}{include}" if include else None)
172
- candidates = (k[len(prefix):] for k in keys)
173
- else:
174
- root = Path(source)
175
- paths = root.rglob(include or "*")
176
- candidates = (str(p.relative_to(root)) for p in (paths if limit else sorted(paths)) if p.is_file())
177
- for rel in candidates:
178
- if is_input_file(rel):
179
- rels.append(rel)
180
- if limit is not None and len(rels) >= limit:
181
- break
182
- return rels
183
-
184
-
185
- def list_outputs(dest: str) -> set[str]:
186
- """Relative paths of outputs already written (for resume)."""
187
- if is_bucket(dest):
188
- url, prefix = as_bucket_dir(dest)
189
- return {k[len(prefix):] for k in iter_keys(url, prefix=prefix)}
190
- root = Path(dest)
191
- return {str(p.relative_to(root)) for p in root.rglob("*") if p.is_file()} if root.is_dir() else set()
192
-
193
-
194
- def md_rel(rel: str, page: int | None = None) -> str:
195
- """Output path for an input: x.jp2 -> x.md; a PDF page -> x/page_001.md."""
196
- stem = str(Path(rel).with_suffix(""))
197
- return f"{stem}/page_{page:03d}.md" if page else f"{stem}.md"
198
-
199
-
200
- def marker_rel(rel: str, mode: str) -> str:
201
- """Written into a PDF's output folder once all its pages are written in this mode."""
202
- return f"{Path(rel).with_suffix('')}/.complete.{mode}"
203
-
204
-
205
- def page_done(md: str, existing: set[str], mode: str) -> bool:
206
- if md not in existing:
207
- return False
208
- return mode != "grounding" or md[: -len(".md")] + ".json" in existing
209
-
210
-
211
- def is_done(rel: str, existing: set[str], mode: str) -> bool:
212
- if rel.lower().endswith(".pdf"):
213
- # Grounding needs the .json sidecars, so only a grounding marker will do;
214
- # plain is satisfied by either (as for images, whose .md exists in both modes).
215
- modes = ["grounding"] if mode == "grounding" else ["plain", "grounding"]
216
- return any(marker_rel(rel, m) in existing for m in modes)
217
- return page_done(md_rel(rel), existing, mode)
218
-
219
-
220
- def iter_local_batches(source: str, rels: list[str], n: int):
221
- """Yield batches of (rel, local_path): straight from disk, or downloaded by bucketbag
222
- (one batch at a time to scratch, deleted as the loop advances)."""
223
- if not is_bucket(source):
224
- for chunk in partition_all(n, rels):
225
- yield [(rel, Path(source) / rel) for rel in chunk]
226
- return
227
- url, prefix = as_bucket_dir(source)
228
- keys = [prefix + rel for rel in rels]
229
- for batch in batched_files(url, keys=keys, n=n, prefetch=2):
230
- yield [(it.key[len(prefix):], it.path) for it in batch]
231
-
232
-
233
- def open_image(path: Path) -> Image.Image:
234
- """Open one image as RGB. JPEG-2000 falls back to imagecodecs when Pillow
235
- was built without OpenJPEG."""
236
- try:
237
- return Image.open(path).convert("RGB")
238
- except Exception:
239
- if path.suffix.lower() not in JP2_EXTENSIONS:
240
- raise
241
- import imagecodecs
242
-
243
- return Image.fromarray(imagecodecs.imread(str(path))).convert("RGB")
244
-
245
-
246
- class PageItem(NamedTuple):
247
- rel: str # input file
248
- md: str | None # output .md path; None for a marker-only item
249
- image: Image.Image | None
250
- last: bool # last page still to do for a PDF: write its .complete.<mode> marker after it
251
-
252
-
253
- def iter_pages(rel: str, path: Path, existing: set[str], mode: str, longest_edge: int):
254
- """PageItems for the pages of one input that still need OCR. PDF pages render one at
255
- a time (as lightonocr.render.render_pdf does), so a long PDF never sits in memory."""
256
- if not rel.lower().endswith(".pdf"):
257
- yield PageItem(rel, md_rel(rel), fit(open_image(path), longest_edge), False)
258
- return
259
- import pypdfium2 as pdfium
260
-
261
- pdf = pdfium.PdfDocument(str(path))
262
- todo = [n for n in range(1, len(pdf) + 1) if not page_done(md_rel(rel, n), existing, mode)]
263
- if not todo: # every page written by an earlier run: only the marker is missing
264
- yield PageItem(rel, None, None, True)
265
- return
266
- for n in todo:
267
- page = pdf[n - 1]
268
- w, h = page.get_size() # points
269
- image = page.render(scale=longest_edge / max(w, h)).to_pil().convert("RGB")
270
- yield PageItem(rel, md_rel(rel, n), image, n == todo[-1])
271
-
272
-
273
- def build_prompt(llm: LLM, mode: str) -> str:
274
- """Chat-template prompt with thinking disabled; grounding adds the "grounding" text."""
275
- content = [{"type": "image"}]
276
- if mode == "grounding":
277
- content.append({"type": "text", "text": GROUNDING_PROMPT})
278
- return llm.get_tokenizer().apply_chat_template(
279
- [{"role": "user", "content": content}],
280
- tokenize=False,
281
- add_generation_prompt=True,
282
- enable_thinking=False,
283
- )
284
-
285
-
286
- def render_outputs(md: str, raw: str, image_size, mode: str, fix_dollars: bool, model: str):
287
- """(relative path, content) pairs for one page: the .md, plus a .json in grounding mode."""
288
- text = raw.strip()
289
- if fix_dollars:
290
- text = fix_escaped_dollars(text)
291
- if mode != "grounding":
292
- return [(md, text)]
293
- blocks = parse_blocks(text)
294
- sidecar = {
295
- "model": model,
296
- "image_size": list(image_size), # size fed to the model; bbox is 0-1000 of this frame
297
- "blocks": [b.to_dict() for b in blocks],
298
- }
299
- # .md before sidecar: a page counts as done in grounding mode only once its .json
300
- # exists, so a write that stops between the two is redone (also when replacing a
301
- # plain-mode .md).
302
- return [
303
- (md, to_markdown(blocks) if blocks else text),
304
- (md[: -len(".md")] + ".json", json.dumps(sidecar, ensure_ascii=False)),
305
- ]
306
-
307
-
308
- def write_outputs(dest: str, pairs: list[tuple[str, str]]):
309
- if not pairs:
310
- return
311
- if is_bucket(dest):
312
- url, prefix = as_bucket_dir(dest)
313
- put_files([(prefix + rel, content) for rel, content in pairs], url) # one upload call
314
- return
315
- for rel, content in pairs:
316
- # Write to a temp file, then rename: a stopped job never leaves a partial .md that
317
- # the next run would count as done.
318
- path = Path(dest) / rel
319
- path.parent.mkdir(parents=True, exist_ok=True)
320
- tmp = path.with_name(f".{path.name}.tmp")
321
- tmp.write_text(content, encoding="utf-8")
322
- os.replace(tmp, path)
323
-
324
-
325
- def main():
326
- parser = argparse.ArgumentParser(
327
- description="OCR images/PDFs from an HF Bucket or directory using LightOnOCR-3, output markdown files.",
328
- formatter_class=argparse.RawDescriptionHelpFormatter,
329
- epilog="""
330
- Modes:
331
- plain markdown transcription (default)
332
- grounding markdown + a .json sidecar of labelled layout blocks (0-1000 boxes)
333
-
334
- Examples:
335
- lighton-ocr3-bucket.py hf://buckets/ns/scans/vol1 hf://buckets/ns/ocr/vol1 --mode grounding
336
- lighton-ocr3-bucket.py /input /output (directories, e.g. -v mounted buckets)
337
- lighton-ocr3-bucket.py hf://buckets/ns/scans /output --include "**/*.jp2"
338
- """,
339
- )
340
- parser.add_argument("input", help="hf://buckets/<ns>/<bucket>[/<prefix>] or a directory of images/PDFs")
341
- parser.add_argument("output", help="hf://buckets/<ns>/<bucket>[/<prefix>] or a directory for the .md files")
342
- parser.add_argument("--model", default=DEFAULT_MODEL, choices=MODELS,
343
- help=f"Model checkpoint (default: {DEFAULT_MODEL})")
344
- parser.add_argument("--mode", default="plain", choices=["plain", "grounding"],
345
- help="plain = markdown; grounding = markdown + .json layout blocks (default: plain)")
346
- parser.add_argument("--include", default=None,
347
- help='Glob relative to the input, e.g. "**/*.jp2" (default: all images and PDFs)')
348
- parser.add_argument("--batch-size", type=int, default=16,
349
- help="Files downloaded, and pages sent to vLLM, per batch (default: 16)")
350
- parser.add_argument("--max-model-len", type=int, default=16384,
351
- help="Max model context length (default: 16384)")
352
- parser.add_argument("--max-tokens", type=int, default=DEFAULT_MAX_TOKENS,
353
- help=f"Max output tokens (default: {DEFAULT_MAX_TOKENS}, the card's vLLM example)")
354
- parser.add_argument("--temperature", type=float, default=DEFAULT_TEMPERATURE,
355
- help=f"Sampling temperature (default: {DEFAULT_TEMPERATURE}, model card)")
356
- parser.add_argument("--top-p", type=float, default=DEFAULT_TOP_P,
357
- help=f"Top-p (default: {DEFAULT_TOP_P}, model card; LightOn's client uses 1.0)")
358
- parser.add_argument("--longest-edge", type=int, default=DEFAULT_LONGEST_EDGE,
359
- help=f"Downscale pages so the longest edge is at most this many pixels; "
360
- f"PDFs render at this size (default: {DEFAULT_LONGEST_EDGE})")
361
- parser.add_argument("--no-fix-dollars", action="store_true",
362
- help="Keep the raw output instead of repairing escaped dollar delimiters")
363
- parser.add_argument("--gpu-memory-utilization", type=float, default=0.8,
364
- help="GPU memory utilization (default: 0.8)")
365
- parser.add_argument("--max-samples", type=int, default=None,
366
- help="Limit the number of input files (files, not pages; a PDF still yields "
367
- "all its pages). Counted before skipping files that are already done.")
368
- parser.add_argument("--overwrite", action="store_true",
369
- help="Redo files that already have output (default: skip them, which resumes a run)")
370
- parser.add_argument("--verbose", action="store_true", help="Print resolved package versions")
371
-
372
- args = parser.parse_args()
373
- if args.max_samples is not None and args.max_samples < 1:
374
- parser.error("--max-samples must be 1 or more")
375
- if args.max_tokens > args.max_model_len:
376
- parser.error(f"--max-tokens ({args.max_tokens}) must be <= --max-model-len ({args.max_model_len})")
377
- for loc in (args.input, args.output):
378
- if is_bucket(loc):
379
- try:
380
- as_bucket_dir(loc)
381
- except ValueError as e:
382
- parser.error(str(e))
383
- if not is_bucket(args.input) and not Path(args.input).is_dir():
384
- parser.error(f"Input directory does not exist: {args.input}")
385
-
386
- check_cuda_availability()
387
-
388
- start_time = time.time()
389
- logger.info(f"Listing inputs in {args.input} ...")
390
- rels = list_inputs(args.input, args.include, args.max_samples)
391
- if not rels:
392
- logger.error(f"No image or PDF files found in {args.input}")
393
- sys.exit(1)
394
- clashes = output_collisions(rels)
395
- if clashes:
396
- logger.error("These inputs would write the same output file(s):")
397
- for clash in clashes[:20]:
398
- logger.error(f" {clash}")
399
- logger.error("Rename them, or narrow the input with --include.")
400
- sys.exit(1)
401
- existing = set() if args.overwrite else list_outputs(args.output)
402
- todo = [rel for rel in rels if not is_done(rel, existing, args.mode)]
403
- skipped = len(rels) - len(todo)
404
- logger.info(f"Found {len(rels)} file(s); {skipped} already done; {len(todo)} to OCR")
405
- if not todo:
406
- logger.info("Nothing to do (--overwrite to redo).")
407
- return
408
-
409
- logger.info(f"Initializing vLLM with {args.model} ({args.mode} mode)...")
410
- # Stock Qwen3_5ForConditionalGeneration arch; gdn_prefill_backend="triton" avoids the
411
- # gated-delta-net prefill path that needs a CUDA JIT toolchain (as in lighton-ocr3.py).
412
- llm = LLM(
413
- model=args.model,
414
- max_model_len=args.max_model_len,
415
- gpu_memory_utilization=args.gpu_memory_utilization,
416
- limit_mm_per_prompt={"image": 1},
417
- gdn_prefill_backend="triton",
418
- )
419
- prompt = build_prompt(llm, args.mode)
420
- sampling_params = SamplingParams(
421
- temperature=args.temperature, top_p=args.top_p, max_tokens=args.max_tokens
422
- )
423
-
424
- pages_done = 0
425
- errors = 0
426
- files_seen = 0
427
- failed: set[str] = set() # inputs with a page that failed: no .complete.<mode> marker this run
428
- open_errors: list[str] = []
429
-
430
- def file_pages(batch):
431
- for rel, path in batch:
432
- try:
433
- yield from iter_pages(rel, path, existing, args.mode, args.longest_edge)
434
- except Exception as e:
435
- logger.error(f"Failed to open {rel}: {e}")
436
- failed.add(rel)
437
- open_errors.append(rel)
438
-
439
- total_batches = (len(todo) + args.batch_size - 1) // args.batch_size
440
- for batch_num, batch in enumerate(iter_local_batches(args.input, todo, args.batch_size), 1):
441
- logger.info(f"Batch {batch_num}/{total_batches} ({files_seen}/{len(todo)} files done)")
442
- files_seen += len(batch)
443
-
444
- # Windows of at most --batch-size pages, rendered lazily.
445
- for window in partition_all(args.batch_size, file_pages(batch)):
446
- pages = [it for it in window if it.image is not None]
447
- outputs = []
448
- if pages:
449
- try:
450
- outputs = llm.generate(
451
- [{"prompt": prompt, "multi_modal_data": {"image": it.image}} for it in pages],
452
- sampling_params,
453
- )
454
- except Exception as e:
455
- # Write nothing: these pages are retried on the next run.
456
- logger.error(f"Batch {batch_num} failed: {e}")
457
- errors += len(pages)
458
- failed.update(it.rel for it in pages)
459
- continue
460
-
461
- pairs = []
462
- for it, output in zip(pages, outputs, strict=True):
463
- pairs.extend(render_outputs(it.md, output.outputs[0].text, it.image.size, args.mode,
464
- not args.no_fix_dollars, args.model))
465
- try:
466
- write_outputs(args.output, pairs)
467
- pages_done += len(pages)
468
- except Exception as e:
469
- logger.error(f"Writing batch {batch_num} failed: {e}")
470
- errors += len(pages)
471
- failed.update(it.rel for it in window)
472
- continue
473
- # Markers in a separate write, only after the page outputs are stored.
474
- finished = [it.rel for it in window if it.last and it.rel not in failed]
475
- try:
476
- write_outputs(args.output, [(marker_rel(rel, args.mode), "ok\n") for rel in finished])
477
- except Exception as e:
478
- logger.error(f"Writing completion markers failed (pages are kept): {e}")
479
- failed.update(finished)
480
-
481
- errors += len(open_errors)
482
- elapsed = time.time() - start_time
483
- elapsed_str = f"{elapsed / 60:.1f} min" if elapsed > 60 else f"{elapsed:.1f}s"
484
- logger.info("=" * 50)
485
- logger.info(f"Done! Wrote {pages_done} page(s) from {files_seen} file(s) in {elapsed_str}")
486
- logger.info(f" Output: {args.output}")
487
- logger.info(f" Skipped (already done): {skipped}")
488
- logger.info(f" Errors (no output, retried next run): {errors}")
489
- if failed:
490
- listed = sorted(failed)
491
- logger.warning(f" Inputs with failures ({len(listed)}): {', '.join(listed[:20])}"
492
- + (" ..." if len(listed) > 20 else ""))
493
- if args.overwrite:
494
- logger.warning(" With --overwrite these keep their previous output: re-run them with --overwrite.")
495
- if pages_done:
496
- logger.info(f" Speed: {pages_done / elapsed:.2f} pages/sec")
497
-
498
- if args.verbose:
499
- import importlib.metadata
500
-
501
- logger.info("--- Package versions ---")
502
- for pkg in ["vllm", "transformers", "torch", "pillow", "imagecodecs", "bucketbag", "lightonocr"]:
503
- try:
504
- logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
505
- except importlib.metadata.PackageNotFoundError:
506
- logger.info(f" {pkg}: not installed")
507
-
508
-
509
- if __name__ == "__main__":
510
- if len(sys.argv) == 1:
511
- print("=" * 60)
512
- print("LightOnOCR-3 Bucket Script")
513
- print("=" * 60)
514
- print("\nOCR images/PDFs from an HF Bucket or directory → markdown files")
515
- print("(+ .json layout blocks in grounding mode). Re-running resumes.")
516
- print()
517
- print("Usage:")
518
- print(" lighton-ocr3-bucket.py INPUT OUTPUT (hf://buckets/... URLs or directories)")
519
- print()
520
- print("HF Jobs (image, flavor + secrets from the [tool.hf-jobs] header; hf CLI 1.32+):")
521
- print(" hf jobs uv run \\")
522
- print(" https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3-bucket.py \\")
523
- print(" hf://buckets/ns/scans/vol1 hf://buckets/ns/ocr/vol1 --mode grounding")
524
- print()
525
- print("For full help: uv run --with vllm==0.30.0 lighton-ocr3-bucket.py --help")
526
- sys.exit(0)
527
-
528
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lighton-ocr3-saturate.py DELETED
@@ -1,475 +0,0 @@
1
- # /// script
2
- # requires-python = ">=3.11"
3
- # dependencies = [
4
- # "saturate[hf]==0.3.0",
5
- # "pillow>=10",
6
- # # LightOn's official client, pinned to a commit (not on PyPI). Used for its page
7
- # # resize, grounding parser and dollar-delimiter repair so outputs match upstream.
8
- # "lightonocr @ https://github.com/lightonai/LightOnOCR/archive/36755d461be079737860a5f03ae0c803501269e9.tar.gz",
9
- # ]
10
- #
11
- # [tool.hf-jobs]
12
- # image = "vllm/vllm-openai:v0.30.0"
13
- # flavor = "a10g-small"
14
- # timeout = "4h"
15
- # secrets = ["HF_TOKEN"]
16
- # ///
17
- """
18
- Convert document images to markdown (or layout blocks) using LightOnOCR-3 via saturate.
19
-
20
- Same model, prompt modes, sampling and page preparation as `lighton-ocr3.py`, but the
21
- script starts `vllm serve` in the Job and the `saturate` library sends the pages to it:
22
- many pages in flight, resumable parquet output and durable error rows. Use this recipe
23
- for large runs.
24
-
25
- Run on HF Jobs. The script starts the server itself; its [tool.hf-jobs] header declares
26
- the image that provides `vllm`, the hardware and the HF_TOKEN secret (`hf` CLI 1.32+).
27
- Flags on the command line override the header:
28
-
29
- hf jobs uv run --detach \\
30
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3-saturate.py \\
31
- <input-dataset> <output-dataset>
32
-
33
- Smoke test first with --max-samples 10. Layout blocks with labels and boxes:
34
-
35
- hf jobs uv run --detach \\
36
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3-saturate.py \\
37
- <input-dataset> <output-dataset> --mode grounding
38
-
39
- Output: the output repo holds `data/part-*.parquet` with rows
40
- `{id, markdown, raw, finish_reason, layout_blocks, model, prompt_tokens, completion_tokens,
41
- error}` keyed by the input row id (`--id-column`, or `<repo>:<config>:<split>:<000000000>`
42
- by default). Read it with `saturate.read_output`, which keeps one row per id (a success
43
- over an earlier error). `datasets.load_dataset(<output>, data_dir="data")` returns every
44
- record, so after a --retry-errors run it also holds the old error rows: drop rows with an
45
- `error` before you join back to the input on id. Re-running the same command skips
46
- finished rows; --retry-errors re-admits failed ones.
47
-
48
- `finish_reason` = "length" marks a page that hit --max-tokens (long tables, or the model
49
- repeating a line). --repair-max-tokens N sends those pages once more, at the end of the
50
- run, with a cap of N tokens and temperature 0.1, and writes the results to `repair/`
51
- (`load_dataset(<output>, data_dir="repair")`); join on id and prefer the repair row where
52
- its finish_reason is "stop". A restarted run also repairs the pages that an earlier,
53
- interrupted run saved as truncated.
54
-
55
- Models (Apache-2.0):
56
- lightonai/LightOnOCR-3-0.8B (default) 85.5 olmOCR-Bench, 74.6 ParseBench
57
- lightonai/LightOnOCR-3-4B 86.3 olmOCR-Bench, 75.1 ParseBench
58
- LightOnOCR-3-1B is not supported: it keeps the LightOnOCR-2 (Pixtral) architecture, and
59
- LightOn reports that transformers 5.17 (the version in the vLLM 0.30.0 image) breaks it.
60
-
61
- Upstream settings kept:
62
- - Serve flags: the LightOnOCR README's flags for the 0.8B and 4B (`--max-model-len 18000`,
63
- thinking off, `--mm-processor-cache-gb 0`, `--no-enable-prefix-caching`,
64
- `--limit-mm-per-prompt '{"image": 1}'`). vLLM 0.30.0, the version LightOn tests.
65
- - Prompt modes: plain sends the image alone; grounding adds the text "grounding". The card
66
- says other instructions are out of distribution.
67
- - Sampling: the model card's vLLM example (temperature 0.2, top_p 0.9, max_tokens 4096).
68
- - Pages: downscaled to 2048 px on the longest edge with LightOn's own resize (never
69
- upscaled), sent as PNG, as the official client does. The PNG uses a fast compression
70
- level; PNG is lossless, so the server decodes the same pixels.
71
- - Escaped dollar delimiters are repaired (`\\$x\\$` -> `$x$`) as the client does; `raw`
72
- keeps the model's text.
73
-
74
- Speed settings: pages are prepared in `--prepare-workers` threads (default: the CPU_CORES
75
- that HF Jobs sets), and saturate's adaptive window sets how many pages are in flight, up to
76
- a cap that fits the Job's memory (window_cap below). `--window N` pins it instead. The
77
- server also gets `--max-num-batched-tokens 16384`, and 4 API server processes on flavors
78
- with 12 or more CPU cores (see SERVING). Pass --serve-args "--api-server-count N" to choose.
79
-
80
- Measured speed, LightOnOCR-3-0.8B (2026-11-05, vLLM 0.30.0). 600 pages: 350 book pages from
81
- finebooks/bhl-impact-gt and 250 pages of typed industry documents, all fitted to 2048 px.
82
- Steady state, excluding the server start (about 4 min, also paid by lighton-ocr3.py):
83
-
84
- flavor pages/s $ per 1,000 pages lighton-ocr3.py (offline batches)
85
- a10g-small 2.2 0.12 0.90 pages/s, $0.31
86
- l4x1 1.6 0.14
87
- a10g-large 2.7 0.15
88
- a100-large 7.2 0.10 1.27 pages/s, $0.55
89
- rtx-pro-6000 10.0 0.08
90
-
91
- The 4B on a100-large (one API server): 2.7 pages/s, $0.26 per 1,000 pages; on these book
92
- pages its character error rate was higher than the 0.8B's (0.10 mean, 0.023 median, one
93
- run), so check a sample before paying for it. The header's a10g-small is a good default
94
- for small and medium runs; for large runs add --flavor rtx-pro-6000 (or a100-large). In
95
- every run the outputs differed from lighton-ocr3.py's no more than two runs of this recipe
96
- differ from each other (sampling at temperature 0.2). The character error rate on the 282
97
- book pages with at least 20 characters of ground truth was 0.077 to 0.083 mean and 0.020
98
- median in every 0.8B run.
99
-
100
- Truncation and repair: 9 to 12 of the 600 pages stopped at max_tokens 4096 in each run,
101
- most of them typed tables. With --repair-max-tokens 12000, 8 of 12 such pages finished:
102
- 3 in fewer than 4,096 tokens on the second try, and 5 long pages that needed 4,900 to
103
- 6,100 tokens. The other 4 hit the cap again. The pass added 22% to the run's output
104
- tokens. With --repair-max-tokens 8192 (suggested), 5 of 9 such pages finished, the same 4
105
- hit the cap again, and the pass added 16%. Pages that hit the cap on both tries keep
106
- their first output in data/.
107
-
108
- The SERVING dict below is the per-model tuning prior. Agents can `ast.literal_eval` it
109
- without running the script; the script itself consumes it.
110
- """
111
-
112
- import argparse
113
- import base64
114
- import hashlib
115
- import io
116
- import json
117
- import os
118
- import shlex
119
- import sys
120
- import tempfile
121
-
122
- # Serving starting values for LightOnOCR-3 (0.8B and 4B). Per-value provenance:
123
- # - image: vLLM 0.30.0, the version LightOn's client pins and tests (0.27.1 makes the
124
- # models loop, per the LightOnOCR README).
125
- # - context 18000 and serve_args: the LightOnOCR README "Models" table for the 0.8B and 4B,
126
- # plus its `--limit-mm-per-prompt '{"image": 1}'`.
127
- # - max_tokens/temperature/top_p: the model card's vLLM example, verbatim.
128
- # - longest_edge 2048: the card's rendering tip and the client's page size for these models.
129
- # - patch 32: 16 px patches with a 2x2 merge, so a 2048x2048 page is at most 64x64 = 4,096
130
- # image tokens (used for the context check).
131
- # - --max-num-batched-tokens 16384: speed only. vLLM 0.30 serves with 2048 on A10G, L4 and
132
- # A100 (8192 on other GPUs of 70 GB or more), less than one page's image tokens. Measured on a100-large:
133
- # 6.20 and 6.30 pages/s against 5.83 without it, outputs within the run-to-run noise.
134
- # - pages_per_gib: see window_cap().
135
- # - api_servers 4 when CPU_CORES >= 12: speed only. With one vLLM API server, a100-large and
136
- # rtx-pro-6000 had 128-256 pages in flight but only 36-60 running in the engine and none
137
- # waiting: the rest queued for image preprocessing in the API process. Measured, 4 API
138
- # servers against one: a100-large 7.29 and 7.18 against 6.20 and 6.30 pages/s,
139
- # rtx-pro-6000 10.0 against 9.15, a10g-large 2.74 against 2.49; outputs within the
140
- # run-to-run noise. Small flavors (a10g-small 3 cores, l4x1 8) keep one, to leave CPU
141
- # for page preparation.
142
- SERVING = {
143
- "models": ["lightonai/LightOnOCR-3-0.8B", "lightonai/LightOnOCR-3-4B"],
144
- "image": "vllm/vllm-openai:v0.30.0",
145
- "context": 18000,
146
- "serve_args": [
147
- "--default-chat-template-kwargs", '{"enable_thinking": false}',
148
- "--limit-mm-per-prompt", '{"image": 1}',
149
- "--mm-processor-cache-gb", "0",
150
- "--no-enable-prefix-caching",
151
- "--max-num-batched-tokens", "16384",
152
- ],
153
- "pages_per_gib": 6,
154
- "api_servers": 4,
155
- "api_servers_min_cores": 12,
156
- "max_tokens": 4096,
157
- "temperature": 0.2,
158
- "top_p": 0.9,
159
- "repair_temperature": 0.1,
160
- "longest_edge": 2048,
161
- "patch": 32,
162
- }
163
-
164
-
165
- def window_cap() -> int:
166
- """Most pages in flight that this machine's memory allows.
167
-
168
- Every page in flight holds about 0.1 GiB of image data on the host (the client's copy and
169
- the server's preprocessed image), on top of 7 to 9 GiB for the engine itself. On
170
- a10g-small (14.9 GiB limit), 64 pages in flight reached the limit and the Job stopped
171
- making progress; 32 peaked at 12.0 GiB, and up to 39 peaked at 13.0 and 14.8 GiB on two
172
- runs. So the window may grow by SERVING "pages_per_gib" pages per GiB above 10 GiB: 29 on
173
- a10g-small (which is GPU-bound from about 20 pages in flight), about 100 on l4x1, the full
174
- 512 on a100-large. The limit is read from the container (cgroup v2), then from the MEMORY
175
- variable that HF Jobs sets.
176
- """
177
- limit_gib = None
178
- try:
179
- with open("/sys/fs/cgroup/memory.max") as handle:
180
- value = handle.read().strip()
181
- if value != "max":
182
- limit_gib = int(value) / 2**30
183
- except (OSError, ValueError):
184
- pass
185
- if limit_gib is None and os.environ.get("MEMORY"):
186
- try: # e.g. "16.0G" (decimal gigabytes)
187
- limit_gib = float(os.environ["MEMORY"].upper().rstrip("GIB ")) * 1e9 / 2**30
188
- except ValueError:
189
- pass
190
- if limit_gib is None:
191
- return 512
192
- return max(8, min(512, int((limit_gib - 10) * SERVING["pages_per_gib"])))
193
-
194
-
195
- def flag_value(tokens: list[str], name: str):
196
- """Last value given for `name` in a `vllm serve` argument list (`--x v` or `--x=v`), else None."""
197
- value = None
198
- for index, token in enumerate(tokens):
199
- if token == name and index + 1 < len(tokens):
200
- value = tokens[index + 1]
201
- elif token.startswith(name + "="):
202
- value = token.split("=", 1)[1]
203
- return value
204
-
205
-
206
- def saved_truncations(output_dataset: str) -> set:
207
- """Ids whose saved result in data/ stopped at max_tokens and that have no saved repair.
208
-
209
- A restarted run skips rows already in data/, so without this the pages truncated
210
- before the restart would never reach the repair pass. Reads only three columns.
211
- """
212
- import fsspec
213
- import pyarrow.parquet as pq
214
-
215
- def records(subdir, columns):
216
- fs, root = fsspec.core.url_to_fs(f"hf://datasets/{output_dataset}/{subdir}")
217
- if not fs.exists(root):
218
- return
219
- for path in fs.glob(f"{root}/part-*.parquet"):
220
- with fs.open(path, "rb") as handle:
221
- yield from pq.read_table(handle, columns=columns).to_pylist()
222
-
223
- finish = {}
224
- for record in records("data", ["id", "error", "finish_reason"]):
225
- if record["error"] is None:
226
- finish[record["id"]] = record["finish_reason"]
227
- repaired = {r["id"] for r in records("repair", ["id", "error"]) if r["error"] is None}
228
- return {row_id for row_id, reason in finish.items() if reason == "length" and row_id not in repaired}
229
-
230
-
231
- def max_image_tokens(longest_edge: int) -> int:
232
- """Upper bound on the image tokens of a page fitted to longest_edge (square page)."""
233
- side = -(-longest_edge // SERVING["patch"])
234
- return side * side
235
-
236
-
237
- def to_pil(value):
238
- from PIL import Image
239
-
240
- if isinstance(value, Image.Image):
241
- return value
242
- if isinstance(value, dict) and value.get("bytes"):
243
- return Image.open(io.BytesIO(value["bytes"]))
244
- if isinstance(value, dict) and value.get("path"):
245
- return Image.open(value["path"])
246
- if isinstance(value, (bytes, bytearray)):
247
- return Image.open(io.BytesIO(value))
248
- raise ValueError(f"unsupported image value: {type(value)}")
249
-
250
-
251
- def page_png(value, longest_edge: int) -> bytes:
252
- """RGB page fitted to longest_edge with LightOn's resize, as PNG bytes.
253
-
254
- compress_level=1 instead of Pillow's default 6: PNG is lossless at every level, so the
255
- pixels are identical, and level 1 encodes several times faster (CPU is the limit on
256
- small flavors).
257
- """
258
- from lightonocr import fit
259
-
260
- image = fit(to_pil(value).convert("RGB"), longest_edge)
261
- buffer = io.BytesIO()
262
- image.save(buffer, format="PNG", compress_level=1)
263
- return buffer.getvalue()
264
-
265
-
266
- def chat_request(model: str, png: bytes, mode: str, max_tokens: int, temperature: float, top_p: float) -> dict:
267
- """One page as the client sends it: the image, plus the word "grounding" in grounding mode."""
268
- from lightonocr import GROUNDING_PROMPT
269
-
270
- url = "data:image/png;base64," + base64.b64encode(png).decode()
271
- content = [{"type": "image_url", "image_url": {"url": url}}]
272
- if mode == "grounding":
273
- content.append({"type": "text", "text": GROUNDING_PROMPT})
274
- return {
275
- "model": model,
276
- "messages": [{"role": "user", "content": content}],
277
- "max_tokens": max_tokens,
278
- "temperature": temperature,
279
- "top_p": top_p,
280
- "chat_template_kwargs": {"enable_thinking": False},
281
- }
282
-
283
-
284
- def postprocess(raw: str, mode: str, fix_dollars: bool):
285
- """Return (markdown, layout_blocks JSON or None) for one model output, as lighton-ocr3.py."""
286
- from lightonocr import fix_escaped_dollars, parse_blocks, to_markdown
287
-
288
- text = fix_escaped_dollars(raw) if fix_dollars else raw
289
- if mode != "grounding":
290
- return text, None
291
- blocks = parse_blocks(text)
292
- if not blocks:
293
- return text, json.dumps([]) # no markers parsed: keep the text so nothing is lost
294
- return to_markdown(blocks), json.dumps([b.to_dict() for b in blocks], ensure_ascii=False)
295
-
296
-
297
- def main():
298
- ap = argparse.ArgumentParser(description="LightOnOCR-3 batch OCR via saturate")
299
- ap.add_argument("input_dataset", help="Input dataset repo id (rows with an image column)")
300
- ap.add_argument("output_dataset", help="Output dataset repo id (created private if missing)")
301
- ap.add_argument("--model", default=SERVING["models"][0], choices=SERVING["models"])
302
- ap.add_argument("--mode", default="plain", choices=["plain", "grounding"],
303
- help="plain = markdown; grounding = labelled layout blocks with 0-1000 boxes")
304
- ap.add_argument("--image-column", default="image")
305
- ap.add_argument("--config", default=None, help="Dataset config name")
306
- ap.add_argument("--split", default="train")
307
- ap.add_argument("--id-column", default=None,
308
- help="Column to use as row id (default: split-index ids)")
309
- ap.add_argument("--max-samples", "--limit", dest="limit", type=int, default=None,
310
- help="Process only the first N rows (smoke test)")
311
- ap.add_argument("--max-tokens", type=int, default=SERVING["max_tokens"],
312
- help="Output cap per page (default 4096, the model card's)")
313
- ap.add_argument("--temperature", type=float, default=SERVING["temperature"])
314
- ap.add_argument("--top-p", type=float, default=SERVING["top_p"],
315
- help="Default 0.9, the model card's; LightOn's client uses 1.0")
316
- ap.add_argument("--longest-edge", type=int, default=SERVING["longest_edge"],
317
- help="Downscale pages to at most this many pixels on the longest edge")
318
- ap.add_argument("--no-fix-dollars", action="store_true",
319
- help="Keep the model's text in `markdown` without repairing escaped dollars")
320
- ap.add_argument("--repair-max-tokens", type=int, default=0,
321
- help="Re-send pages that hit --max-tokens once, with this cap and "
322
- "temperature 0.1, into repair/ (default 0: off; 8192 suggested)")
323
- ap.add_argument("--window", default="auto",
324
- help="Pages in flight: 'auto' (saturate adapts it) or a fixed number")
325
- ap.add_argument("--prepare-workers", type=int, default=None,
326
- help="Threads that decode, resize and encode pages (default: CPU_CORES)")
327
- ap.add_argument("--serve-args", default="",
328
- help="Extra `vllm serve` flags, one quoted string, e.g. "
329
- "\"--max-num-batched-tokens 16384\"")
330
- ap.add_argument("--retry-errors", action="store_true",
331
- help="Re-admit rows whose only record is an error row")
332
- args = ap.parse_args()
333
-
334
- user_serve_args = shlex.split(args.serve_args)
335
- if args.longest_edge < 1:
336
- ap.error("--longest-edge must be at least 1")
337
- try: # --serve-args may set its own --max-model-len; vLLM uses the last one given
338
- context = int(flag_value(user_serve_args, "--max-model-len") or SERVING["context"])
339
- except ValueError:
340
- ap.error("--max-model-len in --serve-args must be a whole number of tokens")
341
- room = context - max_image_tokens(args.longest_edge) - 64
342
- for flag, value in (("--max-tokens", args.max_tokens), ("--repair-max-tokens", args.repair_max_tokens)):
343
- if value > room:
344
- ap.error(f"{flag} {value} can overflow the {context}-token context with a "
345
- f"{args.longest_edge} px page; use at most {room}")
346
- if args.max_tokens < 1:
347
- ap.error("--max-tokens must be at least 1")
348
- if args.repair_max_tokens and args.repair_max_tokens <= args.max_tokens:
349
- ap.error("--repair-max-tokens must be larger than --max-tokens")
350
- if args.window != "auto" and not (args.window.isdigit() and int(args.window) >= 1):
351
- ap.error("--window must be 'auto' or a number of at least 1")
352
-
353
- import pyarrow as pa
354
- from saturate import Auto, Engine, Fixed, dataset_rows, pump
355
-
356
- if args.id_column is None:
357
- ids = "index"
358
- elif args.id_column in ("index", "content"):
359
- # saturate reads these two names as id strategies, so a column with one of them
360
- # needs a callable. It returns the raw value, so saturate still refuses a null id.
361
- def ids(example):
362
- return example[args.id_column]
363
- else:
364
- ids = args.id_column
365
-
366
- rows = dataset_rows(
367
- args.input_dataset, config=args.config, split=args.split,
368
- columns=[args.image_column], ids=ids, limit=args.limit,
369
- )
370
-
371
- # Declared, so a part holding only error rows has the same columns as the rest
372
- # (datasets.load_dataset reads every part with one schema).
373
- schema = pa.schema([
374
- ("id", pa.string()), ("error", pa.string()), ("markdown", pa.string()), ("raw", pa.string()),
375
- ("finish_reason", pa.string()), ("layout_blocks", pa.string()), ("model", pa.string()),
376
- ("prompt_tokens", pa.int64()), ("completion_tokens", pa.int64()),
377
- ]) # fmt: skip
378
-
379
- # Pages that hit --max-tokens, kept on local disk for the repair pass: those truncated
380
- # in this run (stashed in parse) and those saved as truncated by an earlier, interrupted
381
- # run (stashed as the stream passes them; the main pass skips them).
382
- repair_dir = tempfile.mkdtemp(prefix="lighton-ocr3-repair-") if args.repair_max_tokens else None
383
- earlier = saved_truncations(args.output_dataset) if repair_dir else set()
384
- truncated = []
385
-
386
- def stash(row_id, image):
387
- path = os.path.join(repair_dir, hashlib.sha1(row_id.encode()).hexdigest() + ".png")
388
- with open(path, "wb") as handle:
389
- handle.write(page_png(image, args.longest_edge))
390
- truncated.append((row_id, path))
391
-
392
- def to_request(row):
393
- png = page_png(row[args.image_column], args.longest_edge)
394
- return chat_request(args.model, png, args.mode, args.max_tokens, args.temperature, args.top_p)
395
-
396
- def make_parse(stash_truncated: bool):
397
- def parse(row, body):
398
- choice = body["choices"][0]
399
- raw = (choice["message"].get("content") or "").strip()
400
- markdown, blocks = postprocess(raw, args.mode, fix_dollars=not args.no_fix_dollars)
401
- usage = body.get("usage") or {}
402
- if stash_truncated and choice.get("finish_reason") == "length":
403
- stash(row["__id"], row[args.image_column])
404
- return {
405
- "markdown": markdown,
406
- "raw": raw,
407
- "finish_reason": choice.get("finish_reason"),
408
- "layout_blocks": blocks,
409
- "model": args.model,
410
- "prompt_tokens": usage.get("prompt_tokens"),
411
- "completion_tokens": usage.get("completion_tokens"),
412
- }
413
- return parse
414
-
415
- def with_ids(source):
416
- # Keep each row's id on the row, so parse can name the page it stashes for repair.
417
- for row_id, row in source:
418
- if row_id in earlier:
419
- stash(row_id, row[args.image_column])
420
- yield row_id, {**row, "__id": row_id}
421
-
422
- cap = window_cap()
423
- if args.window == "auto":
424
- window = Auto(initial=min(64, cap), max_limit=cap)
425
- print(f"window: auto, at most {cap} pages in flight (host memory)", file=sys.stderr)
426
- else:
427
- window = Fixed(int(args.window))
428
- if int(args.window) > cap:
429
- print(f"warning: --window {args.window} is above the {cap} pages this machine's "
430
- "memory allows; the Job may run out of memory", file=sys.stderr)
431
- cores = max(1, int(float(os.environ.get("CPU_CORES") or "4")))
432
- workers = args.prepare_workers if args.prepare_workers is not None else cores
433
- extra = [
434
- "--max-model-len", str(SERVING["context"]),
435
- *SERVING["serve_args"],
436
- *user_serve_args,
437
- ]
438
- # Several API server processes share the image decoding and preprocessing, which one
439
- # process cannot keep up with on a fast GPU. Only where there are cores to spare.
440
- if cores >= SERVING["api_servers_min_cores"] and flag_value(extra, "--api-server-count") is None:
441
- extra += ["--api-server-count", str(SERVING["api_servers"])]
442
- print(f"server: --api-server-count {SERVING['api_servers']} ({cores} CPU cores)", file=sys.stderr)
443
-
444
- output = f"hf://datasets/{args.output_dataset}/data"
445
- with Engine(args.model, engine="vllm", extra_args=extra) as endpoint:
446
- stats = pump(with_ids(rows) if repair_dir else rows, to_request, make_parse(bool(repair_dir)),
447
- endpoint, output, window=window, prepare_workers=workers,
448
- retry_errors=args.retry_errors, schema=schema)
449
- print("LIGHTON_OCR3_SATURATE " + stats.to_json(), flush=True)
450
-
451
- if repair_dir and truncated:
452
- print(f"repair: re-sending {len(truncated)} pages that hit --max-tokens "
453
- f"with a cap of {args.repair_max_tokens}", file=sys.stderr, flush=True)
454
-
455
- def repair_rows():
456
- for row_id, path in truncated:
457
- with open(path, "rb") as handle:
458
- yield row_id, {"png": handle.read()}
459
-
460
- def repair_request(row):
461
- return chat_request(args.model, row["png"], args.mode, args.repair_max_tokens,
462
- SERVING["repair_temperature"], args.top_p)
463
-
464
- repair_stats = pump(repair_rows(), repair_request, make_parse(False), endpoint,
465
- f"hf://datasets/{args.output_dataset}/repair", window=window,
466
- retry_errors=args.retry_errors, schema=schema)
467
- print("LIGHTON_OCR3_SATURATE_REPAIR " + repair_stats.to_json(), flush=True)
468
-
469
- print(f"https://huggingface.co/datasets/{args.output_dataset} "
470
- f"({stats.rows_processed} ok, {stats.rows_failed} error rows, "
471
- f"{len(truncated) if repair_dir else 'n/a'} truncated pages re-sent to repair/)", file=sys.stderr)
472
-
473
-
474
- if __name__ == "__main__":
475
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lighton-ocr3.py DELETED
@@ -1,810 +0,0 @@
1
- # /// script
2
- # requires-python = ">=3.11"
3
- # dependencies = [
4
- # "datasets>=4.0.0",
5
- # "huggingface-hub",
6
- # "pillow",
7
- # "toolz",
8
- # # LightOn's official client, pinned to a commit (not on PyPI). Used for its
9
- # # parser, page resize and dollar-delimiter repair so outputs match upstream.
10
- # "lightonocr @ https://github.com/lightonai/LightOnOCR/archive/36755d461be079737860a5f03ae0c803501269e9.tar.gz",
11
- # ]
12
- #
13
- # [tool.hf-jobs]
14
- # image = "vllm/vllm-openai:v0.30.0"
15
- # python = "/usr/bin/python3"
16
- # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
17
- # flavor = "a10g-small"
18
- # secrets = ["HF_TOKEN"]
19
- # ///
20
-
21
- """
22
- Convert document images to markdown (or layout blocks) using LightOnOCR-3 with vLLM.
23
-
24
- LightOnOCR-3 is LightOn's third generation of end-to-end OCR models. The 4B and 0.8B
25
- variants use the stock Qwen3.5 vision-language architecture. Besides plain
26
- transcription, they have a grounding mode: every block of the page comes back with a
27
- label (title, text, table, chart, image, ...) and a bounding box. Images get a short
28
- description and charts become an HTML table of their data points.
29
-
30
- Models (Apache-2.0):
31
- lightonai/LightOnOCR-3-4B (default) 86.3 olmOCR-Bench, 75.1 ParseBench
32
- lightonai/LightOnOCR-3-0.8B 85.5 olmOCR-Bench, 74.6 ParseBench
33
- LightOnOCR-3-1B is not supported here: it keeps the LightOnOCR-2 (Pixtral)
34
- architecture and needs a different vLLM/transformers pin.
35
-
36
- Run on HF Jobs (needs `hf` CLI 1.32+; the [tool.hf-jobs] header above sets the
37
- vllm/vllm-openai:v0.30.0 image, a10g-small flavor and HF_TOKEN secret):
38
-
39
- hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3.py \\
40
- input-dataset output-dataset --max-samples 10
41
-
42
- # Layout blocks with labels and boxes, smaller model
43
- hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3.py \\
44
- input-dataset output-dataset --mode grounding --model lightonai/LightOnOCR-3-0.8B
45
-
46
- Run on your own GPU (vLLM and torch come from the image on Jobs, so add them here):
47
-
48
- uv run --with vllm==0.30.0 lighton-ocr3.py input-dataset output-dataset
49
-
50
- For large scans with very small type, try a higher --longest-edge and --max-tokens.
51
-
52
- For large runs use lighton-ocr3-saturate.py: same model, prompts and sampling, served by
53
- vLLM with many pages in flight (measured 2.4x the pages per second on a10g-small, 5.7x on
54
- a100-large), with resumable output.
55
-
56
- The image is pinned to vLLM 0.30.0 because LightOn's client reports that vLLM 0.27.1
57
- makes the models loop and 0.30.0 is the version they test. Loosen the pin once a newer
58
- vLLM is checked against the same outputs.
59
-
60
- Modes:
61
- - plain (default): the image alone -> markdown transcription. Same as LightOnOCR-2.
62
- - grounding: the image + the text "grounding" -> one `![label](x1,y1,x2,y2)` block per
63
- region, coordinates normalised to 0-1000. The output column gets the block texts
64
- joined as markdown; the --blocks-column gets the parsed blocks as JSON
65
- ([{label, bbox, text, continues}, ...]). Grounding adds about 25% output tokens.
66
- The card says other instructions are out of distribution, so there is no custom prompt.
67
-
68
- Sampling matches the model card's vLLM example: temperature 0.2, top_p 0.9,
69
- max_tokens 4096, thinking disabled. (LightOn's client defaults to top_p 1.0 for
70
- LightOnOCR-3; pass --top-p 1.0 to match it.) Pre- and post-processing follow the
71
- official client (lightonocr/render.py, client.py): pages are downscaled to 2048 px on
72
- the longest edge (the card's rendering tip; the processor does no further resizing),
73
- and escaped dollar delimiters are repaired (`\\$x\\$` -> `$x$`) on every output.
74
- """
75
-
76
- import argparse
77
- import io
78
- import json
79
- import logging
80
- import os
81
- import sys
82
- import time
83
- from datetime import datetime
84
- from typing import Any, Dict, Union
85
-
86
- import torch
87
- from datasets import load_dataset
88
- from huggingface_hub import DatasetCard, hf_hub_download, login
89
- from lightonocr import (
90
- DEFAULT_LONGEST_EDGE,
91
- GROUNDING_PROMPT,
92
- fit,
93
- fix_escaped_dollars,
94
- parse_blocks,
95
- to_markdown,
96
- )
97
- from PIL import Image
98
- from toolz import partition_all
99
-
100
- # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
101
- # default uv-script image lacks (engine init then crashes). On the vllm/vllm-openai image it's
102
- # a harmless no-op.
103
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
104
- # DeepGEMM's init asserts on a missing nvcc (non-fatal traceback); OCR doesn't need it.
105
- os.environ.setdefault("VLLM_USE_DEEP_GEMM", "0")
106
- from vllm import LLM, SamplingParams
107
-
108
- logging.basicConfig(level=logging.INFO)
109
- logger = logging.getLogger(__name__)
110
-
111
- MODELS = ["lightonai/LightOnOCR-3-4B", "lightonai/LightOnOCR-3-0.8B"]
112
- DEFAULT_MODEL = MODELS[0]
113
-
114
- # Sampling from the model card's vLLM example (temperature 0.2, top_p 0.9, max_tokens 4096).
115
- DEFAULT_TEMPERATURE = 0.2
116
- DEFAULT_TOP_P = 0.9
117
- DEFAULT_MAX_TOKENS = 4096
118
-
119
-
120
- def check_cuda_availability():
121
- """Check if CUDA is available and exit if not."""
122
- if not torch.cuda.is_available():
123
- logger.error("CUDA is not available. This script requires a GPU.")
124
- logger.error("Please run on a machine with a CUDA-capable GPU.")
125
- sys.exit(1)
126
- else:
127
- logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
128
-
129
-
130
- def ensure_output_columns_free(dataset, columns, overwrite=False):
131
- """Fail fast if an output column would collide with an existing input column.
132
-
133
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
134
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
135
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
136
- column(s) here instead (logged) so the later add_column is clean.
137
- """
138
- clash = [c for c in columns if c in dataset.column_names]
139
- if not clash:
140
- return dataset
141
- if overwrite:
142
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
143
- return dataset.remove_columns(clash)
144
- logger.error(
145
- f"Output column(s) {clash} already exist in the input dataset "
146
- f"(columns: {dataset.column_names})."
147
- )
148
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
149
- sys.exit(1)
150
-
151
-
152
- def to_pil_image(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:
153
- """Convert a dataset image cell (PIL image, bytes dict, or path) to RGB PIL."""
154
- if isinstance(image, Image.Image):
155
- pil_img = image
156
- elif isinstance(image, dict) and "bytes" in image:
157
- pil_img = Image.open(io.BytesIO(image["bytes"]))
158
- elif isinstance(image, str):
159
- pil_img = Image.open(image)
160
- else:
161
- raise ValueError(f"Unsupported image type: {type(image)}")
162
- return pil_img.convert("RGB")
163
-
164
-
165
- def build_prompt(llm: LLM, mode: str) -> str:
166
- """Chat-template prompt for one page, with thinking disabled.
167
-
168
- plain sends the image alone; grounding adds the text "grounding" after it
169
- (client.py). The 0.8B and 4B were trained without thinking, so the template is
170
- rendered with enable_thinking=False, as the card and client do.
171
- """
172
- content = [{"type": "image"}]
173
- if mode == "grounding":
174
- content.append({"type": "text", "text": GROUNDING_PROMPT})
175
- return llm.get_tokenizer().apply_chat_template(
176
- [{"role": "user", "content": content}],
177
- tokenize=False,
178
- add_generation_prompt=True,
179
- enable_thinking=False,
180
- )
181
-
182
-
183
- def postprocess_output(text: str, mode: str, fix_dollars: bool):
184
- """Return (markdown, blocks_json or None) for one raw model output."""
185
- text = text.strip()
186
- if fix_dollars:
187
- text = fix_escaped_dollars(text)
188
- if mode != "grounding":
189
- return text, None
190
- blocks = parse_blocks(text)
191
- if not blocks:
192
- # No markers parsed: keep the raw text so nothing is lost.
193
- return text, json.dumps([])
194
- markdown = to_markdown(blocks)
195
- return markdown, json.dumps([b.to_dict() for b in blocks], ensure_ascii=False)
196
-
197
-
198
- def jobs_flavor() -> str:
199
- """Return the HF Jobs hardware flavor this run is on, or "" when it cannot be told.
200
-
201
- HF Jobs sets ACCELERATOR to "cpu" or "gpu", not the flavor name, so the flavor is looked up
202
- in the public Jobs hardware list: first by GPU model and count, then by the CPU_CORES and
203
- MEMORY values that Jobs sets in the container (to tell a10g-small from a10g-large, or
204
- cpu-basic from cpu-upgrade). Any failure (no network, older huggingface_hub) returns "".
205
- """
206
- hardware = os.environ.get("ACCELERATOR") or ""
207
- if "-" in hardware or any(character.isdigit() for character in hardware):
208
- return hardware # already a flavor name
209
- try:
210
- from huggingface_hub import HfApi
211
-
212
- gpu_name, gpu_count = "", 0
213
- try:
214
- import torch
215
-
216
- if torch.cuda.is_available():
217
- gpu_name = torch.cuda.get_device_name(0)
218
- gpu_count = torch.cuda.device_count()
219
- except ImportError:
220
- # Torch-free drivers (e.g. the -server recipes): ask nvidia-smi instead.
221
- import subprocess
222
-
223
- try:
224
- listed = subprocess.run(
225
- ["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],
226
- capture_output=True, text=True, timeout=10, check=True,
227
- ).stdout
228
- names = [line.strip() for line in listed.splitlines() if line.strip()]
229
- if names:
230
- gpu_name, gpu_count = names[0], len(names)
231
- except (OSError, subprocess.SubprocessError):
232
- pass
233
- if gpu_count == 0 and hardware == "gpu":
234
- return "" # a GPU run whose GPU cannot be identified: do not guess a CPU flavor
235
-
236
- # Whole-word match, so "L4" does not match "NVIDIA L40S" ("NVIDIA A100-SXM4-80GB" -> A100).
237
- gpu_words = gpu_name.upper().replace("-", " ").split()
238
- candidates = []
239
- for flavor in HfApi(token=False).list_jobs_hardware():
240
- accelerator = flavor.accelerator
241
- if gpu_count == 0 and accelerator is None:
242
- candidates.append(flavor)
243
- elif (
244
- gpu_count > 0
245
- and accelerator is not None
246
- and accelerator.model.upper() in gpu_words
247
- and int(accelerator.quantity) == gpu_count
248
- ):
249
- candidates.append(flavor)
250
- if not candidates:
251
- return ""
252
-
253
- cores = float(os.environ.get("CPU_CORES") or 0)
254
- memory_gb = float((os.environ.get("MEMORY") or "0").upper().rstrip("GIB ") or 0)
255
-
256
- def distance(flavor) -> float:
257
- # Relative gap to the listed vCPUs and RAM; Jobs reports slightly different numbers.
258
- listed_cores = float(flavor.cpu.split()[0])
259
- listed_memory = float(flavor.ram.split()[0])
260
- return abs(listed_cores - cores) / listed_cores + abs(listed_memory - memory_gb) / listed_memory
261
-
262
- return min(candidates, key=distance).name
263
- except Exception:
264
- return ""
265
-
266
-
267
- def create_dataset_card(
268
- source_dataset: str,
269
- model: str,
270
- mode: str,
271
- num_samples: int,
272
- processing_time: str,
273
- batch_size: int,
274
- max_model_len: int,
275
- max_tokens: int,
276
- temperature: float,
277
- top_p: float,
278
- longest_edge: int,
279
- gpu_memory_utilization: float,
280
- output_column: str,
281
- blocks_column: str,
282
- image_column: str = "image",
283
- split: str = "train",
284
- ) -> str:
285
- """Create a dataset card documenting the OCR process."""
286
- model_name = model.split("/")[-1]
287
-
288
- # Canonical provenance stamp (see AGENTS.md): Jobs claim gated on JOB_ID, set by HF Jobs in-container.
289
- on_jobs = os.environ.get("JOB_ID") is not None
290
- hw = jobs_flavor() # flavor name, e.g. "a10g-small"; "" when it cannot be told
291
- origin = (
292
- "Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"
293
- + (f" (`{hw}`)" if hw else "")
294
- ) if on_jobs else "Generated"
295
- jobs_tag = "\n- hf-jobs" if on_jobs else ""
296
-
297
- model_arg = f" \\\n --model {model}" if model != DEFAULT_MODEL else ""
298
- mode_arg = " \\\n --mode grounding" if mode == "grounding" else ""
299
- blocks_line = (
300
- f"- `{blocks_column}`: JSON list of layout blocks "
301
- "(`label`, `bbox` as x1,y1,x2,y2 normalised to 0-1000, `text`, `continues`)\n"
302
- if mode == "grounding"
303
- else ""
304
- )
305
-
306
- return f"""---
307
- tags:
308
- - ocr
309
- - document-processing
310
- - lighton-ocr-3
311
- - markdown
312
- - uv-script
313
- - generated{jobs_tag}
314
- ---
315
-
316
- # Document OCR using {model_name}
317
-
318
- This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using [{model_name}](https://huggingface.co/{model}) in **{mode}** mode.
319
-
320
- ## Processing Details
321
-
322
- - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
323
- - **Model**: [{model}](https://huggingface.co/{model})
324
- - **Mode**: `{mode}`
325
- - **Number of Samples**: {num_samples:,}
326
- - **Processing Time**: {processing_time}
327
- - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
328
-
329
- ### Configuration
330
-
331
- - **Image Column**: `{image_column}`
332
- - **Dataset Split**: `{split}`
333
- - **Batch Size**: {batch_size}
334
- - **Longest Image Edge**: {longest_edge}px
335
- - **Max Model Length**: {max_model_len:,} tokens
336
- - **Max Output Tokens**: {max_tokens:,}
337
- - **Temperature**: {temperature}
338
- - **Top P**: {top_p}
339
- - **GPU Memory Utilization**: {gpu_memory_utilization:.1%}
340
-
341
- ## Dataset Structure
342
-
343
- The dataset contains all original columns plus:
344
- - `{output_column}`: The extracted text in markdown format
345
- {blocks_line}- `inference_info`: JSON list tracking all OCR models applied to this dataset
346
-
347
- ## Reproduction
348
-
349
- {origin} with the [`lighton-ocr3.py`](https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3.py) recipe from [uv-scripts](https://huggingface.co/uv-scripts). Run it yourself:
350
-
351
- ```bash
352
- hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3.py \\
353
- {source_dataset} \\
354
- <output-dataset> \\
355
- --image-column {image_column} \\
356
- --batch-size {batch_size}{model_arg}{mode_arg}
357
- ```
358
- """
359
-
360
-
361
- def main(
362
- input_dataset: str,
363
- output_dataset: str,
364
- model: str = DEFAULT_MODEL,
365
- mode: str = "plain",
366
- image_column: str = "image",
367
- batch_size: int = 16,
368
- max_model_len: int = 16384,
369
- max_tokens: int = DEFAULT_MAX_TOKENS,
370
- temperature: float = DEFAULT_TEMPERATURE,
371
- top_p: float = DEFAULT_TOP_P,
372
- longest_edge: int = DEFAULT_LONGEST_EDGE,
373
- no_fix_dollars: bool = False,
374
- gpu_memory_utilization: float = 0.8,
375
- hf_token: str = None,
376
- split: str = "train",
377
- max_samples: int = None,
378
- private: bool = False,
379
- shuffle: bool = False,
380
- seed: int = 42,
381
- output_column: str = "markdown",
382
- blocks_column: str = "layout_blocks",
383
- overwrite: bool = False,
384
- verbose: bool = False,
385
- config: str = None,
386
- create_pr: bool = False,
387
- ):
388
- """Process images from HF dataset through LightOnOCR-3."""
389
-
390
- check_cuda_availability()
391
-
392
- start_time = datetime.now()
393
-
394
- HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
395
- if HF_TOKEN:
396
- login(token=HF_TOKEN)
397
-
398
- logger.info(f"Using model: {model} ({mode} mode)")
399
-
400
- # Load dataset
401
- logger.info(f"Loading dataset: {input_dataset}")
402
- dataset = load_dataset(input_dataset, split=split)
403
-
404
- if image_column not in dataset.column_names:
405
- raise ValueError(
406
- f"Column '{image_column}' not found. Available: {dataset.column_names}"
407
- )
408
-
409
- # Fail fast if an output column would collide with an existing input column
410
- output_columns = [output_column] + ([blocks_column] if mode == "grounding" else [])
411
- dataset = ensure_output_columns_free(dataset, output_columns, overwrite=overwrite)
412
-
413
- if shuffle:
414
- logger.info(f"Shuffling dataset with seed {seed}")
415
- dataset = dataset.shuffle(seed=seed)
416
-
417
- if max_samples:
418
- dataset = dataset.select(range(min(max_samples, len(dataset))))
419
- logger.info(f"Limited to {len(dataset)} samples")
420
-
421
- # Initialize vLLM
422
- logger.info(f"Initializing vLLM with {model}")
423
- logger.info("This may take a few minutes on first run...")
424
- # Stock Qwen3_5ForConditionalGeneration arch, so no trust_remote_code. A 2048px page
425
- # is at most 64x64 = 4,096 image tokens (16px patches, 2x2 merge), so 16384 leaves
426
- # room for the card's 4096 output tokens. gdn_prefill_backend="triton" avoids the
427
- # Qwen3.5 gated-delta-net prefill path that needs a CUDA JIT toolchain (as ovis-ocr2.py).
428
- llm = LLM(
429
- model=model,
430
- max_model_len=max_model_len,
431
- gpu_memory_utilization=gpu_memory_utilization,
432
- limit_mm_per_prompt={"image": 1},
433
- gdn_prefill_backend="triton",
434
- )
435
-
436
- prompt = build_prompt(llm, mode)
437
- sampling_params = SamplingParams(
438
- temperature=temperature, top_p=top_p, max_tokens=max_tokens
439
- )
440
-
441
- logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
442
- logger.info(f"Output will be written to column: {output_column}")
443
- if mode == "grounding":
444
- logger.info(f"Layout blocks will be written to column: {blocks_column}")
445
-
446
- all_markdown = []
447
- all_blocks = []
448
- total_batches = (len(dataset) + batch_size - 1) // batch_size
449
- processed = 0
450
-
451
- for batch_num, batch_indices in enumerate(
452
- partition_all(batch_size, range(len(dataset))), 1
453
- ):
454
- batch_indices = list(batch_indices)
455
- batch_images = [dataset[i][image_column] for i in batch_indices]
456
-
457
- logger.info(
458
- f"Batch {batch_num}/{total_batches} "
459
- f"({processed}/{len(dataset)} images done)"
460
- )
461
-
462
- try:
463
- # Downscale to the training render size (never upscale), as the client does.
464
- vllm_inputs = [
465
- {
466
- "prompt": prompt,
467
- "multi_modal_data": {"image": fit(to_pil_image(img), longest_edge)},
468
- }
469
- for img in batch_images
470
- ]
471
-
472
- outputs = llm.generate(vllm_inputs, sampling_params)
473
-
474
- for output in outputs:
475
- markdown, blocks = postprocess_output(
476
- output.outputs[0].text, mode, fix_dollars=not no_fix_dollars
477
- )
478
- all_markdown.append(markdown)
479
- all_blocks.append(blocks)
480
-
481
- processed += len(batch_images)
482
-
483
- except Exception as e:
484
- logger.error(f"Error processing batch: {e}")
485
- all_markdown.extend(["[OCR ERROR]"] * len(batch_images))
486
- all_blocks.extend([json.dumps([])] * len(batch_images))
487
- processed += len(batch_images)
488
-
489
- processing_duration = datetime.now() - start_time
490
- processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
491
-
492
- logger.info(f"Adding '{output_column}' column to dataset")
493
- dataset = dataset.add_column(output_column, all_markdown)
494
- if mode == "grounding":
495
- logger.info(f"Adding '{blocks_column}' column to dataset")
496
- dataset = dataset.add_column(blocks_column, all_blocks)
497
-
498
- # Inference info tracking
499
- inference_entry = {
500
- "model_id": model,
501
- "model_name": model.split("/")[-1],
502
- "mode": mode,
503
- "column_name": output_column,
504
- "blocks_column": blocks_column if mode == "grounding" else None,
505
- "timestamp": datetime.now().isoformat(),
506
- "temperature": temperature,
507
- "top_p": top_p,
508
- "max_tokens": max_tokens,
509
- "longest_edge": longest_edge,
510
- "fix_dollars": not no_fix_dollars,
511
- }
512
-
513
- if "inference_info" in dataset.column_names:
514
- logger.info("Updating existing inference_info column")
515
-
516
- def update_inference_info(example):
517
- try:
518
- existing_info = (
519
- json.loads(example["inference_info"])
520
- if example["inference_info"]
521
- else []
522
- )
523
- except (json.JSONDecodeError, TypeError):
524
- existing_info = []
525
- existing_info.append(inference_entry)
526
- return {"inference_info": json.dumps(existing_info)}
527
-
528
- dataset = dataset.map(update_inference_info)
529
- else:
530
- logger.info("Creating new inference_info column")
531
- inference_list = [json.dumps([inference_entry])] * len(dataset)
532
- dataset = dataset.add_column("inference_info", inference_list)
533
-
534
- # Push to hub with retry and XET fallback
535
- logger.info(f"Pushing to {output_dataset}")
536
- max_retries = 3
537
- for attempt in range(1, max_retries + 1):
538
- try:
539
- if attempt > 1:
540
- logger.warning("Disabling XET (fallback to HTTP upload)")
541
- os.environ["HF_HUB_DISABLE_XET"] = "1"
542
- commit_info = dataset.push_to_hub(
543
- output_dataset,
544
- private=private,
545
- token=HF_TOKEN,
546
- max_shard_size="500MB",
547
- **({"config_name": config} if config else {}),
548
- create_pr=create_pr,
549
- commit_message=f"Add {model} OCR results ({len(dataset)} samples)"
550
- + (f" [{config}]" if config else ""),
551
- )
552
- break
553
- except Exception as e:
554
- logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
555
- if attempt < max_retries:
556
- delay = 30 * (2 ** (attempt - 1))
557
- logger.info(f"Retrying in {delay}s...")
558
- time.sleep(delay)
559
- else:
560
- logger.error("All upload attempts failed. OCR results are lost.")
561
- sys.exit(1)
562
-
563
- # Create and push dataset card
564
- logger.info("Creating dataset card")
565
- card_content = create_dataset_card(
566
- source_dataset=input_dataset,
567
- model=model,
568
- mode=mode,
569
- num_samples=len(dataset),
570
- processing_time=processing_time_str,
571
- batch_size=batch_size,
572
- max_model_len=max_model_len,
573
- max_tokens=max_tokens,
574
- temperature=temperature,
575
- top_p=top_p,
576
- longest_edge=longest_edge,
577
- gpu_memory_utilization=gpu_memory_utilization,
578
- output_column=output_column,
579
- blocks_column=blocks_column,
580
- image_column=image_column,
581
- split=split,
582
- )
583
-
584
- # With --create-pr the data went to a PR branch; the card goes to the same branch.
585
- revision = commit_info.pr_revision if create_pr else None
586
- card = DatasetCard(card_content)
587
- # Keep the configs/dataset_info metadata push_to_hub just wrote, or named configs
588
- # (--config) stop loading.
589
- pushed = DatasetCard.load(
590
- hf_hub_download(output_dataset, "README.md", repo_type="dataset",
591
- revision=revision, token=HF_TOKEN)
592
- )
593
- for key in ("configs", "dataset_info"):
594
- if pushed.data.get(key) is not None:
595
- card.data[key] = pushed.data[key]
596
- card.push_to_hub(output_dataset, token=HF_TOKEN, revision=revision)
597
-
598
- logger.info("Done! LightOnOCR-3 processing complete.")
599
- logger.info(
600
- f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
601
- )
602
- logger.info(f"Processing time: {processing_time_str}")
603
- logger.info(
604
- f"Processing speed: {len(dataset) / processing_duration.total_seconds():.2f} images/sec"
605
- )
606
-
607
- if verbose:
608
- import importlib.metadata
609
-
610
- logger.info("--- Resolved package versions ---")
611
- for pkg in ["vllm", "transformers", "torch", "datasets", "pyarrow", "pillow", "lightonocr"]:
612
- try:
613
- logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
614
- except importlib.metadata.PackageNotFoundError:
615
- logger.info(f" {pkg}: not installed")
616
- logger.info("--- End versions ---")
617
-
618
-
619
- if __name__ == "__main__":
620
- if len(sys.argv) == 1:
621
- print("=" * 70)
622
- print("LightOnOCR-3 Document Processing")
623
- print("=" * 70)
624
- print("\n4B (default) or 0.8B end-to-end OCR, Qwen3.5 architecture")
625
- print("\nModes:")
626
- print(" plain markdown transcription (default)")
627
- print(" grounding labelled layout blocks with 0-1000 boxes")
628
- print("\nExamples:")
629
- print("\n1. Basic OCR (own GPU):")
630
- print(" uv run --with vllm==0.30.0 lighton-ocr3.py input-dataset output-dataset")
631
- print("\n2. Layout blocks with the 0.8B model:")
632
- print(" uv run --with vllm==0.30.0 lighton-ocr3.py docs results \\")
633
- print(" --mode grounding --model lightonai/LightOnOCR-3-0.8B")
634
- print("\n3. Running on HF Jobs (hf CLI 1.32+; image/flavor/secrets from the script header):")
635
- print(" hf jobs uv run \\")
636
- print(
637
- " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3.py \\"
638
- )
639
- print(" input-dataset output-dataset --max-samples 10")
640
- print("\nFor full help: uv run --with vllm==0.30.0 lighton-ocr3.py --help")
641
- sys.exit(0)
642
-
643
- parser = argparse.ArgumentParser(
644
- description="Document OCR using LightOnOCR-3 (4B or 0.8B, plain or grounding mode)",
645
- formatter_class=argparse.RawDescriptionHelpFormatter,
646
- epilog="""
647
- Examples:
648
- uv run --with vllm==0.30.0 lighton-ocr3.py my-docs analyzed-docs
649
- uv run --with vllm==0.30.0 lighton-ocr3.py docs results --mode grounding
650
- uv run --with vllm==0.30.0 lighton-ocr3.py docs results --model lightonai/LightOnOCR-3-0.8B
651
- """,
652
- )
653
-
654
- parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
655
- parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
656
- parser.add_argument(
657
- "--model",
658
- default=DEFAULT_MODEL,
659
- choices=MODELS,
660
- help=f"Model checkpoint (default: {DEFAULT_MODEL})",
661
- )
662
- parser.add_argument(
663
- "--mode",
664
- default="plain",
665
- choices=["plain", "grounding"],
666
- help="plain = markdown transcription; grounding = labelled layout blocks "
667
- "with boxes, parsed into --blocks-column (default: plain)",
668
- )
669
- parser.add_argument(
670
- "--image-column",
671
- default="image",
672
- help="Column containing images (default: image)",
673
- )
674
- parser.add_argument(
675
- "--batch-size",
676
- type=int,
677
- default=16,
678
- help="Batch size for processing (default: 16)",
679
- )
680
- parser.add_argument(
681
- "--max-model-len",
682
- type=int,
683
- default=16384,
684
- help="Maximum model context length (default: 16384; model supports 262144). "
685
- "A 2048px page is at most 4,096 image tokens.",
686
- )
687
- parser.add_argument(
688
- "--max-tokens",
689
- type=int,
690
- default=DEFAULT_MAX_TOKENS,
691
- help=f"Maximum tokens to generate (default: {DEFAULT_MAX_TOKENS}, the card's "
692
- "vLLM example). Raise it for very dense pages in grounding mode.",
693
- )
694
- parser.add_argument(
695
- "--temperature",
696
- type=float,
697
- default=DEFAULT_TEMPERATURE,
698
- help=f"Sampling temperature (default: {DEFAULT_TEMPERATURE}, model card)",
699
- )
700
- parser.add_argument(
701
- "--top-p",
702
- type=float,
703
- default=DEFAULT_TOP_P,
704
- help=f"Top-p (default: {DEFAULT_TOP_P}, model card; LightOn's client uses 1.0)",
705
- )
706
- parser.add_argument(
707
- "--longest-edge",
708
- type=int,
709
- default=DEFAULT_LONGEST_EDGE,
710
- help=f"Downscale pages so the longest edge is at most this many pixels "
711
- f"(default: {DEFAULT_LONGEST_EDGE}, the training render size)",
712
- )
713
- parser.add_argument(
714
- "--no-fix-dollars",
715
- action="store_true",
716
- help="Keep the raw model output instead of repairing escaped dollar "
717
- "delimiters (the official client repairs them by default)",
718
- )
719
- parser.add_argument(
720
- "--gpu-memory-utilization",
721
- type=float,
722
- default=0.8,
723
- help="GPU memory utilization (default: 0.8)",
724
- )
725
- parser.add_argument("--hf-token", help="Hugging Face API token")
726
- parser.add_argument(
727
- "--split", default="train", help="Dataset split to use (default: train)"
728
- )
729
- parser.add_argument(
730
- "--max-samples",
731
- type=int,
732
- help="Maximum number of samples to process (for testing)",
733
- )
734
- parser.add_argument(
735
- "--private", action="store_true", help="Make output dataset private"
736
- )
737
- parser.add_argument(
738
- "--config",
739
- help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
740
- )
741
- parser.add_argument(
742
- "--create-pr",
743
- action="store_true",
744
- help="Create a pull request instead of pushing directly (for parallel benchmarking)",
745
- )
746
- parser.add_argument(
747
- "--shuffle", action="store_true", help="Shuffle dataset before processing"
748
- )
749
- parser.add_argument(
750
- "--seed",
751
- type=int,
752
- default=42,
753
- help="Random seed for shuffling (default: 42)",
754
- )
755
- parser.add_argument(
756
- "--output-column",
757
- default="markdown",
758
- help="Column name for output text (default: markdown)",
759
- )
760
- parser.add_argument(
761
- "--blocks-column",
762
- default="layout_blocks",
763
- help="Column name for parsed layout blocks in grounding mode (default: layout_blocks)",
764
- )
765
- parser.add_argument(
766
- "--overwrite",
767
- action="store_true",
768
- help="Replace the output column(s) if they already exist in the input dataset "
769
- "(default: error out to avoid clobbering an existing column).",
770
- )
771
- parser.add_argument(
772
- "--verbose",
773
- action="store_true",
774
- help="Log resolved package versions after processing (useful for pinning deps)",
775
- )
776
-
777
- args = parser.parse_args()
778
-
779
- if args.max_tokens > args.max_model_len:
780
- parser.error(
781
- f"--max-tokens ({args.max_tokens}) must be <= --max-model-len ({args.max_model_len})"
782
- )
783
-
784
- main(
785
- input_dataset=args.input_dataset,
786
- output_dataset=args.output_dataset,
787
- model=args.model,
788
- mode=args.mode,
789
- image_column=args.image_column,
790
- batch_size=args.batch_size,
791
- max_model_len=args.max_model_len,
792
- max_tokens=args.max_tokens,
793
- temperature=args.temperature,
794
- top_p=args.top_p,
795
- longest_edge=args.longest_edge,
796
- no_fix_dollars=args.no_fix_dollars,
797
- gpu_memory_utilization=args.gpu_memory_utilization,
798
- hf_token=args.hf_token,
799
- split=args.split,
800
- max_samples=args.max_samples,
801
- private=args.private,
802
- shuffle=args.shuffle,
803
- seed=args.seed,
804
- output_column=args.output_column,
805
- blocks_column=args.blocks_column,
806
- overwrite=args.overwrite,
807
- verbose=args.verbose,
808
- config=args.config,
809
- create_pr=args.create_pr,
810
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
minicpm-ocr.py DELETED
@@ -1,644 +0,0 @@
1
- # /// script
2
- # requires-python = ">=3.11"
3
- # dependencies = [
4
- # "datasets>=3.1.0",
5
- # "huggingface-hub>=1.0",
6
- # "pillow",
7
- # "bucketbag @ https://github.com/davanstrien/bucketbag/archive/refs/tags/v0.3.1.tar.gz",
8
- # ]
9
- #
10
- # [tool.hf-jobs]
11
- # image = "cr.hf.co/davanstrien/minicpm-ocr:1.0-vllm-5d35ce3"
12
- # flavor = "a10g-large"
13
- # timeout = "2h"
14
- # secrets = ["HF_TOKEN"]
15
- # ///
16
-
17
- """
18
- Convert document images to markdown with OpenBMB's MiniCPM-OCR 1.0 pipeline.
19
-
20
- MiniCPM-OCR 1.0 (1.3B, Apache-2.0) is a region reader: the official SDK finds layout regions
21
- with PP-DocLayoutV3, crops them, sends each crop to the model with the prompt for its type
22
- (`Text Recognition:`, `Table Recognition:`, `Formula Recognition:`, ...) and assembles the page
23
- as Markdown (tables as HTML, formulas as LaTeX). This script runs that pipeline unchanged.
24
-
25
- Two ways in and out:
26
-
27
- # Hub dataset -> Hub dataset (adds `markdown` and `markdown_status` columns)
28
- hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/minicpm-ocr.py \\
29
- input-dataset output-dataset --max-samples 20
30
-
31
- # Bucket (or folder) of page images -> one .md per image in a Bucket (or folder)
32
- hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/minicpm-ocr.py \\
33
- hf://buckets/<ns>/<bucket>/pages hf://buckets/<ns>/<bucket>/minicpm-ocr
34
-
35
- Bucket input is listed and downloaded in batches with bucketbag (no mount); `x/y.jp2` becomes
36
- `x/y.md` under the output prefix. A page whose regions all read cleanly is written; a page with
37
- failed regions is not, and is listed at the end, so re-running the same command retries it (pages
38
- with a `.md` already are skipped). In dataset mode every row gets a `markdown_status`: `ok`,
39
- `partial_failed` (some regions failed; the text is kept), `failed` or `error: ...` (no text).
40
-
41
- Runtime image (from the [tool.hf-jobs] header): cr.hf.co/davanstrien/minicpm-ocr, built from
42
- images/minicpm-ocr/Dockerfile. It holds:
43
- - vLLM nightly 5d35ce3. MiniCPMOcrForConditionalGeneration landed in vLLM main on 23 Oct 2026
44
- and is not in a release yet. Drop the custom image for a stock vllm/vllm-openai tag once a
45
- release has the architecture.
46
- - transformers at OpenBMB's pin (549e5b4).
47
- - The minicpm-ocr SDK 1.0.1 in its own venv (/opt/sdk) with PaddlePaddle GPU, as OpenBMB's docs
48
- require (SDK and inference service in separate environments), and the PP-DocLayoutV3 layout
49
- model baked in at /opt/minicpm-ocr-assets.
50
-
51
- Server settings follow OpenBMB's SDK tutorial (docs/minicpmvocr_tutorial_en.md): max-model-len
52
- 40960, 32 sequences, image limit 36, `downsample_mode` 4x, thinking off, DSpark speculative
53
- decoding with the matching draft model (`--no-dspark` for plain decoding). The SDK's bundled
54
- config sets sampling and per-region prompts; nothing here overrides them. The SDK reads page
55
- numbers, headers, footers, footnotes and side notes but leaves them out of the Markdown;
56
- `--keep-labels footnote aside_text` puts those region types back.
57
-
58
- Model: https://huggingface.co/openbmb/MiniCPM-OCR-1.0
59
- SDK: https://github.com/OpenBMB/MiniCPM-OCR
60
- Image: https://huggingface.co/containers/davanstrien/minicpm-ocr
61
- """
62
-
63
- import argparse
64
- import contextlib
65
- import json
66
- import logging
67
- import os
68
- import shlex
69
- import shutil
70
- import signal
71
- import subprocess
72
- import sys
73
- import tempfile
74
- import time
75
- import urllib.request
76
- from datetime import datetime
77
- from pathlib import Path
78
-
79
- logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
80
- logger = logging.getLogger(__name__)
81
-
82
- SCRIPT_URL = "https://huggingface.co/datasets/uv-scripts/ocr/raw/main/minicpm-ocr.py"
83
- MODEL = "openbmb/MiniCPM-OCR-1.0"
84
- MODEL_REVISION = "a59a4acf215e34c6d73149e9eafdb88ed2086e39"
85
- DRAFT_MODEL = "openbmb/MiniCPM-OCR-1.0-DSpark" # must come from the same release as MODEL
86
- DRAFT_REVISION = "31e3feaf80e0061cd6aa73db23480d2d691d6452"
87
- SERVED_NAME = "minicpm-ocr"
88
- PORT = 18499
89
- SDK_PYTHON = "/opt/sdk/bin/python"
90
- LAYOUT_MODEL_DIR = "/opt/minicpm-ocr-assets/models/PP-DocLayoutV3_infer"
91
- # minicpm-ocr SDK 1.0.1 markdown_assembly.ignore_labels: read by the model, left out of the Markdown
92
- SDK_IGNORED_LABELS = ["number", "footnote", "header", "footer", "aside_text"]
93
- IMAGE_TAG = "cr.hf.co/davanstrien/minicpm-ocr:1.0-vllm-5d35ce3"
94
- BUCKET_SCHEME = "hf://buckets/"
95
- IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".tif", ".tiff", ".bmp", ".webp", ".jp2"}
96
-
97
- # Runs inside the SDK venv: the SDK's documented Python API (docs/minicpmvocr_api_en.md),
98
- # with the bundled config and only the input, server and layout path filled in.
99
- SDK_RUNNER = """
100
- import json, sys
101
- from importlib.resources import files
102
- from pathlib import Path
103
- from minicpmvocr import load_config, pipelined_run
104
- from minicpmvocr.prompts import DEFAULT_PROMPT_MAP
105
- args = json.loads(sys.argv[1])
106
- prompt = {}
107
- if args["keep_labels"]:
108
- # A prompt-map file replaces whole top-level sections, so write the full assembly section.
109
- assembly = dict(DEFAULT_PROMPT_MAP["markdown_assembly"])
110
- assembly["ignore_labels"] = [l for l in assembly["ignore_labels"] if l not in args["keep_labels"]]
111
- prompt_map = Path(args["run_root"]) / "prompt_map.json"
112
- prompt_map.parent.mkdir(parents=True, exist_ok=True)
113
- prompt_map.write_text(json.dumps({"markdown_assembly": assembly}))
114
- prompt = {"prompt_map": str(prompt_map)}
115
- cfg = load_config(str(files("minicpmvocr").joinpath("configs/minicpmvocr.yaml")), overrides={
116
- "input": {"image_dir": args["image_dir"]},
117
- "run": {"run_root": args["run_root"], "run_tag": args["run_tag"]},
118
- "engine": {"server_url": args["server_url"], "model_name": args["model_name"], "max_model_len": 40960},
119
- "layout": {"model_dir": args["layout_dir"], "device": "cuda:0"},
120
- "pipeline": {"overlap_layout": True},
121
- "prompt": prompt,
122
- })
123
- pipelined_run(cfg)
124
- print(json.dumps({"run_dir": cfg["_meta"]["run_dir"]}))
125
- """
126
-
127
-
128
- def image_python() -> str | None:
129
- """The image's own python3 (the one with vLLM and torch), looking past this script's venv."""
130
- own_bin = os.path.realpath(os.path.join(sys.prefix, "bin"))
131
- path = os.pathsep.join(p for p in os.environ.get("PATH", "").split(os.pathsep)
132
- if os.path.realpath(p) != own_bin)
133
- return shutil.which("python3", path=path)
134
-
135
-
136
- def check_runtime():
137
- """Fail fast, naming the fix, when not on the MiniCPM-OCR image or without a CUDA GPU."""
138
- py = image_python()
139
- if not (py and shutil.which("vllm") and Path(SDK_PYTHON).exists() and Path(LAYOUT_MODEL_DIR).exists()):
140
- logger.error("This script needs the %s image (vLLM with MiniCPM-OCR support, the "
141
- "minicpm-ocr SDK and the layout model).", IMAGE_TAG)
142
- logger.error("Run it with `hf jobs uv run`, which reads the image from the script header, "
143
- "or pass --image %s.", IMAGE_TAG)
144
- sys.exit(1)
145
- probe = subprocess.run([py, "-c", "import torch; print(torch.cuda.is_available())"],
146
- capture_output=True, text=True)
147
- if probe.stdout.strip() != "True":
148
- logger.error("CUDA is not available to the image's torch. This script needs a GPU "
149
- "(e.g. --flavor a10g-large). %s", probe.stderr.strip()[-300:])
150
- sys.exit(1)
151
-
152
-
153
- @contextlib.contextmanager
154
- def vllm_server(dspark: bool):
155
- """Run vLLM with OpenBMB's tutorial settings for the duration of the block.
156
-
157
- The server gets its own process group, and is terminated, then killed, then reaped, on every
158
- exit path, including a failed or interrupted startup.
159
- """
160
- from huggingface_hub import snapshot_download
161
-
162
- model_dir = snapshot_download(MODEL, revision=MODEL_REVISION)
163
- cmd = [
164
- "vllm", "serve", model_dir, "--served-model-name", SERVED_NAME,
165
- "--host", "127.0.0.1", "--port", str(PORT),
166
- "--max-model-len", "40960", "--max-num-batched-tokens", "40960", "--max-num-seqs", "32",
167
- "--limit-mm-per-prompt", '{"image":36,"video":0}',
168
- "--mm-processor-kwargs", '{"downsample_mode":"4x"}',
169
- "--gpu-memory-utilization", "0.85", "--trust-request-mm-kwargs",
170
- "--default-chat-template-kwargs", '{"enable_thinking":false}',
171
- ]
172
- if dspark:
173
- draft_dir = snapshot_download(DRAFT_MODEL, revision=DRAFT_REVISION)
174
- cmd += ["--speculative-config", json.dumps({
175
- "method": "dspark", "model": draft_dir, "num_speculative_tokens": 15,
176
- "enable_adaptive_verification": False})]
177
- # This script's VIRTUAL_ENV must not leak into the image's vLLM.
178
- env = {k: v for k, v in os.environ.items() if k != "VIRTUAL_ENV"}
179
- logger.info("Starting vLLM: %s", shlex.join(cmd))
180
- proc = subprocess.Popen(cmd, env=env, start_new_session=True)
181
- try:
182
- deadline = time.time() + 1800
183
- while True:
184
- if proc.poll() is not None:
185
- sys.exit(f"vLLM exited during startup (code {proc.returncode})")
186
- try:
187
- with urllib.request.urlopen(f"http://127.0.0.1:{PORT}/v1/models", timeout=5) as r:
188
- if SERVED_NAME in r.read().decode():
189
- break
190
- except OSError:
191
- pass
192
- if time.time() > deadline:
193
- sys.exit("vLLM did not become ready within 30 minutes")
194
- time.sleep(5)
195
- logger.info("vLLM ready")
196
- yield
197
- finally:
198
- stop_process_group(proc)
199
-
200
-
201
- def group_alive(pgid: int) -> bool:
202
- try:
203
- os.killpg(pgid, 0)
204
- return True
205
- except (ProcessLookupError, PermissionError):
206
- return False
207
-
208
-
209
- def stop_process_group(proc: subprocess.Popen):
210
- """SIGTERM the whole group, wait up to 60 s for it to empty, then SIGKILL; always reap the
211
- parent. Checks the group, not just the parent, since vLLM's workers can outlive it."""
212
- pgid = proc.pid # start_new_session=True: the server leads its own group
213
- for sig, wait in ((signal.SIGTERM, 60), (signal.SIGKILL, 30)):
214
- if not group_alive(pgid):
215
- break
216
- with contextlib.suppress(ProcessLookupError):
217
- os.killpg(pgid, sig)
218
- deadline = time.time() + wait
219
- while group_alive(pgid) and time.time() < deadline:
220
- with contextlib.suppress(subprocess.TimeoutExpired):
221
- proc.wait(timeout=1)
222
- with contextlib.suppress(subprocess.TimeoutExpired):
223
- proc.wait(timeout=5)
224
-
225
-
226
- def parse_batch(images: dict, work: Path, tag: str, keep_labels: list[str]) -> dict:
227
- """OCR one batch of pages with the SDK.
228
-
229
- `images` maps a key to a PIL image, a path, or an undecoded datasets image dict. Returns
230
- key -> (status, markdown or None). A page that cannot be read gets an `error: ...` status and
231
- does not stop the batch; if the SDK run itself fails, every page in the batch gets one.
232
- """
233
- from datasets import Image as ImageFeature
234
- from PIL import Image, ImageOps
235
-
236
- decoder = ImageFeature()
237
- image_dir = work / tag / "images"
238
- image_dir.mkdir(parents=True)
239
- results, ids = {}, {}
240
- for i, (key, source) in enumerate(images.items()):
241
- try:
242
- if isinstance(source, dict):
243
- # datasets Image(decode=False): {"bytes", "path"}. The datasets decoder handles
244
- # remote paths and auth, and turns EXIF-rotated photos upright.
245
- img = decoder.decode_example(source)
246
- else:
247
- img = source if isinstance(source, Image.Image) else Image.open(source)
248
- img = ImageOps.exif_transpose(img)
249
- img.convert("RGB").save(image_dir / f"{i:06d}.png")
250
- ids[f"{i:06d}"] = key
251
- except Exception as e: # one unreadable page must not lose the batch
252
- logger.warning("Cannot read %s: %s", key, e)
253
- results[key] = (f"error: unreadable image ({type(e).__name__})", None)
254
- if ids:
255
- args = {"image_dir": str(image_dir), "run_root": str(work / tag / "runs"), "run_tag": tag,
256
- "server_url": f"http://127.0.0.1:{PORT}", "model_name": SERVED_NAME,
257
- "layout_dir": LAYOUT_MODEL_DIR, "keep_labels": keep_labels}
258
- run = subprocess.run([SDK_PYTHON, "-c", SDK_RUNNER, json.dumps(args)],
259
- capture_output=True, text=True)
260
- if run.returncode != 0:
261
- logger.error("SDK run failed for %s (exit %d):\n%s", tag, run.returncode, run.stderr[-3000:])
262
- results.update({key: (f"error: SDK exit {run.returncode}", None) for key in ids.values()})
263
- else:
264
- run_dir = Path(json.loads(run.stdout.strip().splitlines()[-1])["run_dir"])
265
- status = {}
266
- metrics = run_dir / "per_page_metrics.jsonl"
267
- if metrics.exists():
268
- for line in metrics.read_text(encoding="utf-8").splitlines():
269
- row = json.loads(line)
270
- status[row["image_id"]] = row.get("status") or "unknown"
271
- for image_id, key in ids.items():
272
- md = run_dir / "output" / f"{image_id}.md"
273
- page_status = status.get(image_id, "failed" if not md.exists() else "unknown")
274
- text = md.read_text(encoding="utf-8").strip() if md.exists() else None
275
- results[key] = (page_status, text if page_status in ("ok", "partial_failed") else None)
276
- shutil.rmtree(work / tag, ignore_errors=True)
277
- return results
278
-
279
-
280
- # --- Bucket / folder mode ------------------------------------------------------------------
281
-
282
-
283
- def is_bucket(location: str) -> bool:
284
- return location.startswith(BUCKET_SCHEME)
285
-
286
-
287
- def as_bucket_dir(url: str) -> tuple[str, str]:
288
- """Split a bucket URL into (bucket root URL, directory key prefix ending in "/").
289
-
290
- The prefix goes to bucketbag explicitly: it matches prefixes as strings, so `.../vol`
291
- would also list `.../vol2/...`.
292
- """
293
- parts = url[len(BUCKET_SCHEME):].strip("/").split("/", 2)
294
- if len(parts) < 2:
295
- raise ValueError(f"Not a bucket URL: {url} (expected hf://buckets/<ns>/<bucket>[/<prefix>])")
296
- prefix = parts[2] + "/" if len(parts) == 3 else ""
297
- return BUCKET_SCHEME + "/".join(parts[:2]), prefix
298
-
299
-
300
- def md_rel(rel: str) -> str:
301
- return str(Path(rel).with_suffix(".md"))
302
-
303
-
304
- def list_rels(location: str) -> list[str]:
305
- """Relative paths of every file under a bucket prefix or folder, sorted."""
306
- if is_bucket(location):
307
- from bucketbag import iter_keys
308
-
309
- url, prefix = as_bucket_dir(location)
310
- return sorted(k[len(prefix):] for k in iter_keys(url, prefix=prefix))
311
- root = Path(location)
312
- return sorted(str(p.relative_to(root)) for p in root.rglob("*") if p.is_file()) if root.is_dir() else []
313
-
314
-
315
- def iter_local_batches(source: str, rels: list[str], n: int):
316
- """Yield batches of (rel, local path): from disk, or downloaded by bucketbag to scratch."""
317
- if not is_bucket(source):
318
- for i in range(0, len(rels), n):
319
- yield [(rel, Path(source) / rel) for rel in rels[i: i + n]]
320
- return
321
- from bucketbag import batched_files
322
-
323
- url, prefix = as_bucket_dir(source)
324
- for batch in batched_files(url, keys=[prefix + rel for rel in rels], n=n, prefetch=2):
325
- yield [(item.key[len(prefix):], item.path) for item in batch]
326
-
327
-
328
- def write_outputs(dest: str, pairs: list[tuple[str, str]]):
329
- if not pairs:
330
- return
331
- if is_bucket(dest):
332
- from bucketbag import put_files
333
-
334
- url, prefix = as_bucket_dir(dest)
335
- put_files([(prefix + rel, content) for rel, content in pairs], url)
336
- return
337
- for rel, content in pairs:
338
- # Temp file + rename: a stopped job never leaves a partial .md that a re-run counts as done.
339
- path = Path(dest) / rel
340
- path.parent.mkdir(parents=True, exist_ok=True)
341
- tmp = path.with_name(f".{path.name}.tmp")
342
- tmp.write_text(content, encoding="utf-8")
343
- os.replace(tmp, path)
344
-
345
-
346
- def run_files(args):
347
- inputs = [r for r in list_rels(args.input) if Path(r).suffix.lower() in IMAGE_EXTENSIONS]
348
- owners: dict[str, list[str]] = {}
349
- for rel in inputs:
350
- owners.setdefault(md_rel(rel), []).append(rel)
351
- clashes = [" + ".join(group) for group in owners.values() if len(group) > 1]
352
- if clashes:
353
- sys.exit("These inputs would write the same .md file; rename or move them first:\n "
354
- + "\n ".join(clashes))
355
- if args.max_samples:
356
- inputs = inputs[: args.max_samples] # the same pages on every run, so a re-run resumes them
357
- done = {r for r in list_rels(args.output) if r.endswith(".md")}
358
- todo = [r for r in inputs if args.overwrite or md_rel(r) not in done]
359
- already = sum(md_rel(r) in done for r in inputs)
360
- logger.info("%d images under %s, %d already have a .md, %d to OCR", len(inputs), args.input,
361
- already, len(todo))
362
- if not todo:
363
- return
364
- failed = []
365
- with vllm_server(dspark=not args.no_dspark), tempfile.TemporaryDirectory() as work:
366
- for b, batch in enumerate(iter_local_batches(args.input, todo, args.batch_size)):
367
- results = parse_batch(dict(batch), Path(work), f"batch{b:06d}", args.keep_labels)
368
- write_outputs(args.output, [(md_rel(rel), text) for rel, (status, text) in results.items()
369
- if status == "ok"])
370
- failed += [f"{rel} ({status})" for rel, (status, _) in results.items() if status != "ok"]
371
- logger.info("%d/%d images", min((b + 1) * args.batch_size, len(todo)), len(todo))
372
- if failed:
373
- logger.warning("%d pages not written (re-run the same command to retry them):\n %s",
374
- len(failed), "\n ".join(failed))
375
- stale = [f for f in failed if md_rel(f.rsplit(" (", 1)[0]) in done]
376
- if args.overwrite and stale:
377
- logger.warning("%d of them still have a .md from an earlier run, which a re-run without "
378
- "--overwrite will skip; delete those files to retry them:\n %s",
379
- len(stale), "\n ".join(stale))
380
-
381
-
382
- # --- Dataset mode ----------------------------------------------------------------------------
383
-
384
-
385
- def jobs_flavor() -> str:
386
- """Return the HF Jobs hardware flavor this run is on, or "" when it cannot be told.
387
-
388
- HF Jobs sets ACCELERATOR to "cpu" or "gpu", not the flavor name, so the flavor is looked up
389
- in the public Jobs hardware list: first by GPU model and count, then by the CPU_CORES and
390
- MEMORY values that Jobs sets in the container (to tell a10g-small from a10g-large, or
391
- cpu-basic from cpu-upgrade). Any failure (no network, older huggingface_hub) returns "".
392
- """
393
- hardware = os.environ.get("ACCELERATOR") or ""
394
- if "-" in hardware or any(character.isdigit() for character in hardware):
395
- return hardware # already a flavor name
396
- try:
397
- from huggingface_hub import HfApi
398
-
399
- gpu_name, gpu_count = "", 0
400
- try:
401
- import torch
402
-
403
- if torch.cuda.is_available():
404
- gpu_name = torch.cuda.get_device_name(0)
405
- gpu_count = torch.cuda.device_count()
406
- except ImportError:
407
- # Torch-free drivers (e.g. the -server recipes): ask nvidia-smi instead.
408
- import subprocess
409
-
410
- try:
411
- listed = subprocess.run(
412
- ["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],
413
- capture_output=True, text=True, timeout=10, check=True,
414
- ).stdout
415
- names = [line.strip() for line in listed.splitlines() if line.strip()]
416
- if names:
417
- gpu_name, gpu_count = names[0], len(names)
418
- except (OSError, subprocess.SubprocessError):
419
- pass
420
- if gpu_count == 0 and hardware == "gpu":
421
- return "" # a GPU run whose GPU cannot be identified: do not guess a CPU flavor
422
-
423
- # Whole-word match, so "L4" does not match "NVIDIA L40S" ("NVIDIA A100-SXM4-80GB" -> A100).
424
- gpu_words = gpu_name.upper().replace("-", " ").split()
425
- candidates = []
426
- for flavor in HfApi(token=False).list_jobs_hardware():
427
- accelerator = flavor.accelerator
428
- if gpu_count == 0 and accelerator is None:
429
- candidates.append(flavor)
430
- elif (
431
- gpu_count > 0
432
- and accelerator is not None
433
- and accelerator.model.upper() in gpu_words
434
- and int(accelerator.quantity) == gpu_count
435
- ):
436
- candidates.append(flavor)
437
- if not candidates:
438
- return ""
439
-
440
- cores = float(os.environ.get("CPU_CORES") or 0)
441
- memory_gb = float((os.environ.get("MEMORY") or "0").upper().rstrip("GIB ") or 0)
442
-
443
- def distance(flavor) -> float:
444
- # Relative gap to the listed vCPUs and RAM; Jobs reports slightly different numbers.
445
- listed_cores = float(flavor.cpu.split()[0])
446
- listed_memory = float(flavor.ram.split()[0])
447
- return abs(listed_cores - cores) / listed_cores + abs(listed_memory - memory_gb) / listed_memory
448
-
449
- return min(candidates, key=distance).name
450
- except Exception:
451
- return ""
452
-
453
-
454
- def create_dataset_card(args, num_samples: int, counts: dict, processing_time: str) -> str:
455
- # Canonical provenance stamp (see AGENTS.md): Jobs claim gated on JOB_ID, set by HF Jobs in-container.
456
- on_jobs = os.environ.get("JOB_ID") is not None
457
- hw = jobs_flavor()
458
- origin = (
459
- "Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"
460
- + (f" (`{hw}`)" if hw else "")
461
- ) if on_jobs else "Generated"
462
- jobs_tag = "\n- hf-jobs" if on_jobs else ""
463
- status_col = f"{args.output_column}_status"
464
- flags = [f"--flavor {hw or 'a10g-large'}"]
465
- for flag, value, default in (("--split", args.split, "train"), ("--image-column", args.image_column, "image"),
466
- ("--output-column", args.output_column, "markdown"),
467
- ("--batch-size", args.batch_size, 64)):
468
- if value != default:
469
- flags.append(f"{flag} {shlex.quote(str(value))}")
470
- if args.max_samples:
471
- flags.append(f"--max-samples {args.max_samples}")
472
- if args.shuffle:
473
- flags.append(f"--shuffle --seed {args.seed}")
474
- if args.no_dspark:
475
- flags.append("--no-dspark")
476
- if args.keep_labels:
477
- flags.append("--keep-labels " + " ".join(args.keep_labels))
478
- if args.overwrite:
479
- flags.append("--overwrite")
480
- command = f"hf jobs uv run {' '.join(flags[:1])} \\\n {SCRIPT_URL} \\\n {args.input} <output-dataset>"
481
- if flags[1:]:
482
- command += " \\\n " + " ".join(flags[1:])
483
- counts_line = ", ".join(f"`{k}` {v:,}" for k, v in sorted(counts.items()))
484
- return f"""---
485
- tags:
486
- - ocr
487
- - document-processing
488
- - minicpm-ocr
489
- - markdown
490
- - uv-script
491
- - generated{jobs_tag}
492
- ---
493
-
494
- # Document OCR using MiniCPM-OCR 1.0
495
-
496
- OCR of [{args.input}](https://huggingface.co/datasets/{args.input}) with OpenBMB's
497
- [MiniCPM-OCR 1.0](https://huggingface.co/{MODEL}) pipeline: PP-DocLayoutV3 layout regions, each
498
- region read by the model, assembled into Markdown by the official SDK.
499
-
500
- ## Processing Details
501
-
502
- - **Source Dataset**: [{args.input}](https://huggingface.co/datasets/{args.input}) (split `{args.split}`, column `{args.image_column}`)
503
- - **Model**: [{MODEL}](https://huggingface.co/{MODEL}) @ `{MODEL_REVISION[:7]}`
504
- - **Decoding**: {"standard" if args.no_dspark else "DSpark speculative decoding"}
505
- - **Region types left out of the Markdown**: {", ".join(f"`{l}`" for l in SDK_IGNORED_LABELS if l not in args.keep_labels) or "none"}
506
- - **Number of Samples**: {num_samples:,}
507
- - **Page status**: {counts_line}
508
- - **Processing Time**: {processing_time}
509
- - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
510
-
511
- ## Columns
512
-
513
- - `{args.output_column}`: the SDK's Markdown for each page (tables as HTML, formulas as LaTeX); empty when
514
- the page failed
515
- - `{status_col}`: `ok`, `partial_failed` (some regions failed; text kept), `failed` or `error: ...`
516
- - `inference_info`: JSON list tracking all OCR models applied to this dataset
517
-
518
- ## Reproduction
519
-
520
- {origin} with the [`minicpm-ocr.py`]({SCRIPT_URL}) recipe from [uv-scripts](https://huggingface.co/uv-scripts). Run it yourself:
521
-
522
- ```bash
523
- {command}
524
- ```
525
- """
526
-
527
-
528
- def run_dataset(args):
529
- from datasets import load_dataset
530
- from huggingface_hub import DatasetCard
531
-
532
- status_col = f"{args.output_column}_status"
533
- reserved = {"inference_info", args.image_column}
534
- if args.output_column in reserved or status_col in reserved:
535
- sys.exit(f"--output-column {args.output_column!r} clashes with {sorted(reserved)}; pick another name")
536
-
537
- dataset = load_dataset(args.input, split=args.split)
538
- if args.shuffle:
539
- dataset = dataset.shuffle(seed=args.seed)
540
- if args.max_samples:
541
- dataset = dataset.select(range(min(args.max_samples, len(dataset))))
542
- # Undecoded: a corrupt image then fails inside parse_batch's per-page guard, not in the slice.
543
- from datasets import Image as ImageFeature
544
-
545
- dataset = dataset.cast_column(args.image_column, ImageFeature(decode=False))
546
- clash = [c for c in (args.output_column, status_col) if c in dataset.column_names]
547
- if clash and not args.overwrite:
548
- sys.exit(f"Output column(s) {clash} already exist; choose another --output-column or pass --overwrite")
549
- if clash:
550
- logger.warning("--overwrite: replacing existing column(s) %s", clash)
551
- dataset = dataset.remove_columns(clash)
552
- logger.info("%d pages from %s", len(dataset), args.input)
553
-
554
- # Slice only the image column: slicing the full dataset would decode every other image
555
- # column too, outside the per-page guard.
556
- image_only = dataset.select_columns([args.image_column])
557
- start = datetime.now()
558
- texts, statuses = [], []
559
- with vllm_server(dspark=not args.no_dspark), tempfile.TemporaryDirectory() as work:
560
- for b in range(0, len(dataset), args.batch_size):
561
- images = image_only[b: b + args.batch_size][args.image_column]
562
- results = parse_batch(dict(enumerate(images)), Path(work), f"batch{b:08d}", args.keep_labels)
563
- for i in range(len(images)):
564
- status, text = results[i]
565
- statuses.append(status)
566
- texts.append(text or "")
567
- logger.info("%d/%d pages", len(texts), len(dataset))
568
- elapsed = datetime.now() - start
569
-
570
- counts = {}
571
- for s in statuses:
572
- key = "error" if s.startswith("error") else s
573
- counts[key] = counts.get(key, 0) + 1
574
- logger.info("Page status: %s", counts)
575
-
576
- dataset = dataset.cast_column(args.image_column, ImageFeature())
577
- dataset = dataset.add_column(args.output_column, texts).add_column(status_col, statuses)
578
- entry = {"model_id": MODEL, "model_name": "MiniCPM-OCR-1.0", "column_name": args.output_column,
579
- "timestamp": datetime.now().isoformat(), "model_revision": MODEL_REVISION,
580
- "pipeline": "minicpm-ocr SDK 1.0.1 (PP-DocLayoutV3)", "dspark": not args.no_dspark,
581
- "keep_labels": args.keep_labels}
582
- if "inference_info" in dataset.column_names:
583
- def update(example):
584
- try:
585
- info = json.loads(example["inference_info"]) if example["inference_info"] else []
586
- except (json.JSONDecodeError, TypeError):
587
- info = []
588
- return {"inference_info": json.dumps(info + [entry])}
589
- dataset = dataset.map(update)
590
- else:
591
- dataset = dataset.add_column("inference_info", [json.dumps([entry])] * len(dataset))
592
-
593
- dataset.push_to_hub(args.output, private=args.private)
594
- card = create_dataset_card(args, len(dataset), counts, f"{elapsed.total_seconds() / 60:.1f} min")
595
- DatasetCard(card).push_to_hub(args.output)
596
- logger.info("Done: https://huggingface.co/datasets/%s (%.2f pages/s including startup)",
597
- args.output, len(dataset) / elapsed.total_seconds())
598
-
599
-
600
- def main():
601
- parser = argparse.ArgumentParser(
602
- description="Document OCR with the MiniCPM-OCR 1.0 pipeline",
603
- formatter_class=argparse.RawDescriptionHelpFormatter,
604
- epilog="Input/output: Hub dataset IDs (dataset mode), or hf://buckets/<ns>/<bucket>[/<prefix>] "
605
- "URLs / folders (one .md per image).")
606
- parser.add_argument("input", help="Hub dataset ID, or hf://buckets/... URL or folder of page images")
607
- parser.add_argument("output", help="Hub dataset ID (dataset input), or hf://buckets/... URL or folder")
608
- parser.add_argument("--image-column", default="image", help="Dataset mode: image column")
609
- parser.add_argument("--output-column", default="markdown", help="Dataset mode: output column")
610
- parser.add_argument("--split", default="train", help="Dataset mode: split")
611
- parser.add_argument("--max-samples", type=int, help="Process only the first N pages (for testing)")
612
- parser.add_argument("--shuffle", action="store_true", help="Dataset mode: shuffle before --max-samples")
613
- parser.add_argument("--seed", type=int, default=42)
614
- parser.add_argument("--batch-size", type=int, default=64,
615
- help="Pages handed to the SDK per run (it parallelises regions inside a run)")
616
- parser.add_argument("--no-dspark", action="store_true", help="Standard decoding, no draft model")
617
- parser.add_argument("--keep-labels", nargs="+", default=[], choices=SDK_IGNORED_LABELS,
618
- help="Region types to keep in the Markdown that the SDK leaves out by default")
619
- parser.add_argument("--private", action="store_true", help="Dataset mode: private output dataset")
620
- parser.add_argument("--overwrite", action="store_true",
621
- help="Replace an existing output column / re-OCR images that already have a .md")
622
- parser.add_argument("--hf-token", help="Hugging Face token (default: HF_TOKEN env var)")
623
- args = parser.parse_args()
624
-
625
- if args.hf_token:
626
- os.environ["HF_TOKEN"] = args.hf_token
627
- if args.max_samples is not None and args.max_samples < 1:
628
- sys.exit("--max-samples must be at least 1")
629
- if args.batch_size < 1:
630
- sys.exit("--batch-size must be at least 1")
631
- # The input decides the mode: a Bucket or an existing folder means files, anything else is a
632
- # Hub dataset ID. In file mode the output is a Bucket URL or a folder (created if new).
633
- file_in = is_bucket(args.input) or Path(args.input).is_dir()
634
- if not file_in and (is_bucket(args.output) or Path(args.output).is_dir()):
635
- sys.exit("Dataset input writes a Hub dataset; for Bucket output, give a Bucket or folder as input.")
636
- check_runtime()
637
- if file_in:
638
- run_files(args)
639
- else:
640
- run_dataset(args)
641
-
642
-
643
- if __name__ == "__main__":
644
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models.json DELETED
@@ -1,1116 +0,0 @@
1
- {
2
- "_meta": {
3
- "description": "Machine-readable catalog of the OCR recipes in this directory: script -> model, params, backend, support level, the tested Jobs launch config (the script's [tool.hf-jobs] header), and what the model's own card claims about language coverage. Human-readable language notes: LANGUAGES.md. Language evidence levels, strongest first: per-language-benchmark | count-claim | named-list | multilingual-unspecified | english-only | not-stated | not-applicable. Claims come from model cards (compiled 2026-07-15) - treat as claims, not guarantees.",
4
- "updated": "2026-11-06",
5
- "run_pattern": "hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/<script> <input-dataset> <output-dataset> (hf CLI >= 1.32 reads image/flavor/secrets from the script's [tool.hf-jobs] header; add --timeout for long runs. Scripts without a `jobs` entry need --flavor/-s HF_TOKEN (and any --image in their docstring).)",
6
- "support_levels": {
7
- "core": "Maintained. Smoke-tested flagless on HF Jobs on 2026-09-23/24 with the pinned launch config in `jobs`.",
8
- "tool": "Maintained companion (judge, layout, text extraction), not a page-OCR recipe.",
9
- "legacy": "Works (smoke-tested 2026-09-23) but superseded or little used; no header yet. See support_note for the alternative.",
10
- "unsupported": "Known broken as of 2026-09-23; kept in the repo for now. See support_note.",
11
- "experimental": "Works in testing on HF Jobs with the launch config in `jobs`, but changes often and may break. See support_note for the stable alternative."
12
- }
13
- },
14
- "tesseract-ocr.py": {
15
- "model_id": null,
16
- "model_name": "Tesseract 5",
17
- "params": null,
18
- "backend": "pytesseract (CPU)",
19
- "task": "ocr",
20
- "output": "plain text",
21
- "license": "apache-2.0",
22
- "languages": {
23
- "evidence": "named-list",
24
- "count": "125 traineddata packs (~100+ languages + script models)",
25
- "list_url": "https://github.com/tesseract-ocr/tessdata_best",
26
- "notes": "Broadest named coverage; script models (Latin, Cyrillic, Devanagari, ...) cover languages without a dedicated pack. Legacy baseline quality."
27
- },
28
- "support": "core",
29
- "jobs": {
30
- "flavor": "cpu-upgrade",
31
- "secrets": [
32
- "HF_TOKEN"
33
- ]
34
- }
35
- },
36
- "pp-ocrv6.py": {
37
- "model_id": "PaddlePaddle/PP-OCRv6",
38
- "params": "1.5M-34.5M",
39
- "backend": "paddleocr",
40
- "task": "ocr",
41
- "output": "plain text",
42
- "license": "apache-2.0",
43
- "languages": {
44
- "evidence": "count-claim",
45
- "count": 48
46
- },
47
- "support": "core",
48
- "jobs": {
49
- "flavor": "t4-small",
50
- "secrets": [
51
- "HF_TOKEN"
52
- ]
53
- }
54
- },
55
- "falcon-ocr.py": {
56
- "model_id": "tiiuae/Falcon-OCR",
57
- "params": "0.3B",
58
- "backend": "falcon-perception",
59
- "task": "ocr",
60
- "output": "markdown",
61
- "license": "apache-2.0",
62
- "languages": {
63
- "evidence": "not-stated"
64
- },
65
- "support": "legacy",
66
- "support_note": "Falcon-OCR v1; v1.5 work is in PR #110."
67
- },
68
- "smoldocling-ocr.py": {
69
- "model_id": "ds4sd/SmolDocling-256M-preview",
70
- "params": "256M",
71
- "backend": "transformers",
72
- "task": "ocr",
73
- "output": "DocTags",
74
- "languages": {
75
- "evidence": "english-only"
76
- },
77
- "support": "unsupported",
78
- "support_note": "Broken (2026-09-23): the DocTags-to-markdown converter is a stub, so rows are raw DocTags."
79
- },
80
- "surya-ocr.py": {
81
- "model_id": "datalab-to/surya-ocr-2",
82
- "params": "0.65B",
83
- "backend": "vllm",
84
- "image": "vllm/vllm-openai:v0.20.1",
85
- "task": "ocr | layout | table",
86
- "output": "markdown + surya_blocks (per-block HTML, bboxes, reading order)",
87
- "license": "modified OpenRAIL-M",
88
- "languages": {
89
- "evidence": "per-language-benchmark",
90
- "count": 91,
91
- "benchmark_url": "https://github.com/datalab-to/surya/blob/master/static/docs/multilingual.md",
92
- "notes": "38/91 languages score >=90%, 76/91 >=80%; weakest of top-15: Arabic 72.7%, Vietnamese 73.2%."
93
- },
94
- "support": "core",
95
- "jobs": {
96
- "image": "vllm/vllm-openai:v0.20.1",
97
- "python": "/usr/local/bin/python3",
98
- "env": {
99
- "PYTHONPATH": "/usr/local/lib/python3.12/site-packages"
100
- },
101
- "flavor": "a10g-small",
102
- "secrets": [
103
- "HF_TOKEN"
104
- ]
105
- }
106
- },
107
- "glm-ocr.py": {
108
- "model_id": "zai-org/GLM-OCR",
109
- "params": "0.9B",
110
- "backend": "vllm",
111
- "task": "ocr",
112
- "output": "markdown",
113
- "languages": {
114
- "evidence": "named-list",
115
- "count": 8,
116
- "named": [
117
- "zh",
118
- "en",
119
- "fr",
120
- "es",
121
- "ru",
122
- "de",
123
- "ja",
124
- "ko"
125
- ],
126
- "notes": "Declared in card metadata only; no per-language evidence in the card body."
127
- },
128
- "support": "core",
129
- "jobs": {
130
- "image": "vllm/vllm-openai:v0.30.0",
131
- "python": "/usr/bin/python3",
132
- "env": {
133
- "PYTHONPATH": "/usr/local/lib/python3.12/dist-packages"
134
- },
135
- "flavor": "a10g-small",
136
- "secrets": [
137
- "HF_TOKEN"
138
- ]
139
- },
140
- "image": "vllm/vllm-openai:v0.30.0"
141
- },
142
- "paddleocr-vl.py": {
143
- "model_id": "PaddlePaddle/PaddleOCR-VL",
144
- "params": "0.9B",
145
- "backend": "vllm",
146
- "task": "ocr | table | formula | chart",
147
- "output": "markdown",
148
- "languages": {
149
- "evidence": "count-claim",
150
- "count": 109,
151
- "notes": "Names scripts (Cyrillic, Arabic, Devanagari, Thai); claims handwriting + historical documents; no per-language numbers."
152
- },
153
- "support": "legacy",
154
- "support_note": "PaddleOCR-VL 1.0; use paddleocr-vl-1.6.py."
155
- },
156
- "paddleocr-vl-1.5.py": {
157
- "model_id": "PaddlePaddle/PaddleOCR-VL-1.5",
158
- "params": "0.9B",
159
- "backend": "transformers",
160
- "task": "ocr (6 modes)",
161
- "output": "markdown",
162
- "languages": {
163
- "evidence": "count-claim",
164
- "count": "109+ (adds Tibetan, Bengali)",
165
- "notes": "Claims improved rare-character and ancient-text recognition."
166
- },
167
- "support": "unsupported",
168
- "support_note": "Broken (2026-09-23): every row is an [OCR ERROR] ('min_pixels' attribute removed in transformers 5). Use paddleocr-vl-1.6.py."
169
- },
170
- "paddleocr-vl-1.6.py": {
171
- "model_id": "PaddlePaddle/PaddleOCR-VL-1.6",
172
- "params": "0.9B",
173
- "backend": "vllm",
174
- "task": "ocr",
175
- "output": "markdown",
176
- "languages": {
177
- "evidence": "count-claim",
178
- "count": "109+ (inherited from 1.5, not restated)",
179
- "notes": "Upgrade-focused card; language-specific claims are Chinese ancient documents and rare characters."
180
- },
181
- "support": "core",
182
- "jobs": {
183
- "image": "vllm/vllm-openai:v0.29.0",
184
- "python": "/usr/bin/python3",
185
- "env": {
186
- "PYTHONPATH": "/usr/local/lib/python3.12/dist-packages"
187
- },
188
- "flavor": "a10g-small",
189
- "secrets": [
190
- "HF_TOKEN"
191
- ]
192
- },
193
- "image": "vllm/vllm-openai:v0.29.0"
194
- },
195
- "ovis-ocr2.py": {
196
- "model_id": "ATH-MaaS/OvisOCR2",
197
- "params": "0.9B",
198
- "backend": "vllm",
199
- "task": "ocr",
200
- "output": "markdown + LaTeX + HTML tables",
201
- "license": "apache-2.0",
202
- "languages": {
203
- "evidence": "not-stated"
204
- },
205
- "support": "core",
206
- "jobs": {
207
- "image": "vllm/vllm-openai:v0.29.0",
208
- "python": "/usr/bin/python3",
209
- "env": {
210
- "PYTHONPATH": "/usr/local/lib/python3.12/dist-packages"
211
- },
212
- "flavor": "a10g-small",
213
- "secrets": [
214
- "HF_TOKEN"
215
- ]
216
- },
217
- "image": "vllm/vllm-openai:v0.29.0"
218
- },
219
- "ovis-ocr2-server.py": {
220
- "model_id": "ATH-MaaS/OvisOCR2",
221
- "params": "0.9B",
222
- "backend": "vllm-server (in-job vllm serve + concurrent driver)",
223
- "image": "vllm/vllm-openai:v0.22.1",
224
- "task": "ocr",
225
- "output": "markdown + LaTeX + HTML tables",
226
- "license": "apache-2.0",
227
- "notes": "Server-mode sibling of ovis-ocr2.py: ~1.7x its inference throughput, per-request failure isolation. See SERVING.md.",
228
- "languages": {
229
- "evidence": "not-stated"
230
- },
231
- "support": "legacy",
232
- "support_note": "Use ovis-ocr2-saturate.py (same model and server, adaptive concurrency, resumable)."
233
- },
234
- "ovis-ocr2-saturate.py": {
235
- "model_id": "ATH-MaaS/OvisOCR2",
236
- "params": "0.9B",
237
- "backend": "saturate (in-job vllm serve + saturate pump)",
238
- "image": "vllm/vllm-openai:v0.22.1",
239
- "task": "ocr",
240
- "output": "markdown + LaTeX + HTML tables",
241
- "license": "apache-2.0",
242
- "notes": "saturate companion of ovis-ocr2-server.py: same model/prompt/sampling/post-processing; the driver half (adaptive concurrency, retries, resumable parquet output, durable error rows) is the saturate library. SERVING dict at the top of the script is the machine-readable tuning prior.",
243
- "languages": {
244
- "evidence": "not-stated"
245
- },
246
- "support": "core",
247
- "jobs": {
248
- "image": "vllm/vllm-openai:v0.22.1",
249
- "flavor": "a10g-small",
250
- "secrets": [
251
- "HF_TOKEN"
252
- ]
253
- }
254
- },
255
- "xiaomi-ocr-0-saturate.py": {
256
- "model_id": "xiaomi-research/Xiaomi-OCR-0",
257
- "params": "0.8B",
258
- "backend": "saturate (in-job vllm serve or SGLang + saturate pump)",
259
- "image": "vllm/vllm-openai:v0.29.0",
260
- "task": "ocr",
261
- "output": "markdown + LaTeX + HTML tables",
262
- "license": "apache-2.0",
263
- "notes": "Single-stage whole-page mode. Card scores (96.83 OmniDocBench v1.6, 95.24 Real5, 87.94 Wild) come from Xiaomi's two-stage pipeline, which this recipe does not run. --engine sglang needs --image lmsysorg/sglang:v0.5.20-cu130. Measured on UFO scans: a10g-small 3.4 pages/s, rtx-pro-6000 9.7 pages/s, both about $0.08 per 1,000 pages excluding boot.",
264
- "languages": {
265
- "evidence": "not-stated"
266
- },
267
- "support": "core",
268
- "support_note": "Works well on clean print. On small-print historical newspapers it can loop or insert Chinese characters, with finish_reason still stop; check tables for lost items and separators.",
269
- "jobs": {
270
- "image": "vllm/vllm-openai:v0.29.0",
271
- "flavor": "a10g-small",
272
- "timeout": "4h",
273
- "secrets": [
274
- "HF_TOKEN"
275
- ]
276
- }
277
- },
278
- "lighton-ocr.py": {
279
- "model_id": "lightonai/LightOnOCR-1B-1025",
280
- "params": "1B",
281
- "backend": "vllm",
282
- "task": "ocr",
283
- "output": "markdown",
284
- "languages": {
285
- "evidence": "named-list",
286
- "count": 9,
287
- "named": [
288
- "en",
289
- "fr",
290
- "de",
291
- "es",
292
- "it",
293
- "nl",
294
- "pt",
295
- "sv",
296
- "da"
297
- ],
298
- "notes": "Explicitly European / Latin-alphabet focused."
299
- },
300
- "support": "legacy",
301
- "support_note": "LightOnOCR v1; use lighton-ocr2.py."
302
- },
303
- "lighton-ocr2.py": {
304
- "model_id": "lightonai/LightOnOCR-2-1B",
305
- "params": "1B",
306
- "backend": "vllm",
307
- "task": "ocr",
308
- "output": "markdown",
309
- "languages": {
310
- "evidence": "named-list",
311
- "count": 11,
312
- "named": [
313
- "en",
314
- "fr",
315
- "de",
316
- "es",
317
- "it",
318
- "nl",
319
- "pt",
320
- "sv",
321
- "da",
322
- "zh",
323
- "ja"
324
- ],
325
- "notes": "Adds zh/ja over v1; declared, not benchmarked per language."
326
- },
327
- "support": "core",
328
- "support_note": "Frozen 2026-11-06 (superseded by lighton-ocr3.py): image digest, package cutoff and model revision pinned; fixed only when it breaks. Use lighton-ocr3.py for new runs.",
329
- "revision": "be7c41313c30e940fe5571de59e5fabc779e00c8",
330
- "jobs": {
331
- "image": "vllm/vllm-openai@sha256:953d3a06d5e64ab582985cd7401289d3abf2a2c14ef2158e9a84313daeec77d7",
332
- "python": "/usr/bin/python3",
333
- "env": {
334
- "PYTHONPATH": "/usr/local/lib/python3.12/dist-packages"
335
- },
336
- "flavor": "a10g-small",
337
- "secrets": [
338
- "HF_TOKEN"
339
- ]
340
- },
341
- "image": "vllm/vllm-openai:v0.22.1"
342
- },
343
- "lighton-ocr3.py": {
344
- "model_id": "lightonai/LightOnOCR-3-4B",
345
- "params": "4B (or 0.8B via --model)",
346
- "backend": "vllm",
347
- "task": "ocr",
348
- "output": "markdown; --mode grounding adds labelled layout blocks with 0-1000 boxes (layout_blocks JSON column)",
349
- "license": "apache-2.0",
350
- "languages": {
351
- "evidence": "not-stated",
352
- "notes": "LightOnOCR-3 cards give no language list (LightOnOCR-2 named 11)."
353
- },
354
- "support": "core",
355
- "jobs": {
356
- "image": "vllm/vllm-openai:v0.30.0",
357
- "python": "/usr/bin/python3",
358
- "env": {
359
- "PYTHONPATH": "/usr/local/lib/python3.12/dist-packages"
360
- },
361
- "flavor": "a10g-small",
362
- "secrets": [
363
- "HF_TOKEN"
364
- ]
365
- },
366
- "image": "vllm/vllm-openai:v0.30.0",
367
- "notes": "Also runs lightonai/LightOnOCR-3-0.8B. Not LightOnOCR-3-1B (Pixtral arch, different pins). vLLM 0.30.0 pinned: upstream reports 0.27.1 loops."
368
- },
369
- "lighton-ocr3-bucket.py": {
370
- "model_id": "lightonai/LightOnOCR-3-4B",
371
- "params": "4B (or 0.8B via --model)",
372
- "backend": "vllm",
373
- "task": "ocr",
374
- "output": "one .md per image/PDF page in an output dir; --mode grounding adds a .json sidecar of layout blocks",
375
- "license": "apache-2.0",
376
- "languages": {
377
- "evidence": "not-stated",
378
- "notes": "LightOnOCR-3 cards give no language list (LightOnOCR-2 named 11)."
379
- },
380
- "support": "core",
381
- "jobs": {
382
- "image": "vllm/vllm-openai:v0.30.0",
383
- "python": "/usr/bin/python3",
384
- "env": {
385
- "PYTHONPATH": "/usr/local/lib/python3.12/dist-packages"
386
- },
387
- "flavor": "a10g-small",
388
- "secrets": [
389
- "HF_TOKEN"
390
- ]
391
- },
392
- "image": "vllm/vllm-openai:v0.30.0",
393
- "notes": "Bucket sibling of lighton-ocr3.py (same model, prompt, sampling). Input/output: hf://buckets/... URLs via bucketbag v0.3.1 (no mount) or directories. Reads .jp2; resume-by-skip."
394
- },
395
- "lighton-ocr3-saturate.py": {
396
- "model_id": "lightonai/LightOnOCR-3-0.8B",
397
- "params": "0.8B (or 4B via --model)",
398
- "backend": "saturate (in-job vllm serve + saturate pump)",
399
- "image": "vllm/vllm-openai:v0.30.0",
400
- "task": "ocr",
401
- "output": "markdown; --mode grounding adds labelled layout blocks with 0-1000 boxes (layout_blocks JSON column)",
402
- "license": "apache-2.0",
403
- "notes": "Large-run sibling of lighton-ocr3.py: same prompt modes, sampling and page resize; LightOn's serve flags (--max-model-len 18000) plus --max-num-batched-tokens 16384, and 4 vLLM API servers when CPU_CORES >= 12. Window capped by host memory. Measured 2026-11-05 (0.8B, 600 pages, steady state): a10g-small 2.2 pages/s, a100-large 7.2, rtx-pro-6000 10.0 (about $0.08 per 1,000 pages); lighton-ocr3.py: 0.90 and 1.27. Not LightOnOCR-3-1B.",
404
- "languages": {
405
- "evidence": "not-stated",
406
- "notes": "LightOnOCR-3 cards give no language list (LightOnOCR-2 named 11)."
407
- },
408
- "support": "core",
409
- "jobs": {
410
- "image": "vllm/vllm-openai:v0.30.0",
411
- "flavor": "a10g-small",
412
- "timeout": "4h",
413
- "secrets": [
414
- "HF_TOKEN"
415
- ]
416
- }
417
- },
418
- "lighton-ocr2-server.py": {
419
- "model_id": "lightonai/LightOnOCR-2-1B",
420
- "params": "1B",
421
- "backend": "vllm-server (in-job vllm serve + concurrent driver)",
422
- "image": "vllm/vllm-openai:v0.22.1",
423
- "task": "ocr",
424
- "output": "markdown",
425
- "notes": "Server-mode sibling of lighton-ocr2.py (the model card's own documented path): ~1.8x its inference throughput. See SERVING.md.",
426
- "languages": {
427
- "evidence": "named-list",
428
- "count": 11,
429
- "named": [
430
- "en",
431
- "fr",
432
- "de",
433
- "es",
434
- "it",
435
- "nl",
436
- "pt",
437
- "sv",
438
- "da",
439
- "zh",
440
- "ja"
441
- ],
442
- "notes": "Adds zh/ja over v1; declared, not benchmarked per language."
443
- },
444
- "support": "legacy",
445
- "support_note": "Use lighton-ocr2-saturate.py (same model and server, adaptive concurrency, resumable)."
446
- },
447
- "lighton-ocr2-saturate.py": {
448
- "model_id": "lightonai/LightOnOCR-2-1B",
449
- "params": "1B",
450
- "backend": "saturate (in-job vllm serve + saturate pump)",
451
- "image": "vllm/vllm-openai:v0.22.1",
452
- "task": "ocr",
453
- "output": "markdown",
454
- "notes": "saturate companion of lighton-ocr2-server.py: same model/message shape/sampling; the driver half (adaptive concurrency, retries, resumable parquet output, durable error rows) is the saturate library. SERVING dict at the top of the script is the machine-readable tuning prior.",
455
- "languages": {
456
- "evidence": "named-list",
457
- "count": 11,
458
- "named": [
459
- "en",
460
- "fr",
461
- "de",
462
- "es",
463
- "it",
464
- "nl",
465
- "pt",
466
- "sv",
467
- "da",
468
- "zh",
469
- "ja"
470
- ],
471
- "notes": "Adds zh/ja over v1; declared, not benchmarked per language."
472
- },
473
- "support": "core",
474
- "jobs": {
475
- "image": "vllm/vllm-openai:v0.22.1",
476
- "flavor": "a10g-small",
477
- "secrets": [
478
- "HF_TOKEN"
479
- ]
480
- }
481
- },
482
- "hunyuan-ocr.py": {
483
- "model_id": "tencent/HunyuanOCR",
484
- "revision": "f6af82ee007fe6091b29fb3bb287b491ead41c82",
485
- "params": "1B",
486
- "backend": "vllm",
487
- "task": "ocr",
488
- "output": "markdown",
489
- "license": "Hunyuan Community License (excludes EU/UK/KR)",
490
- "languages": {
491
- "evidence": "multilingual-unspecified"
492
- },
493
- "support": "unsupported",
494
- "support_note": "Broken (2026-09-23): the pinned 1.0 revision fails on current vLLM/transformers. Use hunyuan-ocr-1.5.py."
495
- },
496
- "hunyuan-ocr-1.5.py": {
497
- "model_id": "tencent/HunyuanOCR",
498
- "params": "1B",
499
- "backend": "vllm",
500
- "task": "ocr | 12 task types",
501
- "output": "markdown",
502
- "license": "Hunyuan Community License (excludes EU/UK/KR)",
503
- "languages": {
504
- "evidence": "multilingual-unspecified",
505
- "notes": "Explicitly targets low-resource + ancient-script OCR as a design goal; nothing enumerated."
506
- },
507
- "support": "core",
508
- "jobs": {
509
- "image": "vllm/vllm-openai:v0.24.0",
510
- "python": "/usr/bin/python3",
511
- "env": {
512
- "PYTHONPATH": "/usr/local/lib/python3.12/dist-packages"
513
- },
514
- "flavor": "a10g-small",
515
- "secrets": [
516
- "HF_TOKEN"
517
- ]
518
- },
519
- "image": "vllm/vllm-openai:v0.24.0"
520
- },
521
- "dots-ocr.py": {
522
- "model_id": "rednote-hilab/dots.ocr",
523
- "params": "1.7B",
524
- "backend": "vllm",
525
- "task": "ocr + layout",
526
- "output": "markdown",
527
- "languages": {
528
- "evidence": "count-claim",
529
- "count": 100,
530
- "notes": "Explicit low-resource claim backed by in-house dots.ocr-bench (1,493 PDFs across 100 languages); aggregate scores only."
531
- },
532
- "support": "core",
533
- "jobs": {
534
- "image": "vllm/vllm-openai:v0.30.0",
535
- "python": "/usr/bin/python3",
536
- "env": {
537
- "PYTHONPATH": "/usr/local/lib/python3.12/dist-packages"
538
- },
539
- "flavor": "a10g-small",
540
- "secrets": [
541
- "HF_TOKEN"
542
- ]
543
- },
544
- "image": "vllm/vllm-openai:v0.30.0"
545
- },
546
- "firered-ocr.py": {
547
- "model_id": "FireRedTeam/FireRed-OCR",
548
- "params": "2.1B",
549
- "backend": "vllm",
550
- "task": "ocr",
551
- "output": "markdown",
552
- "license": "apache-2.0",
553
- "languages": {
554
- "evidence": "not-stated"
555
- },
556
- "support": "legacy",
557
- "support_note": "Works; low adoption."
558
- },
559
- "abot-ocr.py": {
560
- "model_id": "acvlab/ABot-OCR",
561
- "params": "2B",
562
- "backend": "vllm",
563
- "image": "vllm/vllm-openai",
564
- "task": "ocr",
565
- "output": "markdown (text, LaTeX, HTML tables)",
566
- "languages": {
567
- "evidence": "not-stated"
568
- },
569
- "support": "legacy",
570
- "support_note": "Works; low adoption and no declared model licence."
571
- },
572
- "nanonets-ocr.py": {
573
- "model_id": "nanonets/Nanonets-OCR-s",
574
- "params": "2B",
575
- "backend": "vllm",
576
- "task": "ocr",
577
- "output": "markdown (LaTeX, tables, forms)",
578
- "languages": {
579
- "evidence": "english-only"
580
- },
581
- "support": "legacy",
582
- "support_note": "Nanonets-OCR-s; use nanonets-ocr2.py."
583
- },
584
- "dots-mocr.py": {
585
- "model_id": "rednote-hilab/dots.mocr",
586
- "params": "3B",
587
- "backend": "vllm",
588
- "task": "ocr | 8 prompt modes incl. SVG, layout + bbox",
589
- "output": "markdown",
590
- "languages": {
591
- "evidence": "multilingual-unspecified"
592
- },
593
- "support": "core",
594
- "jobs": {
595
- "image": "vllm/vllm-openai:v0.30.0",
596
- "python": "/usr/bin/python3",
597
- "env": {
598
- "PYTHONPATH": "/usr/local/lib/python3.12/dist-packages"
599
- },
600
- "flavor": "a10g-small",
601
- "secrets": [
602
- "HF_TOKEN"
603
- ]
604
- },
605
- "image": "vllm/vllm-openai:v0.30.0"
606
- },
607
- "nanonets-ocr2.py": {
608
- "model_id": "nanonets/Nanonets-OCR2-3B",
609
- "params": "3B",
610
- "backend": "vllm",
611
- "image": "vllm/vllm-openai:v0.10.2",
612
- "task": "ocr",
613
- "output": "markdown",
614
- "languages": {
615
- "evidence": "named-list",
616
- "count": "11 named + 'many more'",
617
- "named": [
618
- "en",
619
- "zh",
620
- "fr",
621
- "es",
622
- "pt",
623
- "de",
624
- "it",
625
- "ru",
626
- "ja",
627
- "ko",
628
- "ar"
629
- ],
630
- "notes": "Only card claiming multilingual handwriting; list illustrative, no per-language benchmark."
631
- },
632
- "support": "legacy",
633
- "support_note": "Works on its pinned vllm/vllm-openai:v0.10.2 image; not header-migrated."
634
- },
635
- "deepseek-ocr-vllm.py": {
636
- "model_id": "deepseek-ai/DeepSeek-OCR",
637
- "params": "4B",
638
- "backend": "vllm",
639
- "task": "ocr | 5 resolution + 5 prompt modes",
640
- "output": "markdown",
641
- "license": "mit",
642
- "languages": {
643
- "evidence": "multilingual-unspecified"
644
- },
645
- "support": "core",
646
- "jobs": {
647
- "image": "vllm/vllm-openai:v0.29.0",
648
- "python": "/usr/bin/python3",
649
- "env": {
650
- "PYTHONPATH": "/usr/local/lib/python3.12/dist-packages"
651
- },
652
- "flavor": "a10g-small",
653
- "secrets": [
654
- "HF_TOKEN"
655
- ]
656
- },
657
- "image": "vllm/vllm-openai:v0.29.0"
658
- },
659
- "jina-ocr-v1.py": {
660
- "model_id": "jinaai/jina-ocr-v1",
661
- "model_name": "jina-ocr-v1",
662
- "params": "3.4B (MoE, ~570M active)",
663
- "backend": "vllm",
664
- "task": "ocr",
665
- "output": "markdown",
666
- "license": "cc-by-nc-4.0",
667
- "notes": "DeepSeek-OCR fine-tune with a FastMTP speculative-decoding head; offline vLLM only (the checkpoint's register() must run in-process, no vllm serve path yet). Card: 91.14 OmniDocBench v1.6, 83.4 olmOCR-Bench.",
668
- "languages": {
669
- "evidence": "multilingual-unspecified",
670
- "notes": "Card metadata says multilingual; no per-language list or evidence in the card body."
671
- },
672
- "support": "unsupported",
673
- "support_note": "Broken (2026-09-23): vLLM 0.30 DeepEncoder kernel error; pinning vllm/vllm-openai:v0.29.0 likely fixes it (as for deepseek-ocr-vllm.py). CC-BY-NC-4.0 model.",
674
- "jobs": {
675
- "flavor": "a10g-small",
676
- "secrets": [
677
- "HF_TOKEN"
678
- ],
679
- "env": {
680
- "UV_TORCH_BACKEND": "auto"
681
- }
682
- }
683
- },
684
- "deepseek-ocr.py": {
685
- "model_id": "deepseek-ai/DeepSeek-OCR",
686
- "params": "4B",
687
- "backend": "transformers",
688
- "task": "ocr",
689
- "output": "markdown",
690
- "license": "mit",
691
- "languages": {
692
- "evidence": "multilingual-unspecified"
693
- },
694
- "support": "unsupported",
695
- "support_note": "Broken (2026-09-23): every output row is the string 'None' (model.infer returns None). Use deepseek-ocr-vllm.py."
696
- },
697
- "deepseek-ocr2-vllm.py": {
698
- "model_id": "deepseek-ai/DeepSeek-OCR-2",
699
- "params": "3B",
700
- "backend": "vllm (nightly)",
701
- "image": "vllm/vllm-openai:v0.29.0",
702
- "task": "ocr",
703
- "output": "markdown",
704
- "license": "apache-2.0",
705
- "languages": {
706
- "evidence": "multilingual-unspecified"
707
- },
708
- "support": "core",
709
- "jobs": {
710
- "image": "vllm/vllm-openai:v0.29.0",
711
- "python": "/usr/bin/python3",
712
- "env": {
713
- "PYTHONPATH": "/usr/local/lib/python3.12/dist-packages"
714
- },
715
- "flavor": "a10g-small",
716
- "secrets": [
717
- "HF_TOKEN"
718
- ]
719
- }
720
- },
721
- "unlimited-ocr2.py": {
722
- "model_id": "baidu/Unlimited-OCR-2",
723
- "params": "3.3B (MoE, 0.5B active)",
724
- "backend": "saturate (in-job SGLang from Baidu's wheel + saturate pump)",
725
- "image": "lmsysorg/sglang:v0.5.20-cu130",
726
- "task": "ocr (multi-page documents: folders of page images; cross-page continuations)",
727
- "output": "markdown per page + layout-grounded raw, one row per 16-page window",
728
- "license": "mit",
729
- "notes": "Sends 16 consecutive pages per request so the model keeps context across page breaks. Needs a >= 48 GB GPU (24 GB cards thrash the KV cache). Measured on 1771 Britannica: rtx-pro-6000 ~1,570 tok/s end to end. About 2% of dense 18th-century pages loop; unlimited-ocr2-saturate.py repairs them.",
730
- "languages": {
731
- "evidence": "multilingual-unspecified"
732
- },
733
- "support": "core",
734
- "jobs": {
735
- "image": "lmsysorg/sglang:v0.5.20-cu130",
736
- "flavor": "rtx-pro-6000",
737
- "timeout": "4h",
738
- "secrets": [
739
- "HF_TOKEN"
740
- ]
741
- }
742
- },
743
- "unlimited-ocr2-saturate.py": {
744
- "model_id": "baidu/Unlimited-OCR-2",
745
- "params": "3.3B (MoE, 0.5B active)",
746
- "backend": "saturate (in-job SGLang from Baidu's wheel + saturate pump)",
747
- "image": "lmsysorg/sglang:v0.5.20-cu130",
748
- "task": "ocr (multi-page documents: book volumes, PDFs; cross-page continuations)",
749
- "output": "markdown per page and per window + layout-grounded raw",
750
- "license": "mit",
751
- "notes": "Tuned version of unlimited-ocr2.py: repair pass for looping pages (fixed 28/33 in testing), PDF input, Baidu's own Markdown post-processing, speed flags.",
752
- "languages": {
753
- "evidence": "multilingual-unspecified"
754
- },
755
- "support": "experimental",
756
- "support_note": "Use unlimited-ocr2.py unless you need the repair pass, PDFs or the extras.",
757
- "jobs": {
758
- "image": "lmsysorg/sglang:v0.5.20-cu130",
759
- "flavor": "rtx-pro-6000",
760
- "timeout": "4h",
761
- "secrets": [
762
- "HF_TOKEN"
763
- ]
764
- }
765
- },
766
- "unlimited-ocr2-live.py": {
767
- "model_id": "baidu/Unlimited-OCR-2",
768
- "params": "3.3B (MoE, 0.5B active)",
769
- "backend": "saturate (in-job SGLang from Baidu's wheel + saturate pump)",
770
- "image": "lmsysorg/sglang:v0.5.20-cu130",
771
- "task": "ocr (multi-page documents) with a live view of the run",
772
- "output": "markdown per page + layout-grounded raw, one row per 16-page window",
773
- "license": "mit",
774
- "notes": "unlimited-ocr2.py plus --live-port: a dashboard served from the Job (start-up steps, the page being read with its text streaming in, finished pages, pages/min, GPU load) for watching or screen-recording a run. Measured on 1,456 Wellcome Library pages: ~130 pages/min on rtx-pro-6000.",
775
- "languages": {
776
- "evidence": "multilingual-unspecified"
777
- },
778
- "support": "experimental",
779
- "support_note": "Use unlimited-ocr2.py for normal runs; this adds a live view for demos.",
780
- "jobs": {
781
- "image": "lmsysorg/sglang:v0.5.20-cu130",
782
- "flavor": "rtx-pro-6000",
783
- "timeout": "4h",
784
- "secrets": [
785
- "HF_TOKEN"
786
- ]
787
- }
788
- },
789
- "minicpm-ocr.py": {
790
- "model_id": "openbmb/MiniCPM-OCR-1.0",
791
- "params": "1.3B",
792
- "backend": "in-job vLLM (nightly) + OpenBMB's minicpm-ocr SDK (PP-DocLayoutV3 layout, per-region prompts, Markdown assembly)",
793
- "image": "cr.hf.co/davanstrien/minicpm-ocr:1.0-vllm-5d35ce3",
794
- "task": "ocr (page images -> Markdown; tables as HTML, formulas as LaTeX); Hub dataset or Bucket/folder I/O",
795
- "output": "dataset mode: markdown + markdown_status columns; Bucket/folder mode: one .md per image (failed pages not written, re-run retries)",
796
- "license": "apache-2.0",
797
- "notes": "A region reader behind a layout model, run through the vendor SDK unchanged. Custom public image (Dockerfile in images/minicpm-ocr/): the architecture is in vLLM main but not a release, and the SDK needs PaddlePaddle in its own venv. DSpark speculative decoding on by default (--no-dspark). Bucket I/O via bucketbag v0.3.1 (no mount), resume-by-skip. Smoke-tested 2026-10-27 on BHL pages (dataset mode) and 1771 Britannica .jp2 (Bucket mode), a10g-large.",
798
- "languages": {
799
- "evidence": "named-list",
800
- "count": 2,
801
- "named": [
802
- "zh",
803
- "en"
804
- ],
805
- "notes": "Card: 'Primary languages: Chinese and English'; card metadata lists en, zh. Card examples include historical scans; fine-tuning guide uses French handwriting."
806
- },
807
- "support": "experimental",
808
- "jobs": {
809
- "image": "cr.hf.co/davanstrien/minicpm-ocr:1.0-vllm-5d35ce3",
810
- "flavor": "a10g-large",
811
- "timeout": "2h",
812
- "secrets": [
813
- "HF_TOKEN"
814
- ]
815
- }
816
- },
817
- "unlimited-ocr-vllm.py": {
818
- "model_id": "baidu/Unlimited-OCR",
819
- "params": "3.3B",
820
- "backend": "vllm",
821
- "image": "vllm/vllm-openai:unlimited-ocr",
822
- "task": "ocr (layout-grounded markdown; single-image batch)",
823
- "output": "markdown",
824
- "license": "mit",
825
- "languages": {
826
- "evidence": "multilingual-unspecified"
827
- },
828
- "support": "core",
829
- "jobs": {
830
- "image": "vllm/vllm-openai:unlimited-ocr",
831
- "python": "/usr/bin/python3",
832
- "env": {
833
- "PYTHONPATH": "/usr/local/lib/python3.12/dist-packages"
834
- },
835
- "flavor": "a10g-small",
836
- "secrets": [
837
- "HF_TOKEN"
838
- ]
839
- }
840
- },
841
- "nuextract3.py": {
842
- "model_id": "numind/NuExtract3",
843
- "params": "4B",
844
- "backend": "vllm",
845
- "image": "vllm/vllm-openai:v0.29.0",
846
- "task": "ocr | schema-guided extraction",
847
- "output": "markdown or JSON",
848
- "languages": {
849
- "evidence": "multilingual-unspecified"
850
- },
851
- "support": "core",
852
- "jobs": {
853
- "image": "vllm/vllm-openai:v0.29.0",
854
- "python": "/usr/bin/python3",
855
- "env": {
856
- "PYTHONPATH": "/usr/local/lib/python3.12/dist-packages"
857
- },
858
- "flavor": "a10g-small",
859
- "secrets": [
860
- "HF_TOKEN"
861
- ]
862
- }
863
- },
864
- "qianfan-ocr.py": {
865
- "model_id": "baidu/Qianfan-OCR",
866
- "params": "4.7B",
867
- "backend": "vllm",
868
- "task": "ocr",
869
- "output": "markdown",
870
- "languages": {
871
- "evidence": "count-claim",
872
- "count": 192,
873
- "notes": "Headline claim; no list or per-language numbers."
874
- },
875
- "support": "core",
876
- "jobs": {
877
- "image": "vllm/vllm-openai:v0.29.0",
878
- "python": "/usr/bin/python3",
879
- "env": {
880
- "PYTHONPATH": "/usr/local/lib/python3.12/dist-packages"
881
- },
882
- "flavor": "a10g-small",
883
- "secrets": [
884
- "HF_TOKEN"
885
- ]
886
- },
887
- "image": "vllm/vllm-openai:v0.29.0"
888
- },
889
- "olmocr2-vllm.py": {
890
- "model_id": "allenai/olmOCR-2-7B-1025-FP8",
891
- "params": "7B",
892
- "backend": "vllm",
893
- "task": "ocr",
894
- "output": "markdown",
895
- "languages": {
896
- "evidence": "english-only"
897
- },
898
- "support": "core",
899
- "jobs": {
900
- "image": "vllm/vllm-openai:v0.29.0",
901
- "python": "/usr/bin/python3",
902
- "env": {
903
- "PYTHONPATH": "/usr/local/lib/python3.12/dist-packages"
904
- },
905
- "flavor": "a10g-small",
906
- "secrets": [
907
- "HF_TOKEN"
908
- ]
909
- },
910
- "image": "vllm/vllm-openai:v0.29.0"
911
- },
912
- "rolm-ocr.py": {
913
- "model_id": "reducto/RolmOCR",
914
- "params": "7B",
915
- "backend": "vllm",
916
- "task": "ocr",
917
- "output": "plain text",
918
- "languages": {
919
- "evidence": "not-stated"
920
- },
921
- "support": "unsupported",
922
- "support_note": "Broken (2026-09-23): no KV cache room on a 24 GB L4 with the default settings. Use olmocr2-vllm.py."
923
- },
924
- "numarkdown-ocr.py": {
925
- "model_id": "numind/NuMarkdown-8B-Thinking",
926
- "params": "8B",
927
- "backend": "vllm",
928
- "task": "ocr (reasoning)",
929
- "output": "markdown",
930
- "languages": {
931
- "evidence": "not-stated"
932
- },
933
- "support": "legacy",
934
- "support_note": "8B reasoning model; works, little used."
935
- },
936
- "lfm2-vl-extract.py": {
937
- "model_id": "LiquidAI/LFM2.5-VL-1.6B-Extract",
938
- "params": "1.6B",
939
- "backend": "vllm",
940
- "image": "vllm/vllm-openai",
941
- "task": "schema-guided extraction (image -> JSON)",
942
- "output": "JSON",
943
- "languages": {
944
- "evidence": "english-only",
945
- "notes": "Vision card declares en only; the text sibling's 9-language list does NOT carry over."
946
- },
947
- "support": "legacy",
948
- "support_note": "Works; nuextract3.py and lift-extract.py cover image-to-JSON extraction."
949
- },
950
- "lfm2-extract.py": {
951
- "model_id": "LiquidAI/LFM2-1.2B-Extract",
952
- "params": "1.2B",
953
- "backend": "vllm",
954
- "image": "vllm/vllm-openai:v0.29.0",
955
- "task": "schema-guided extraction (text -> structured); chain after any OCR recipe",
956
- "output": "JSON / XML / YAML",
957
- "languages": {
958
- "evidence": "named-list",
959
- "count": 9,
960
- "named": [
961
- "en",
962
- "ar",
963
- "zh",
964
- "fr",
965
- "de",
966
- "ja",
967
- "ko",
968
- "pt",
969
- "es"
970
- ],
971
- "notes": "Text-only model (not OCR). Card prose names 9 incl. Portuguese; card YAML lists 8 (pt missing)."
972
- },
973
- "support": "tool",
974
- "jobs": {
975
- "image": "vllm/vllm-openai:v0.29.0",
976
- "python": "/usr/bin/python3",
977
- "env": {
978
- "PYTHONPATH": "/usr/local/lib/python3.12/dist-packages"
979
- },
980
- "flavor": "a10g-small",
981
- "secrets": [
982
- "HF_TOKEN"
983
- ]
984
- }
985
- },
986
- "lift-extract.py": {
987
- "model_id": "datalab-to/lift",
988
- "params": "9B",
989
- "backend": "transformers | vllm",
990
- "task": "schema-guided extraction (image or multi-page PDF -> JSON)",
991
- "output": "JSON",
992
- "license": "modified OpenRAIL-M",
993
- "languages": {
994
- "evidence": "not-stated"
995
- },
996
- "support": "core",
997
- "jobs": {
998
- "flavor": "a100-large",
999
- "secrets": [
1000
- "HF_TOKEN"
1001
- ]
1002
- }
1003
- },
1004
- "pp-doclayout.py": {
1005
- "model_id": "PaddlePaddle/PP-DocLayout-L",
1006
- "params": "123M",
1007
- "backend": "paddleocr",
1008
- "task": "layout detection (no text extraction)",
1009
- "output": "bounding boxes + region classes",
1010
- "languages": {
1011
- "evidence": "not-applicable"
1012
- },
1013
- "support": "tool",
1014
- "jobs": {
1015
- "flavor": "t4-small",
1016
- "secrets": [
1017
- "HF_TOKEN"
1018
- ]
1019
- }
1020
- },
1021
- "glm-ocr-v2.py": {
1022
- "variant_of": "glm-ocr.py",
1023
- "notes": "Adds checkpoint/resume for very large jobs.",
1024
- "support": "legacy",
1025
- "support_note": "Superseded by glm-ocr.py for most runs; kept for its resume support."
1026
- },
1027
- "glm-ocr-bucket.py": {
1028
- "variant_of": "glm-ocr.py",
1029
- "notes": "Reads images/PDFs from a mounted bucket, writes one .md per page.",
1030
- "support": "core",
1031
- "jobs": {
1032
- "image": "vllm/vllm-openai:v0.29.0",
1033
- "python": "/usr/bin/python3",
1034
- "env": {
1035
- "PYTHONPATH": "/usr/local/lib/python3.12/dist-packages"
1036
- },
1037
- "flavor": "a10g-small",
1038
- "secrets": [
1039
- "HF_TOKEN"
1040
- ]
1041
- },
1042
- "image": "vllm/vllm-openai:v0.29.0"
1043
- },
1044
- "falcon-ocr-bucket.py": {
1045
- "variant_of": "falcon-ocr.py",
1046
- "notes": "Reads images/PDFs from a mounted bucket, writes one .md per page.",
1047
- "support": "legacy",
1048
- "support_note": "Falcon-OCR v1; v1.5 work is in PR #110. --max-samples counts files, not pages."
1049
- },
1050
- "surya-ocr-bucket.py": {
1051
- "variant_of": "surya-ocr.py",
1052
- "notes": "Bucket-to-bucket structured OCR (--io-mode mount|copy), resumable.",
1053
- "support": "core",
1054
- "jobs": {
1055
- "image": "vllm/vllm-openai:v0.20.1",
1056
- "python": "/usr/local/bin/python3",
1057
- "env": {
1058
- "PYTHONPATH": "/usr/local/lib/python3.12/site-packages"
1059
- },
1060
- "flavor": "a10g-small",
1061
- "secrets": [
1062
- "HF_TOKEN"
1063
- ]
1064
- },
1065
- "image": "vllm/vllm-openai:v0.20.1"
1066
- },
1067
- "ocr-vllm-judge.py": {
1068
- "model_id": "configurable",
1069
- "task": "pairwise OCR-quality judging (VLM-as-judge)",
1070
- "languages": {
1071
- "evidence": "not-applicable"
1072
- },
1073
- "support": "tool",
1074
- "jobs": {
1075
- "image": "vllm/vllm-openai:v0.29.0",
1076
- "python": "/usr/bin/python3",
1077
- "env": {
1078
- "PYTHONPATH": "/usr/local/lib/python3.12/dist-packages"
1079
- },
1080
- "flavor": "a100-large",
1081
- "secrets": [
1082
- "HF_TOKEN"
1083
- ]
1084
- },
1085
- "image": "vllm/vllm-openai:v0.29.0"
1086
- },
1087
- "hpd-parsing-saturate.py": {
1088
- "model_id": "PaddlePaddle/HPD-Parsing",
1089
- "params": "1B",
1090
- "backend": "saturate (in-job vllm serve from Paddle's vLLM fork 0.17.1+hpdparsing: request forking + P-MTP speculative decoding)",
1091
- "image": "cr.hf.co/davanstrien/hpd-parsing-vllm:87496aa5-uv0.13.6",
1092
- "task": "ocr | layout",
1093
- "output": "markdown + hpd_blocks (per-block type, bbox, text; bbox 0-1000 NORMALIZED, not pixels) + raw + looped_blocks",
1094
- "license": "apache-2.0",
1095
- "notes": "Runs only on Paddle's vLLM fork, shipped in their registry image. The header image is that image (latest-nvidia-gpu, pinned by digest 87496aa5) plus uv, built by images/hpd-parsing/build.sh; the docstring also gives the command for Paddle's image directly. Serve command = the image's own entrypoint, except the P-MTP speculative head path (downloaded locally) and a --revision pin. Keeps --enable-prefix-caching ON: forked children share the parent's prefix KV. max_tokens bounds one decoding branch, not the page, so dense pages can loop in many branches; looped_blocks flags them. 94.91 OmniDocBench v1.6; accuracy below ovis-ocr2 and paddleocr-vl-1.6. ~11 GB image pull on a cold node.",
1096
- "languages": {
1097
- "evidence": "named-list",
1098
- "count": 2,
1099
- "named": [
1100
- "en",
1101
- "zh"
1102
- ],
1103
- "notes": "Card metadata lists en + zh only; no per-language numbers. Smoke runs on degraded French scans produced stray Chinese characters - treat other languages as unsupported."
1104
- },
1105
- "support": "experimental",
1106
- "support_note": "Dense pages loop: filter on looped_blocks == 0. Check a sample of your own pages.",
1107
- "jobs": {
1108
- "image": "cr.hf.co/davanstrien/hpd-parsing-vllm:87496aa5-uv0.13.6",
1109
- "flavor": "l4x1",
1110
- "timeout": "2h",
1111
- "secrets": [
1112
- "HF_TOKEN"
1113
- ]
1114
- }
1115
- }
1116
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
nanonets-ocr.py CHANGED
@@ -40,10 +40,6 @@ from huggingface_hub import DatasetCard, login
40
  from PIL import Image
41
  from toolz import partition_all
42
  from tqdm.auto import tqdm
43
- # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
44
- # default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
45
- # lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
46
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
47
  from vllm import LLM, SamplingParams
48
  from datetime import datetime
49
 
@@ -61,28 +57,6 @@ def check_cuda_availability():
61
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
62
 
63
 
64
- def ensure_output_columns_free(dataset, columns, overwrite=False):
65
- """Fail fast if an output column would collide with an existing input column.
66
-
67
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
68
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
69
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
70
- column(s) here instead (logged) so the later add_column is clean.
71
- """
72
- clash = [c for c in columns if c in dataset.column_names]
73
- if not clash:
74
- return dataset
75
- if overwrite:
76
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
77
- return dataset.remove_columns(clash)
78
- logger.error(
79
- f"Output column(s) {clash} already exist in the input dataset "
80
- f"(columns: {dataset.column_names})."
81
- )
82
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
83
- sys.exit(1)
84
-
85
-
86
  def make_ocr_message(
87
  image: Union[Image.Image, Dict[str, Any], str],
88
  prompt: str = "Extract the text from the above document as if you were reading it naturally. Return the tables in html format. Return the equations in LaTeX representation. If there is an image in the document and image caption is not present, add a small description of the image inside the <img></img> tag; otherwise, add the image caption inside <img></img>. Watermarks should be wrapped in brackets. Ex: <watermark>OFFICIAL COPY</watermark>. Page numbers should be wrapped in brackets. Ex: <page_number>14</page_number> or <page_number>9/22</page_number>. Prefer using ☐ and ☑ for check boxes.",
@@ -115,75 +89,6 @@ def make_ocr_message(
115
  ]
116
 
117
 
118
- def jobs_flavor() -> str:
119
- """Return the HF Jobs hardware flavor this run is on, or "" when it cannot be told.
120
-
121
- HF Jobs sets ACCELERATOR to "cpu" or "gpu", not the flavor name, so the flavor is looked up
122
- in the public Jobs hardware list: first by GPU model and count, then by the CPU_CORES and
123
- MEMORY values that Jobs sets in the container (to tell a10g-small from a10g-large, or
124
- cpu-basic from cpu-upgrade). Any failure (no network, older huggingface_hub) returns "".
125
- """
126
- hardware = os.environ.get("ACCELERATOR") or ""
127
- if "-" in hardware or any(character.isdigit() for character in hardware):
128
- return hardware # already a flavor name
129
- try:
130
- from huggingface_hub import HfApi
131
-
132
- gpu_name, gpu_count = "", 0
133
- try:
134
- import torch
135
-
136
- if torch.cuda.is_available():
137
- gpu_name = torch.cuda.get_device_name(0)
138
- gpu_count = torch.cuda.device_count()
139
- except ImportError:
140
- # Torch-free drivers (e.g. the -server recipes): ask nvidia-smi instead.
141
- import subprocess
142
-
143
- try:
144
- listed = subprocess.run(
145
- ["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],
146
- capture_output=True, text=True, timeout=10, check=True,
147
- ).stdout
148
- names = [line.strip() for line in listed.splitlines() if line.strip()]
149
- if names:
150
- gpu_name, gpu_count = names[0], len(names)
151
- except (OSError, subprocess.SubprocessError):
152
- pass
153
- if gpu_count == 0 and hardware == "gpu":
154
- return "" # a GPU run whose GPU cannot be identified: do not guess a CPU flavor
155
-
156
- # Whole-word match, so "L4" does not match "NVIDIA L40S" ("NVIDIA A100-SXM4-80GB" -> A100).
157
- gpu_words = gpu_name.upper().replace("-", " ").split()
158
- candidates = []
159
- for flavor in HfApi(token=False).list_jobs_hardware():
160
- accelerator = flavor.accelerator
161
- if gpu_count == 0 and accelerator is None:
162
- candidates.append(flavor)
163
- elif (
164
- gpu_count > 0
165
- and accelerator is not None
166
- and accelerator.model.upper() in gpu_words
167
- and int(accelerator.quantity) == gpu_count
168
- ):
169
- candidates.append(flavor)
170
- if not candidates:
171
- return ""
172
-
173
- cores = float(os.environ.get("CPU_CORES") or 0)
174
- memory_gb = float((os.environ.get("MEMORY") or "0").upper().rstrip("GIB ") or 0)
175
-
176
- def distance(flavor) -> float:
177
- # Relative gap to the listed vCPUs and RAM; Jobs reports slightly different numbers.
178
- listed_cores = float(flavor.cpu.split()[0])
179
- listed_memory = float(flavor.ram.split()[0])
180
- return abs(listed_cores - cores) / listed_cores + abs(listed_memory - memory_gb) / listed_memory
181
-
182
- return min(candidates, key=distance).name
183
- except Exception:
184
- return ""
185
-
186
-
187
  def create_dataset_card(
188
  source_dataset: str,
189
  model: str,
@@ -199,15 +104,6 @@ def create_dataset_card(
199
  """Create a dataset card documenting the OCR process."""
200
  model_name = model.split("/")[-1]
201
 
202
- # Canonical provenance stamp (see AGENTS.md): Jobs claim gated on JOB_ID, set by HF Jobs in-container.
203
- on_jobs = os.environ.get("JOB_ID") is not None
204
- hw = jobs_flavor() # flavor name, e.g. "a10g-small"; "" on CPU
205
- origin = (
206
- "Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"
207
- + (f" (`{hw}`)" if hw else "")
208
- ) if on_jobs else "Generated"
209
- jobs_tag = "\n- hf-jobs" if on_jobs else ""
210
-
211
  return f"""---
212
  viewer: false
213
  tags:
@@ -216,7 +112,7 @@ tags:
216
  - nanonets
217
  - markdown
218
  - uv-script
219
- - generated{jobs_tag}
220
  ---
221
 
222
  # Document OCR using {model_name}
@@ -280,10 +176,10 @@ for info in inference_info:
280
 
281
  ## Reproduction
282
 
283
- {origin} with the [`nanonets-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-ocr.py) recipe from [uv-scripts](https://huggingface.co/uv-scripts). Run it yourself:
284
 
285
  ```bash
286
- hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-ocr.py \\
287
  {source_dataset} \\
288
  <output-dataset> \\
289
  --image-column {image_column} \\
@@ -297,6 +193,8 @@ hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-
297
 
298
  - **Processing Speed**: ~{num_samples / (float(processing_time.split()[0]) * 60):.1f} images/second
299
  - **GPU Configuration**: vLLM with {gpu_memory_utilization:.0%} GPU memory utilization
 
 
300
  """
301
 
302
 
@@ -306,7 +204,7 @@ def main(
306
  image_column: str = "image",
307
  batch_size: int = 32,
308
  model: str = "nanonets/Nanonets-OCR-s",
309
- max_model_len: int = 32768,
310
  max_tokens: int = 15000,
311
  gpu_memory_utilization: float = 0.8,
312
  hf_token: str = None,
@@ -315,8 +213,6 @@ def main(
315
  private: bool = False,
316
  shuffle: bool = False,
317
  seed: int = 42,
318
- output_column: str = "markdown",
319
- overwrite: bool = False,
320
  verbose: bool = False,
321
  ):
322
  """Process images from HF dataset through OCR model."""
@@ -345,9 +241,6 @@ def main(
345
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
346
  )
347
 
348
- # Fail fast if the output column would collide with an existing input column
349
- dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
350
-
351
  # Shuffle if requested
352
  if shuffle:
353
  logger.info(f"Shuffling dataset with seed {seed}")
@@ -404,9 +297,9 @@ def main(
404
  # Add error placeholders for failed batch
405
  all_markdown.extend(["[OCR FAILED]"] * len(batch_images))
406
 
407
- # Add output column to dataset
408
- logger.info(f"Adding '{output_column}' column to dataset")
409
- dataset = dataset.add_column(output_column, all_markdown)
410
 
411
  # Handle inference_info tracking
412
  logger.info("Updating inference_info...")
@@ -414,7 +307,7 @@ def main(
414
  inference_entry = {
415
  "model_id": model,
416
  "model_name": "Nanonets-OCR-s",
417
- "column_name": output_column,
418
  "timestamp": datetime.now().isoformat(),
419
  "batch_size": batch_size,
420
  "max_tokens": max_tokens,
@@ -569,10 +462,8 @@ Examples:
569
  parser.add_argument(
570
  "--max-model-len",
571
  type=int,
572
- default=32768,
573
- help="Maximum model context length (default: 32768; must exceed --max-tokens "
574
- "15000 plus the image/prompt tokens — the old 8192 default couldn't hold the "
575
- "output budget). Model max is 128k, so there's ample room.",
576
  )
577
  parser.add_argument(
578
  "--max-tokens",
@@ -609,17 +500,6 @@ Examples:
609
  default=42,
610
  help="Random seed for shuffling (default: 42)",
611
  )
612
- parser.add_argument(
613
- "--output-column",
614
- default="markdown",
615
- help="Column name for the OCR output text (default: markdown)",
616
- )
617
- parser.add_argument(
618
- "--overwrite",
619
- action="store_true",
620
- help="Replace the output column if it already exists in the input dataset "
621
- "(default: error out to avoid clobbering an existing column).",
622
- )
623
  parser.add_argument(
624
  "--verbose",
625
  action="store_true",
@@ -643,7 +523,5 @@ Examples:
643
  private=args.private,
644
  shuffle=args.shuffle,
645
  seed=args.seed,
646
- output_column=args.output_column,
647
- overwrite=args.overwrite,
648
  verbose=args.verbose,
649
  )
 
40
  from PIL import Image
41
  from toolz import partition_all
42
  from tqdm.auto import tqdm
 
 
 
 
43
  from vllm import LLM, SamplingParams
44
  from datetime import datetime
45
 
 
57
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
58
 
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  def make_ocr_message(
61
  image: Union[Image.Image, Dict[str, Any], str],
62
  prompt: str = "Extract the text from the above document as if you were reading it naturally. Return the tables in html format. Return the equations in LaTeX representation. If there is an image in the document and image caption is not present, add a small description of the image inside the <img></img> tag; otherwise, add the image caption inside <img></img>. Watermarks should be wrapped in brackets. Ex: <watermark>OFFICIAL COPY</watermark>. Page numbers should be wrapped in brackets. Ex: <page_number>14</page_number> or <page_number>9/22</page_number>. Prefer using ☐ and ☑ for check boxes.",
 
89
  ]
90
 
91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  def create_dataset_card(
93
  source_dataset: str,
94
  model: str,
 
104
  """Create a dataset card documenting the OCR process."""
105
  model_name = model.split("/")[-1]
106
 
 
 
 
 
 
 
 
 
 
107
  return f"""---
108
  viewer: false
109
  tags:
 
112
  - nanonets
113
  - markdown
114
  - uv-script
115
+ - generated
116
  ---
117
 
118
  # Document OCR using {model_name}
 
176
 
177
  ## Reproduction
178
 
179
+ This dataset was generated using the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) Nanonets OCR script:
180
 
181
  ```bash
182
+ uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-ocr.py \\
183
  {source_dataset} \\
184
  <output-dataset> \\
185
  --image-column {image_column} \\
 
193
 
194
  - **Processing Speed**: ~{num_samples / (float(processing_time.split()[0]) * 60):.1f} images/second
195
  - **GPU Configuration**: vLLM with {gpu_memory_utilization:.0%} GPU memory utilization
196
+
197
+ Generated with 🤖 [UV Scripts](https://huggingface.co/uv-scripts)
198
  """
199
 
200
 
 
204
  image_column: str = "image",
205
  batch_size: int = 32,
206
  model: str = "nanonets/Nanonets-OCR-s",
207
+ max_model_len: int = 8192,
208
  max_tokens: int = 15000,
209
  gpu_memory_utilization: float = 0.8,
210
  hf_token: str = None,
 
213
  private: bool = False,
214
  shuffle: bool = False,
215
  seed: int = 42,
 
 
216
  verbose: bool = False,
217
  ):
218
  """Process images from HF dataset through OCR model."""
 
241
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
242
  )
243
 
 
 
 
244
  # Shuffle if requested
245
  if shuffle:
246
  logger.info(f"Shuffling dataset with seed {seed}")
 
297
  # Add error placeholders for failed batch
298
  all_markdown.extend(["[OCR FAILED]"] * len(batch_images))
299
 
300
+ # Add markdown column to dataset
301
+ logger.info("Adding markdown column to dataset")
302
+ dataset = dataset.add_column("markdown", all_markdown)
303
 
304
  # Handle inference_info tracking
305
  logger.info("Updating inference_info...")
 
307
  inference_entry = {
308
  "model_id": model,
309
  "model_name": "Nanonets-OCR-s",
310
+ "column_name": "markdown",
311
  "timestamp": datetime.now().isoformat(),
312
  "batch_size": batch_size,
313
  "max_tokens": max_tokens,
 
462
  parser.add_argument(
463
  "--max-model-len",
464
  type=int,
465
+ default=8192,
466
+ help="Maximum model context length (default: 8192)",
 
 
467
  )
468
  parser.add_argument(
469
  "--max-tokens",
 
500
  default=42,
501
  help="Random seed for shuffling (default: 42)",
502
  )
 
 
 
 
 
 
 
 
 
 
 
503
  parser.add_argument(
504
  "--verbose",
505
  action="store_true",
 
523
  private=args.private,
524
  shuffle=args.shuffle,
525
  seed=args.seed,
 
 
526
  verbose=args.verbose,
527
  )
nanonets-ocr2.py CHANGED
@@ -4,8 +4,10 @@
4
  # "datasets>=4.0.0",
5
  # "huggingface-hub",
6
  # "pillow",
 
7
  # "tqdm",
8
  # "toolz",
 
9
  # ]
10
  #
11
  # ///
@@ -24,20 +26,6 @@ Features:
24
  - Signature and watermark detection
25
  - Checkbox recognition
26
  - Multilingual support
27
-
28
- ⚠️ Pinned vLLM image required. Nanonets-OCR2-3B is a Qwen2.5-VL model, and vLLM
29
- >=0.11 regressed Qwen2.5-VL decoding to a stream of "!" (vllm-project/vllm#27775,
30
- #14126); 0.10.2 is the last known-good. So `vllm` and `torch` are intentionally
31
- omitted from the deps above and come from the `vllm/vllm-openai:v0.10.2` image at
32
- runtime via PYTHONPATH. Run it like:
33
-
34
- hf jobs uv run --flavor a10g-small -s HF_TOKEN \
35
- --image vllm/vllm-openai:v0.10.2 --python /usr/bin/python3 \
36
- -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \
37
- nanonets-ocr2.py INPUT_DATASET OUTPUT_DATASET --max-samples 10 --shuffle
38
-
39
- Re-test the pin when a newer vLLM ships a Qwen2.5-VL decode fix; it can then move
40
- back to a plain `vllm>=...` dep on the default image.
41
  """
42
 
43
  import argparse
@@ -50,33 +38,12 @@ import sys
50
  from typing import Any, Dict, List, Union
51
  from datetime import datetime
52
 
53
- # Preflight: torch/vllm are deliberately NOT PEP 723 deps (see docstring) — they come from
54
- # the pinned vllm/vllm-openai:v0.10.2 image. On the bare uv image the imports below would
55
- # die with a raw ModuleNotFoundError; fail fast naming the exact flags instead.
56
- import importlib.util
57
-
58
- if importlib.util.find_spec("vllm") is None or importlib.util.find_spec("torch") is None:
59
- sys.stderr.write(
60
- "ERROR: vllm/torch not importable — this recipe cannot run on the bare uv image.\n"
61
- "Nanonets-OCR2-3B needs vLLM 0.10.2 (>=0.11 regresses Qwen2.5-VL decoding to '!').\n"
62
- "Re-run with the pinned image + interpreter flags:\n"
63
- " hf jobs uv run --flavor a10g-small -s HF_TOKEN \\\n"
64
- " --image vllm/vllm-openai:v0.10.2 --python /usr/bin/python3 \\\n"
65
- " -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\\n"
66
- " nanonets-ocr2.py INPUT_DATASET OUTPUT_DATASET ...\n"
67
- )
68
- sys.exit(1)
69
-
70
  import torch
71
  from datasets import load_dataset
72
  from huggingface_hub import DatasetCard, login
73
  from PIL import Image
74
  from toolz import partition_all
75
  from tqdm.auto import tqdm
76
- # Disable vLLM's FlashInfer sampler (JIT-compiles a CUDA kernel; greedy OCR doesn't use it).
77
- # Harmless no-op on the pinned vllm/vllm-openai image; kept in case the pin is ever relaxed
78
- # back to an environment without nvcc.
79
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
80
  from vllm import LLM, SamplingParams
81
 
82
  logging.basicConfig(level=logging.INFO)
@@ -93,28 +60,6 @@ def check_cuda_availability():
93
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
94
 
95
 
96
- def ensure_output_columns_free(dataset, columns, overwrite=False):
97
- """Fail fast if an output column would collide with an existing input column.
98
-
99
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
100
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
101
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
102
- column(s) here instead (logged) so the later add_column is clean.
103
- """
104
- clash = [c for c in columns if c in dataset.column_names]
105
- if not clash:
106
- return dataset
107
- if overwrite:
108
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
109
- return dataset.remove_columns(clash)
110
- logger.error(
111
- f"Output column(s) {clash} already exist in the input dataset "
112
- f"(columns: {dataset.column_names})."
113
- )
114
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
115
- sys.exit(1)
116
-
117
-
118
  def make_ocr_message(
119
  image: Union[Image.Image, Dict[str, Any], str],
120
  prompt: str = "Extract the text from the above document as if you were reading it naturally. Return the tables in html format. Return the equations in LaTeX representation. If there is an image in the document and image caption is not present, add a small description of the image inside the <img></img> tag; otherwise, add the image caption inside <img></img>. Watermarks should be wrapped in brackets. Ex: <watermark>OFFICIAL COPY</watermark>. Page numbers should be wrapped in brackets. Ex: <page_number>14</page_number> or <page_number>9/22</page_number>. Prefer using ☐ and ☑ for check boxes.",
@@ -265,7 +210,7 @@ def main(
265
  image_column: str = "image",
266
  batch_size: int = 16,
267
  model: str = "nanonets/Nanonets-OCR2-3B",
268
- max_model_len: int = 32768,
269
  max_tokens: int = 15000,
270
  gpu_memory_utilization: float = 0.8,
271
  hf_token: str = None,
@@ -274,11 +219,7 @@ def main(
274
  private: bool = False,
275
  shuffle: bool = False,
276
  seed: int = 42,
277
- output_column: str = "markdown",
278
- overwrite: bool = False,
279
  verbose: bool = False,
280
- config: str = None,
281
- create_pr: bool = False,
282
  ):
283
  """Process images from HF dataset through Nanonets-OCR2-3B model."""
284
 
@@ -306,9 +247,6 @@ def main(
306
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
307
  )
308
 
309
- # Fail fast if the output column would collide with an existing input column
310
- dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
311
-
312
  # Shuffle if requested
313
  if shuffle:
314
  logger.info(f"Shuffling dataset with seed {seed}")
@@ -365,9 +303,9 @@ def main(
365
  # Add error placeholders for failed batch
366
  all_markdown.extend(["[OCR FAILED]"] * len(batch_images))
367
 
368
- # Add output column to dataset
369
- logger.info(f"Adding '{output_column}' column to dataset")
370
- dataset = dataset.add_column(output_column, all_markdown)
371
 
372
  # Handle inference_info tracking
373
  logger.info("Updating inference_info...")
@@ -375,7 +313,7 @@ def main(
375
  inference_entry = {
376
  "model_id": model,
377
  "model_name": "Nanonets-OCR2-3B",
378
- "column_name": output_column,
379
  "timestamp": datetime.now().isoformat(),
380
  "batch_size": batch_size,
381
  "max_tokens": max_tokens,
@@ -408,15 +346,7 @@ def main(
408
 
409
  # Push to hub
410
  logger.info(f"Pushing to {output_dataset}")
411
- commit_info = dataset.push_to_hub(
412
- output_dataset,
413
- private=private,
414
- token=HF_TOKEN,
415
- **({"config_name": config} if config else {}),
416
- create_pr=create_pr,
417
- commit_message=f"Add {model} OCR results ({len(dataset)} samples)"
418
- + (f" [{config}]" if config else ""),
419
- )
420
 
421
  # Calculate processing time
422
  end_time = datetime.now()
@@ -446,8 +376,6 @@ def main(
446
  logger.info(
447
  f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
448
  )
449
- if create_pr and getattr(commit_info, "pr_url", None):
450
- logger.info(f"Pull request created: {commit_info.pr_url}")
451
 
452
  if verbose:
453
  import importlib.metadata
@@ -544,8 +472,8 @@ Examples:
544
  parser.add_argument(
545
  "--max-model-len",
546
  type=int,
547
- default=32768,
548
- help="Maximum model context length (default: 32768)",
549
  )
550
  parser.add_argument(
551
  "--max-tokens",
@@ -571,15 +499,6 @@ Examples:
571
  parser.add_argument(
572
  "--private", action="store_true", help="Make output dataset private"
573
  )
574
- parser.add_argument(
575
- "--config",
576
- help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
577
- )
578
- parser.add_argument(
579
- "--create-pr",
580
- action="store_true",
581
- help="Create a pull request instead of pushing directly (for parallel benchmarking)",
582
- )
583
  parser.add_argument(
584
  "--shuffle",
585
  action="store_true",
@@ -591,17 +510,6 @@ Examples:
591
  default=42,
592
  help="Random seed for shuffling (default: 42)",
593
  )
594
- parser.add_argument(
595
- "--output-column",
596
- default="markdown",
597
- help="Column name for the OCR output text (default: markdown)",
598
- )
599
- parser.add_argument(
600
- "--overwrite",
601
- action="store_true",
602
- help="Replace the output column if it already exists in the input dataset "
603
- "(default: error out to avoid clobbering an existing column).",
604
- )
605
  parser.add_argument(
606
  "--verbose",
607
  action="store_true",
@@ -625,9 +533,5 @@ Examples:
625
  private=args.private,
626
  shuffle=args.shuffle,
627
  seed=args.seed,
628
- output_column=args.output_column,
629
- overwrite=args.overwrite,
630
  verbose=args.verbose,
631
- config=args.config,
632
- create_pr=args.create_pr,
633
  )
 
4
  # "datasets>=4.0.0",
5
  # "huggingface-hub",
6
  # "pillow",
7
+ # "vllm>=0.15.1",
8
  # "tqdm",
9
  # "toolz",
10
+ # "torch",
11
  # ]
12
  #
13
  # ///
 
26
  - Signature and watermark detection
27
  - Checkbox recognition
28
  - Multilingual support
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  """
30
 
31
  import argparse
 
38
  from typing import Any, Dict, List, Union
39
  from datetime import datetime
40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  import torch
42
  from datasets import load_dataset
43
  from huggingface_hub import DatasetCard, login
44
  from PIL import Image
45
  from toolz import partition_all
46
  from tqdm.auto import tqdm
 
 
 
 
47
  from vllm import LLM, SamplingParams
48
 
49
  logging.basicConfig(level=logging.INFO)
 
60
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
61
 
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  def make_ocr_message(
64
  image: Union[Image.Image, Dict[str, Any], str],
65
  prompt: str = "Extract the text from the above document as if you were reading it naturally. Return the tables in html format. Return the equations in LaTeX representation. If there is an image in the document and image caption is not present, add a small description of the image inside the <img></img> tag; otherwise, add the image caption inside <img></img>. Watermarks should be wrapped in brackets. Ex: <watermark>OFFICIAL COPY</watermark>. Page numbers should be wrapped in brackets. Ex: <page_number>14</page_number> or <page_number>9/22</page_number>. Prefer using ☐ and ☑ for check boxes.",
 
210
  image_column: str = "image",
211
  batch_size: int = 16,
212
  model: str = "nanonets/Nanonets-OCR2-3B",
213
+ max_model_len: int = 8192,
214
  max_tokens: int = 15000,
215
  gpu_memory_utilization: float = 0.8,
216
  hf_token: str = None,
 
219
  private: bool = False,
220
  shuffle: bool = False,
221
  seed: int = 42,
 
 
222
  verbose: bool = False,
 
 
223
  ):
224
  """Process images from HF dataset through Nanonets-OCR2-3B model."""
225
 
 
247
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
248
  )
249
 
 
 
 
250
  # Shuffle if requested
251
  if shuffle:
252
  logger.info(f"Shuffling dataset with seed {seed}")
 
303
  # Add error placeholders for failed batch
304
  all_markdown.extend(["[OCR FAILED]"] * len(batch_images))
305
 
306
+ # Add markdown column to dataset
307
+ logger.info("Adding markdown column to dataset")
308
+ dataset = dataset.add_column("markdown", all_markdown)
309
 
310
  # Handle inference_info tracking
311
  logger.info("Updating inference_info...")
 
313
  inference_entry = {
314
  "model_id": model,
315
  "model_name": "Nanonets-OCR2-3B",
316
+ "column_name": "markdown",
317
  "timestamp": datetime.now().isoformat(),
318
  "batch_size": batch_size,
319
  "max_tokens": max_tokens,
 
346
 
347
  # Push to hub
348
  logger.info(f"Pushing to {output_dataset}")
349
+ dataset.push_to_hub(output_dataset, private=private, token=HF_TOKEN)
 
 
 
 
 
 
 
 
350
 
351
  # Calculate processing time
352
  end_time = datetime.now()
 
376
  logger.info(
377
  f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
378
  )
 
 
379
 
380
  if verbose:
381
  import importlib.metadata
 
472
  parser.add_argument(
473
  "--max-model-len",
474
  type=int,
475
+ default=8192,
476
+ help="Maximum model context length (default: 8192)",
477
  )
478
  parser.add_argument(
479
  "--max-tokens",
 
499
  parser.add_argument(
500
  "--private", action="store_true", help="Make output dataset private"
501
  )
 
 
 
 
 
 
 
 
 
502
  parser.add_argument(
503
  "--shuffle",
504
  action="store_true",
 
510
  default=42,
511
  help="Random seed for shuffling (default: 42)",
512
  )
 
 
 
 
 
 
 
 
 
 
 
513
  parser.add_argument(
514
  "--verbose",
515
  action="store_true",
 
533
  private=args.private,
534
  shuffle=args.shuffle,
535
  seed=args.seed,
 
 
536
  verbose=args.verbose,
 
 
537
  )
nuextract3.py DELETED
@@ -1,784 +0,0 @@
1
- # /// script
2
- # requires-python = ">=3.11"
3
- # dependencies = [
4
- # "datasets>=3.1.0,<5.1", # 5.1 needs huggingface_hub>=1.31; the image ships an older 1.x on PYTHONPATH, which wins
5
- # "huggingface-hub",
6
- # "pillow",
7
- # "toolz",
8
- # "numind",
9
- # ]
10
- #
11
- # [tool.hf-jobs]
12
- # image = "vllm/vllm-openai:v0.29.0"
13
- # python = "/usr/bin/python3"
14
- # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
15
- # flavor = "a10g-small"
16
- # secrets = ["HF_TOKEN"]
17
- # ///
18
-
19
- """
20
- Convert document images to markdown OR extract structured JSON using NuExtract3 with vLLM.
21
-
22
- NuExtract3 is a 4B Qwen3.5-based VLM for document understanding. It does two things:
23
-
24
- 1. Document-to-Markdown OCR (default): images -> clean markdown with HTML tables,
25
- LaTeX math, and <figure> tags.
26
- 2. Schema-guided structured extraction: images + a JSON template -> JSON output
27
- shaped exactly like the template. Useful for invoices, receipts, forms, contracts.
28
-
29
- Modes are selected via flags:
30
- - (no flags) -> markdown OCR
31
- - --mode content -> plain-content extraction
32
- - --template SOURCE -> structured extraction with a NuExtract template
33
- - --schema SOURCE -> structured extraction with a JSON Schema
34
- (auto-converted via numind.nuextract_utils)
35
- - --instructions STR -> free-text guidance passed through to the model
36
- (output-format rules, branch routing, etc.).
37
- Combines with any of the modes above.
38
- See https://huggingface.co/numind/NuExtract3#instructions
39
-
40
- --template / --schema each accept inline JSON, a URL, or a local file path, so a
41
- schema can be hosted (e.g. on an HF dataset's raw URL) and reused across jobs:
42
- --template https://huggingface.co/datasets/ORG/REPO/raw/main/card.json
43
-
44
- HF Jobs invocation: the [tool.hf-jobs] header above sets the vllm/vllm-openai
45
- image (vLLM + torch come from the image, with pre-built CUDA kernels), the
46
- flavor and the HF_TOKEN secret. Needs `hf` CLI 1.32+.
47
-
48
- hf jobs uv run \\
49
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nuextract3.py \\
50
- INPUT_DATASET OUTPUT_DATASET --max-samples 5 --shuffle --seed 42
51
-
52
- On your own GPU: uv run --with vllm==0.29.0 nuextract3.py INPUT_DATASET OUTPUT_DATASET
53
-
54
- Model: numind/NuExtract3
55
- License: Apache-2.0
56
- """
57
-
58
- import argparse
59
- import base64
60
- import io
61
- import json
62
- import logging
63
- import os
64
- import sys
65
- import time
66
- from datetime import datetime
67
- from pathlib import Path
68
- from typing import Any, Dict, List, Optional, Union
69
-
70
- import torch
71
- from datasets import load_dataset
72
- from huggingface_hub import DatasetCard, login
73
- from PIL import Image
74
- from toolz import partition_all
75
- # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
76
- # default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
77
- # lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
78
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
79
- from vllm import LLM, SamplingParams
80
-
81
- logging.basicConfig(level=logging.INFO)
82
- logger = logging.getLogger(__name__)
83
-
84
- MODEL_DEFAULT = "numind/NuExtract3"
85
- MODEL_NAME = "NuExtract3"
86
-
87
-
88
- def check_cuda_availability():
89
- """Check if CUDA is available and exit if not."""
90
- if not torch.cuda.is_available():
91
- logger.error("CUDA is not available. This script requires a GPU.")
92
- logger.error("Please run on a machine with a CUDA-capable GPU.")
93
- sys.exit(1)
94
- else:
95
- logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
96
-
97
-
98
- def ensure_output_columns_free(dataset, columns, overwrite=False):
99
- """Fail fast if an output column would collide with an existing input column.
100
-
101
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
102
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
103
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
104
- column(s) here instead (logged) so the later add_column is clean.
105
- """
106
- clash = [c for c in columns if c in dataset.column_names]
107
- if not clash:
108
- return dataset
109
- if overwrite:
110
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
111
- return dataset.remove_columns(clash)
112
- logger.error(
113
- f"Output column(s) {clash} already exist in the input dataset "
114
- f"(columns: {dataset.column_names})."
115
- )
116
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
117
- sys.exit(1)
118
-
119
-
120
- def load_template_arg(value: Optional[str]) -> Optional[Dict[str, Any]]:
121
- """Load a NuExtract template/JSON Schema from inline JSON, a URL, or a file path."""
122
- if value is None:
123
- return None
124
- text = value
125
- if value.startswith(("http://", "https://")):
126
- import urllib.request
127
-
128
- with urllib.request.urlopen(value) as resp: # noqa: S310
129
- text = resp.read().decode("utf-8")
130
- elif "{" not in value:
131
- # Inline JSON often exceeds the OS filename limit, so only probe the
132
- # filesystem when the value doesn't look like JSON; treat OSError as
133
- # "not a path".
134
- try:
135
- candidate_path = Path(value)
136
- if candidate_path.is_file():
137
- text = candidate_path.read_text()
138
- except OSError:
139
- pass
140
- try:
141
- return json.loads(text)
142
- except json.JSONDecodeError as e:
143
- raise ValueError(
144
- f"Could not parse template/schema as JSON (tried URL/path/inline): {e}"
145
- ) from e
146
-
147
-
148
- def resolve_template(
149
- template_arg: Optional[str],
150
- schema_arg: Optional[str],
151
- ) -> Optional[Dict[str, Any]]:
152
- """Resolve --template / --schema into a NuExtract template dict, or None."""
153
- if template_arg and schema_arg:
154
- raise ValueError("--template and --schema are mutually exclusive.")
155
-
156
- if template_arg is not None:
157
- return load_template_arg(template_arg)
158
-
159
- if schema_arg is not None:
160
- schema = load_template_arg(schema_arg)
161
- try:
162
- from numind.nuextract_utils import convert_json_schema_to_nuextract_template
163
- except ImportError as e:
164
- raise RuntimeError(
165
- "--schema requires the `numind` package. "
166
- "It should be listed in this script's PEP 723 dependencies."
167
- ) from e
168
- template, dropped = convert_json_schema_to_nuextract_template(schema)
169
- if dropped:
170
- logger.warning(
171
- f"numind dropped {len(dropped)} unsupported branches from the JSON Schema: "
172
- f"{dropped}"
173
- )
174
- return template
175
-
176
- return None
177
-
178
-
179
- def image_to_data_uri(image: Union[Image.Image, Dict[str, Any], str]) -> str:
180
- """Normalize an HF dataset image cell to a PNG data URI."""
181
- if isinstance(image, Image.Image):
182
- pil_img = image
183
- elif isinstance(image, dict) and "bytes" in image:
184
- pil_img = Image.open(io.BytesIO(image["bytes"]))
185
- elif isinstance(image, str):
186
- pil_img = Image.open(image)
187
- else:
188
- raise ValueError(f"Unsupported image type: {type(image)}")
189
-
190
- pil_img = pil_img.convert("RGB")
191
- buf = io.BytesIO()
192
- pil_img.save(buf, format="PNG")
193
- return f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
194
-
195
-
196
- def make_message(image: Union[Image.Image, Dict[str, Any], str]) -> List[Dict]:
197
- """Build an OpenAI-format chat message containing one image."""
198
- data_uri = image_to_data_uri(image)
199
- return [
200
- {
201
- "role": "user",
202
- "content": [
203
- {"type": "image_url", "image_url": {"url": data_uri}},
204
- ],
205
- }
206
- ]
207
-
208
-
209
- def split_thinking(text: str) -> tuple[Optional[str], str]:
210
- """Return (reasoning, answer) if <think>...</think> is present, else (None, text)."""
211
- if "<think>" in text and "</think>" in text:
212
- reasoning = text.split("<think>", 1)[1].split("</think>", 1)[0].strip()
213
- answer = text.split("</think>", 1)[1].strip()
214
- return reasoning, answer
215
- return None, text.strip()
216
-
217
-
218
- def parse_json_output(text: str) -> tuple[Optional[Any], bool]:
219
- """Parse an extraction output; strip ``` fences as the model card describes.
220
-
221
- Returns (parsed_value, parse_error). On failure, parsed_value is None.
222
- """
223
- stripped = text.strip()
224
- if stripped.startswith("```"):
225
- stripped = stripped.split("\n", 1)[-1] if "\n" in stripped else stripped[3:]
226
- if stripped.endswith("```"):
227
- stripped = stripped[:-3].rstrip()
228
- try:
229
- return json.loads(stripped), False
230
- except json.JSONDecodeError:
231
- return None, True
232
-
233
-
234
- def create_dataset_card(
235
- source_dataset: str,
236
- model: str,
237
- num_samples: int,
238
- processing_time: str,
239
- mode_label: str,
240
- template: Optional[Dict[str, Any]],
241
- enable_thinking: bool,
242
- temperature: float,
243
- output_column: str,
244
- image_column: str,
245
- split: str,
246
- ) -> str:
247
- """Create a dataset card documenting the NuExtract3 run."""
248
- model_name = model.split("/")[-1]
249
- template_block = ""
250
- if template is not None:
251
- template_block = (
252
- "\n### Extraction Template\n\n```json\n"
253
- + json.dumps(template, indent=2)
254
- + "\n```\n"
255
- )
256
-
257
- return f"""---
258
- tags:
259
- - ocr
260
- - structured-extraction
261
- - document-processing
262
- - nuextract3
263
- - markdown
264
- - uv-script
265
- - generated
266
- ---
267
-
268
- # {model_name} on {source_dataset}
269
-
270
- 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.
271
-
272
- ## Processing Details
273
-
274
- - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
275
- - **Model**: [{model}](https://huggingface.co/{model})
276
- - **Mode**: {mode_label}
277
- - **Number of Samples**: {num_samples:,}
278
- - **Processing Time**: {processing_time}
279
- - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
280
-
281
- ### Configuration
282
-
283
- - **Image Column**: `{image_column}`
284
- - **Output Column**: `{output_column}`
285
- - **Dataset Split**: `{split}`
286
- - **Temperature**: {temperature}
287
- - **Thinking Mode**: {"enabled" if enable_thinking else "disabled"}
288
- {template_block}
289
- ## Dataset Structure
290
-
291
- Original columns plus:
292
- - `{output_column}`: NuExtract3 output ({"JSON string" if template else "markdown"})
293
- - `inference_info`: JSON list tracking models applied to this dataset
294
- {"- `" + output_column + "_reasoning`: model's thinking trace (when enabled)" if enable_thinking else ""}
295
-
296
- Generated with [UV Scripts](https://huggingface.co/uv-scripts)
297
- """
298
-
299
-
300
- def main(
301
- input_dataset: str,
302
- output_dataset: str,
303
- image_column: str = "image",
304
- batch_size: int = 16,
305
- max_model_len: int = 16384,
306
- max_tokens: int = 8192,
307
- gpu_memory_utilization: float = 0.8,
308
- mode: str = "markdown",
309
- template_arg: Optional[str] = None,
310
- schema_arg: Optional[str] = None,
311
- enable_thinking: bool = False,
312
- instructions: Optional[str] = None,
313
- temperature: Optional[float] = None,
314
- model: str = MODEL_DEFAULT,
315
- hf_token: str = None,
316
- split: str = "train",
317
- max_samples: int = None,
318
- private: bool = False,
319
- shuffle: bool = False,
320
- seed: int = 42,
321
- output_column: Optional[str] = None,
322
- overwrite: bool = False,
323
- verbose: bool = False,
324
- config: str = None,
325
- create_pr: bool = False,
326
- ):
327
- """Process images from an HF dataset through NuExtract3."""
328
-
329
- check_cuda_availability()
330
- start_time = datetime.now()
331
-
332
- HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
333
- if HF_TOKEN:
334
- login(token=HF_TOKEN)
335
-
336
- template = resolve_template(template_arg, schema_arg)
337
- extraction_mode = template is not None
338
- mode_label = "structured-extraction" if extraction_mode else mode
339
-
340
- if output_column is None:
341
- output_column = "extraction" if extraction_mode else "markdown"
342
-
343
- if temperature is None:
344
- temperature = 0.6 if enable_thinking else 0.2
345
-
346
- logger.info(f"Using model: {model}")
347
- logger.info(f"Mode: {mode_label}")
348
- logger.info(f"Thinking: {enable_thinking} Temperature: {temperature}")
349
- if extraction_mode:
350
- logger.info(f"Template: {json.dumps(template, indent=2)}")
351
-
352
- logger.info(f"Loading dataset: {input_dataset}")
353
- dataset = load_dataset(input_dataset, split=split)
354
-
355
- if image_column not in dataset.column_names:
356
- raise ValueError(
357
- f"Column '{image_column}' not found. Available: {dataset.column_names}"
358
- )
359
-
360
- # Fail fast if an output column would collide with an existing input column.
361
- # With --enable-thinking the script also writes "{output_column}_reasoning".
362
- out_cols = [output_column]
363
- if enable_thinking:
364
- out_cols.append(f"{output_column}_reasoning")
365
- dataset = ensure_output_columns_free(dataset, out_cols, overwrite=overwrite)
366
-
367
- if shuffle:
368
- logger.info(f"Shuffling dataset with seed {seed}")
369
- dataset = dataset.shuffle(seed=seed)
370
-
371
- if max_samples:
372
- dataset = dataset.select(range(min(max_samples, len(dataset))))
373
- logger.info(f"Limited to {len(dataset)} samples")
374
-
375
- logger.info("Initializing vLLM with NuExtract3")
376
- logger.info("This may take a few minutes on first run...")
377
- llm = LLM(
378
- model=model,
379
- trust_remote_code=True,
380
- max_model_len=max_model_len,
381
- gpu_memory_utilization=gpu_memory_utilization,
382
- limit_mm_per_prompt={"image": 1},
383
- )
384
-
385
- sampling_params = SamplingParams(
386
- temperature=temperature,
387
- max_tokens=max_tokens,
388
- )
389
-
390
- chat_template_kwargs: Dict[str, Any] = {"enable_thinking": enable_thinking}
391
- if extraction_mode:
392
- chat_template_kwargs["template"] = json.dumps(template, indent=4)
393
- else:
394
- chat_template_kwargs["mode"] = mode
395
- if instructions:
396
- chat_template_kwargs["instructions"] = instructions
397
-
398
- logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
399
- logger.info(f"Output will be written to column: {output_column}")
400
-
401
- all_outputs: List[str] = []
402
- all_reasoning: List[Optional[str]] = []
403
- all_parse_errors: List[bool] = []
404
- total_batches = (len(dataset) + batch_size - 1) // batch_size
405
- processed = 0
406
-
407
- for batch_num, batch_indices in enumerate(
408
- partition_all(batch_size, range(len(dataset))), 1
409
- ):
410
- batch_indices = list(batch_indices)
411
- batch_images = [dataset[i][image_column] for i in batch_indices]
412
-
413
- logger.info(
414
- f"Batch {batch_num}/{total_batches} "
415
- f"({processed}/{len(dataset)} images done)"
416
- )
417
-
418
- try:
419
- batch_messages = [make_message(img) for img in batch_images]
420
- outputs = llm.chat(
421
- batch_messages,
422
- sampling_params,
423
- chat_template_kwargs=chat_template_kwargs,
424
- chat_template_content_format="openai",
425
- )
426
-
427
- for output in outputs:
428
- raw_text = output.outputs[0].text
429
- reasoning, answer = split_thinking(raw_text)
430
-
431
- if extraction_mode:
432
- parsed, parse_error = parse_json_output(answer)
433
- stored = (
434
- json.dumps(parsed, ensure_ascii=False)
435
- if parsed is not None
436
- else answer
437
- )
438
- all_outputs.append(stored)
439
- all_parse_errors.append(parse_error)
440
- else:
441
- all_outputs.append(answer)
442
- all_parse_errors.append(False)
443
-
444
- all_reasoning.append(reasoning)
445
-
446
- processed += len(batch_images)
447
-
448
- except Exception as e:
449
- logger.error(f"Error processing batch: {e}")
450
- all_outputs.extend(["[NUEXTRACT3 ERROR]"] * len(batch_images))
451
- all_reasoning.extend([None] * len(batch_images))
452
- all_parse_errors.extend([True] * len(batch_images))
453
- processed += len(batch_images)
454
-
455
- processing_duration = datetime.now() - start_time
456
- processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
457
-
458
- logger.info(f"Adding '{output_column}' column to dataset")
459
- dataset = dataset.add_column(output_column, all_outputs)
460
-
461
- if enable_thinking and any(r is not None for r in all_reasoning):
462
- reasoning_col = f"{output_column}_reasoning"
463
- logger.info(f"Adding '{reasoning_col}' column to dataset")
464
- dataset = dataset.add_column(reasoning_col, all_reasoning)
465
-
466
- if extraction_mode:
467
- parse_error_count = sum(all_parse_errors)
468
- if parse_error_count:
469
- logger.warning(
470
- f"{parse_error_count}/{len(all_parse_errors)} extractions failed to parse as JSON"
471
- )
472
-
473
- inference_entry = {
474
- "model_id": model,
475
- "model_name": MODEL_NAME,
476
- "column_name": output_column,
477
- "timestamp": datetime.now().isoformat(),
478
- "mode": mode_label,
479
- "has_template": extraction_mode,
480
- "enable_thinking": enable_thinking,
481
- "temperature": temperature,
482
- "max_tokens": max_tokens,
483
- }
484
- if extraction_mode:
485
- inference_entry["parse_error_rate"] = (
486
- sum(all_parse_errors) / len(all_parse_errors) if all_parse_errors else 0.0
487
- )
488
-
489
- if "inference_info" in dataset.column_names:
490
- logger.info("Updating existing inference_info column")
491
-
492
- def update_inference_info(example):
493
- try:
494
- existing_info = (
495
- json.loads(example["inference_info"])
496
- if example["inference_info"]
497
- else []
498
- )
499
- except (json.JSONDecodeError, TypeError):
500
- existing_info = []
501
- existing_info.append(inference_entry)
502
- return {"inference_info": json.dumps(existing_info)}
503
-
504
- dataset = dataset.map(update_inference_info)
505
- else:
506
- logger.info("Creating new inference_info column")
507
- inference_list = [json.dumps([inference_entry])] * len(dataset)
508
- dataset = dataset.add_column("inference_info", inference_list)
509
-
510
- logger.info(f"Pushing to {output_dataset}")
511
- max_retries = 3
512
- for attempt in range(1, max_retries + 1):
513
- try:
514
- if attempt > 1:
515
- logger.warning("Disabling XET (fallback to HTTP upload)")
516
- os.environ["HF_HUB_DISABLE_XET"] = "1"
517
- dataset.push_to_hub(
518
- output_dataset,
519
- private=private,
520
- token=HF_TOKEN,
521
- max_shard_size="500MB",
522
- **({"config_name": config} if config else {}),
523
- create_pr=create_pr,
524
- commit_message=f"Add {model} {mode_label} results ({len(dataset)} samples)"
525
- + (f" [{config}]" if config else ""),
526
- )
527
- break
528
- except Exception as e:
529
- logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
530
- if attempt < max_retries:
531
- delay = 30 * (2 ** (attempt - 1))
532
- logger.info(f"Retrying in {delay}s...")
533
- time.sleep(delay)
534
- else:
535
- logger.error("All upload attempts failed. Results are lost.")
536
- sys.exit(1)
537
-
538
- logger.info("Creating dataset card")
539
- card_content = create_dataset_card(
540
- source_dataset=input_dataset,
541
- model=model,
542
- num_samples=len(dataset),
543
- processing_time=processing_time_str,
544
- mode_label=mode_label,
545
- template=template,
546
- enable_thinking=enable_thinking,
547
- temperature=temperature,
548
- output_column=output_column,
549
- image_column=image_column,
550
- split=split,
551
- )
552
- card = DatasetCard(card_content)
553
- card.push_to_hub(output_dataset, token=HF_TOKEN)
554
-
555
- logger.info("Done! NuExtract3 processing complete.")
556
- logger.info(
557
- f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
558
- )
559
- logger.info(f"Processing time: {processing_time_str}")
560
- logger.info(
561
- f"Processing speed: {len(dataset) / processing_duration.total_seconds():.2f} images/sec"
562
- )
563
-
564
- if verbose:
565
- import importlib.metadata
566
-
567
- logger.info("--- Resolved package versions ---")
568
- for pkg in [
569
- "vllm",
570
- "transformers",
571
- "torch",
572
- "datasets",
573
- "pyarrow",
574
- "pillow",
575
- "numind",
576
- ]:
577
- try:
578
- logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
579
- except importlib.metadata.PackageNotFoundError:
580
- logger.info(f" {pkg}: not installed")
581
- logger.info("--- End versions ---")
582
-
583
-
584
- if __name__ == "__main__":
585
- if len(sys.argv) == 1:
586
- print("=" * 70)
587
- print("NuExtract3 - Document-to-Markdown + Structured Extraction (4B)")
588
- print("=" * 70)
589
- print("\nModes:")
590
- print(" markdown - Image -> markdown (default)")
591
- print(" content - Image -> plain content")
592
- print(" --template / --schema - Image -> JSON shaped like the template")
593
- print("\nExamples:")
594
- print("\n1. Markdown OCR:")
595
- print(" uv run --with vllm==0.29.0 nuextract3.py input-dataset output-dataset")
596
- print("\n2. Structured extraction with an inline template:")
597
- print(" uv run --with vllm==0.29.0 nuextract3.py input output \\")
598
- print(' --template \'{"title": "verbatim-string", "date": "date"}\'')
599
- print("\n3. Structured extraction from a JSON Schema (e.g. Pydantic):")
600
- print(" uv run --with vllm==0.29.0 nuextract3.py input output --schema schema.json")
601
- print("\n (--template / --schema also accept a URL or a local file path)")
602
- print("\n4. Reasoning mode for harder documents:")
603
- print(" uv run --with vllm==0.29.0 nuextract3.py input output --enable-thinking")
604
- print("\n5. Test with 10 samples:")
605
- print(" uv run --with vllm==0.29.0 nuextract3.py large-ds test --max-samples 10 --shuffle")
606
- print("\n6. Running on HF Jobs (image/flavor/secrets from the script header, hf 1.32+):")
607
- print(" hf jobs uv run \\")
608
- print(
609
- " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nuextract3.py \\"
610
- )
611
- print(" input-dataset output-dataset --batch-size 16")
612
- print("\nFor full help: uv run --with vllm==0.29.0 nuextract3.py --help")
613
- sys.exit(0)
614
-
615
- parser = argparse.ArgumentParser(
616
- description="NuExtract3: document-to-markdown + schema-guided JSON extraction (4B VLM)",
617
- formatter_class=argparse.RawDescriptionHelpFormatter,
618
- epilog="""
619
- Modes:
620
- (default) Markdown OCR (image -> clean markdown)
621
- --mode content
622
- Plain-content extraction (less structured than markdown)
623
- --template PATH_OR_JSON
624
- Structured extraction with a NuExtract template
625
- --schema PATH_OR_JSON
626
- Structured extraction from a JSON Schema
627
- (e.g. Pydantic Model.model_json_schema())
628
-
629
- Examples:
630
- uv run --with vllm==0.29.0 nuextract3.py my-docs analyzed-docs
631
- uv run --with vllm==0.29.0 nuextract3.py receipts extracted \\
632
- --template '{"store": "verbatim-string", "total": "number"}'
633
- uv run --with vllm==0.29.0 nuextract3.py contracts extracted --schema contract_schema.json
634
- uv run --with vllm==0.29.0 nuextract3.py hard-docs out --enable-thinking
635
- """,
636
- )
637
-
638
- parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
639
- parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
640
- parser.add_argument(
641
- "--image-column",
642
- default="image",
643
- help="Column containing images (default: image)",
644
- )
645
- parser.add_argument(
646
- "--batch-size",
647
- type=int,
648
- default=16,
649
- help="Batch size for processing (default: 16)",
650
- )
651
- parser.add_argument(
652
- "--max-model-len",
653
- type=int,
654
- default=16384,
655
- help="Maximum model context length (default: 16384)",
656
- )
657
- parser.add_argument(
658
- "--max-tokens",
659
- type=int,
660
- default=8192,
661
- help="Maximum tokens to generate (default: 8192)",
662
- )
663
- parser.add_argument(
664
- "--gpu-memory-utilization",
665
- type=float,
666
- default=0.8,
667
- help="GPU memory utilization (default: 0.8)",
668
- )
669
- parser.add_argument(
670
- "--mode",
671
- choices=["markdown", "content"],
672
- default="markdown",
673
- help="OCR mode when no template/schema is given (default: markdown)",
674
- )
675
- parser.add_argument(
676
- "--template",
677
- help="NuExtract template: inline JSON, a URL, or a file path",
678
- )
679
- parser.add_argument(
680
- "--schema",
681
- help="JSON Schema to auto-convert: inline JSON, a URL, or a file path",
682
- )
683
- parser.add_argument(
684
- "--enable-thinking",
685
- action="store_true",
686
- help="Enable reasoning mode (slower, better on hard documents)",
687
- )
688
- parser.add_argument(
689
- "--instructions",
690
- default=None,
691
- help=(
692
- "Free-text instructions passed to NuExtract via "
693
- "chat_template_kwargs.instructions (e.g. routing guidance across "
694
- "optional schema branches, output-format rules). "
695
- "See https://huggingface.co/numind/NuExtract3#instructions"
696
- ),
697
- )
698
- parser.add_argument(
699
- "--temperature",
700
- type=float,
701
- default=None,
702
- help="Sampling temperature (default: 0.2 non-thinking, 0.6 thinking)",
703
- )
704
- parser.add_argument(
705
- "--model",
706
- default=MODEL_DEFAULT,
707
- help=f"Model ID (default: {MODEL_DEFAULT})",
708
- )
709
- parser.add_argument("--hf-token", help="Hugging Face API token")
710
- parser.add_argument(
711
- "--split", default="train", help="Dataset split to use (default: train)"
712
- )
713
- parser.add_argument(
714
- "--max-samples",
715
- type=int,
716
- help="Maximum number of samples to process (for testing)",
717
- )
718
- parser.add_argument(
719
- "--private", action="store_true", help="Make output dataset private"
720
- )
721
- parser.add_argument(
722
- "--config",
723
- help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
724
- )
725
- parser.add_argument(
726
- "--create-pr",
727
- action="store_true",
728
- help="Create a pull request instead of pushing directly (for parallel benchmarking)",
729
- )
730
- parser.add_argument(
731
- "--shuffle", action="store_true", help="Shuffle dataset before processing"
732
- )
733
- parser.add_argument(
734
- "--seed",
735
- type=int,
736
- default=42,
737
- help="Random seed for shuffling (default: 42)",
738
- )
739
- parser.add_argument(
740
- "--output-column",
741
- default=None,
742
- help="Column name for output (default: 'markdown' in OCR mode, 'extraction' in template mode)",
743
- )
744
- parser.add_argument(
745
- "--overwrite",
746
- action="store_true",
747
- help="Replace the output column if it already exists in the input dataset "
748
- "(default: error out to avoid clobbering an existing column).",
749
- )
750
- parser.add_argument(
751
- "--verbose",
752
- action="store_true",
753
- help="Log resolved package versions after processing",
754
- )
755
-
756
- args = parser.parse_args()
757
-
758
- main(
759
- input_dataset=args.input_dataset,
760
- output_dataset=args.output_dataset,
761
- image_column=args.image_column,
762
- batch_size=args.batch_size,
763
- max_model_len=args.max_model_len,
764
- max_tokens=args.max_tokens,
765
- gpu_memory_utilization=args.gpu_memory_utilization,
766
- mode=args.mode,
767
- template_arg=args.template,
768
- schema_arg=args.schema,
769
- enable_thinking=args.enable_thinking,
770
- instructions=args.instructions,
771
- temperature=args.temperature,
772
- model=args.model,
773
- hf_token=args.hf_token,
774
- split=args.split,
775
- max_samples=args.max_samples,
776
- private=args.private,
777
- shuffle=args.shuffle,
778
- seed=args.seed,
779
- output_column=args.output_column,
780
- overwrite=args.overwrite,
781
- verbose=args.verbose,
782
- config=args.config,
783
- create_pr=args.create_pr,
784
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
numarkdown-ocr.py CHANGED
@@ -47,10 +47,6 @@ from huggingface_hub import DatasetCard, login
47
  from PIL import Image
48
  from toolz import partition_all
49
  from tqdm.auto import tqdm
50
- # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
51
- # default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
52
- # lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
53
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
54
  from vllm import LLM, SamplingParams
55
 
56
  logging.basicConfig(level=logging.INFO)
@@ -75,28 +71,6 @@ def check_gpu_availability() -> int:
75
  return num_gpus
76
 
77
 
78
- def ensure_output_columns_free(dataset, columns, overwrite=False):
79
- """Fail fast if an output column would collide with an existing input column.
80
-
81
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
82
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
83
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
84
- column(s) here instead (logged) so the later add_column is clean.
85
- """
86
- clash = [c for c in columns if c in dataset.column_names]
87
- if not clash:
88
- return dataset
89
- if overwrite:
90
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
91
- return dataset.remove_columns(clash)
92
- logger.error(
93
- f"Output column(s) {clash} already exist in the input dataset "
94
- f"(columns: {dataset.column_names})."
95
- )
96
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
97
- sys.exit(1)
98
-
99
-
100
  def validate_and_resize_image(
101
  image: Image.Image,
102
  min_pixels: int = 100 * 28 * 28,
@@ -339,7 +313,6 @@ def main(
339
  temperature: float = 0.0,
340
  custom_prompt: Optional[str] = None,
341
  output_column: str = "markdown",
342
- overwrite: bool = False,
343
  config: str = None,
344
  create_pr: bool = False,
345
  verbose: bool = False,
@@ -384,9 +357,6 @@ def main(
384
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
385
  )
386
 
387
- # Fail fast if the output column would collide with an existing input column
388
- dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
389
-
390
  # Shuffle if requested
391
  if shuffle:
392
  logger.info(f"Shuffling dataset with seed {seed}")
@@ -603,7 +573,7 @@ if __name__ == "__main__":
603
  " uv run numarkdown-ocr.py large-docs processed-docs --tensor-parallel-size 2"
604
  )
605
  print("\n7. Running on HF Jobs:")
606
- print(" hf jobs uv run --flavor a100x4 \\")
607
  print(
608
  ' -e HF_TOKEN=$(python3 -c "from huggingface_hub import get_token; print(get_token())") \\'
609
  )
@@ -726,12 +696,6 @@ Examples:
726
  default="markdown",
727
  help="Column name for output text (default: markdown)",
728
  )
729
- parser.add_argument(
730
- "--overwrite",
731
- action="store_true",
732
- help="Replace the output column if it already exists in the input dataset "
733
- "(default: error out to avoid clobbering an existing column).",
734
- )
735
  parser.add_argument(
736
  "--config",
737
  help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
@@ -769,7 +733,6 @@ Examples:
769
  temperature=args.temperature,
770
  custom_prompt=args.custom_prompt,
771
  output_column=args.output_column,
772
- overwrite=args.overwrite,
773
  config=args.config,
774
  create_pr=args.create_pr,
775
  verbose=args.verbose,
 
47
  from PIL import Image
48
  from toolz import partition_all
49
  from tqdm.auto import tqdm
 
 
 
 
50
  from vllm import LLM, SamplingParams
51
 
52
  logging.basicConfig(level=logging.INFO)
 
71
  return num_gpus
72
 
73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  def validate_and_resize_image(
75
  image: Image.Image,
76
  min_pixels: int = 100 * 28 * 28,
 
313
  temperature: float = 0.0,
314
  custom_prompt: Optional[str] = None,
315
  output_column: str = "markdown",
 
316
  config: str = None,
317
  create_pr: bool = False,
318
  verbose: bool = False,
 
357
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
358
  )
359
 
 
 
 
360
  # Shuffle if requested
361
  if shuffle:
362
  logger.info(f"Shuffling dataset with seed {seed}")
 
573
  " uv run numarkdown-ocr.py large-docs processed-docs --tensor-parallel-size 2"
574
  )
575
  print("\n7. Running on HF Jobs:")
576
+ print(" hf jobs uv run --flavor a100x2 \\")
577
  print(
578
  ' -e HF_TOKEN=$(python3 -c "from huggingface_hub import get_token; print(get_token())") \\'
579
  )
 
696
  default="markdown",
697
  help="Column name for output text (default: markdown)",
698
  )
 
 
 
 
 
 
699
  parser.add_argument(
700
  "--config",
701
  help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
 
733
  temperature=args.temperature,
734
  custom_prompt=args.custom_prompt,
735
  output_column=args.output_column,
 
736
  config=args.config,
737
  create_pr=args.create_pr,
738
  verbose=args.verbose,
ocr-vllm-judge.py CHANGED
@@ -2,20 +2,14 @@
2
  # /// script
3
  # requires-python = ">=3.11"
4
  # dependencies = [
5
- # "datasets>=4.0.0,<5.1", # 5.1 needs huggingface_hub>=1.31; the image ships an older 1.x on PYTHONPATH, which wins
6
  # "huggingface-hub",
7
  # "pillow",
 
 
8
  # "rich",
9
  # "tqdm",
10
  # ]
11
- #
12
- # [tool.hf-jobs]
13
- # image = "vllm/vllm-openai:v0.29.0"
14
- # python = "/usr/bin/python3"
15
- # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
16
- # flavor = "a100-large"
17
- # timeout = "1h"
18
- # secrets = ["HF_TOKEN"]
19
  # ///
20
  """
21
  Offline vLLM judge for OCR benchmark evaluation.
@@ -41,10 +35,8 @@ Usage:
41
  --judge-model Qwen/Qwen2.5-VL-7B-Instruct \\
42
  --max-samples 50
43
 
44
- # Via HF Job. The [tool.hf-jobs] header pins vllm/vllm-openai:v0.29.0 (the
45
- # default uv image has no nvcc, which vLLM needs at warmup) and a100-large
46
- # (the default 7B judge does not leave room for the KV cache on a 24 GB L4).
47
- hf jobs uv run --timeout 1h \\
48
  ocr-vllm-judge.py davanstrien/ocr-bench-nls-50 --from-prs \\
49
  --judge-model Qwen/Qwen3-VL-8B-Instruct --max-samples 50
50
  """
@@ -644,7 +636,7 @@ Examples:
644
  --max-samples 50
645
 
646
  # Via HF Job
647
- hf jobs uv run --timeout 1h \\
648
  ocr-vllm-judge.py my-bench --from-prs \\
649
  --judge-model Qwen/Qwen3-VL-8B-Instruct
650
  """,
@@ -703,9 +695,6 @@ Examples:
703
  default=None,
704
  help="Push judge results to this HF dataset repo (e.g. davanstrien/ocr-bench-rubenstein-judge)",
705
  )
706
- parser.add_argument(
707
- "--private", action="store_true", help="Create the --save-results repo as private"
708
- )
709
  args = parser.parse_args()
710
 
711
  # --- CUDA check ---
@@ -787,7 +776,7 @@ Examples:
787
 
788
  # Comparisons config
789
  comp_ds = Dataset.from_list(comparison_log)
790
- comp_ds.push_to_hub(args.save_results, config_name="comparisons", private=args.private)
791
  console.print(f" Pushed [cyan]comparisons[/cyan] ({len(comparison_log)} rows)")
792
 
793
  # Leaderboard config
@@ -806,7 +795,7 @@ Examples:
806
  }
807
  )
808
  Dataset.from_list(leaderboard_rows).push_to_hub(
809
- args.save_results, config_name="leaderboard", private=args.private
810
  )
811
  console.print(
812
  f" Pushed [cyan]leaderboard[/cyan] ({len(leaderboard_rows)} rows)"
@@ -824,7 +813,7 @@ Examples:
824
  "from_prs": args.from_prs,
825
  }
826
  Dataset.from_list([metadata_row]).push_to_hub(
827
- args.save_results, config_name="metadata", private=args.private
828
  )
829
  console.print(" Pushed [cyan]metadata[/cyan]")
830
  console.print(f" [green]Results saved to: {args.save_results}[/green]")
 
2
  # /// script
3
  # requires-python = ">=3.11"
4
  # dependencies = [
5
+ # "datasets>=4.0.0",
6
  # "huggingface-hub",
7
  # "pillow",
8
+ # "vllm>=0.15.1",
9
+ # "torch",
10
  # "rich",
11
  # "tqdm",
12
  # ]
 
 
 
 
 
 
 
 
13
  # ///
14
  """
15
  Offline vLLM judge for OCR benchmark evaluation.
 
35
  --judge-model Qwen/Qwen2.5-VL-7B-Instruct \\
36
  --max-samples 50
37
 
38
+ # Via HF Job
39
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
 
 
40
  ocr-vllm-judge.py davanstrien/ocr-bench-nls-50 --from-prs \\
41
  --judge-model Qwen/Qwen3-VL-8B-Instruct --max-samples 50
42
  """
 
636
  --max-samples 50
637
 
638
  # Via HF Job
639
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
640
  ocr-vllm-judge.py my-bench --from-prs \\
641
  --judge-model Qwen/Qwen3-VL-8B-Instruct
642
  """,
 
695
  default=None,
696
  help="Push judge results to this HF dataset repo (e.g. davanstrien/ocr-bench-rubenstein-judge)",
697
  )
 
 
 
698
  args = parser.parse_args()
699
 
700
  # --- CUDA check ---
 
776
 
777
  # Comparisons config
778
  comp_ds = Dataset.from_list(comparison_log)
779
+ comp_ds.push_to_hub(args.save_results, config_name="comparisons")
780
  console.print(f" Pushed [cyan]comparisons[/cyan] ({len(comparison_log)} rows)")
781
 
782
  # Leaderboard config
 
795
  }
796
  )
797
  Dataset.from_list(leaderboard_rows).push_to_hub(
798
+ args.save_results, config_name="leaderboard"
799
  )
800
  console.print(
801
  f" Pushed [cyan]leaderboard[/cyan] ({len(leaderboard_rows)} rows)"
 
813
  "from_prs": args.from_prs,
814
  }
815
  Dataset.from_list([metadata_row]).push_to_hub(
816
+ args.save_results, config_name="metadata"
817
  )
818
  console.print(" Pushed [cyan]metadata[/cyan]")
819
  console.print(f" [green]Results saved to: {args.save_results}[/green]")
olmocr2-vllm.py CHANGED
@@ -1,21 +1,16 @@
1
  # /// script
2
  # requires-python = ">=3.11"
3
  # dependencies = [
4
- # "datasets>=4.0.0,<5.1", # 5.1 needs huggingface_hub>=1.31; the image ships an older 1.x on PYTHONPATH, which wins
5
  # "huggingface-hub",
6
  # "pillow",
 
7
  # "tqdm",
8
  # "toolz",
 
9
  # "pyyaml", # For parsing YAML front matter
10
  # ]
11
  #
12
- # [tool.hf-jobs]
13
- # image = "vllm/vllm-openai:v0.29.0"
14
- # python = "/usr/bin/python3"
15
- # env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
16
- # flavor = "a10g-small"
17
- # timeout = "2h"
18
- # secrets = ["HF_TOKEN"]
19
  # ///
20
 
21
  """
@@ -35,13 +30,6 @@ Features:
35
 
36
  Model: allenai/olmOCR-2-7B-1025-FP8
37
  Based on: Qwen2.5-VL-7B-Instruct fine-tuned on olmOCR-mix
38
-
39
- Run on HF Jobs (the [tool.hf-jobs] header sets image, flavor and secrets;
40
- needs `hf` CLI 1.32+):
41
- hf jobs uv run olmocr2-vllm.py input-dataset output-dataset
42
-
43
- Run on your own GPU (vLLM and torch come from the Jobs image, so add vLLM):
44
- uv run --with vllm==0.29.0 olmocr2-vllm.py input-dataset output-dataset
45
  """
46
 
47
  import argparse
@@ -62,11 +50,8 @@ from huggingface_hub import DatasetCard, login
62
  from PIL import Image
63
  from toolz import partition_all
64
  from tqdm.auto import tqdm
65
- # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
66
- # default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
67
- # lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
68
- os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
69
  from vllm import LLM, SamplingParams
 
70
 
71
  logging.basicConfig(level=logging.INFO)
72
  logger = logging.getLogger(__name__)
@@ -93,28 +78,6 @@ def check_cuda_availability():
93
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
94
 
95
 
96
- def ensure_output_columns_free(dataset, columns, overwrite=False):
97
- """Fail fast if an output column would collide with an existing input column.
98
-
99
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
100
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
101
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
102
- column(s) here instead (logged) so the later add_column is clean.
103
- """
104
- clash = [c for c in columns if c in dataset.column_names]
105
- if not clash:
106
- return dataset
107
- if overwrite:
108
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
109
- return dataset.remove_columns(clash)
110
- logger.error(
111
- f"Output column(s) {clash} already exist in the input dataset "
112
- f"(columns: {dataset.column_names})."
113
- )
114
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
115
- sys.exit(1)
116
-
117
-
118
  def parse_yaml_frontmatter(text: str) -> tuple[dict, str]:
119
  """
120
  Parse YAML front matter from olmOCR output.
@@ -277,14 +240,15 @@ Each row contains:
277
  ## Reproduction
278
 
279
  ```bash
280
- # Using HF Jobs (recommended; the script header sets image/flavor/secrets, hf CLI 1.32+)
281
- hf jobs uv run \\
 
282
  https://huggingface.co/datasets/uv-scripts/ocr/raw/main/olmocr2-vllm.py \\
283
  {source_dataset} \\
284
  your-username/output-dataset
285
 
286
  # Local with GPU
287
- uv run --with vllm==0.29.0 https://huggingface.co/datasets/uv-scripts/ocr/raw/main/olmocr2-vllm.py \\
288
  {source_dataset} \\
289
  your-username/output-dataset
290
  ```
@@ -313,7 +277,6 @@ def main(
313
  output_dataset: str,
314
  image_column: str = "image",
315
  output_column: str = "markdown",
316
- overwrite: bool = False,
317
  batch_size: int = 16,
318
  model: str = "allenai/olmOCR-2-7B-1025-FP8",
319
  max_model_len: int = 16384,
@@ -327,8 +290,6 @@ def main(
327
  private: bool = False,
328
  shuffle: bool = False,
329
  seed: int = 42,
330
- config: str = None,
331
- create_pr: bool = False,
332
  ):
333
  """
334
  Process a dataset of document images through olmOCR-2 to extract markdown.
@@ -369,9 +330,6 @@ def main(
369
  logger.info(f"Loading dataset: {input_dataset}")
370
  ds = load_dataset(input_dataset, split=split)
371
 
372
- # Fail fast if the output column would collide with an existing input column
373
- ds = ensure_output_columns_free(ds, [output_column], overwrite=overwrite)
374
-
375
  # Shuffle if requested
376
  if shuffle:
377
  logger.info(f"Shuffling dataset with seed {seed}")
@@ -407,25 +365,13 @@ def main(
407
  "stop": ["<|im_end|>", "<|endoftext|>"],
408
  }
409
 
410
- # Add guided decoding if requested (enforces YAML front matter structure).
411
- # vLLM 0.22.x renamed this API: GuidedDecodingParams (guided_decoding=) →
412
- # StructuredOutputsParams (structured_outputs=). Import lazily + shim so the
413
- # default path (guided_decoding=False) never touches the moved symbol.
414
  if guided_decoding:
415
  logger.info("Enabling guided decoding with YAML front matter regex")
416
- front_matter_regex = r"---\nprimary_language: (?:[a-z]{2}|null)\nis_rotation_valid: (?:True|False|true|false)\nrotation_correction: (?:0|90|180|270)\nis_table: (?:True|False|true|false)\nis_diagram: (?:True|False|true|false)\n(?:---|---\n[\s\S]+)"
417
- try:
418
- from vllm.sampling_params import StructuredOutputsParams
419
-
420
- sampling_params_kwargs["structured_outputs"] = StructuredOutputsParams(
421
- regex=front_matter_regex
422
- )
423
- except ImportError:
424
- from vllm.sampling_params import GuidedDecodingParams
425
-
426
- sampling_params_kwargs["guided_decoding"] = GuidedDecodingParams(
427
- regex=front_matter_regex
428
- )
429
 
430
  sampling_params = SamplingParams(**sampling_params_kwargs)
431
 
@@ -474,41 +420,36 @@ def main(
474
  ds = ds.remove_columns([metadata_column_name])
475
  ds = ds.add_column(metadata_column_name, all_metadata)
476
 
477
- # Add inference information — standard schema: a JSON-string LIST of entries, each carrying
478
- # model_id (used as the leaderboard label) and column_name (the output text column). The
479
- # script's own extras (version, timestamp, sampling params) ride along as extra keys.
480
- inference_entry = {
481
- "model_id": model,
482
- "column_name": output_column,
483
- "script": "olmocr2-vllm.py",
484
- "version": "1.0.0",
485
- "timestamp": datetime.now().isoformat(),
486
- "batch_size": batch_size,
487
- "max_tokens": max_tokens,
488
- "temperature": temperature,
489
- }
490
 
491
- # Handle existing inference_info column (append to the list; create a fresh list otherwise)
492
  if inference_info_column in ds.column_names:
493
- logger.info("Updating existing inference_info column")
494
-
495
  def update_inference_info(example):
496
  try:
497
- existing_info = (
498
- json.loads(example[inference_info_column])
499
- if example[inference_info_column]
500
- else []
501
- )
502
- except (json.JSONDecodeError, TypeError):
503
- existing_info = []
504
- existing_info.append(inference_entry)
505
- return {inference_info_column: json.dumps(existing_info)}
506
 
507
  ds = ds.map(update_inference_info)
508
  else:
509
- logger.info("Creating new inference_info column")
510
- inference_list = [json.dumps([inference_entry])] * len(ds)
511
- ds = ds.add_column(inference_info_column, inference_list)
512
 
513
  # Calculate processing time
514
  elapsed_time = time.time() - start_time
@@ -533,13 +474,9 @@ def main(
533
 
534
  # Push to hub
535
  logger.info(f"Pushing to HuggingFace Hub: {output_dataset}")
536
- commit_info = ds.push_to_hub(
537
  output_dataset,
538
  private=private,
539
- **({"config_name": config} if config else {}),
540
- create_pr=create_pr,
541
- commit_message=f"Add {model} OCR results ({len(ds)} samples)"
542
- + (f" [{config}]" if config else ""),
543
  )
544
 
545
  # Update dataset card
@@ -550,8 +487,6 @@ def main(
550
  logger.info(f"✓ Dataset: https://huggingface.co/datasets/{output_dataset}")
551
  logger.info(f"✓ Processing time: {processing_time}")
552
  logger.info(f"✓ Samples processed: {len(ds):,}")
553
- if create_pr and getattr(commit_info, "pr_url", None):
554
- logger.info(f"✓ Pull request created: {commit_info.pr_url}")
555
 
556
 
557
  if __name__ == "__main__":
@@ -562,30 +497,32 @@ if __name__ == "__main__":
562
  Examples:
563
 
564
  1. Basic OCR on a dataset:
565
- uv run --with vllm==0.29.0 olmocr2-vllm.py input-dataset output-dataset
566
 
567
  2. Test with first 10 samples:
568
- uv run --with vllm==0.29.0 olmocr2-vllm.py input-dataset output-dataset --max-samples 10
569
 
570
  3. Process with custom batch size:
571
- uv run --with vllm==0.29.0 olmocr2-vllm.py input-dataset output-dataset --batch-size 8
572
 
573
  4. Custom image column:
574
- uv run --with vllm==0.29.0 olmocr2-vllm.py input-dataset output-dataset --image-column page_image
575
 
576
  5. Private output dataset:
577
- uv run --with vllm==0.29.0 olmocr2-vllm.py input-dataset output-dataset --private
578
 
579
  6. Random sampling:
580
- uv run --with vllm==0.29.0 olmocr2-vllm.py input-dataset output-dataset --max-samples 100 --shuffle
581
 
582
- 7. Running on HuggingFace Jobs (header sets image/flavor/secrets; hf CLI 1.32+):
583
- hf jobs uv run \\
 
584
  https://huggingface.co/datasets/uv-scripts/ocr/raw/main/olmocr2-vllm.py \\
585
  input-dataset output-dataset
586
 
587
  8. Real example with historical documents:
588
- hf jobs uv run --timeout 2h \\
 
589
  https://huggingface.co/datasets/uv-scripts/ocr/raw/main/olmocr2-vllm.py \\
590
  NationalLibraryOfScotland/Britain-and-UK-Handbooks-Dataset \\
591
  your-username/handbooks-olmocr \\
@@ -606,12 +543,6 @@ Examples:
606
  default="markdown",
607
  help="Column name for markdown output (default: markdown)",
608
  )
609
- parser.add_argument(
610
- "--overwrite",
611
- action="store_true",
612
- help="Replace the output column if it already exists in the input dataset "
613
- "(default: error out to avoid clobbering an existing column).",
614
- )
615
  parser.add_argument(
616
  "--batch-size",
617
  type=int,
@@ -671,15 +602,6 @@ Examples:
671
  action="store_true",
672
  help="Make output dataset private",
673
  )
674
- parser.add_argument(
675
- "--config",
676
- help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
677
- )
678
- parser.add_argument(
679
- "--create-pr",
680
- action="store_true",
681
- help="Create a pull request instead of pushing directly (for parallel benchmarking)",
682
- )
683
  parser.add_argument(
684
  "--shuffle",
685
  action="store_true",
@@ -698,7 +620,6 @@ Examples:
698
  output_dataset=args.output_dataset,
699
  image_column=args.image_column,
700
  output_column=args.output_column,
701
- overwrite=args.overwrite,
702
  batch_size=args.batch_size,
703
  model=args.model,
704
  max_model_len=args.max_model_len,
@@ -712,6 +633,4 @@ Examples:
712
  private=args.private,
713
  shuffle=args.shuffle,
714
  seed=args.seed,
715
- config=args.config,
716
- create_pr=args.create_pr,
717
  )
 
1
  # /// script
2
  # requires-python = ">=3.11"
3
  # dependencies = [
4
+ # "datasets",
5
  # "huggingface-hub",
6
  # "pillow",
7
+ # "vllm",
8
  # "tqdm",
9
  # "toolz",
10
+ # "torch",
11
  # "pyyaml", # For parsing YAML front matter
12
  # ]
13
  #
 
 
 
 
 
 
 
14
  # ///
15
 
16
  """
 
30
 
31
  Model: allenai/olmOCR-2-7B-1025-FP8
32
  Based on: Qwen2.5-VL-7B-Instruct fine-tuned on olmOCR-mix
 
 
 
 
 
 
 
33
  """
34
 
35
  import argparse
 
50
  from PIL import Image
51
  from toolz import partition_all
52
  from tqdm.auto import tqdm
 
 
 
 
53
  from vllm import LLM, SamplingParams
54
+ from vllm.sampling_params import GuidedDecodingParams
55
 
56
  logging.basicConfig(level=logging.INFO)
57
  logger = logging.getLogger(__name__)
 
78
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
79
 
80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  def parse_yaml_frontmatter(text: str) -> tuple[dict, str]:
82
  """
83
  Parse YAML front matter from olmOCR output.
 
240
  ## Reproduction
241
 
242
  ```bash
243
+ # Using HF Jobs (recommended)
244
+ hf jobs uv run --flavor l4x1 \\
245
+ -s HF_TOKEN \\
246
  https://huggingface.co/datasets/uv-scripts/ocr/raw/main/olmocr2-vllm.py \\
247
  {source_dataset} \\
248
  your-username/output-dataset
249
 
250
  # Local with GPU
251
+ uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/olmocr2-vllm.py \\
252
  {source_dataset} \\
253
  your-username/output-dataset
254
  ```
 
277
  output_dataset: str,
278
  image_column: str = "image",
279
  output_column: str = "markdown",
 
280
  batch_size: int = 16,
281
  model: str = "allenai/olmOCR-2-7B-1025-FP8",
282
  max_model_len: int = 16384,
 
290
  private: bool = False,
291
  shuffle: bool = False,
292
  seed: int = 42,
 
 
293
  ):
294
  """
295
  Process a dataset of document images through olmOCR-2 to extract markdown.
 
330
  logger.info(f"Loading dataset: {input_dataset}")
331
  ds = load_dataset(input_dataset, split=split)
332
 
 
 
 
333
  # Shuffle if requested
334
  if shuffle:
335
  logger.info(f"Shuffling dataset with seed {seed}")
 
365
  "stop": ["<|im_end|>", "<|endoftext|>"],
366
  }
367
 
368
+ # Add guided decoding if requested (enforces YAML front matter structure)
 
 
 
369
  if guided_decoding:
370
  logger.info("Enabling guided decoding with YAML front matter regex")
371
+ guided_params = GuidedDecodingParams(
372
+ regex=r"---\nprimary_language: (?:[a-z]{2}|null)\nis_rotation_valid: (?:True|False|true|false)\nrotation_correction: (?:0|90|180|270)\nis_table: (?:True|False|true|false)\nis_diagram: (?:True|False|true|false)\n(?:---|---\n[\s\S]+)"
373
+ )
374
+ sampling_params_kwargs["guided_decoding"] = guided_params
 
 
 
 
 
 
 
 
 
375
 
376
  sampling_params = SamplingParams(**sampling_params_kwargs)
377
 
 
420
  ds = ds.remove_columns([metadata_column_name])
421
  ds = ds.add_column(metadata_column_name, all_metadata)
422
 
423
+ # Add inference information
424
+ inference_info = json.dumps(
425
+ {
426
+ "model": model,
427
+ "script": "olmocr2-vllm.py",
428
+ "version": "1.0.0",
429
+ "timestamp": datetime.now().isoformat(),
430
+ "batch_size": batch_size,
431
+ "max_tokens": max_tokens,
432
+ "temperature": temperature,
433
+ }
434
+ )
 
435
 
436
+ # Handle existing inference_info column
437
  if inference_info_column in ds.column_names:
438
+ # Parse existing, append new model info
 
439
  def update_inference_info(example):
440
  try:
441
+ existing = json.loads(example[inference_info_column])
442
+ if not isinstance(existing, list):
443
+ existing = [existing]
444
+ except (json.JSONDecodeError, KeyError):
445
+ existing = []
446
+
447
+ existing.append(json.loads(inference_info))
448
+ return {inference_info_column: json.dumps(existing)}
 
449
 
450
  ds = ds.map(update_inference_info)
451
  else:
452
+ ds = ds.add_column(inference_info_column, [inference_info] * len(ds))
 
 
453
 
454
  # Calculate processing time
455
  elapsed_time = time.time() - start_time
 
474
 
475
  # Push to hub
476
  logger.info(f"Pushing to HuggingFace Hub: {output_dataset}")
477
+ ds.push_to_hub(
478
  output_dataset,
479
  private=private,
 
 
 
 
480
  )
481
 
482
  # Update dataset card
 
487
  logger.info(f"✓ Dataset: https://huggingface.co/datasets/{output_dataset}")
488
  logger.info(f"✓ Processing time: {processing_time}")
489
  logger.info(f"✓ Samples processed: {len(ds):,}")
 
 
490
 
491
 
492
  if __name__ == "__main__":
 
497
  Examples:
498
 
499
  1. Basic OCR on a dataset:
500
+ uv run olmocr2-vllm.py input-dataset output-dataset
501
 
502
  2. Test with first 10 samples:
503
+ uv run olmocr2-vllm.py input-dataset output-dataset --max-samples 10
504
 
505
  3. Process with custom batch size:
506
+ uv run olmocr2-vllm.py input-dataset output-dataset --batch-size 8
507
 
508
  4. Custom image column:
509
+ uv run olmocr2-vllm.py input-dataset output-dataset --image-column page_image
510
 
511
  5. Private output dataset:
512
+ uv run olmocr2-vllm.py input-dataset output-dataset --private
513
 
514
  6. Random sampling:
515
+ uv run olmocr2-vllm.py input-dataset output-dataset --max-samples 100 --shuffle
516
 
517
+ 7. Running on HuggingFace Jobs:
518
+ hf jobs uv run --flavor l4x1 \\
519
+ -s HF_TOKEN \\
520
  https://huggingface.co/datasets/uv-scripts/ocr/raw/main/olmocr2-vllm.py \\
521
  input-dataset output-dataset
522
 
523
  8. Real example with historical documents:
524
+ hf jobs uv run --flavor l4x1 \\
525
+ -s HF_TOKEN \\
526
  https://huggingface.co/datasets/uv-scripts/ocr/raw/main/olmocr2-vllm.py \\
527
  NationalLibraryOfScotland/Britain-and-UK-Handbooks-Dataset \\
528
  your-username/handbooks-olmocr \\
 
543
  default="markdown",
544
  help="Column name for markdown output (default: markdown)",
545
  )
 
 
 
 
 
 
546
  parser.add_argument(
547
  "--batch-size",
548
  type=int,
 
602
  action="store_true",
603
  help="Make output dataset private",
604
  )
 
 
 
 
 
 
 
 
 
605
  parser.add_argument(
606
  "--shuffle",
607
  action="store_true",
 
620
  output_dataset=args.output_dataset,
621
  image_column=args.image_column,
622
  output_column=args.output_column,
 
623
  batch_size=args.batch_size,
624
  model=args.model,
625
  max_model_len=args.max_model_len,
 
633
  private=args.private,
634
  shuffle=args.shuffle,
635
  seed=args.seed,
 
 
636
  )
ovis-ocr2-saturate.py DELETED
@@ -1,254 +0,0 @@
1
- # /// script
2
- # requires-python = ">=3.11"
3
- # dependencies = [
4
- # "saturate[hf]==0.3.0",
5
- # "pillow>=10",
6
- # ]
7
- #
8
- # [tool.hf-jobs]
9
- # image = "vllm/vllm-openai:v0.22.1"
10
- # flavor = "a10g-small"
11
- # timeout = "4h"
12
- # secrets = ["HF_TOKEN"]
13
- # ///
14
- """
15
- Convert document images to markdown using OvisOCR2 via saturate.
16
-
17
- Companion to `ovis-ocr2-server.py`: same model, prompt, message shape, sampling,
18
- and post-processing, same in-job `vllm serve` — but the driver half (concurrency,
19
- retries, output, resume) is the `saturate` library instead of hand-rolled code.
20
- What that buys over the -server recipe:
21
-
22
- - **Adaptive concurrency** — the window sizes itself from live engine signals
23
- (no `--concurrency` flag to tune).
24
- - **Crash-safe, resumable output** — results stream to the output repo as
25
- parquet parts while the run is hot; re-running the same command skips
26
- everything already done (exact anti-join on id).
27
- - **Durable error rows** — a failed page is recorded as `{id, error}` instead of
28
- an `[OCR ERROR]` string in the text column; `--retry-errors` re-admits only
29
- those rows on a later run.
30
-
31
- Run on HF Jobs. The script starts `vllm serve` itself; its [tool.hf-jobs] header
32
- declares the image that provides the `vllm` binary, the hardware and the HF_TOKEN
33
- secret (`hf` CLI 1.32+). Pass --timeout for a long run; flags override the header:
34
-
35
- hf jobs uv run --detach --timeout 4h \\
36
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/ovis-ocr2-saturate.py \\
37
- <input-dataset> <output-dataset>
38
-
39
- Smoke test first with --max-samples 3. On your own GPU (vllm on PATH):
40
-
41
- uv run --with vllm==0.22.1 ovis-ocr2-saturate.py <input-dataset> <output-dataset>
42
-
43
- Output layout (differs from the -server recipe, which pushes input+markdown):
44
- the output repo holds `data/part-*.parquet` with rows
45
- `{id, markdown, model, prompt_tokens, completion_tokens, error}` keyed by the
46
- input row id (`--id-column`, or `<split>-<index>` by default). Read it with
47
- `datasets.load_dataset(<output>, data_dir="data")` or `saturate.read_output`;
48
- join back to the input on id. Run metadata lands in `data/completions/`.
49
-
50
- Model: ATH-MaaS/OvisOCR2 (0.9B, Apache-2.0, 96.58 OmniDocBench)
51
- - The card's exact OCR prompt (leading newline included — outputs are tuned to
52
- this wording), image before text, `enable_thinking=False` via
53
- chat_template_kwargs (the Qwen3.5 template otherwise injects a thinking
54
- preamble).
55
- - Images downscaled client-side to the processor's max_pixels bound (8.3MP) and
56
- sent as JPEG q95 — the same clamp the server would apply, moved client-side to
57
- shrink the payload; min/max pixel bounds ride on the engine boot flag.
58
- - Post-processing per the card: bbox `<img>` placeholder blocks dropped (keep
59
- with --keep-image-tags) and degenerate trailing repeats trimmed.
60
-
61
- The SERVING dict below is the per-model tuning prior (serve flags + client
62
- sampling + context math). Agents can `ast.literal_eval` it without running
63
- the script; the script itself consumes it, so it cannot drift from reality.
64
- """
65
-
66
- import argparse
67
- import base64
68
- import io
69
- import math
70
- import sys
71
-
72
- # Serving starting values for ATH-MaaS/OvisOCR2. Per-value provenance:
73
- # - The card documents OFFLINE inference only — no `vllm serve` command exists
74
- # upstream. The whole server arrangement here (incl. serve_args) is the
75
- # uv-scripts construction inherited from ovis-ocr2-server.py.
76
- # - max_model_len 32768: house choice (card sets none; native ctx is 262144 —
77
- # NEVER boot without a cap on 24GB, the full-context KV profile kills boot).
78
- # - cache/mm flags: house OCR defaults (OCR never reuses images, so prefix/
79
- # processor caches only cost memory).
80
- # - mm-processor-kwargs pixel bounds: card's offline example, verbatim
81
- # (min 448*448=200704, max 2880*2880=8294400), moved to the engine flag.
82
- # - max_tokens 16384 / temperature 0.0: card's sampling, verbatim.
83
- # Throughput receipt (a10g-small, 20 pages): 4,057 tok/s, window ramped to 32.
84
- SERVING = {
85
- "model": "ATH-MaaS/OvisOCR2",
86
- "image": "vllm/vllm-openai:v0.22.1",
87
- "max_model_len": 32768,
88
- "serve_args": [
89
- "--limit-mm-per-prompt", '{"image": 1}',
90
- "--mm-processor-cache-gb", "0",
91
- "--no-enable-prefix-caching",
92
- "--mm-processor-kwargs",
93
- '{"images_kwargs": {"min_pixels": 200704, "max_pixels": 8294400}}',
94
- ],
95
- "max_tokens": 16384,
96
- "temperature": 0.0,
97
- "max_pixels": 8294400,
98
- }
99
- assert SERVING["max_tokens"] < SERVING["max_model_len"], (
100
- "context math: max_tokens must leave room for the image tokens "
101
- "(input + output <= max_model_len, or every request 400s)"
102
- )
103
-
104
- OCR_PROMPT = (
105
- "\nExtract all readable content from the image in natural human reading order "
106
- "and output the result as a single Markdown document. For charts or images, "
107
- 'represent them using an HTML image tag: <img src="images/bbox_{left}_{top}_{right}_{bottom}.jpg" />, '
108
- "where left, top, right, bottom are bounding box coordinates scaled to [0, 1000). "
109
- "Format formulas as LaTeX. Format tables as HTML: <table>...</table>. "
110
- "Transcribe all other text as standard Markdown. Preserve the original text "
111
- "without translation or paraphrasing."
112
- )
113
-
114
-
115
- def to_pil(value):
116
- from PIL import Image
117
-
118
- if isinstance(value, Image.Image):
119
- return value
120
- if isinstance(value, dict) and value.get("bytes"):
121
- return Image.open(io.BytesIO(value["bytes"]))
122
- if isinstance(value, (bytes, bytearray)):
123
- return Image.open(io.BytesIO(value))
124
- raise ValueError(f"unsupported image value: {type(value)}")
125
-
126
-
127
- def encode_image(value, max_pixels: int) -> str:
128
- """RGB-convert, downscale to max_pixels if needed, return base64 JPEG q95."""
129
- from PIL import Image
130
-
131
- img = to_pil(value).convert("RGB")
132
- w, h = img.size
133
- if w * h > max_pixels:
134
- scale = math.sqrt(max_pixels / (w * h))
135
- img = img.resize((int(w * scale), int(h * scale)), Image.LANCZOS)
136
- buf = io.BytesIO()
137
- img.save(buf, format="JPEG", quality=95)
138
- return base64.b64encode(buf.getvalue()).decode()
139
-
140
-
141
- def clean_truncated_repeats(
142
- text: str,
143
- min_text_len: int = 8000,
144
- max_period: int = 200,
145
- min_period: int = 1,
146
- min_repeat_chars: int = 100,
147
- min_repeat_times: int = 5,
148
- ) -> str:
149
- """Trim degenerate trailing repetition (verbatim port of the model card's cleanup)."""
150
- n = len(text)
151
- if n < min_text_len:
152
- return text
153
-
154
- max_period = min(max_period, n - 1)
155
- for unit_len in range(min_period, max_period + 1):
156
- if text[n - 1] != text[n - 1 - unit_len]:
157
- continue
158
-
159
- match_len = 1
160
- idx = n - 2
161
- while idx >= unit_len and text[idx] == text[idx - unit_len]:
162
- match_len += 1
163
- idx -= 1
164
-
165
- total_len = match_len + unit_len
166
- repeat_times = total_len // unit_len
167
- tail_len = total_len % unit_len
168
-
169
- if repeat_times >= min_repeat_times and total_len >= min_repeat_chars:
170
- return text[: n - total_len + unit_len] + text[n - tail_len:]
171
-
172
- return text
173
-
174
-
175
- def filter_image_tags(text: str) -> str:
176
- blocks = text.split("\n\n")
177
- return "\n\n".join(
178
- b for b in blocks if not b.strip().startswith('<img src="images/bbox_')
179
- )
180
-
181
-
182
- def main():
183
- ap = argparse.ArgumentParser(description="OvisOCR2 batch OCR via saturate")
184
- ap.add_argument("input_dataset", help="Input dataset repo id (rows with an image column)")
185
- ap.add_argument("output_dataset", help="Output dataset repo id (created if missing)")
186
- ap.add_argument("--image-column", default="image")
187
- ap.add_argument("--config", default=None, help="Dataset config name")
188
- ap.add_argument("--split", default="train")
189
- ap.add_argument("--id-column", default=None,
190
- help="Column to use as row id (default: split-index ids)")
191
- ap.add_argument("--max-samples", "--limit", dest="limit", type=int, default=None,
192
- help="Process only the first N rows (smoke test)")
193
- ap.add_argument("--max-tokens", type=int, default=SERVING["max_tokens"])
194
- ap.add_argument("--keep-image-tags", action="store_true",
195
- help="Keep the bbox <img> placeholder blocks in the output")
196
- ap.add_argument("--retry-errors", action="store_true",
197
- help="Re-admit rows whose only record is an error row")
198
- args = ap.parse_args()
199
-
200
- import pyarrow as pa
201
- from saturate import Auto, Engine, dataset_rows, pump
202
-
203
- rows = dataset_rows(
204
- args.input_dataset, config=args.config, split=args.split,
205
- columns=[args.image_column], ids=args.id_column or "index", limit=args.limit,
206
- )
207
-
208
- def to_request(row):
209
- b64 = encode_image(row[args.image_column], SERVING["max_pixels"])
210
- return {
211
- "model": SERVING["model"],
212
- "messages": [{"role": "user", "content": [
213
- {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64}"}},
214
- {"type": "text", "text": OCR_PROMPT},
215
- ]}],
216
- "temperature": SERVING["temperature"],
217
- "max_tokens": args.max_tokens,
218
- "chat_template_kwargs": {"enable_thinking": False},
219
- }
220
-
221
- # Declared, so a part holding only error rows has the same columns as the rest
222
- # (datasets.load_dataset reads every part with one schema).
223
- schema = pa.schema([
224
- ("id", pa.string()), ("error", pa.string()), ("markdown", pa.string()),
225
- ("model", pa.string()), ("prompt_tokens", pa.int64()), ("completion_tokens", pa.int64()),
226
- ]) # fmt: skip
227
-
228
- def parse(row, body):
229
- text = body["choices"][0]["message"]["content"].strip()
230
- if not args.keep_image_tags:
231
- text = filter_image_tags(text)
232
- text = clean_truncated_repeats(text)
233
- usage = body.get("usage") or {}
234
- return {
235
- "markdown": text,
236
- "model": SERVING["model"],
237
- "prompt_tokens": usage.get("prompt_tokens"),
238
- "completion_tokens": usage.get("completion_tokens"),
239
- }
240
-
241
- extra = ["--max-model-len", str(SERVING["max_model_len"]), *SERVING["serve_args"]]
242
- output = f"hf://datasets/{args.output_dataset}/data"
243
- with Engine(SERVING["model"], engine="vllm", extra_args=extra) as endpoint:
244
- stats = pump(rows, to_request, parse, endpoint, output,
245
- window=Auto(initial=8, max_limit=48),
246
- retry_errors=args.retry_errors, schema=schema)
247
-
248
- print(f"https://huggingface.co/datasets/{args.output_dataset} "
249
- f"({stats.rows_processed} ok, {stats.rows_failed} error rows)", file=sys.stderr)
250
- print("OVIS_OCR2_SATURATE " + stats.to_json(), flush=True)
251
-
252
-
253
- if __name__ == "__main__":
254
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ovis-ocr2-server.py DELETED
@@ -1,794 +0,0 @@
1
- # /// script
2
- # requires-python = ">=3.11"
3
- # dependencies = [
4
- # "datasets>=4.0.0",
5
- # "huggingface-hub",
6
- # "pillow",
7
- # "requests",
8
- # ]
9
- # ///
10
-
11
- """
12
- Convert document images to markdown using OvisOCR2 via an in-job vLLM server.
13
-
14
- Same model, prompt, and outputs as ovis-ocr2.py, but serves the model behind
15
- `vllm serve` inside the job and posts images concurrently — continuous batching
16
- stays fed instead of draining at each offline `llm.generate()` batch barrier,
17
- and a bad image fails one request instead of a whole batch of 16.
18
-
19
- This script is the *driver* half: it expects the server on localhost (started
20
- by the job command below), loads the input dataset, posts images concurrently,
21
- postprocesses (repeat-trim + img-tag filter, as in ovis-ocr2.py), and pushes
22
- the result dataset. The driver has no torch/vllm deps, so `uv run` starts in
23
- seconds while the server warms up in parallel.
24
-
25
- NOTE: OvisOCR2's card documents offline vLLM only (checked 2026-07-16) — this
26
- server translation is ours, not the authors'. The serve flags below mirror the
27
- card's offline args; treat A/B output parity with ovis-ocr2.py as part of any
28
- benchmark run (same --max-samples slice, diff the markdown columns).
29
-
30
- Run on HF Jobs (standard uv-run shape — the script starts `vllm serve` itself
31
- as a subprocess when no server is already reachable; the only thing to get
32
- right is the --image flag, which provides the `vllm` binary):
33
-
34
- hf jobs uv run --detach --flavor l4x1 -s HF_TOKEN --timeout 4h \\
35
- --image vllm/vllm-openai:v0.22.1 \\
36
- https://huggingface.co/datasets/uv-scripts/ocr/raw/main/ovis-ocr2-server.py \\
37
- <input-dataset> <output-dataset>
38
-
39
- To use an already-running or remote endpoint instead, pass --server URL — the
40
- script only spawns a server when the (default localhost) URL is unreachable.
41
- The serve flags live in SERVE_ARGS below, the single source of truth.
42
-
43
- Serve-flag provenance (the card only shows offline `LLM(...)` args):
44
- - `--no-enable-prefix-caching --mm-processor-cache-gb 0`: the recurring official
45
- OCR-serving pattern (DeepSeek-OCR vLLM recipe, LightOnOCR, PaddleOCR-VL recipe)
46
- — OCR never reuses images, the caches only cost memory.
47
- - `--mm-processor-kwargs`: server-side equivalent of the card's per-request
48
- `images_kwargs` pixel bounds. The driver ALSO downscales oversized images
49
- client-side to the same max_pixels, so outputs match even if the server flag
50
- is dropped.
51
- - The card's offline `gdn_prefill_backend="triton"` (JIT/nvcc workaround for the
52
- bare uv image) is NOT needed here: the vllm-openai image ships the full CUDA
53
- toolchain. Add `--gdn-prefill-backend triton` to the serve command if the
54
- default backend misbehaves.
55
- - `enable_thinking=False` (card-mandated, Qwen3.5 templates can inject a
56
- thinking preamble) is passed per-request via `chat_template_kwargs`.
57
-
58
- Model: ATH-MaaS/OvisOCR2 (0.9B, Apache-2.0, 96.58 OmniDocBench v1.6)
59
- vLLM: stock Qwen3_5ForConditionalGeneration arch, needs vllm >= 0.22.1.
60
- """
61
-
62
- import argparse
63
- import atexit
64
- import base64
65
- import concurrent.futures
66
- import io
67
- import json
68
- import logging
69
- import math
70
- import os
71
- import shutil
72
- import subprocess
73
- import sys
74
- import threading
75
- import time
76
- from datetime import datetime
77
- from typing import Any, Dict, Union
78
- from urllib.parse import urlparse
79
-
80
- import requests
81
- from datasets import load_dataset
82
- from huggingface_hub import DatasetCard, login
83
- from PIL import Image
84
-
85
- logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
86
- logger = logging.getLogger(__name__)
87
-
88
- MODEL = "ATH-MaaS/OvisOCR2"
89
-
90
- # Fixed instruction prompt, verbatim from the model card (including the leading newline).
91
- # The card warns outputs are tuned to this exact wording — don't "improve" it.
92
- OCR_PROMPT = (
93
- "\nExtract all readable content from the image in natural human reading order "
94
- "and output the result as a single Markdown document. For charts or images, "
95
- 'represent them using an HTML image tag: <img src="images/bbox_{left}_{top}_'
96
- '{right}_{bottom}.jpg" />, where left, top, right, bottom are bounding box '
97
- "coordinates scaled to [0, 1000). Format formulas as LaTeX. Format tables as "
98
- "HTML: <table>...</table>. Transcribe all other text as standard Markdown. "
99
- "Preserve the original text without translation or paraphrasing."
100
- )
101
-
102
- # Image bounds from the model card's parser.
103
- DEFAULT_MIN_PIXELS = 448 * 448 # 200,704
104
- DEFAULT_MAX_PIXELS = 2880 * 2880 # 8,294,400
105
-
106
- # The serve command this script spawns when no server is reachable — single
107
- # source of truth for the serving configuration (see docstring for provenance).
108
- SERVE_ARGS = [
109
- "vllm", "serve", MODEL,
110
- "--max-model-len", "32768",
111
- "--gpu-memory-utilization", "0.85",
112
- "--limit-mm-per-prompt", '{"image": 1}',
113
- "--no-enable-prefix-caching",
114
- "--mm-processor-cache-gb", "0",
115
- "--mm-processor-kwargs",
116
- f'{{"images_kwargs": {{"min_pixels": {DEFAULT_MIN_PIXELS}, "max_pixels": {DEFAULT_MAX_PIXELS}}}}}',
117
- "--port", "8000",
118
- ]
119
-
120
- RUN_COMMAND = (
121
- "hf jobs uv run --detach --flavor l4x1 -s HF_TOKEN --timeout 4h \\\n"
122
- " --image vllm/vllm-openai:v0.22.1 \\\n"
123
- " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/ovis-ocr2-server.py \\\n"
124
- " <input-dataset> <output-dataset>"
125
- )
126
-
127
-
128
- def ensure_output_columns_free(dataset, columns, overwrite=False):
129
- """Fail fast if an output column would collide with an existing input column.
130
-
131
- Adding a column that already exists silently overwrites it (e.g. a ground-truth
132
- `text`/`markdown` column) or crashes on push with a duplicate-column error only
133
- *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
134
- column(s) here instead (logged) so the later add_column is clean.
135
- """
136
- clash = [c for c in columns if c in dataset.column_names]
137
- if not clash:
138
- return dataset
139
- if overwrite:
140
- logger.warning(f"--overwrite: replacing existing column(s) {clash}")
141
- return dataset.remove_columns(clash)
142
- logger.error(
143
- f"Output column(s) {clash} already exist in the input dataset "
144
- f"(columns: {dataset.column_names})."
145
- )
146
- logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
147
- sys.exit(1)
148
-
149
-
150
- def to_pil_image(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:
151
- """Convert a dataset image cell (PIL image, bytes dict, or path) to RGB PIL."""
152
- if isinstance(image, Image.Image):
153
- pil_img = image
154
- elif isinstance(image, dict) and "bytes" in image:
155
- pil_img = Image.open(io.BytesIO(image["bytes"]))
156
- elif isinstance(image, str):
157
- pil_img = Image.open(image)
158
- else:
159
- raise ValueError(f"Unsupported image type: {type(image)}")
160
- return pil_img.convert("RGB")
161
-
162
-
163
- def encode_image(image, max_pixels: int) -> str:
164
- """RGB-convert, downscale to max_pixels if oversized, return base64 JPEG.
165
-
166
- The server's processor clamps to the same bound, so this only changes where
167
- the downscale happens — doing it client-side shrinks the request payload
168
- (a 30MP scan is ~4x the bytes of its 8.3MP clamp) and keeps outputs
169
- identical even if the serve command omits --mm-processor-kwargs.
170
- """
171
- img = to_pil_image(image)
172
- w, h = img.size
173
- if w * h > max_pixels:
174
- scale = math.sqrt(max_pixels / (w * h))
175
- img = img.resize((max(1, int(w * scale)), max(1, int(h * scale))), Image.LANCZOS)
176
- buf = io.BytesIO()
177
- img.save(buf, format="JPEG", quality=95)
178
- return base64.b64encode(buf.getvalue()).decode()
179
-
180
-
181
- def clean_truncated_repeats(
182
- text: str,
183
- min_text_len: int = 8000,
184
- max_period: int = 200,
185
- min_period: int = 1,
186
- min_repeat_chars: int = 100,
187
- min_repeat_times: int = 5,
188
- ) -> str:
189
- """Trim degenerate trailing repetition (verbatim port of the model card's cleanup).
190
-
191
- Long outputs that hit max_tokens can end in a repeated unit (a char, phrase, or
192
- table row); this detects the shortest repeating tail unit and keeps one copy.
193
- """
194
- n = len(text)
195
- if n < min_text_len:
196
- return text
197
-
198
- max_period = min(max_period, n - 1)
199
- for unit_len in range(min_period, max_period + 1):
200
- if text[n - 1] != text[n - 1 - unit_len]:
201
- continue
202
-
203
- match_len = 1
204
- idx = n - 2
205
- while idx >= unit_len and text[idx] == text[idx - unit_len]:
206
- match_len += 1
207
- idx -= 1
208
-
209
- total_len = match_len + unit_len
210
- repeat_times = total_len // unit_len
211
- tail_len = total_len % unit_len
212
-
213
- if repeat_times >= min_repeat_times and total_len >= min_repeat_chars:
214
- return text[: n - total_len + unit_len] + text[n - tail_len :]
215
-
216
- return text
217
-
218
-
219
- def filter_image_tags(text: str) -> str:
220
- """Drop visual-region <img> blocks (upstream parser's default behaviour)."""
221
- return "\n\n".join(
222
- block
223
- for block in text.split("\n\n")
224
- if not block.strip().startswith('<img src="images/bbox_')
225
- )
226
-
227
-
228
- def postprocess_output(text: str, keep_image_tags: bool) -> str:
229
- text = text.strip()
230
- if not keep_image_tags:
231
- text = filter_image_tags(text)
232
- return clean_truncated_repeats(text)
233
-
234
-
235
- def server_alive(server: str) -> bool:
236
- try:
237
- return requests.get(f"{server}/health", timeout=5).status_code == 200
238
- except requests.RequestException:
239
- return False
240
-
241
-
242
- def wait_for_server(server: str, timeout_s: int, proc: "subprocess.Popen | None" = None):
243
- logger.info(f"Waiting for server at {server}...")
244
- deadline = time.time() + timeout_s
245
- while time.time() < deadline:
246
- if server_alive(server):
247
- logger.info("Server is ready")
248
- return
249
- if proc is not None and proc.poll() is not None:
250
- logger.error(f"Spawned vllm serve exited with code {proc.returncode} before becoming ready")
251
- sys.exit(1)
252
- time.sleep(10)
253
- logger.error(f"Server did not become ready within {timeout_s}s")
254
- sys.exit(1)
255
-
256
-
257
- def ensure_server(server: str, timeout_s: int = 1800):
258
- """Use a reachable server; otherwise spawn `vllm serve` ourselves; else fail fast.
259
-
260
- Spawning is only attempted for a localhost URL — a remote --server that is
261
- down is the user's to fix, not ours to shadow with a local model.
262
- """
263
- if server_alive(server):
264
- logger.info(f"Using already-running server at {server}")
265
- return
266
-
267
- host = urlparse(server).hostname or ""
268
- if host not in ("127.0.0.1", "localhost", "0.0.0.0"):
269
- logger.info(f"Remote server {server} not up yet — waiting for it")
270
- wait_for_server(server, timeout_s)
271
- return
272
-
273
- if shutil.which("vllm") is None:
274
- logger.error("No server is running and the `vllm` binary is not on PATH.")
275
- logger.error("Run this script on a vLLM image so it can start the server itself:\n")
276
- logger.error(RUN_COMMAND)
277
- logger.error("\n(or start `vllm serve` yourself / pass --server URL of a running endpoint)")
278
- sys.exit(1)
279
-
280
- logger.info(f"Starting server: {' '.join(SERVE_ARGS)}")
281
- proc = subprocess.Popen(SERVE_ARGS) # logs interleave with ours on stdout/stderr
282
- atexit.register(proc.terminate) # don't leave a GPU server behind on local runs
283
- wait_for_server(server, timeout_s, proc=proc)
284
-
285
-
286
- def ocr_one(
287
- server: str,
288
- image,
289
- max_pixels: int,
290
- max_tokens: int,
291
- timeout_s: int,
292
- retries: int = 2,
293
- ) -> str:
294
- """OCR a single image via the chat completions API. Returns raw model text."""
295
- b64 = encode_image(image, max_pixels)
296
- payload = {
297
- "model": MODEL,
298
- "messages": [
299
- {
300
- "role": "user",
301
- "content": [
302
- # Image first, then text — same order the card's chat template uses.
303
- {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64}"}},
304
- {"type": "text", "text": OCR_PROMPT},
305
- ],
306
- }
307
- ],
308
- "temperature": 0.0,
309
- "max_tokens": max_tokens,
310
- # Card-mandated: Qwen3.5 templates can inject a thinking preamble otherwise.
311
- "chat_template_kwargs": {"enable_thinking": False},
312
- }
313
- last_err = None
314
- for attempt in range(retries + 1):
315
- try:
316
- resp = requests.post(
317
- f"{server}/v1/chat/completions", json=payload, timeout=timeout_s
318
- )
319
- resp.raise_for_status()
320
- return resp.json()["choices"][0]["message"]["content"]
321
- except Exception as e:
322
- last_err = e
323
- if attempt < retries:
324
- time.sleep(10 * (attempt + 1))
325
- raise RuntimeError(f"request failed after {retries + 1} attempts: {last_err}")
326
-
327
-
328
- def jobs_flavor() -> str:
329
- """Return the HF Jobs hardware flavor this run is on, or "" when it cannot be told.
330
-
331
- HF Jobs sets ACCELERATOR to "cpu" or "gpu", not the flavor name, so the flavor is looked up
332
- in the public Jobs hardware list: first by GPU model and count, then by the CPU_CORES and
333
- MEMORY values that Jobs sets in the container (to tell a10g-small from a10g-large, or
334
- cpu-basic from cpu-upgrade). Any failure (no network, older huggingface_hub) returns "".
335
- """
336
- hardware = os.environ.get("ACCELERATOR") or ""
337
- if "-" in hardware or any(character.isdigit() for character in hardware):
338
- return hardware # already a flavor name
339
- try:
340
- from huggingface_hub import HfApi
341
-
342
- gpu_name, gpu_count = "", 0
343
- try:
344
- import torch
345
-
346
- if torch.cuda.is_available():
347
- gpu_name = torch.cuda.get_device_name(0)
348
- gpu_count = torch.cuda.device_count()
349
- except ImportError:
350
- # Torch-free drivers (e.g. the -server recipes): ask nvidia-smi instead.
351
- import subprocess
352
-
353
- try:
354
- listed = subprocess.run(
355
- ["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],
356
- capture_output=True, text=True, timeout=10, check=True,
357
- ).stdout
358
- names = [line.strip() for line in listed.splitlines() if line.strip()]
359
- if names:
360
- gpu_name, gpu_count = names[0], len(names)
361
- except (OSError, subprocess.SubprocessError):
362
- pass
363
- if gpu_count == 0 and hardware == "gpu":
364
- return "" # a GPU run whose GPU cannot be identified: do not guess a CPU flavor
365
-
366
- # Whole-word match, so "L4" does not match "NVIDIA L40S" ("NVIDIA A100-SXM4-80GB" -> A100).
367
- gpu_words = gpu_name.upper().replace("-", " ").split()
368
- candidates = []
369
- for flavor in HfApi(token=False).list_jobs_hardware():
370
- accelerator = flavor.accelerator
371
- if gpu_count == 0 and accelerator is None:
372
- candidates.append(flavor)
373
- elif (
374
- gpu_count > 0
375
- and accelerator is not None
376
- and accelerator.model.upper() in gpu_words
377
- and int(accelerator.quantity) == gpu_count
378
- ):
379
- candidates.append(flavor)
380
- if not candidates:
381
- return ""
382
-
383
- cores = float(os.environ.get("CPU_CORES") or 0)
384
- memory_gb = float((os.environ.get("MEMORY") or "0").upper().rstrip("GIB ") or 0)
385
-
386
- def distance(flavor) -> float:
387
- # Relative gap to the listed vCPUs and RAM; Jobs reports slightly different numbers.
388
- listed_cores = float(flavor.cpu.split()[0])
389
- listed_memory = float(flavor.ram.split()[0])
390
- return abs(listed_cores - cores) / listed_cores + abs(listed_memory - memory_gb) / listed_memory
391
-
392
- return min(candidates, key=distance).name
393
- except Exception:
394
- return ""
395
-
396
-
397
- def create_dataset_card(
398
- source_dataset: str,
399
- model: str,
400
- num_samples: int,
401
- num_errors: int,
402
- processing_time: str,
403
- images_per_sec: float,
404
- concurrency: int,
405
- max_tokens: int,
406
- keep_image_tags: bool,
407
- image_column: str = "image",
408
- split: str = "train",
409
- ) -> str:
410
- """Create a dataset card documenting the OCR process."""
411
- model_name = model.split("/")[-1]
412
-
413
- # Canonical provenance stamp (see AGENTS.md): Jobs claim gated on JOB_ID, set by HF Jobs in-container.
414
- on_jobs = os.environ.get("JOB_ID") is not None
415
- hw = jobs_flavor() # flavor name, e.g. "a10g-small"; "" on CPU
416
- origin = (
417
- "Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"
418
- + (f" (`{hw}`)" if hw else "")
419
- ) if on_jobs else "Generated"
420
- jobs_tag = "\n- hf-jobs" if on_jobs else ""
421
-
422
- return f"""---
423
- tags:
424
- - ocr
425
- - document-processing
426
- - ovis-ocr2
427
- - markdown
428
- - uv-script
429
- - generated{jobs_tag}
430
- ---
431
-
432
- # Document OCR using {model_name} (server mode)
433
-
434
- 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), served behind an in-job vLLM server with concurrent requests (continuous batching).
435
-
436
- ## Processing Details
437
-
438
- - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
439
- - **Model**: [{model}](https://huggingface.co/{model})
440
- - **Number of Samples**: {num_samples:,}
441
- - **Failed Requests**: {num_errors:,} (marked `[OCR ERROR]`)
442
- - **Processing Time**: {processing_time}
443
- - **Throughput**: {images_per_sec:.2f} images/sec
444
- - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
445
-
446
- ### Configuration
447
-
448
- - **Mode**: vLLM server (`vllm serve`) + concurrent driver, {concurrency} concurrent requests
449
- - **Image Column**: `{image_column}`
450
- - **Dataset Split**: `{split}`
451
- - **Max Output Tokens**: {max_tokens:,}
452
- - **Temperature**: 0.0 (greedy, per model card)
453
- - **Visual-region image tags**: {"kept" if keep_image_tags else "filtered (default)"}
454
-
455
- ## Dataset Structure
456
-
457
- The dataset contains all original columns plus:
458
- - `markdown`: The extracted text in markdown format
459
- - `inference_info`: JSON list tracking all OCR models applied to this dataset
460
-
461
- ## Reproduction
462
-
463
- {origin} with the [`ovis-ocr2-server.py`](https://huggingface.co/datasets/uv-scripts/ocr/raw/main/ovis-ocr2-server.py) recipe from [uv-scripts](https://huggingface.co/uv-scripts) — see the script docstring for the single `hf jobs run` command that starts the server and driver together. The offline-vLLM sibling recipe is [`ovis-ocr2.py`](https://huggingface.co/datasets/uv-scripts/ocr/raw/main/ovis-ocr2.py).
464
- """
465
-
466
-
467
- def main(
468
- input_dataset: str,
469
- output_dataset: str,
470
- image_column: str = "image",
471
- server: str = "http://127.0.0.1:8000",
472
- concurrency: int = 32,
473
- max_tokens: int = 16384,
474
- max_pixels: int = DEFAULT_MAX_PIXELS,
475
- request_timeout: int = 1800,
476
- keep_image_tags: bool = False,
477
- hf_token: str = None,
478
- split: str = "train",
479
- max_samples: int = None,
480
- private: bool = False,
481
- shuffle: bool = False,
482
- seed: int = 42,
483
- output_column: str = "markdown",
484
- overwrite: bool = False,
485
- config: str = None,
486
- create_pr: bool = False,
487
- ):
488
- """Process images from HF dataset through an OvisOCR2 vLLM server."""
489
-
490
- start_time = datetime.now()
491
-
492
- HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
493
- if HF_TOKEN:
494
- login(token=HF_TOKEN)
495
-
496
- logger.info(f"Using model: {MODEL} via server {server}")
497
-
498
- logger.info(f"Loading dataset: {input_dataset}")
499
- dataset = load_dataset(input_dataset, split=split)
500
-
501
- if image_column not in dataset.column_names:
502
- raise ValueError(
503
- f"Column '{image_column}' not found. Available: {dataset.column_names}"
504
- )
505
-
506
- dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
507
-
508
- if shuffle:
509
- logger.info(f"Shuffling dataset with seed {seed}")
510
- dataset = dataset.shuffle(seed=seed)
511
-
512
- if max_samples:
513
- dataset = dataset.select(range(min(max_samples, len(dataset))))
514
- logger.info(f"Limited to {len(dataset)} samples")
515
-
516
- # Reuse a reachable server, else spawn `vllm serve` (needs the vllm binary,
517
- # i.e. a vllm/vllm-openai image), else fail fast with the correct command.
518
- ensure_server(server)
519
-
520
- n = len(dataset)
521
- logger.info(f"Processing {n} images, concurrency {concurrency}")
522
- all_outputs = [None] * n
523
- errors = 0
524
- done = 0
525
- inference_start = time.time()
526
- lock = threading.Lock()
527
-
528
- def worker(i: int) -> None:
529
- nonlocal errors, done
530
- try:
531
- text = ocr_one(
532
- server,
533
- dataset[i][image_column],
534
- max_pixels,
535
- max_tokens,
536
- request_timeout,
537
- )
538
- all_outputs[i] = postprocess_output(text, keep_image_tags)
539
- except Exception as e:
540
- logger.error(f"Image {i} failed: {e}")
541
- all_outputs[i] = "[OCR ERROR]"
542
- with lock:
543
- errors += 1
544
- with lock:
545
- done += 1
546
- if done % 25 == 0 or done == n:
547
- rate = done / max(time.time() - inference_start, 1e-9)
548
- logger.info(f"{done}/{n} done ({rate:.2f} img/s, {errors} errors)")
549
-
550
- with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as pool:
551
- list(pool.map(worker, range(n)))
552
-
553
- inference_secs = time.time() - inference_start
554
- processing_duration = datetime.now() - start_time
555
- processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
556
- images_per_sec = n / inference_secs if inference_secs else 0.0
557
-
558
- logger.info(f"Adding '{output_column}' column to dataset")
559
- dataset = dataset.add_column(output_column, all_outputs)
560
-
561
- # Inference info tracking
562
- inference_entry = {
563
- "model_id": MODEL,
564
- "model_name": "OvisOCR2",
565
- "column_name": output_column,
566
- "timestamp": datetime.now().isoformat(),
567
- "temperature": 0.0,
568
- "max_tokens": max_tokens,
569
- "max_pixels": max_pixels,
570
- "keep_image_tags": keep_image_tags,
571
- "mode": "vllm-server",
572
- "concurrency": concurrency,
573
- }
574
-
575
- if "inference_info" in dataset.column_names:
576
- logger.info("Updating existing inference_info column")
577
-
578
- def update_inference_info(example):
579
- try:
580
- existing_info = (
581
- json.loads(example["inference_info"])
582
- if example["inference_info"]
583
- else []
584
- )
585
- except (json.JSONDecodeError, TypeError):
586
- existing_info = []
587
- existing_info.append(inference_entry)
588
- return {"inference_info": json.dumps(existing_info)}
589
-
590
- dataset = dataset.map(update_inference_info)
591
- else:
592
- logger.info("Creating new inference_info column")
593
- inference_list = [json.dumps([inference_entry])] * len(dataset)
594
- dataset = dataset.add_column("inference_info", inference_list)
595
-
596
- # Push to hub with retry and XET fallback
597
- logger.info(f"Pushing to {output_dataset}")
598
- max_retries = 3
599
- for attempt in range(1, max_retries + 1):
600
- try:
601
- if attempt > 1:
602
- logger.warning("Disabling XET (fallback to HTTP upload)")
603
- os.environ["HF_HUB_DISABLE_XET"] = "1"
604
- dataset.push_to_hub(
605
- output_dataset,
606
- private=private,
607
- token=HF_TOKEN,
608
- max_shard_size="500MB",
609
- **({"config_name": config} if config else {}),
610
- create_pr=create_pr,
611
- commit_message=f"Add {MODEL} OCR results ({len(dataset)} samples, server mode)"
612
- + (f" [{config}]" if config else ""),
613
- )
614
- break
615
- except Exception as e:
616
- logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
617
- if attempt < max_retries:
618
- delay = 30 * (2 ** (attempt - 1))
619
- logger.info(f"Retrying in {delay}s...")
620
- time.sleep(delay)
621
- else:
622
- logger.error("All upload attempts failed. OCR results are lost.")
623
- sys.exit(1)
624
-
625
- logger.info("Creating dataset card")
626
- card_content = create_dataset_card(
627
- source_dataset=input_dataset,
628
- model=MODEL,
629
- num_samples=len(dataset),
630
- num_errors=errors,
631
- processing_time=processing_time_str,
632
- images_per_sec=images_per_sec,
633
- concurrency=concurrency,
634
- max_tokens=max_tokens,
635
- keep_image_tags=keep_image_tags,
636
- image_column=image_column,
637
- split=split,
638
- )
639
-
640
- card = DatasetCard(card_content)
641
- card.push_to_hub(output_dataset, token=HF_TOKEN)
642
-
643
- logger.info("Done! OvisOCR2 server-mode processing complete.")
644
- logger.info(
645
- f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
646
- )
647
- logger.info(f"Processing time: {processing_time_str}")
648
- logger.info(
649
- f"Throughput: {images_per_sec:.2f} images/sec "
650
- f"(inference only, excl. dataset load/push; {errors} errors)"
651
- )
652
-
653
-
654
- if __name__ == "__main__":
655
- if len(sys.argv) == 1:
656
- print("=" * 70)
657
- print("OvisOCR2 Document Processing (vLLM server mode)")
658
- print("=" * 70)
659
- print("\nSame model + outputs as ovis-ocr2.py, but drives an in-job")
660
- print("`vllm serve` with concurrent requests — no batch barriers,")
661
- print("per-image (not per-batch) failure isolation.")
662
- print("\nThe server must already be running (the job command starts")
663
- print("both — see the module docstring for the full `hf jobs run`).")
664
- print("\nExamples:")
665
- print("\n1. Basic OCR (server on localhost:8000):")
666
- print(" uv run ovis-ocr2-server.py input-dataset output-dataset")
667
- print("\n2. Test with a small sample:")
668
- print(" uv run ovis-ocr2-server.py large-dataset test --max-samples 10 --shuffle")
669
- print("\n3. Throughput A/B vs the offline recipe:")
670
- print(" run both scripts on the same --max-samples slice and compare")
671
- print(" the images/sec lines + diff the markdown columns")
672
- print("\nFor full help: uv run ovis-ocr2-server.py --help")
673
- sys.exit(0)
674
-
675
- parser = argparse.ArgumentParser(
676
- description="Document OCR using OvisOCR2 via an in-job vLLM server",
677
- formatter_class=argparse.RawDescriptionHelpFormatter,
678
- epilog="""
679
- Examples:
680
- uv run ovis-ocr2-server.py my-docs analyzed-docs
681
- uv run ovis-ocr2-server.py large-dataset test --max-samples 50 --shuffle
682
- See the module docstring for the full `hf jobs run` command (server + driver in one job).
683
- """,
684
- )
685
-
686
- parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
687
- parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
688
- parser.add_argument(
689
- "--image-column",
690
- default="image",
691
- help="Column containing images (default: image)",
692
- )
693
- parser.add_argument(
694
- "--server",
695
- default="http://127.0.0.1:8000",
696
- help="vLLM server base URL (default: in-job localhost:8000)",
697
- )
698
- parser.add_argument(
699
- "--concurrency",
700
- type=int,
701
- default=32,
702
- help="Concurrent OCR requests (default: 32; vLLM queues excess internally, "
703
- "so this mainly needs to be high enough to keep continuous batching fed)",
704
- )
705
- parser.add_argument(
706
- "--max-tokens",
707
- type=int,
708
- default=16384,
709
- help="Maximum tokens to generate (default: 16384, the model card value)",
710
- )
711
- parser.add_argument(
712
- "--max-pixels",
713
- type=int,
714
- default=DEFAULT_MAX_PIXELS,
715
- help=f"Maximum image pixels; larger images are downscaled client-side before "
716
- f"upload (default: {DEFAULT_MAX_PIXELS}, = 2880*2880, the model card value)",
717
- )
718
- parser.add_argument(
719
- "--request-timeout",
720
- type=int,
721
- default=1800,
722
- help="Per-request timeout in seconds (default: 1800)",
723
- )
724
- parser.add_argument(
725
- "--keep-image-tags",
726
- action="store_true",
727
- help="Keep visual-region <img src=\"images/bbox_...\"> tags in the output "
728
- "(default: filtered, matching the upstream parser)",
729
- )
730
- parser.add_argument("--hf-token", help="Hugging Face API token")
731
- parser.add_argument(
732
- "--split", default="train", help="Dataset split to use (default: train)"
733
- )
734
- parser.add_argument(
735
- "--max-samples",
736
- type=int,
737
- help="Maximum number of samples to process (for testing)",
738
- )
739
- parser.add_argument(
740
- "--private", action="store_true", help="Make output dataset private"
741
- )
742
- parser.add_argument(
743
- "--config",
744
- help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
745
- )
746
- parser.add_argument(
747
- "--create-pr",
748
- action="store_true",
749
- help="Create a pull request instead of pushing directly (for parallel benchmarking)",
750
- )
751
- parser.add_argument(
752
- "--shuffle", action="store_true", help="Shuffle dataset before processing"
753
- )
754
- parser.add_argument(
755
- "--seed",
756
- type=int,
757
- default=42,
758
- help="Random seed for shuffling (default: 42)",
759
- )
760
- parser.add_argument(
761
- "--output-column",
762
- default="markdown",
763
- help="Column name for output text (default: markdown)",
764
- )
765
- parser.add_argument(
766
- "--overwrite",
767
- action="store_true",
768
- help="Replace the output column if it already exists in the input dataset "
769
- "(default: error out to avoid clobbering an existing column).",
770
- )
771
-
772
- args = parser.parse_args()
773
-
774
- main(
775
- input_dataset=args.input_dataset,
776
- output_dataset=args.output_dataset,
777
- image_column=args.image_column,
778
- server=args.server,
779
- concurrency=args.concurrency,
780
- max_tokens=args.max_tokens,
781
- max_pixels=args.max_pixels,
782
- request_timeout=args.request_timeout,
783
- keep_image_tags=args.keep_image_tags,
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
- overwrite=args.overwrite,
792
- config=args.config,
793
- create_pr=args.create_pr,
794
- )