Sync from GitHub via hub-sync
Browse files- CLAUDE.md +52 -0
- LANGUAGES.md +1 -0
- README.md +9 -0
- SERVING.md +6 -0
- hpd-parsing-saturate.py +558 -0
- images/hpd-parsing/README.md +18 -0
- images/hpd-parsing/build.sh +42 -0
- models.json +30 -1
CLAUDE.md
CHANGED
|
@@ -96,6 +96,7 @@ Legend: ✅ production-ready · ⚠️ works only with a required pinned image
|
|
| 96 |
| `unlimited-ocr2.py` | ✅+image | SGLang (Baidu wheel) on `lmsysorg/sglang:v0.5.20-cu130` | rtx-pro-6000 | 16-page windows; ≥48 GB GPU |
|
| 97 |
| `unlimited-ocr2-saturate.py` | 🧪+image | same | rtx-pro-6000 | tuned/experimental: repair pass, JP2 fast decode, PDFs |
|
| 98 |
| `unlimited-ocr2-live.py` | 🧪+image | same | rtx-pro-6000 | experimental: minimal script + `--live-port` dashboard (streams the page being read) |
|
|
|
|
| 99 |
| `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` |
|
| 100 |
| `surya-ocr.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | offline backend inject; site-packages PYTHONPATH |
|
| 101 |
| `surya-ocr-bucket.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | bucket I/O; pin `surya-ocr==0.20.0` |
|
|
@@ -191,6 +192,48 @@ require) against `vllm serve` started in the job. Measured/learned 2026-10-27:
|
|
| 191 |
- vLLM runs in its own process group and is terminated → killed → reaped on every exit path; one bad
|
| 192 |
image or a failed SDK run marks its pages `error: ...` instead of losing finished batches.
|
| 193 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
### `unlimited-ocr2.py` / `unlimited-ocr2-saturate.py` — Baidu SGLang wheel, multi-page windows
|
| 195 |
v2 has no vLLM support; Baidu ships a custom SGLang wheel in the model repo. Its pins (torch 2.13.0,
|
| 196 |
transformers 5.12.1, flashinfer 0.6.18 cu13) match **`lmsysorg/sglang:v0.5.20`** exactly → `-cu130` image,
|
|
@@ -344,6 +387,15 @@ ARM wheels) — if a nightly-recipe install fails on resolution, wait and retry
|
|
| 344 |
|
| 345 |
## Change log
|
| 346 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 347 |
- **2026-11-02** — `xiaomi-ocr-0-saturate.py` moved to `core`. NASA demo: 7/7 in 31 s; checked pages read well, but a table lost one item and some cells lost separators. 16 multilingual historical newspaper pages: 16/16 with no error rows, but repetition loops on 2 small-print German Fraktur pages (lines about 10–13 px after the 2048 px fit), a partial loop on a third, and Chinese characters inserted on 3 pages. `finish_reason` stayed `stop` on all of them.
|
| 348 |
- **2026-10-30** — added `xiaomi-ocr-0-saturate.py` for `xiaomi-research/Xiaomi-OCR-0` (0.8B, Qwen3.5 arch), on
|
| 349 |
saturate `==0.3.0`. Do not set `max_limit` by copying older saturate recipes: on `rtx-pro-6000`, `Auto(max_limit=48)`
|
|
|
|
| 96 |
| `unlimited-ocr2.py` | ✅+image | SGLang (Baidu wheel) on `lmsysorg/sglang:v0.5.20-cu130` | rtx-pro-6000 | 16-page windows; ≥48 GB GPU |
|
| 97 |
| `unlimited-ocr2-saturate.py` | 🧪+image | same | rtx-pro-6000 | tuned/experimental: repair pass, JP2 fast decode, PDFs |
|
| 98 |
| `unlimited-ocr2-live.py` | 🧪+image | same | rtx-pro-6000 | experimental: minimal script + `--live-port` dashboard (streams the page being read) |
|
| 99 |
+
| `hpd-parsing-saturate.py` | 🧪+image | saturate + Paddle's vLLM fork on `cr.hf.co/davanstrien/hpd-parsing-vllm` (vendor image + uv) | l4x1 | `markdown` + `hpd_blocks` + `looped_blocks` — see gotcha |
|
| 100 |
| `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` |
|
| 101 |
| `surya-ocr.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | offline backend inject; site-packages PYTHONPATH |
|
| 102 |
| `surya-ocr-bucket.py` | ✅+image | vLLM `:v0.20.1` | l4x1 | bucket I/O; pin `surya-ocr==0.20.0` |
|
|
|
|
| 192 |
- vLLM runs in its own process group and is terminated → killed → reaped on every exit path; one bad
|
| 193 |
image or a failed SDK run marks its pages `error: ...` instead of losing finished batches.
|
| 194 |
|
| 195 |
+
### `hpd-parsing-saturate.py` — Paddle's vLLM fork, on their image plus uv
|
| 196 |
+
`PaddlePaddle/HPD-Parsing` (1B, InternVL3.5 + Qwen3-0.6B) runs only on Paddle's **fork of vLLM**
|
| 197 |
+
(`0.17.1+hpdparsing`), which adds the request forking its decoding needs. The fork ships only in
|
| 198 |
+
`ccr-2vdh3abv-pub.cnc.bj.baidubce.com/paddlepaddle/hpd-parsing-vllm` (tags `latest-nvidia-gpu`, and
|
| 199 |
+
`-offline` with weights baked in). It pulls anonymously; the recipe pins `latest-nvidia-gpu` by digest
|
| 200 |
+
(`87496aa5…`, built 2026-07-16, unchanged as of 2026-11-05). ~11 GB. Job scheduling time (queue + pull) on
|
| 201 |
+
5 Nov: 7–27 min from Paddle's registry, 2.5 min for the same image from `cr.hf.co`.
|
| 202 |
+
Inside: CUDA 12.8.1, python3.10 venv at `/home/hpd/venv` first on `PATH`, user `hpd`, FlashInfer.
|
| 203 |
+
Measured 2026-07-27 and 2026-11-05:
|
| 204 |
+
1. **No `uv` in Paddle's image**, which `hf jobs uv run` needs. The header uses
|
| 205 |
+
`cr.hf.co/davanstrien/hpd-parsing-vllm`: Paddle's image (digest-pinned) plus one layer with `uv`/`uvx`
|
| 206 |
+
(`images/hpd-parsing/build.sh`, `crane append` on a CPU Job, ~7 min; public). To rebuild after a Paddle
|
| 207 |
+
update, change `BASE_DIGEST` in `build.sh`. The docstring keeps a `hf jobs run … bash -lc 'pip install uv
|
| 208 |
+
&& uv run …'` command for Paddle's image directly.
|
| 209 |
+
2. `requires-python` includes 3.10 so uv uses the image's own Python instead of downloading one.
|
| 210 |
+
3. **Speculative head path:** the entrypoint's `"model": "PaddlePaddle/HPD-Parsing/P-MTP"` is a local
|
| 211 |
+
directory in the `-offline` image only. The recipe downloads the `P-MTP/*` subfolder and passes its
|
| 212 |
+
path. Expected log line, every run: `Error retrieving safetensors: Repo id must be in the form …`.
|
| 213 |
+
4. **`--enable-prefix-caching` stays ON** (forked children share the parent's prefix KV; 43.9–52.9% hit
|
| 214 |
+
rate). `--attention-config '{"use_prefill_query_quantization":true}'` is fork-only. Both come from
|
| 215 |
+
`/home/hpd/entrypoint.sh`. Works on `a100-large` (sm80) as well as `l4x1`.
|
| 216 |
+
5. **Bboxes are 0–1000 normalized**, not pixels (`px = v/1000 * width`), verified by overlay in July.
|
| 217 |
+
The parser is the demo Space's bbox-preserving `parse_blocks`; the model repo's `eval/hpd_to_markdown.py`
|
| 218 |
+
drops chart/seal blocks and bboxes. Re-parsing July's `hpd_raw` reproduced July's markdown on 34/34 pages.
|
| 219 |
+
6. saturate's readiness probe logs `The model 'readiness-probe' does not exist` (404) once; that is the
|
| 220 |
+
"server is alive" signal, not an error.
|
| 221 |
+
|
| 222 |
+
**Limits seen in testing: loops, and `max_tokens` does not bound a page.** Each forked child branch has
|
| 223 |
+
its own `max_tokens` budget, so a page that fragments into hundreds of regions can emit far more than the
|
| 224 |
+
cap (179k completion tokens for one page at `max_tokens` 8000). On 12 Chronicling America pages
|
| 225 |
+
(1774–1809), 3 pages looped: 726,706 chars (July) / 544,120 (November) vs 24,907 in LoC's OCR on the
|
| 226 |
+
worst. Those 3 ended with `finish_reason=length`, the other 9 with `stop`, and `looped_blocks` > 0 on
|
| 227 |
+
exactly the same 3. One UFO page had a 26,675-char loop. `looped_blocks` counts blocks
|
| 228 |
+
of ≥2000 bytes whose zlib ratio is ≥4 (≥10 for `table`): ordinary text compresses ~2×, loops 6–330×
|
| 229 |
+
(a counting loop "of the 860th of the 861th …" is the 6× case), the most compressible real block was a
|
| 230 |
+
1.5 KB table at 5.3×. Calibrated on 345 blocks from the July outputs: 0 false positives. The text is
|
| 231 |
+
kept as the model wrote it; filter rows on `looped_blocks == 0`. Accuracy (94.91 OmniDocBench v1.6) is
|
| 232 |
+
below `ovis-ocr2`/`paddleocr-vl-1.6`; the recipe earns its place with the layout column. en/zh only.
|
| 233 |
+
|
| 234 |
+
`hpd-parsing-server.py` (PR #95, July) is the hand-rolled driver for the same server; this recipe
|
| 235 |
+
replaces it.
|
| 236 |
+
|
| 237 |
### `unlimited-ocr2.py` / `unlimited-ocr2-saturate.py` — Baidu SGLang wheel, multi-page windows
|
| 238 |
v2 has no vLLM support; Baidu ships a custom SGLang wheel in the model repo. Its pins (torch 2.13.0,
|
| 239 |
transformers 5.12.1, flashinfer 0.6.18 cu13) match **`lmsysorg/sglang:v0.5.20`** exactly → `-cu130` image,
|
|
|
|
| 387 |
|
| 388 |
## Change log
|
| 389 |
|
| 390 |
+
- **2026-11-05** — added `hpd-parsing-saturate.py` (experimental) for `PaddlePaddle/HPD-Parsing` (1B,
|
| 391 |
+
Apache-2.0): the July server recipe's serve command and block parser, driven by saturate `==0.3.0`
|
| 392 |
+
(`Engine(cmd=…)` for the vendor fork), plus a `looped_blocks` flag. Header image
|
| 393 |
+
`cr.hf.co/davanstrien/hpd-parsing-vllm` = Paddle's image (pinned by digest) + uv (`images/hpd-parsing/`). Smoke-tested on HF Jobs: `a100-large`, 10 UFO pages, 10/10, 0
|
| 394 |
+
error rows, 12 s pump time; `l4x1`, 12 Chronicling America pages in two runs to one repo (5, then 12:
|
| 395 |
+
the second run skipped the 5 done rows), 12/12, 0 error rows; 9 clean pages within 1–5% of LoC's OCR
|
| 396 |
+
length, 3 looping pages flagged. Header defaults on the public image (`l4x1`, published-path
|
| 397 |
+
equivalent: local script, no flags but `--max-samples 5`): 5/5, 0 error rows, 153 s scheduling incl. pull.
|
| 398 |
+
|
| 399 |
- **2026-11-02** — `xiaomi-ocr-0-saturate.py` moved to `core`. NASA demo: 7/7 in 31 s; checked pages read well, but a table lost one item and some cells lost separators. 16 multilingual historical newspaper pages: 16/16 with no error rows, but repetition loops on 2 small-print German Fraktur pages (lines about 10–13 px after the 2048 px fit), a partial loop on a third, and Chinese characters inserted on 3 pages. `finish_reason` stayed `stop` on all of them.
|
| 400 |
- **2026-10-30** — added `xiaomi-ocr-0-saturate.py` for `xiaomi-research/Xiaomi-OCR-0` (0.8B, Qwen3.5 arch), on
|
| 401 |
saturate `==0.3.0`. Do not set `max_limit` by copying older saturate recipes: on `rtx-pro-6000`, `Auto(max_limit=48)`
|
LANGUAGES.md
CHANGED
|
@@ -21,6 +21,7 @@ _Sorted by strength of evidence, then coverage:_
|
|
| 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 |
|
|
|
|
| 21 |
| [PaddleOCR-VL](https://huggingface.co/PaddlePaddle/PaddleOCR-VL) / [1.5](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.5) / [1.6](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.6) | 109 languages; 1.5 adds Tibetan + Bengali | Names scripts (Cyrillic, Arabic, Devanagari, Thai) and claims handwriting + historical documents; no per-language numbers |
|
| 22 |
| [PP-OCRv6](https://huggingface.co/collections/PaddlePaddle/pp-ocrv6) | 48 languages | Official card claim |
|
| 23 |
| [MiniCPM-OCR 1.0](https://huggingface.co/openbmb/MiniCPM-OCR-1.0) | Chinese and English ("primary languages") | Card names two; no per-language numbers. Examples include historical scans |
|
| 24 |
+
| [HPD-Parsing](https://huggingface.co/PaddlePaddle/HPD-Parsing) | 2 (en, zh) | Card metadata only. On degraded French scans our smoke runs (July and November 2026) produced stray Chinese characters mid-word, so treat languages other than en/zh as unsupported |
|
| 25 |
| [Nanonets-OCR2-3B](https://huggingface.co/nanonets/Nanonets-OCR2-3B) | 11 named + "many more" (incl. Arabic + CJK) | Illustrative list, no benchmark — but the only card claiming multilingual **handwriting** |
|
| 26 |
| [LightOnOCR-2-1B](https://huggingface.co/lightonai/LightOnOCR-2-1B) | 11 (9 European + zh/ja) | Declared, not benchmarked. [v1](https://huggingface.co/lightonai/LightOnOCR-1B-1025) is explicitly European/Latin-script only (9) |
|
| 27 |
| [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) | 8 (zh en fr es ru de ja ko) | Declared in card metadata only; no per-language evidence in the card body |
|
README.md
CHANGED
|
@@ -219,6 +219,15 @@ hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/pp-doclay
|
|
| 219 |
your-dataset your-layout-output --max-samples 10
|
| 220 |
```
|
| 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).
|
|
|
|
| 219 |
your-dataset your-layout-output --max-samples 10
|
| 220 |
```
|
| 221 |
|
| 222 |
+
**[HPD-Parsing](https://huggingface.co/PaddlePaddle/HPD-Parsing)** (`hpd-parsing-saturate.py`, 1B, Apache-2.0, experimental) reads text and layout in one pass. Next to the `markdown` it writes an `hpd_blocks` column with a type, a box and the text for each block, in reading order. The boxes are on a 0–1000 scale, not pixels. The model needs Paddle's own vLLM build; the script header picks an image with it ([`images/hpd-parsing/`](images/hpd-parsing/)).
|
| 223 |
+
|
| 224 |
+
```bash
|
| 225 |
+
hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/hpd-parsing-saturate.py \
|
| 226 |
+
your-dataset your-output --max-samples 5
|
| 227 |
+
```
|
| 228 |
+
|
| 229 |
+
The image is about 11 GB, so a cold start takes several minutes. On dense pages with hundreds of blocks the model can repeat itself inside many blocks at once. The `looped_blocks` column counts those blocks; keep rows where it is 0. The model card lists English and Chinese only.
|
| 230 |
+
|
| 231 |
## Scaling up
|
| 232 |
|
| 233 |
**Large datasets:** `lighton-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).
|
SERVING.md
CHANGED
|
@@ -50,6 +50,12 @@ recipe, LightOn's card, Paddle's vLLM recipe, Unlimited-OCR's recipe):
|
|
| 50 |
|
| 51 |
OCR workloads never reuse images, so prefix/multimodal caches only cost memory.
|
| 52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
## Version pins carry over — via the image tag
|
| 54 |
|
| 55 |
Where an offline recipe pins an engine version, the server variant needs the same pin
|
|
|
|
| 50 |
|
| 51 |
OCR workloads never reuse images, so prefix/multimodal caches only cost memory.
|
| 52 |
|
| 53 |
+
**One exception: HPD-Parsing** (`hpd-parsing-saturate.py`). Its vendor entrypoint sets
|
| 54 |
+
`--enable-prefix-caching` on purpose. Hierarchical parallel decoding forks a child branch per
|
| 55 |
+
page region, and the children reuse the parent branch's prefix KV, so the cache does real work
|
| 56 |
+
(hit rate 52.9% on 5 UFO pages in July 2026, 43.9% on 10 in November). Do not change it to
|
| 57 |
+
`--no-enable-prefix-caching` in a sweep.
|
| 58 |
+
|
| 59 |
## Version pins carry over — via the image tag
|
| 60 |
|
| 61 |
Where an offline recipe pins an engine version, the server variant needs the same pin
|
hpd-parsing-saturate.py
ADDED
|
@@ -0,0 +1,558 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.10,<3.15"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "saturate[hf]==0.3.0",
|
| 5 |
+
# "pillow>=10",
|
| 6 |
+
# ]
|
| 7 |
+
#
|
| 8 |
+
# [tool.hf-jobs]
|
| 9 |
+
# image = "cr.hf.co/davanstrien/hpd-parsing-vllm:87496aa5-uv0.13.6"
|
| 10 |
+
# flavor = "l4x1"
|
| 11 |
+
# timeout = "2h"
|
| 12 |
+
# secrets = ["HF_TOKEN"]
|
| 13 |
+
# ///
|
| 14 |
+
"""
|
| 15 |
+
Parse document images with HPD-Parsing via saturate.
|
| 16 |
+
|
| 17 |
+
HPD-Parsing (1B, InternVL3.5-1B vision + Qwen3-0.6B) parses a page with
|
| 18 |
+
*hierarchical parallel decoding*: a main layout branch emits `<BLOCK> <type>
|
| 19 |
+
[bbox]` headers and forks a child branch per region (children reuse the parent's
|
| 20 |
+
prefix KV), with a P-MTP medusa head drafting tokens inside each branch. Its
|
| 21 |
+
output carries a type, a bbox and reading order for every block; this recipe keeps
|
| 22 |
+
them in an `hpd_blocks` column next to the markdown.
|
| 23 |
+
|
| 24 |
+
The server half is the vendor's own `vllm serve` command, started in the job. The
|
| 25 |
+
driver half (concurrency, retries, output, resume) is the `saturate` library:
|
| 26 |
+
adaptive concurrency, resumable parquet output and durable error rows.
|
| 27 |
+
|
| 28 |
+
NEEDS PADDLE'S vLLM FORK. Forking is a scheduler feature of Paddle's vLLM fork
|
| 29 |
+
(`0.17.1+hpdparsing`), which ships in their registry image. The [tool.hf-jobs]
|
| 30 |
+
header above names `cr.hf.co/davanstrien/hpd-parsing-vllm`: Paddle's image
|
| 31 |
+
(`latest-nvidia-gpu`, pinned by digest, built 2026-07-16) plus `uv`, which their
|
| 32 |
+
image lacks. Build script and digest: images/hpd-parsing/ in the uv-scripts repo.
|
| 33 |
+
Run on HF Jobs (`hf` CLI 1.32+ reads image, flavor, timeout and secrets from the
|
| 34 |
+
header):
|
| 35 |
+
|
| 36 |
+
hf jobs uv run --detach \\
|
| 37 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/hpd-parsing-saturate.py \\
|
| 38 |
+
<input-dataset> <output-dataset>
|
| 39 |
+
|
| 40 |
+
Smoke test first with --max-samples 5. Budget for an ~11 GB image pull on a cold
|
| 41 |
+
node before anything runs. requires-python includes 3.10 so that uv uses the
|
| 42 |
+
image's own Python (3.10) instead of downloading one.
|
| 43 |
+
|
| 44 |
+
On Paddle's image directly (no uv in it), install uv in the job command:
|
| 45 |
+
|
| 46 |
+
hf jobs run --detach --flavor l4x1 -s HF_TOKEN --timeout 2h \\
|
| 47 |
+
ccr-2vdh3abv-pub.cnc.bj.baidubce.com/paddlepaddle/hpd-parsing-vllm@sha256:87496aa5dd702a7df6c70bb00c29d5bf8d1a0f0505d66b613fafa6f71cd72de2 \\
|
| 48 |
+
-- bash -lc 'pip install -q uv==0.13.6 && uv run \\
|
| 49 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/hpd-parsing-saturate.py \\
|
| 50 |
+
<input-dataset> <output-dataset>'
|
| 51 |
+
|
| 52 |
+
Output: the output repo (created private if missing) holds `data/part-*.parquet`
|
| 53 |
+
with rows `{id, markdown, hpd_blocks, raw, looped_blocks, finish_reason, model,
|
| 54 |
+
prompt_tokens, completion_tokens, error}` keyed by the input row id
|
| 55 |
+
(`--id-column`, or `<repo>:<config>:<split>:<000000000>` by default). Read it with
|
| 56 |
+
`saturate.read_output`, which keeps one row per id (a success over an earlier
|
| 57 |
+
error). `datasets.load_dataset(<output>, data_dir="data")` returns every record,
|
| 58 |
+
so after a --retry-errors run it also holds the old error rows: drop rows with an
|
| 59 |
+
`error` before you join back to the input on id. Re-running the same command
|
| 60 |
+
skips finished rows; --retry-errors re-admits failed ones.
|
| 61 |
+
|
| 62 |
+
- `hpd_blocks`: JSON list, one entry per region in the model's reading order:
|
| 63 |
+
`{"type": "text|title|table|formula|figure|...", "bbox": [x1, y1, x2, y2], "text": "..."}`.
|
| 64 |
+
BBOX SPACE: 0-1000 **normalized**, not pixels. Convert with
|
| 65 |
+
`px = value / 1000 * width`. Container blocks (`list`, the `table` wrapper)
|
| 66 |
+
and `chart`/`seal` regions carry a bbox with empty `text`.
|
| 67 |
+
- `raw`: the model's untouched `<BLOCK>/<FORK>/<CHILD>` stream.
|
| 68 |
+
- `looped_blocks`: number of blocks whose text is a repetition loop (see Limits).
|
| 69 |
+
|
| 70 |
+
Model: PaddlePaddle/HPD-Parsing (Apache-2.0), paper arXiv:2607.18839
|
| 71 |
+
- Card prompt `document parsing with fork.` (hierarchical parallel decoding);
|
| 72 |
+
--no-fork sends the card's single-trajectory `document parsing.` for an A/B.
|
| 73 |
+
- Image before text, greedy decoding, max_tokens 8000, context 16384: the card's
|
| 74 |
+
values.
|
| 75 |
+
- Block parsing and formula clean-up adapted from the model repo's Apache-2.0
|
| 76 |
+
`eval/hpd_to_markdown.py`, via the bbox-preserving `parse_blocks` in
|
| 77 |
+
multimodalart's demo Space (hugging-apps/hpd-parsing, `hpd_postprocess.py`).
|
| 78 |
+
|
| 79 |
+
Limits seen in testing:
|
| 80 |
+
- `max_tokens` bounds ONE decoding branch, not the page. A dense page that
|
| 81 |
+
fragments into hundreds of blocks can loop inside many children at once: on 12
|
| 82 |
+
Chronicling America pages (1774-1809), 3 pages looped, one emitting 544k
|
| 83 |
+
characters against 24.9k in LoC's own OCR. Nothing errors. This recipe flags
|
| 84 |
+
such blocks in `looped_blocks` and leaves the text as the model wrote it.
|
| 85 |
+
Filter on `looped_blocks == 0`, or drop the looped blocks from `hpd_blocks`
|
| 86 |
+
yourself. On those 12 pages the 3 looping pages also ended with
|
| 87 |
+
`finish_reason` "length" and the other 9 with "stop".
|
| 88 |
+
- Card languages are en and zh. A smoke run on degraded French scans produced
|
| 89 |
+
stray CJK tokens.
|
| 90 |
+
|
| 91 |
+
The SERVING dict below is the per-model tuning prior. Agents can `ast.literal_eval`
|
| 92 |
+
it without running the script; the script itself consumes it.
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
import argparse
|
| 96 |
+
import base64
|
| 97 |
+
import io
|
| 98 |
+
import json
|
| 99 |
+
import math
|
| 100 |
+
import os
|
| 101 |
+
import re
|
| 102 |
+
import shutil
|
| 103 |
+
import subprocess
|
| 104 |
+
import sys
|
| 105 |
+
import zlib
|
| 106 |
+
|
| 107 |
+
# Serving starting values for PaddlePaddle/HPD-Parsing. Per-value provenance:
|
| 108 |
+
# - serve_args: the vendor image's own /home/hpd/entrypoint.sh, verbatim, except
|
| 109 |
+
# for the speculative head path (see serve_command) and an added --revision pin.
|
| 110 |
+
# Two flags look wrong and are not:
|
| 111 |
+
# * --enable-prefix-caching contradicts the house OCR default (SERVING.md: OCR
|
| 112 |
+
# never reuses images). Here the forked children share the parent branch's
|
| 113 |
+
# prefix KV, so the cache is load-bearing (52.9% hit rate measured, 2026-07-27).
|
| 114 |
+
# * --attention-config use_prefill_query_quantization is a fork-only flag.
|
| 115 |
+
# - served_model_name / port 8118: the entrypoint's values; requests use the name.
|
| 116 |
+
# - max_model_len 16384, max_tokens 8000, temperature 0.0: card values.
|
| 117 |
+
# - max_pixels 0 (no client-side downscale): the model picks its 448 px tile grid
|
| 118 |
+
# partly from image area (find_closest_aspect_ratio_optim), so pre-shrinking can
|
| 119 |
+
# land a page on a smaller grid. Set --max-pixels only for huge payloads.
|
| 120 |
+
# - image: Paddle's `latest-nvidia-gpu` tag pinned by digest on 2026-11-05
|
| 121 |
+
# (base_image), plus uv (image; built by images/hpd-parsing/build.sh).
|
| 122 |
+
SERVING = {
|
| 123 |
+
"model": "PaddlePaddle/HPD-Parsing",
|
| 124 |
+
"revision": "91de80054c23ab4238e3d7073fa2b83c2a7e301e",
|
| 125 |
+
"served_model_name": "HPD-Parsing",
|
| 126 |
+
"image": "cr.hf.co/davanstrien/hpd-parsing-vllm:87496aa5-uv0.13.6",
|
| 127 |
+
"base_image": (
|
| 128 |
+
"ccr-2vdh3abv-pub.cnc.bj.baidubce.com/paddlepaddle/hpd-parsing-vllm"
|
| 129 |
+
"@sha256:87496aa5dd702a7df6c70bb00c29d5bf8d1a0f0505d66b613fafa6f71cd72de2"
|
| 130 |
+
),
|
| 131 |
+
"port": 8118,
|
| 132 |
+
"max_model_len": 16384,
|
| 133 |
+
"serve_args": [
|
| 134 |
+
"--trust-remote-code",
|
| 135 |
+
"--host", "0.0.0.0",
|
| 136 |
+
"--limit-mm-per-prompt", '{"image": 1}',
|
| 137 |
+
"--gpu-memory-utilization", "0.9",
|
| 138 |
+
"--attention-backend", "FLASHINFER",
|
| 139 |
+
"--attention-config", '{"use_prefill_query_quantization":true}',
|
| 140 |
+
"--enable-chunked-prefill",
|
| 141 |
+
"--enable-prefix-caching",
|
| 142 |
+
],
|
| 143 |
+
"num_speculative_tokens": 6,
|
| 144 |
+
"max_tokens": 8000,
|
| 145 |
+
"temperature": 0.0,
|
| 146 |
+
"max_pixels": 0,
|
| 147 |
+
} # fmt: skip
|
| 148 |
+
assert SERVING["max_tokens"] < SERVING["max_model_len"], (
|
| 149 |
+
"context math: max_tokens must leave room for the image tokens "
|
| 150 |
+
"(input + output <= max_model_len, or every request 400s)"
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
# Card-verbatim prompts. Do not "improve" either.
|
| 154 |
+
FORK_PROMPT = "document parsing with fork."
|
| 155 |
+
PLAIN_PROMPT = "document parsing."
|
| 156 |
+
|
| 157 |
+
RUN_COMMAND = (
|
| 158 |
+
f"hf jobs uv run --detach --image {SERVING['image']} --flavor l4x1 -s HF_TOKEN \\\n"
|
| 159 |
+
" https://huggingface.co/datasets/uv-scripts/ocr/raw/main/hpd-parsing-saturate.py \\\n"
|
| 160 |
+
" <input-dataset> <output-dataset>"
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def to_pil(value):
|
| 165 |
+
from PIL import Image
|
| 166 |
+
|
| 167 |
+
if isinstance(value, Image.Image):
|
| 168 |
+
return value
|
| 169 |
+
if isinstance(value, dict) and value.get("bytes"):
|
| 170 |
+
return Image.open(io.BytesIO(value["bytes"]))
|
| 171 |
+
if isinstance(value, (bytes, bytearray)):
|
| 172 |
+
return Image.open(io.BytesIO(value))
|
| 173 |
+
raise ValueError(f"unsupported image value: {type(value)}")
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def encode_image(value, max_pixels: int) -> str:
|
| 177 |
+
"""RGB-convert, downscale only if max_pixels is set, return base64 JPEG q95."""
|
| 178 |
+
from PIL import Image
|
| 179 |
+
|
| 180 |
+
img = to_pil(value).convert("RGB")
|
| 181 |
+
w, h = img.size
|
| 182 |
+
if max_pixels and w * h > max_pixels:
|
| 183 |
+
scale = math.sqrt(max_pixels / (w * h))
|
| 184 |
+
img = img.resize((max(1, int(w * scale)), max(1, int(h * scale))), Image.LANCZOS)
|
| 185 |
+
buf = io.BytesIO()
|
| 186 |
+
img.save(buf, format="JPEG", quality=95)
|
| 187 |
+
return base64.b64encode(buf.getvalue()).decode()
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
# --- Formula cleaning (verbatim from the model repo's eval/hpd_to_markdown.py) ---
|
| 191 |
+
|
| 192 |
+
_TALL = re.compile(
|
| 193 |
+
r'\\d?frac|\\tfrac|\\cfrac|\\binom|\\sqrt'
|
| 194 |
+
r'|\\sum|\\prod|\\coprod|\\int|\\iint|\\iiint|\\oint'
|
| 195 |
+
r'|\\bigcup|\\bigcap|\\bigoplus|\\bigotimes|\\bigsqcup'
|
| 196 |
+
r'|\\begin\{'
|
| 197 |
+
r'|\\overbrace|\\underbrace|\\overset|\\underset|\\stackrel'
|
| 198 |
+
r'|\\substack|\\atop|\\\\'
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _scan_delims(s):
|
| 203 |
+
out = []
|
| 204 |
+
for m in re.finditer(r'\\(left|right)\s*', s):
|
| 205 |
+
dm = re.match(r'\\[a-zA-Z]+|\\.|.', s[m.end():])
|
| 206 |
+
if not dm:
|
| 207 |
+
continue
|
| 208 |
+
out.append({'kind': m.group(1), 'delim': dm.group(0),
|
| 209 |
+
'start': m.start(), 'end': m.end() + dm.end()})
|
| 210 |
+
return out
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def simplify_left_right(s: str) -> str:
|
| 214 |
+
"""Downgrade `\\left( ... \\right)` with no tall inner structure to plain `( )`."""
|
| 215 |
+
if '\\left' not in s:
|
| 216 |
+
return s
|
| 217 |
+
stack, pairs = [], []
|
| 218 |
+
for d in _scan_delims(s):
|
| 219 |
+
if d['kind'] == 'left':
|
| 220 |
+
stack.append(d)
|
| 221 |
+
elif stack:
|
| 222 |
+
pairs.append((stack.pop(), d))
|
| 223 |
+
edits = []
|
| 224 |
+
for L, R in pairs:
|
| 225 |
+
if L['delim'] == '(' and R['delim'] == ')' and not _TALL.search(s[L['end']:R['start']]):
|
| 226 |
+
edits.append((L['start'], L['end'], '('))
|
| 227 |
+
edits.append((R['start'], R['end'], ')'))
|
| 228 |
+
for st, en, rep in sorted(edits, key=lambda x: x[0], reverse=True):
|
| 229 |
+
s = s[:st] + rep + s[en:]
|
| 230 |
+
return s
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
_ELLIPSIS = r'(?:\\dots|\\cdots|\\ldots|\\dotsb|\\dotsc)'
|
| 234 |
+
_CLOSER = r'(?:\\right\s*[.\}\]\)]|\\end\s*\{(?:array|matrix|cases|bmatrix|pmatrix|vmatrix|smallmatrix)\})'
|
| 235 |
+
_TAIL_WRAP = re.compile(r'^(?P<core>.*?)(?P<wrap>\s*(?:\\\]|\\\)|\$\$))?\s*$', re.DOTALL)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def clean_formula_tail(s: str) -> str:
|
| 239 |
+
"""Strip degenerate formula tails (repeated/dangling ellipses, stray `\\quad`)."""
|
| 240 |
+
if not s:
|
| 241 |
+
return s
|
| 242 |
+
m = _TAIL_WRAP.match(s)
|
| 243 |
+
core, wrap = m.group('core'), m.group('wrap') or ''
|
| 244 |
+
prev = None
|
| 245 |
+
while prev != core:
|
| 246 |
+
prev = core
|
| 247 |
+
core = re.sub(r'(' + _ELLIPSIS + r')(?:\s*' + _ELLIPSIS + r')+', r'\1', core)
|
| 248 |
+
core = re.sub(r'(?P<keep>' + _CLOSER + r')\s*(?:\\q?quad\s*)*' + _ELLIPSIS + r'\s*$',
|
| 249 |
+
lambda mm: mm.group('keep'), core)
|
| 250 |
+
core = re.sub(r'(?:\s*\\q?quad)+\s*' + _ELLIPSIS + r'\s*$', '', core)
|
| 251 |
+
core = re.sub(r'(?:\s*\\q?quad)+\s*$', '', core)
|
| 252 |
+
core = core.rstrip()
|
| 253 |
+
return core + wrap
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
_OP_MAP = {
|
| 257 |
+
'≈': r'\approx', '≠': r'\neq', '≤': r'\leq', '≥': r'\geq', '×': r'\times',
|
| 258 |
+
'÷': r'\div', '±': r'\pm', '∓': r'\mp', '·': r'\cdot', '∙': r'\cdot',
|
| 259 |
+
'⋅': r'\cdot', '∗': '*', '−': '-', '≡': r'\equiv', '∝': r'\propto',
|
| 260 |
+
'∞': r'\infty', '√': r'\sqrt', '→': r'\to', '≪': r'\ll', '≫': r'\gg',
|
| 261 |
+
}
|
| 262 |
+
_ARITH_ALLOWED = re.compile(r'^[0-9A-Za-z\s=+\-*/^_().,:;<>|%!\u4e00-\u9fff' + ''.join(_OP_MAP.keys()) + r']+$')
|
| 263 |
+
_ARITH_HASOP = re.compile(r'[=+\-*/' + ''.join(_OP_MAP.keys()) + r']')
|
| 264 |
+
_KNOWN_FUNCS = {'sin', 'cos', 'tan', 'cot', 'sec', 'csc', 'log', 'ln', 'exp',
|
| 265 |
+
'lim', 'max', 'min', 'det', 'mod', 'arcsin', 'arccos', 'arctan', 'sqrt'}
|
| 266 |
+
_CJK_RUN = re.compile(r'[\u4e00-\u9fff]+')
|
| 267 |
+
_MATH_SPAN = re.compile(r'(\\\[.*?\\\]|\$\$.*?\$\$|\\\(.*?\\\)|\$.*?\$)', re.DOTALL)
|
| 268 |
+
|
| 269 |
+
WRAP_CJK_IN_ARITH = True
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def _convert_unicode_ops(s: str) -> str:
|
| 273 |
+
for k, v in _OP_MAP.items():
|
| 274 |
+
s = s.replace(k, (v + ' ') if v.startswith('\\') else v)
|
| 275 |
+
if WRAP_CJK_IN_ARITH:
|
| 276 |
+
s = _CJK_RUN.sub(lambda m: r'\text{' + m.group(0) + '}', s)
|
| 277 |
+
return re.sub(r'[ \t]{2,}', ' ', s)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def _is_pure_arith_line(line: str) -> bool:
|
| 281 |
+
t = line.strip()
|
| 282 |
+
if not t or '\\(' in t or '\\[' in t or '$' in t or '<' in t:
|
| 283 |
+
return False
|
| 284 |
+
if not WRAP_CJK_IN_ARITH and re.search(r'[\u4e00-\u9fff]', t):
|
| 285 |
+
return False
|
| 286 |
+
if not _ARITH_ALLOWED.match(t) or not _ARITH_HASOP.search(t):
|
| 287 |
+
return False
|
| 288 |
+
return all(w.lower() in _KNOWN_FUNCS for w in re.findall(r'[A-Za-z]{2,}', t))
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def normalize_arith(text: str) -> str:
|
| 292 |
+
"""Normalize Unicode operators to LaTeX and wrap pure-arithmetic lines as `\\( .. \\)`."""
|
| 293 |
+
if not text:
|
| 294 |
+
return text
|
| 295 |
+
text = _MATH_SPAN.sub(lambda m: _convert_unicode_ops(m.group(0)), text)
|
| 296 |
+
out = []
|
| 297 |
+
for line in text.split('\n'):
|
| 298 |
+
if _is_pure_arith_line(line):
|
| 299 |
+
out.append('\\( ' + _convert_unicode_ops(line.strip()) + ' \\)')
|
| 300 |
+
else:
|
| 301 |
+
out.append(line)
|
| 302 |
+
return '\n'.join(out)
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def clean_text(text: str) -> str:
|
| 306 |
+
"""Per-block cleaning, matching the official hpd_to_markdown.py steps."""
|
| 307 |
+
text = text.strip()
|
| 308 |
+
text = text.replace('The image is too blurry to recognize any text content.', '').strip()
|
| 309 |
+
text = text.replace(
|
| 310 |
+
"The image contains no text or characters. It is a graphical element (a horizontal "
|
| 311 |
+
"line with a vertical line) and does not contain any chart, graph, or data points "
|
| 312 |
+
"that can be extracted. Therefore, the correct OCR output is an empty string.", ""
|
| 313 |
+
).strip()
|
| 314 |
+
if not text or text == '[Non-Text]':
|
| 315 |
+
return ''
|
| 316 |
+
if text.startswith('\\[') and not text.endswith('\n\\]'):
|
| 317 |
+
text += '\n\\]'
|
| 318 |
+
if text.startswith('<table>') and not text.endswith('</table>'):
|
| 319 |
+
text += '</table>'
|
| 320 |
+
if '\\[\n' in text and '\\\\' not in text:
|
| 321 |
+
text = text.replace('\\[\n', '\\(').replace('\n\\]', '\\)')
|
| 322 |
+
text = text.replace('\\) \\(', '\\)\n\n\\(')
|
| 323 |
+
if '÷' in text and '\\(' not in text:
|
| 324 |
+
text = '\\( ' + text + ' \\)'
|
| 325 |
+
text = re.sub(r'\\tag\s*\{[^{}]*\}', '', text)
|
| 326 |
+
text = text.replace('\\supset', '\\sqsupset')
|
| 327 |
+
text = simplify_left_right(text)
|
| 328 |
+
text = clean_formula_tail(text)
|
| 329 |
+
return normalize_arith(text)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
# --- Block parsing (bbox-preserving; the official script discards bboxes) ---
|
| 333 |
+
|
| 334 |
+
# type + [bbox], usually followed by <FORK|CHILD|BLOCK>. Container blocks such as
|
| 335 |
+
# `list [x1,y1,x2,y2]` may have no trailing tag at all, so the tag is optional.
|
| 336 |
+
_BLOCK_HEADER = re.compile(r'([a-zA-Z_]+)\s*\[\s*([-\d.,\s]+)\]\s*(?:<(?:FORK|CHILD|BLOCK)>)?')
|
| 337 |
+
_NO_CONTENT_TYPES = {'chart', 'seal'}
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def parse_blocks(raw_text: str) -> list[dict]:
|
| 341 |
+
"""Parse the `<BLOCK> <type> [bbox] <CHILD> <content>` stream.
|
| 342 |
+
|
| 343 |
+
Returns `[{"type": str, "bbox": [x1,y1,x2,y2] | None, "text": str}, ...]` in the
|
| 344 |
+
model's own reading order. `bbox` is in the model's native 0-1000 NORMALIZED
|
| 345 |
+
coordinate space, not pixels. `text` is empty for container blocks (e.g. `list`,
|
| 346 |
+
the `table` wrapper) and for `chart`/`seal`, matching the official export.
|
| 347 |
+
"""
|
| 348 |
+
blocks = []
|
| 349 |
+
for seg in raw_text.split('<BLOCK>')[1:]:
|
| 350 |
+
header_m = _BLOCK_HEADER.match(seg.strip())
|
| 351 |
+
type_m = re.match(r'\s*([a-zA-Z_]+)', seg)
|
| 352 |
+
block_type = type_m.group(1) if type_m else 'unknown'
|
| 353 |
+
|
| 354 |
+
bbox = None
|
| 355 |
+
if header_m:
|
| 356 |
+
block_type = header_m.group(1)
|
| 357 |
+
nums = [float(x) for x in re.split(r'[,\s]+', header_m.group(2).strip()) if x]
|
| 358 |
+
if len(nums) == 4:
|
| 359 |
+
bbox = nums
|
| 360 |
+
|
| 361 |
+
text = ''
|
| 362 |
+
if block_type.lower() not in _NO_CONTENT_TYPES:
|
| 363 |
+
content_m = re.search(r'<CHILD>(.*)', seg, re.DOTALL)
|
| 364 |
+
if content_m:
|
| 365 |
+
# stop at the next control tag if any leaked through
|
| 366 |
+
raw_content = re.split(r'<(?:FORK|CHILD|BLOCK)>', content_m.group(1))[0]
|
| 367 |
+
text = clean_text(raw_content)
|
| 368 |
+
|
| 369 |
+
blocks.append({'type': block_type, 'bbox': bbox, 'text': text})
|
| 370 |
+
return blocks
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
def blocks_to_markdown(blocks: list[dict]) -> str:
|
| 374 |
+
"""Join the non-empty block texts in reading order into one markdown string."""
|
| 375 |
+
return '\n\n'.join(b['text'] for b in blocks if b['text']).strip()
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
# --- Loop flag ---
|
| 379 |
+
|
| 380 |
+
# Calibrated on the 2026-07-27 test outputs (ChronAm, OmniDocBench, UFO; 345 blocks of
|
| 381 |
+
# 200+ bytes). Ordinary text blocks of 2000+ bytes compress about 2x with zlib; looping
|
| 382 |
+
# blocks compressed 6x (a counting loop: "of the 860th of the 861th ...") to 330x. The
|
| 383 |
+
# most compressible real block was a 1.5 KB table at 5.3x, so tables get a higher bar.
|
| 384 |
+
LOOP_MIN_BYTES = 2000
|
| 385 |
+
LOOP_MIN_RATIO = 4.0
|
| 386 |
+
LOOP_MIN_RATIO_TABLE = 10.0
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def is_looped(block: dict) -> bool:
|
| 390 |
+
"""True when a block's text is long and highly repetitive (a decoding loop)."""
|
| 391 |
+
data = block["text"].encode()
|
| 392 |
+
if len(data) < LOOP_MIN_BYTES:
|
| 393 |
+
return False
|
| 394 |
+
ratio = len(data) / len(zlib.compress(data))
|
| 395 |
+
threshold = LOOP_MIN_RATIO_TABLE if block["type"] == "table" else LOOP_MIN_RATIO
|
| 396 |
+
return ratio >= threshold
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
# --- Server ---
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def vendor_vllm() -> str:
|
| 403 |
+
"""Return the vendor fork's `vllm` binary, or exit with the command that provides it."""
|
| 404 |
+
vllm = shutil.which("vllm")
|
| 405 |
+
version = ""
|
| 406 |
+
if vllm:
|
| 407 |
+
out = subprocess.run([vllm, "--version"], capture_output=True, text=True, check=False)
|
| 408 |
+
lines = out.stdout.strip().splitlines()
|
| 409 |
+
version = lines[-1] if lines else ""
|
| 410 |
+
if "hpdparsing" not in version:
|
| 411 |
+
found = f"found vllm {version!r} at {vllm}" if vllm else "no `vllm` on PATH"
|
| 412 |
+
sys.exit(
|
| 413 |
+
f"HPD-Parsing needs Paddle's vLLM fork (0.17.1+hpdparsing); {found}. "
|
| 414 |
+
f"Run the job on an image that has it:\n\n{RUN_COMMAND}"
|
| 415 |
+
)
|
| 416 |
+
print(f"vendor vllm {version} at {vllm}", file=sys.stderr)
|
| 417 |
+
return vllm
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def resolve_spec_model() -> str:
|
| 421 |
+
"""Download the P-MTP speculative head and return its local directory.
|
| 422 |
+
|
| 423 |
+
The vendor entrypoint passes `PaddlePaddle/HPD-Parsing/P-MTP`, a local directory in
|
| 424 |
+
the image's offline variant (weights baked in). This image has no weights, so pull
|
| 425 |
+
that subfolder (~644 MB) into the normal HF cache and pass its path.
|
| 426 |
+
"""
|
| 427 |
+
from huggingface_hub import snapshot_download
|
| 428 |
+
|
| 429 |
+
snapshot = snapshot_download(
|
| 430 |
+
SERVING["model"], revision=SERVING["revision"], allow_patterns=["P-MTP/*"]
|
| 431 |
+
)
|
| 432 |
+
spec_dir = os.path.join(snapshot, "P-MTP")
|
| 433 |
+
if not os.path.isfile(os.path.join(spec_dir, "config.json")):
|
| 434 |
+
sys.exit(f"P-MTP head has no config.json under {spec_dir}")
|
| 435 |
+
return spec_dir
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
def serve_command(vllm: str, max_model_len: int) -> list[str]:
|
| 439 |
+
"""The vendor entrypoint's `vllm serve` command, with a local speculative head."""
|
| 440 |
+
speculative = {
|
| 441 |
+
"method": "medusa",
|
| 442 |
+
"model": resolve_spec_model(),
|
| 443 |
+
"num_speculative_tokens": SERVING["num_speculative_tokens"],
|
| 444 |
+
}
|
| 445 |
+
return [
|
| 446 |
+
vllm, "serve", SERVING["model"],
|
| 447 |
+
"--revision", SERVING["revision"],
|
| 448 |
+
"--served-model-name", SERVING["served_model_name"],
|
| 449 |
+
"--port", str(SERVING["port"]),
|
| 450 |
+
"--max-model-len", str(max_model_len),
|
| 451 |
+
*SERVING["serve_args"],
|
| 452 |
+
"--speculative-config", json.dumps(speculative),
|
| 453 |
+
] # fmt: skip
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def main():
|
| 457 |
+
ap = argparse.ArgumentParser(
|
| 458 |
+
description="HPD-Parsing document parsing via saturate (vendor vLLM fork image only)"
|
| 459 |
+
)
|
| 460 |
+
ap.add_argument("input_dataset", help="Input dataset repo id (rows with an image column)")
|
| 461 |
+
ap.add_argument("output_dataset", help="Output dataset repo id (created private if missing)")
|
| 462 |
+
ap.add_argument("--image-column", default="image")
|
| 463 |
+
ap.add_argument("--config", default=None, help="Dataset config name")
|
| 464 |
+
ap.add_argument("--split", default="train")
|
| 465 |
+
ap.add_argument("--id-column", default=None,
|
| 466 |
+
help="Column to use as row id (default: split-index ids)")
|
| 467 |
+
ap.add_argument("--max-samples", "--limit", dest="limit", type=int, default=None,
|
| 468 |
+
help="Process only the first N rows (smoke test)")
|
| 469 |
+
ap.add_argument("--max-tokens", type=int, default=SERVING["max_tokens"],
|
| 470 |
+
help="Output cap PER DECODING BRANCH, not per page (card: 8000)")
|
| 471 |
+
ap.add_argument("--max-pixels", type=int, default=SERVING["max_pixels"],
|
| 472 |
+
help="Downscale images above this pixel count before upload (default 0 = off)")
|
| 473 |
+
ap.add_argument("--no-fork", action="store_true",
|
| 474 |
+
help="Send the single-trajectory prompt ('document parsing.') instead of "
|
| 475 |
+
"hierarchical parallel decoding; for an A/B only")
|
| 476 |
+
ap.add_argument("--retry-errors", action="store_true",
|
| 477 |
+
help="Re-admit rows whose only record is an error row")
|
| 478 |
+
args = ap.parse_args()
|
| 479 |
+
|
| 480 |
+
if not 1 <= args.max_tokens < SERVING["max_model_len"]:
|
| 481 |
+
ap.error(f"--max-tokens must be between 1 and {SERVING['max_model_len'] - 1}")
|
| 482 |
+
|
| 483 |
+
vllm = vendor_vllm() # fail before the dataset is touched if this is the wrong image
|
| 484 |
+
|
| 485 |
+
import pyarrow as pa
|
| 486 |
+
from saturate import Engine, dataset_rows, pump
|
| 487 |
+
|
| 488 |
+
if args.id_column is None:
|
| 489 |
+
ids = "index"
|
| 490 |
+
elif args.id_column in ("index", "content"):
|
| 491 |
+
# saturate reads these two names as id strategies, so a column with one of them
|
| 492 |
+
# needs a callable. It returns the raw value, so saturate still refuses a null id.
|
| 493 |
+
ids = lambda example: example[args.id_column]
|
| 494 |
+
else:
|
| 495 |
+
ids = args.id_column
|
| 496 |
+
|
| 497 |
+
rows = dataset_rows(
|
| 498 |
+
args.input_dataset, config=args.config, split=args.split,
|
| 499 |
+
columns=[args.image_column], ids=ids, limit=args.limit,
|
| 500 |
+
)
|
| 501 |
+
prompt = PLAIN_PROMPT if args.no_fork else FORK_PROMPT
|
| 502 |
+
|
| 503 |
+
def to_request(row):
|
| 504 |
+
b64 = encode_image(row[args.image_column], args.max_pixels)
|
| 505 |
+
return {
|
| 506 |
+
"model": SERVING["served_model_name"],
|
| 507 |
+
"messages": [{"role": "user", "content": [
|
| 508 |
+
# Image first, then text: the order of the card's example.
|
| 509 |
+
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64}"}},
|
| 510 |
+
{"type": "text", "text": prompt},
|
| 511 |
+
]}],
|
| 512 |
+
"temperature": SERVING["temperature"],
|
| 513 |
+
"max_tokens": args.max_tokens,
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
# Declared, so a part holding only error rows has the same columns as the rest
|
| 517 |
+
# (datasets.load_dataset reads every part with one schema).
|
| 518 |
+
schema = pa.schema([
|
| 519 |
+
("id", pa.string()), ("error", pa.string()), ("markdown", pa.string()),
|
| 520 |
+
("hpd_blocks", pa.string()), ("raw", pa.string()), ("looped_blocks", pa.int64()),
|
| 521 |
+
("finish_reason", pa.string()), ("model", pa.string()),
|
| 522 |
+
("prompt_tokens", pa.int64()), ("completion_tokens", pa.int64()),
|
| 523 |
+
]) # fmt: skip
|
| 524 |
+
|
| 525 |
+
def parse(row, body):
|
| 526 |
+
choice = body["choices"][0]
|
| 527 |
+
raw = choice["message"]["content"] or ""
|
| 528 |
+
blocks = parse_blocks(raw)
|
| 529 |
+
usage = body.get("usage") or {}
|
| 530 |
+
return {
|
| 531 |
+
"markdown": blocks_to_markdown(blocks),
|
| 532 |
+
"hpd_blocks": json.dumps(blocks, ensure_ascii=False),
|
| 533 |
+
"raw": raw,
|
| 534 |
+
"looped_blocks": sum(is_looped(b) for b in blocks),
|
| 535 |
+
"finish_reason": choice.get("finish_reason"),
|
| 536 |
+
"model": SERVING["model"],
|
| 537 |
+
"prompt_tokens": usage.get("prompt_tokens"),
|
| 538 |
+
"completion_tokens": usage.get("completion_tokens"),
|
| 539 |
+
}
|
| 540 |
+
|
| 541 |
+
engine = Engine(
|
| 542 |
+
SERVING["model"],
|
| 543 |
+
port=SERVING["port"],
|
| 544 |
+
cmd=serve_command(vllm, SERVING["max_model_len"]),
|
| 545 |
+
)
|
| 546 |
+
output = f"hf://datasets/{args.output_dataset}/data"
|
| 547 |
+
with engine as endpoint:
|
| 548 |
+
stats = pump(rows, to_request, parse, endpoint, output,
|
| 549 |
+
prepare_workers=int(float(os.environ.get("CPU_CORES") or "4")),
|
| 550 |
+
retry_errors=args.retry_errors, schema=schema)
|
| 551 |
+
|
| 552 |
+
print(f"https://huggingface.co/datasets/{args.output_dataset} "
|
| 553 |
+
f"({stats.rows_processed} ok, {stats.rows_failed} error rows)", file=sys.stderr)
|
| 554 |
+
print("HPD_PARSING_SATURATE " + stats.to_json(), flush=True)
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
if __name__ == "__main__":
|
| 558 |
+
main()
|
images/hpd-parsing/README.md
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# cr.hf.co/davanstrien/hpd-parsing-vllm
|
| 2 |
+
|
| 3 |
+
Public. Built 2026-11-05. Public page: https://huggingface.co/containers/davanstrien/hpd-parsing-vllm
|
| 4 |
+
|
| 5 |
+
Runtime image for [`../../hpd-parsing-saturate.py`](../../hpd-parsing-saturate.py): Paddle's
|
| 6 |
+
HPD-Parsing image with `uv` added, so the recipe runs with `hf jobs uv run`.
|
| 7 |
+
|
| 8 |
+
| Tag | Base (Paddle, pinned) | Digest |
|
| 9 |
+
|---|---|---|
|
| 10 |
+
| `87496aa5-uv0.13.6` (also `latest`) | `ccr-2vdh3abv-pub.cnc.bj.baidubce.com/paddlepaddle/hpd-parsing-vllm@sha256:87496aa5…` (`latest-nvidia-gpu`, built 2026-07-16) | `sha256:b7d3c561cc245572b11ec3bce0739fd359c564b890d8e848b53b1a8346a573c5` |
|
| 11 |
+
|
| 12 |
+
Why a custom image: HPD-Parsing runs on Paddle's vLLM fork (`0.17.1+hpdparsing`, request
|
| 13 |
+
forking + P-MTP speculative decoding), which ships in their registry image. That image has no
|
| 14 |
+
`uv`, which `hf jobs uv run --image <image>` needs. This image adds one layer, `uv` and `uvx` (0.13.6, checksum-verified)
|
| 15 |
+
in `/usr/local/bin`. User, venv, environment and entrypoint are unchanged.
|
| 16 |
+
|
| 17 |
+
Built with [`build.sh`](build.sh) and `crane append` on an HF CPU Job (`cpu-upgrade`); no Docker
|
| 18 |
+
daemon. Drop it when Paddle's image ships `uv`, or when request forking lands in an upstream vLLM release.
|
images/hpd-parsing/build.sh
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Build cr.hf.co/<namespace>/hpd-parsing-vllm: Paddle's HPD-Parsing image plus uv.
|
| 3 |
+
#
|
| 4 |
+
# Paddle's image (vendor vLLM fork 0.17.1+hpdparsing) has no `uv`, which
|
| 5 |
+
# `hf jobs uv run --image <image>` needs. This adds one layer, the uv and uvx binaries in /usr/local/bin, to the
|
| 6 |
+
# vendor image pinned by digest. Nothing else changes: same user (hpd), same venv,
|
| 7 |
+
# same entrypoint. No Docker daemon is needed: `crane append` adds the layer and
|
| 8 |
+
# pushes. Runs on a CPU Job (the base layers stream from Baidu's registry to cr.hf.co).
|
| 9 |
+
#
|
| 10 |
+
# Run (the container repo must exist; HF_TOKEN needs write on its namespace):
|
| 11 |
+
#
|
| 12 |
+
# hf jobs run --flavor cpu-upgrade -s HF_TOKEN --timeout 1h \
|
| 13 |
+
# -v hf://datasets/uv-scripts/ocr:/recipe:ro \
|
| 14 |
+
# python:3.12 -- bash /recipe/images/hpd-parsing/build.sh cr.hf.co/<namespace>/hpd-parsing-vllm
|
| 15 |
+
set -euo pipefail
|
| 16 |
+
|
| 17 |
+
REPO="${1:?usage: build.sh <cr.hf.co/namespace/name>}"
|
| 18 |
+
BASE_DIGEST="sha256:87496aa5dd702a7df6c70bb00c29d5bf8d1a0f0505d66b613fafa6f71cd72de2"
|
| 19 |
+
BASE="ccr-2vdh3abv-pub.cnc.bj.baidubce.com/paddlepaddle/hpd-parsing-vllm@${BASE_DIGEST}"
|
| 20 |
+
UV_VERSION="0.13.6"
|
| 21 |
+
CRANE_VERSION="v0.22.1"
|
| 22 |
+
TAG="${BASE_DIGEST:7:8}-uv${UV_VERSION}"
|
| 23 |
+
|
| 24 |
+
# 1. The layer: uv + uvx from the official release, checksum-verified.
|
| 25 |
+
cd /tmp
|
| 26 |
+
UV_TGZ="uv-x86_64-unknown-linux-gnu.tar.gz"
|
| 27 |
+
curl -sSfLO "https://github.com/astral-sh/uv/releases/download/${UV_VERSION}/${UV_TGZ}"
|
| 28 |
+
curl -sSfLO "https://github.com/astral-sh/uv/releases/download/${UV_VERSION}/${UV_TGZ}.sha256"
|
| 29 |
+
sha256sum -c "${UV_TGZ}.sha256"
|
| 30 |
+
tar -xzf "$UV_TGZ"
|
| 31 |
+
mkdir -p layer/usr/local/bin
|
| 32 |
+
install -m 755 uv-x86_64-unknown-linux-gnu/uv uv-x86_64-unknown-linux-gnu/uvx layer/usr/local/bin/
|
| 33 |
+
tar -C layer --owner=0 --group=0 -cf layer.tar usr
|
| 34 |
+
tar -tvf layer.tar
|
| 35 |
+
|
| 36 |
+
# 2. Append it to the vendor image and push.
|
| 37 |
+
curl -sSfL "https://github.com/google/go-containerregistry/releases/download/${CRANE_VERSION}/go-containerregistry_Linux_x86_64.tar.gz" \
|
| 38 |
+
| tar -xz -C /usr/local/bin crane
|
| 39 |
+
crane auth login cr.hf.co -u "${HF_USER:-user}" -p "$HF_TOKEN"
|
| 40 |
+
crane append --platform linux/amd64 -b "$BASE" -f layer.tar -t "$REPO:$TAG"
|
| 41 |
+
crane tag "$REPO:$TAG" latest
|
| 42 |
+
echo "PUSHED $REPO:$TAG $(crane digest "$REPO:$TAG")"
|
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-11-
|
| 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`.",
|
|
@@ -1058,5 +1058,34 @@
|
|
| 1058 |
]
|
| 1059 |
},
|
| 1060 |
"image": "vllm/vllm-openai:v0.29.0"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1061 |
}
|
| 1062 |
}
|
|
|
|
| 1 |
{
|
| 2 |
"_meta": {
|
| 3 |
"description": "Machine-readable catalog of the OCR recipes in this directory: script -> model, params, backend, support level, the tested Jobs launch config (the script's [tool.hf-jobs] header), and what the model's own card claims about language coverage. Human-readable language notes: LANGUAGES.md. Language evidence levels, strongest first: per-language-benchmark | count-claim | named-list | multilingual-unspecified | english-only | not-stated | not-applicable. Claims come from model cards (compiled 2026-07-15) - treat as claims, not guarantees.",
|
| 4 |
+
"updated": "2026-11-05",
|
| 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`.",
|
|
|
|
| 1058 |
]
|
| 1059 |
},
|
| 1060 |
"image": "vllm/vllm-openai:v0.29.0"
|
| 1061 |
+
},
|
| 1062 |
+
"hpd-parsing-saturate.py": {
|
| 1063 |
+
"model_id": "PaddlePaddle/HPD-Parsing",
|
| 1064 |
+
"params": "1B",
|
| 1065 |
+
"backend": "saturate (in-job vllm serve from Paddle's vLLM fork 0.17.1+hpdparsing: request forking + P-MTP speculative decoding)",
|
| 1066 |
+
"image": "cr.hf.co/davanstrien/hpd-parsing-vllm:87496aa5-uv0.13.6",
|
| 1067 |
+
"task": "ocr | layout",
|
| 1068 |
+
"output": "markdown + hpd_blocks (per-block type, bbox, text; bbox 0-1000 NORMALIZED, not pixels) + raw + looped_blocks",
|
| 1069 |
+
"license": "apache-2.0",
|
| 1070 |
+
"notes": "Runs only on Paddle's vLLM fork, shipped in their registry image. The header image is that image (latest-nvidia-gpu, pinned by digest 87496aa5) plus uv, built by images/hpd-parsing/build.sh; the docstring also gives the command for Paddle's image directly. Serve command = the image's own entrypoint, except the P-MTP speculative head path (downloaded locally) and a --revision pin. Keeps --enable-prefix-caching ON: forked children share the parent's prefix KV. max_tokens bounds one decoding branch, not the page, so dense pages can loop in many branches; looped_blocks flags them. 94.91 OmniDocBench v1.6; accuracy below ovis-ocr2 and paddleocr-vl-1.6. ~11 GB image pull on a cold node.",
|
| 1071 |
+
"languages": {
|
| 1072 |
+
"evidence": "named-list",
|
| 1073 |
+
"count": 2,
|
| 1074 |
+
"named": [
|
| 1075 |
+
"en",
|
| 1076 |
+
"zh"
|
| 1077 |
+
],
|
| 1078 |
+
"notes": "Card metadata lists en + zh only; no per-language numbers. Smoke runs on degraded French scans produced stray Chinese characters - treat other languages as unsupported."
|
| 1079 |
+
},
|
| 1080 |
+
"support": "experimental",
|
| 1081 |
+
"support_note": "Dense pages loop: filter on looped_blocks == 0. Check a sample of your own pages.",
|
| 1082 |
+
"jobs": {
|
| 1083 |
+
"image": "cr.hf.co/davanstrien/hpd-parsing-vllm:87496aa5-uv0.13.6",
|
| 1084 |
+
"flavor": "l4x1",
|
| 1085 |
+
"timeout": "2h",
|
| 1086 |
+
"secrets": [
|
| 1087 |
+
"HF_TOKEN"
|
| 1088 |
+
]
|
| 1089 |
+
}
|
| 1090 |
}
|
| 1091 |
}
|