Sync from GitHub via hub-sync
Browse files- CLAUDE.md +6 -0
- LANGUAGES.md +1 -1
- README.md +3 -2
- models.json +24 -1
- xiaomi-ocr-0-saturate.py +610 -0
CLAUDE.md
CHANGED
|
@@ -88,6 +88,7 @@ Legend: ✅ production-ready · ⚠️ works only with a required pinned image
|
|
| 88 |
| `dots-ocr-1.5.py` | ✅ | vLLM 0.17.1 | l4x1 | see gotcha (`content_format`, mirror, bbox space) |
|
| 89 |
| `glm-ocr.py` | ✅ | vLLM (nightly) | l4x1 | `VLLM_USE_DEEP_GEMM=0`; no pyarrow cap |
|
| 90 |
| `ovis-ocr2.py` | ✅ | vLLM (stable ≥0.22.1) | l4x1 / a10g-small | `gdn_prefill_backend="triton"` (card); card-exact prompt via `enable_thinking=False` template + `llm.generate`; `<img>` region tags filtered by default (`--keep-image-tags`) |
|
|
|
|
| 91 |
| `glm-ocr-v2.py` | 🧪 | vLLM (nightly) | l4x1 | CommitScheduler incremental — on hold (see Deferred) |
|
| 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 `!` |
|
|
@@ -343,6 +344,11 @@ ARM wheels) — if a nightly-recipe install fails on resolution, wait and retry
|
|
| 343 |
|
| 344 |
## Change log
|
| 345 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 346 |
- **2026-10-27** — added `minicpm-ocr.py` (experimental) for `openbmb/MiniCPM-OCR-1.0`: OpenBMB's SDK
|
| 347 |
pipeline on a public custom image `cr.hf.co/davanstrien/minicpm-ocr` (first recipe on the HF container
|
| 348 |
registry; Dockerfile in `images/minicpm-ocr/`).
|
|
|
|
| 88 |
| `dots-ocr-1.5.py` | ✅ | vLLM 0.17.1 | l4x1 | see gotcha (`content_format`, mirror, bbox space) |
|
| 89 |
| `glm-ocr.py` | ✅ | vLLM (nightly) | l4x1 | `VLLM_USE_DEEP_GEMM=0`; no pyarrow cap |
|
| 90 |
| `ovis-ocr2.py` | ✅ | vLLM (stable ≥0.22.1) | l4x1 / a10g-small | `gdn_prefill_backend="triton"` (card); card-exact prompt via `enable_thinking=False` template + `llm.generate`; `<img>` region tags filtered by default (`--keep-image-tags`) |
|
| 91 |
+
| `xiaomi-ocr-0-saturate.py` | 🧪 | vLLM or SGLang + saturate | a10g-small / rtx-pro-6000 | single-stage only; OTSL→HTML + math delimiters vendored from upstream; `max_tokens` 12000 to fit the 16384 context; default `Auto()` window |
|
| 92 |
| `glm-ocr-v2.py` | 🧪 | vLLM (nightly) | l4x1 | CommitScheduler incremental — on hold (see Deferred) |
|
| 93 |
| `nanonets-ocr.py` | ✅ | vLLM | a10g-small | `--max-model-len` 32768 (`--max-tokens` 15000) |
|
| 94 |
| `nanonets-ocr2.py` | ⚠️+image | vLLM `:v0.10.2` | a10g-small | Qwen2.5-VL ≥0.11 regression → pure `!` |
|
|
|
|
| 344 |
|
| 345 |
## Change log
|
| 346 |
|
| 347 |
+
- **2026-10-30** — added `xiaomi-ocr-0-saturate.py` for `xiaomi-research/Xiaomi-OCR-0` (0.8B, Qwen3.5 arch), on
|
| 348 |
+
saturate `==0.3.0`. Do not set `max_limit` by copying older saturate recipes: on `rtx-pro-6000`, `Auto(max_limit=48)`
|
| 349 |
+
gave 4.7 pages/s and the default `Auto()` with `prepare_workers` gave 9.7 (1,200 pages, 95% GPU, 0 failures).
|
| 350 |
+
On `a10g-small`: 2.9 vs 3.4 pages/s. Output cost is about $0.08 per 1,000 pages on both, excluding boot.
|
| 351 |
+
|
| 352 |
- **2026-10-27** — added `minicpm-ocr.py` (experimental) for `openbmb/MiniCPM-OCR-1.0`: OpenBMB's SDK
|
| 353 |
pipeline on a public custom image `cr.hf.co/davanstrien/minicpm-ocr` (first recipe on the HF container
|
| 354 |
registry; Dockerfile in `images/minicpm-ocr/`).
|
LANGUAGES.md
CHANGED
|
@@ -27,7 +27,7 @@ _Sorted by strength of evidence, then coverage:_
|
|
| 27 |
| [HunyuanOCR-1.5](https://huggingface.co/tencent/HunyuanOCR) | "Multilingual" | Nothing enumerated, but explicitly targets **low-resource + ancient-script OCR** as a design goal (new in 1.5; the pinned 1.0 revision doesn't claim this) |
|
| 28 |
| [dots.mocr](https://huggingface.co/rednote-hilab/dots.mocr) · [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) / [-2](https://huggingface.co/deepseek-ai/DeepSeek-OCR-2) · [Unlimited-OCR](https://huggingface.co/baidu/Unlimited-OCR) · [NuExtract3](https://huggingface.co/numind/NuExtract3) | "Multilingual", unspecified | A tag or one-liner only — no count, list, or benchmark |
|
| 29 |
| [olmOCR-2](https://huggingface.co/allenai/olmOCR-2-7B-1025-FP8) · [Nanonets-OCR-s](https://huggingface.co/nanonets/Nanonets-OCR-s) · [SmolDocling](https://huggingface.co/ds4sd/SmolDocling-256M-preview) · [LFM2.5-VL-Extract](https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-Extract) | English only | Stated on the card |
|
| 30 |
-
| [Falcon-OCR](https://huggingface.co/tiiuae/Falcon-OCR) · [OvisOCR2](https://huggingface.co/ATH-MaaS/OvisOCR2) · [LightOnOCR-3](https://huggingface.co/collections/lightonai/lightonocr-3) · [FireRed-OCR](https://huggingface.co/FireRedTeam/FireRed-OCR) · [ABot-OCR](https://huggingface.co/acvlab/ABot-OCR) · [RolmOCR](https://huggingface.co/reducto/RolmOCR) · [NuMarkdown-8B](https://huggingface.co/numind/NuMarkdown-8B-Thinking) · [lift](https://huggingface.co/datalab-to/lift) | Not stated | No language information on the card at all |
|
| 31 |
|
| 32 |
Text-only extraction: [LFM2-1.2B-Extract](https://huggingface.co/LiquidAI/LFM2-1.2B-Extract) (chains after OCR) names 9 languages: English, Arabic, Chinese, French, German, Japanese, Korean, Portuguese, Spanish.
|
| 33 |
|
|
|
|
| 27 |
| [HunyuanOCR-1.5](https://huggingface.co/tencent/HunyuanOCR) | "Multilingual" | Nothing enumerated, but explicitly targets **low-resource + ancient-script OCR** as a design goal (new in 1.5; the pinned 1.0 revision doesn't claim this) |
|
| 28 |
| [dots.mocr](https://huggingface.co/rednote-hilab/dots.mocr) · [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) / [-2](https://huggingface.co/deepseek-ai/DeepSeek-OCR-2) · [Unlimited-OCR](https://huggingface.co/baidu/Unlimited-OCR) · [NuExtract3](https://huggingface.co/numind/NuExtract3) | "Multilingual", unspecified | A tag or one-liner only — no count, list, or benchmark |
|
| 29 |
| [olmOCR-2](https://huggingface.co/allenai/olmOCR-2-7B-1025-FP8) · [Nanonets-OCR-s](https://huggingface.co/nanonets/Nanonets-OCR-s) · [SmolDocling](https://huggingface.co/ds4sd/SmolDocling-256M-preview) · [LFM2.5-VL-Extract](https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-Extract) | English only | Stated on the card |
|
| 30 |
+
| [Falcon-OCR](https://huggingface.co/tiiuae/Falcon-OCR) · [OvisOCR2](https://huggingface.co/ATH-MaaS/OvisOCR2) · [Xiaomi-OCR-0](https://huggingface.co/xiaomi-research/Xiaomi-OCR-0) · [LightOnOCR-3](https://huggingface.co/collections/lightonai/lightonocr-3) · [FireRed-OCR](https://huggingface.co/FireRedTeam/FireRed-OCR) · [ABot-OCR](https://huggingface.co/acvlab/ABot-OCR) · [RolmOCR](https://huggingface.co/reducto/RolmOCR) · [NuMarkdown-8B](https://huggingface.co/numind/NuMarkdown-8B-Thinking) · [lift](https://huggingface.co/datalab-to/lift) | Not stated | No language information on the card at all |
|
| 31 |
|
| 32 |
Text-only extraction: [LFM2-1.2B-Extract](https://huggingface.co/LiquidAI/LFM2-1.2B-Extract) (chains after OCR) names 9 languages: English, Arabic, Chinese, French, German, Japanese, Korean, Portuguese, Spanish.
|
| 33 |
|
README.md
CHANGED
|
@@ -87,6 +87,7 @@ These are the maintained recipes. Each one has a tested `[tool.hf-jobs]` header,
|
|
| 87 |
| [`glm-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/glm-ocr.py) | [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) | 0.9B | 94.62 OmniDocBench v1.5 | MIT | `a10g-small` |
|
| 88 |
| [`paddleocr-vl-1.6.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/paddleocr-vl-1.6.py) | [PaddleOCR-VL-1.6](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.6) | 0.9B | 96.33 OmniDocBench v1.6; six task modes | Apache-2.0 | `a10g-small` |
|
| 89 |
| [`ovis-ocr2.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/ovis-ocr2.py) | [OvisOCR2](https://huggingface.co/ATH-MaaS/OvisOCR2) | 0.9B | 96.58 OmniDocBench v1.6; LaTeX and HTML tables | Apache-2.0 | `a10g-small` |
|
|
|
|
| 90 |
| [`lighton-ocr2.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/lighton-ocr2.py) | [LightOnOCR-2-1B](https://huggingface.co/lightonai/LightOnOCR-2-1B) | 1B | 83.2 olmOCR-Bench | Apache-2.0 | `a10g-small` |
|
| 91 |
| [`hunyuan-ocr-1.5.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/hunyuan-ocr-1.5.py) | [HunyuanOCR-1.5](https://huggingface.co/tencent/HunyuanOCR) | 1B | 12 task types, including spotting, charts and translation | [Hunyuan Community](https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE) (excludes EU, UK, South Korea) | `a10g-small` |
|
| 92 |
| [`minicpm-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/minicpm-ocr.py) | [MiniCPM-OCR 1.0](https://huggingface.co/openbmb/MiniCPM-OCR-1.0) | 1.3B | OpenBMB's full pipeline: layout regions, per-region prompts, Markdown with HTML tables; Hub dataset or Bucket in/out; runs on a public [`cr.hf.co`](https://huggingface.co/containers/davanstrien/minicpm-ocr) image (experimental) | Apache-2.0 | `a10g-large` |
|
|
@@ -103,7 +104,7 @@ These are the maintained recipes. Each one has a tested `[tool.hf-jobs]` header,
|
|
| 103 |
|
| 104 |
Start with a model under 2B. Use a larger model only if the output of a small one is not good enough. Check the licence before you use a model: Surya and lift use a modified OpenRAIL-M licence (free for research, personal use and startups under $5M; no competitive use against Datalab's API), and the Hunyuan licence excludes the EU, the UK and South Korea.
|
| 105 |
|
| 106 |
-
**Variants and tools:** `glm-ocr-bucket.py`, `surya-ocr-bucket.py` and `lighton-ocr3-bucket.py` read images and PDFs from a Bucket and write one `.md` per page. `lighton-ocr3-bucket.py` also takes `hf://buckets/...` URLs for input and output directly, so it reads large buckets in batches through the Hub API without mounting them. It reads `.jp2`, skips pages that already have output (so a re-run resumes), and in `--mode grounding` writes a `.json` sidecar with the layout blocks. `surya-ocr-bucket.py` also writes a `.json` sidecar with the layout blocks, resumes from existing JSON, and can mount or copy its input (`--io-mode mount|copy`); the dataset version, `surya-ocr.py`, keeps the blocks in a `surya_blocks` column. `lighton-ocr2-saturate.py`
|
| 107 |
|
| 108 |
Which model is best depends on your documents. The public olmOCR-Bench leaderboard is one command away:
|
| 109 |
|
|
@@ -220,7 +221,7 @@ hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/pp-doclay
|
|
| 220 |
|
| 221 |
## Scaling up
|
| 222 |
|
| 223 |
-
**Large datasets:** `lighton-ocr2-saturate.py`
|
| 224 |
|
| 225 |
**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:
|
| 226 |
|
|
|
|
| 87 |
| [`glm-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/glm-ocr.py) | [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) | 0.9B | 94.62 OmniDocBench v1.5 | MIT | `a10g-small` |
|
| 88 |
| [`paddleocr-vl-1.6.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/paddleocr-vl-1.6.py) | [PaddleOCR-VL-1.6](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.6) | 0.9B | 96.33 OmniDocBench v1.6; six task modes | Apache-2.0 | `a10g-small` |
|
| 89 |
| [`ovis-ocr2.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/ovis-ocr2.py) | [OvisOCR2](https://huggingface.co/ATH-MaaS/OvisOCR2) | 0.9B | 96.58 OmniDocBench v1.6; LaTeX and HTML tables | Apache-2.0 | `a10g-small` |
|
| 90 |
+
| [`xiaomi-ocr-0-saturate.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/xiaomi-ocr-0-saturate.py) | [Xiaomi-OCR-0](https://huggingface.co/xiaomi-research/Xiaomi-OCR-0) | 0.8B | Whole-page Markdown with LaTeX and HTML tables on vLLM or SGLang; the card's benchmark scores use a two-stage pipeline this recipe does not run (experimental) | Apache-2.0 | `a10g-small` |
|
| 91 |
| [`lighton-ocr2.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/lighton-ocr2.py) | [LightOnOCR-2-1B](https://huggingface.co/lightonai/LightOnOCR-2-1B) | 1B | 83.2 olmOCR-Bench | Apache-2.0 | `a10g-small` |
|
| 92 |
| [`hunyuan-ocr-1.5.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/hunyuan-ocr-1.5.py) | [HunyuanOCR-1.5](https://huggingface.co/tencent/HunyuanOCR) | 1B | 12 task types, including spotting, charts and translation | [Hunyuan Community](https://huggingface.co/tencent/HunyuanOCR/blob/main/LICENSE) (excludes EU, UK, South Korea) | `a10g-small` |
|
| 93 |
| [`minicpm-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/minicpm-ocr.py) | [MiniCPM-OCR 1.0](https://huggingface.co/openbmb/MiniCPM-OCR-1.0) | 1.3B | OpenBMB's full pipeline: layout regions, per-region prompts, Markdown with HTML tables; Hub dataset or Bucket in/out; runs on a public [`cr.hf.co`](https://huggingface.co/containers/davanstrien/minicpm-ocr) image (experimental) | Apache-2.0 | `a10g-large` |
|
|
|
|
| 104 |
|
| 105 |
Start with a model under 2B. Use a larger model only if the output of a small one is not good enough. Check the licence before you use a model: Surya and lift use a modified OpenRAIL-M licence (free for research, personal use and startups under $5M; no competitive use against Datalab's API), and the Hunyuan licence excludes the EU, the UK and South Korea.
|
| 106 |
|
| 107 |
+
**Variants and tools:** `glm-ocr-bucket.py`, `surya-ocr-bucket.py` and `lighton-ocr3-bucket.py` read images and PDFs from a Bucket and write one `.md` per page. `lighton-ocr3-bucket.py` also takes `hf://buckets/...` URLs for input and output directly, so it reads large buckets in batches through the Hub API without mounting them. It reads `.jp2`, skips pages that already have output (so a re-run resumes), and in `--mode grounding` writes a `.json` sidecar with the layout blocks. `surya-ocr-bucket.py` also writes a `.json` sidecar with the layout blocks, resumes from existing JSON, and can mount or copy its input (`--io-mode mount|copy`); the dataset version, `surya-ocr.py`, keeps the blocks in a `surya_blocks` column. `lighton-ocr2-saturate.py`, `ovis-ocr2-saturate.py` and `xiaomi-ocr-0-saturate.py` are for large runs, and `ocr-vllm-judge.py` compares outputs ([Scaling up](#scaling-up)). `pp-doclayout.py` and `lfm2-extract.py` are described in [Structured extraction and layout](#structured-extraction-and-layout).
|
| 108 |
|
| 109 |
Which model is best depends on your documents. The public olmOCR-Bench leaderboard is one command away:
|
| 110 |
|
|
|
|
| 221 |
|
| 222 |
## Scaling up
|
| 223 |
|
| 224 |
+
**Large datasets:** `lighton-ocr2-saturate.py`, `ovis-ocr2-saturate.py` and `xiaomi-ocr-0-saturate.py` start a vLLM server in the Job (the Xiaomi recipe can use SGLang instead) and send pages to it with adaptive concurrency. They stream results to the output repo as parquet parts. If a run stops, run the same command again and it skips the rows that are done. A failed page is stored as an error row, and `--retry-errors` tries those rows again. The output layout is different from the other recipes; the script header explains how to read it. [SERVING.md](SERVING.md) compares server mode with offline batches (measured throughput and output parity).
|
| 225 |
|
| 226 |
**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:
|
| 227 |
|
models.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
{
|
| 2 |
"_meta": {
|
| 3 |
"description": "Machine-readable catalog of the OCR recipes in this directory: script -> model, params, backend, support level, the tested Jobs launch config (the script's [tool.hf-jobs] header), and what the model's own card claims about language coverage. Human-readable language notes: LANGUAGES.md. Language evidence levels, strongest first: per-language-benchmark | count-claim | named-list | multilingual-unspecified | english-only | not-stated | not-applicable. Claims come from model cards (compiled 2026-07-15) - treat as claims, not guarantees.",
|
| 4 |
-
"updated": "2026-10-
|
| 5 |
"run_pattern": "hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/<script> <input-dataset> <output-dataset> (hf CLI >= 1.32 reads image/flavor/secrets from the script's [tool.hf-jobs] header; add --timeout for long runs. Scripts without a `jobs` entry need --flavor/-s HF_TOKEN (and any --image in their docstring).)",
|
| 6 |
"support_levels": {
|
| 7 |
"core": "Maintained. Smoke-tested flagless on HF Jobs on 2026-09-23/24 with the pinned launch config in `jobs`.",
|
|
@@ -252,6 +252,29 @@
|
|
| 252 |
]
|
| 253 |
}
|
| 254 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
"lighton-ocr.py": {
|
| 256 |
"model_id": "lightonai/LightOnOCR-1B-1025",
|
| 257 |
"params": "1B",
|
|
|
|
| 1 |
{
|
| 2 |
"_meta": {
|
| 3 |
"description": "Machine-readable catalog of the OCR recipes in this directory: script -> model, params, backend, support level, the tested Jobs launch config (the script's [tool.hf-jobs] header), and what the model's own card claims about language coverage. Human-readable language notes: LANGUAGES.md. Language evidence levels, strongest first: per-language-benchmark | count-claim | named-list | multilingual-unspecified | english-only | not-stated | not-applicable. Claims come from model cards (compiled 2026-07-15) - treat as claims, not guarantees.",
|
| 4 |
+
"updated": "2026-10-30",
|
| 5 |
"run_pattern": "hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/<script> <input-dataset> <output-dataset> (hf CLI >= 1.32 reads image/flavor/secrets from the script's [tool.hf-jobs] header; add --timeout for long runs. Scripts without a `jobs` entry need --flavor/-s HF_TOKEN (and any --image in their docstring).)",
|
| 6 |
"support_levels": {
|
| 7 |
"core": "Maintained. Smoke-tested flagless on HF Jobs on 2026-09-23/24 with the pinned launch config in `jobs`.",
|
|
|
|
| 252 |
]
|
| 253 |
}
|
| 254 |
},
|
| 255 |
+
"xiaomi-ocr-0-saturate.py": {
|
| 256 |
+
"model_id": "xiaomi-research/Xiaomi-OCR-0",
|
| 257 |
+
"params": "0.8B",
|
| 258 |
+
"backend": "saturate (in-job vllm serve or SGLang + saturate pump)",
|
| 259 |
+
"image": "vllm/vllm-openai:v0.29.0",
|
| 260 |
+
"task": "ocr",
|
| 261 |
+
"output": "markdown + LaTeX + HTML tables",
|
| 262 |
+
"license": "apache-2.0",
|
| 263 |
+
"notes": "Single-stage whole-page mode. Card scores (96.83 OmniDocBench v1.6, 95.24 Real5, 87.94 Wild) come from Xiaomi's two-stage pipeline, which this recipe does not run. --engine sglang needs --image lmsysorg/sglang:v0.5.20-cu130. Measured on UFO scans: a10g-small 3.4 pages/s, rtx-pro-6000 9.7 pages/s, both about $0.08 per 1,000 pages excluding boot.",
|
| 264 |
+
"languages": {
|
| 265 |
+
"evidence": "not-stated"
|
| 266 |
+
},
|
| 267 |
+
"support": "experimental",
|
| 268 |
+
"support_note": "New on 2026-10-30; tested on one English scan collection only.",
|
| 269 |
+
"jobs": {
|
| 270 |
+
"image": "vllm/vllm-openai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10 |
+
# flavor = "a10g-small"
|
| 11 |
+
# timeout = "4h"
|
| 12 |
+
# secrets = ["HF_TOKEN"]
|
| 13 |
+
# ///
|
| 14 |
+
"""
|
| 15 |
+
Convert document images to markdown using Xiaomi-OCR-0 via saturate.
|
| 16 |
+
|
| 17 |
+
Whole-page parsing on an in-job vLLM or SGLang server, driven by the `saturate`
|
| 18 |
+
library: adaptive concurrency, resumable parquet output and durable error rows.
|
| 19 |
+
|
| 20 |
+
Run on HF Jobs. The script starts the server itself; its [tool.hf-jobs] header
|
| 21 |
+
declares the image that provides `vllm`, the hardware and the HF_TOKEN secret
|
| 22 |
+
(`hf` CLI 1.32+). Flags on the command line override the header:
|
| 23 |
+
|
| 24 |
+
hf jobs uv run --detach \\
|
| 25 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/xiaomi-ocr-0-saturate.py \\
|
| 26 |
+
<input-dataset> <output-dataset>
|
| 27 |
+
|
| 28 |
+
SGLang instead of vLLM, on the matching image:
|
| 29 |
+
|
| 30 |
+
hf jobs uv run --detach --image lmsysorg/sglang:v0.5.20-cu130 \\
|
| 31 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/xiaomi-ocr-0-saturate.py \\
|
| 32 |
+
<input-dataset> <output-dataset> --engine sglang
|
| 33 |
+
|
| 34 |
+
Smoke test first with --max-samples 3. For speed at the same cost per page, add
|
| 35 |
+
--flavor rtx-pro-6000.
|
| 36 |
+
|
| 37 |
+
Output: the output repo holds `data/part-*.parquet` with rows
|
| 38 |
+
`{id, markdown, raw, finish_reason, model, prompt_tokens, completion_tokens, error}`
|
| 39 |
+
keyed by the input row id (`--id-column`, or `<repo>:<config>:<split>:<000000000>` by
|
| 40 |
+
default). Read it with `saturate.read_output`, which keeps one row per id (a success over
|
| 41 |
+
an earlier error). `datasets.load_dataset(<output>, data_dir="data")` returns every
|
| 42 |
+
record, so after a --retry-errors run it also holds the old error rows: drop rows with an
|
| 43 |
+
`error` before you join back to the input on id. Re-running the same command skips
|
| 44 |
+
finished rows; --retry-errors re-admits failed ones. A corrupt image stops the run when
|
| 45 |
+
it is read (images are decoded as the dataset streams); remove that row and run again.
|
| 46 |
+
`finish_reason` = "length" marks a page that hit --max-tokens. Empty `markdown` with no `error` means the model returned no text,
|
| 47 |
+
which is the correct result for a blank page; greedy decoding would repeat it on retry.
|
| 48 |
+
|
| 49 |
+
Model: xiaomi-research/Xiaomi-OCR-0 (0.8B, Apache-2.0)
|
| 50 |
+
- Card scores (OmniDocBench v1.6 96.83, Real5 95.24, Wild 87.94) come from Xiaomi's
|
| 51 |
+
TWO-STAGE pipeline (PP-DocLayoutV3 layout, then per-region prompts). This recipe
|
| 52 |
+
runs the model's single-stage whole-page mode, so do not quote those scores for it.
|
| 53 |
+
- The card's document prompt, image before text, `enable_thinking=False`, greedy
|
| 54 |
+
decoding, and images fitted to 2048 px on the long edge and sent as PNG
|
| 55 |
+
(skills/xiaomi-ocr/mcp_ocr_server.py `_chat`, evaluation_pipeline/cropping.py).
|
| 56 |
+
- Post-processing as upstream's `finalize_document`: repeated-tail cleanup, math
|
| 57 |
+
delimiters to `$`/`$$`, OTSL tables to HTML. The model's text is kept in `raw`.
|
| 58 |
+
- Deliberate deviation: the card and MCP server use max_tokens 4096, which truncates
|
| 59 |
+
dense pages. Upstream's whole-page evaluation (evaluation_pipeline/e2e_img2md.py) uses
|
| 60 |
+
16384 on the model's full context. This recipe serves the 16384 context from the repo
|
| 61 |
+
README, to keep KV memory small, so the default is 12000: the most that context leaves
|
| 62 |
+
after a worst-case 2048x2048 page (about 4200 image tokens). Lower it with --max-tokens.
|
| 63 |
+
- Deliberate deviation: upstream's evaluation re-requests pages that its repetition
|
| 64 |
+
guard flags (--retry-repetitive, presence penalty 1.5). This recipe does not. It only
|
| 65 |
+
trims a repeated tail, so a page where the model loops keeps the looped text.
|
| 66 |
+
- Upstream behaviour kept: a paragraph (text between blank lines) that holds an OTSL
|
| 67 |
+
table tag is replaced by the converted table, so text in the same paragraph is lost.
|
| 68 |
+
`raw` keeps the model's full output.
|
| 69 |
+
|
| 70 |
+
The SERVING dict below is the per-model tuning prior. Agents can `ast.literal_eval`
|
| 71 |
+
it without running the script; the script itself consumes it.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
import argparse
|
| 75 |
+
import base64
|
| 76 |
+
import io
|
| 77 |
+
import os
|
| 78 |
+
import re
|
| 79 |
+
import shutil
|
| 80 |
+
import subprocess
|
| 81 |
+
import sys
|
| 82 |
+
from dataclasses import dataclass
|
| 83 |
+
|
| 84 |
+
# Serving starting values for xiaomi-research/Xiaomi-OCR-0. Per-value provenance:
|
| 85 |
+
# - context 16384: the repo README's `vllm serve --max-model-len` and SGLang
|
| 86 |
+
# `--context-length` value, verbatim.
|
| 87 |
+
# - vllm_args cache/mm flags: house OCR defaults (see SERVING.md).
|
| 88 |
+
# - max_tokens 12000: house choice, see the docstring. Upstream sends 4096 (card, MCP)
|
| 89 |
+
# and 16384 in its whole-page evaluation, on the full model context.
|
| 90 |
+
# - temperature, top_p, presence_penalty, repetition_penalty: mcp_ocr_server.py `_chat`.
|
| 91 |
+
# - max_edge 2048: evaluation_pipeline/cropping.py MAX_IMAGE_EDGE.
|
| 92 |
+
# - window: saturate's default Auto(). Receipts below; a fixed cap only slowed large GPUs.
|
| 93 |
+
# - prepare_workers: threads for PNG encoding, sized from CPU_CORES (set by HF Jobs).
|
| 94 |
+
# Throughput receipts on UFO scans, vLLM, excluding boot (2026-10-30):
|
| 95 |
+
# a10g-small 3.4 pages/s, rtx-pro-6000 9.7 pages/s, both about $0.08 per 1,000 pages.
|
| 96 |
+
# - images: vLLM pin matches ovis-ocr2.py (same Qwen3_5 arch); SGLang pin matches
|
| 97 |
+
# unlimited-ocr2.py. Move them forward once a newer image passes a smoke test.
|
| 98 |
+
SERVING = {
|
| 99 |
+
"model": "xiaomi-research/Xiaomi-OCR-0",
|
| 100 |
+
"images": {"vllm": "vllm/vllm-openai:v0.29.0", "sglang": "lmsysorg/sglang:v0.5.20-cu130"},
|
| 101 |
+
"context": 16384,
|
| 102 |
+
"vllm_args": [
|
| 103 |
+
"--limit-mm-per-prompt", '{"image": 1}',
|
| 104 |
+
"--mm-processor-cache-gb", "0",
|
| 105 |
+
"--no-enable-prefix-caching",
|
| 106 |
+
],
|
| 107 |
+
"max_tokens": 12000,
|
| 108 |
+
"temperature": 0.0,
|
| 109 |
+
"top_p": 0.8,
|
| 110 |
+
"presence_penalty": 0.0,
|
| 111 |
+
"repetition_penalty": 1.0,
|
| 112 |
+
"max_edge": 2048,
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
# Card "Task prompts" table, Document row, verbatim.
|
| 116 |
+
OCR_PROMPT = (
|
| 117 |
+
"Extract all information from the main body of the document image and represent it "
|
| 118 |
+
"in markdown format, ignoring headers and footers. Tables should be expressed in OTSL "
|
| 119 |
+
"format, formulas in the document should be represented using LATEX format, and the "
|
| 120 |
+
"parsing should be organized according to the reading order."
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def to_pil(value):
|
| 125 |
+
from PIL import Image
|
| 126 |
+
|
| 127 |
+
if isinstance(value, Image.Image):
|
| 128 |
+
return value
|
| 129 |
+
if isinstance(value, dict) and value.get("bytes"):
|
| 130 |
+
return Image.open(io.BytesIO(value["bytes"]))
|
| 131 |
+
if isinstance(value, (bytes, bytearray)):
|
| 132 |
+
return Image.open(io.BytesIO(value))
|
| 133 |
+
raise ValueError(f"unsupported image value: {type(value)}")
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def encode_image(value, max_edge: int) -> str:
|
| 137 |
+
"""RGB-convert, fit within max_edge keeping aspect ratio, return base64 PNG."""
|
| 138 |
+
from PIL import Image
|
| 139 |
+
|
| 140 |
+
img = to_pil(value).convert("RGB")
|
| 141 |
+
img.thumbnail((max_edge, max_edge), Image.Resampling.LANCZOS)
|
| 142 |
+
buf = io.BytesIO()
|
| 143 |
+
img.save(buf, format="PNG")
|
| 144 |
+
return base64.b64encode(buf.getvalue()).decode()
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# Vendored from github.com/xiaomi-research/Xiaomi-OCR-0 at b1a9bb4 (Apache-2.0,
|
| 148 |
+
# Copyright 2026 Xiaomi Corporation): postprocess/otsl.py and postprocess/document.py.
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
ROW_BREAK = "<nl>"
|
| 152 |
+
CELL = "<fcel>"
|
| 153 |
+
EMPTY = "<ecel>"
|
| 154 |
+
LEFT = "<lcel>"
|
| 155 |
+
UP = "<ucel>"
|
| 156 |
+
BOTH = "<xcel>"
|
| 157 |
+
|
| 158 |
+
ALL_TAGS = (CELL, EMPTY, LEFT, UP, BOTH, ROW_BREAK)
|
| 159 |
+
TAG_RE = re.compile("(" + "|".join(re.escape(tag) for tag in ALL_TAGS) + ")")
|
| 160 |
+
|
| 161 |
+
ORIGIN_TAGS = frozenset({CELL, EMPTY})
|
| 162 |
+
RIGHT_CONTINUATION = frozenset({LEFT, BOTH})
|
| 163 |
+
DOWN_CONTINUATION = frozenset({UP, BOTH})
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
@dataclass
|
| 167 |
+
class Cell:
|
| 168 |
+
"""A resolved cell placed on the rectangular grid."""
|
| 169 |
+
|
| 170 |
+
text: str
|
| 171 |
+
row: int
|
| 172 |
+
column: int
|
| 173 |
+
rowspan: int = 1
|
| 174 |
+
colspan: int = 1
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _tag_of(chunk: str) -> str:
|
| 178 |
+
match = TAG_RE.match(chunk)
|
| 179 |
+
return match.group(0) if match else ""
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def _split_chunks(line: str) -> list[str]:
|
| 183 |
+
"""Split a row into chunks, each holding one tag plus the text after it."""
|
| 184 |
+
starts = [match.start() for match in TAG_RE.finditer(line)]
|
| 185 |
+
ends = starts[1:] + [len(line)]
|
| 186 |
+
return [line[start:end] for start, end in zip(starts, ends)]
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _required_width(chunks: list[str]) -> int:
|
| 190 |
+
"""Number of leading cells a row must keep to preserve its last content."""
|
| 191 |
+
width = 0
|
| 192 |
+
for position, chunk in enumerate(chunks, start=1):
|
| 193 |
+
if _tag_of(chunk) == CELL:
|
| 194 |
+
width = position
|
| 195 |
+
return width
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def _target_width(rows: list[list[str]]) -> int:
|
| 199 |
+
"""Pick one cell count every row is padded or truncated to.
|
| 200 |
+
|
| 201 |
+
Every row must keep at least the cells it declared content for, and the
|
| 202 |
+
cheapest width balances the total amount of truncation and padding.
|
| 203 |
+
"""
|
| 204 |
+
lower = max(_required_width(row) for row in rows)
|
| 205 |
+
upper = max(len(row) for row in rows)
|
| 206 |
+
best_width = upper
|
| 207 |
+
best_cost = None
|
| 208 |
+
for width in range(lower, upper + 1):
|
| 209 |
+
cost = sum(abs(len(row) - width) for row in rows)
|
| 210 |
+
if best_cost is None or cost < best_cost:
|
| 211 |
+
best_width = width
|
| 212 |
+
best_cost = cost
|
| 213 |
+
return best_width
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def pad_rows(otsl: str) -> str:
|
| 217 |
+
"""Give every row the same cell count so the grid can be indexed."""
|
| 218 |
+
text = otsl.strip()
|
| 219 |
+
if ROW_BREAK not in text:
|
| 220 |
+
return text + ROW_BREAK
|
| 221 |
+
|
| 222 |
+
rows = []
|
| 223 |
+
for line in text.split(ROW_BREAK):
|
| 224 |
+
chunks = _split_chunks(line)
|
| 225 |
+
if chunks:
|
| 226 |
+
rows.append(chunks)
|
| 227 |
+
if not rows:
|
| 228 |
+
return ROW_BREAK
|
| 229 |
+
|
| 230 |
+
width = _target_width(rows)
|
| 231 |
+
padded = []
|
| 232 |
+
for chunks in rows:
|
| 233 |
+
fixed = chunks[:width]
|
| 234 |
+
fixed += [EMPTY] * (width - len(fixed))
|
| 235 |
+
padded.append("".join(fixed))
|
| 236 |
+
return ROW_BREAK.join(padded) + ROW_BREAK
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def parse_grid(otsl: str) -> tuple[list[list[str]], list[list[str]]]:
|
| 240 |
+
"""Return the padded table as parallel tag and text grids."""
|
| 241 |
+
tag_rows: list[list[str]] = []
|
| 242 |
+
text_rows: list[list[str]] = []
|
| 243 |
+
|
| 244 |
+
for line in otsl.split(ROW_BREAK):
|
| 245 |
+
chunks = _split_chunks(line)
|
| 246 |
+
if not chunks:
|
| 247 |
+
continue
|
| 248 |
+
tags = []
|
| 249 |
+
texts = []
|
| 250 |
+
for chunk in chunks:
|
| 251 |
+
tag = _tag_of(chunk)
|
| 252 |
+
tags.append(tag)
|
| 253 |
+
texts.append(chunk[len(tag):] if tag == CELL else "")
|
| 254 |
+
tag_rows.append(tags)
|
| 255 |
+
text_rows.append(texts)
|
| 256 |
+
|
| 257 |
+
width = max((len(row) for row in tag_rows), default=0)
|
| 258 |
+
for tags, texts in zip(tag_rows, text_rows):
|
| 259 |
+
tags += [EMPTY] * (width - len(tags))
|
| 260 |
+
texts += [""] * (width - len(texts))
|
| 261 |
+
return tag_rows, text_rows
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def resolve_cells(
|
| 265 |
+
tag_rows: list[list[str]], text_rows: list[list[str]]
|
| 266 |
+
) -> list[Cell]:
|
| 267 |
+
"""Turn origin tags into cells, measuring spans from the continuation tags."""
|
| 268 |
+
height = len(tag_rows)
|
| 269 |
+
cells: list[Cell] = []
|
| 270 |
+
|
| 271 |
+
for row_index, tags in enumerate(tag_rows):
|
| 272 |
+
for column, tag in enumerate(tags):
|
| 273 |
+
if tag not in ORIGIN_TAGS:
|
| 274 |
+
continue
|
| 275 |
+
|
| 276 |
+
colspan = 1
|
| 277 |
+
while (
|
| 278 |
+
column + colspan < len(tags)
|
| 279 |
+
and tags[column + colspan] in RIGHT_CONTINUATION
|
| 280 |
+
):
|
| 281 |
+
colspan += 1
|
| 282 |
+
|
| 283 |
+
rowspan = 1
|
| 284 |
+
while (
|
| 285 |
+
row_index + rowspan < height
|
| 286 |
+
and column < len(tag_rows[row_index + rowspan])
|
| 287 |
+
and tag_rows[row_index + rowspan][column] in DOWN_CONTINUATION
|
| 288 |
+
):
|
| 289 |
+
rowspan += 1
|
| 290 |
+
|
| 291 |
+
text = text_rows[row_index][column] if tag == CELL else ""
|
| 292 |
+
cells.append(
|
| 293 |
+
Cell(
|
| 294 |
+
text=text.strip(),
|
| 295 |
+
row=row_index,
|
| 296 |
+
column=column,
|
| 297 |
+
rowspan=rowspan,
|
| 298 |
+
colspan=colspan,
|
| 299 |
+
)
|
| 300 |
+
)
|
| 301 |
+
return cells
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def render_html(cells: list[Cell], num_rows: int, num_cols: int) -> str:
|
| 305 |
+
"""Render resolved cells as an HTML table element.
|
| 306 |
+
|
| 307 |
+
Layout is walked column by column, so every row emits exactly one cell per
|
| 308 |
+
grid column and the result stays a well-formed table even when the input
|
| 309 |
+
OTSL contradicts itself. Spans are measured against the ownership grid, so
|
| 310 |
+
a span never claims a position owned by another cell.
|
| 311 |
+
"""
|
| 312 |
+
if not cells:
|
| 313 |
+
return ""
|
| 314 |
+
|
| 315 |
+
grid: list[list[Cell | None]] = [
|
| 316 |
+
[None] * num_cols for _ in range(num_rows)
|
| 317 |
+
]
|
| 318 |
+
for cell in cells:
|
| 319 |
+
for row in range(cell.row, min(cell.row + cell.rowspan, num_rows)):
|
| 320 |
+
for column in range(cell.column, min(cell.column + cell.colspan, num_cols)):
|
| 321 |
+
if row >= 0 and column >= 0:
|
| 322 |
+
grid[row][column] = cell
|
| 323 |
+
|
| 324 |
+
covered_until: dict[int, int] = {}
|
| 325 |
+
parts = []
|
| 326 |
+
for row in range(num_rows):
|
| 327 |
+
parts.append("<tr>")
|
| 328 |
+
column = 0
|
| 329 |
+
while column < num_cols:
|
| 330 |
+
if covered_until.get(column, 0) > row:
|
| 331 |
+
column += 1
|
| 332 |
+
continue
|
| 333 |
+
|
| 334 |
+
cell = grid[row][column]
|
| 335 |
+
if cell is None or cell.row != row or cell.column != column:
|
| 336 |
+
# A continuation tag with no origin of its own: keep the column
|
| 337 |
+
# so the row still spans the full grid width.
|
| 338 |
+
parts.append("<td></td>")
|
| 339 |
+
column += 1
|
| 340 |
+
continue
|
| 341 |
+
|
| 342 |
+
colspan = 1
|
| 343 |
+
while (
|
| 344 |
+
column + colspan < num_cols
|
| 345 |
+
and grid[row][column + colspan] is cell
|
| 346 |
+
):
|
| 347 |
+
colspan += 1
|
| 348 |
+
|
| 349 |
+
rowspan = 1
|
| 350 |
+
while row + rowspan < num_rows and all(
|
| 351 |
+
grid[row + rowspan][offset] is cell
|
| 352 |
+
for offset in range(column, column + colspan)
|
| 353 |
+
):
|
| 354 |
+
rowspan += 1
|
| 355 |
+
|
| 356 |
+
attributes = ""
|
| 357 |
+
if rowspan > 1:
|
| 358 |
+
attributes += f' rowspan="{rowspan}"'
|
| 359 |
+
if colspan > 1:
|
| 360 |
+
attributes += f' colspan="{colspan}"'
|
| 361 |
+
parts.append(f"<td{attributes}>{cell.text}</td>")
|
| 362 |
+
|
| 363 |
+
for offset in range(column, column + colspan):
|
| 364 |
+
covered_until[offset] = max(
|
| 365 |
+
covered_until.get(offset, 0), row + rowspan
|
| 366 |
+
)
|
| 367 |
+
column += colspan
|
| 368 |
+
parts.append("</tr>")
|
| 369 |
+
return "<table>" + "".join(parts) + "</table>"
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def convert_otsl_to_html(otsl_content: str) -> str:
|
| 373 |
+
"""Convert an OTSL table into an HTML ``<table>`` element."""
|
| 374 |
+
if not isinstance(otsl_content, str):
|
| 375 |
+
raise TypeError("otsl_content must be a string")
|
| 376 |
+
|
| 377 |
+
tag_rows, text_rows = parse_grid(pad_rows(otsl_content))
|
| 378 |
+
cells = resolve_cells(tag_rows, text_rows)
|
| 379 |
+
num_rows = len(tag_rows)
|
| 380 |
+
num_cols = max((len(row) for row in tag_rows), default=0)
|
| 381 |
+
return render_html(cells, num_rows, num_cols)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
OTSL_TAG_RE = re.compile(r"<(?:fcel|ecel|nl|lcel|ucel|xcel)>")
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def postprocess_math_delimiters(markdown: str) -> str:
|
| 388 |
+
"""Convert LaTeX delimiters in whole-page markdown to markdown math delimiters."""
|
| 389 |
+
if not markdown:
|
| 390 |
+
return markdown
|
| 391 |
+
markdown = markdown.replace("\\[\\[", "\\[").replace("\\]\\]", "\\]")
|
| 392 |
+
markdown = re.sub(
|
| 393 |
+
r"\$\$?\s*\\\[\s*(.*?)\s*\\\]\s*\$\$?",
|
| 394 |
+
r" $$ \1 $$ ",
|
| 395 |
+
markdown,
|
| 396 |
+
flags=re.DOTALL,
|
| 397 |
+
)
|
| 398 |
+
markdown = re.sub(
|
| 399 |
+
r"\$\s*\\\(\s*(.*?)\s*\\\)\s*\$",
|
| 400 |
+
r" $ \1 $",
|
| 401 |
+
markdown,
|
| 402 |
+
flags=re.DOTALL,
|
| 403 |
+
)
|
| 404 |
+
markdown = re.sub(
|
| 405 |
+
r"\\\[\s*(.*?)\s*\\\]",
|
| 406 |
+
r" $$ \1 $$ ",
|
| 407 |
+
markdown,
|
| 408 |
+
flags=re.DOTALL,
|
| 409 |
+
)
|
| 410 |
+
markdown = re.sub(
|
| 411 |
+
r"\\\(\s*(.*?)\s*\\\)",
|
| 412 |
+
r" $ \1 $",
|
| 413 |
+
markdown,
|
| 414 |
+
flags=re.DOTALL,
|
| 415 |
+
)
|
| 416 |
+
return markdown
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def _split_markdown_blocks(markdown: str):
|
| 420 |
+
parts = re.split(r"(\n\s*\n)", markdown)
|
| 421 |
+
blocks = []
|
| 422 |
+
for i in range(0, len(parts), 2):
|
| 423 |
+
text = parts[i]
|
| 424 |
+
sep = parts[i + 1] if i + 1 < len(parts) else ""
|
| 425 |
+
blocks.append([text, sep])
|
| 426 |
+
return blocks
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def postprocess_otsl_tables(markdown: str) -> str:
|
| 430 |
+
"""Convert OTSL-looking markdown blocks to HTML tables; keep original on failure."""
|
| 431 |
+
if not markdown or not OTSL_TAG_RE.search(markdown):
|
| 432 |
+
return markdown
|
| 433 |
+
|
| 434 |
+
blocks = _split_markdown_blocks(markdown)
|
| 435 |
+
in_fence = False
|
| 436 |
+
converted = []
|
| 437 |
+
for text, sep in blocks:
|
| 438 |
+
stripped = text.strip()
|
| 439 |
+
fence_count = stripped.count("```")
|
| 440 |
+
should_skip = in_fence
|
| 441 |
+
if fence_count % 2 == 1:
|
| 442 |
+
in_fence = not in_fence
|
| 443 |
+
should_skip = True
|
| 444 |
+
|
| 445 |
+
if not should_skip and OTSL_TAG_RE.search(stripped):
|
| 446 |
+
try:
|
| 447 |
+
html = convert_otsl_to_html(stripped)
|
| 448 |
+
if html:
|
| 449 |
+
text = html
|
| 450 |
+
except Exception:
|
| 451 |
+
pass
|
| 452 |
+
converted.append(text + sep)
|
| 453 |
+
return "".join(converted)
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def _clean_truncated_repeats(
|
| 457 |
+
text: str,
|
| 458 |
+
min_text_len: int = 8000,
|
| 459 |
+
max_period: int = 200,
|
| 460 |
+
min_period: int = 1,
|
| 461 |
+
min_repeat_chars: int = 100,
|
| 462 |
+
min_repeat_times: int = 5,
|
| 463 |
+
) -> str:
|
| 464 |
+
"""Trim a degenerate repeated tail, keeping one period plus the remainder."""
|
| 465 |
+
n = len(text)
|
| 466 |
+
if n < min_text_len:
|
| 467 |
+
return text
|
| 468 |
+
|
| 469 |
+
max_period = min(max_period, n - 1)
|
| 470 |
+
for unit_len in range(min_period, max_period + 1):
|
| 471 |
+
if text[n - 1] != text[n - 1 - unit_len]:
|
| 472 |
+
continue
|
| 473 |
+
|
| 474 |
+
match_len = 1
|
| 475 |
+
idx = n - 2
|
| 476 |
+
while idx >= unit_len and text[idx] == text[idx - unit_len]:
|
| 477 |
+
match_len += 1
|
| 478 |
+
idx -= 1
|
| 479 |
+
|
| 480 |
+
total_len = match_len + unit_len
|
| 481 |
+
repeat_times = total_len // unit_len
|
| 482 |
+
tail_len = total_len % unit_len
|
| 483 |
+
|
| 484 |
+
if repeat_times >= min_repeat_times and total_len >= min_repeat_chars:
|
| 485 |
+
return text[: n - total_len + unit_len] + text[n - tail_len:]
|
| 486 |
+
|
| 487 |
+
return text
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def finalize_document(text: str) -> str:
|
| 491 |
+
"""Upstream's whole-page post-processing order (postprocess/document.py)."""
|
| 492 |
+
return postprocess_otsl_tables(postprocess_math_delimiters(_clean_truncated_repeats(text)))
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def sglang_command() -> list[str]:
|
| 496 |
+
"""Return the SGLang server command, using the image's Python rather than this script's venv."""
|
| 497 |
+
# The SGLang image keeps sglang in its own venv, first on PATH; `uv run` puts
|
| 498 |
+
# this script's venv in front, so look past it.
|
| 499 |
+
own_bin = os.path.realpath(os.path.join(sys.prefix, "bin"))
|
| 500 |
+
path = os.pathsep.join(
|
| 501 |
+
p for p in os.environ.get("PATH", "").split(os.pathsep) if os.path.realpath(p) != own_bin
|
| 502 |
+
)
|
| 503 |
+
python = shutil.which("python3", path=path)
|
| 504 |
+
found = python and subprocess.run([python, "-c", "import sglang"], check=False, capture_output=True).returncode == 0
|
| 505 |
+
if not found:
|
| 506 |
+
sys.exit(f"--engine sglang needs sglang: add --image {SERVING['images']['sglang']} to hf jobs uv run.")
|
| 507 |
+
return [
|
| 508 |
+
python, "-m", "sglang.launch_server", "--model-path", SERVING["model"],
|
| 509 |
+
"--context-length", str(SERVING["context"]), "--enable-metrics",
|
| 510 |
+
"--host", "127.0.0.1", "--port", "8000",
|
| 511 |
+
] # fmt: skip
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def main():
|
| 515 |
+
ap = argparse.ArgumentParser(description="Xiaomi-OCR-0 batch OCR via saturate")
|
| 516 |
+
ap.add_argument("input_dataset", help="Input dataset repo id (rows with an image column)")
|
| 517 |
+
ap.add_argument("output_dataset", help="Output dataset repo id (created if missing)")
|
| 518 |
+
ap.add_argument("--engine", choices=["vllm", "sglang"], default="vllm",
|
| 519 |
+
help="Serving engine; sglang also needs the SGLang --image (see docstring)")
|
| 520 |
+
ap.add_argument("--image-column", default="image")
|
| 521 |
+
ap.add_argument("--config", default=None, help="Dataset config name")
|
| 522 |
+
ap.add_argument("--split", default="train")
|
| 523 |
+
ap.add_argument("--id-column", default=None,
|
| 524 |
+
help="Column to use as row id (default: split-index ids)")
|
| 525 |
+
ap.add_argument("--max-samples", "--limit", dest="limit", type=int, default=None,
|
| 526 |
+
help="Process only the first N rows (smoke test)")
|
| 527 |
+
ap.add_argument("--max-tokens", type=int, default=SERVING["max_tokens"],
|
| 528 |
+
help="Output cap; must leave room for the image in the 16384 context")
|
| 529 |
+
ap.add_argument("--retry-errors", action="store_true",
|
| 530 |
+
help="Re-admit rows whose only record is an error row")
|
| 531 |
+
args = ap.parse_args()
|
| 532 |
+
|
| 533 |
+
if args.max_tokens < 1:
|
| 534 |
+
ap.error("--max-tokens must be at least 1")
|
| 535 |
+
if args.max_tokens > SERVING["max_tokens"]:
|
| 536 |
+
ap.error(f"--max-tokens above {SERVING['max_tokens']} can overflow the {SERVING['context']} context")
|
| 537 |
+
|
| 538 |
+
import pyarrow as pa
|
| 539 |
+
from saturate import Engine, dataset_rows, pump
|
| 540 |
+
|
| 541 |
+
if args.id_column is None:
|
| 542 |
+
ids = "index"
|
| 543 |
+
elif args.id_column in ("index", "content"):
|
| 544 |
+
# saturate reads these two names as id strategies, so a column with one of them
|
| 545 |
+
# needs a callable. It returns the raw value, so saturate still refuses a null id.
|
| 546 |
+
ids = lambda example: example[args.id_column]
|
| 547 |
+
else:
|
| 548 |
+
ids = args.id_column
|
| 549 |
+
|
| 550 |
+
rows = dataset_rows(
|
| 551 |
+
args.input_dataset, config=args.config, split=args.split,
|
| 552 |
+
columns=[args.image_column], ids=ids, limit=args.limit,
|
| 553 |
+
)
|
| 554 |
+
|
| 555 |
+
def to_request(row):
|
| 556 |
+
b64 = encode_image(row[args.image_column], SERVING["max_edge"])
|
| 557 |
+
return {
|
| 558 |
+
"model": SERVING["model"],
|
| 559 |
+
"messages": [{"role": "user", "content": [
|
| 560 |
+
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}},
|
| 561 |
+
{"type": "text", "text": OCR_PROMPT},
|
| 562 |
+
]}],
|
| 563 |
+
"max_tokens": args.max_tokens,
|
| 564 |
+
"temperature": SERVING["temperature"],
|
| 565 |
+
"top_p": SERVING["top_p"],
|
| 566 |
+
"presence_penalty": SERVING["presence_penalty"],
|
| 567 |
+
"repetition_penalty": SERVING["repetition_penalty"],
|
| 568 |
+
"chat_template_kwargs": {"enable_thinking": False},
|
| 569 |
+
}
|
| 570 |
+
|
| 571 |
+
# Declared, so a part holding only error rows has the same columns as the rest
|
| 572 |
+
# (datasets.load_dataset reads every part with one schema).
|
| 573 |
+
schema = pa.schema([
|
| 574 |
+
("id", pa.string()), ("error", pa.string()), ("markdown", pa.string()), ("raw", pa.string()),
|
| 575 |
+
("finish_reason", pa.string()), ("model", pa.string()),
|
| 576 |
+
("prompt_tokens", pa.int64()), ("completion_tokens", pa.int64()),
|
| 577 |
+
]) # fmt: skip
|
| 578 |
+
|
| 579 |
+
def parse(row, body):
|
| 580 |
+
choice = body["choices"][0]
|
| 581 |
+
raw = choice["message"]["content"].strip()
|
| 582 |
+
usage = body.get("usage") or {}
|
| 583 |
+
return {
|
| 584 |
+
"markdown": finalize_document(raw),
|
| 585 |
+
"raw": raw,
|
| 586 |
+
"finish_reason": choice.get("finish_reason"),
|
| 587 |
+
"model": SERVING["model"],
|
| 588 |
+
"prompt_tokens": usage.get("prompt_tokens"),
|
| 589 |
+
"completion_tokens": usage.get("completion_tokens"),
|
| 590 |
+
}
|
| 591 |
+
|
| 592 |
+
if args.engine == "sglang":
|
| 593 |
+
engine = Engine(SERVING["model"], engine="sglang", cmd=sglang_command())
|
| 594 |
+
else:
|
| 595 |
+
extra = ["--max-model-len", str(SERVING["context"]), *SERVING["vllm_args"]]
|
| 596 |
+
engine = Engine(SERVING["model"], engine="vllm", extra_args=extra)
|
| 597 |
+
|
| 598 |
+
output = f"hf://datasets/{args.output_dataset}/data"
|
| 599 |
+
with engine as endpoint:
|
| 600 |
+
stats = pump(rows, to_request, parse, endpoint, output,
|
| 601 |
+
prepare_workers=int(float(os.environ.get("CPU_CORES") or "4")),
|
| 602 |
+
retry_errors=args.retry_errors, schema=schema)
|
| 603 |
+
|
| 604 |
+
print(f"https://huggingface.co/datasets/{args.output_dataset} "
|
| 605 |
+
f"({stats.rows_processed} ok, {stats.rows_failed} error rows)", file=sys.stderr)
|
| 606 |
+
print("XIAOMI_OCR_0_SATURATE " + stats.to_json(), flush=True)
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
if __name__ == "__main__":
|
| 610 |
+
main()
|