Sync from GitHub via hub-sync
Browse files- CLAUDE.md +24 -0
- LANGUAGES.md +1 -0
- README.md +1 -0
- images/minicpm-ocr/Dockerfile +44 -0
- images/minicpm-ocr/README.md +18 -0
- images/minicpm-ocr/sdk-requirements.lock +90 -0
- minicpm-ocr.py +644 -0
- models.json +30 -2
CLAUDE.md
CHANGED
|
@@ -95,6 +95,7 @@ Legend: ✅ production-ready · ⚠️ works only with a required pinned image
|
|
| 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 |
| `unlimited-ocr2-live.py` | 🧪+image | same | rtx-pro-6000 | experimental: minimal script + `--live-port` dashboard (streams the page being read) |
|
|
|
|
| 98 |
| `surya-ocr.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | offline backend inject; site-packages PYTHONPATH |
|
| 99 |
| `surya-ocr-bucket.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | bucket I/O; pin `surya-ocr==0.20.0` |
|
| 100 |
| `lift-extract.py` | ✅ | hf / vLLM | a100-large | schema-constrained extraction; naming gotcha |
|
|
@@ -169,6 +170,26 @@ hard scans) and belongs to **serving** — both engines read clean multi-page do
|
|
| 169 |
robust on hard/degraded scans**. Serving setup (SGLang pin `lmsysorg/sglang:v0.5.10.post1`, a100+flashinfer
|
| 170 |
— HF `h200` nodes fail with `CUDA error 802`) is in `serving-unlimited-ocr.md`.
|
| 171 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
### `unlimited-ocr2.py` / `unlimited-ocr2-saturate.py` — Baidu SGLang wheel, multi-page windows
|
| 173 |
v2 has no vLLM support; Baidu ships a custom SGLang wheel in the model repo. Its pins (torch 2.13.0,
|
| 174 |
transformers 5.12.1, flashinfer 0.6.18 cu13) match **`lmsysorg/sglang:v0.5.20`** exactly → `-cu130` image,
|
|
@@ -322,6 +343,9 @@ ARM wheels) — if a nightly-recipe install fails on resolution, wait and retry
|
|
| 322 |
|
| 323 |
## Change log
|
| 324 |
|
|
|
|
|
|
|
|
|
|
| 325 |
- **2026-10-27** — added `unlimited-ocr2.py` (minimal) and `unlimited-ocr2-saturate.py` (tuned, experimental)
|
| 326 |
for `baidu/Unlimited-OCR-2`: whole-document OCR in 16-page windows on Baidu's SGLang build, driven by
|
| 327 |
saturate (pinned `==0.2.0`). First recipes whose unit of work is a document, not a page; input is a
|
|
|
|
| 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 |
| `unlimited-ocr2-live.py` | 🧪+image | same | rtx-pro-6000 | experimental: minimal script + `--live-port` dashboard (streams the page being read) |
|
| 98 |
+
| `minicpm-ocr.py` | 🧪+image | in-job vLLM nightly + minicpm-ocr SDK on `cr.hf.co/davanstrien/minicpm-ocr` | a10g-large | vendor pipeline; custom public image; dataset **or** bucket I/O (bucketbag), `markdown_status` |
|
| 99 |
| `surya-ocr.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | offline backend inject; site-packages PYTHONPATH |
|
| 100 |
| `surya-ocr-bucket.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | bucket I/O; pin `surya-ocr==0.20.0` |
|
| 101 |
| `lift-extract.py` | ✅ | hf / vLLM | a100-large | schema-constrained extraction; naming gotcha |
|
|
|
|
| 170 |
robust on hard/degraded scans**. Serving setup (SGLang pin `lmsysorg/sglang:v0.5.10.post1`, a100+flashinfer
|
| 171 |
— HF `h200` nodes fail with `CUDA error 802`) is in `serving-unlimited-ocr.md`.
|
| 172 |
|
| 173 |
+
### `minicpm-ocr.py` — vendor SDK pipeline on a custom `cr.hf.co` image
|
| 174 |
+
MiniCPM-OCR 1.0 is a region reader: OpenBMB's SDK runs PP-DocLayoutV3, crops regions, prompts each by
|
| 175 |
+
type and assembles Markdown. The recipe runs that SDK unchanged (separate venv `/opt/sdk`, as OpenBMB
|
| 176 |
+
require) against `vllm serve` started in the job. Measured/learned 2026-10-27:
|
| 177 |
+
- `MiniCPMOcrForConditionalGeneration` is in vLLM main (18343393b4, 23 Oct) but not in v0.32.0, and
|
| 178 |
+
OpenBMB's install builds vLLM from source (~40 min). The image uses nightly 5d35ce3 pinned by digest
|
| 179 |
+
instead; Dockerfile + digest in `images/minicpm-ocr/`. Move to a stock tag when a release has the arch.
|
| 180 |
+
- pip warns `transformers 5.21.0.dev0` (OpenBMB's pin 549e5b4) violates vLLM's `<5.21.0` (a pre-release
|
| 181 |
+
of 5.21.0 is excluded by `<5.21.0`); vLLM serves the model anyway.
|
| 182 |
+
- The SDK's default layout path is `${ASSETS_DIR}/PP-DocLayoutV3`, not the docs' `models/PP-DocLayoutV3_infer`;
|
| 183 |
+
the recipe passes the baked path explicitly. The layout tar is sha256-checked at build time.
|
| 184 |
+
- Built with kaniko on a `cpu-upgrade` Job (~20 min); container repo creation needed the stored `cli` token
|
| 185 |
+
(the OAuth login gets 403). `l4x1` had no capacity on 27 Oct; smoke ran on `a10g-large`.
|
| 186 |
+
- The SDK reads a folder: the recipe writes each batch as `{i:06d}.png` and reads `output/{i:06d}.md` back.
|
| 187 |
+
- The SDK writes a `.md` even when regions fail (empty for a failed text region); the page status lives in
|
| 188 |
+
`per_page_metrics.jsonl` (`ok` / `partial_failed` / `failed`). The recipe reads it: dataset mode keeps it in
|
| 189 |
+
`markdown_status`; bucket mode writes only `ok` pages so a re-run retries the rest (Codex review, 27 Oct).
|
| 190 |
+
- vLLM runs in its own process group and is terminated → killed → reaped on every exit path; one bad
|
| 191 |
+
image or a failed SDK run marks its pages `error: ...` instead of losing finished batches.
|
| 192 |
+
|
| 193 |
### `unlimited-ocr2.py` / `unlimited-ocr2-saturate.py` — Baidu SGLang wheel, multi-page windows
|
| 194 |
v2 has no vLLM support; Baidu ships a custom SGLang wheel in the model repo. Its pins (torch 2.13.0,
|
| 195 |
transformers 5.12.1, flashinfer 0.6.18 cu13) match **`lmsysorg/sglang:v0.5.20`** exactly → `-cu130` image,
|
|
|
|
| 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/`).
|
| 349 |
- **2026-10-27** — added `unlimited-ocr2.py` (minimal) and `unlimited-ocr2-saturate.py` (tuned, experimental)
|
| 350 |
for `baidu/Unlimited-OCR-2`: whole-document OCR in 16-page windows on Baidu's SGLang build, driven by
|
| 351 |
saturate (pinned `==0.2.0`). First recipes whose unit of work is a document, not a page; input is a
|
LANGUAGES.md
CHANGED
|
@@ -20,6 +20,7 @@ _Sorted by strength of evidence, then coverage:_
|
|
| 20 |
| [Qianfan-OCR](https://huggingface.co/baidu/Qianfan-OCR) | 192 languages | Headline claim; no list or per-language numbers |
|
| 21 |
| [PaddleOCR-VL](https://huggingface.co/PaddlePaddle/PaddleOCR-VL) / [1.5](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.5) / [1.6](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.6) | 109 languages; 1.5 adds Tibetan + Bengali | Names scripts (Cyrillic, Arabic, Devanagari, Thai) and claims handwriting + historical documents; no per-language numbers |
|
| 22 |
| [PP-OCRv6](https://huggingface.co/collections/PaddlePaddle/pp-ocrv6) | 48 languages | Official card claim |
|
|
|
|
| 23 |
| [Nanonets-OCR2-3B](https://huggingface.co/nanonets/Nanonets-OCR2-3B) | 11 named + "many more" (incl. Arabic + CJK) | Illustrative list, no benchmark — but the only card claiming multilingual **handwriting** |
|
| 24 |
| [LightOnOCR-2-1B](https://huggingface.co/lightonai/LightOnOCR-2-1B) | 11 (9 European + zh/ja) | Declared, not benchmarked. [v1](https://huggingface.co/lightonai/LightOnOCR-1B-1025) is explicitly European/Latin-script only (9) |
|
| 25 |
| [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) | 8 (zh en fr es ru de ja ko) | Declared in card metadata only; no per-language evidence in the card body |
|
|
|
|
| 20 |
| [Qianfan-OCR](https://huggingface.co/baidu/Qianfan-OCR) | 192 languages | Headline claim; no list or per-language numbers |
|
| 21 |
| [PaddleOCR-VL](https://huggingface.co/PaddlePaddle/PaddleOCR-VL) / [1.5](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.5) / [1.6](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.6) | 109 languages; 1.5 adds Tibetan + Bengali | Names scripts (Cyrillic, Arabic, Devanagari, Thai) and claims handwriting + historical documents; no per-language numbers |
|
| 22 |
| [PP-OCRv6](https://huggingface.co/collections/PaddlePaddle/pp-ocrv6) | 48 languages | Official card claim |
|
| 23 |
+
| [MiniCPM-OCR 1.0](https://huggingface.co/openbmb/MiniCPM-OCR-1.0) | Chinese and English ("primary languages") | Card names two; no per-language numbers. Examples include historical scans |
|
| 24 |
| [Nanonets-OCR2-3B](https://huggingface.co/nanonets/Nanonets-OCR2-3B) | 11 named + "many more" (incl. Arabic + CJK) | Illustrative list, no benchmark — but the only card claiming multilingual **handwriting** |
|
| 25 |
| [LightOnOCR-2-1B](https://huggingface.co/lightonai/LightOnOCR-2-1B) | 11 (9 European + zh/ja) | Declared, not benchmarked. [v1](https://huggingface.co/lightonai/LightOnOCR-1B-1025) is explicitly European/Latin-script only (9) |
|
| 26 |
| [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) | 8 (zh en fr es ru de ja ko) | Declared in card metadata only; no per-language evidence in the card body |
|
README.md
CHANGED
|
@@ -89,6 +89,7 @@ These are the maintained recipes. Each one has a tested `[tool.hf-jobs]` header,
|
|
| 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 |
| [`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` |
|
|
|
|
| 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` |
|
| 93 |
| [`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` |
|
| 94 |
| [`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` |
|
| 95 |
| [`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` |
|
images/minicpm-ocr/Dockerfile
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MiniCPM-OCR 1.0 runtime for Hugging Face Jobs: cr.hf.co/davanstrien/minicpm-ocr
|
| 2 |
+
#
|
| 3 |
+
# - vLLM nightly 5d35ce3 (27 Oct 2026). MiniCPMOcrForConditionalGeneration landed in vLLM main on
|
| 4 |
+
# 23 Oct (18343393b4, the commit OpenBMB's install.sh builds from source) and is not in a
|
| 5 |
+
# release yet; this nightly is newer and also has DSpark speculative decoding.
|
| 6 |
+
# - transformers at OpenBMB's pin (549e5b4, "5.21.0.dev0"). pip reports it as outside the nightly's
|
| 7 |
+
# transformers>=5.16.1,<5.21.0 (a pre-release of 5.21.0 is excluded by <5.21.0); vLLM serves the
|
| 8 |
+
# model with it (smoke test, 27 Oct 2026).
|
| 9 |
+
# - The minicpm-ocr SDK (layout, crops, assembly) in its own venv at /opt/sdk, as OpenBMB's docs
|
| 10 |
+
# require (SDK and inference service in separate environments), with PaddlePaddle GPU for the
|
| 11 |
+
# PP-DocLayoutV3 layout model.
|
| 12 |
+
# - The layout model is baked in (sha256-checked) at $OCR_ASSETS_DIR, so a run never fetches it
|
| 13 |
+
# from Paddle's CDN. Model weights are not baked in: pull a pinned revision at run time.
|
| 14 |
+
FROM vllm/vllm-openai:nightly-5d35ce3934a7804b298559d2d99eec33792e1eb9@sha256:3431ebee919296f7a5f3604db353f639e1474a4c7ef37595e31de6699fd831a7
|
| 15 |
+
|
| 16 |
+
ARG TRANSFORMERS_COMMIT=549e5b410733fb50e8efbbe4aa585cb89f6478ea
|
| 17 |
+
ARG LAYOUT_URL=https://paddle-model-ecology.bj.bcebos.com/paddlex/official_inference_model/paddle3.0.0/PP-DocLayoutV3_infer.tar
|
| 18 |
+
ARG LAYOUT_SHA256=98b9bac88c80f6bc0fda7e0bfc2cae180020371c0b2edbb1eb498a70ace751b1
|
| 19 |
+
|
| 20 |
+
RUN python3 -m pip install --no-cache-dir \
|
| 21 |
+
"transformers @ https://github.com/huggingface/transformers/archive/${TRANSFORMERS_COMMIT}.tar.gz"
|
| 22 |
+
|
| 23 |
+
# sdk-requirements.lock is `uv pip freeze` of /opt/sdk in the published image (digest in README.md),
|
| 24 |
+
# so a rebuild installs the tested SDK environment rather than resolving it afresh.
|
| 25 |
+
COPY sdk-requirements.lock /tmp/sdk-requirements.lock
|
| 26 |
+
RUN python3 -m pip install --no-cache-dir uv==0.13.6 \
|
| 27 |
+
&& uv venv /opt/sdk --python 3.12 \
|
| 28 |
+
&& uv pip install --python /opt/sdk/bin/python --no-cache \
|
| 29 |
+
--extra-index-url https://www.paddlepaddle.org.cn/packages/stable/cu129/ --index-strategy unsafe-best-match \
|
| 30 |
+
-r /tmp/sdk-requirements.lock
|
| 31 |
+
|
| 32 |
+
ENV OCR_ASSETS_DIR=/opt/minicpm-ocr-assets
|
| 33 |
+
RUN mkdir -p ${OCR_ASSETS_DIR}/models \
|
| 34 |
+
&& curl -fsSL -o /tmp/layout.tar "${LAYOUT_URL}" \
|
| 35 |
+
&& echo "${LAYOUT_SHA256} /tmp/layout.tar" | sha256sum -c - \
|
| 36 |
+
&& tar -xf /tmp/layout.tar -C ${OCR_ASSETS_DIR}/models \
|
| 37 |
+
&& rm /tmp/layout.tar
|
| 38 |
+
|
| 39 |
+
# The SDK CLI is on PATH as `minicpmvocr`; vLLM stays the image's `vllm`.
|
| 40 |
+
RUN ln -s /opt/sdk/bin/minicpmvocr /usr/local/bin/minicpmvocr \
|
| 41 |
+
&& minicpmvocr --help > /dev/null
|
| 42 |
+
|
| 43 |
+
ENTRYPOINT []
|
| 44 |
+
CMD ["bash"]
|
images/minicpm-ocr/README.md
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# cr.hf.co/davanstrien/minicpm-ocr
|
| 2 |
+
|
| 3 |
+
Runtime image for [`../../minicpm-ocr.py`](../../minicpm-ocr.py), public on the Hugging Face
|
| 4 |
+
container registry: https://huggingface.co/containers/davanstrien/minicpm-ocr
|
| 5 |
+
|
| 6 |
+
| Tag | Digest |
|
| 7 |
+
|---|---|
|
| 8 |
+
| `1.0-vllm-5d35ce3` (also `latest`) | `sha256:2fb9a09980abecb3102b99b0685b57b4ecde22702b3a441c03fab22e30239aea` |
|
| 9 |
+
|
| 10 |
+
Built with kaniko on an HF CPU Job (`cpu-upgrade`, about 20 minutes),
|
| 11 |
+
pushed to `cr.hf.co`. The published digest was built before `sdk-requirements.lock` existed;
|
| 12 |
+
the lock is that image's `/opt/sdk` environment (`uv pip freeze`), so a rebuild reproduces it. Why a custom image: MiniCPM-OCR's architecture is in vLLM main but not in a
|
| 13 |
+
vLLM release yet, and the SDK needs PaddlePaddle in its own environment. Drop it for a stock
|
| 14 |
+
`vllm/vllm-openai` tag plus a pip-installed SDK once a vLLM release has the architecture.
|
| 15 |
+
|
| 16 |
+
Build note: pip warns that `transformers 5.21.0.dev0` does not satisfy vLLM's
|
| 17 |
+
`transformers<5.21.0` (a pre-release of 5.21.0 is excluded by `<5.21.0`). This is OpenBMB's pin;
|
| 18 |
+
vLLM serves the model with it (smoke test, 27 Oct 2026).
|
images/minicpm-ocr/sdk-requirements.lock
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
aistudio-sdk==0.3.9
|
| 2 |
+
annotated-types==0.8.0
|
| 3 |
+
anyio==4.15.1
|
| 4 |
+
bce-python-sdk==0.9.79
|
| 5 |
+
beautifulsoup4==4.15.0
|
| 6 |
+
certifi==2026.10.23
|
| 7 |
+
cffi==2.1.1
|
| 8 |
+
chardet==7.7.0
|
| 9 |
+
charset-normalizer==3.5.2
|
| 10 |
+
click==8.5.0
|
| 11 |
+
colorlog==6.12.0
|
| 12 |
+
crc32c==2.9.post0
|
| 13 |
+
cryptography==50.0.2
|
| 14 |
+
cuda-bindings==12.9.5
|
| 15 |
+
cuda-pathfinder==1.3.3
|
| 16 |
+
cuda-python==12.9.4
|
| 17 |
+
filelock==4.2.4
|
| 18 |
+
flatbuffers==25.12.19
|
| 19 |
+
fsspec==2026.9.0
|
| 20 |
+
future==1.0.0
|
| 21 |
+
h11==0.16.0
|
| 22 |
+
hf-xet==1.7.0
|
| 23 |
+
httpcore==1.0.9
|
| 24 |
+
httpcore2==2.16.0
|
| 25 |
+
httpx==0.28.1
|
| 26 |
+
httpx2==2.16.0
|
| 27 |
+
huggingface-hub==2.3.0
|
| 28 |
+
idna==3.20
|
| 29 |
+
imagesize==2.0.1
|
| 30 |
+
minicpm-ocr==1.0.1
|
| 31 |
+
modelscope==1.40.2
|
| 32 |
+
modelscope-hub==0.5.1
|
| 33 |
+
networkx==3.7
|
| 34 |
+
numpy==2.5.4
|
| 35 |
+
nvidia-cublas-cu12==12.9.0.13
|
| 36 |
+
nvidia-cuda-cccl-cu12==12.9.27
|
| 37 |
+
nvidia-cuda-cupti-cu12==12.9.19
|
| 38 |
+
nvidia-cuda-nvrtc-cu12==12.9.41
|
| 39 |
+
nvidia-cuda-runtime-cu12==12.9.37
|
| 40 |
+
nvidia-cudnn-cu12==9.9.0.52
|
| 41 |
+
nvidia-cufft-cu12==11.4.0.6
|
| 42 |
+
nvidia-cufile-cu12==1.14.0.30
|
| 43 |
+
nvidia-curand-cu12==10.3.10.19
|
| 44 |
+
nvidia-cusolver-cu12==11.7.4.40
|
| 45 |
+
nvidia-cusparse-cu12==12.5.9.5
|
| 46 |
+
nvidia-cusparselt-cu12==0.7.1
|
| 47 |
+
nvidia-nccl-cu12==2.27.3
|
| 48 |
+
nvidia-nvjitlink-cu12==12.9.41
|
| 49 |
+
nvidia-nvtx-cu12==12.9.19
|
| 50 |
+
onnxruntime==1.31.1
|
| 51 |
+
opencv-contrib-python==4.10.0.84
|
| 52 |
+
opt-einsum==3.3.0
|
| 53 |
+
packaging==26.3
|
| 54 |
+
paddleocr==3.4.1
|
| 55 |
+
paddlepaddle-gpu==3.3.0
|
| 56 |
+
paddlex==3.4.2
|
| 57 |
+
pandas==3.1.0
|
| 58 |
+
pillow==13.0.0
|
| 59 |
+
prettytable==3.18.0
|
| 60 |
+
protobuf==7.36.2
|
| 61 |
+
psutil==7.2.2
|
| 62 |
+
py-cpuinfo==9.0.0
|
| 63 |
+
pyclipper==1.4.0
|
| 64 |
+
pycparser==3.12
|
| 65 |
+
pycryptodome==4.2.0
|
| 66 |
+
pydantic==2.14.1
|
| 67 |
+
pydantic-core==2.50.1
|
| 68 |
+
pymupdf==2.0
|
| 69 |
+
pymupdf-layout==2.0
|
| 70 |
+
pymupdf4llm==2.0
|
| 71 |
+
pypdfium2==5.14.0
|
| 72 |
+
python-bidi==0.6.12
|
| 73 |
+
python-dateutil==3.0.0
|
| 74 |
+
pyyaml==6.0.2
|
| 75 |
+
requests==2.34.2
|
| 76 |
+
ruamel-yaml==0.19.1
|
| 77 |
+
safetensors==0.7.0
|
| 78 |
+
setuptools==84.2.1
|
| 79 |
+
shapely==2.2.0
|
| 80 |
+
six==1.17.0
|
| 81 |
+
soupsieve==3.0.4
|
| 82 |
+
tabulate==0.10.0
|
| 83 |
+
tqdm==4.70.1
|
| 84 |
+
truststore==0.10.5
|
| 85 |
+
typing-extensions==4.16.0
|
| 86 |
+
typing-inspection==0.4.4
|
| 87 |
+
tzdata==2026.5
|
| 88 |
+
ujson==6.0.0
|
| 89 |
+
urllib3==2.8.0
|
| 90 |
+
wcwidth==0.9.4
|
minicpm-ocr.py
ADDED
|
@@ -0,0 +1,644 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "datasets>=3.1.0",
|
| 5 |
+
# "huggingface-hub>=1.0",
|
| 6 |
+
# "pillow",
|
| 7 |
+
# "bucketbag @ https://github.com/davanstrien/bucketbag/archive/refs/tags/v0.3.1.tar.gz",
|
| 8 |
+
# ]
|
| 9 |
+
#
|
| 10 |
+
# [tool.hf-jobs]
|
| 11 |
+
# image = "cr.hf.co/davanstrien/minicpm-ocr:1.0-vllm-5d35ce3"
|
| 12 |
+
# flavor = "a10g-large"
|
| 13 |
+
# timeout = "2h"
|
| 14 |
+
# secrets = ["HF_TOKEN"]
|
| 15 |
+
# ///
|
| 16 |
+
|
| 17 |
+
"""
|
| 18 |
+
Convert document images to markdown with OpenBMB's MiniCPM-OCR 1.0 pipeline.
|
| 19 |
+
|
| 20 |
+
MiniCPM-OCR 1.0 (1.3B, Apache-2.0) is a region reader: the official SDK finds layout regions
|
| 21 |
+
with PP-DocLayoutV3, crops them, sends each crop to the model with the prompt for its type
|
| 22 |
+
(`Text Recognition:`, `Table Recognition:`, `Formula Recognition:`, ...) and assembles the page
|
| 23 |
+
as Markdown (tables as HTML, formulas as LaTeX). This script runs that pipeline unchanged.
|
| 24 |
+
|
| 25 |
+
Two ways in and out:
|
| 26 |
+
|
| 27 |
+
# Hub dataset -> Hub dataset (adds `markdown` and `markdown_status` columns)
|
| 28 |
+
hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/minicpm-ocr.py \\
|
| 29 |
+
input-dataset output-dataset --max-samples 20
|
| 30 |
+
|
| 31 |
+
# Bucket (or folder) of page images -> one .md per image in a Bucket (or folder)
|
| 32 |
+
hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/minicpm-ocr.py \\
|
| 33 |
+
hf://buckets/<ns>/<bucket>/pages hf://buckets/<ns>/<bucket>/minicpm-ocr
|
| 34 |
+
|
| 35 |
+
Bucket input is listed and downloaded in batches with bucketbag (no mount); `x/y.jp2` becomes
|
| 36 |
+
`x/y.md` under the output prefix. A page whose regions all read cleanly is written; a page with
|
| 37 |
+
failed regions is not, and is listed at the end, so re-running the same command retries it (pages
|
| 38 |
+
with a `.md` already are skipped). In dataset mode every row gets a `markdown_status`: `ok`,
|
| 39 |
+
`partial_failed` (some regions failed; the text is kept), `failed` or `error: ...` (no text).
|
| 40 |
+
|
| 41 |
+
Runtime image (from the [tool.hf-jobs] header): cr.hf.co/davanstrien/minicpm-ocr, built from
|
| 42 |
+
images/minicpm-ocr/Dockerfile. It holds:
|
| 43 |
+
- vLLM nightly 5d35ce3. MiniCPMOcrForConditionalGeneration landed in vLLM main on 23 Oct 2026
|
| 44 |
+
and is not in a release yet. Drop the custom image for a stock vllm/vllm-openai tag once a
|
| 45 |
+
release has the architecture.
|
| 46 |
+
- transformers at OpenBMB's pin (549e5b4).
|
| 47 |
+
- The minicpm-ocr SDK 1.0.1 in its own venv (/opt/sdk) with PaddlePaddle GPU, as OpenBMB's docs
|
| 48 |
+
require (SDK and inference service in separate environments), and the PP-DocLayoutV3 layout
|
| 49 |
+
model baked in at /opt/minicpm-ocr-assets.
|
| 50 |
+
|
| 51 |
+
Server settings follow OpenBMB's SDK tutorial (docs/minicpmvocr_tutorial_en.md): max-model-len
|
| 52 |
+
40960, 32 sequences, image limit 36, `downsample_mode` 4x, thinking off, DSpark speculative
|
| 53 |
+
decoding with the matching draft model (`--no-dspark` for plain decoding). The SDK's bundled
|
| 54 |
+
config sets sampling and per-region prompts; nothing here overrides them. The SDK reads page
|
| 55 |
+
numbers, headers, footers, footnotes and side notes but leaves them out of the Markdown;
|
| 56 |
+
`--keep-labels footnote aside_text` puts those region types back.
|
| 57 |
+
|
| 58 |
+
Model: https://huggingface.co/openbmb/MiniCPM-OCR-1.0
|
| 59 |
+
SDK: https://github.com/OpenBMB/MiniCPM-OCR
|
| 60 |
+
Image: https://huggingface.co/containers/davanstrien/minicpm-ocr
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
import argparse
|
| 64 |
+
import contextlib
|
| 65 |
+
import json
|
| 66 |
+
import logging
|
| 67 |
+
import os
|
| 68 |
+
import shlex
|
| 69 |
+
import shutil
|
| 70 |
+
import signal
|
| 71 |
+
import subprocess
|
| 72 |
+
import sys
|
| 73 |
+
import tempfile
|
| 74 |
+
import time
|
| 75 |
+
import urllib.request
|
| 76 |
+
from datetime import datetime
|
| 77 |
+
from pathlib import Path
|
| 78 |
+
|
| 79 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
| 80 |
+
logger = logging.getLogger(__name__)
|
| 81 |
+
|
| 82 |
+
SCRIPT_URL = "https://huggingface.co/datasets/uv-scripts/ocr/raw/main/minicpm-ocr.py"
|
| 83 |
+
MODEL = "openbmb/MiniCPM-OCR-1.0"
|
| 84 |
+
MODEL_REVISION = "a59a4acf215e34c6d73149e9eafdb88ed2086e39"
|
| 85 |
+
DRAFT_MODEL = "openbmb/MiniCPM-OCR-1.0-DSpark" # must come from the same release as MODEL
|
| 86 |
+
DRAFT_REVISION = "31e3feaf80e0061cd6aa73db23480d2d691d6452"
|
| 87 |
+
SERVED_NAME = "minicpm-ocr"
|
| 88 |
+
PORT = 18499
|
| 89 |
+
SDK_PYTHON = "/opt/sdk/bin/python"
|
| 90 |
+
LAYOUT_MODEL_DIR = "/opt/minicpm-ocr-assets/models/PP-DocLayoutV3_infer"
|
| 91 |
+
# minicpm-ocr SDK 1.0.1 markdown_assembly.ignore_labels: read by the model, left out of the Markdown
|
| 92 |
+
SDK_IGNORED_LABELS = ["number", "footnote", "header", "footer", "aside_text"]
|
| 93 |
+
IMAGE_TAG = "cr.hf.co/davanstrien/minicpm-ocr:1.0-vllm-5d35ce3"
|
| 94 |
+
BUCKET_SCHEME = "hf://buckets/"
|
| 95 |
+
IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".tif", ".tiff", ".bmp", ".webp", ".jp2"}
|
| 96 |
+
|
| 97 |
+
# Runs inside the SDK venv: the SDK's documented Python API (docs/minicpmvocr_api_en.md),
|
| 98 |
+
# with the bundled config and only the input, server and layout path filled in.
|
| 99 |
+
SDK_RUNNER = """
|
| 100 |
+
import json, sys
|
| 101 |
+
from importlib.resources import files
|
| 102 |
+
from pathlib import Path
|
| 103 |
+
from minicpmvocr import load_config, pipelined_run
|
| 104 |
+
from minicpmvocr.prompts import DEFAULT_PROMPT_MAP
|
| 105 |
+
args = json.loads(sys.argv[1])
|
| 106 |
+
prompt = {}
|
| 107 |
+
if args["keep_labels"]:
|
| 108 |
+
# A prompt-map file replaces whole top-level sections, so write the full assembly section.
|
| 109 |
+
assembly = dict(DEFAULT_PROMPT_MAP["markdown_assembly"])
|
| 110 |
+
assembly["ignore_labels"] = [l for l in assembly["ignore_labels"] if l not in args["keep_labels"]]
|
| 111 |
+
prompt_map = Path(args["run_root"]) / "prompt_map.json"
|
| 112 |
+
prompt_map.parent.mkdir(parents=True, exist_ok=True)
|
| 113 |
+
prompt_map.write_text(json.dumps({"markdown_assembly": assembly}))
|
| 114 |
+
prompt = {"prompt_map": str(prompt_map)}
|
| 115 |
+
cfg = load_config(str(files("minicpmvocr").joinpath("configs/minicpmvocr.yaml")), overrides={
|
| 116 |
+
"input": {"image_dir": args["image_dir"]},
|
| 117 |
+
"run": {"run_root": args["run_root"], "run_tag": args["run_tag"]},
|
| 118 |
+
"engine": {"server_url": args["server_url"], "model_name": args["model_name"], "max_model_len": 40960},
|
| 119 |
+
"layout": {"model_dir": args["layout_dir"], "device": "cuda:0"},
|
| 120 |
+
"pipeline": {"overlap_layout": True},
|
| 121 |
+
"prompt": prompt,
|
| 122 |
+
})
|
| 123 |
+
pipelined_run(cfg)
|
| 124 |
+
print(json.dumps({"run_dir": cfg["_meta"]["run_dir"]}))
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def image_python() -> str | None:
|
| 129 |
+
"""The image's own python3 (the one with vLLM and torch), looking past this script's venv."""
|
| 130 |
+
own_bin = os.path.realpath(os.path.join(sys.prefix, "bin"))
|
| 131 |
+
path = os.pathsep.join(p for p in os.environ.get("PATH", "").split(os.pathsep)
|
| 132 |
+
if os.path.realpath(p) != own_bin)
|
| 133 |
+
return shutil.which("python3", path=path)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def check_runtime():
|
| 137 |
+
"""Fail fast, naming the fix, when not on the MiniCPM-OCR image or without a CUDA GPU."""
|
| 138 |
+
py = image_python()
|
| 139 |
+
if not (py and shutil.which("vllm") and Path(SDK_PYTHON).exists() and Path(LAYOUT_MODEL_DIR).exists()):
|
| 140 |
+
logger.error("This script needs the %s image (vLLM with MiniCPM-OCR support, the "
|
| 141 |
+
"minicpm-ocr SDK and the layout model).", IMAGE_TAG)
|
| 142 |
+
logger.error("Run it with `hf jobs uv run`, which reads the image from the script header, "
|
| 143 |
+
"or pass --image %s.", IMAGE_TAG)
|
| 144 |
+
sys.exit(1)
|
| 145 |
+
probe = subprocess.run([py, "-c", "import torch; print(torch.cuda.is_available())"],
|
| 146 |
+
capture_output=True, text=True)
|
| 147 |
+
if probe.stdout.strip() != "True":
|
| 148 |
+
logger.error("CUDA is not available to the image's torch. This script needs a GPU "
|
| 149 |
+
"(e.g. --flavor a10g-large). %s", probe.stderr.strip()[-300:])
|
| 150 |
+
sys.exit(1)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@contextlib.contextmanager
|
| 154 |
+
def vllm_server(dspark: bool):
|
| 155 |
+
"""Run vLLM with OpenBMB's tutorial settings for the duration of the block.
|
| 156 |
+
|
| 157 |
+
The server gets its own process group, and is terminated, then killed, then reaped, on every
|
| 158 |
+
exit path, including a failed or interrupted startup.
|
| 159 |
+
"""
|
| 160 |
+
from huggingface_hub import snapshot_download
|
| 161 |
+
|
| 162 |
+
model_dir = snapshot_download(MODEL, revision=MODEL_REVISION)
|
| 163 |
+
cmd = [
|
| 164 |
+
"vllm", "serve", model_dir, "--served-model-name", SERVED_NAME,
|
| 165 |
+
"--host", "127.0.0.1", "--port", str(PORT),
|
| 166 |
+
"--max-model-len", "40960", "--max-num-batched-tokens", "40960", "--max-num-seqs", "32",
|
| 167 |
+
"--limit-mm-per-prompt", '{"image":36,"video":0}',
|
| 168 |
+
"--mm-processor-kwargs", '{"downsample_mode":"4x"}',
|
| 169 |
+
"--gpu-memory-utilization", "0.85", "--trust-request-mm-kwargs",
|
| 170 |
+
"--default-chat-template-kwargs", '{"enable_thinking":false}',
|
| 171 |
+
]
|
| 172 |
+
if dspark:
|
| 173 |
+
draft_dir = snapshot_download(DRAFT_MODEL, revision=DRAFT_REVISION)
|
| 174 |
+
cmd += ["--speculative-config", json.dumps({
|
| 175 |
+
"method": "dspark", "model": draft_dir, "num_speculative_tokens": 15,
|
| 176 |
+
"enable_adaptive_verification": False})]
|
| 177 |
+
# This script's VIRTUAL_ENV must not leak into the image's vLLM.
|
| 178 |
+
env = {k: v for k, v in os.environ.items() if k != "VIRTUAL_ENV"}
|
| 179 |
+
logger.info("Starting vLLM: %s", shlex.join(cmd))
|
| 180 |
+
proc = subprocess.Popen(cmd, env=env, start_new_session=True)
|
| 181 |
+
try:
|
| 182 |
+
deadline = time.time() + 1800
|
| 183 |
+
while True:
|
| 184 |
+
if proc.poll() is not None:
|
| 185 |
+
sys.exit(f"vLLM exited during startup (code {proc.returncode})")
|
| 186 |
+
try:
|
| 187 |
+
with urllib.request.urlopen(f"http://127.0.0.1:{PORT}/v1/models", timeout=5) as r:
|
| 188 |
+
if SERVED_NAME in r.read().decode():
|
| 189 |
+
break
|
| 190 |
+
except OSError:
|
| 191 |
+
pass
|
| 192 |
+
if time.time() > deadline:
|
| 193 |
+
sys.exit("vLLM did not become ready within 30 minutes")
|
| 194 |
+
time.sleep(5)
|
| 195 |
+
logger.info("vLLM ready")
|
| 196 |
+
yield
|
| 197 |
+
finally:
|
| 198 |
+
stop_process_group(proc)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def group_alive(pgid: int) -> bool:
|
| 202 |
+
try:
|
| 203 |
+
os.killpg(pgid, 0)
|
| 204 |
+
return True
|
| 205 |
+
except (ProcessLookupError, PermissionError):
|
| 206 |
+
return False
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def stop_process_group(proc: subprocess.Popen):
|
| 210 |
+
"""SIGTERM the whole group, wait up to 60 s for it to empty, then SIGKILL; always reap the
|
| 211 |
+
parent. Checks the group, not just the parent, since vLLM's workers can outlive it."""
|
| 212 |
+
pgid = proc.pid # start_new_session=True: the server leads its own group
|
| 213 |
+
for sig, wait in ((signal.SIGTERM, 60), (signal.SIGKILL, 30)):
|
| 214 |
+
if not group_alive(pgid):
|
| 215 |
+
break
|
| 216 |
+
with contextlib.suppress(ProcessLookupError):
|
| 217 |
+
os.killpg(pgid, sig)
|
| 218 |
+
deadline = time.time() + wait
|
| 219 |
+
while group_alive(pgid) and time.time() < deadline:
|
| 220 |
+
with contextlib.suppress(subprocess.TimeoutExpired):
|
| 221 |
+
proc.wait(timeout=1)
|
| 222 |
+
with contextlib.suppress(subprocess.TimeoutExpired):
|
| 223 |
+
proc.wait(timeout=5)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def parse_batch(images: dict, work: Path, tag: str, keep_labels: list[str]) -> dict:
|
| 227 |
+
"""OCR one batch of pages with the SDK.
|
| 228 |
+
|
| 229 |
+
`images` maps a key to a PIL image, a path, or an undecoded datasets image dict. Returns
|
| 230 |
+
key -> (status, markdown or None). A page that cannot be read gets an `error: ...` status and
|
| 231 |
+
does not stop the batch; if the SDK run itself fails, every page in the batch gets one.
|
| 232 |
+
"""
|
| 233 |
+
from datasets import Image as ImageFeature
|
| 234 |
+
from PIL import Image, ImageOps
|
| 235 |
+
|
| 236 |
+
decoder = ImageFeature()
|
| 237 |
+
image_dir = work / tag / "images"
|
| 238 |
+
image_dir.mkdir(parents=True)
|
| 239 |
+
results, ids = {}, {}
|
| 240 |
+
for i, (key, source) in enumerate(images.items()):
|
| 241 |
+
try:
|
| 242 |
+
if isinstance(source, dict):
|
| 243 |
+
# datasets Image(decode=False): {"bytes", "path"}. The datasets decoder handles
|
| 244 |
+
# remote paths and auth, and turns EXIF-rotated photos upright.
|
| 245 |
+
img = decoder.decode_example(source)
|
| 246 |
+
else:
|
| 247 |
+
img = source if isinstance(source, Image.Image) else Image.open(source)
|
| 248 |
+
img = ImageOps.exif_transpose(img)
|
| 249 |
+
img.convert("RGB").save(image_dir / f"{i:06d}.png")
|
| 250 |
+
ids[f"{i:06d}"] = key
|
| 251 |
+
except Exception as e: # one unreadable page must not lose the batch
|
| 252 |
+
logger.warning("Cannot read %s: %s", key, e)
|
| 253 |
+
results[key] = (f"error: unreadable image ({type(e).__name__})", None)
|
| 254 |
+
if ids:
|
| 255 |
+
args = {"image_dir": str(image_dir), "run_root": str(work / tag / "runs"), "run_tag": tag,
|
| 256 |
+
"server_url": f"http://127.0.0.1:{PORT}", "model_name": SERVED_NAME,
|
| 257 |
+
"layout_dir": LAYOUT_MODEL_DIR, "keep_labels": keep_labels}
|
| 258 |
+
run = subprocess.run([SDK_PYTHON, "-c", SDK_RUNNER, json.dumps(args)],
|
| 259 |
+
capture_output=True, text=True)
|
| 260 |
+
if run.returncode != 0:
|
| 261 |
+
logger.error("SDK run failed for %s (exit %d):\n%s", tag, run.returncode, run.stderr[-3000:])
|
| 262 |
+
results.update({key: (f"error: SDK exit {run.returncode}", None) for key in ids.values()})
|
| 263 |
+
else:
|
| 264 |
+
run_dir = Path(json.loads(run.stdout.strip().splitlines()[-1])["run_dir"])
|
| 265 |
+
status = {}
|
| 266 |
+
metrics = run_dir / "per_page_metrics.jsonl"
|
| 267 |
+
if metrics.exists():
|
| 268 |
+
for line in metrics.read_text(encoding="utf-8").splitlines():
|
| 269 |
+
row = json.loads(line)
|
| 270 |
+
status[row["image_id"]] = row.get("status") or "unknown"
|
| 271 |
+
for image_id, key in ids.items():
|
| 272 |
+
md = run_dir / "output" / f"{image_id}.md"
|
| 273 |
+
page_status = status.get(image_id, "failed" if not md.exists() else "unknown")
|
| 274 |
+
text = md.read_text(encoding="utf-8").strip() if md.exists() else None
|
| 275 |
+
results[key] = (page_status, text if page_status in ("ok", "partial_failed") else None)
|
| 276 |
+
shutil.rmtree(work / tag, ignore_errors=True)
|
| 277 |
+
return results
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
# --- Bucket / folder mode ------------------------------------------------------------------
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def is_bucket(location: str) -> bool:
|
| 284 |
+
return location.startswith(BUCKET_SCHEME)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def as_bucket_dir(url: str) -> tuple[str, str]:
|
| 288 |
+
"""Split a bucket URL into (bucket root URL, directory key prefix ending in "/").
|
| 289 |
+
|
| 290 |
+
The prefix goes to bucketbag explicitly: it matches prefixes as strings, so `.../vol`
|
| 291 |
+
would also list `.../vol2/...`.
|
| 292 |
+
"""
|
| 293 |
+
parts = url[len(BUCKET_SCHEME):].strip("/").split("/", 2)
|
| 294 |
+
if len(parts) < 2:
|
| 295 |
+
raise ValueError(f"Not a bucket URL: {url} (expected hf://buckets/<ns>/<bucket>[/<prefix>])")
|
| 296 |
+
prefix = parts[2] + "/" if len(parts) == 3 else ""
|
| 297 |
+
return BUCKET_SCHEME + "/".join(parts[:2]), prefix
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def md_rel(rel: str) -> str:
|
| 301 |
+
return str(Path(rel).with_suffix(".md"))
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def list_rels(location: str) -> list[str]:
|
| 305 |
+
"""Relative paths of every file under a bucket prefix or folder, sorted."""
|
| 306 |
+
if is_bucket(location):
|
| 307 |
+
from bucketbag import iter_keys
|
| 308 |
+
|
| 309 |
+
url, prefix = as_bucket_dir(location)
|
| 310 |
+
return sorted(k[len(prefix):] for k in iter_keys(url, prefix=prefix))
|
| 311 |
+
root = Path(location)
|
| 312 |
+
return sorted(str(p.relative_to(root)) for p in root.rglob("*") if p.is_file()) if root.is_dir() else []
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def iter_local_batches(source: str, rels: list[str], n: int):
|
| 316 |
+
"""Yield batches of (rel, local path): from disk, or downloaded by bucketbag to scratch."""
|
| 317 |
+
if not is_bucket(source):
|
| 318 |
+
for i in range(0, len(rels), n):
|
| 319 |
+
yield [(rel, Path(source) / rel) for rel in rels[i: i + n]]
|
| 320 |
+
return
|
| 321 |
+
from bucketbag import batched_files
|
| 322 |
+
|
| 323 |
+
url, prefix = as_bucket_dir(source)
|
| 324 |
+
for batch in batched_files(url, keys=[prefix + rel for rel in rels], n=n, prefetch=2):
|
| 325 |
+
yield [(item.key[len(prefix):], item.path) for item in batch]
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def write_outputs(dest: str, pairs: list[tuple[str, str]]):
|
| 329 |
+
if not pairs:
|
| 330 |
+
return
|
| 331 |
+
if is_bucket(dest):
|
| 332 |
+
from bucketbag import put_files
|
| 333 |
+
|
| 334 |
+
url, prefix = as_bucket_dir(dest)
|
| 335 |
+
put_files([(prefix + rel, content) for rel, content in pairs], url)
|
| 336 |
+
return
|
| 337 |
+
for rel, content in pairs:
|
| 338 |
+
# Temp file + rename: a stopped job never leaves a partial .md that a re-run counts as done.
|
| 339 |
+
path = Path(dest) / rel
|
| 340 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 341 |
+
tmp = path.with_name(f".{path.name}.tmp")
|
| 342 |
+
tmp.write_text(content, encoding="utf-8")
|
| 343 |
+
os.replace(tmp, path)
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def run_files(args):
|
| 347 |
+
inputs = [r for r in list_rels(args.input) if Path(r).suffix.lower() in IMAGE_EXTENSIONS]
|
| 348 |
+
owners: dict[str, list[str]] = {}
|
| 349 |
+
for rel in inputs:
|
| 350 |
+
owners.setdefault(md_rel(rel), []).append(rel)
|
| 351 |
+
clashes = [" + ".join(group) for group in owners.values() if len(group) > 1]
|
| 352 |
+
if clashes:
|
| 353 |
+
sys.exit("These inputs would write the same .md file; rename or move them first:\n "
|
| 354 |
+
+ "\n ".join(clashes))
|
| 355 |
+
if args.max_samples:
|
| 356 |
+
inputs = inputs[: args.max_samples] # the same pages on every run, so a re-run resumes them
|
| 357 |
+
done = {r for r in list_rels(args.output) if r.endswith(".md")}
|
| 358 |
+
todo = [r for r in inputs if args.overwrite or md_rel(r) not in done]
|
| 359 |
+
already = sum(md_rel(r) in done for r in inputs)
|
| 360 |
+
logger.info("%d images under %s, %d already have a .md, %d to OCR", len(inputs), args.input,
|
| 361 |
+
already, len(todo))
|
| 362 |
+
if not todo:
|
| 363 |
+
return
|
| 364 |
+
failed = []
|
| 365 |
+
with vllm_server(dspark=not args.no_dspark), tempfile.TemporaryDirectory() as work:
|
| 366 |
+
for b, batch in enumerate(iter_local_batches(args.input, todo, args.batch_size)):
|
| 367 |
+
results = parse_batch(dict(batch), Path(work), f"batch{b:06d}", args.keep_labels)
|
| 368 |
+
write_outputs(args.output, [(md_rel(rel), text) for rel, (status, text) in results.items()
|
| 369 |
+
if status == "ok"])
|
| 370 |
+
failed += [f"{rel} ({status})" for rel, (status, _) in results.items() if status != "ok"]
|
| 371 |
+
logger.info("%d/%d images", min((b + 1) * args.batch_size, len(todo)), len(todo))
|
| 372 |
+
if failed:
|
| 373 |
+
logger.warning("%d pages not written (re-run the same command to retry them):\n %s",
|
| 374 |
+
len(failed), "\n ".join(failed))
|
| 375 |
+
stale = [f for f in failed if md_rel(f.rsplit(" (", 1)[0]) in done]
|
| 376 |
+
if args.overwrite and stale:
|
| 377 |
+
logger.warning("%d of them still have a .md from an earlier run, which a re-run without "
|
| 378 |
+
"--overwrite will skip; delete those files to retry them:\n %s",
|
| 379 |
+
len(stale), "\n ".join(stale))
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
# --- Dataset mode ----------------------------------------------------------------------------
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def jobs_flavor() -> str:
|
| 386 |
+
"""Return the HF Jobs hardware flavor this run is on, or "" when it cannot be told.
|
| 387 |
+
|
| 388 |
+
HF Jobs sets ACCELERATOR to "cpu" or "gpu", not the flavor name, so the flavor is looked up
|
| 389 |
+
in the public Jobs hardware list: first by GPU model and count, then by the CPU_CORES and
|
| 390 |
+
MEMORY values that Jobs sets in the container (to tell a10g-small from a10g-large, or
|
| 391 |
+
cpu-basic from cpu-upgrade). Any failure (no network, older huggingface_hub) returns "".
|
| 392 |
+
"""
|
| 393 |
+
hardware = os.environ.get("ACCELERATOR") or ""
|
| 394 |
+
if "-" in hardware or any(character.isdigit() for character in hardware):
|
| 395 |
+
return hardware # already a flavor name
|
| 396 |
+
try:
|
| 397 |
+
from huggingface_hub import HfApi
|
| 398 |
+
|
| 399 |
+
gpu_name, gpu_count = "", 0
|
| 400 |
+
try:
|
| 401 |
+
import torch
|
| 402 |
+
|
| 403 |
+
if torch.cuda.is_available():
|
| 404 |
+
gpu_name = torch.cuda.get_device_name(0)
|
| 405 |
+
gpu_count = torch.cuda.device_count()
|
| 406 |
+
except ImportError:
|
| 407 |
+
# Torch-free drivers (e.g. the -server recipes): ask nvidia-smi instead.
|
| 408 |
+
import subprocess
|
| 409 |
+
|
| 410 |
+
try:
|
| 411 |
+
listed = subprocess.run(
|
| 412 |
+
["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],
|
| 413 |
+
capture_output=True, text=True, timeout=10, check=True,
|
| 414 |
+
).stdout
|
| 415 |
+
names = [line.strip() for line in listed.splitlines() if line.strip()]
|
| 416 |
+
if names:
|
| 417 |
+
gpu_name, gpu_count = names[0], len(names)
|
| 418 |
+
except (OSError, subprocess.SubprocessError):
|
| 419 |
+
pass
|
| 420 |
+
if gpu_count == 0 and hardware == "gpu":
|
| 421 |
+
return "" # a GPU run whose GPU cannot be identified: do not guess a CPU flavor
|
| 422 |
+
|
| 423 |
+
# Whole-word match, so "L4" does not match "NVIDIA L40S" ("NVIDIA A100-SXM4-80GB" -> A100).
|
| 424 |
+
gpu_words = gpu_name.upper().replace("-", " ").split()
|
| 425 |
+
candidates = []
|
| 426 |
+
for flavor in HfApi(token=False).list_jobs_hardware():
|
| 427 |
+
accelerator = flavor.accelerator
|
| 428 |
+
if gpu_count == 0 and accelerator is None:
|
| 429 |
+
candidates.append(flavor)
|
| 430 |
+
elif (
|
| 431 |
+
gpu_count > 0
|
| 432 |
+
and accelerator is not None
|
| 433 |
+
and accelerator.model.upper() in gpu_words
|
| 434 |
+
and int(accelerator.quantity) == gpu_count
|
| 435 |
+
):
|
| 436 |
+
candidates.append(flavor)
|
| 437 |
+
if not candidates:
|
| 438 |
+
return ""
|
| 439 |
+
|
| 440 |
+
cores = float(os.environ.get("CPU_CORES") or 0)
|
| 441 |
+
memory_gb = float((os.environ.get("MEMORY") or "0").upper().rstrip("GIB ") or 0)
|
| 442 |
+
|
| 443 |
+
def distance(flavor) -> float:
|
| 444 |
+
# Relative gap to the listed vCPUs and RAM; Jobs reports slightly different numbers.
|
| 445 |
+
listed_cores = float(flavor.cpu.split()[0])
|
| 446 |
+
listed_memory = float(flavor.ram.split()[0])
|
| 447 |
+
return abs(listed_cores - cores) / listed_cores + abs(listed_memory - memory_gb) / listed_memory
|
| 448 |
+
|
| 449 |
+
return min(candidates, key=distance).name
|
| 450 |
+
except Exception:
|
| 451 |
+
return ""
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
def create_dataset_card(args, num_samples: int, counts: dict, processing_time: str) -> str:
|
| 455 |
+
# Canonical provenance stamp (see AGENTS.md): Jobs claim gated on JOB_ID, set by HF Jobs in-container.
|
| 456 |
+
on_jobs = os.environ.get("JOB_ID") is not None
|
| 457 |
+
hw = jobs_flavor()
|
| 458 |
+
origin = (
|
| 459 |
+
"Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"
|
| 460 |
+
+ (f" (`{hw}`)" if hw else "")
|
| 461 |
+
) if on_jobs else "Generated"
|
| 462 |
+
jobs_tag = "\n- hf-jobs" if on_jobs else ""
|
| 463 |
+
status_col = f"{args.output_column}_status"
|
| 464 |
+
flags = [f"--flavor {hw or 'a10g-large'}"]
|
| 465 |
+
for flag, value, default in (("--split", args.split, "train"), ("--image-column", args.image_column, "image"),
|
| 466 |
+
("--output-column", args.output_column, "markdown"),
|
| 467 |
+
("--batch-size", args.batch_size, 64)):
|
| 468 |
+
if value != default:
|
| 469 |
+
flags.append(f"{flag} {shlex.quote(str(value))}")
|
| 470 |
+
if args.max_samples:
|
| 471 |
+
flags.append(f"--max-samples {args.max_samples}")
|
| 472 |
+
if args.shuffle:
|
| 473 |
+
flags.append(f"--shuffle --seed {args.seed}")
|
| 474 |
+
if args.no_dspark:
|
| 475 |
+
flags.append("--no-dspark")
|
| 476 |
+
if args.keep_labels:
|
| 477 |
+
flags.append("--keep-labels " + " ".join(args.keep_labels))
|
| 478 |
+
if args.overwrite:
|
| 479 |
+
flags.append("--overwrite")
|
| 480 |
+
command = f"hf jobs uv run {' '.join(flags[:1])} \\\n {SCRIPT_URL} \\\n {args.input} <output-dataset>"
|
| 481 |
+
if flags[1:]:
|
| 482 |
+
command += " \\\n " + " ".join(flags[1:])
|
| 483 |
+
counts_line = ", ".join(f"`{k}` {v:,}" for k, v in sorted(counts.items()))
|
| 484 |
+
return f"""---
|
| 485 |
+
tags:
|
| 486 |
+
- ocr
|
| 487 |
+
- document-processing
|
| 488 |
+
- minicpm-ocr
|
| 489 |
+
- markdown
|
| 490 |
+
- uv-script
|
| 491 |
+
- generated{jobs_tag}
|
| 492 |
+
---
|
| 493 |
+
|
| 494 |
+
# Document OCR using MiniCPM-OCR 1.0
|
| 495 |
+
|
| 496 |
+
OCR of [{args.input}](https://huggingface.co/datasets/{args.input}) with OpenBMB's
|
| 497 |
+
[MiniCPM-OCR 1.0](https://huggingface.co/{MODEL}) pipeline: PP-DocLayoutV3 layout regions, each
|
| 498 |
+
region read by the model, assembled into Markdown by the official SDK.
|
| 499 |
+
|
| 500 |
+
## Processing Details
|
| 501 |
+
|
| 502 |
+
- **Source Dataset**: [{args.input}](https://huggingface.co/datasets/{args.input}) (split `{args.split}`, column `{args.image_column}`)
|
| 503 |
+
- **Model**: [{MODEL}](https://huggingface.co/{MODEL}) @ `{MODEL_REVISION[:7]}`
|
| 504 |
+
- **Decoding**: {"standard" if args.no_dspark else "DSpark speculative decoding"}
|
| 505 |
+
- **Region types left out of the Markdown**: {", ".join(f"`{l}`" for l in SDK_IGNORED_LABELS if l not in args.keep_labels) or "none"}
|
| 506 |
+
- **Number of Samples**: {num_samples:,}
|
| 507 |
+
- **Page status**: {counts_line}
|
| 508 |
+
- **Processing Time**: {processing_time}
|
| 509 |
+
- **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
|
| 510 |
+
|
| 511 |
+
## Columns
|
| 512 |
+
|
| 513 |
+
- `{args.output_column}`: the SDK's Markdown for each page (tables as HTML, formulas as LaTeX); empty when
|
| 514 |
+
the page failed
|
| 515 |
+
- `{status_col}`: `ok`, `partial_failed` (some regions failed; text kept), `failed` or `error: ...`
|
| 516 |
+
- `inference_info`: JSON list tracking all OCR models applied to this dataset
|
| 517 |
+
|
| 518 |
+
## Reproduction
|
| 519 |
+
|
| 520 |
+
{origin} with the [`minicpm-ocr.py`]({SCRIPT_URL}) recipe from [uv-scripts](https://huggingface.co/uv-scripts). Run it yourself:
|
| 521 |
+
|
| 522 |
+
```bash
|
| 523 |
+
{command}
|
| 524 |
+
```
|
| 525 |
+
"""
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def run_dataset(args):
|
| 529 |
+
from datasets import load_dataset
|
| 530 |
+
from huggingface_hub import DatasetCard
|
| 531 |
+
|
| 532 |
+
status_col = f"{args.output_column}_status"
|
| 533 |
+
reserved = {"inference_info", args.image_column}
|
| 534 |
+
if args.output_column in reserved or status_col in reserved:
|
| 535 |
+
sys.exit(f"--output-column {args.output_column!r} clashes with {sorted(reserved)}; pick another name")
|
| 536 |
+
|
| 537 |
+
dataset = load_dataset(args.input, split=args.split)
|
| 538 |
+
if args.shuffle:
|
| 539 |
+
dataset = dataset.shuffle(seed=args.seed)
|
| 540 |
+
if args.max_samples:
|
| 541 |
+
dataset = dataset.select(range(min(args.max_samples, len(dataset))))
|
| 542 |
+
# Undecoded: a corrupt image then fails inside parse_batch's per-page guard, not in the slice.
|
| 543 |
+
from datasets import Image as ImageFeature
|
| 544 |
+
|
| 545 |
+
dataset = dataset.cast_column(args.image_column, ImageFeature(decode=False))
|
| 546 |
+
clash = [c for c in (args.output_column, status_col) if c in dataset.column_names]
|
| 547 |
+
if clash and not args.overwrite:
|
| 548 |
+
sys.exit(f"Output column(s) {clash} already exist; choose another --output-column or pass --overwrite")
|
| 549 |
+
if clash:
|
| 550 |
+
logger.warning("--overwrite: replacing existing column(s) %s", clash)
|
| 551 |
+
dataset = dataset.remove_columns(clash)
|
| 552 |
+
logger.info("%d pages from %s", len(dataset), args.input)
|
| 553 |
+
|
| 554 |
+
# Slice only the image column: slicing the full dataset would decode every other image
|
| 555 |
+
# column too, outside the per-page guard.
|
| 556 |
+
image_only = dataset.select_columns([args.image_column])
|
| 557 |
+
start = datetime.now()
|
| 558 |
+
texts, statuses = [], []
|
| 559 |
+
with vllm_server(dspark=not args.no_dspark), tempfile.TemporaryDirectory() as work:
|
| 560 |
+
for b in range(0, len(dataset), args.batch_size):
|
| 561 |
+
images = image_only[b: b + args.batch_size][args.image_column]
|
| 562 |
+
results = parse_batch(dict(enumerate(images)), Path(work), f"batch{b:08d}", args.keep_labels)
|
| 563 |
+
for i in range(len(images)):
|
| 564 |
+
status, text = results[i]
|
| 565 |
+
statuses.append(status)
|
| 566 |
+
texts.append(text or "")
|
| 567 |
+
logger.info("%d/%d pages", len(texts), len(dataset))
|
| 568 |
+
elapsed = datetime.now() - start
|
| 569 |
+
|
| 570 |
+
counts = {}
|
| 571 |
+
for s in statuses:
|
| 572 |
+
key = "error" if s.startswith("error") else s
|
| 573 |
+
counts[key] = counts.get(key, 0) + 1
|
| 574 |
+
logger.info("Page status: %s", counts)
|
| 575 |
+
|
| 576 |
+
dataset = dataset.cast_column(args.image_column, ImageFeature())
|
| 577 |
+
dataset = dataset.add_column(args.output_column, texts).add_column(status_col, statuses)
|
| 578 |
+
entry = {"model_id": MODEL, "model_name": "MiniCPM-OCR-1.0", "column_name": args.output_column,
|
| 579 |
+
"timestamp": datetime.now().isoformat(), "model_revision": MODEL_REVISION,
|
| 580 |
+
"pipeline": "minicpm-ocr SDK 1.0.1 (PP-DocLayoutV3)", "dspark": not args.no_dspark,
|
| 581 |
+
"keep_labels": args.keep_labels}
|
| 582 |
+
if "inference_info" in dataset.column_names:
|
| 583 |
+
def update(example):
|
| 584 |
+
try:
|
| 585 |
+
info = json.loads(example["inference_info"]) if example["inference_info"] else []
|
| 586 |
+
except (json.JSONDecodeError, TypeError):
|
| 587 |
+
info = []
|
| 588 |
+
return {"inference_info": json.dumps(info + [entry])}
|
| 589 |
+
dataset = dataset.map(update)
|
| 590 |
+
else:
|
| 591 |
+
dataset = dataset.add_column("inference_info", [json.dumps([entry])] * len(dataset))
|
| 592 |
+
|
| 593 |
+
dataset.push_to_hub(args.output, private=args.private)
|
| 594 |
+
card = create_dataset_card(args, len(dataset), counts, f"{elapsed.total_seconds() / 60:.1f} min")
|
| 595 |
+
DatasetCard(card).push_to_hub(args.output)
|
| 596 |
+
logger.info("Done: https://huggingface.co/datasets/%s (%.2f pages/s including startup)",
|
| 597 |
+
args.output, len(dataset) / elapsed.total_seconds())
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
def main():
|
| 601 |
+
parser = argparse.ArgumentParser(
|
| 602 |
+
description="Document OCR with the MiniCPM-OCR 1.0 pipeline",
|
| 603 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 604 |
+
epilog="Input/output: Hub dataset IDs (dataset mode), or hf://buckets/<ns>/<bucket>[/<prefix>] "
|
| 605 |
+
"URLs / folders (one .md per image).")
|
| 606 |
+
parser.add_argument("input", help="Hub dataset ID, or hf://buckets/... URL or folder of page images")
|
| 607 |
+
parser.add_argument("output", help="Hub dataset ID (dataset input), or hf://buckets/... URL or folder")
|
| 608 |
+
parser.add_argument("--image-column", default="image", help="Dataset mode: image column")
|
| 609 |
+
parser.add_argument("--output-column", default="markdown", help="Dataset mode: output column")
|
| 610 |
+
parser.add_argument("--split", default="train", help="Dataset mode: split")
|
| 611 |
+
parser.add_argument("--max-samples", type=int, help="Process only the first N pages (for testing)")
|
| 612 |
+
parser.add_argument("--shuffle", action="store_true", help="Dataset mode: shuffle before --max-samples")
|
| 613 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 614 |
+
parser.add_argument("--batch-size", type=int, default=64,
|
| 615 |
+
help="Pages handed to the SDK per run (it parallelises regions inside a run)")
|
| 616 |
+
parser.add_argument("--no-dspark", action="store_true", help="Standard decoding, no draft model")
|
| 617 |
+
parser.add_argument("--keep-labels", nargs="+", default=[], choices=SDK_IGNORED_LABELS,
|
| 618 |
+
help="Region types to keep in the Markdown that the SDK leaves out by default")
|
| 619 |
+
parser.add_argument("--private", action="store_true", help="Dataset mode: private output dataset")
|
| 620 |
+
parser.add_argument("--overwrite", action="store_true",
|
| 621 |
+
help="Replace an existing output column / re-OCR images that already have a .md")
|
| 622 |
+
parser.add_argument("--hf-token", help="Hugging Face token (default: HF_TOKEN env var)")
|
| 623 |
+
args = parser.parse_args()
|
| 624 |
+
|
| 625 |
+
if args.hf_token:
|
| 626 |
+
os.environ["HF_TOKEN"] = args.hf_token
|
| 627 |
+
if args.max_samples is not None and args.max_samples < 1:
|
| 628 |
+
sys.exit("--max-samples must be at least 1")
|
| 629 |
+
if args.batch_size < 1:
|
| 630 |
+
sys.exit("--batch-size must be at least 1")
|
| 631 |
+
# The input decides the mode: a Bucket or an existing folder means files, anything else is a
|
| 632 |
+
# Hub dataset ID. In file mode the output is a Bucket URL or a folder (created if new).
|
| 633 |
+
file_in = is_bucket(args.input) or Path(args.input).is_dir()
|
| 634 |
+
if not file_in and (is_bucket(args.output) or Path(args.output).is_dir()):
|
| 635 |
+
sys.exit("Dataset input writes a Hub dataset; for Bucket output, give a Bucket or folder as input.")
|
| 636 |
+
check_runtime()
|
| 637 |
+
if file_in:
|
| 638 |
+
run_files(args)
|
| 639 |
+
else:
|
| 640 |
+
run_dataset(args)
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
if __name__ == "__main__":
|
| 644 |
+
main()
|
models.json
CHANGED
|
@@ -1,14 +1,14 @@
|
|
| 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`.",
|
| 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 |
},
|
| 14 |
"tesseract-ocr.py": {
|
|
@@ -738,6 +738,34 @@
|
|
| 738 |
]
|
| 739 |
}
|
| 740 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 741 |
"unlimited-ocr-vllm.py": {
|
| 742 |
"model_id": "baidu/Unlimited-OCR",
|
| 743 |
"params": "3.3B",
|
|
|
|
| 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-27",
|
| 5 |
"run_pattern": "hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/<script> <input-dataset> <output-dataset> (hf CLI >= 1.32 reads image/flavor/secrets from the script's [tool.hf-jobs] header; add --timeout for long runs. Scripts without a `jobs` entry need --flavor/-s HF_TOKEN (and any --image in their docstring).)",
|
| 6 |
"support_levels": {
|
| 7 |
"core": "Maintained. Smoke-tested flagless on HF Jobs on 2026-09-23/24 with the pinned launch config in `jobs`.",
|
| 8 |
"tool": "Maintained companion (judge, layout, text extraction), not a page-OCR recipe.",
|
| 9 |
"legacy": "Works (smoke-tested 2026-09-23) but superseded or little used; no header yet. See support_note for the alternative.",
|
| 10 |
"unsupported": "Known broken as of 2026-09-23; kept in the repo for now. See support_note.",
|
| 11 |
+
"experimental": "Works in testing on HF Jobs with the launch config in `jobs`, but changes often and may break. See support_note for the stable alternative."
|
| 12 |
}
|
| 13 |
},
|
| 14 |
"tesseract-ocr.py": {
|
|
|
|
| 738 |
]
|
| 739 |
}
|
| 740 |
},
|
| 741 |
+
"minicpm-ocr.py": {
|
| 742 |
+
"model_id": "openbmb/MiniCPM-OCR-1.0",
|
| 743 |
+
"params": "1.3B",
|
| 744 |
+
"backend": "in-job vLLM (nightly) + OpenBMB's minicpm-ocr SDK (PP-DocLayoutV3 layout, per-region prompts, Markdown assembly)",
|
| 745 |
+
"image": "cr.hf.co/davanstrien/minicpm-ocr:1.0-vllm-5d35ce3",
|
| 746 |
+
"task": "ocr (page images -> Markdown; tables as HTML, formulas as LaTeX); Hub dataset or Bucket/folder I/O",
|
| 747 |
+
"output": "dataset mode: markdown + markdown_status columns; Bucket/folder mode: one .md per image (failed pages not written, re-run retries)",
|
| 748 |
+
"license": "apache-2.0",
|
| 749 |
+
"notes": "A region reader behind a layout model, run through the vendor SDK unchanged. Custom public image (Dockerfile in images/minicpm-ocr/): the architecture is in vLLM main but not a release, and the SDK needs PaddlePaddle in its own venv. DSpark speculative decoding on by default (--no-dspark). Bucket I/O via bucketbag v0.3.1 (no mount), resume-by-skip. Smoke-tested 2026-10-27 on BHL pages (dataset mode) and 1771 Britannica .jp2 (Bucket mode), a10g-large.",
|
| 750 |
+
"languages": {
|
| 751 |
+
"evidence": "named-list",
|
| 752 |
+
"count": 2,
|
| 753 |
+
"named": [
|
| 754 |
+
"zh",
|
| 755 |
+
"en"
|
| 756 |
+
],
|
| 757 |
+
"notes": "Card: 'Primary languages: Chinese and English'; card metadata lists en, zh. Card examples include historical scans; fine-tuning guide uses French handwriting."
|
| 758 |
+
},
|
| 759 |
+
"support": "experimental",
|
| 760 |
+
"jobs": {
|
| 761 |
+
"image": "cr.hf.co/davanstrien/minicpm-ocr:1.0-vllm-5d35ce3",
|
| 762 |
+
"flavor": "a10g-large",
|
| 763 |
+
"timeout": "2h",
|
| 764 |
+
"secrets": [
|
| 765 |
+
"HF_TOKEN"
|
| 766 |
+
]
|
| 767 |
+
}
|
| 768 |
+
},
|
| 769 |
"unlimited-ocr-vllm.py": {
|
| 770 |
"model_id": "baidu/Unlimited-OCR",
|
| 771 |
"params": "3.3B",
|