Sync from GitHub via hub-sync
Browse files- CLAUDE.md +29 -0
- README.md +12 -0
- models.json +47 -1
- unlimited-ocr2-saturate.py +911 -0
- unlimited-ocr2.py +303 -0
CLAUDE.md
CHANGED
|
@@ -92,6 +92,8 @@ Legend: ✅ production-ready · ⚠️ works only with a required pinned image
|
|
| 92 |
| `nanonets-ocr.py` | ✅ | vLLM | a10g-small | `--max-model-len` 32768 (`--max-tokens` 15000) |
|
| 93 |
| `nanonets-ocr2.py` | ⚠️+image | vLLM `:v0.10.2` | a10g-small | Qwen2.5-VL ≥0.11 regression → pure `!` |
|
| 94 |
| `unlimited-ocr-vllm.py` | ✅+image | vLLM `:unlimited-ocr` | l4x1 | single-image; multi-page → serve |
|
|
|
|
|
|
|
| 95 |
| `surya-ocr.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | offline backend inject; site-packages PYTHONPATH |
|
| 96 |
| `surya-ocr-bucket.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | bucket I/O; pin `surya-ocr==0.20.0` |
|
| 97 |
| `lift-extract.py` | ✅ | hf / vLLM | a100-large | schema-constrained extraction; naming gotcha |
|
|
@@ -166,6 +168,26 @@ hard scans) and belongs to **serving** — both engines read clean multi-page do
|
|
| 166 |
robust on hard/degraded scans**. Serving setup (SGLang pin `lmsysorg/sglang:v0.5.10.post1`, a100+flashinfer
|
| 167 |
— HF `h200` nodes fail with `CUDA error 802`) is in `serving-unlimited-ocr.md`.
|
| 168 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
### `lift-extract.py` — naming + backends
|
| 170 |
Datalab `lift` (9B, Qwen3.5), schema-constrained image/PDF → JSON; the only recipe ingesting PDFs directly.
|
| 171 |
**Must not be named `lift.py`** (shadows the installed `lift` package → ImportError). Two in-process backends
|
|
@@ -299,6 +321,13 @@ ARM wheels) — if a nightly-recipe install fails on resolution, wait and retry
|
|
| 299 |
|
| 300 |
## Change log
|
| 301 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
- **2026-07-29** — added the first two **`-saturate.py` companions**: `lighton-ocr2-saturate.py` and
|
| 303 |
`ovis-ocr2-saturate.py`. Same model/prompt/sampling/post-processing as their `-server.py` siblings;
|
| 304 |
the driver half (concurrency, retries, output, resume) is the `saturate` package (pinned `>=0.1.1`,
|
|
|
|
| 92 |
| `nanonets-ocr.py` | ✅ | vLLM | a10g-small | `--max-model-len` 32768 (`--max-tokens` 15000) |
|
| 93 |
| `nanonets-ocr2.py` | ⚠️+image | vLLM `:v0.10.2` | a10g-small | Qwen2.5-VL ≥0.11 regression → pure `!` |
|
| 94 |
| `unlimited-ocr-vllm.py` | ✅+image | vLLM `:unlimited-ocr` | l4x1 | single-image; multi-page → serve |
|
| 95 |
+
| `unlimited-ocr2.py` | ✅+image | SGLang (Baidu wheel) on `lmsysorg/sglang:v0.5.20-cu130` | rtx-pro-6000 | 16-page windows; ≥48 GB GPU |
|
| 96 |
+
| `unlimited-ocr2-saturate.py` | 🧪+image | same | rtx-pro-6000 | tuned/experimental: repair pass, JP2 fast decode, PDFs |
|
| 97 |
| `surya-ocr.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | offline backend inject; site-packages PYTHONPATH |
|
| 98 |
| `surya-ocr-bucket.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | bucket I/O; pin `surya-ocr==0.20.0` |
|
| 99 |
| `lift-extract.py` | ✅ | hf / vLLM | a100-large | schema-constrained extraction; naming gotcha |
|
|
|
|
| 168 |
robust on hard/degraded scans**. Serving setup (SGLang pin `lmsysorg/sglang:v0.5.10.post1`, a100+flashinfer
|
| 169 |
— HF `h200` nodes fail with `CUDA error 802`) is in `serving-unlimited-ocr.md`.
|
| 170 |
|
| 171 |
+
### `unlimited-ocr2.py` / `unlimited-ocr2-saturate.py` — Baidu SGLang wheel, multi-page windows
|
| 172 |
+
v2 has no vLLM support; Baidu ships a custom SGLang wheel in the model repo. Its pins (torch 2.13.0,
|
| 173 |
+
transformers 5.12.1, flashinfer 0.6.18 cu13) match **`lmsysorg/sglang:v0.5.20`** exactly → `-cu130` image,
|
| 174 |
+
wheel installed `--no-deps` into the image's **`/opt/sglang` venv** (found on PATH past the uv venv). Move
|
| 175 |
+
image and wheel together. Gotchas measured 2026-10-27 on 1771 Britannica:
|
| 176 |
+
- The card's n-gram guard is a pure-Python logit processor run every decode step → decode is
|
| 177 |
+
scheduler-CPU-bound (A100 at ~33% GPU util). Turning it off breaks windows (13/32 failed); window 128
|
| 178 |
+
is 1.3x faster but loops more → keep 1024. The processor string is a fixed pickled global (no sglang
|
| 179 |
+
or dill needed in the driver).
|
| 180 |
+
- 16-page windows reach ~31k tokens of KV each: 24 GB GPUs thrash (retractions), l40s (48 GB) hits KV
|
| 181 |
+
pressure; rtx-pro-6000 (96 GB, 23 vCPU) was 1.6x a100-large throughput at ~30% lower $/page.
|
| 182 |
+
- ~2% of dense pages (mathematics) loop; the per-page token cap then forces a `<PAGE>` and shifts the next
|
| 183 |
+
page's text by one. `-saturate` re-reads looping pages + empty neighbours alone in gundam mode (28/33 fixed).
|
| 184 |
+
- Send pages at 1280 px in base mode (the model sees a 1024 view): 1600+ px bodies (~14 MB per window)
|
| 185 |
+
stalled SGLang's HTTP front end past saturate's fixed 30 s connect/write timeouts.
|
| 186 |
+
- saturate 0.2.0: `RETRY_BUDGET_S` (300 s) < one window, so retries always timed out → raised to 3600 in
|
| 187 |
+
the scripts; `Auto` widens only on completions (start it at 32); `flush_every=4`. Pinned `==0.2.0`.
|
| 188 |
+
- JP2 decode at a reduced level (`img.reduce`) failed intermittently in Jobs ("broken data stream", not
|
| 189 |
+
reproducible on macOS) → fallback to a fuller decode.
|
| 190 |
+
|
| 191 |
### `lift-extract.py` — naming + backends
|
| 192 |
Datalab `lift` (9B, Qwen3.5), schema-constrained image/PDF → JSON; the only recipe ingesting PDFs directly.
|
| 193 |
**Must not be named `lift.py`** (shadows the installed `lift` package → ImportError). Two in-process backends
|
|
|
|
| 321 |
|
| 322 |
## Change log
|
| 323 |
|
| 324 |
+
- **2026-10-27** — added `unlimited-ocr2.py` (minimal) and `unlimited-ocr2-saturate.py` (tuned, experimental)
|
| 325 |
+
for `baidu/Unlimited-OCR-2`: whole-document OCR in 16-page windows on Baidu's SGLang build, driven by
|
| 326 |
+
saturate (pinned `==0.2.0`). First recipes whose unit of work is a document, not a page; input is a
|
| 327 |
+
glob/folder of page files (Buckets), output one row per window with a `status` column. Header flavor
|
| 328 |
+
`rtx-pro-6000` from a flavor sweep. Full 1771 Britannica (2,724 pages): 171 windows, 0 errors, 123
|
| 329 |
+
pages re-read by the repair pass. New `support` level `experimental` in models.json.
|
| 330 |
+
|
| 331 |
- **2026-07-29** — added the first two **`-saturate.py` companions**: `lighton-ocr2-saturate.py` and
|
| 332 |
`ovis-ocr2-saturate.py`. Same model/prompt/sampling/post-processing as their `-server.py` siblings;
|
| 333 |
the driver half (concurrency, retries, output, resume) is the `saturate` package (pinned `>=0.1.1`,
|
README.md
CHANGED
|
@@ -92,6 +92,7 @@ These are the maintained recipes. Each one has a tested `[tool.hf-jobs]` header,
|
|
| 92 |
| [`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` |
|
| 93 |
| [`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` |
|
| 94 |
| [`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` |
|
|
|
|
| 95 |
| [`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` |
|
| 96 |
| [`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` |
|
| 97 |
| [`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` |
|
|
@@ -220,6 +221,17 @@ hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/pp-doclay
|
|
| 220 |
|
| 221 |
**Large datasets:** `lighton-ocr2-saturate.py` and `ovis-ocr2-saturate.py` start a vLLM server in the Job 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).
|
| 222 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
```bash
|
| 224 |
hf jobs uv run --detach --timeout 4h \
|
| 225 |
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr2-saturate.py \
|
|
|
|
| 92 |
| [`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` |
|
| 93 |
| [`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` |
|
| 94 |
| [`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` |
|
| 95 |
+
| [`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` |
|
| 96 |
| [`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` |
|
| 97 |
| [`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` |
|
| 98 |
| [`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` |
|
|
|
|
| 221 |
|
| 222 |
**Large datasets:** `lighton-ocr2-saturate.py` and `ovis-ocr2-saturate.py` start a vLLM server in the Job 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).
|
| 223 |
|
| 224 |
+
**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:
|
| 225 |
+
|
| 226 |
+
```bash
|
| 227 |
+
hf jobs uv run --detach \
|
| 228 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/unlimited-ocr2.py \
|
| 229 |
+
"hf://buckets/biglam/britannica/source/pages/1771EncyclopediaBritannicaNLS/*.jp2" \
|
| 230 |
+
your-username/britannica-1771
|
| 231 |
+
```
|
| 232 |
+
|
| 233 |
+
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 faster JPEG 2000 decoding.
|
| 234 |
+
|
| 235 |
```bash
|
| 236 |
hf jobs uv run --detach --timeout 4h \
|
| 237 |
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr2-saturate.py \
|
models.json
CHANGED
|
@@ -7,7 +7,8 @@
|
|
| 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 |
}
|
| 12 |
},
|
| 13 |
"tesseract-ocr.py": {
|
|
@@ -669,6 +670,51 @@
|
|
| 669 |
]
|
| 670 |
}
|
| 671 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 672 |
"unlimited-ocr-vllm.py": {
|
| 673 |
"model_id": "baidu/Unlimited-OCR",
|
| 674 |
"params": "3.3B",
|
|
|
|
| 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": {
|
|
|
|
| 670 |
]
|
| 671 |
}
|
| 672 |
},
|
| 673 |
+
"unlimited-ocr2.py": {
|
| 674 |
+
"model_id": "baidu/Unlimited-OCR-2",
|
| 675 |
+
"params": "3.3B (MoE, 0.5B active)",
|
| 676 |
+
"backend": "saturate (in-job SGLang from Baidu's wheel + saturate pump)",
|
| 677 |
+
"image": "lmsysorg/sglang:v0.5.20-cu130",
|
| 678 |
+
"task": "ocr (multi-page documents: folders of page images; cross-page continuations)",
|
| 679 |
+
"output": "markdown per page + layout-grounded raw, one row per 16-page window",
|
| 680 |
+
"license": "mit",
|
| 681 |
+
"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.",
|
| 682 |
+
"languages": {
|
| 683 |
+
"evidence": "multilingual-unspecified"
|
| 684 |
+
},
|
| 685 |
+
"support": "core",
|
| 686 |
+
"jobs": {
|
| 687 |
+
"image": "lmsysorg/sglang:v0.5.20-cu130",
|
| 688 |
+
"flavor": "rtx-pro-6000",
|
| 689 |
+
"timeout": "4h",
|
| 690 |
+
"secrets": [
|
| 691 |
+
"HF_TOKEN"
|
| 692 |
+
]
|
| 693 |
+
}
|
| 694 |
+
},
|
| 695 |
+
"unlimited-ocr2-saturate.py": {
|
| 696 |
+
"model_id": "baidu/Unlimited-OCR-2",
|
| 697 |
+
"params": "3.3B (MoE, 0.5B active)",
|
| 698 |
+
"backend": "saturate (in-job SGLang from Baidu's wheel + saturate pump)",
|
| 699 |
+
"image": "lmsysorg/sglang:v0.5.20-cu130",
|
| 700 |
+
"task": "ocr (multi-page documents: book volumes, PDFs; cross-page continuations)",
|
| 701 |
+
"output": "markdown per page and per window + layout-grounded raw",
|
| 702 |
+
"license": "mit",
|
| 703 |
+
"notes": "Tuned version of unlimited-ocr2.py: repair pass for looping pages (fixed 28/33 in testing), faster JPEG 2000 decoding, PDF input, Baidu's own Markdown post-processing, speed flags.",
|
| 704 |
+
"languages": {
|
| 705 |
+
"evidence": "multilingual-unspecified"
|
| 706 |
+
},
|
| 707 |
+
"support": "experimental",
|
| 708 |
+
"support_note": "Use unlimited-ocr2.py unless you need the repair pass, PDFs or the extras.",
|
| 709 |
+
"jobs": {
|
| 710 |
+
"image": "lmsysorg/sglang:v0.5.20-cu130",
|
| 711 |
+
"flavor": "rtx-pro-6000",
|
| 712 |
+
"timeout": "4h",
|
| 713 |
+
"secrets": [
|
| 714 |
+
"HF_TOKEN"
|
| 715 |
+
]
|
| 716 |
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "saturate[hf]==0.2.0",
|
| 5 |
+
# "pillow>=10",
|
| 6 |
+
# "pymupdf>=1.24",
|
| 7 |
+
# ]
|
| 8 |
+
#
|
| 9 |
+
# [tool.hf-jobs]
|
| 10 |
+
# image = "lmsysorg/sglang:v0.5.20-cu130"
|
| 11 |
+
# flavor = "rtx-pro-6000"
|
| 12 |
+
# timeout = "4h"
|
| 13 |
+
# secrets = ["HF_TOKEN"]
|
| 14 |
+
# ///
|
| 15 |
+
"""
|
| 16 |
+
OCR whole documents (book volumes, PDFs) with Baidu Unlimited-OCR-2 via saturate.
|
| 17 |
+
|
| 18 |
+
Tuned version of `unlimited-ocr2.py`, and experimental: it adds a repair pass for
|
| 19 |
+
pages the model loops on, faster JPEG 2000 decoding, PDF input, Baidu's own
|
| 20 |
+
Markdown post-processing and speed flags. It changes more often; start with
|
| 21 |
+
`unlimited-ocr2.py` and use this one when you need the extras. Window ids and the
|
| 22 |
+
main output layout are the same, so `--repair-only` works on a minimal run too.
|
| 23 |
+
|
| 24 |
+
Unlimited-OCR-2 reads many pages in ONE request and keeps context across page
|
| 25 |
+
breaks: a paragraph that runs onto the next page comes back tagged as a
|
| 26 |
+
continuation, not as two fragments. So the unit of work here is a document, not
|
| 27 |
+
a page. Input is a folder (bucket, mounted dir or local) of page images and/or
|
| 28 |
+
PDFs; pages are grouped into documents, each document is cut into windows of
|
| 29 |
+
--pages-per-request consecutive pages, and each window is one request.
|
| 30 |
+
|
| 31 |
+
Run on HF Jobs (the [tool.hf-jobs] table above supplies image, flavor, timeout
|
| 32 |
+
and HF_TOKEN; flags you pass on the command line win):
|
| 33 |
+
|
| 34 |
+
hf jobs uv run --detach \\
|
| 35 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/unlimited-ocr2-saturate.py \\
|
| 36 |
+
"hf://buckets/biglam/britannica/source/pages/1771EncyclopediaBritannicaNLS/*.jp2" \\
|
| 37 |
+
<user>/britannica-1771-uocr2
|
| 38 |
+
|
| 39 |
+
Grouping pages into documents:
|
| 40 |
+
- Page files: the document is the parent folder plus the file name with its
|
| 41 |
+
trailing page number removed (`Volume 1, A-B_0007.jp2` -> `Volume 1, A-B`),
|
| 42 |
+
so an Internet Archive item holding several volumes splits into volumes.
|
| 43 |
+
Pages are ordered by that number (natural sort).
|
| 44 |
+
- PDFs: one document per file, pages rendered at --pdf-dpi.
|
| 45 |
+
|
| 46 |
+
Output: `data/part-*.parquet` in the output dataset (or any fsspec URI, e.g.
|
| 47 |
+
hf://buckets/...), one row per window:
|
| 48 |
+
`{id, doc_id, first_page, page_files, num_pages, status, finish_reason,
|
| 49 |
+
page_markdown, markdown, raw, prompt_tokens, completion_tokens, error}`. `page_markdown` is aligned with
|
| 50 |
+
`page_files`; `raw` keeps the model's grounded output (block types + boxes).
|
| 51 |
+
`markdown` is the whole window through Baidu's own post-processor (vendored
|
| 52 |
+
below at a pinned commit): cross-page paragraph/table chains merged, figures as
|
| 53 |
+
image links, page furniture kept. `page_markdown` is a lighter per-page cleanup
|
| 54 |
+
that stays aligned with page files (page numbers and running heads dropped
|
| 55 |
+
unless --keep-furniture). A window whose output is truncated or has the wrong
|
| 56 |
+
number of <PAGE> blocks keeps its text with `status` = truncated / page_mismatch
|
| 57 |
+
(greedy decoding repeats it on retry); `page_markdown` is set only when status = ok.
|
| 58 |
+
Re-running the same command resumes; --retry-errors re-admits failed windows.
|
| 59 |
+
|
| 60 |
+
Repair pass (on by default; --no-repair skips it, --repair-only runs just it):
|
| 61 |
+
about 2% of 1771 Britannica pages, mostly dense mathematics, sent the model
|
| 62 |
+
into a loop inside a window; the forced page break then shifted the next
|
| 63 |
+
page's text by one. After the main pass, looping pages, their empty neighbours
|
| 64 |
+
and every page of a failed window are re-OCR'd one at a time in gundam mode
|
| 65 |
+
into `repairs/` (one row per page: `{page_file, page, doc_id, window, status,
|
| 66 |
+
markdown, raw}`). That fixed 28 of 33 flagged pages in testing; the rest keep
|
| 67 |
+
their text with status = degenerate. To assemble final per-page text, take the
|
| 68 |
+
`repairs/` row for a page when it exists, else `page_markdown` from its window.
|
| 69 |
+
|
| 70 |
+
Why this is a saturate recipe, not an offline one: the multi-page engine lives
|
| 71 |
+
in Baidu's own SGLang build (no vLLM support for v2). The script installs that
|
| 72 |
+
wheel into the image's Python, boots `sglang.launch_server`, and lets saturate
|
| 73 |
+
drive it (adaptive concurrency from SGLang's /metrics, resumable parquet output).
|
| 74 |
+
|
| 75 |
+
Model: baidu/Unlimited-OCR-2 (3.3B, MIT). https://huggingface.co/baidu/Unlimited-OCR-2
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
import argparse
|
| 79 |
+
import base64
|
| 80 |
+
import io
|
| 81 |
+
import json
|
| 82 |
+
import os
|
| 83 |
+
import pickle
|
| 84 |
+
import re
|
| 85 |
+
import shutil
|
| 86 |
+
import subprocess
|
| 87 |
+
import sys
|
| 88 |
+
import threading
|
| 89 |
+
import types
|
| 90 |
+
import zlib
|
| 91 |
+
|
| 92 |
+
# Per-value provenance:
|
| 93 |
+
# - image lmsysorg/sglang:v0.5.20-cu130: the SGLang release whose pins match
|
| 94 |
+
# Baidu's wheel exactly (torch 2.13.0, transformers 5.12.1, flashinfer 0.6.18
|
| 95 |
+
# cu13). The wheel is installed --no-deps on top. Move the pin only together
|
| 96 |
+
# with the wheel; drop both once upstream SGLang ships the architecture.
|
| 97 |
+
# - env + serve_args: the model card's launch command, verbatim (tuned for an
|
| 98 |
+
# 80 GB A800; validated 2026-10-27 on a100-large and rtx-pro-6000, boot ~3.5 min).
|
| 99 |
+
# - flavor rtx-pro-6000: on the same 512 1771 Britannica pages it finished 32/32
|
| 100 |
+
# windows in 805 s (1,571 tok/s end to end) vs a100-large 1,267 s (866 tok/s):
|
| 101 |
+
# ~30% cheaper per page. The n-gram guard makes decode scheduler-CPU-bound, so
|
| 102 |
+
# CPU matters as much as the GPU. 24 GB cards (a10g, l4) thrash the KV cache on
|
| 103 |
+
# 16-page windows (~31k tokens each); use >= 48 GB.
|
| 104 |
+
# - tokens_per_page 8000, ngram 35, window 1024 multi / 128 single, page guard
|
| 105 |
+
# 20000, temperature 0: the card's client example.
|
| 106 |
+
# - crop_mode False (base, one global view per page): the card's multi-page
|
| 107 |
+
# default (infer_multi). On a 32-page 1861 scan gundam (crop) mode read the
|
| 108 |
+
# same text with 6.7x the image tokens (58k vs 8.7k).
|
| 109 |
+
SERVING = {
|
| 110 |
+
"model": "baidu/Unlimited-OCR-2",
|
| 111 |
+
"served_name": "Unlimited-OCR-2",
|
| 112 |
+
"image": "lmsysorg/sglang:v0.5.20-cu130",
|
| 113 |
+
"wheel": "https://huggingface.co/baidu/Unlimited-OCR-2/resolve/main/wheel/"
|
| 114 |
+
"sglang-0.5.20.dev10%2Bg8d62f5fb9c-py3-none-any.whl",
|
| 115 |
+
"extra_pip": ["fastokens==0.3.2"],
|
| 116 |
+
"env": {
|
| 117 |
+
"SGLANG_UOCR_EANABLE_DOC_LIMIT": "1", # (sic) upstream spelling
|
| 118 |
+
"SGLANG_UOCR_DOC_GUNDAM_PAGE_WINDOW": "10",
|
| 119 |
+
"SGLANG_UOCR_DOC_BASE_PAGE_WINDOW": "10",
|
| 120 |
+
"SGLANG_UOCR_MAX_PAGE_TOKENS": "20000",
|
| 121 |
+
"SGLANG_OPT_UOCR_SAM_REL_POS_BIAS_MB": "64",
|
| 122 |
+
"SGLANG_UOCR_SHM_WRAP_MODEL_DATA": "1",
|
| 123 |
+
"SGLANG_UOCR_SHM_WRAP_MIN_MB": "1",
|
| 124 |
+
"SGLANG_VLM_CACHE_SIZE_MB": "0",
|
| 125 |
+
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
|
| 126 |
+
},
|
| 127 |
+
"serve_args": [
|
| 128 |
+
"--chat-template", "unlimited-ocr",
|
| 129 |
+
"--tokenizer-backend", "fastokens", "--tokenizer-worker-num", "8",
|
| 130 |
+
"--mem-fraction-static", "0.7",
|
| 131 |
+
"--max-running-requests", "64",
|
| 132 |
+
"--max-prefill-tokens", "2048",
|
| 133 |
+
"--enable-custom-logit-processor", "--enable-streaming-session",
|
| 134 |
+
"--allow-auto-truncate", "--disable-radix-cache",
|
| 135 |
+
"--mm-preprocess-cache-size-mb", "0",
|
| 136 |
+
"--cuda-graph-backend-decode", "full", "--cuda-graph-max-bs-decode", "64",
|
| 137 |
+
"--cuda-graph-backend-prefill", "full",
|
| 138 |
+
"--cuda-graph-max-bs-prefill", "16384",
|
| 139 |
+
"--cuda-graph-bs-prefill", "1024", "2048",
|
| 140 |
+
"--cuda-graph-config", '{"prefill": {"backend": "full", "full_prefill_max_req": 64}}',
|
| 141 |
+
],
|
| 142 |
+
"tokens_per_page": 8000,
|
| 143 |
+
"temperature": 0.0,
|
| 144 |
+
"crop_mode": False,
|
| 145 |
+
"ngram_size": 35,
|
| 146 |
+
"page_token_id": 128827, # <PAGE>, = sparse_attention_config.page_token_id
|
| 147 |
+
"eos_token_id": 1,
|
| 148 |
+
"max_page_tokens": 20000,
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
PDF_LOCK = threading.Lock()
|
| 152 |
+
PAGE_EXTS = (".jp2", ".jpg", ".jpeg", ".png", ".tif", ".tiff", ".webp")
|
| 153 |
+
FURNITURE = {"page_number", "header", "footer"}
|
| 154 |
+
PAGE_BLOCK_RE = re.compile(r"<BLOCK>(?P<type>[a-z_]+)(?:<LEVEL(?P<level>\d)>)?\[[\d, ]*\]<FORK>")
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def ngram_processor() -> str:
|
| 158 |
+
"""The card's DeepseekOCRNoRepeatNGramLogitProcessor.to_str(), built without sglang.
|
| 159 |
+
|
| 160 |
+
to_str() is json({"callable": dill.dumps(cls).hex()}) and dill pickles an
|
| 161 |
+
importable class by reference, so the payload is just a pickled global
|
| 162 |
+
(module + name). Building it here keeps sglang/torch/dill out of the driver.
|
| 163 |
+
"""
|
| 164 |
+
mod, name = "sglang.srt.sampling.custom_logit_processor", "DeepseekOCRNoRepeatNGramLogitProcessor"
|
| 165 |
+
saved = {k: sys.modules.get(k) for k in ("sglang", "sglang.srt", "sglang.srt.sampling", mod)}
|
| 166 |
+
try:
|
| 167 |
+
parts = mod.split(".")
|
| 168 |
+
for i in range(len(parts)):
|
| 169 |
+
sys.modules[".".join(parts[: i + 1])] = types.ModuleType(parts[i])
|
| 170 |
+
cls = type(name, (), {"__module__": mod})
|
| 171 |
+
setattr(sys.modules[mod], name, cls)
|
| 172 |
+
return json.dumps({"callable": pickle.dumps(cls).hex()})
|
| 173 |
+
finally:
|
| 174 |
+
for k, v in saved.items():
|
| 175 |
+
if v is None:
|
| 176 |
+
sys.modules.pop(k, None)
|
| 177 |
+
else:
|
| 178 |
+
sys.modules[k] = v
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def natural_key(s: str):
|
| 182 |
+
return [int(t) if t.isdigit() else t for t in re.split(r"(\d+)", s)]
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def doc_key(rel_path: str) -> str:
|
| 186 |
+
"""`item/Volume 1, A-B_0007.jp2` -> `item/Volume 1, A-B`; a PDF is its own doc."""
|
| 187 |
+
if rel_path.lower().endswith(".pdf"):
|
| 188 |
+
return rel_path
|
| 189 |
+
stem = rel_path.rsplit(".", 1)[0]
|
| 190 |
+
doc = re.sub(r"[_\-. ]?\d+$", "", stem)
|
| 191 |
+
return doc if doc and not doc.endswith("/") else (doc or ".")
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def list_windows(pattern: str, pages_per_request: int, limit_docs, max_pages, pdf_dpi):
|
| 195 |
+
"""List page files, group into documents, cut each into windows -> (id, row)."""
|
| 196 |
+
import fsspec
|
| 197 |
+
from saturate import bucket_rows
|
| 198 |
+
|
| 199 |
+
if not re.search(r"[*?\[]", pattern) and not pattern.lower().endswith(".pdf"):
|
| 200 |
+
pattern = pattern.rstrip("/") + "/**"
|
| 201 |
+
files = [(rid, row["path"]) for rid, row in bucket_rows(pattern, read=False)
|
| 202 |
+
if rid.lower().endswith(PAGE_EXTS + (".pdf",))]
|
| 203 |
+
if not files:
|
| 204 |
+
sys.exit(f"no page images or PDFs matched {pattern!r}")
|
| 205 |
+
|
| 206 |
+
docs: dict[str, list[tuple[str, str]]] = {}
|
| 207 |
+
for rid, path in files:
|
| 208 |
+
docs.setdefault(doc_key(rid), []).append((rid, path))
|
| 209 |
+
doc_ids = sorted(docs, key=natural_key)[:limit_docs]
|
| 210 |
+
|
| 211 |
+
fs = fsspec.core.url_to_fs(pattern)[0]
|
| 212 |
+
n_pages = 0
|
| 213 |
+
for d in doc_ids:
|
| 214 |
+
pages = sorted(docs[d], key=lambda p: natural_key(p[0]))
|
| 215 |
+
if d.lower().endswith(".pdf"): # explode a PDF into (page-index) entries
|
| 216 |
+
import fitz
|
| 217 |
+
|
| 218 |
+
with fs.open(pages[0][1], "rb") as f:
|
| 219 |
+
count = fitz.open(stream=f.read(), filetype="pdf").page_count
|
| 220 |
+
pages = [(f"{d}#{i + 1}", f"{pages[0][1]}#{i}") for i in range(count)]
|
| 221 |
+
for start in range(0, len(pages), pages_per_request):
|
| 222 |
+
if max_pages is not None and n_pages >= max_pages:
|
| 223 |
+
return
|
| 224 |
+
window = pages[start: start + pages_per_request]
|
| 225 |
+
if max_pages is not None:
|
| 226 |
+
window = window[: max_pages - n_pages]
|
| 227 |
+
n_pages += len(window)
|
| 228 |
+
# The id encodes the page range: a --max-pages-truncated window must
|
| 229 |
+
# not mark the full window done on a later resume.
|
| 230 |
+
yield f"{d}@{start:06d}-{start + len(window):06d}", {
|
| 231 |
+
"doc_id": d, "first_page": start,
|
| 232 |
+
"page_files": [rid for rid, _ in window],
|
| 233 |
+
"paths": [p for _, p in window],
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def load_page(fs, path: str, max_side: int, pdf_dpi: int) -> str:
|
| 238 |
+
"""Read one page (image file or `file.pdf#i`), downscale, return base64 JPEG."""
|
| 239 |
+
from PIL import Image
|
| 240 |
+
|
| 241 |
+
if "#" in path and path.split("#")[0].lower().endswith(".pdf"):
|
| 242 |
+
import fitz
|
| 243 |
+
|
| 244 |
+
pdf_path, idx = path.rsplit("#", 1)
|
| 245 |
+
with fs.open(pdf_path, "rb") as f:
|
| 246 |
+
data = f.read()
|
| 247 |
+
with PDF_LOCK: # PyMuPDF is not thread-safe; pages are prepared in threads
|
| 248 |
+
png = fitz.open(stream=data, filetype="pdf")[int(idx)].get_pixmap(dpi=pdf_dpi).tobytes("png")
|
| 249 |
+
img = Image.open(io.BytesIO(png))
|
| 250 |
+
else:
|
| 251 |
+
with fs.open(path, "rb") as f:
|
| 252 |
+
data = f.read()
|
| 253 |
+
img = Image.open(io.BytesIO(data))
|
| 254 |
+
if img.format == "JPEG2000":
|
| 255 |
+
# Decode straight at a lower wavelet level when the page stays >= max_side:
|
| 256 |
+
# same pixels the model would see after downscaling, ~2.5x less CPU
|
| 257 |
+
# (measured: 406 -> 160 ms/page at 8 threads on 1771 Britannica scans).
|
| 258 |
+
# Some codestreams fail at a reduced level ("broken data stream"), so step
|
| 259 |
+
# back towards a full decode until one works.
|
| 260 |
+
reduce = 0
|
| 261 |
+
while max(img.size) >> (reduce + 1) >= max_side:
|
| 262 |
+
reduce += 1
|
| 263 |
+
while True:
|
| 264 |
+
try:
|
| 265 |
+
img = Image.open(io.BytesIO(data))
|
| 266 |
+
img.reduce = reduce
|
| 267 |
+
img.load()
|
| 268 |
+
break
|
| 269 |
+
except OSError:
|
| 270 |
+
if reduce == 0:
|
| 271 |
+
raise
|
| 272 |
+
reduce -= 1
|
| 273 |
+
else:
|
| 274 |
+
img.load()
|
| 275 |
+
img = img.convert("RGB")
|
| 276 |
+
img.thumbnail((max_side, max_side), Image.LANCZOS)
|
| 277 |
+
buf = io.BytesIO()
|
| 278 |
+
img.save(buf, format="JPEG", quality=90)
|
| 279 |
+
return base64.b64encode(buf.getvalue()).decode()
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def clean_page(raw_page: str, keep_furniture: bool) -> tuple[str, bool]:
|
| 283 |
+
"""Grounded page -> (markdown, continues_previous_page).
|
| 284 |
+
|
| 285 |
+
Tags and boxes dropped, titles -> #, furniture dropped. A block preceded by
|
| 286 |
+
<MERGE> belongs to the block before it (joined with a newline, e.g. verse
|
| 287 |
+
lines); an `append_*` first block continues the previous page's last block.
|
| 288 |
+
"""
|
| 289 |
+
blocks: list[str] = []
|
| 290 |
+
continues = False
|
| 291 |
+
merge_next = False
|
| 292 |
+
matches = list(PAGE_BLOCK_RE.finditer(raw_page))
|
| 293 |
+
for i, m in enumerate(matches):
|
| 294 |
+
body = raw_page[m.end(): matches[i + 1].start() if i + 1 < len(matches) else len(raw_page)].strip()
|
| 295 |
+
merge_prev, merge_next = merge_next, body.endswith("<MERGE>")
|
| 296 |
+
body = body.removesuffix("<MERGE>").strip()
|
| 297 |
+
kind = m.group("type")
|
| 298 |
+
if not body or (kind in FURNITURE and not keep_furniture):
|
| 299 |
+
continue
|
| 300 |
+
if kind == "title" and m.group("level"):
|
| 301 |
+
body = "#" * int(m.group("level")) + " " + body
|
| 302 |
+
if not blocks and kind.startswith("append_"):
|
| 303 |
+
continues = True
|
| 304 |
+
if merge_prev and blocks:
|
| 305 |
+
blocks[-1] += "\n" + body
|
| 306 |
+
else:
|
| 307 |
+
blocks.append(body)
|
| 308 |
+
return "\n\n".join(blocks), continues
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def degenerate(raw_page: str) -> bool:
|
| 312 |
+
"""A looping page: far longer than any real page, or highly repetitive.
|
| 313 |
+
|
| 314 |
+
Thresholds from 1771 Britannica (median raw page ~6.5k chars, densest real
|
| 315 |
+
page ~10k; loops ran 14k-109k chars at zlib ratio 0.005-0.19, real text ~0.35).
|
| 316 |
+
"""
|
| 317 |
+
if len(raw_page) > 15000:
|
| 318 |
+
return True
|
| 319 |
+
return len(raw_page) > 2000 and len(zlib.compress(raw_page.encode())) / len(raw_page) < 0.2
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def repair_rows(windows, output: str):
|
| 323 |
+
"""Pages to re-OCR one at a time, from the windows and what the main pass wrote.
|
| 324 |
+
|
| 325 |
+
A window with no usable record (error row, or truncated / page_mismatch) has all
|
| 326 |
+
its pages repaired. In an ok window, a looping page is repaired together with
|
| 327 |
+
an empty neighbour: the loop's forced page break shifts the next page's text.
|
| 328 |
+
"""
|
| 329 |
+
from saturate import read_output
|
| 330 |
+
|
| 331 |
+
done = dict(read_output(output))
|
| 332 |
+
for wid, row in windows:
|
| 333 |
+
n = len(row["paths"])
|
| 334 |
+
rec = done.get(wid)
|
| 335 |
+
raw_pages = (rec or {}).get("raw", "").split("<PAGE>")[1:]
|
| 336 |
+
texts = (rec or {}).get("page_markdown") or []
|
| 337 |
+
# Anything we cannot line up page-for-page is repaired whole (also covers
|
| 338 |
+
# records written before the status column existed).
|
| 339 |
+
if rec is None or rec.get("status", "ok") != "ok" or len(raw_pages) != n or len(texts) != n:
|
| 340 |
+
bad = set(range(n))
|
| 341 |
+
else:
|
| 342 |
+
bad = {i for i, p in enumerate(raw_pages) if degenerate(p)}
|
| 343 |
+
for i in list(bad):
|
| 344 |
+
bad |= {j for j in (i - 1, i + 1) if 0 <= j < n and not (texts[j] or "").strip()}
|
| 345 |
+
for i in sorted(bad):
|
| 346 |
+
yield row["page_files"][i], {
|
| 347 |
+
"doc_id": row["doc_id"], "page": row["first_page"] + i, "window": wid,
|
| 348 |
+
"page_file": row["page_files"][i], "paths": [row["paths"][i]],
|
| 349 |
+
# alone and tiled: fixed 8 of 10 looping 1771 pages in testing
|
| 350 |
+
"crop": True, "max_side": 2048,
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def find_server_python(candidates) -> str:
|
| 355 |
+
"""The image's Python (the one that has sglang), not this script's uv venv.
|
| 356 |
+
|
| 357 |
+
The SGLang image keeps sglang in its own venv (/opt/sglang/bin), first on PATH;
|
| 358 |
+
`uv run` puts this script's venv in front, so search PATH without it.
|
| 359 |
+
"""
|
| 360 |
+
own_bin = os.path.join(sys.prefix, "bin")
|
| 361 |
+
path = os.pathsep.join(p for p in os.environ.get("PATH", "").split(os.pathsep)
|
| 362 |
+
if os.path.realpath(p) != os.path.realpath(own_bin))
|
| 363 |
+
on_path = [shutil.which(name, path=path) for name in ("python3", "python")]
|
| 364 |
+
for py in [p for p in on_path if p] + list(candidates):
|
| 365 |
+
if os.path.exists(py) and subprocess.run(
|
| 366 |
+
[py, "-c", "import sglang"], check=False, capture_output=True
|
| 367 |
+
).returncode == 0:
|
| 368 |
+
return py
|
| 369 |
+
sys.exit(
|
| 370 |
+
"No Python with sglang found. Run on the SGLang image, e.g.\n"
|
| 371 |
+
f" hf jobs uv run --image {SERVING['image']} --flavor a100-large -s HF_TOKEN ...\n"
|
| 372 |
+
"(the script's [tool.hf-jobs] table sets this when launched with `hf jobs uv run`)."
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def main():
|
| 377 |
+
ap = argparse.ArgumentParser(description="Unlimited-OCR-2 document OCR via saturate")
|
| 378 |
+
ap.add_argument("input", help="Folder/glob of page images or PDFs: hf://buckets/..., a mounted dir, ...")
|
| 379 |
+
ap.add_argument("output", help="Output dataset id (org/name) or fsspec URI (hf://buckets/...)")
|
| 380 |
+
ap.add_argument("--pages-per-request", type=int, default=16,
|
| 381 |
+
help="Window size: consecutive pages sent in one request (default 16). "
|
| 382 |
+
"Each request decodes as one serial stream, so smaller windows finish "
|
| 383 |
+
"sooner and leave throughput to concurrency; the server itself works "
|
| 384 |
+
"in 10-page chunks with KV reuse across them.")
|
| 385 |
+
ap.add_argument("--limit-docs", type=int, default=None, help="Only the first N documents")
|
| 386 |
+
ap.add_argument("--max-pages", type=int, default=None, help="Stop after N pages in total (smoke tests)")
|
| 387 |
+
ap.add_argument("--crop-mode", action="store_true",
|
| 388 |
+
help="Gundam mode: tile each page (more image tokens; for small print)")
|
| 389 |
+
ap.add_argument("--max-side", type=int, default=None,
|
| 390 |
+
help="Long side (px) pages are sent at. Default 1280 in base mode (the model "
|
| 391 |
+
"resizes every page to one 1024 px view, so more pixels are discarded) and "
|
| 392 |
+
"2048 with --crop-mode (tiles use the detail)")
|
| 393 |
+
ap.add_argument("--pdf-dpi", type=int, default=150)
|
| 394 |
+
ap.add_argument("--keep-furniture", action="store_true",
|
| 395 |
+
help="Keep page numbers, running heads and footers in `markdown`")
|
| 396 |
+
ap.add_argument("--ngram-window", type=int, default=1024,
|
| 397 |
+
help="Look-back (tokens) of the card's no-repeat n-gram guard for multi-page "
|
| 398 |
+
"windows (single pages use 128). It runs in Python on every decode step "
|
| 399 |
+
"for every request, so it bounds throughput; 0 disables the guard "
|
| 400 |
+
"(and its per-page length cap)")
|
| 401 |
+
ap.add_argument("--retry-errors", action="store_true", help="Re-admit windows recorded as errors")
|
| 402 |
+
ap.add_argument("--no-repair", action="store_true",
|
| 403 |
+
help="Skip the repair pass (re-OCR of looping pages one at a time, in gundam mode)")
|
| 404 |
+
ap.add_argument("--repair-only", action="store_true",
|
| 405 |
+
help="Run only the repair pass over an existing output (same input/output args)")
|
| 406 |
+
ap.add_argument("--prepare-workers", type=int, default=8,
|
| 407 |
+
help="Threads decoding/encoding pages ahead of the engine")
|
| 408 |
+
ap.add_argument("--dp-size", type=int, default=1,
|
| 409 |
+
help="SGLang data-parallel replicas (one per GPU on multi-GPU flavors). The n-gram "
|
| 410 |
+
"guard makes each scheduler CPU-bound, so replicas multiply throughput")
|
| 411 |
+
ap.add_argument("--endpoint", default=None,
|
| 412 |
+
help="Use a running server (e.g. a Jobs --expose URL + /v1) instead of booting one")
|
| 413 |
+
ap.add_argument("--server-python", nargs="+", default=["/opt/sglang/bin/python3", "/usr/bin/python3"],
|
| 414 |
+
help="Fallback Pythons to try after PATH (the one with sglang wins)")
|
| 415 |
+
args = ap.parse_args()
|
| 416 |
+
if args.max_side is None:
|
| 417 |
+
# Payload matters as much as pixels: 32 concurrent 16-page bodies at 1600 px
|
| 418 |
+
# (~14 MB of base64 each) stalled SGLang's HTTP front end past saturate's fixed
|
| 419 |
+
# 30 s connect/write timeouts.
|
| 420 |
+
args.max_side = 2048 if args.crop_mode else 1280
|
| 421 |
+
|
| 422 |
+
import fsspec
|
| 423 |
+
from saturate import Auto, Engine, pump
|
| 424 |
+
|
| 425 |
+
rows = list(list_windows(args.input, args.pages_per_request, args.limit_docs,
|
| 426 |
+
args.max_pages, args.pdf_dpi))
|
| 427 |
+
n_pages = sum(len(r["paths"]) for _, r in rows)
|
| 428 |
+
print(f"{len({r['doc_id'] for _, r in rows})} documents, {n_pages} pages, "
|
| 429 |
+
f"{len(rows)} windows of <= {args.pages_per_request} pages", file=sys.stderr)
|
| 430 |
+
fs = fsspec.core.url_to_fs(args.input.split("*")[0] or ".")[0]
|
| 431 |
+
processor = ngram_processor()
|
| 432 |
+
|
| 433 |
+
def to_request(row):
|
| 434 |
+
max_side = row.get("max_side", args.max_side)
|
| 435 |
+
images = [load_page(fs, p, max_side, args.pdf_dpi) for p in row["paths"]]
|
| 436 |
+
n = len(images)
|
| 437 |
+
content = [{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b}"}}
|
| 438 |
+
for b in images]
|
| 439 |
+
content.append({"type": "text", "text": "<PAGE><image>" * n + "Multi page parsing."})
|
| 440 |
+
body = {
|
| 441 |
+
"model": SERVING["served_name"],
|
| 442 |
+
"messages": [{"role": "user", "content": content}],
|
| 443 |
+
"max_tokens": SERVING["tokens_per_page"] * n, # global budget for the window
|
| 444 |
+
"temperature": SERVING["temperature"],
|
| 445 |
+
"skip_special_tokens": False, # <PAGE>/<BLOCK> markers are the structure
|
| 446 |
+
"images_config": {"crop_mode": row.get("crop", args.crop_mode or SERVING["crop_mode"])},
|
| 447 |
+
}
|
| 448 |
+
if args.ngram_window > 0:
|
| 449 |
+
body["custom_logit_processor"] = processor
|
| 450 |
+
body["custom_params"] = {
|
| 451 |
+
"ngram_size": SERVING["ngram_size"],
|
| 452 |
+
"window_size": args.ngram_window if n > 1 else 128,
|
| 453 |
+
"page_token_id": SERVING["page_token_id"],
|
| 454 |
+
"eos_token_id": SERVING["eos_token_id"],
|
| 455 |
+
"max_page_tokens": SERVING["max_page_tokens"],
|
| 456 |
+
}
|
| 457 |
+
return body
|
| 458 |
+
|
| 459 |
+
def parse(row, body):
|
| 460 |
+
raw = body["choices"][0]["message"]["content"]
|
| 461 |
+
raw_pages = raw.split("<PAGE>")[1:] if "<PAGE>" in raw else [raw]
|
| 462 |
+
finish = body["choices"][0].get("finish_reason")
|
| 463 |
+
# Decoding is greedy, so a truncated or page-misaligned window comes back the same
|
| 464 |
+
# on retry: keep its text and flag it (`status`) instead of an error row.
|
| 465 |
+
# Only transport failures become error rows (--retry-errors).
|
| 466 |
+
if finish == "length":
|
| 467 |
+
status = "truncated"
|
| 468 |
+
elif len(raw_pages) != len(row["paths"]):
|
| 469 |
+
status = "page_mismatch"
|
| 470 |
+
else:
|
| 471 |
+
status = "ok"
|
| 472 |
+
cleaned = [clean_page(p, args.keep_furniture) for p in raw_pages]
|
| 473 |
+
pages = [text for text, _ in cleaned]
|
| 474 |
+
usage = body.get("usage") or {}
|
| 475 |
+
return {
|
| 476 |
+
"doc_id": row["doc_id"],
|
| 477 |
+
"first_page": row["first_page"],
|
| 478 |
+
"page_files": row["page_files"],
|
| 479 |
+
"num_pages": len(row["paths"]),
|
| 480 |
+
"status": status,
|
| 481 |
+
"finish_reason": finish,
|
| 482 |
+
# aligned with page_files only when status == "ok"
|
| 483 |
+
"page_markdown": pages if status == "ok" else None,
|
| 484 |
+
"markdown": convert(raw),
|
| 485 |
+
"raw": raw,
|
| 486 |
+
"model": SERVING["model"],
|
| 487 |
+
"prompt_tokens": usage.get("prompt_tokens"),
|
| 488 |
+
"completion_tokens": usage.get("completion_tokens"),
|
| 489 |
+
}
|
| 490 |
+
|
| 491 |
+
def parse_repair(row, body):
|
| 492 |
+
raw = body["choices"][0]["message"]["content"]
|
| 493 |
+
finish = body["choices"][0].get("finish_reason")
|
| 494 |
+
pages = raw.split("<PAGE>")[1:]
|
| 495 |
+
page_raw = pages[0] if pages else raw
|
| 496 |
+
if len(pages) != 1:
|
| 497 |
+
status = "page_mismatch" # never substitute a malformed reading for the page
|
| 498 |
+
elif finish == "length" or degenerate(page_raw):
|
| 499 |
+
status = "degenerate" # still looping alone: keep the text, flagged
|
| 500 |
+
else:
|
| 501 |
+
status = "ok"
|
| 502 |
+
usage = body.get("usage") or {}
|
| 503 |
+
return {
|
| 504 |
+
"doc_id": row["doc_id"],
|
| 505 |
+
"page": row["page"],
|
| 506 |
+
"page_file": row["page_file"],
|
| 507 |
+
"window": row["window"],
|
| 508 |
+
"status": status,
|
| 509 |
+
"finish_reason": finish,
|
| 510 |
+
"markdown": clean_page(page_raw, args.keep_furniture)[0],
|
| 511 |
+
"raw": raw,
|
| 512 |
+
"mode": "gundam",
|
| 513 |
+
"model": SERVING["model"],
|
| 514 |
+
"completion_tokens": usage.get("completion_tokens"),
|
| 515 |
+
}
|
| 516 |
+
|
| 517 |
+
is_repo_id = re.fullmatch(r"[\w-][\w.-]*/[\w.-]*[\w-]", args.output) and not os.path.exists(args.output)
|
| 518 |
+
output = f"hf://datasets/{args.output}/data" if is_repo_id else args.output
|
| 519 |
+
# Sibling of data/, or a subfolder of the output (saturate only reads <root>/part-*.parquet,
|
| 520 |
+
# so it never mixes the two); never a path outside the output repo or bucket.
|
| 521 |
+
repairs_out = re.sub(r"/data/?$", "/repairs", output) if re.search(r"/data/?$", output) \
|
| 522 |
+
else output.rstrip("/") + "/repairs"
|
| 523 |
+
# One window is minutes of decode, and Auto widens only on completed-request
|
| 524 |
+
# evidence, so it ramps slowly from a small start. Start near the measured
|
| 525 |
+
# headroom (a100-large: 8 x 32-page windows used ~25% of KV) and flush often,
|
| 526 |
+
# since each row is expensive to redo.
|
| 527 |
+
window = Auto(initial=32, max_limit=64)
|
| 528 |
+
# saturate caps a row's retries at RETRY_BUDGET_S (300 s, counted from the first
|
| 529 |
+
# attempt), which is shorter than one legitimate multi-page generation here, so a
|
| 530 |
+
# transient first-attempt failure always ended in a TimeoutError row. Match the
|
| 531 |
+
# read timeout until saturate exposes this as a pump() argument.
|
| 532 |
+
import saturate.transport
|
| 533 |
+
|
| 534 |
+
saturate.transport.RETRY_BUDGET_S = 3600.0
|
| 535 |
+
|
| 536 |
+
def run_passes(endpoint, headers=None):
|
| 537 |
+
common = {"retry_errors": args.retry_errors, "headers": headers,
|
| 538 |
+
"prepare_workers": args.prepare_workers, "read_timeout": 3600}
|
| 539 |
+
if not args.repair_only:
|
| 540 |
+
stats = pump(rows, to_request, parse, endpoint, output, window=window, flush_every=4, **common)
|
| 541 |
+
print(f"{output} ({stats.rows_processed} ok, {stats.rows_failed} error rows)", file=sys.stderr)
|
| 542 |
+
print("UNLIMITED_OCR2_SATURATE " + stats.to_json(), flush=True)
|
| 543 |
+
if args.no_repair:
|
| 544 |
+
return
|
| 545 |
+
targets = list(repair_rows(rows, output))
|
| 546 |
+
print(f"repair pass: {len(targets)} pages to re-OCR alone (gundam) -> {repairs_out}", file=sys.stderr)
|
| 547 |
+
if targets:
|
| 548 |
+
rstats = pump(targets, to_request, parse_repair, endpoint, repairs_out,
|
| 549 |
+
window=Auto(initial=32, max_limit=64), flush_every=16, **common)
|
| 550 |
+
print("UNLIMITED_OCR2_REPAIR " + rstats.to_json(), flush=True)
|
| 551 |
+
|
| 552 |
+
if args.endpoint:
|
| 553 |
+
run_passes(args.endpoint, {"Authorization": f"Bearer {os.environ['HF_TOKEN']}"}
|
| 554 |
+
if os.environ.get("HF_TOKEN") else None)
|
| 555 |
+
else:
|
| 556 |
+
py = find_server_python(args.server_python)
|
| 557 |
+
print(f"server python: {py}", file=sys.stderr)
|
| 558 |
+
# The image's venv may have no pip (uv-built); uv is always present under `uv run`.
|
| 559 |
+
has_pip = subprocess.run([py, "-m", "pip", "--version"], check=False,
|
| 560 |
+
capture_output=True).returncode == 0
|
| 561 |
+
pip = [py, "-m", "pip", "install", "-q"] if has_pip else ["uv", "pip", "install", "-q", "--python", py]
|
| 562 |
+
pip_env = {**os.environ, "PIP_BREAK_SYSTEM_PACKAGES": "1"}
|
| 563 |
+
pip_env.pop("VIRTUAL_ENV", None) # never install into this script's venv
|
| 564 |
+
subprocess.run([*pip, "--no-deps", SERVING["wheel"]], check=True, env=pip_env)
|
| 565 |
+
subprocess.run([*pip, *SERVING["extra_pip"]], check=True, env=pip_env)
|
| 566 |
+
os.environ.update(SERVING["env"]) # inherited by the server process
|
| 567 |
+
cmd = [py, "-m", "sglang.launch_server", "--model-path", SERVING["model"],
|
| 568 |
+
"--served-model-name", SERVING["served_name"], *SERVING["serve_args"],
|
| 569 |
+
"--enable-metrics", "--host", "127.0.0.1", "--port", "8000"]
|
| 570 |
+
if args.dp_size > 1:
|
| 571 |
+
cmd += ["--dp-size", str(args.dp_size)]
|
| 572 |
+
with Engine(SERVING["model"], engine="sglang", cmd=cmd) as endpoint:
|
| 573 |
+
run_passes(endpoint)
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
# ---------------------------------------------------------------------------
|
| 577 |
+
# Vendored verbatim from Baidu's Unlimited-OCR repo (MIT License, Copyright (c) 2026 Baidu):
|
| 578 |
+
# https://github.com/baidu/Unlimited-OCR/blob/0cdd7877868bd0e17715d742911b9ce937c53d3f/utils/process_unlimitedOCR2.py
|
| 579 |
+
# Lines 30-353 (constants, helpers, convert()); only the file's CLI main() is left out.
|
| 580 |
+
# To update: re-copy those lines from a newer commit and bump the hash above.
|
| 581 |
+
# Kept byte-for-byte, so its two style-rule hits are waived file-wide:
|
| 582 |
+
# ruff: noqa: FURB167, SIM114
|
| 583 |
+
# ---------------------------------------------------------------------------
|
| 584 |
+
|
| 585 |
+
# ── block / token patterns ───────────────────────────────────────────────────
|
| 586 |
+
PAGE_SPLIT_RE = re.compile(r'<\s*/?\s*PAGE\s*\d*\s*>', re.I)
|
| 587 |
+
MERGE_RE = re.compile(r'<\s*/?\s*MERGE\s*>', re.I)
|
| 588 |
+
STRAY_TOKEN_RE = re.compile(
|
| 589 |
+
r'<[||]/?[a-zA-Z_]+[||]>|<image>'
|
| 590 |
+
r'|<\s*/?\s*PAGE\s*\d*\s*>|<\s*/?\s*BLOCK\s*>|<\s*/?\s*FORK\s*>'
|
| 591 |
+
r'|<\s*/?\s*LEVEL\s*\d*\s*[>}]?|<\s*/?\s*MERGE\s*>', re.I)
|
| 592 |
+
# <BLOCK>label [<LEVELn>|[bbox]] [<LEVELn>|[bbox]] [<FORK>] ; LEVEL-first or bbox-first.
|
| 593 |
+
BLOCK_RE = re.compile(
|
| 594 |
+
r'<\s*BLOCK\s*>\s*([a-zA-Z_]+)'
|
| 595 |
+
r'(?:'
|
| 596 |
+
r'\s*<\s*/?\s*LEVEL\s*(\d*)\s*[>}]?(?:\s*\[\s*(-?\d+)\s*[,,]\s*(-?\d+)\s*[,,]\s*(-?\d+)\s*[,,]\s*(-?\d+)'
|
| 597 |
+
r'(?:\s*[,,]\s*-?\d+)*\s*\])?'
|
| 598 |
+
r'|'
|
| 599 |
+
r'\s*\[\s*(-?\d+)\s*[,,]\s*(-?\d+)\s*[,,]\s*(-?\d+)\s*[,,]\s*(-?\d+)'
|
| 600 |
+
r'(?:\s*[,,]\s*-?\d+)*\s*\](?:\s*<\s*/?\s*LEVEL\s*(\d*)\s*[>}]?)?'
|
| 601 |
+
r')?'
|
| 602 |
+
r'\s*(?:<\s*FORK\s*>)?', re.I)
|
| 603 |
+
TR_RE = re.compile(r'<tr\b[^>]*>.*?</tr>', re.I | re.S)
|
| 604 |
+
TABLE_OPEN_RE = re.compile(r'<table\b[^>]*>', re.I)
|
| 605 |
+
SPAN_ATTR_RE = re.compile(r'\b(colspan|rowspan)\s*=\s*"([^"]*)"', re.I)
|
| 606 |
+
|
| 607 |
+
DROP_LABELS = set() # header/footer/page_number kept (canonical default)
|
| 608 |
+
IMAGE_LABELS = {'image', 'figure', 'picture', 'chart', 'img', 'seal'}
|
| 609 |
+
NOISE_CONTENT = {'[non-text]', '[unreadable]', '[image]', '[figure]'}
|
| 610 |
+
CHAIN_TYPES = {'text', 'table'}
|
| 611 |
+
MAX_HEADER_ROWS = 5
|
| 612 |
+
|
| 613 |
+
_BASE_LABELS = {
|
| 614 |
+
'text', 'title', 'header', 'footer', 'page_number', 'image', 'figure',
|
| 615 |
+
'chart', 'seal', 'table', 'image_caption', 'image_footnote',
|
| 616 |
+
'page_footnote', 'equation', 'ref_text', 'aside_text', 'algorithm',
|
| 617 |
+
}
|
| 618 |
+
_BARE_LABELS = _BASE_LABELS | {
|
| 619 |
+
f'{p}{l}' for p in ('cross_', 'append_') for l in _BASE_LABELS}
|
| 620 |
+
BARE_BLOCK_RE = re.compile(
|
| 621 |
+
r'(?:(?<=<FORK>)|(?<=<PAGE>)|(?<=\n)|^)'
|
| 622 |
+
r'(?:<[||]\s*det\s*[||]>)?'
|
| 623 |
+
r'((?:[a-zA-Z_][a-zA-Z_0-9]*)(?:\s*<\s*/?\s*LEVEL\s*\d*\s*[>}]?)?\s*'
|
| 624 |
+
r'\[\s*-?\d+(?:\s*[,,]\s*-?\d+){3,}[^\]]*\])', re.I)
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
def _scale(v):
|
| 628 |
+
return max(0, min(1000, int(v)))
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
def _fix_span_attrs(text):
|
| 632 |
+
def repl(m):
|
| 633 |
+
name, val = m.group(1), m.group(2)
|
| 634 |
+
try:
|
| 635 |
+
int(val)
|
| 636 |
+
return m.group(0)
|
| 637 |
+
except ValueError:
|
| 638 |
+
num = re.search(r'\d+', val)
|
| 639 |
+
return f'{name}="{num.group() if num else 1}"'
|
| 640 |
+
return SPAN_ATTR_RE.sub(repl, text)
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
def _fix_bare_blocks(text):
|
| 644 |
+
"""Add the missing <BLOCK> prefix to bare block declarations (known labels only)."""
|
| 645 |
+
def _repl(m):
|
| 646 |
+
label = re.match(r'[a-zA-Z_][a-zA-Z_0-9]*', m.group(1)).group(0)
|
| 647 |
+
if label.lower() not in _BARE_LABELS:
|
| 648 |
+
return m.group(0)
|
| 649 |
+
return f'<BLOCK>{m.group(1)}'
|
| 650 |
+
text = BARE_BLOCK_RE.sub(_repl, text)
|
| 651 |
+
return re.sub(r'\n\s*<FORK>\s*(?=<BLOCK>)', '\n', text, flags=re.I)
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
def _base_type(label):
|
| 655 |
+
"""cross_text/append_text -> text; append_table/cross_table -> table."""
|
| 656 |
+
for p in ('append_', 'cross_'):
|
| 657 |
+
if label.startswith(p):
|
| 658 |
+
return label[len(p):]
|
| 659 |
+
return label
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
def _parse_blocks(text, page_base=1):
|
| 663 |
+
"""Split on <PAGE>; return blocks [{label,bbox,level,content,page,merge_prev}]."""
|
| 664 |
+
text = _fix_bare_blocks(text)
|
| 665 |
+
segments = PAGE_SPLIT_RE.split(text)
|
| 666 |
+
if segments and not segments[0].strip():
|
| 667 |
+
segments = segments[1:]
|
| 668 |
+
blocks = []
|
| 669 |
+
for i, seg in enumerate(segments):
|
| 670 |
+
page_no = page_base + i
|
| 671 |
+
if not seg.strip():
|
| 672 |
+
continue
|
| 673 |
+
matches = list(BLOCK_RE.finditer(seg))
|
| 674 |
+
if not matches:
|
| 675 |
+
blocks.append({'label': '__raw__', 'bbox': None, 'level': None,
|
| 676 |
+
'content': MERGE_RE.sub('', seg).strip(),
|
| 677 |
+
'page': page_no, 'merge_prev': False})
|
| 678 |
+
continue
|
| 679 |
+
for j, m in enumerate(matches):
|
| 680 |
+
gap = seg[:m.start()] if j == 0 else seg[matches[j - 1].end():m.start()]
|
| 681 |
+
merge_prev = bool(MERGE_RE.search(gap))
|
| 682 |
+
if j == 0:
|
| 683 |
+
pre = STRAY_TOKEN_RE.sub('', MERGE_RE.sub('', gap)).strip()
|
| 684 |
+
if pre:
|
| 685 |
+
blocks.append({'label': '__raw__', 'bbox': None, 'level': None,
|
| 686 |
+
'content': pre, 'page': page_no, 'merge_prev': False})
|
| 687 |
+
end = matches[j + 1].start() if j + 1 < len(matches) else len(seg)
|
| 688 |
+
content = MERGE_RE.sub('', seg[m.end():end]).strip()
|
| 689 |
+
if m.group(2) is not None: # LEVEL-first
|
| 690 |
+
level = int(m.group(2)) if m.group(2) else None
|
| 691 |
+
bbox = (tuple(int(m.group(k)) for k in range(3, 7))
|
| 692 |
+
if m.group(3) is not None else None)
|
| 693 |
+
else: # bbox-first (or none)
|
| 694 |
+
bbox = (tuple(int(m.group(k)) for k in range(7, 11))
|
| 695 |
+
if m.group(7) is not None else None)
|
| 696 |
+
level = int(m.group(11)) if m.group(11) else None
|
| 697 |
+
blocks.append({'label': m.group(1).lower(), 'bbox': bbox, 'level': level,
|
| 698 |
+
'content': content, 'page': page_no, 'merge_prev': merge_prev})
|
| 699 |
+
return blocks
|
| 700 |
+
|
| 701 |
+
def _merge_adjacent_titles(blocks):
|
| 702 |
+
"""Merge strictly-adjacent, same-page, same-<LEVELn> title blocks into one."""
|
| 703 |
+
if not blocks:
|
| 704 |
+
return blocks
|
| 705 |
+
out = [blocks[0]]
|
| 706 |
+
for blk in blocks[1:]:
|
| 707 |
+
prev = out[-1]
|
| 708 |
+
if (blk['label'] == 'title' and prev['label'] == 'title'
|
| 709 |
+
and blk['page'] == prev['page']
|
| 710 |
+
and blk['level'] is not None and prev['level'] is not None
|
| 711 |
+
and blk['level'] == prev['level']):
|
| 712 |
+
prev['content'] = '\n'.join(x for x in (prev['content'], blk['content']) if x)
|
| 713 |
+
continue
|
| 714 |
+
out.append(blk)
|
| 715 |
+
return out
|
| 716 |
+
|
| 717 |
+
|
| 718 |
+
def _build_groups(blocks):
|
| 719 |
+
"""Union-find grouping of append/cross chains and same-page <MERGE> columns."""
|
| 720 |
+
n = len(blocks)
|
| 721 |
+
parent = list(range(n))
|
| 722 |
+
|
| 723 |
+
def find(x):
|
| 724 |
+
while parent[x] != x:
|
| 725 |
+
parent[x] = parent[parent[x]]
|
| 726 |
+
x = parent[x]
|
| 727 |
+
return x
|
| 728 |
+
|
| 729 |
+
def union(a, b):
|
| 730 |
+
ra, rb = find(a), find(b)
|
| 731 |
+
if ra != rb:
|
| 732 |
+
parent[max(ra, rb)] = min(ra, rb)
|
| 733 |
+
|
| 734 |
+
pages_with = {}
|
| 735 |
+
for blk in blocks:
|
| 736 |
+
b = _base_type(blk['label'])
|
| 737 |
+
if blk['label'] != '__raw__' and b in CHAIN_TYPES:
|
| 738 |
+
pages_with.setdefault(b, set()).add(blk['page'])
|
| 739 |
+
|
| 740 |
+
def _table_adjacent(tail_page, cur_page):
|
| 741 |
+
if cur_page - tail_page <= 1:
|
| 742 |
+
return True
|
| 743 |
+
return all(p not in pages_with.get('table', ())
|
| 744 |
+
for p in range(tail_page + 1, cur_page))
|
| 745 |
+
|
| 746 |
+
open_chain = {} # base type -> current chain-tail index
|
| 747 |
+
for i, blk in enumerate(blocks):
|
| 748 |
+
label, base = blk['label'], _base_type(blk['label'])
|
| 749 |
+
if label == '__raw__' or base not in CHAIN_TYPES:
|
| 750 |
+
continue
|
| 751 |
+
if label.startswith('append_'):
|
| 752 |
+
tail = open_chain.get(base)
|
| 753 |
+
if tail is None:
|
| 754 |
+
continue
|
| 755 |
+
if base == 'table' and not _table_adjacent(blocks[tail]['page'], blk['page']):
|
| 756 |
+
open_chain.pop(base, None)
|
| 757 |
+
continue
|
| 758 |
+
union(tail, i)
|
| 759 |
+
open_chain[base] = i
|
| 760 |
+
elif label.startswith('cross_'):
|
| 761 |
+
open_chain[base] = i
|
| 762 |
+
elif base == 'table':
|
| 763 |
+
open_chain[base] = i
|
| 764 |
+
|
| 765 |
+
for i, blk in enumerate(blocks): # same-page <MERGE> column edges
|
| 766 |
+
if not blk.get('merge_prev') or i == 0:
|
| 767 |
+
continue
|
| 768 |
+
pblk = blocks[i - 1]
|
| 769 |
+
if pblk['page'] != blk['page']:
|
| 770 |
+
continue
|
| 771 |
+
if (blk['label'] == 'title' or _base_type(blk['label']) == 'text') \
|
| 772 |
+
and (pblk['label'] == 'title' or _base_type(pblk['label']) == 'text'):
|
| 773 |
+
union(i - 1, i)
|
| 774 |
+
|
| 775 |
+
groups = {}
|
| 776 |
+
for i in range(n):
|
| 777 |
+
groups.setdefault(find(i), []).append(i)
|
| 778 |
+
return [groups[r] for r in sorted(groups, key=lambda r: groups[r][0])]
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
def _row_key(tr_html):
|
| 782 |
+
txt = re.sub(r'<[^>]+>', ' ', tr_html)
|
| 783 |
+
txt = ''.join(chr(ord(c) - 0xFEE0) if 0xFF01 <= ord(c) <= 0xFF5E else c for c in txt)
|
| 784 |
+
ncells = len(re.findall(r'<t[hd]\b', tr_html, re.I))
|
| 785 |
+
return (ncells, ''.join(txt.split()).lower())
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
def _merge_table_fragments(frags):
|
| 789 |
+
"""Merge cross-page table fragments, skipping repeated leading header rows."""
|
| 790 |
+
frags = [f for f in frags if f and f.strip()]
|
| 791 |
+
if len(frags) <= 1:
|
| 792 |
+
return frags[0] if frags else ''
|
| 793 |
+
base_rows = TR_RE.findall(frags[0])
|
| 794 |
+
if not base_rows:
|
| 795 |
+
return '\n\n'.join(frags)
|
| 796 |
+
out_rows, base_keys, extra = list(base_rows), [_row_key(r) for r in base_rows], []
|
| 797 |
+
for frag in frags[1:]:
|
| 798 |
+
rows = TR_RE.findall(frag)
|
| 799 |
+
if not rows:
|
| 800 |
+
extra.append(frag.strip())
|
| 801 |
+
continue
|
| 802 |
+
skip = 0
|
| 803 |
+
for r in rows[:MAX_HEADER_ROWS]:
|
| 804 |
+
if skip < len(base_keys) and _row_key(r) == base_keys[skip]:
|
| 805 |
+
skip += 1
|
| 806 |
+
else:
|
| 807 |
+
break
|
| 808 |
+
out_rows.extend(rows[skip:])
|
| 809 |
+
m = TABLE_OPEN_RE.search(frags[0])
|
| 810 |
+
merged = (m.group(0) if m else '<table>') + ''.join(out_rows) + '</table>'
|
| 811 |
+
return merged + ('\n\n' + '\n\n'.join(extra) if extra else '')
|
| 812 |
+
|
| 813 |
+
def _render_blocks(blocks, groups):
|
| 814 |
+
"""Render each group to a Markdown item (figure/table/heading/text)."""
|
| 815 |
+
items = []
|
| 816 |
+
for members in groups:
|
| 817 |
+
head = blocks[members[0]]
|
| 818 |
+
base = head['label'] if head['label'] == '__raw__' else _base_type(head['label'])
|
| 819 |
+
contents = [blocks[k]['content'] for k in members
|
| 820 |
+
if blocks[k]['content'] and blocks[k]['content'].lower() not in NOISE_CONTENT]
|
| 821 |
+
if base == '__raw__':
|
| 822 |
+
if contents:
|
| 823 |
+
items.append(contents[0])
|
| 824 |
+
continue
|
| 825 |
+
if base in IMAGE_LABELS:
|
| 826 |
+
if head['bbox'] is not None:
|
| 827 |
+
x1, y1, x2, y2 = (_scale(v) for v in head['bbox'])
|
| 828 |
+
items.append(f'')
|
| 829 |
+
if contents:
|
| 830 |
+
items.append(contents[0])
|
| 831 |
+
continue
|
| 832 |
+
if not contents or base in DROP_LABELS:
|
| 833 |
+
continue
|
| 834 |
+
if base == 'title':
|
| 835 |
+
lv = max(1, head['level'] or 1)
|
| 836 |
+
joined = ''.join(contents)
|
| 837 |
+
if not STRAY_TOKEN_RE.sub('', joined).strip():
|
| 838 |
+
continue
|
| 839 |
+
items.append(f'{"#" * lv} {joined}')
|
| 840 |
+
continue
|
| 841 |
+
if base == 'table':
|
| 842 |
+
items.append(_merge_table_fragments(contents) if len(contents) > 1 else contents[0])
|
| 843 |
+
continue
|
| 844 |
+
items.append(''.join(contents)) # text family: concatenate, no separator
|
| 845 |
+
return items
|
| 846 |
+
|
| 847 |
+
|
| 848 |
+
def _head_level(item):
|
| 849 |
+
s = item.lstrip()
|
| 850 |
+
return len(s) - len(s.lstrip('#'))
|
| 851 |
+
|
| 852 |
+
|
| 853 |
+
def _single_root_titles(items):
|
| 854 |
+
"""Collapse multiple top-level headings under the first one (single root)."""
|
| 855 |
+
idxs = [i for i, it in enumerate(items) if it.lstrip().startswith('#')]
|
| 856 |
+
if len(idxs) <= 1:
|
| 857 |
+
return items
|
| 858 |
+
levels = [_head_level(items[i]) for i in idxs]
|
| 859 |
+
min_lv = min(levels)
|
| 860 |
+
if sum(1 for lv in levels if lv == min_lv) <= 1:
|
| 861 |
+
return items
|
| 862 |
+
first_lv, out = levels[0], list(items)
|
| 863 |
+
for k, i in enumerate(idxs):
|
| 864 |
+
body = items[i].lstrip()[levels[k]:].lstrip(' ')
|
| 865 |
+
new_lv = 1 if k == 0 else max(2, levels[k] - first_lv + 2)
|
| 866 |
+
out[i] = '#' * new_lv + ' ' + body
|
| 867 |
+
return out
|
| 868 |
+
|
| 869 |
+
|
| 870 |
+
def _fold_head_ws(items):
|
| 871 |
+
out = []
|
| 872 |
+
for it in items:
|
| 873 |
+
s = it.lstrip()
|
| 874 |
+
if s.startswith('#'):
|
| 875 |
+
n = len(s) - len(s.lstrip('#'))
|
| 876 |
+
it = '#' * n + ' ' + re.sub(r'\s+', ' ', s[n:]).strip()
|
| 877 |
+
out.append(it)
|
| 878 |
+
return out
|
| 879 |
+
|
| 880 |
+
|
| 881 |
+
def _drop_empty_heads(items):
|
| 882 |
+
return [it for it in items
|
| 883 |
+
if not (it.lstrip().startswith('#') and not it.lstrip().lstrip('#').strip())]
|
| 884 |
+
|
| 885 |
+
|
| 886 |
+
def convert(result):
|
| 887 |
+
"""Unlimited-OCR 2 raw document string -> MarathonDocBench evaluation Markdown."""
|
| 888 |
+
text = (result or '').strip()
|
| 889 |
+
if text.startswith('```markdown'):
|
| 890 |
+
text = text[len('```markdown'):].strip()
|
| 891 |
+
if text.endswith('```'):
|
| 892 |
+
text = text[:-3].strip()
|
| 893 |
+
|
| 894 |
+
blocks = _parse_blocks(text, page_base=1)
|
| 895 |
+
blocks = _merge_adjacent_titles(blocks)
|
| 896 |
+
groups = _build_groups(blocks)
|
| 897 |
+
items = _drop_empty_heads(_render_blocks(blocks, groups))
|
| 898 |
+
items = _fold_head_ws(items)
|
| 899 |
+
text = '\n\n'.join(items)
|
| 900 |
+
|
| 901 |
+
text = text.replace('\\coloneqq', ':=').replace('\\eqqcolon', '=:')
|
| 902 |
+
text = STRAY_TOKEN_RE.sub('', text)
|
| 903 |
+
text = _fix_span_attrs(text)
|
| 904 |
+
text = re.sub(r'(?m)^\s*\[\s*-?\d+\s*,\s*-?\d+\s*,\s*-?\d+\s*,\s*-?\d+\s*\]\s*$', '', text)
|
| 905 |
+
text = re.sub(r'[ \t]+\n', '\n', text)
|
| 906 |
+
text = re.sub(r'\n{3,}', '\n\n', text).strip()
|
| 907 |
+
return '\n\n'.join(_single_root_titles(text.split('\n\n')))
|
| 908 |
+
|
| 909 |
+
|
| 910 |
+
if __name__ == "__main__":
|
| 911 |
+
main()
|
unlimited-ocr2.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "saturate[hf]==0.2.0",
|
| 5 |
+
# "pillow>=10",
|
| 6 |
+
# ]
|
| 7 |
+
#
|
| 8 |
+
# [tool.hf-jobs]
|
| 9 |
+
# image = "lmsysorg/sglang:v0.5.20-cu130"
|
| 10 |
+
# flavor = "rtx-pro-6000"
|
| 11 |
+
# timeout = "4h"
|
| 12 |
+
# secrets = ["HF_TOKEN"]
|
| 13 |
+
# ///
|
| 14 |
+
"""
|
| 15 |
+
OCR whole documents (book volumes, folders of scans) with Baidu Unlimited-OCR-2.
|
| 16 |
+
|
| 17 |
+
Unlimited-OCR-2 reads many pages in ONE request and keeps context across page
|
| 18 |
+
breaks: a paragraph that runs onto the next page comes back tagged as a
|
| 19 |
+
continuation, not as two fragments. This script groups page images into
|
| 20 |
+
documents and sends 16 consecutive pages per request.
|
| 21 |
+
|
| 22 |
+
hf jobs uv run --detach \\
|
| 23 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/unlimited-ocr2.py \\
|
| 24 |
+
"hf://buckets/biglam/britannica/source/pages/1771EncyclopediaBritannicaNLS/*.jp2" \\
|
| 25 |
+
<user>/britannica-1771
|
| 26 |
+
|
| 27 |
+
The [tool.hf-jobs] table above sets the image, GPU, timeout and HF_TOKEN.
|
| 28 |
+
The GPU needs >= 48 GB: on 24 GB cards a 16-page request (~31k tokens of KV)
|
| 29 |
+
thrashes the cache. rtx-pro-6000 was the fastest per dollar in our tests.
|
| 30 |
+
|
| 31 |
+
Input: a glob or folder of page images (a Bucket, a mounted dir, a local dir).
|
| 32 |
+
A document is the parent folder plus the file name without its trailing page
|
| 33 |
+
number (`Volume 1, A-B_0007.jp2` -> `Volume 1, A-B`); pages sort by that number.
|
| 34 |
+
|
| 35 |
+
Output: `data/part-*.parquet`, one row per 16-page window:
|
| 36 |
+
`{id, doc_id, first_page, page_files, status, page_markdown, raw, ...}`.
|
| 37 |
+
`page_markdown` lines up with `page_files`; `raw` is the model's output with its
|
| 38 |
+
layout blocks and boxes. `status` is `truncated` or `page_mismatch` when the model
|
| 39 |
+
ran out of budget or lost a page boundary (then `page_markdown` is empty and only
|
| 40 |
+
`raw` is kept). Re-running the same command resumes where it stopped.
|
| 41 |
+
|
| 42 |
+
About 2% of dense 18th-century pages (mostly mathematics) send the model into a
|
| 43 |
+
loop. `unlimited-ocr2-saturate.py` is the tuned version of this script: it
|
| 44 |
+
re-reads those pages one at a time, decodes JPEG 2000 faster, reads PDFs and adds
|
| 45 |
+
Baidu's own Markdown post-processing. It may change more often.
|
| 46 |
+
|
| 47 |
+
How it runs: Unlimited-OCR-2 needs Baidu's own SGLang build (no vLLM support).
|
| 48 |
+
The script installs that wheel into the image's Python, starts the server in the
|
| 49 |
+
Job, and sends requests with saturate (adaptive concurrency, resumable output).
|
| 50 |
+
|
| 51 |
+
Model: https://huggingface.co/baidu/Unlimited-OCR-2 (3.3B, MIT)
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
import argparse
|
| 55 |
+
import base64
|
| 56 |
+
import io
|
| 57 |
+
import json
|
| 58 |
+
import os
|
| 59 |
+
import re
|
| 60 |
+
import shutil
|
| 61 |
+
import subprocess
|
| 62 |
+
import sys
|
| 63 |
+
|
| 64 |
+
# The model card's launch settings. The image is the SGLang release whose pins
|
| 65 |
+
# match Baidu's wheel (torch 2.13.0, transformers 5.12.1); move both together.
|
| 66 |
+
SERVING = {
|
| 67 |
+
"model": "baidu/Unlimited-OCR-2",
|
| 68 |
+
"served_name": "Unlimited-OCR-2",
|
| 69 |
+
"wheel": "https://huggingface.co/baidu/Unlimited-OCR-2/resolve/main/wheel/"
|
| 70 |
+
"sglang-0.5.20.dev10%2Bg8d62f5fb9c-py3-none-any.whl",
|
| 71 |
+
"extra_pip": ["fastokens==0.3.2"],
|
| 72 |
+
"env": {
|
| 73 |
+
"SGLANG_UOCR_EANABLE_DOC_LIMIT": "1", # (sic) upstream spelling
|
| 74 |
+
"SGLANG_UOCR_DOC_GUNDAM_PAGE_WINDOW": "10",
|
| 75 |
+
"SGLANG_UOCR_DOC_BASE_PAGE_WINDOW": "10",
|
| 76 |
+
"SGLANG_UOCR_MAX_PAGE_TOKENS": "20000",
|
| 77 |
+
"SGLANG_OPT_UOCR_SAM_REL_POS_BIAS_MB": "64",
|
| 78 |
+
"SGLANG_UOCR_SHM_WRAP_MODEL_DATA": "1",
|
| 79 |
+
"SGLANG_UOCR_SHM_WRAP_MIN_MB": "1",
|
| 80 |
+
"SGLANG_VLM_CACHE_SIZE_MB": "0",
|
| 81 |
+
"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True",
|
| 82 |
+
},
|
| 83 |
+
"serve_args": [
|
| 84 |
+
"--chat-template", "unlimited-ocr",
|
| 85 |
+
"--tokenizer-backend", "fastokens", "--tokenizer-worker-num", "8",
|
| 86 |
+
"--mem-fraction-static", "0.7",
|
| 87 |
+
"--max-running-requests", "64",
|
| 88 |
+
"--max-prefill-tokens", "2048",
|
| 89 |
+
"--enable-custom-logit-processor", "--enable-streaming-session",
|
| 90 |
+
"--allow-auto-truncate", "--disable-radix-cache",
|
| 91 |
+
"--mm-preprocess-cache-size-mb", "0",
|
| 92 |
+
"--cuda-graph-backend-decode", "full", "--cuda-graph-max-bs-decode", "64",
|
| 93 |
+
"--cuda-graph-backend-prefill", "full",
|
| 94 |
+
"--cuda-graph-max-bs-prefill", "16384",
|
| 95 |
+
"--cuda-graph-bs-prefill", "1024", "2048",
|
| 96 |
+
"--cuda-graph-config", '{"prefill": {"backend": "full", "full_prefill_max_req": 64}}',
|
| 97 |
+
],
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
# The card's no-repeat n-gram guard: DeepseekOCRNoRepeatNGramLogitProcessor.to_str(),
|
| 101 |
+
# i.e. json({"callable": dill.dumps(cls).hex()}). dill pickles an importable class
|
| 102 |
+
# by reference (module + name), so this is a fixed string and needs no sglang here.
|
| 103 |
+
NGRAM_PROCESSOR = json.dumps({"callable": (
|
| 104 |
+
"80059559000000000000008c2a73676c616e672e7372742e73616d706c696e672e637573746f6d5f6c6f6769"
|
| 105 |
+
"745f70726f636573736f72948c26446565707365656b4f43524e6f5265706561744e4772616d4c6f67697450"
|
| 106 |
+
"726f636573736f729493942e")})
|
| 107 |
+
|
| 108 |
+
PAGE_EXTS = (".jp2", ".jpg", ".jpeg", ".png", ".tif", ".tiff", ".webp")
|
| 109 |
+
FURNITURE = {"page_number", "header", "footer"}
|
| 110 |
+
BLOCK_RE = re.compile(r"<BLOCK>(?P<type>[a-z_]+)(?:<LEVEL(?P<level>\d)>)?\[[\d, ]*\]<FORK>")
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def natural_key(s: str):
|
| 114 |
+
return [int(t) if t.isdigit() else t for t in re.split(r"(\d+)", s)]
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def doc_key(rel_path: str) -> str:
|
| 118 |
+
"""`item/Volume 1, A-B_0007.jp2` -> `item/Volume 1, A-B`; bare `0007.jp2` -> `.`."""
|
| 119 |
+
stem = rel_path.rsplit(".", 1)[0]
|
| 120 |
+
doc = re.sub(r"[_\-. ]?\d+$", "", stem)
|
| 121 |
+
return doc if doc and not doc.endswith("/") else (doc or ".")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def list_windows(pattern: str, pages_per_request: int, max_pages):
|
| 125 |
+
"""List page files, group them into documents, cut each into windows -> (id, row)."""
|
| 126 |
+
from saturate import bucket_rows
|
| 127 |
+
|
| 128 |
+
if not re.search(r"[*?\[]", pattern):
|
| 129 |
+
pattern = pattern.rstrip("/") + "/**"
|
| 130 |
+
docs: dict[str, list[tuple[str, str]]] = {}
|
| 131 |
+
for rid, row in bucket_rows(pattern, read=False):
|
| 132 |
+
if rid.lower().endswith(PAGE_EXTS):
|
| 133 |
+
docs.setdefault(doc_key(rid), []).append((rid, row["path"]))
|
| 134 |
+
if not docs:
|
| 135 |
+
sys.exit(f"no page images matched {pattern!r}")
|
| 136 |
+
|
| 137 |
+
n_pages = 0
|
| 138 |
+
for doc in sorted(docs, key=natural_key):
|
| 139 |
+
pages = sorted(docs[doc], key=lambda p: natural_key(p[0]))
|
| 140 |
+
for start in range(0, len(pages), pages_per_request):
|
| 141 |
+
if max_pages is not None and n_pages >= max_pages:
|
| 142 |
+
return
|
| 143 |
+
window = pages[start: start + pages_per_request]
|
| 144 |
+
if max_pages is not None:
|
| 145 |
+
window = window[: max_pages - n_pages]
|
| 146 |
+
n_pages += len(window)
|
| 147 |
+
# The id encodes the page range, so a --max-pages-truncated window is not
|
| 148 |
+
# mistaken for the full window when a later run resumes.
|
| 149 |
+
yield f"{doc}@{start:06d}-{start + len(window):06d}", {
|
| 150 |
+
"doc_id": doc, "first_page": start,
|
| 151 |
+
"page_files": [rid for rid, _ in window],
|
| 152 |
+
"paths": [p for _, p in window],
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def load_page(fs, path: str, max_side: int) -> str:
|
| 157 |
+
"""Read one page image, downscale it, return base64 JPEG."""
|
| 158 |
+
from PIL import Image
|
| 159 |
+
|
| 160 |
+
with fs.open(path, "rb") as f:
|
| 161 |
+
img = Image.open(io.BytesIO(f.read()))
|
| 162 |
+
img.load()
|
| 163 |
+
img = img.convert("RGB")
|
| 164 |
+
img.thumbnail((max_side, max_side), Image.LANCZOS)
|
| 165 |
+
buf = io.BytesIO()
|
| 166 |
+
img.save(buf, format="JPEG", quality=90)
|
| 167 |
+
return base64.b64encode(buf.getvalue()).decode()
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def clean_page(raw_page: str, keep_furniture: bool) -> str:
|
| 171 |
+
"""One page of model output -> plain markdown.
|
| 172 |
+
|
| 173 |
+
Drops block tags and boxes, turns titles into `#` headings, drops page
|
| 174 |
+
numbers and running heads, and joins `<MERGE>`d blocks (e.g. verse lines).
|
| 175 |
+
"""
|
| 176 |
+
blocks: list[str] = []
|
| 177 |
+
merge_next = False
|
| 178 |
+
matches = list(BLOCK_RE.finditer(raw_page))
|
| 179 |
+
for i, m in enumerate(matches):
|
| 180 |
+
end = matches[i + 1].start() if i + 1 < len(matches) else len(raw_page)
|
| 181 |
+
body = raw_page[m.end(): end].strip()
|
| 182 |
+
merge_prev, merge_next = merge_next, body.endswith("<MERGE>")
|
| 183 |
+
body = body.removesuffix("<MERGE>").strip()
|
| 184 |
+
kind = m.group("type")
|
| 185 |
+
if not body or (kind in FURNITURE and not keep_furniture):
|
| 186 |
+
continue
|
| 187 |
+
if kind == "title" and m.group("level"):
|
| 188 |
+
body = "#" * int(m.group("level")) + " " + body
|
| 189 |
+
if merge_prev and blocks:
|
| 190 |
+
blocks[-1] += "\n" + body
|
| 191 |
+
else:
|
| 192 |
+
blocks.append(body)
|
| 193 |
+
return "\n\n".join(blocks)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def start_server_cmd() -> list[str]:
|
| 197 |
+
"""Install Baidu's wheel into the image's sglang Python and return the server command."""
|
| 198 |
+
# The SGLang image keeps sglang in its own venv (/opt/sglang/bin), first on PATH;
|
| 199 |
+
# `uv run` puts this script's venv in front, so look past it.
|
| 200 |
+
own_bin = os.path.realpath(os.path.join(sys.prefix, "bin"))
|
| 201 |
+
path = os.pathsep.join(p for p in os.environ.get("PATH", "").split(os.pathsep)
|
| 202 |
+
if os.path.realpath(p) != own_bin)
|
| 203 |
+
py = shutil.which("python3", path=path)
|
| 204 |
+
if not py or subprocess.run([py, "-c", "import sglang"], check=False,
|
| 205 |
+
capture_output=True).returncode != 0:
|
| 206 |
+
sys.exit("No Python with sglang found: run this on the lmsysorg/sglang image "
|
| 207 |
+
"(`hf jobs uv run` picks it up from the script's [tool.hf-jobs] table).")
|
| 208 |
+
env = {k: v for k, v in os.environ.items() if k != "VIRTUAL_ENV"}
|
| 209 |
+
pip = ["uv", "pip", "install", "-q", "--python", py]
|
| 210 |
+
subprocess.run([*pip, "--no-deps", SERVING["wheel"]], check=True, env=env)
|
| 211 |
+
subprocess.run([*pip, *SERVING["extra_pip"]], check=True, env=env)
|
| 212 |
+
os.environ.update(SERVING["env"]) # inherited by the server process
|
| 213 |
+
return [py, "-m", "sglang.launch_server", "--model-path", SERVING["model"],
|
| 214 |
+
"--served-model-name", SERVING["served_name"], *SERVING["serve_args"],
|
| 215 |
+
"--enable-metrics", "--host", "127.0.0.1", "--port", "8000"]
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def main():
|
| 219 |
+
ap = argparse.ArgumentParser(description="Unlimited-OCR-2 document OCR on HF Jobs")
|
| 220 |
+
ap.add_argument("input", help="Glob or folder of page images: hf://buckets/..., a mounted dir, ...")
|
| 221 |
+
ap.add_argument("output", help="Output dataset id (org/name) or fsspec URI (hf://buckets/...)")
|
| 222 |
+
ap.add_argument("--pages-per-request", type=int, default=16,
|
| 223 |
+
help="Consecutive pages per request (default 16)")
|
| 224 |
+
ap.add_argument("--max-pages", type=int, default=None, help="Stop after N pages (for a test run)")
|
| 225 |
+
ap.add_argument("--max-side", type=int, default=1280,
|
| 226 |
+
help="Long side (px) pages are sent at. The model resizes each page to a "
|
| 227 |
+
"1024 px view, so more pixels only make the requests bigger")
|
| 228 |
+
ap.add_argument("--keep-furniture", action="store_true",
|
| 229 |
+
help="Keep page numbers and running heads in page_markdown")
|
| 230 |
+
ap.add_argument("--retry-errors", action="store_true", help="Retry windows recorded as errors")
|
| 231 |
+
args = ap.parse_args()
|
| 232 |
+
|
| 233 |
+
import fsspec
|
| 234 |
+
import saturate.transport
|
| 235 |
+
from saturate import Auto, Engine, pump
|
| 236 |
+
|
| 237 |
+
rows = list(list_windows(args.input, args.pages_per_request, args.max_pages))
|
| 238 |
+
print(f"{len({r['doc_id'] for _, r in rows})} documents, "
|
| 239 |
+
f"{sum(len(r['paths']) for _, r in rows)} pages, {len(rows)} requests", file=sys.stderr)
|
| 240 |
+
fs = fsspec.core.url_to_fs(args.input.split("*")[0] or ".")[0]
|
| 241 |
+
|
| 242 |
+
def to_request(row):
|
| 243 |
+
n = len(row["paths"])
|
| 244 |
+
content = [{"type": "image_url",
|
| 245 |
+
"image_url": {"url": f"data:image/jpeg;base64,{load_page(fs, p, args.max_side)}"}}
|
| 246 |
+
for p in row["paths"]]
|
| 247 |
+
content.append({"type": "text", "text": "<PAGE><image>" * n + "Multi page parsing."})
|
| 248 |
+
# Sampling and guard settings from the model card's client example.
|
| 249 |
+
return {
|
| 250 |
+
"model": SERVING["served_name"],
|
| 251 |
+
"messages": [{"role": "user", "content": content}],
|
| 252 |
+
"max_tokens": 8000 * n, # output budget for the whole window
|
| 253 |
+
"temperature": 0,
|
| 254 |
+
"skip_special_tokens": False, # <PAGE>/<BLOCK> markers are the structure
|
| 255 |
+
"images_config": {"crop_mode": False}, # base mode: one 1024 px view per page
|
| 256 |
+
"custom_logit_processor": NGRAM_PROCESSOR,
|
| 257 |
+
"custom_params": {
|
| 258 |
+
"ngram_size": 35, "window_size": 1024 if n > 1 else 128,
|
| 259 |
+
"page_token_id": 128827, "eos_token_id": 1, "max_page_tokens": 20000,
|
| 260 |
+
},
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
def parse(row, body):
|
| 264 |
+
choice = body["choices"][0]
|
| 265 |
+
raw = choice["message"]["content"]
|
| 266 |
+
raw_pages = raw.split("<PAGE>")[1:]
|
| 267 |
+
if choice.get("finish_reason") == "length":
|
| 268 |
+
status = "truncated"
|
| 269 |
+
elif len(raw_pages) != len(row["paths"]):
|
| 270 |
+
status = "page_mismatch"
|
| 271 |
+
else:
|
| 272 |
+
status = "ok"
|
| 273 |
+
usage = body.get("usage") or {}
|
| 274 |
+
return {
|
| 275 |
+
"doc_id": row["doc_id"],
|
| 276 |
+
"first_page": row["first_page"],
|
| 277 |
+
"page_files": row["page_files"],
|
| 278 |
+
"status": status,
|
| 279 |
+
"page_markdown": [clean_page(p, args.keep_furniture) for p in raw_pages]
|
| 280 |
+
if status == "ok" else None,
|
| 281 |
+
"raw": raw,
|
| 282 |
+
"model": SERVING["model"],
|
| 283 |
+
"prompt_tokens": usage.get("prompt_tokens"),
|
| 284 |
+
"completion_tokens": usage.get("completion_tokens"),
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
is_repo_id = re.fullmatch(r"[\w-][\w.-]*/[\w.-]*[\w-]", args.output) and not os.path.exists(args.output)
|
| 288 |
+
output = f"hf://datasets/{args.output}/data" if is_repo_id else args.output
|
| 289 |
+
|
| 290 |
+
# One request is minutes of decoding. saturate 0.2.0 caps a request's retries at
|
| 291 |
+
# 300 s in total, which a retried 16-page request never fits in; match the read timeout.
|
| 292 |
+
saturate.transport.RETRY_BUDGET_S = 3600.0
|
| 293 |
+
with Engine(SERVING["model"], engine="sglang", cmd=start_server_cmd()) as endpoint:
|
| 294 |
+
stats = pump(rows, to_request, parse, endpoint, output,
|
| 295 |
+
window=Auto(initial=32, max_limit=64), # long requests: start wide
|
| 296 |
+
flush_every=4, # each row is minutes of GPU time; write often
|
| 297 |
+
read_timeout=3600, prepare_workers=8, retry_errors=args.retry_errors)
|
| 298 |
+
print(f"{output}: {stats.rows_processed} windows written, {stats.rows_failed} errors", file=sys.stderr)
|
| 299 |
+
print("UNLIMITED_OCR2 " + stats.to_json(), flush=True)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
if __name__ == "__main__":
|
| 303 |
+
main()
|