davanstrien HF Staff commited on
Commit
ec846c3
·
verified ·
1 Parent(s): 3035c3c

Sync from GitHub via hub-sync

Browse files
Files changed (5) hide show
  1. README.md +3 -1
  2. SERVING.md +93 -0
  3. lighton-ocr2-server.py +651 -0
  4. models.json +26 -0
  5. ovis-ocr2-server.py +725 -0
README.md CHANGED
@@ -33,7 +33,7 @@ This will:
33
 
34
  ## Serve a model as a live endpoint
35
 
36
- The recipes here run as batch jobs. To call a model interactively, from an agent, or with concurrent ad-hoc requests, you can instead run it as a temporary endpoint: [HF Jobs serving](https://huggingface.co/docs/hub/jobs-serving) exposes a port on a GPU Job, giving an OpenAI-compatible endpoint that runs until the job is cancelled or its `--timeout` is reached. See [serving-unlimited-ocr.md](serving-unlimited-ocr.md) for a worked example serving Baidu's [Unlimited-OCR](https://huggingface.co/baidu/Unlimited-OCR) — with vLLM (official image) or SGLang. To OCR a whole corpus of single-page images instead, the batch recipe `unlimited-ocr-vllm.py` is the better fit (it's single-image only). **Multi-page** documents need a server: both vLLM and SGLang read clean multi-page docs, but **SGLang is the more robust** — on hard/degraded scans vLLM multi-page hallucinated in our tests while SGLang held up.
37
 
38
  ## Models at a glance
39
 
@@ -61,8 +61,10 @@ _Sorted by model size:_
61
  | [`paddleocr-vl-1.5.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/paddleocr-vl-1.5.py) | [PaddleOCR-VL-1.5](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.5) | 0.9B | Transformers | 94.5% OmniDocBench, 6 task modes |
62
  | [`paddleocr-vl-1.6.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/paddleocr-vl-1.6.py) | [PaddleOCR-VL-1.6](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.6) | 0.9B | vLLM | **96.33% OmniDocBench v1.6**, drop-in upgrade of 1.5 |
63
  | [`ovis-ocr2.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/ovis-ocr2.py) | [OvisOCR2](https://huggingface.co/ATH-MaaS/OvisOCR2) | 0.9B | vLLM | **96.58 OmniDocBench v1.6** (SOTA; first end-to-end model to top it). Qwen3.5 base; markdown + LaTeX + HTML tables. Apache 2.0 |
 
64
  | [`lighton-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/lighton-ocr.py) | [LightOnOCR-1B](https://huggingface.co/lightonai/LightOnOCR-1B-1025) | 1B | vLLM | Fast, 3 vocab sizes |
65
  | [`lighton-ocr2.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/lighton-ocr2.py) | [LightOnOCR-2-1B](https://huggingface.co/lightonai/LightOnOCR-2-1B) | 1B | vLLM | 7× faster than v1, RLVR trained |
 
66
  | [`hunyuan-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/hunyuan-ocr.py) | [HunyuanOCR 1.0](https://huggingface.co/tencent/HunyuanOCR/tree/f6af82ee007fe6091b29fb3bb287b491ead41c82) | 1B | vLLM | Lightweight VLM. Pinned to the last 1.0 revision (repo root became 1.5 in-place on 2026-07-06). [Hunyuan Community License](https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE) (excludes EU/UK/KR) |
67
  | [`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 | vLLM | 128K context, 4K images, 12 task types, ancient scripts. ~4-5× faster/page than dots.ocr & DeepSeek-OCR-2 (tech report). [Hunyuan Community License](https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE) (excludes EU/UK/KR) |
68
  | [`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 | vLLM | 100 languages (in-house bench), explicit low-resource claim |
 
33
 
34
  ## Serve a model as a live endpoint
35
 
36
+ The recipes here run as batch jobs. Some models also have a **`-server.py` sibling recipe** that runs the same dataset→dataset batch job through an in-job `vllm serve` + concurrent driver — measurably faster (continuous batching stays fed) and more robust (one bad image fails one request, not a whole batch); see [SERVING.md](SERVING.md) for the architecture, A/B numbers, and which models officially document server mode. To call a model interactively, from an agent, or with concurrent ad-hoc requests, you can instead run it as a temporary endpoint: [HF Jobs serving](https://huggingface.co/docs/hub/jobs-serving) exposes a port on a GPU Job, giving an OpenAI-compatible endpoint that runs until the job is cancelled or its `--timeout` is reached. See [serving-unlimited-ocr.md](serving-unlimited-ocr.md) for a worked example serving Baidu's [Unlimited-OCR](https://huggingface.co/baidu/Unlimited-OCR) — with vLLM (official image) or SGLang. To OCR a whole corpus of single-page images instead, the batch recipe `unlimited-ocr-vllm.py` is the better fit (it's single-image only). **Multi-page** documents need a server: both vLLM and SGLang read clean multi-page docs, but **SGLang is the more robust** — on hard/degraded scans vLLM multi-page hallucinated in our tests while SGLang held up.
37
 
38
  ## Models at a glance
39
 
 
61
  | [`paddleocr-vl-1.5.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/paddleocr-vl-1.5.py) | [PaddleOCR-VL-1.5](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.5) | 0.9B | Transformers | 94.5% OmniDocBench, 6 task modes |
62
  | [`paddleocr-vl-1.6.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/paddleocr-vl-1.6.py) | [PaddleOCR-VL-1.6](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.6) | 0.9B | vLLM | **96.33% OmniDocBench v1.6**, drop-in upgrade of 1.5 |
63
  | [`ovis-ocr2.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/ovis-ocr2.py) | [OvisOCR2](https://huggingface.co/ATH-MaaS/OvisOCR2) | 0.9B | vLLM | **96.58 OmniDocBench v1.6** (SOTA; first end-to-end model to top it). Qwen3.5 base; markdown + LaTeX + HTML tables. Apache 2.0 |
64
+ | [`ovis-ocr2-server.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/ovis-ocr2-server.py) | [OvisOCR2](https://huggingface.co/ATH-MaaS/OvisOCR2) | 0.9B | vLLM server | **Server-mode sibling** of `ovis-ocr2.py`: in-job `vllm serve` + concurrent driver — ~1.7× its throughput, per-image failure isolation. See [SERVING.md](SERVING.md) |
65
  | [`lighton-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/lighton-ocr.py) | [LightOnOCR-1B](https://huggingface.co/lightonai/LightOnOCR-1B-1025) | 1B | vLLM | Fast, 3 vocab sizes |
66
  | [`lighton-ocr2.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/lighton-ocr2.py) | [LightOnOCR-2-1B](https://huggingface.co/lightonai/LightOnOCR-2-1B) | 1B | vLLM | 7× faster than v1, RLVR trained |
67
+ | [`lighton-ocr2-server.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/lighton-ocr2-server.py) | [LightOnOCR-2-1B](https://huggingface.co/lightonai/LightOnOCR-2-1B) | 1B | vLLM server | **Server-mode sibling** of `lighton-ocr2.py` (the card's own documented path) — ~1.8× its throughput. See [SERVING.md](SERVING.md) |
68
  | [`hunyuan-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/hunyuan-ocr.py) | [HunyuanOCR 1.0](https://huggingface.co/tencent/HunyuanOCR/tree/f6af82ee007fe6091b29fb3bb287b491ead41c82) | 1B | vLLM | Lightweight VLM. Pinned to the last 1.0 revision (repo root became 1.5 in-place on 2026-07-06). [Hunyuan Community License](https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE) (excludes EU/UK/KR) |
69
  | [`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 | vLLM | 128K context, 4K images, 12 task types, ancient scripts. ~4-5× faster/page than dots.ocr & DeepSeek-OCR-2 (tech report). [Hunyuan Community License](https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE) (excludes EU/UK/KR) |
70
  | [`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 | vLLM | 100 languages (in-house bench), explicit low-resource claim |
SERVING.md ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ The job command stays the standard `hf jobs uv run` shape: the driver spawns
30
+ `vllm serve` itself as a subprocess when no server is reachable (flags live in the
31
+ script's `SERVE_ARGS`, taken from the model's own card where they exist), so the only
32
+ thing to get right is `--image vllm/vllm-openai:<tag>` — which provides the `vllm`
33
+ binary. Without it the script fails fast, printing the exact correct command. Pass
34
+ `--server URL` to use an already-running or remote endpoint instead (nothing is
35
+ spawned when the server is reachable, so the moss-style explicit `bash -c` serve
36
+ command keeps working too).
37
+
38
+ For **interactive/agent** use (a live endpoint instead of a batch run), see
39
+ [serving-unlimited-ocr.md](serving-unlimited-ocr.md) — `hf jobs run --expose` gives an
40
+ OpenAI-compatible URL that outlives a single script.
41
+
42
+ ## The recurring official serve pattern for OCR
43
+
44
+ Three flags recur across independent vendors' official serve commands (DeepSeek's vLLM
45
+ recipe, LightOn's card, Paddle's vLLM recipe, Unlimited-OCR's recipe):
46
+
47
+ ```
48
+ --no-enable-prefix-caching --mm-processor-cache-gb 0 --limit-mm-per-prompt '{"image": 1}'
49
+ ```
50
+
51
+ OCR workloads never reuse images, so prefix/multimodal caches only cost memory.
52
+
53
+ ## Version pins carry over — via the image tag
54
+
55
+ Where an offline recipe pins an engine version, the server variant needs the same pin
56
+ as a `vllm/vllm-openai:<tag>` image (e.g. Nanonets-OCR2-3B uses `v0.10.2`, matching its
57
+ offline recipe). [`models.json`](models.json) records the required image per script.
58
+ When trying a new model/image combination, sanity-check the first few outputs before
59
+ scaling: a mismatched combination can produce degenerate output while looking like
60
+ normal load from the outside (full GPU utilisation, no errors).
61
+
62
+ ## Which models document server mode themselves? (surveyed 2026-07-16)
63
+
64
+ Server mode is the officially documented path for most models in this collection —
65
+ for several of them it's the *only* documented vLLM path. Summary of each model's own
66
+ card/docs (verbatim commands live in the linked sources):
67
+
68
+ | Model | Official server example | Notes |
69
+ |---|---|---|
70
+ | lightonai/LightOnOCR-1B / 2-1B | ✅ vLLM | Card ships the serve command + client; ≥0.11.1 for v1; images longest-dim 1540px |
71
+ | nanonets/OCR-s / OCR2-3B | ✅ vLLM | Bare `vllm serve` + client in card; **pin v0.10.2 for OCR2** (see above) |
72
+ | rednote-hilab/dots.mocr | ✅ vLLM ≥0.11 | Direct from Hub id on `vllm/vllm-openai:v0.11.0`+ |
73
+ | rednote-hilab/dots.ocr | ✅ (GitHub) | HF card shows a legacy pre-0.11 hack; GitHub README: integrated upstream since 0.11 |
74
+ | tencent/HunyuanOCR | ✅ vLLM 0.18.1 | serve.sh in repo; nightly adds DFlash speculative decoding |
75
+ | zai-org/GLM-OCR | ✅ vLLM + SGLang + Ollama | Only card here with an SGLang serve example; needs vLLM nightly |
76
+ | numind/NuExtract3 | ✅ vLLM | Production-grade recipe: MTP speculative decoding, per-request `chat_template_kwargs` |
77
+ | numind/NuMarkdown-8B-Thinking | ✅ vLLM | Thinking always on — parse `<think>`/`<answer>` |
78
+ | baidu/Unlimited-OCR | ✅ vLLM + SGLang | Custom image / dev wheel; see [serving-unlimited-ocr.md](serving-unlimited-ocr.md) |
79
+ | baidu/Qianfan-OCR | ✅ vLLM (minimal) | Needs `--hf-overrides '{"architectures": ["InternVLChatModel"]}'` |
80
+ | 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) |
81
+ | deepseek-ai/DeepSeek-OCR / -2 | ⚠️ vLLM recipe pages only | docs.vllm.ai recipes; needs the DeepSeek n-gram logits processor flags |
82
+ | allenai/olmOCR-2-7B-FP8 | ✅ (GitHub) | olmocr toolkit spawns `vllm serve` itself; YAML-front-matter prompt required |
83
+ | reducto/RolmOCR | ✅ vLLM | Card serve + client (client's model string has a typo — pass `--served-model-name`) |
84
+ | tiiuae/Falcon-OCR | ✅ vLLM in official Docker | `ghcr.io/tiiuae/falcon-ocr`; task-token prompts |
85
+ | datalab-to/surya-ocr-2, lift | ⚠️ wrapper-mediated | Server-native but driven via their own managers (`SURYA_INFERENCE_URL`, `lift_vllm`) |
86
+ | LiquidAI LFM2.5-VL-Extract | ⚠️ family docs | vLLM ≥0.23 + SGLang cookbooks, not Extract-specific |
87
+ | ATH-MaaS/OvisOCR2 | ❌ offline vLLM only | `ovis-ocr2-server.py` is our translation of the card's offline args (parity-validated, table above) |
88
+ | FireRedTeam/FireRed-OCR | ❌ transformers only | |
89
+ | acvlab/ABot-OCR | ❌ offline script only | pinned vllm 0.18.0 |
90
+
91
+ SGLang reality check: only GLM-OCR and Unlimited-OCR ship SGLang serve paths (olmOCR
92
+ dropped SGLang for vLLM in v0.1.75). For this collection, "server mode" effectively
93
+ means a vLLM OpenAI-compatible endpoint.
lighton-ocr2-server.py ADDED
@@ -0,0 +1,651 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 create_dataset_card(
246
+ source_dataset: str,
247
+ model: str,
248
+ num_samples: int,
249
+ num_errors: int,
250
+ processing_time: str,
251
+ images_per_sec: float,
252
+ concurrency: int,
253
+ max_tokens: int,
254
+ temperature: float,
255
+ target_size: int,
256
+ image_column: str = "image",
257
+ split: str = "train",
258
+ ) -> str:
259
+ """Create a dataset card documenting the OCR process."""
260
+ model_name = model.split("/")[-1]
261
+
262
+ # Canonical provenance stamp (see AGENTS.md): Jobs claim gated on JOB_ID, set by HF Jobs in-container.
263
+ on_jobs = os.environ.get("JOB_ID") is not None
264
+ hw = os.environ.get("ACCELERATOR") or ""
265
+ origin = (
266
+ "Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"
267
+ + (f" (`{hw}`)" if hw else "")
268
+ ) if on_jobs else "Generated"
269
+ jobs_tag = "\n- hf-jobs" if on_jobs else ""
270
+
271
+ return f"""---
272
+ tags:
273
+ - ocr
274
+ - document-processing
275
+ - lighton-ocr
276
+ - markdown
277
+ - uv-script
278
+ - generated{jobs_tag}
279
+ ---
280
+
281
+ # Document OCR using {model_name} (server mode)
282
+
283
+ 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).
284
+
285
+ ## Processing Details
286
+
287
+ - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
288
+ - **Model**: [{model}](https://huggingface.co/{model})
289
+ - **Number of Samples**: {num_samples:,}
290
+ - **Failed Requests**: {num_errors:,} (marked `[OCR ERROR]`)
291
+ - **Processing Time**: {processing_time}
292
+ - **Throughput**: {images_per_sec:.2f} images/sec
293
+ - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
294
+
295
+ ### Configuration
296
+
297
+ - **Mode**: vLLM server (`vllm serve`) + concurrent driver, {concurrency} concurrent requests
298
+ - **Image Column**: `{image_column}`
299
+ - **Dataset Split**: `{split}`
300
+ - **Target Image Size**: {target_size}px (longest dimension)
301
+ - **Max Output Tokens**: {max_tokens:,}
302
+ - **Temperature**: {temperature}
303
+
304
+ ## Dataset Structure
305
+
306
+ The dataset contains all original columns plus:
307
+ - `markdown`: The extracted text in markdown format
308
+ - `inference_info`: JSON list tracking all OCR models applied to this dataset
309
+
310
+ ## Reproduction
311
+
312
+ {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).
313
+ """
314
+
315
+
316
+ def main(
317
+ input_dataset: str,
318
+ output_dataset: str,
319
+ image_column: str = "image",
320
+ server: str = "http://127.0.0.1:8000",
321
+ concurrency: int = 32,
322
+ max_tokens: int = 4096,
323
+ temperature: float = 0.2,
324
+ top_p: float = 0.9,
325
+ target_size: int = DEFAULT_TARGET_SIZE,
326
+ request_timeout: int = 1800,
327
+ hf_token: str = None,
328
+ split: str = "train",
329
+ max_samples: int = None,
330
+ private: bool = False,
331
+ shuffle: bool = False,
332
+ seed: int = 42,
333
+ output_column: str = "markdown",
334
+ overwrite: bool = False,
335
+ config: str = None,
336
+ create_pr: bool = False,
337
+ ):
338
+ """Process images from HF dataset through a LightOnOCR-2 vLLM server."""
339
+
340
+ start_time = datetime.now()
341
+
342
+ HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
343
+ if HF_TOKEN:
344
+ login(token=HF_TOKEN)
345
+
346
+ logger.info(f"Using model: {MODEL} via server {server}")
347
+
348
+ logger.info(f"Loading dataset: {input_dataset}")
349
+ dataset = load_dataset(input_dataset, split=split)
350
+
351
+ if image_column not in dataset.column_names:
352
+ raise ValueError(
353
+ f"Column '{image_column}' not found. Available: {dataset.column_names}"
354
+ )
355
+
356
+ dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
357
+
358
+ if shuffle:
359
+ logger.info(f"Shuffling dataset with seed {seed}")
360
+ dataset = dataset.shuffle(seed=seed)
361
+
362
+ if max_samples:
363
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
364
+ logger.info(f"Limited to {len(dataset)} samples")
365
+
366
+ # Reuse a reachable server, else spawn `vllm serve` (needs the vllm binary,
367
+ # i.e. a vllm/vllm-openai image), else fail fast with the correct command.
368
+ ensure_server(server)
369
+
370
+ n = len(dataset)
371
+ logger.info(f"Processing {n} images, concurrency {concurrency}")
372
+ all_outputs = [None] * n
373
+ errors = 0
374
+ done = 0
375
+ inference_start = time.time()
376
+ lock = threading.Lock()
377
+
378
+ def worker(i: int) -> None:
379
+ nonlocal errors, done
380
+ try:
381
+ text = ocr_one(
382
+ server,
383
+ dataset[i][image_column],
384
+ target_size,
385
+ max_tokens,
386
+ temperature,
387
+ top_p,
388
+ request_timeout,
389
+ )
390
+ all_outputs[i] = text.strip()
391
+ except Exception as e:
392
+ logger.error(f"Image {i} failed: {e}")
393
+ all_outputs[i] = "[OCR ERROR]"
394
+ with lock:
395
+ errors += 1
396
+ with lock:
397
+ done += 1
398
+ if done % 25 == 0 or done == n:
399
+ rate = done / max(time.time() - inference_start, 1e-9)
400
+ logger.info(f"{done}/{n} done ({rate:.2f} img/s, {errors} errors)")
401
+
402
+ with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as pool:
403
+ list(pool.map(worker, range(n)))
404
+
405
+ inference_secs = time.time() - inference_start
406
+ processing_duration = datetime.now() - start_time
407
+ processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
408
+ images_per_sec = n / inference_secs if inference_secs else 0.0
409
+
410
+ logger.info(f"Adding '{output_column}' column to dataset")
411
+ dataset = dataset.add_column(output_column, all_outputs)
412
+
413
+ # Inference info tracking
414
+ inference_entry = {
415
+ "model_id": MODEL,
416
+ "model_name": "LightOnOCR-2-1B",
417
+ "column_name": output_column,
418
+ "timestamp": datetime.now().isoformat(),
419
+ "temperature": temperature,
420
+ "top_p": top_p,
421
+ "max_tokens": max_tokens,
422
+ "target_size": target_size,
423
+ "mode": "vllm-server",
424
+ "concurrency": concurrency,
425
+ }
426
+
427
+ if "inference_info" in dataset.column_names:
428
+ logger.info("Updating existing inference_info column")
429
+
430
+ def update_inference_info(example):
431
+ try:
432
+ existing_info = (
433
+ json.loads(example["inference_info"])
434
+ if example["inference_info"]
435
+ else []
436
+ )
437
+ except (json.JSONDecodeError, TypeError):
438
+ existing_info = []
439
+ existing_info.append(inference_entry)
440
+ return {"inference_info": json.dumps(existing_info)}
441
+
442
+ dataset = dataset.map(update_inference_info)
443
+ else:
444
+ logger.info("Creating new inference_info column")
445
+ inference_list = [json.dumps([inference_entry])] * len(dataset)
446
+ dataset = dataset.add_column("inference_info", inference_list)
447
+
448
+ # Push to hub with retry and XET fallback
449
+ logger.info(f"Pushing to {output_dataset}")
450
+ max_retries = 3
451
+ for attempt in range(1, max_retries + 1):
452
+ try:
453
+ if attempt > 1:
454
+ logger.warning("Disabling XET (fallback to HTTP upload)")
455
+ os.environ["HF_HUB_DISABLE_XET"] = "1"
456
+ dataset.push_to_hub(
457
+ output_dataset,
458
+ private=private,
459
+ token=HF_TOKEN,
460
+ max_shard_size="500MB",
461
+ **({"config_name": config} if config else {}),
462
+ create_pr=create_pr,
463
+ commit_message=f"Add {MODEL} OCR results ({len(dataset)} samples, server mode)"
464
+ + (f" [{config}]" if config else ""),
465
+ )
466
+ break
467
+ except Exception as e:
468
+ logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
469
+ if attempt < max_retries:
470
+ delay = 30 * (2 ** (attempt - 1))
471
+ logger.info(f"Retrying in {delay}s...")
472
+ time.sleep(delay)
473
+ else:
474
+ logger.error("All upload attempts failed. OCR results are lost.")
475
+ sys.exit(1)
476
+
477
+ logger.info("Creating dataset card")
478
+ card_content = create_dataset_card(
479
+ source_dataset=input_dataset,
480
+ model=MODEL,
481
+ num_samples=len(dataset),
482
+ num_errors=errors,
483
+ processing_time=processing_time_str,
484
+ images_per_sec=images_per_sec,
485
+ concurrency=concurrency,
486
+ max_tokens=max_tokens,
487
+ temperature=temperature,
488
+ target_size=target_size,
489
+ image_column=image_column,
490
+ split=split,
491
+ )
492
+
493
+ card = DatasetCard(card_content)
494
+ card.push_to_hub(output_dataset, token=HF_TOKEN)
495
+
496
+ logger.info("Done! LightOnOCR-2 server-mode processing complete.")
497
+ logger.info(
498
+ f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
499
+ )
500
+ logger.info(f"Processing time: {processing_time_str}")
501
+ logger.info(
502
+ f"Throughput: {images_per_sec:.2f} images/sec "
503
+ f"(inference only, excl. dataset load/push; {errors} errors)"
504
+ )
505
+
506
+
507
+ if __name__ == "__main__":
508
+ if len(sys.argv) == 1:
509
+ print("=" * 70)
510
+ print("LightOnOCR-2 Document Processing (vLLM server mode)")
511
+ print("=" * 70)
512
+ print("\nSame model + outputs as lighton-ocr2.py, but drives an in-job")
513
+ print("`vllm serve` with concurrent requests — no batch barriers,")
514
+ print("per-image (not per-batch) failure isolation.")
515
+ print("\nThe server must already be running (the job command starts")
516
+ print("both — see the module docstring for the full `hf jobs run`).")
517
+ print("\nExamples:")
518
+ print("\n1. Basic OCR (server on localhost:8000):")
519
+ print(" uv run lighton-ocr2-server.py input-dataset output-dataset")
520
+ print("\n2. Test with a small sample:")
521
+ print(" uv run lighton-ocr2-server.py large-dataset test --max-samples 10 --shuffle")
522
+ print("\nFor full help: uv run lighton-ocr2-server.py --help")
523
+ sys.exit(0)
524
+
525
+ parser = argparse.ArgumentParser(
526
+ description="Document OCR using LightOnOCR-2 via an in-job vLLM server",
527
+ formatter_class=argparse.RawDescriptionHelpFormatter,
528
+ epilog="""
529
+ Examples:
530
+ uv run lighton-ocr2-server.py my-docs analyzed-docs
531
+ uv run lighton-ocr2-server.py large-dataset test --max-samples 50 --shuffle
532
+ See the module docstring for the full `hf jobs run` command (server + driver in one job).
533
+ """,
534
+ )
535
+
536
+ parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
537
+ parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
538
+ parser.add_argument(
539
+ "--image-column",
540
+ default="image",
541
+ help="Column containing images (default: image)",
542
+ )
543
+ parser.add_argument(
544
+ "--server",
545
+ default="http://127.0.0.1:8000",
546
+ help="vLLM server base URL (default: in-job localhost:8000)",
547
+ )
548
+ parser.add_argument(
549
+ "--concurrency",
550
+ type=int,
551
+ default=32,
552
+ help="Concurrent OCR requests (default: 32; vLLM queues excess internally, "
553
+ "so this mainly needs to be high enough to keep continuous batching fed)",
554
+ )
555
+ parser.add_argument(
556
+ "--max-tokens",
557
+ type=int,
558
+ default=4096,
559
+ help="Maximum tokens to generate (default: 4096, the model card value)",
560
+ )
561
+ parser.add_argument(
562
+ "--temperature",
563
+ type=float,
564
+ default=0.2,
565
+ help="Sampling temperature (default: 0.2, the model card value)",
566
+ )
567
+ parser.add_argument(
568
+ "--top-p",
569
+ type=float,
570
+ default=0.9,
571
+ help="Top-p sampling (default: 0.9, the model card value)",
572
+ )
573
+ parser.add_argument(
574
+ "--target-size",
575
+ type=int,
576
+ default=DEFAULT_TARGET_SIZE,
577
+ help=f"Resize images so the longest dimension is this many pixels before upload "
578
+ f"(default: {DEFAULT_TARGET_SIZE}, the model's training resolution); 0 disables",
579
+ )
580
+ parser.add_argument(
581
+ "--request-timeout",
582
+ type=int,
583
+ default=1800,
584
+ help="Per-request timeout in seconds (default: 1800)",
585
+ )
586
+ parser.add_argument("--hf-token", help="Hugging Face API token")
587
+ parser.add_argument(
588
+ "--split", default="train", help="Dataset split to use (default: train)"
589
+ )
590
+ parser.add_argument(
591
+ "--max-samples",
592
+ type=int,
593
+ help="Maximum number of samples to process (for testing)",
594
+ )
595
+ parser.add_argument(
596
+ "--private", action="store_true", help="Make output dataset private"
597
+ )
598
+ parser.add_argument(
599
+ "--config",
600
+ help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
601
+ )
602
+ parser.add_argument(
603
+ "--create-pr",
604
+ action="store_true",
605
+ help="Create a pull request instead of pushing directly (for parallel benchmarking)",
606
+ )
607
+ parser.add_argument(
608
+ "--shuffle", action="store_true", help="Shuffle dataset before processing"
609
+ )
610
+ parser.add_argument(
611
+ "--seed",
612
+ type=int,
613
+ default=42,
614
+ help="Random seed for shuffling (default: 42)",
615
+ )
616
+ parser.add_argument(
617
+ "--output-column",
618
+ default="markdown",
619
+ help="Column name for output text (default: markdown)",
620
+ )
621
+ parser.add_argument(
622
+ "--overwrite",
623
+ action="store_true",
624
+ help="Replace the output column if it already exists in the input dataset "
625
+ "(default: error out to avoid clobbering an existing column).",
626
+ )
627
+
628
+ args = parser.parse_args()
629
+
630
+ main(
631
+ input_dataset=args.input_dataset,
632
+ output_dataset=args.output_dataset,
633
+ image_column=args.image_column,
634
+ server=args.server,
635
+ concurrency=args.concurrency,
636
+ max_tokens=args.max_tokens,
637
+ temperature=args.temperature,
638
+ top_p=args.top_p,
639
+ target_size=args.target_size,
640
+ request_timeout=args.request_timeout,
641
+ hf_token=args.hf_token,
642
+ split=args.split,
643
+ max_samples=args.max_samples,
644
+ private=args.private,
645
+ shuffle=args.shuffle,
646
+ seed=args.seed,
647
+ output_column=args.output_column,
648
+ overwrite=args.overwrite,
649
+ config=args.config,
650
+ create_pr=args.create_pr,
651
+ )
models.json CHANGED
@@ -118,6 +118,17 @@
118
  "license": "apache-2.0",
119
  "languages": { "evidence": "not-stated" }
120
  },
 
 
 
 
 
 
 
 
 
 
 
121
  "lighton-ocr.py": {
122
  "model_id": "lightonai/LightOnOCR-1B-1025",
123
  "params": "1B",
@@ -144,6 +155,21 @@
144
  "notes": "Adds zh/ja over v1; declared, not benchmarked per language."
145
  }
146
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  "hunyuan-ocr.py": {
148
  "model_id": "tencent/HunyuanOCR",
149
  "revision": "f6af82ee007fe6091b29fb3bb287b491ead41c82",
 
118
  "license": "apache-2.0",
119
  "languages": { "evidence": "not-stated" }
120
  },
121
+ "ovis-ocr2-server.py": {
122
+ "model_id": "ATH-MaaS/OvisOCR2",
123
+ "params": "0.9B",
124
+ "backend": "vllm-server (in-job vllm serve + concurrent driver)",
125
+ "image": "vllm/vllm-openai:v0.22.1",
126
+ "task": "ocr",
127
+ "output": "markdown + LaTeX + HTML tables",
128
+ "license": "apache-2.0",
129
+ "notes": "Server-mode sibling of ovis-ocr2.py: ~1.7x its inference throughput, per-request failure isolation. See SERVING.md.",
130
+ "languages": { "evidence": "not-stated" }
131
+ },
132
  "lighton-ocr.py": {
133
  "model_id": "lightonai/LightOnOCR-1B-1025",
134
  "params": "1B",
 
155
  "notes": "Adds zh/ja over v1; declared, not benchmarked per language."
156
  }
157
  },
158
+ "lighton-ocr2-server.py": {
159
+ "model_id": "lightonai/LightOnOCR-2-1B",
160
+ "params": "1B",
161
+ "backend": "vllm-server (in-job vllm serve + concurrent driver)",
162
+ "image": "vllm/vllm-openai:v0.22.1",
163
+ "task": "ocr",
164
+ "output": "markdown",
165
+ "notes": "Server-mode sibling of lighton-ocr2.py (the model card's own documented path): ~1.8x its inference throughput. See SERVING.md.",
166
+ "languages": {
167
+ "evidence": "named-list",
168
+ "count": 11,
169
+ "named": ["en", "fr", "de", "es", "it", "nl", "pt", "sv", "da", "zh", "ja"],
170
+ "notes": "Adds zh/ja over v1; declared, not benchmarked per language."
171
+ }
172
+ },
173
  "hunyuan-ocr.py": {
174
  "model_id": "tencent/HunyuanOCR",
175
  "revision": "f6af82ee007fe6091b29fb3bb287b491ead41c82",
ovis-ocr2-server.py ADDED
@@ -0,0 +1,725 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 create_dataset_card(
329
+ source_dataset: str,
330
+ model: str,
331
+ num_samples: int,
332
+ num_errors: int,
333
+ processing_time: str,
334
+ images_per_sec: float,
335
+ concurrency: int,
336
+ max_tokens: int,
337
+ keep_image_tags: bool,
338
+ image_column: str = "image",
339
+ split: str = "train",
340
+ ) -> str:
341
+ """Create a dataset card documenting the OCR process."""
342
+ model_name = model.split("/")[-1]
343
+
344
+ # Canonical provenance stamp (see AGENTS.md): Jobs claim gated on JOB_ID, set by HF Jobs in-container.
345
+ on_jobs = os.environ.get("JOB_ID") is not None
346
+ hw = os.environ.get("ACCELERATOR") or ""
347
+ origin = (
348
+ "Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"
349
+ + (f" (`{hw}`)" if hw else "")
350
+ ) if on_jobs else "Generated"
351
+ jobs_tag = "\n- hf-jobs" if on_jobs else ""
352
+
353
+ return f"""---
354
+ tags:
355
+ - ocr
356
+ - document-processing
357
+ - ovis-ocr2
358
+ - markdown
359
+ - uv-script
360
+ - generated{jobs_tag}
361
+ ---
362
+
363
+ # Document OCR using {model_name} (server mode)
364
+
365
+ 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).
366
+
367
+ ## Processing Details
368
+
369
+ - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
370
+ - **Model**: [{model}](https://huggingface.co/{model})
371
+ - **Number of Samples**: {num_samples:,}
372
+ - **Failed Requests**: {num_errors:,} (marked `[OCR ERROR]`)
373
+ - **Processing Time**: {processing_time}
374
+ - **Throughput**: {images_per_sec:.2f} images/sec
375
+ - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
376
+
377
+ ### Configuration
378
+
379
+ - **Mode**: vLLM server (`vllm serve`) + concurrent driver, {concurrency} concurrent requests
380
+ - **Image Column**: `{image_column}`
381
+ - **Dataset Split**: `{split}`
382
+ - **Max Output Tokens**: {max_tokens:,}
383
+ - **Temperature**: 0.0 (greedy, per model card)
384
+ - **Visual-region image tags**: {"kept" if keep_image_tags else "filtered (default)"}
385
+
386
+ ## Dataset Structure
387
+
388
+ The dataset contains all original columns plus:
389
+ - `markdown`: The extracted text in markdown format
390
+ - `inference_info`: JSON list tracking all OCR models applied to this dataset
391
+
392
+ ## Reproduction
393
+
394
+ {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).
395
+ """
396
+
397
+
398
+ def main(
399
+ input_dataset: str,
400
+ output_dataset: str,
401
+ image_column: str = "image",
402
+ server: str = "http://127.0.0.1:8000",
403
+ concurrency: int = 32,
404
+ max_tokens: int = 16384,
405
+ max_pixels: int = DEFAULT_MAX_PIXELS,
406
+ request_timeout: int = 1800,
407
+ keep_image_tags: bool = False,
408
+ hf_token: str = None,
409
+ split: str = "train",
410
+ max_samples: int = None,
411
+ private: bool = False,
412
+ shuffle: bool = False,
413
+ seed: int = 42,
414
+ output_column: str = "markdown",
415
+ overwrite: bool = False,
416
+ config: str = None,
417
+ create_pr: bool = False,
418
+ ):
419
+ """Process images from HF dataset through an OvisOCR2 vLLM server."""
420
+
421
+ start_time = datetime.now()
422
+
423
+ HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
424
+ if HF_TOKEN:
425
+ login(token=HF_TOKEN)
426
+
427
+ logger.info(f"Using model: {MODEL} via server {server}")
428
+
429
+ logger.info(f"Loading dataset: {input_dataset}")
430
+ dataset = load_dataset(input_dataset, split=split)
431
+
432
+ if image_column not in dataset.column_names:
433
+ raise ValueError(
434
+ f"Column '{image_column}' not found. Available: {dataset.column_names}"
435
+ )
436
+
437
+ dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
438
+
439
+ if shuffle:
440
+ logger.info(f"Shuffling dataset with seed {seed}")
441
+ dataset = dataset.shuffle(seed=seed)
442
+
443
+ if max_samples:
444
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
445
+ logger.info(f"Limited to {len(dataset)} samples")
446
+
447
+ # Reuse a reachable server, else spawn `vllm serve` (needs the vllm binary,
448
+ # i.e. a vllm/vllm-openai image), else fail fast with the correct command.
449
+ ensure_server(server)
450
+
451
+ n = len(dataset)
452
+ logger.info(f"Processing {n} images, concurrency {concurrency}")
453
+ all_outputs = [None] * n
454
+ errors = 0
455
+ done = 0
456
+ inference_start = time.time()
457
+ lock = threading.Lock()
458
+
459
+ def worker(i: int) -> None:
460
+ nonlocal errors, done
461
+ try:
462
+ text = ocr_one(
463
+ server,
464
+ dataset[i][image_column],
465
+ max_pixels,
466
+ max_tokens,
467
+ request_timeout,
468
+ )
469
+ all_outputs[i] = postprocess_output(text, keep_image_tags)
470
+ except Exception as e:
471
+ logger.error(f"Image {i} failed: {e}")
472
+ all_outputs[i] = "[OCR ERROR]"
473
+ with lock:
474
+ errors += 1
475
+ with lock:
476
+ done += 1
477
+ if done % 25 == 0 or done == n:
478
+ rate = done / max(time.time() - inference_start, 1e-9)
479
+ logger.info(f"{done}/{n} done ({rate:.2f} img/s, {errors} errors)")
480
+
481
+ with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as pool:
482
+ list(pool.map(worker, range(n)))
483
+
484
+ inference_secs = time.time() - inference_start
485
+ processing_duration = datetime.now() - start_time
486
+ processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
487
+ images_per_sec = n / inference_secs if inference_secs else 0.0
488
+
489
+ logger.info(f"Adding '{output_column}' column to dataset")
490
+ dataset = dataset.add_column(output_column, all_outputs)
491
+
492
+ # Inference info tracking
493
+ inference_entry = {
494
+ "model_id": MODEL,
495
+ "model_name": "OvisOCR2",
496
+ "column_name": output_column,
497
+ "timestamp": datetime.now().isoformat(),
498
+ "temperature": 0.0,
499
+ "max_tokens": max_tokens,
500
+ "max_pixels": max_pixels,
501
+ "keep_image_tags": keep_image_tags,
502
+ "mode": "vllm-server",
503
+ "concurrency": concurrency,
504
+ }
505
+
506
+ if "inference_info" in dataset.column_names:
507
+ logger.info("Updating existing inference_info column")
508
+
509
+ def update_inference_info(example):
510
+ try:
511
+ existing_info = (
512
+ json.loads(example["inference_info"])
513
+ if example["inference_info"]
514
+ else []
515
+ )
516
+ except (json.JSONDecodeError, TypeError):
517
+ existing_info = []
518
+ existing_info.append(inference_entry)
519
+ return {"inference_info": json.dumps(existing_info)}
520
+
521
+ dataset = dataset.map(update_inference_info)
522
+ else:
523
+ logger.info("Creating new inference_info column")
524
+ inference_list = [json.dumps([inference_entry])] * len(dataset)
525
+ dataset = dataset.add_column("inference_info", inference_list)
526
+
527
+ # Push to hub with retry and XET fallback
528
+ logger.info(f"Pushing to {output_dataset}")
529
+ max_retries = 3
530
+ for attempt in range(1, max_retries + 1):
531
+ try:
532
+ if attempt > 1:
533
+ logger.warning("Disabling XET (fallback to HTTP upload)")
534
+ os.environ["HF_HUB_DISABLE_XET"] = "1"
535
+ dataset.push_to_hub(
536
+ output_dataset,
537
+ private=private,
538
+ token=HF_TOKEN,
539
+ max_shard_size="500MB",
540
+ **({"config_name": config} if config else {}),
541
+ create_pr=create_pr,
542
+ commit_message=f"Add {MODEL} OCR results ({len(dataset)} samples, server mode)"
543
+ + (f" [{config}]" if config else ""),
544
+ )
545
+ break
546
+ except Exception as e:
547
+ logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
548
+ if attempt < max_retries:
549
+ delay = 30 * (2 ** (attempt - 1))
550
+ logger.info(f"Retrying in {delay}s...")
551
+ time.sleep(delay)
552
+ else:
553
+ logger.error("All upload attempts failed. OCR results are lost.")
554
+ sys.exit(1)
555
+
556
+ logger.info("Creating dataset card")
557
+ card_content = create_dataset_card(
558
+ source_dataset=input_dataset,
559
+ model=MODEL,
560
+ num_samples=len(dataset),
561
+ num_errors=errors,
562
+ processing_time=processing_time_str,
563
+ images_per_sec=images_per_sec,
564
+ concurrency=concurrency,
565
+ max_tokens=max_tokens,
566
+ keep_image_tags=keep_image_tags,
567
+ image_column=image_column,
568
+ split=split,
569
+ )
570
+
571
+ card = DatasetCard(card_content)
572
+ card.push_to_hub(output_dataset, token=HF_TOKEN)
573
+
574
+ logger.info("Done! OvisOCR2 server-mode processing complete.")
575
+ logger.info(
576
+ f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
577
+ )
578
+ logger.info(f"Processing time: {processing_time_str}")
579
+ logger.info(
580
+ f"Throughput: {images_per_sec:.2f} images/sec "
581
+ f"(inference only, excl. dataset load/push; {errors} errors)"
582
+ )
583
+
584
+
585
+ if __name__ == "__main__":
586
+ if len(sys.argv) == 1:
587
+ print("=" * 70)
588
+ print("OvisOCR2 Document Processing (vLLM server mode)")
589
+ print("=" * 70)
590
+ print("\nSame model + outputs as ovis-ocr2.py, but drives an in-job")
591
+ print("`vllm serve` with concurrent requests — no batch barriers,")
592
+ print("per-image (not per-batch) failure isolation.")
593
+ print("\nThe server must already be running (the job command starts")
594
+ print("both — see the module docstring for the full `hf jobs run`).")
595
+ print("\nExamples:")
596
+ print("\n1. Basic OCR (server on localhost:8000):")
597
+ print(" uv run ovis-ocr2-server.py input-dataset output-dataset")
598
+ print("\n2. Test with a small sample:")
599
+ print(" uv run ovis-ocr2-server.py large-dataset test --max-samples 10 --shuffle")
600
+ print("\n3. Throughput A/B vs the offline recipe:")
601
+ print(" run both scripts on the same --max-samples slice and compare")
602
+ print(" the images/sec lines + diff the markdown columns")
603
+ print("\nFor full help: uv run ovis-ocr2-server.py --help")
604
+ sys.exit(0)
605
+
606
+ parser = argparse.ArgumentParser(
607
+ description="Document OCR using OvisOCR2 via an in-job vLLM server",
608
+ formatter_class=argparse.RawDescriptionHelpFormatter,
609
+ epilog="""
610
+ Examples:
611
+ uv run ovis-ocr2-server.py my-docs analyzed-docs
612
+ uv run ovis-ocr2-server.py large-dataset test --max-samples 50 --shuffle
613
+ See the module docstring for the full `hf jobs run` command (server + driver in one job).
614
+ """,
615
+ )
616
+
617
+ parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
618
+ parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
619
+ parser.add_argument(
620
+ "--image-column",
621
+ default="image",
622
+ help="Column containing images (default: image)",
623
+ )
624
+ parser.add_argument(
625
+ "--server",
626
+ default="http://127.0.0.1:8000",
627
+ help="vLLM server base URL (default: in-job localhost:8000)",
628
+ )
629
+ parser.add_argument(
630
+ "--concurrency",
631
+ type=int,
632
+ default=32,
633
+ help="Concurrent OCR requests (default: 32; vLLM queues excess internally, "
634
+ "so this mainly needs to be high enough to keep continuous batching fed)",
635
+ )
636
+ parser.add_argument(
637
+ "--max-tokens",
638
+ type=int,
639
+ default=16384,
640
+ help="Maximum tokens to generate (default: 16384, the model card value)",
641
+ )
642
+ parser.add_argument(
643
+ "--max-pixels",
644
+ type=int,
645
+ default=DEFAULT_MAX_PIXELS,
646
+ help=f"Maximum image pixels; larger images are downscaled client-side before "
647
+ f"upload (default: {DEFAULT_MAX_PIXELS}, = 2880*2880, the model card value)",
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(
656
+ "--keep-image-tags",
657
+ action="store_true",
658
+ help="Keep visual-region <img src=\"images/bbox_...\"> tags in the output "
659
+ "(default: filtered, matching the upstream parser)",
660
+ )
661
+ parser.add_argument("--hf-token", help="Hugging Face API token")
662
+ parser.add_argument(
663
+ "--split", default="train", help="Dataset split to use (default: train)"
664
+ )
665
+ parser.add_argument(
666
+ "--max-samples",
667
+ type=int,
668
+ help="Maximum number of samples to process (for testing)",
669
+ )
670
+ parser.add_argument(
671
+ "--private", action="store_true", help="Make output dataset private"
672
+ )
673
+ parser.add_argument(
674
+ "--config",
675
+ help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
676
+ )
677
+ parser.add_argument(
678
+ "--create-pr",
679
+ action="store_true",
680
+ help="Create a pull request instead of pushing directly (for parallel benchmarking)",
681
+ )
682
+ parser.add_argument(
683
+ "--shuffle", action="store_true", help="Shuffle dataset before processing"
684
+ )
685
+ parser.add_argument(
686
+ "--seed",
687
+ type=int,
688
+ default=42,
689
+ help="Random seed for shuffling (default: 42)",
690
+ )
691
+ parser.add_argument(
692
+ "--output-column",
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
+
703
+ args = parser.parse_args()
704
+
705
+ main(
706
+ input_dataset=args.input_dataset,
707
+ output_dataset=args.output_dataset,
708
+ image_column=args.image_column,
709
+ server=args.server,
710
+ concurrency=args.concurrency,
711
+ max_tokens=args.max_tokens,
712
+ max_pixels=args.max_pixels,
713
+ request_timeout=args.request_timeout,
714
+ keep_image_tags=args.keep_image_tags,
715
+ hf_token=args.hf_token,
716
+ split=args.split,
717
+ max_samples=args.max_samples,
718
+ private=args.private,
719
+ shuffle=args.shuffle,
720
+ seed=args.seed,
721
+ output_column=args.output_column,
722
+ overwrite=args.overwrite,
723
+ config=args.config,
724
+ create_pr=args.create_pr,
725
+ )