Sync from GitHub via hub-sync
Browse files- CLAUDE.md +18 -0
- LANGUAGES.md +1 -1
- README.md +3 -1
- lighton-ocr3-bucket.py +528 -0
- lighton-ocr3.py +806 -0
- models.json +53 -1
CLAUDE.md
CHANGED
|
@@ -79,6 +79,8 @@ Legend: ✅ production-ready · ⚠️ works only with a required pinned image
|
|
| 79 |
| `deepseek-ocr-vllm.py` | ✅ | vLLM (stable) | l4x1 | `NGramPerReqLogitsProcessor` anti-repeat |
|
| 80 |
| `deepseek-ocr2-vllm.py` | ✅ | vLLM (nightly) | l4x1 | arch needs nightly; `addict`+`matplotlib` deps |
|
| 81 |
| `lighton-ocr2.py` | ✅ | vLLM | a100-large / l4x1 | resize 1540px; `--max-model-len` 16384 |
|
|
|
|
|
|
|
| 82 |
| `paddleocr-vl-1.5.py` | ✅ | transformers | l4x1 | not vLLM (server-only upstream); single-image |
|
| 83 |
| `paddleocr-vl-1.6.py` | ✅ | vLLM | l4x1 | smart-resize ~1M px; SOTA OmniDocBench |
|
| 84 |
| `paddleocr-vl.py` | ✅ | vLLM | l4x1 | |
|
|
@@ -198,6 +200,22 @@ client's `hunyuan_tasks.py`) and sampling is card-locked (temp 0.0, rep-penalty
|
|
| 198 |
Chatty on blank pages / can emit degenerate repeats — that's **model quality, not a crash**; don't
|
| 199 |
re-debug it as a recipe bug. (The actual historical crash was the `pyarrow<18` cap — see Conventions.)
|
| 200 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
### `lighton-ocr2.py`
|
| 202 |
The original breakage was **not** vLLM — it was a dead `HF_HUB_ENABLE_HF_TRANSFER=1` (the `hf_transfer`
|
| 203 |
package is gone), which surfaced as "Can't load image processor". Removed. Pixtral ViT + Qwen3, RLVR-trained,
|
|
|
|
| 79 |
| `deepseek-ocr-vllm.py` | ✅ | vLLM (stable) | l4x1 | `NGramPerReqLogitsProcessor` anti-repeat |
|
| 80 |
| `deepseek-ocr2-vllm.py` | ✅ | vLLM (nightly) | l4x1 | arch needs nightly; `addict`+`matplotlib` deps |
|
| 81 |
| `lighton-ocr2.py` | ✅ | vLLM | a100-large / l4x1 | resize 1540px; `--max-model-len` 16384 |
|
| 82 |
+
| `lighton-ocr3-bucket.py` | ✅ | vLLM `:v0.30.0` | a10g-small | `hf://buckets/...` or dir → `.md` (+ `.json` blocks in grounding); bucket I/O via `bucketbag` v0.3.1 (no mount); `.jp2` via imagecodecs; resume-by-skip; failed pages write nothing |
|
| 83 |
+
| `lighton-ocr3.py` | ✅ | vLLM `:v0.30.0` | a10g-small | 4B/0.8B Qwen3.5; resize 2048px; `--mode grounding` → `layout_blocks`; pinned upstream `lightonocr` client dep — see gotcha |
|
| 84 |
| `paddleocr-vl-1.5.py` | ✅ | transformers | l4x1 | not vLLM (server-only upstream); single-image |
|
| 85 |
| `paddleocr-vl-1.6.py` | ✅ | vLLM | l4x1 | smart-resize ~1M px; SOTA OmniDocBench |
|
| 86 |
| `paddleocr-vl.py` | ✅ | vLLM | l4x1 | |
|
|
|
|
| 200 |
Chatty on blank pages / can emit degenerate repeats — that's **model quality, not a crash**; don't
|
| 201 |
re-debug it as a recipe bug. (The actual historical crash was the `pyarrow<18` cap — see Conventions.)
|
| 202 |
|
| 203 |
+
### `lighton-ocr3.py`
|
| 204 |
+
Covers the two Qwen3.5 variants (`LightOnOCR-3-4B` default, `-0.8B`); **not** `LightOnOCR-3-1B`, which keeps
|
| 205 |
+
the LightOnOCR-2 Pixtral arch (needs `transformers` ≤5.16 for `PixtralRotaryEmbedding`). Image pinned to
|
| 206 |
+
**`vllm/vllm-openai:v0.30.0`** because upstream's `pyproject.toml` says vLLM 0.27.1 makes the models loop and
|
| 207 |
+
0.30.0 is tested — loosen after re-checking outputs on a newer tag. Imports parser, `fit` (2048px) and
|
| 208 |
+
`fix_escaped_dollars` from LightOn's own client (`lightonocr`, not on PyPI) via a commit-pinned GitHub
|
| 209 |
+
archive URL, so post-processing matches upstream byte for byte. Sampling = model card vLLM example
|
| 210 |
+
(temp 0.2, **top_p 0.9**, max_tokens 4096); LightOn's client `models.py` uses top_p 1.0 instead. Grounding mode writes `to_markdown(blocks)`
|
| 211 |
+
to the output column and the parsed blocks JSON to `--blocks-column`; the card says prompts other than
|
| 212 |
+
`""`/`grounding` are out of distribution, so no custom prompt flag. Very small type after the 2048
|
| 213 |
+
resize (≲15 px line height) can give empty or looping output; a higher `--longest-edge` helps some pages.
|
| 214 |
+
**Bucket sibling** (`lighton-ocr3-bucket.py`): input/output are `hf://buckets/...` URLs (bucketbag: list → batched
|
| 215 |
+
download → `put_files`) or directories. Use URLs for big buckets: a `-v` mount of `biglam/britannica` (~1 TB)
|
| 216 |
+
sat in RUNNING with no log output for 21 min (2026-10-22), while the same pages via bucketbag ran fine.
|
| 217 |
+
Prefixes get a trailing `/` and go to bucketbag as `prefix=` (it strips a slash from the URL and matches string prefixes, so `vol` would also list `vol2/`). `--max-samples` caps files after listing: bucketbag lists and sorts the whole prefix first, so point smoke tests at a narrow prefix. Directory writes go through a temp file + rename; PDF markers are written in a separate call after their pages. A PDF counts as done once its `.complete.<mode>` marker exists (written with its last page; grounding needs a grounding marker, plain takes either); a re-run without it OCRs only the missing pages. `--overwrite` does not delete anything first: a page that fails keeps its old output, and the run lists those inputs. Known limit: `--overwrite --mode plain` over grounding output leaves the old `.json` + `.complete.grounding`, so a later grounding run skips those pages; use one output prefix per mode. PDF pages render one at a time and go to vLLM in windows of `--batch-size` pages, so a long PDF never sits in memory.
|
| 218 |
+
|
| 219 |
### `lighton-ocr2.py`
|
| 220 |
The original breakage was **not** vLLM — it was a dead `HF_HUB_ENABLE_HF_TRANSFER=1` (the `hf_transfer`
|
| 221 |
package is gone), which surfaced as "Can't load image processor". Removed. Pixtral ViT + Qwen3, RLVR-trained,
|
LANGUAGES.md
CHANGED
|
@@ -26,7 +26,7 @@ _Sorted by strength of evidence, then coverage:_
|
|
| 26 |
| [HunyuanOCR-1.5](https://huggingface.co/tencent/HunyuanOCR) | "Multilingual" | Nothing enumerated, but explicitly targets **low-resource + ancient-script OCR** as a design goal (new in 1.5; the pinned 1.0 revision doesn't claim this) |
|
| 27 |
| [dots.mocr](https://huggingface.co/rednote-hilab/dots.mocr) · [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) / [-2](https://huggingface.co/deepseek-ai/DeepSeek-OCR-2) · [Unlimited-OCR](https://huggingface.co/baidu/Unlimited-OCR) · [NuExtract3](https://huggingface.co/numind/NuExtract3) | "Multilingual", unspecified | A tag or one-liner only — no count, list, or benchmark |
|
| 28 |
| [olmOCR-2](https://huggingface.co/allenai/olmOCR-2-7B-1025-FP8) · [Nanonets-OCR-s](https://huggingface.co/nanonets/Nanonets-OCR-s) · [SmolDocling](https://huggingface.co/ds4sd/SmolDocling-256M-preview) · [LFM2.5-VL-Extract](https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-Extract) | English only | Stated on the card |
|
| 29 |
-
| [Falcon-OCR](https://huggingface.co/tiiuae/Falcon-OCR) · [OvisOCR2](https://huggingface.co/ATH-MaaS/OvisOCR2) · [FireRed-OCR](https://huggingface.co/FireRedTeam/FireRed-OCR) · [ABot-OCR](https://huggingface.co/acvlab/ABot-OCR) · [RolmOCR](https://huggingface.co/reducto/RolmOCR) · [NuMarkdown-8B](https://huggingface.co/numind/NuMarkdown-8B-Thinking) · [lift](https://huggingface.co/datalab-to/lift) | Not stated | No language information on the card at all |
|
| 30 |
|
| 31 |
Text-only extraction: [LFM2-1.2B-Extract](https://huggingface.co/LiquidAI/LFM2-1.2B-Extract) (chains after OCR) names 9 languages: English, Arabic, Chinese, French, German, Japanese, Korean, Portuguese, Spanish.
|
| 32 |
|
|
|
|
| 26 |
| [HunyuanOCR-1.5](https://huggingface.co/tencent/HunyuanOCR) | "Multilingual" | Nothing enumerated, but explicitly targets **low-resource + ancient-script OCR** as a design goal (new in 1.5; the pinned 1.0 revision doesn't claim this) |
|
| 27 |
| [dots.mocr](https://huggingface.co/rednote-hilab/dots.mocr) · [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) / [-2](https://huggingface.co/deepseek-ai/DeepSeek-OCR-2) · [Unlimited-OCR](https://huggingface.co/baidu/Unlimited-OCR) · [NuExtract3](https://huggingface.co/numind/NuExtract3) | "Multilingual", unspecified | A tag or one-liner only — no count, list, or benchmark |
|
| 28 |
| [olmOCR-2](https://huggingface.co/allenai/olmOCR-2-7B-1025-FP8) · [Nanonets-OCR-s](https://huggingface.co/nanonets/Nanonets-OCR-s) · [SmolDocling](https://huggingface.co/ds4sd/SmolDocling-256M-preview) · [LFM2.5-VL-Extract](https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-Extract) | English only | Stated on the card |
|
| 29 |
+
| [Falcon-OCR](https://huggingface.co/tiiuae/Falcon-OCR) · [OvisOCR2](https://huggingface.co/ATH-MaaS/OvisOCR2) · [LightOnOCR-3](https://huggingface.co/collections/lightonai/lightonocr-3) · [FireRed-OCR](https://huggingface.co/FireRedTeam/FireRed-OCR) · [ABot-OCR](https://huggingface.co/acvlab/ABot-OCR) · [RolmOCR](https://huggingface.co/reducto/RolmOCR) · [NuMarkdown-8B](https://huggingface.co/numind/NuMarkdown-8B-Thinking) · [lift](https://huggingface.co/datalab-to/lift) | Not stated | No language information on the card at all |
|
| 30 |
|
| 31 |
Text-only extraction: [LFM2-1.2B-Extract](https://huggingface.co/LiquidAI/LFM2-1.2B-Extract) (chains after OCR) names 9 languages: English, Arabic, Chinese, French, German, Japanese, Korean, Portuguese, Spanish.
|
| 32 |
|
README.md
CHANGED
|
@@ -83,6 +83,7 @@ These are the maintained recipes. Each one has a tested `[tool.hf-jobs]` header,
|
|
| 83 |
| [`tesseract-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/tesseract-ocr.py) | [Tesseract 5](https://github.com/tesseract-ocr/tesseract) | classical | Baseline plain text, no GPU, 100+ language packs (`--lang`) | Apache-2.0 | `cpu-upgrade` |
|
| 84 |
| [`pp-ocrv6.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/pp-ocrv6.py) | [PP-OCRv6](https://huggingface.co/collections/PaddlePaddle/pp-ocrv6) | 1.5M–34.5M | Small detection + recognition pipeline, plain text, 48 languages | Apache-2.0 | `t4-small` |
|
| 85 |
| [`surya-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/surya-ocr.py) | [Surya OCR 2](https://huggingface.co/datalab-to/surya-ocr-2) | 0.65B | Per-block HTML with boxes and reading order; layout and table tasks; PDFs | modified OpenRAIL-M | `a10g-small` |
|
|
|
|
| 86 |
| [`glm-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/glm-ocr.py) | [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) | 0.9B | 94.62 OmniDocBench v1.5 | MIT | `a10g-small` |
|
| 87 |
| [`paddleocr-vl-1.6.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/paddleocr-vl-1.6.py) | [PaddleOCR-VL-1.6](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.6) | 0.9B | 96.33 OmniDocBench v1.6; six task modes | Apache-2.0 | `a10g-small` |
|
| 88 |
| [`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` |
|
|
@@ -100,7 +101,7 @@ These are the maintained recipes. Each one has a tested `[tool.hf-jobs]` header,
|
|
| 100 |
|
| 101 |
Start with a model under 2B. Use a larger model only if the output of a small one is not good enough. Check the licence before you use a model: Surya and lift use a modified OpenRAIL-M licence (free for research, personal use and startups under $5M; no competitive use against Datalab's API), and the Hunyuan licence excludes the EU, the UK and South Korea.
|
| 102 |
|
| 103 |
-
**Variants and tools:** `glm-ocr-bucket.py`
|
| 104 |
|
| 105 |
Which model is best depends on your documents. The public olmOCR-Bench leaderboard is one command away:
|
| 106 |
|
|
@@ -169,6 +170,7 @@ Most dataset recipes also record the model and settings in an `inference_info` c
|
|
| 169 |
| `glm-ocr.py` | `--task ocr\|formula\|table` |
|
| 170 |
| `paddleocr-vl-1.6.py` | `--task-mode ocr\|table\|formula\|chart\|spotting\|seal` |
|
| 171 |
| `ovis-ocr2.py` | `--keep-image-tags`, `--min-pixels`, `--max-pixels` |
|
|
|
|
| 172 |
| `hunyuan-ocr-1.5.py` | `--task-type` (12 types, default `doc_parse`), `--custom-prompt` |
|
| 173 |
| `dots-ocr.py` | `--prompt-mode ocr\|layout-all\|layout-only` |
|
| 174 |
| `dots-mocr.py` | `--prompt-mode` (8 modes). For SVG: `--model rednote-hilab/dots.mocr-svg --prompt-mode svg` |
|
|
|
|
| 83 |
| [`tesseract-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/tesseract-ocr.py) | [Tesseract 5](https://github.com/tesseract-ocr/tesseract) | classical | Baseline plain text, no GPU, 100+ language packs (`--lang`) | Apache-2.0 | `cpu-upgrade` |
|
| 84 |
| [`pp-ocrv6.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/pp-ocrv6.py) | [PP-OCRv6](https://huggingface.co/collections/PaddlePaddle/pp-ocrv6) | 1.5M–34.5M | Small detection + recognition pipeline, plain text, 48 languages | Apache-2.0 | `t4-small` |
|
| 85 |
| [`surya-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/surya-ocr.py) | [Surya OCR 2](https://huggingface.co/datalab-to/surya-ocr-2) | 0.65B | Per-block HTML with boxes and reading order; layout and table tasks; PDFs | modified OpenRAIL-M | `a10g-small` |
|
| 86 |
+
| [`lighton-ocr3.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/lighton-ocr3.py) | [LightOnOCR-3](https://huggingface.co/collections/lightonai/lightonocr-3) | 0.8B / 4B | 86.3 olmOCR-Bench (4B), 85.5 (0.8B); `--mode grounding` adds labelled layout boxes, image descriptions and chart tables | Apache-2.0 | `a10g-small` |
|
| 87 |
| [`glm-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/glm-ocr.py) | [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) | 0.9B | 94.62 OmniDocBench v1.5 | MIT | `a10g-small` |
|
| 88 |
| [`paddleocr-vl-1.6.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/paddleocr-vl-1.6.py) | [PaddleOCR-VL-1.6](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.6) | 0.9B | 96.33 OmniDocBench v1.6; six task modes | Apache-2.0 | `a10g-small` |
|
| 89 |
| [`ovis-ocr2.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/ovis-ocr2.py) | [OvisOCR2](https://huggingface.co/ATH-MaaS/OvisOCR2) | 0.9B | 96.58 OmniDocBench v1.6; LaTeX and HTML tables | Apache-2.0 | `a10g-small` |
|
|
|
|
| 101 |
|
| 102 |
Start with a model under 2B. Use a larger model only if the output of a small one is not good enough. Check the licence before you use a model: Surya and lift use a modified OpenRAIL-M licence (free for research, personal use and startups under $5M; no competitive use against Datalab's API), and the Hunyuan licence excludes the EU, the UK and South Korea.
|
| 103 |
|
| 104 |
+
**Variants and tools:** `glm-ocr-bucket.py`, `surya-ocr-bucket.py` and `lighton-ocr3-bucket.py` read images and PDFs from a Bucket and write one `.md` per page. `lighton-ocr3-bucket.py` also takes `hf://buckets/...` URLs for input and output directly, so it reads large buckets in batches through the Hub API without mounting them. It reads `.jp2`, skips pages that already have output (so a re-run resumes), and in `--mode grounding` writes a `.json` sidecar with the layout blocks. `surya-ocr-bucket.py` also writes a `.json` sidecar with the layout blocks, resumes from existing JSON, and can mount or copy its input (`--io-mode mount|copy`); the dataset version, `surya-ocr.py`, keeps the blocks in a `surya_blocks` column. `lighton-ocr2-saturate.py` and `ovis-ocr2-saturate.py` are for large runs, and `ocr-vllm-judge.py` compares outputs ([Scaling up](#scaling-up)). `pp-doclayout.py` and `lfm2-extract.py` are described in [Structured extraction and layout](#structured-extraction-and-layout).
|
| 105 |
|
| 106 |
Which model is best depends on your documents. The public olmOCR-Bench leaderboard is one command away:
|
| 107 |
|
|
|
|
| 170 |
| `glm-ocr.py` | `--task ocr\|formula\|table` |
|
| 171 |
| `paddleocr-vl-1.6.py` | `--task-mode ocr\|table\|formula\|chart\|spotting\|seal` |
|
| 172 |
| `ovis-ocr2.py` | `--keep-image-tags`, `--min-pixels`, `--max-pixels` |
|
| 173 |
+
| `lighton-ocr3.py` | `--model lightonai/LightOnOCR-3-4B\|lightonai/LightOnOCR-3-0.8B`, `--mode plain\|grounding`, `--blocks-column`, `--longest-edge` |
|
| 174 |
| `hunyuan-ocr-1.5.py` | `--task-type` (12 types, default `doc_parse`), `--custom-prompt` |
|
| 175 |
| `dots-ocr.py` | `--prompt-mode ocr\|layout-all\|layout-only` |
|
| 176 |
| `dots-mocr.py` | `--prompt-mode` (8 modes). For SVG: `--model rednote-hilab/dots.mocr-svg --prompt-mode svg` |
|
lighton-ocr3-bucket.py
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "pillow",
|
| 5 |
+
# "imagecodecs",
|
| 6 |
+
# "toolz",
|
| 7 |
+
# "bucketbag @ https://github.com/davanstrien/bucketbag/archive/refs/tags/v0.3.1.tar.gz",
|
| 8 |
+
# # LightOn's official client, pinned to a commit (not on PyPI). Used for its
|
| 9 |
+
# # parser, page resize, PDF rendering and dollar-delimiter repair.
|
| 10 |
+
# "lightonocr @ https://github.com/lightonai/LightOnOCR/archive/36755d461be079737860a5f03ae0c803501269e9.tar.gz",
|
| 11 |
+
# ]
|
| 12 |
+
#
|
| 13 |
+
# [tool.hf-jobs]
|
| 14 |
+
# image = "vllm/vllm-openai:v0.30.0"
|
| 15 |
+
# python = "/usr/bin/python3"
|
| 16 |
+
# env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
|
| 17 |
+
# flavor = "a10g-small"
|
| 18 |
+
# secrets = ["HF_TOKEN"]
|
| 19 |
+
# ///
|
| 20 |
+
|
| 21 |
+
"""
|
| 22 |
+
OCR images and PDFs from an HF Bucket (or a directory) using LightOnOCR-3,
|
| 23 |
+
writing markdown files.
|
| 24 |
+
|
| 25 |
+
Bucket sibling of lighton-ocr3.py: same model, prompt, sampling and post-processing.
|
| 26 |
+
Writes one .md per image (or per PDF page), preserving the key/directory structure.
|
| 27 |
+
In grounding mode each .md gets a .json sidecar with the parsed layout blocks.
|
| 28 |
+
|
| 29 |
+
INPUT and OUTPUT are each either
|
| 30 |
+
- an `hf://buckets/<ns>/<bucket>[/<prefix>]` URL: read with bucketbag (list, then
|
| 31 |
+
download one batch at a time to scratch, no mount) / written with one upload call
|
| 32 |
+
per batch. Use this for large buckets: mounting a very large bucket can be slow.
|
| 33 |
+
- a directory: a local folder, or a bucket mounted with `-v`.
|
| 34 |
+
|
| 35 |
+
Input: Output:
|
| 36 |
+
/input/page1.jp2 → /output/page1.md (+ page1.json with --mode grounding)
|
| 37 |
+
/input/report.pdf → /output/report/page_001.md
|
| 38 |
+
(3 pages) /output/report/page_002.md
|
| 39 |
+
/output/report/page_003.md
|
| 40 |
+
/output/report/.complete.plain
|
| 41 |
+
/input/sub/photo.jpg → /output/sub/photo.md
|
| 42 |
+
|
| 43 |
+
Pages that already have their output are skipped, so re-running the same command
|
| 44 |
+
resumes a stopped run. A page that fails writes nothing and is retried on the next
|
| 45 |
+
run. A PDF gets a `.complete.<mode>` marker in its output folder once every page is
|
| 46 |
+
written; until then, a re-run OCRs only its missing pages. --overwrite redoes
|
| 47 |
+
everything, replacing outputs as it goes: a page that fails keeps its previous output
|
| 48 |
+
(the run lists those inputs), so re-run them with --overwrite or use a fresh output prefix.
|
| 49 |
+
Keep plain and grounding runs in separate output prefixes.
|
| 50 |
+
|
| 51 |
+
Examples:
|
| 52 |
+
|
| 53 |
+
# Bucket to bucket on HF Jobs (image, flavor and HF_TOKEN come from the
|
| 54 |
+
# [tool.hf-jobs] header; needs hf CLI 1.32+). One folder of a large bucket:
|
| 55 |
+
hf jobs uv run \\
|
| 56 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3-bucket.py \\
|
| 57 |
+
hf://buckets/biglam/britannica/source/pages/00070476bsb \\
|
| 58 |
+
hf://buckets/user/ocr-output/britannica --mode grounding --max-samples 20
|
| 59 |
+
|
| 60 |
+
# Mounted volumes work too (simplest for small buckets)
|
| 61 |
+
hf jobs uv run \\
|
| 62 |
+
-v hf://buckets/user/ocr-input:/input:ro \\
|
| 63 |
+
-v hf://buckets/user/ocr-output:/output \\
|
| 64 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3-bucket.py \\
|
| 65 |
+
/input /output
|
| 66 |
+
|
| 67 |
+
# Own GPU (vLLM and torch come from the image on Jobs, so add them here)
|
| 68 |
+
uv run --with vllm==0.30.0 lighton-ocr3-bucket.py ./images ./output
|
| 69 |
+
|
| 70 |
+
Models: lightonai/LightOnOCR-3-4B (default) or lightonai/LightOnOCR-3-0.8B (Apache-2.0).
|
| 71 |
+
See lighton-ocr3.py for the settings and why the vLLM image is pinned.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
import argparse
|
| 75 |
+
import json
|
| 76 |
+
import logging
|
| 77 |
+
import os
|
| 78 |
+
import sys
|
| 79 |
+
import time
|
| 80 |
+
from pathlib import Path
|
| 81 |
+
from typing import NamedTuple
|
| 82 |
+
|
| 83 |
+
import torch
|
| 84 |
+
from bucketbag import batched_files, iter_keys, put_files
|
| 85 |
+
from lightonocr import (
|
| 86 |
+
DEFAULT_LONGEST_EDGE,
|
| 87 |
+
GROUNDING_PROMPT,
|
| 88 |
+
fit,
|
| 89 |
+
fix_escaped_dollars,
|
| 90 |
+
parse_blocks,
|
| 91 |
+
to_markdown,
|
| 92 |
+
)
|
| 93 |
+
from PIL import Image
|
| 94 |
+
from toolz import partition_all
|
| 95 |
+
|
| 96 |
+
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 97 |
+
# default uv-script image lacks (engine init then crashes). On the vllm/vllm-openai image it's
|
| 98 |
+
# a harmless no-op.
|
| 99 |
+
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 100 |
+
# DeepGEMM's init asserts on a missing nvcc (non-fatal traceback); OCR doesn't need it.
|
| 101 |
+
os.environ.setdefault("VLLM_USE_DEEP_GEMM", "0")
|
| 102 |
+
from vllm import LLM, SamplingParams
|
| 103 |
+
|
| 104 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
| 105 |
+
logger = logging.getLogger(__name__)
|
| 106 |
+
|
| 107 |
+
MODELS = ["lightonai/LightOnOCR-3-4B", "lightonai/LightOnOCR-3-0.8B"]
|
| 108 |
+
DEFAULT_MODEL = MODELS[0]
|
| 109 |
+
|
| 110 |
+
# Sampling from the model card's vLLM example (temperature 0.2, top_p 0.9, max_tokens 4096).
|
| 111 |
+
DEFAULT_TEMPERATURE = 0.2
|
| 112 |
+
DEFAULT_TOP_P = 0.9
|
| 113 |
+
DEFAULT_MAX_TOKENS = 4096
|
| 114 |
+
|
| 115 |
+
IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".tiff", ".tif", ".bmp", ".webp", ".jp2", ".j2k"}
|
| 116 |
+
JP2_EXTENSIONS = {".jp2", ".j2k"}
|
| 117 |
+
BUCKET_SCHEME = "hf://buckets/"
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def check_cuda_availability():
|
| 121 |
+
if not torch.cuda.is_available():
|
| 122 |
+
logger.error("CUDA is not available. This script requires a GPU.")
|
| 123 |
+
sys.exit(1)
|
| 124 |
+
logger.info(f"CUDA available. GPU: {torch.cuda.get_device_name(0)}")
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def is_bucket(location: str) -> bool:
|
| 128 |
+
return location.startswith(BUCKET_SCHEME)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def as_bucket_dir(url: str) -> tuple[str, str]:
|
| 132 |
+
"""Split a bucket URL into (bucket root URL, directory key prefix ending in "/").
|
| 133 |
+
|
| 134 |
+
Pass the prefix to bucketbag explicitly: it strips a trailing slash from the URL and
|
| 135 |
+
matches prefixes as strings, so `.../pages/00070476bsb` would also list
|
| 136 |
+
`.../pages/00070476bsb2/...`.
|
| 137 |
+
"""
|
| 138 |
+
parts = url[len(BUCKET_SCHEME):].strip("/").split("/", 2)
|
| 139 |
+
if len(parts) < 2:
|
| 140 |
+
raise ValueError(f"Not a bucket URL: {url} (expected hf://buckets/<ns>/<bucket>[/<prefix>])")
|
| 141 |
+
prefix = parts[2] + "/" if len(parts) == 3 else ""
|
| 142 |
+
return BUCKET_SCHEME + "/".join(parts[:2]), prefix
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def output_collisions(rels: list[str]) -> list[str]:
|
| 146 |
+
"""Inputs whose outputs would overwrite each other, e.g. scan.png + scan.jpg -> scan.md,
|
| 147 |
+
or report.pdf (report/page_001.md) + report/page_001.png."""
|
| 148 |
+
owners: dict[str, list[str]] = {}
|
| 149 |
+
for rel in rels:
|
| 150 |
+
# A PDF owns its whole output folder; an image owns one .md.
|
| 151 |
+
key = str(Path(rel).with_suffix("")) + "/" if rel.lower().endswith(".pdf") else md_rel(rel)
|
| 152 |
+
owners.setdefault(key, []).append(rel)
|
| 153 |
+
clashes = [group for group in owners.values() if len(group) > 1]
|
| 154 |
+
folders = {key for key in owners if key.endswith("/")}
|
| 155 |
+
for key, group in owners.items():
|
| 156 |
+
if not key.endswith("/") and any(key.startswith(folder) for folder in folders):
|
| 157 |
+
clashes.append(group + owners[next(f for f in folders if key.startswith(f))])
|
| 158 |
+
return [" + ".join(group) for group in clashes]
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def is_input_file(rel: str) -> bool:
|
| 162 |
+
ext = Path(rel).suffix.lower()
|
| 163 |
+
return ext in IMAGE_EXTENSIONS or ext == ".pdf"
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def list_inputs(source: str, include: str | None, limit: int | None) -> list[str]:
|
| 167 |
+
"""Relative paths of image/PDF inputs, sorted. With `limit`, stops early."""
|
| 168 |
+
rels = []
|
| 169 |
+
if is_bucket(source):
|
| 170 |
+
url, prefix = as_bucket_dir(source)
|
| 171 |
+
keys = iter_keys(url, prefix=prefix, include=f"{prefix}{include}" if include else None)
|
| 172 |
+
candidates = (k[len(prefix):] for k in keys)
|
| 173 |
+
else:
|
| 174 |
+
root = Path(source)
|
| 175 |
+
paths = root.rglob(include or "*")
|
| 176 |
+
candidates = (str(p.relative_to(root)) for p in (paths if limit else sorted(paths)) if p.is_file())
|
| 177 |
+
for rel in candidates:
|
| 178 |
+
if is_input_file(rel):
|
| 179 |
+
rels.append(rel)
|
| 180 |
+
if limit is not None and len(rels) >= limit:
|
| 181 |
+
break
|
| 182 |
+
return rels
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def list_outputs(dest: str) -> set[str]:
|
| 186 |
+
"""Relative paths of outputs already written (for resume)."""
|
| 187 |
+
if is_bucket(dest):
|
| 188 |
+
url, prefix = as_bucket_dir(dest)
|
| 189 |
+
return {k[len(prefix):] for k in iter_keys(url, prefix=prefix)}
|
| 190 |
+
root = Path(dest)
|
| 191 |
+
return {str(p.relative_to(root)) for p in root.rglob("*") if p.is_file()} if root.is_dir() else set()
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def md_rel(rel: str, page: int | None = None) -> str:
|
| 195 |
+
"""Output path for an input: x.jp2 -> x.md; a PDF page -> x/page_001.md."""
|
| 196 |
+
stem = str(Path(rel).with_suffix(""))
|
| 197 |
+
return f"{stem}/page_{page:03d}.md" if page else f"{stem}.md"
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def marker_rel(rel: str, mode: str) -> str:
|
| 201 |
+
"""Written into a PDF's output folder once all its pages are written in this mode."""
|
| 202 |
+
return f"{Path(rel).with_suffix('')}/.complete.{mode}"
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def page_done(md: str, existing: set[str], mode: str) -> bool:
|
| 206 |
+
if md not in existing:
|
| 207 |
+
return False
|
| 208 |
+
return mode != "grounding" or md[: -len(".md")] + ".json" in existing
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def is_done(rel: str, existing: set[str], mode: str) -> bool:
|
| 212 |
+
if rel.lower().endswith(".pdf"):
|
| 213 |
+
# Grounding needs the .json sidecars, so only a grounding marker will do;
|
| 214 |
+
# plain is satisfied by either (as for images, whose .md exists in both modes).
|
| 215 |
+
modes = ["grounding"] if mode == "grounding" else ["plain", "grounding"]
|
| 216 |
+
return any(marker_rel(rel, m) in existing for m in modes)
|
| 217 |
+
return page_done(md_rel(rel), existing, mode)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def iter_local_batches(source: str, rels: list[str], n: int):
|
| 221 |
+
"""Yield batches of (rel, local_path): straight from disk, or downloaded by bucketbag
|
| 222 |
+
(one batch at a time to scratch, deleted as the loop advances)."""
|
| 223 |
+
if not is_bucket(source):
|
| 224 |
+
for chunk in partition_all(n, rels):
|
| 225 |
+
yield [(rel, Path(source) / rel) for rel in chunk]
|
| 226 |
+
return
|
| 227 |
+
url, prefix = as_bucket_dir(source)
|
| 228 |
+
keys = [prefix + rel for rel in rels]
|
| 229 |
+
for batch in batched_files(url, keys=keys, n=n, prefetch=2):
|
| 230 |
+
yield [(it.key[len(prefix):], it.path) for it in batch]
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def open_image(path: Path) -> Image.Image:
|
| 234 |
+
"""Open one image as RGB. JPEG-2000 falls back to imagecodecs when Pillow
|
| 235 |
+
was built without OpenJPEG."""
|
| 236 |
+
try:
|
| 237 |
+
return Image.open(path).convert("RGB")
|
| 238 |
+
except Exception:
|
| 239 |
+
if path.suffix.lower() not in JP2_EXTENSIONS:
|
| 240 |
+
raise
|
| 241 |
+
import imagecodecs
|
| 242 |
+
|
| 243 |
+
return Image.fromarray(imagecodecs.imread(str(path))).convert("RGB")
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
class PageItem(NamedTuple):
|
| 247 |
+
rel: str # input file
|
| 248 |
+
md: str | None # output .md path; None for a marker-only item
|
| 249 |
+
image: Image.Image | None
|
| 250 |
+
last: bool # last page still to do for a PDF: write its .complete.<mode> marker after it
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def iter_pages(rel: str, path: Path, existing: set[str], mode: str, longest_edge: int):
|
| 254 |
+
"""PageItems for the pages of one input that still need OCR. PDF pages render one at
|
| 255 |
+
a time (as lightonocr.render.render_pdf does), so a long PDF never sits in memory."""
|
| 256 |
+
if not rel.lower().endswith(".pdf"):
|
| 257 |
+
yield PageItem(rel, md_rel(rel), fit(open_image(path), longest_edge), False)
|
| 258 |
+
return
|
| 259 |
+
import pypdfium2 as pdfium
|
| 260 |
+
|
| 261 |
+
pdf = pdfium.PdfDocument(str(path))
|
| 262 |
+
todo = [n for n in range(1, len(pdf) + 1) if not page_done(md_rel(rel, n), existing, mode)]
|
| 263 |
+
if not todo: # every page written by an earlier run: only the marker is missing
|
| 264 |
+
yield PageItem(rel, None, None, True)
|
| 265 |
+
return
|
| 266 |
+
for n in todo:
|
| 267 |
+
page = pdf[n - 1]
|
| 268 |
+
w, h = page.get_size() # points
|
| 269 |
+
image = page.render(scale=longest_edge / max(w, h)).to_pil().convert("RGB")
|
| 270 |
+
yield PageItem(rel, md_rel(rel, n), image, n == todo[-1])
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def build_prompt(llm: LLM, mode: str) -> str:
|
| 274 |
+
"""Chat-template prompt with thinking disabled; grounding adds the "grounding" text."""
|
| 275 |
+
content = [{"type": "image"}]
|
| 276 |
+
if mode == "grounding":
|
| 277 |
+
content.append({"type": "text", "text": GROUNDING_PROMPT})
|
| 278 |
+
return llm.get_tokenizer().apply_chat_template(
|
| 279 |
+
[{"role": "user", "content": content}],
|
| 280 |
+
tokenize=False,
|
| 281 |
+
add_generation_prompt=True,
|
| 282 |
+
enable_thinking=False,
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def render_outputs(md: str, raw: str, image_size, mode: str, fix_dollars: bool, model: str):
|
| 287 |
+
"""(relative path, content) pairs for one page: the .md, plus a .json in grounding mode."""
|
| 288 |
+
text = raw.strip()
|
| 289 |
+
if fix_dollars:
|
| 290 |
+
text = fix_escaped_dollars(text)
|
| 291 |
+
if mode != "grounding":
|
| 292 |
+
return [(md, text)]
|
| 293 |
+
blocks = parse_blocks(text)
|
| 294 |
+
sidecar = {
|
| 295 |
+
"model": model,
|
| 296 |
+
"image_size": list(image_size), # size fed to the model; bbox is 0-1000 of this frame
|
| 297 |
+
"blocks": [b.to_dict() for b in blocks],
|
| 298 |
+
}
|
| 299 |
+
# .md before sidecar: a page counts as done in grounding mode only once its .json
|
| 300 |
+
# exists, so a write that stops between the two is redone (also when replacing a
|
| 301 |
+
# plain-mode .md).
|
| 302 |
+
return [
|
| 303 |
+
(md, to_markdown(blocks) if blocks else text),
|
| 304 |
+
(md[: -len(".md")] + ".json", json.dumps(sidecar, ensure_ascii=False)),
|
| 305 |
+
]
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def write_outputs(dest: str, pairs: list[tuple[str, str]]):
|
| 309 |
+
if not pairs:
|
| 310 |
+
return
|
| 311 |
+
if is_bucket(dest):
|
| 312 |
+
url, prefix = as_bucket_dir(dest)
|
| 313 |
+
put_files([(prefix + rel, content) for rel, content in pairs], url) # one upload call
|
| 314 |
+
return
|
| 315 |
+
for rel, content in pairs:
|
| 316 |
+
# Write to a temp file, then rename: a stopped job never leaves a partial .md that
|
| 317 |
+
# the next run would count as done.
|
| 318 |
+
path = Path(dest) / rel
|
| 319 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 320 |
+
tmp = path.with_name(f".{path.name}.tmp")
|
| 321 |
+
tmp.write_text(content, encoding="utf-8")
|
| 322 |
+
os.replace(tmp, path)
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def main():
|
| 326 |
+
parser = argparse.ArgumentParser(
|
| 327 |
+
description="OCR images/PDFs from an HF Bucket or directory using LightOnOCR-3, output markdown files.",
|
| 328 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 329 |
+
epilog="""
|
| 330 |
+
Modes:
|
| 331 |
+
plain markdown transcription (default)
|
| 332 |
+
grounding markdown + a .json sidecar of labelled layout blocks (0-1000 boxes)
|
| 333 |
+
|
| 334 |
+
Examples:
|
| 335 |
+
lighton-ocr3-bucket.py hf://buckets/ns/scans/vol1 hf://buckets/ns/ocr/vol1 --mode grounding
|
| 336 |
+
lighton-ocr3-bucket.py /input /output (directories, e.g. -v mounted buckets)
|
| 337 |
+
lighton-ocr3-bucket.py hf://buckets/ns/scans /output --include "**/*.jp2"
|
| 338 |
+
""",
|
| 339 |
+
)
|
| 340 |
+
parser.add_argument("input", help="hf://buckets/<ns>/<bucket>[/<prefix>] or a directory of images/PDFs")
|
| 341 |
+
parser.add_argument("output", help="hf://buckets/<ns>/<bucket>[/<prefix>] or a directory for the .md files")
|
| 342 |
+
parser.add_argument("--model", default=DEFAULT_MODEL, choices=MODELS,
|
| 343 |
+
help=f"Model checkpoint (default: {DEFAULT_MODEL})")
|
| 344 |
+
parser.add_argument("--mode", default="plain", choices=["plain", "grounding"],
|
| 345 |
+
help="plain = markdown; grounding = markdown + .json layout blocks (default: plain)")
|
| 346 |
+
parser.add_argument("--include", default=None,
|
| 347 |
+
help='Glob relative to the input, e.g. "**/*.jp2" (default: all images and PDFs)')
|
| 348 |
+
parser.add_argument("--batch-size", type=int, default=16,
|
| 349 |
+
help="Files downloaded, and pages sent to vLLM, per batch (default: 16)")
|
| 350 |
+
parser.add_argument("--max-model-len", type=int, default=16384,
|
| 351 |
+
help="Max model context length (default: 16384)")
|
| 352 |
+
parser.add_argument("--max-tokens", type=int, default=DEFAULT_MAX_TOKENS,
|
| 353 |
+
help=f"Max output tokens (default: {DEFAULT_MAX_TOKENS}, the card's vLLM example)")
|
| 354 |
+
parser.add_argument("--temperature", type=float, default=DEFAULT_TEMPERATURE,
|
| 355 |
+
help=f"Sampling temperature (default: {DEFAULT_TEMPERATURE}, model card)")
|
| 356 |
+
parser.add_argument("--top-p", type=float, default=DEFAULT_TOP_P,
|
| 357 |
+
help=f"Top-p (default: {DEFAULT_TOP_P}, model card; LightOn's client uses 1.0)")
|
| 358 |
+
parser.add_argument("--longest-edge", type=int, default=DEFAULT_LONGEST_EDGE,
|
| 359 |
+
help=f"Downscale pages so the longest edge is at most this many pixels; "
|
| 360 |
+
f"PDFs render at this size (default: {DEFAULT_LONGEST_EDGE})")
|
| 361 |
+
parser.add_argument("--no-fix-dollars", action="store_true",
|
| 362 |
+
help="Keep the raw output instead of repairing escaped dollar delimiters")
|
| 363 |
+
parser.add_argument("--gpu-memory-utilization", type=float, default=0.8,
|
| 364 |
+
help="GPU memory utilization (default: 0.8)")
|
| 365 |
+
parser.add_argument("--max-samples", type=int, default=None,
|
| 366 |
+
help="Limit the number of input files (files, not pages; a PDF still yields "
|
| 367 |
+
"all its pages). Counted before skipping files that are already done.")
|
| 368 |
+
parser.add_argument("--overwrite", action="store_true",
|
| 369 |
+
help="Redo files that already have output (default: skip them, which resumes a run)")
|
| 370 |
+
parser.add_argument("--verbose", action="store_true", help="Print resolved package versions")
|
| 371 |
+
|
| 372 |
+
args = parser.parse_args()
|
| 373 |
+
if args.max_samples is not None and args.max_samples < 1:
|
| 374 |
+
parser.error("--max-samples must be 1 or more")
|
| 375 |
+
if args.max_tokens > args.max_model_len:
|
| 376 |
+
parser.error(f"--max-tokens ({args.max_tokens}) must be <= --max-model-len ({args.max_model_len})")
|
| 377 |
+
for loc in (args.input, args.output):
|
| 378 |
+
if is_bucket(loc):
|
| 379 |
+
try:
|
| 380 |
+
as_bucket_dir(loc)
|
| 381 |
+
except ValueError as e:
|
| 382 |
+
parser.error(str(e))
|
| 383 |
+
if not is_bucket(args.input) and not Path(args.input).is_dir():
|
| 384 |
+
parser.error(f"Input directory does not exist: {args.input}")
|
| 385 |
+
|
| 386 |
+
check_cuda_availability()
|
| 387 |
+
|
| 388 |
+
start_time = time.time()
|
| 389 |
+
logger.info(f"Listing inputs in {args.input} ...")
|
| 390 |
+
rels = list_inputs(args.input, args.include, args.max_samples)
|
| 391 |
+
if not rels:
|
| 392 |
+
logger.error(f"No image or PDF files found in {args.input}")
|
| 393 |
+
sys.exit(1)
|
| 394 |
+
clashes = output_collisions(rels)
|
| 395 |
+
if clashes:
|
| 396 |
+
logger.error("These inputs would write the same output file(s):")
|
| 397 |
+
for clash in clashes[:20]:
|
| 398 |
+
logger.error(f" {clash}")
|
| 399 |
+
logger.error("Rename them, or narrow the input with --include.")
|
| 400 |
+
sys.exit(1)
|
| 401 |
+
existing = set() if args.overwrite else list_outputs(args.output)
|
| 402 |
+
todo = [rel for rel in rels if not is_done(rel, existing, args.mode)]
|
| 403 |
+
skipped = len(rels) - len(todo)
|
| 404 |
+
logger.info(f"Found {len(rels)} file(s); {skipped} already done; {len(todo)} to OCR")
|
| 405 |
+
if not todo:
|
| 406 |
+
logger.info("Nothing to do (--overwrite to redo).")
|
| 407 |
+
return
|
| 408 |
+
|
| 409 |
+
logger.info(f"Initializing vLLM with {args.model} ({args.mode} mode)...")
|
| 410 |
+
# Stock Qwen3_5ForConditionalGeneration arch; gdn_prefill_backend="triton" avoids the
|
| 411 |
+
# gated-delta-net prefill path that needs a CUDA JIT toolchain (as in lighton-ocr3.py).
|
| 412 |
+
llm = LLM(
|
| 413 |
+
model=args.model,
|
| 414 |
+
max_model_len=args.max_model_len,
|
| 415 |
+
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 416 |
+
limit_mm_per_prompt={"image": 1},
|
| 417 |
+
gdn_prefill_backend="triton",
|
| 418 |
+
)
|
| 419 |
+
prompt = build_prompt(llm, args.mode)
|
| 420 |
+
sampling_params = SamplingParams(
|
| 421 |
+
temperature=args.temperature, top_p=args.top_p, max_tokens=args.max_tokens
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
pages_done = 0
|
| 425 |
+
errors = 0
|
| 426 |
+
files_seen = 0
|
| 427 |
+
failed: set[str] = set() # inputs with a page that failed: no .complete.<mode> marker this run
|
| 428 |
+
open_errors: list[str] = []
|
| 429 |
+
|
| 430 |
+
def file_pages(batch):
|
| 431 |
+
for rel, path in batch:
|
| 432 |
+
try:
|
| 433 |
+
yield from iter_pages(rel, path, existing, args.mode, args.longest_edge)
|
| 434 |
+
except Exception as e:
|
| 435 |
+
logger.error(f"Failed to open {rel}: {e}")
|
| 436 |
+
failed.add(rel)
|
| 437 |
+
open_errors.append(rel)
|
| 438 |
+
|
| 439 |
+
total_batches = (len(todo) + args.batch_size - 1) // args.batch_size
|
| 440 |
+
for batch_num, batch in enumerate(iter_local_batches(args.input, todo, args.batch_size), 1):
|
| 441 |
+
logger.info(f"Batch {batch_num}/{total_batches} ({files_seen}/{len(todo)} files done)")
|
| 442 |
+
files_seen += len(batch)
|
| 443 |
+
|
| 444 |
+
# Windows of at most --batch-size pages, rendered lazily.
|
| 445 |
+
for window in partition_all(args.batch_size, file_pages(batch)):
|
| 446 |
+
pages = [it for it in window if it.image is not None]
|
| 447 |
+
outputs = []
|
| 448 |
+
if pages:
|
| 449 |
+
try:
|
| 450 |
+
outputs = llm.generate(
|
| 451 |
+
[{"prompt": prompt, "multi_modal_data": {"image": it.image}} for it in pages],
|
| 452 |
+
sampling_params,
|
| 453 |
+
)
|
| 454 |
+
except Exception as e:
|
| 455 |
+
# Write nothing: these pages are retried on the next run.
|
| 456 |
+
logger.error(f"Batch {batch_num} failed: {e}")
|
| 457 |
+
errors += len(pages)
|
| 458 |
+
failed.update(it.rel for it in pages)
|
| 459 |
+
continue
|
| 460 |
+
|
| 461 |
+
pairs = []
|
| 462 |
+
for it, output in zip(pages, outputs, strict=True):
|
| 463 |
+
pairs.extend(render_outputs(it.md, output.outputs[0].text, it.image.size, args.mode,
|
| 464 |
+
not args.no_fix_dollars, args.model))
|
| 465 |
+
try:
|
| 466 |
+
write_outputs(args.output, pairs)
|
| 467 |
+
pages_done += len(pages)
|
| 468 |
+
except Exception as e:
|
| 469 |
+
logger.error(f"Writing batch {batch_num} failed: {e}")
|
| 470 |
+
errors += len(pages)
|
| 471 |
+
failed.update(it.rel for it in window)
|
| 472 |
+
continue
|
| 473 |
+
# Markers in a separate write, only after the page outputs are stored.
|
| 474 |
+
finished = [it.rel for it in window if it.last and it.rel not in failed]
|
| 475 |
+
try:
|
| 476 |
+
write_outputs(args.output, [(marker_rel(rel, args.mode), "ok\n") for rel in finished])
|
| 477 |
+
except Exception as e:
|
| 478 |
+
logger.error(f"Writing completion markers failed (pages are kept): {e}")
|
| 479 |
+
failed.update(finished)
|
| 480 |
+
|
| 481 |
+
errors += len(open_errors)
|
| 482 |
+
elapsed = time.time() - start_time
|
| 483 |
+
elapsed_str = f"{elapsed / 60:.1f} min" if elapsed > 60 else f"{elapsed:.1f}s"
|
| 484 |
+
logger.info("=" * 50)
|
| 485 |
+
logger.info(f"Done! Wrote {pages_done} page(s) from {files_seen} file(s) in {elapsed_str}")
|
| 486 |
+
logger.info(f" Output: {args.output}")
|
| 487 |
+
logger.info(f" Skipped (already done): {skipped}")
|
| 488 |
+
logger.info(f" Errors (no output, retried next run): {errors}")
|
| 489 |
+
if failed:
|
| 490 |
+
listed = sorted(failed)
|
| 491 |
+
logger.warning(f" Inputs with failures ({len(listed)}): {', '.join(listed[:20])}"
|
| 492 |
+
+ (" ..." if len(listed) > 20 else ""))
|
| 493 |
+
if args.overwrite:
|
| 494 |
+
logger.warning(" With --overwrite these keep their previous output: re-run them with --overwrite.")
|
| 495 |
+
if pages_done:
|
| 496 |
+
logger.info(f" Speed: {pages_done / elapsed:.2f} pages/sec")
|
| 497 |
+
|
| 498 |
+
if args.verbose:
|
| 499 |
+
import importlib.metadata
|
| 500 |
+
|
| 501 |
+
logger.info("--- Package versions ---")
|
| 502 |
+
for pkg in ["vllm", "transformers", "torch", "pillow", "imagecodecs", "bucketbag", "lightonocr"]:
|
| 503 |
+
try:
|
| 504 |
+
logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
|
| 505 |
+
except importlib.metadata.PackageNotFoundError:
|
| 506 |
+
logger.info(f" {pkg}: not installed")
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
if __name__ == "__main__":
|
| 510 |
+
if len(sys.argv) == 1:
|
| 511 |
+
print("=" * 60)
|
| 512 |
+
print("LightOnOCR-3 Bucket Script")
|
| 513 |
+
print("=" * 60)
|
| 514 |
+
print("\nOCR images/PDFs from an HF Bucket or directory → markdown files")
|
| 515 |
+
print("(+ .json layout blocks in grounding mode). Re-running resumes.")
|
| 516 |
+
print()
|
| 517 |
+
print("Usage:")
|
| 518 |
+
print(" lighton-ocr3-bucket.py INPUT OUTPUT (hf://buckets/... URLs or directories)")
|
| 519 |
+
print()
|
| 520 |
+
print("HF Jobs (image, flavor + secrets from the [tool.hf-jobs] header; hf CLI 1.32+):")
|
| 521 |
+
print(" hf jobs uv run \\")
|
| 522 |
+
print(" https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3-bucket.py \\")
|
| 523 |
+
print(" hf://buckets/ns/scans/vol1 hf://buckets/ns/ocr/vol1 --mode grounding")
|
| 524 |
+
print()
|
| 525 |
+
print("For full help: uv run --with vllm==0.30.0 lighton-ocr3-bucket.py --help")
|
| 526 |
+
sys.exit(0)
|
| 527 |
+
|
| 528 |
+
main()
|
lighton-ocr3.py
ADDED
|
@@ -0,0 +1,806 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "datasets>=4.0.0",
|
| 5 |
+
# "huggingface-hub",
|
| 6 |
+
# "pillow",
|
| 7 |
+
# "toolz",
|
| 8 |
+
# # LightOn's official client, pinned to a commit (not on PyPI). Used for its
|
| 9 |
+
# # parser, page resize and dollar-delimiter repair so outputs match upstream.
|
| 10 |
+
# "lightonocr @ https://github.com/lightonai/LightOnOCR/archive/36755d461be079737860a5f03ae0c803501269e9.tar.gz",
|
| 11 |
+
# ]
|
| 12 |
+
#
|
| 13 |
+
# [tool.hf-jobs]
|
| 14 |
+
# image = "vllm/vllm-openai:v0.30.0"
|
| 15 |
+
# python = "/usr/bin/python3"
|
| 16 |
+
# env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" }
|
| 17 |
+
# flavor = "a10g-small"
|
| 18 |
+
# secrets = ["HF_TOKEN"]
|
| 19 |
+
# ///
|
| 20 |
+
|
| 21 |
+
"""
|
| 22 |
+
Convert document images to markdown (or layout blocks) using LightOnOCR-3 with vLLM.
|
| 23 |
+
|
| 24 |
+
LightOnOCR-3 is LightOn's third generation of end-to-end OCR models. The 4B and 0.8B
|
| 25 |
+
variants use the stock Qwen3.5 vision-language architecture. Besides plain
|
| 26 |
+
transcription, they have a grounding mode: every block of the page comes back with a
|
| 27 |
+
label (title, text, table, chart, image, ...) and a bounding box. Images get a short
|
| 28 |
+
description and charts become an HTML table of their data points.
|
| 29 |
+
|
| 30 |
+
Models (Apache-2.0):
|
| 31 |
+
lightonai/LightOnOCR-3-4B (default) 86.3 olmOCR-Bench, 75.1 ParseBench
|
| 32 |
+
lightonai/LightOnOCR-3-0.8B 85.5 olmOCR-Bench, 74.6 ParseBench
|
| 33 |
+
LightOnOCR-3-1B is not supported here: it keeps the LightOnOCR-2 (Pixtral)
|
| 34 |
+
architecture and needs a different vLLM/transformers pin.
|
| 35 |
+
|
| 36 |
+
Run on HF Jobs (needs `hf` CLI 1.32+; the [tool.hf-jobs] header above sets the
|
| 37 |
+
vllm/vllm-openai:v0.30.0 image, a10g-small flavor and HF_TOKEN secret):
|
| 38 |
+
|
| 39 |
+
hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3.py \\
|
| 40 |
+
input-dataset output-dataset --max-samples 10
|
| 41 |
+
|
| 42 |
+
# Layout blocks with labels and boxes, smaller model
|
| 43 |
+
hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3.py \\
|
| 44 |
+
input-dataset output-dataset --mode grounding --model lightonai/LightOnOCR-3-0.8B
|
| 45 |
+
|
| 46 |
+
Run on your own GPU (vLLM and torch come from the image on Jobs, so add them here):
|
| 47 |
+
|
| 48 |
+
uv run --with vllm==0.30.0 lighton-ocr3.py input-dataset output-dataset
|
| 49 |
+
|
| 50 |
+
For large scans with very small type, try a higher --longest-edge and --max-tokens.
|
| 51 |
+
|
| 52 |
+
The image is pinned to vLLM 0.30.0 because LightOn's client reports that vLLM 0.27.1
|
| 53 |
+
makes the models loop and 0.30.0 is the version they test. Loosen the pin once a newer
|
| 54 |
+
vLLM is checked against the same outputs.
|
| 55 |
+
|
| 56 |
+
Modes:
|
| 57 |
+
- plain (default): the image alone -> markdown transcription. Same as LightOnOCR-2.
|
| 58 |
+
- grounding: the image + the text "grounding" -> one `` block per
|
| 59 |
+
region, coordinates normalised to 0-1000. The output column gets the block texts
|
| 60 |
+
joined as markdown; the --blocks-column gets the parsed blocks as JSON
|
| 61 |
+
([{label, bbox, text, continues}, ...]). Grounding adds about 25% output tokens.
|
| 62 |
+
The card says other instructions are out of distribution, so there is no custom prompt.
|
| 63 |
+
|
| 64 |
+
Sampling matches the model card's vLLM example: temperature 0.2, top_p 0.9,
|
| 65 |
+
max_tokens 4096, thinking disabled. (LightOn's client defaults to top_p 1.0 for
|
| 66 |
+
LightOnOCR-3; pass --top-p 1.0 to match it.) Pre- and post-processing follow the
|
| 67 |
+
official client (lightonocr/render.py, client.py): pages are downscaled to 2048 px on
|
| 68 |
+
the longest edge (the card's rendering tip; the processor does no further resizing),
|
| 69 |
+
and escaped dollar delimiters are repaired (`\\$x\\$` -> `$x$`) on every output.
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
import argparse
|
| 73 |
+
import io
|
| 74 |
+
import json
|
| 75 |
+
import logging
|
| 76 |
+
import os
|
| 77 |
+
import sys
|
| 78 |
+
import time
|
| 79 |
+
from datetime import datetime
|
| 80 |
+
from typing import Any, Dict, Union
|
| 81 |
+
|
| 82 |
+
import torch
|
| 83 |
+
from datasets import load_dataset
|
| 84 |
+
from huggingface_hub import DatasetCard, hf_hub_download, login
|
| 85 |
+
from lightonocr import (
|
| 86 |
+
DEFAULT_LONGEST_EDGE,
|
| 87 |
+
GROUNDING_PROMPT,
|
| 88 |
+
fit,
|
| 89 |
+
fix_escaped_dollars,
|
| 90 |
+
parse_blocks,
|
| 91 |
+
to_markdown,
|
| 92 |
+
)
|
| 93 |
+
from PIL import Image
|
| 94 |
+
from toolz import partition_all
|
| 95 |
+
|
| 96 |
+
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 97 |
+
# default uv-script image lacks (engine init then crashes). On the vllm/vllm-openai image it's
|
| 98 |
+
# a harmless no-op.
|
| 99 |
+
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 100 |
+
# DeepGEMM's init asserts on a missing nvcc (non-fatal traceback); OCR doesn't need it.
|
| 101 |
+
os.environ.setdefault("VLLM_USE_DEEP_GEMM", "0")
|
| 102 |
+
from vllm import LLM, SamplingParams
|
| 103 |
+
|
| 104 |
+
logging.basicConfig(level=logging.INFO)
|
| 105 |
+
logger = logging.getLogger(__name__)
|
| 106 |
+
|
| 107 |
+
MODELS = ["lightonai/LightOnOCR-3-4B", "lightonai/LightOnOCR-3-0.8B"]
|
| 108 |
+
DEFAULT_MODEL = MODELS[0]
|
| 109 |
+
|
| 110 |
+
# Sampling from the model card's vLLM example (temperature 0.2, top_p 0.9, max_tokens 4096).
|
| 111 |
+
DEFAULT_TEMPERATURE = 0.2
|
| 112 |
+
DEFAULT_TOP_P = 0.9
|
| 113 |
+
DEFAULT_MAX_TOKENS = 4096
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def check_cuda_availability():
|
| 117 |
+
"""Check if CUDA is available and exit if not."""
|
| 118 |
+
if not torch.cuda.is_available():
|
| 119 |
+
logger.error("CUDA is not available. This script requires a GPU.")
|
| 120 |
+
logger.error("Please run on a machine with a CUDA-capable GPU.")
|
| 121 |
+
sys.exit(1)
|
| 122 |
+
else:
|
| 123 |
+
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def ensure_output_columns_free(dataset, columns, overwrite=False):
|
| 127 |
+
"""Fail fast if an output column would collide with an existing input column.
|
| 128 |
+
|
| 129 |
+
Adding a column that already exists silently overwrites it (e.g. a ground-truth
|
| 130 |
+
`text`/`markdown` column) or crashes on push with a duplicate-column error only
|
| 131 |
+
*after* inference has run. Catch it up front. With overwrite=True, drop the clashing
|
| 132 |
+
column(s) here instead (logged) so the later add_column is clean.
|
| 133 |
+
"""
|
| 134 |
+
clash = [c for c in columns if c in dataset.column_names]
|
| 135 |
+
if not clash:
|
| 136 |
+
return dataset
|
| 137 |
+
if overwrite:
|
| 138 |
+
logger.warning(f"--overwrite: replacing existing column(s) {clash}")
|
| 139 |
+
return dataset.remove_columns(clash)
|
| 140 |
+
logger.error(
|
| 141 |
+
f"Output column(s) {clash} already exist in the input dataset "
|
| 142 |
+
f"(columns: {dataset.column_names})."
|
| 143 |
+
)
|
| 144 |
+
logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
|
| 145 |
+
sys.exit(1)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def to_pil_image(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:
|
| 149 |
+
"""Convert a dataset image cell (PIL image, bytes dict, or path) to RGB PIL."""
|
| 150 |
+
if isinstance(image, Image.Image):
|
| 151 |
+
pil_img = image
|
| 152 |
+
elif isinstance(image, dict) and "bytes" in image:
|
| 153 |
+
pil_img = Image.open(io.BytesIO(image["bytes"]))
|
| 154 |
+
elif isinstance(image, str):
|
| 155 |
+
pil_img = Image.open(image)
|
| 156 |
+
else:
|
| 157 |
+
raise ValueError(f"Unsupported image type: {type(image)}")
|
| 158 |
+
return pil_img.convert("RGB")
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def build_prompt(llm: LLM, mode: str) -> str:
|
| 162 |
+
"""Chat-template prompt for one page, with thinking disabled.
|
| 163 |
+
|
| 164 |
+
plain sends the image alone; grounding adds the text "grounding" after it
|
| 165 |
+
(client.py). The 0.8B and 4B were trained without thinking, so the template is
|
| 166 |
+
rendered with enable_thinking=False, as the card and client do.
|
| 167 |
+
"""
|
| 168 |
+
content = [{"type": "image"}]
|
| 169 |
+
if mode == "grounding":
|
| 170 |
+
content.append({"type": "text", "text": GROUNDING_PROMPT})
|
| 171 |
+
return llm.get_tokenizer().apply_chat_template(
|
| 172 |
+
[{"role": "user", "content": content}],
|
| 173 |
+
tokenize=False,
|
| 174 |
+
add_generation_prompt=True,
|
| 175 |
+
enable_thinking=False,
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def postprocess_output(text: str, mode: str, fix_dollars: bool):
|
| 180 |
+
"""Return (markdown, blocks_json or None) for one raw model output."""
|
| 181 |
+
text = text.strip()
|
| 182 |
+
if fix_dollars:
|
| 183 |
+
text = fix_escaped_dollars(text)
|
| 184 |
+
if mode != "grounding":
|
| 185 |
+
return text, None
|
| 186 |
+
blocks = parse_blocks(text)
|
| 187 |
+
if not blocks:
|
| 188 |
+
# No markers parsed: keep the raw text so nothing is lost.
|
| 189 |
+
return text, json.dumps([])
|
| 190 |
+
markdown = to_markdown(blocks)
|
| 191 |
+
return markdown, json.dumps([b.to_dict() for b in blocks], ensure_ascii=False)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def jobs_flavor() -> str:
|
| 195 |
+
"""Return the HF Jobs hardware flavor this run is on, or "" when it cannot be told.
|
| 196 |
+
|
| 197 |
+
HF Jobs sets ACCELERATOR to "cpu" or "gpu", not the flavor name, so the flavor is looked up
|
| 198 |
+
in the public Jobs hardware list: first by GPU model and count, then by the CPU_CORES and
|
| 199 |
+
MEMORY values that Jobs sets in the container (to tell a10g-small from a10g-large, or
|
| 200 |
+
cpu-basic from cpu-upgrade). Any failure (no network, older huggingface_hub) returns "".
|
| 201 |
+
"""
|
| 202 |
+
hardware = os.environ.get("ACCELERATOR") or ""
|
| 203 |
+
if "-" in hardware or any(character.isdigit() for character in hardware):
|
| 204 |
+
return hardware # already a flavor name
|
| 205 |
+
try:
|
| 206 |
+
from huggingface_hub import HfApi
|
| 207 |
+
|
| 208 |
+
gpu_name, gpu_count = "", 0
|
| 209 |
+
try:
|
| 210 |
+
import torch
|
| 211 |
+
|
| 212 |
+
if torch.cuda.is_available():
|
| 213 |
+
gpu_name = torch.cuda.get_device_name(0)
|
| 214 |
+
gpu_count = torch.cuda.device_count()
|
| 215 |
+
except ImportError:
|
| 216 |
+
# Torch-free drivers (e.g. the -server recipes): ask nvidia-smi instead.
|
| 217 |
+
import subprocess
|
| 218 |
+
|
| 219 |
+
try:
|
| 220 |
+
listed = subprocess.run(
|
| 221 |
+
["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"],
|
| 222 |
+
capture_output=True, text=True, timeout=10, check=True,
|
| 223 |
+
).stdout
|
| 224 |
+
names = [line.strip() for line in listed.splitlines() if line.strip()]
|
| 225 |
+
if names:
|
| 226 |
+
gpu_name, gpu_count = names[0], len(names)
|
| 227 |
+
except (OSError, subprocess.SubprocessError):
|
| 228 |
+
pass
|
| 229 |
+
if gpu_count == 0 and hardware == "gpu":
|
| 230 |
+
return "" # a GPU run whose GPU cannot be identified: do not guess a CPU flavor
|
| 231 |
+
|
| 232 |
+
# Whole-word match, so "L4" does not match "NVIDIA L40S" ("NVIDIA A100-SXM4-80GB" -> A100).
|
| 233 |
+
gpu_words = gpu_name.upper().replace("-", " ").split()
|
| 234 |
+
candidates = []
|
| 235 |
+
for flavor in HfApi(token=False).list_jobs_hardware():
|
| 236 |
+
accelerator = flavor.accelerator
|
| 237 |
+
if gpu_count == 0 and accelerator is None:
|
| 238 |
+
candidates.append(flavor)
|
| 239 |
+
elif (
|
| 240 |
+
gpu_count > 0
|
| 241 |
+
and accelerator is not None
|
| 242 |
+
and accelerator.model.upper() in gpu_words
|
| 243 |
+
and int(accelerator.quantity) == gpu_count
|
| 244 |
+
):
|
| 245 |
+
candidates.append(flavor)
|
| 246 |
+
if not candidates:
|
| 247 |
+
return ""
|
| 248 |
+
|
| 249 |
+
cores = float(os.environ.get("CPU_CORES") or 0)
|
| 250 |
+
memory_gb = float((os.environ.get("MEMORY") or "0").upper().rstrip("GIB ") or 0)
|
| 251 |
+
|
| 252 |
+
def distance(flavor) -> float:
|
| 253 |
+
# Relative gap to the listed vCPUs and RAM; Jobs reports slightly different numbers.
|
| 254 |
+
listed_cores = float(flavor.cpu.split()[0])
|
| 255 |
+
listed_memory = float(flavor.ram.split()[0])
|
| 256 |
+
return abs(listed_cores - cores) / listed_cores + abs(listed_memory - memory_gb) / listed_memory
|
| 257 |
+
|
| 258 |
+
return min(candidates, key=distance).name
|
| 259 |
+
except Exception:
|
| 260 |
+
return ""
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def create_dataset_card(
|
| 264 |
+
source_dataset: str,
|
| 265 |
+
model: str,
|
| 266 |
+
mode: str,
|
| 267 |
+
num_samples: int,
|
| 268 |
+
processing_time: str,
|
| 269 |
+
batch_size: int,
|
| 270 |
+
max_model_len: int,
|
| 271 |
+
max_tokens: int,
|
| 272 |
+
temperature: float,
|
| 273 |
+
top_p: float,
|
| 274 |
+
longest_edge: int,
|
| 275 |
+
gpu_memory_utilization: float,
|
| 276 |
+
output_column: str,
|
| 277 |
+
blocks_column: str,
|
| 278 |
+
image_column: str = "image",
|
| 279 |
+
split: str = "train",
|
| 280 |
+
) -> str:
|
| 281 |
+
"""Create a dataset card documenting the OCR process."""
|
| 282 |
+
model_name = model.split("/")[-1]
|
| 283 |
+
|
| 284 |
+
# Canonical provenance stamp (see AGENTS.md): Jobs claim gated on JOB_ID, set by HF Jobs in-container.
|
| 285 |
+
on_jobs = os.environ.get("JOB_ID") is not None
|
| 286 |
+
hw = jobs_flavor() # flavor name, e.g. "a10g-small"; "" when it cannot be told
|
| 287 |
+
origin = (
|
| 288 |
+
"Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"
|
| 289 |
+
+ (f" (`{hw}`)" if hw else "")
|
| 290 |
+
) if on_jobs else "Generated"
|
| 291 |
+
jobs_tag = "\n- hf-jobs" if on_jobs else ""
|
| 292 |
+
|
| 293 |
+
model_arg = f" \\\n --model {model}" if model != DEFAULT_MODEL else ""
|
| 294 |
+
mode_arg = " \\\n --mode grounding" if mode == "grounding" else ""
|
| 295 |
+
blocks_line = (
|
| 296 |
+
f"- `{blocks_column}`: JSON list of layout blocks "
|
| 297 |
+
"(`label`, `bbox` as x1,y1,x2,y2 normalised to 0-1000, `text`, `continues`)\n"
|
| 298 |
+
if mode == "grounding"
|
| 299 |
+
else ""
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
return f"""---
|
| 303 |
+
tags:
|
| 304 |
+
- ocr
|
| 305 |
+
- document-processing
|
| 306 |
+
- lighton-ocr-3
|
| 307 |
+
- markdown
|
| 308 |
+
- uv-script
|
| 309 |
+
- generated{jobs_tag}
|
| 310 |
+
---
|
| 311 |
+
|
| 312 |
+
# Document OCR using {model_name}
|
| 313 |
+
|
| 314 |
+
This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using [{model_name}](https://huggingface.co/{model}) in **{mode}** mode.
|
| 315 |
+
|
| 316 |
+
## Processing Details
|
| 317 |
+
|
| 318 |
+
- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
|
| 319 |
+
- **Model**: [{model}](https://huggingface.co/{model})
|
| 320 |
+
- **Mode**: `{mode}`
|
| 321 |
+
- **Number of Samples**: {num_samples:,}
|
| 322 |
+
- **Processing Time**: {processing_time}
|
| 323 |
+
- **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
|
| 324 |
+
|
| 325 |
+
### Configuration
|
| 326 |
+
|
| 327 |
+
- **Image Column**: `{image_column}`
|
| 328 |
+
- **Dataset Split**: `{split}`
|
| 329 |
+
- **Batch Size**: {batch_size}
|
| 330 |
+
- **Longest Image Edge**: {longest_edge}px
|
| 331 |
+
- **Max Model Length**: {max_model_len:,} tokens
|
| 332 |
+
- **Max Output Tokens**: {max_tokens:,}
|
| 333 |
+
- **Temperature**: {temperature}
|
| 334 |
+
- **Top P**: {top_p}
|
| 335 |
+
- **GPU Memory Utilization**: {gpu_memory_utilization:.1%}
|
| 336 |
+
|
| 337 |
+
## Dataset Structure
|
| 338 |
+
|
| 339 |
+
The dataset contains all original columns plus:
|
| 340 |
+
- `{output_column}`: The extracted text in markdown format
|
| 341 |
+
{blocks_line}- `inference_info`: JSON list tracking all OCR models applied to this dataset
|
| 342 |
+
|
| 343 |
+
## Reproduction
|
| 344 |
+
|
| 345 |
+
{origin} with the [`lighton-ocr3.py`](https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3.py) recipe from [uv-scripts](https://huggingface.co/uv-scripts). Run it yourself:
|
| 346 |
+
|
| 347 |
+
```bash
|
| 348 |
+
hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3.py \\
|
| 349 |
+
{source_dataset} \\
|
| 350 |
+
<output-dataset> \\
|
| 351 |
+
--image-column {image_column} \\
|
| 352 |
+
--batch-size {batch_size}{model_arg}{mode_arg}
|
| 353 |
+
```
|
| 354 |
+
"""
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def main(
|
| 358 |
+
input_dataset: str,
|
| 359 |
+
output_dataset: str,
|
| 360 |
+
model: str = DEFAULT_MODEL,
|
| 361 |
+
mode: str = "plain",
|
| 362 |
+
image_column: str = "image",
|
| 363 |
+
batch_size: int = 16,
|
| 364 |
+
max_model_len: int = 16384,
|
| 365 |
+
max_tokens: int = DEFAULT_MAX_TOKENS,
|
| 366 |
+
temperature: float = DEFAULT_TEMPERATURE,
|
| 367 |
+
top_p: float = DEFAULT_TOP_P,
|
| 368 |
+
longest_edge: int = DEFAULT_LONGEST_EDGE,
|
| 369 |
+
no_fix_dollars: bool = False,
|
| 370 |
+
gpu_memory_utilization: float = 0.8,
|
| 371 |
+
hf_token: str = None,
|
| 372 |
+
split: str = "train",
|
| 373 |
+
max_samples: int = None,
|
| 374 |
+
private: bool = False,
|
| 375 |
+
shuffle: bool = False,
|
| 376 |
+
seed: int = 42,
|
| 377 |
+
output_column: str = "markdown",
|
| 378 |
+
blocks_column: str = "layout_blocks",
|
| 379 |
+
overwrite: bool = False,
|
| 380 |
+
verbose: bool = False,
|
| 381 |
+
config: str = None,
|
| 382 |
+
create_pr: bool = False,
|
| 383 |
+
):
|
| 384 |
+
"""Process images from HF dataset through LightOnOCR-3."""
|
| 385 |
+
|
| 386 |
+
check_cuda_availability()
|
| 387 |
+
|
| 388 |
+
start_time = datetime.now()
|
| 389 |
+
|
| 390 |
+
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
|
| 391 |
+
if HF_TOKEN:
|
| 392 |
+
login(token=HF_TOKEN)
|
| 393 |
+
|
| 394 |
+
logger.info(f"Using model: {model} ({mode} mode)")
|
| 395 |
+
|
| 396 |
+
# Load dataset
|
| 397 |
+
logger.info(f"Loading dataset: {input_dataset}")
|
| 398 |
+
dataset = load_dataset(input_dataset, split=split)
|
| 399 |
+
|
| 400 |
+
if image_column not in dataset.column_names:
|
| 401 |
+
raise ValueError(
|
| 402 |
+
f"Column '{image_column}' not found. Available: {dataset.column_names}"
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
# Fail fast if an output column would collide with an existing input column
|
| 406 |
+
output_columns = [output_column] + ([blocks_column] if mode == "grounding" else [])
|
| 407 |
+
dataset = ensure_output_columns_free(dataset, output_columns, overwrite=overwrite)
|
| 408 |
+
|
| 409 |
+
if shuffle:
|
| 410 |
+
logger.info(f"Shuffling dataset with seed {seed}")
|
| 411 |
+
dataset = dataset.shuffle(seed=seed)
|
| 412 |
+
|
| 413 |
+
if max_samples:
|
| 414 |
+
dataset = dataset.select(range(min(max_samples, len(dataset))))
|
| 415 |
+
logger.info(f"Limited to {len(dataset)} samples")
|
| 416 |
+
|
| 417 |
+
# Initialize vLLM
|
| 418 |
+
logger.info(f"Initializing vLLM with {model}")
|
| 419 |
+
logger.info("This may take a few minutes on first run...")
|
| 420 |
+
# Stock Qwen3_5ForConditionalGeneration arch, so no trust_remote_code. A 2048px page
|
| 421 |
+
# is at most 64x64 = 4,096 image tokens (16px patches, 2x2 merge), so 16384 leaves
|
| 422 |
+
# room for the card's 4096 output tokens. gdn_prefill_backend="triton" avoids the
|
| 423 |
+
# Qwen3.5 gated-delta-net prefill path that needs a CUDA JIT toolchain (as ovis-ocr2.py).
|
| 424 |
+
llm = LLM(
|
| 425 |
+
model=model,
|
| 426 |
+
max_model_len=max_model_len,
|
| 427 |
+
gpu_memory_utilization=gpu_memory_utilization,
|
| 428 |
+
limit_mm_per_prompt={"image": 1},
|
| 429 |
+
gdn_prefill_backend="triton",
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
prompt = build_prompt(llm, mode)
|
| 433 |
+
sampling_params = SamplingParams(
|
| 434 |
+
temperature=temperature, top_p=top_p, max_tokens=max_tokens
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
|
| 438 |
+
logger.info(f"Output will be written to column: {output_column}")
|
| 439 |
+
if mode == "grounding":
|
| 440 |
+
logger.info(f"Layout blocks will be written to column: {blocks_column}")
|
| 441 |
+
|
| 442 |
+
all_markdown = []
|
| 443 |
+
all_blocks = []
|
| 444 |
+
total_batches = (len(dataset) + batch_size - 1) // batch_size
|
| 445 |
+
processed = 0
|
| 446 |
+
|
| 447 |
+
for batch_num, batch_indices in enumerate(
|
| 448 |
+
partition_all(batch_size, range(len(dataset))), 1
|
| 449 |
+
):
|
| 450 |
+
batch_indices = list(batch_indices)
|
| 451 |
+
batch_images = [dataset[i][image_column] for i in batch_indices]
|
| 452 |
+
|
| 453 |
+
logger.info(
|
| 454 |
+
f"Batch {batch_num}/{total_batches} "
|
| 455 |
+
f"({processed}/{len(dataset)} images done)"
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
try:
|
| 459 |
+
# Downscale to the training render size (never upscale), as the client does.
|
| 460 |
+
vllm_inputs = [
|
| 461 |
+
{
|
| 462 |
+
"prompt": prompt,
|
| 463 |
+
"multi_modal_data": {"image": fit(to_pil_image(img), longest_edge)},
|
| 464 |
+
}
|
| 465 |
+
for img in batch_images
|
| 466 |
+
]
|
| 467 |
+
|
| 468 |
+
outputs = llm.generate(vllm_inputs, sampling_params)
|
| 469 |
+
|
| 470 |
+
for output in outputs:
|
| 471 |
+
markdown, blocks = postprocess_output(
|
| 472 |
+
output.outputs[0].text, mode, fix_dollars=not no_fix_dollars
|
| 473 |
+
)
|
| 474 |
+
all_markdown.append(markdown)
|
| 475 |
+
all_blocks.append(blocks)
|
| 476 |
+
|
| 477 |
+
processed += len(batch_images)
|
| 478 |
+
|
| 479 |
+
except Exception as e:
|
| 480 |
+
logger.error(f"Error processing batch: {e}")
|
| 481 |
+
all_markdown.extend(["[OCR ERROR]"] * len(batch_images))
|
| 482 |
+
all_blocks.extend([json.dumps([])] * len(batch_images))
|
| 483 |
+
processed += len(batch_images)
|
| 484 |
+
|
| 485 |
+
processing_duration = datetime.now() - start_time
|
| 486 |
+
processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
|
| 487 |
+
|
| 488 |
+
logger.info(f"Adding '{output_column}' column to dataset")
|
| 489 |
+
dataset = dataset.add_column(output_column, all_markdown)
|
| 490 |
+
if mode == "grounding":
|
| 491 |
+
logger.info(f"Adding '{blocks_column}' column to dataset")
|
| 492 |
+
dataset = dataset.add_column(blocks_column, all_blocks)
|
| 493 |
+
|
| 494 |
+
# Inference info tracking
|
| 495 |
+
inference_entry = {
|
| 496 |
+
"model_id": model,
|
| 497 |
+
"model_name": model.split("/")[-1],
|
| 498 |
+
"mode": mode,
|
| 499 |
+
"column_name": output_column,
|
| 500 |
+
"blocks_column": blocks_column if mode == "grounding" else None,
|
| 501 |
+
"timestamp": datetime.now().isoformat(),
|
| 502 |
+
"temperature": temperature,
|
| 503 |
+
"top_p": top_p,
|
| 504 |
+
"max_tokens": max_tokens,
|
| 505 |
+
"longest_edge": longest_edge,
|
| 506 |
+
"fix_dollars": not no_fix_dollars,
|
| 507 |
+
}
|
| 508 |
+
|
| 509 |
+
if "inference_info" in dataset.column_names:
|
| 510 |
+
logger.info("Updating existing inference_info column")
|
| 511 |
+
|
| 512 |
+
def update_inference_info(example):
|
| 513 |
+
try:
|
| 514 |
+
existing_info = (
|
| 515 |
+
json.loads(example["inference_info"])
|
| 516 |
+
if example["inference_info"]
|
| 517 |
+
else []
|
| 518 |
+
)
|
| 519 |
+
except (json.JSONDecodeError, TypeError):
|
| 520 |
+
existing_info = []
|
| 521 |
+
existing_info.append(inference_entry)
|
| 522 |
+
return {"inference_info": json.dumps(existing_info)}
|
| 523 |
+
|
| 524 |
+
dataset = dataset.map(update_inference_info)
|
| 525 |
+
else:
|
| 526 |
+
logger.info("Creating new inference_info column")
|
| 527 |
+
inference_list = [json.dumps([inference_entry])] * len(dataset)
|
| 528 |
+
dataset = dataset.add_column("inference_info", inference_list)
|
| 529 |
+
|
| 530 |
+
# Push to hub with retry and XET fallback
|
| 531 |
+
logger.info(f"Pushing to {output_dataset}")
|
| 532 |
+
max_retries = 3
|
| 533 |
+
for attempt in range(1, max_retries + 1):
|
| 534 |
+
try:
|
| 535 |
+
if attempt > 1:
|
| 536 |
+
logger.warning("Disabling XET (fallback to HTTP upload)")
|
| 537 |
+
os.environ["HF_HUB_DISABLE_XET"] = "1"
|
| 538 |
+
commit_info = dataset.push_to_hub(
|
| 539 |
+
output_dataset,
|
| 540 |
+
private=private,
|
| 541 |
+
token=HF_TOKEN,
|
| 542 |
+
max_shard_size="500MB",
|
| 543 |
+
**({"config_name": config} if config else {}),
|
| 544 |
+
create_pr=create_pr,
|
| 545 |
+
commit_message=f"Add {model} OCR results ({len(dataset)} samples)"
|
| 546 |
+
+ (f" [{config}]" if config else ""),
|
| 547 |
+
)
|
| 548 |
+
break
|
| 549 |
+
except Exception as e:
|
| 550 |
+
logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
|
| 551 |
+
if attempt < max_retries:
|
| 552 |
+
delay = 30 * (2 ** (attempt - 1))
|
| 553 |
+
logger.info(f"Retrying in {delay}s...")
|
| 554 |
+
time.sleep(delay)
|
| 555 |
+
else:
|
| 556 |
+
logger.error("All upload attempts failed. OCR results are lost.")
|
| 557 |
+
sys.exit(1)
|
| 558 |
+
|
| 559 |
+
# Create and push dataset card
|
| 560 |
+
logger.info("Creating dataset card")
|
| 561 |
+
card_content = create_dataset_card(
|
| 562 |
+
source_dataset=input_dataset,
|
| 563 |
+
model=model,
|
| 564 |
+
mode=mode,
|
| 565 |
+
num_samples=len(dataset),
|
| 566 |
+
processing_time=processing_time_str,
|
| 567 |
+
batch_size=batch_size,
|
| 568 |
+
max_model_len=max_model_len,
|
| 569 |
+
max_tokens=max_tokens,
|
| 570 |
+
temperature=temperature,
|
| 571 |
+
top_p=top_p,
|
| 572 |
+
longest_edge=longest_edge,
|
| 573 |
+
gpu_memory_utilization=gpu_memory_utilization,
|
| 574 |
+
output_column=output_column,
|
| 575 |
+
blocks_column=blocks_column,
|
| 576 |
+
image_column=image_column,
|
| 577 |
+
split=split,
|
| 578 |
+
)
|
| 579 |
+
|
| 580 |
+
# With --create-pr the data went to a PR branch; the card goes to the same branch.
|
| 581 |
+
revision = commit_info.pr_revision if create_pr else None
|
| 582 |
+
card = DatasetCard(card_content)
|
| 583 |
+
# Keep the configs/dataset_info metadata push_to_hub just wrote, or named configs
|
| 584 |
+
# (--config) stop loading.
|
| 585 |
+
pushed = DatasetCard.load(
|
| 586 |
+
hf_hub_download(output_dataset, "README.md", repo_type="dataset",
|
| 587 |
+
revision=revision, token=HF_TOKEN)
|
| 588 |
+
)
|
| 589 |
+
for key in ("configs", "dataset_info"):
|
| 590 |
+
if pushed.data.get(key) is not None:
|
| 591 |
+
card.data[key] = pushed.data[key]
|
| 592 |
+
card.push_to_hub(output_dataset, token=HF_TOKEN, revision=revision)
|
| 593 |
+
|
| 594 |
+
logger.info("Done! LightOnOCR-3 processing complete.")
|
| 595 |
+
logger.info(
|
| 596 |
+
f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
|
| 597 |
+
)
|
| 598 |
+
logger.info(f"Processing time: {processing_time_str}")
|
| 599 |
+
logger.info(
|
| 600 |
+
f"Processing speed: {len(dataset) / processing_duration.total_seconds():.2f} images/sec"
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
if verbose:
|
| 604 |
+
import importlib.metadata
|
| 605 |
+
|
| 606 |
+
logger.info("--- Resolved package versions ---")
|
| 607 |
+
for pkg in ["vllm", "transformers", "torch", "datasets", "pyarrow", "pillow", "lightonocr"]:
|
| 608 |
+
try:
|
| 609 |
+
logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
|
| 610 |
+
except importlib.metadata.PackageNotFoundError:
|
| 611 |
+
logger.info(f" {pkg}: not installed")
|
| 612 |
+
logger.info("--- End versions ---")
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
if __name__ == "__main__":
|
| 616 |
+
if len(sys.argv) == 1:
|
| 617 |
+
print("=" * 70)
|
| 618 |
+
print("LightOnOCR-3 Document Processing")
|
| 619 |
+
print("=" * 70)
|
| 620 |
+
print("\n4B (default) or 0.8B end-to-end OCR, Qwen3.5 architecture")
|
| 621 |
+
print("\nModes:")
|
| 622 |
+
print(" plain markdown transcription (default)")
|
| 623 |
+
print(" grounding labelled layout blocks with 0-1000 boxes")
|
| 624 |
+
print("\nExamples:")
|
| 625 |
+
print("\n1. Basic OCR (own GPU):")
|
| 626 |
+
print(" uv run --with vllm==0.30.0 lighton-ocr3.py input-dataset output-dataset")
|
| 627 |
+
print("\n2. Layout blocks with the 0.8B model:")
|
| 628 |
+
print(" uv run --with vllm==0.30.0 lighton-ocr3.py docs results \\")
|
| 629 |
+
print(" --mode grounding --model lightonai/LightOnOCR-3-0.8B")
|
| 630 |
+
print("\n3. Running on HF Jobs (hf CLI 1.32+; image/flavor/secrets from the script header):")
|
| 631 |
+
print(" hf jobs uv run \\")
|
| 632 |
+
print(
|
| 633 |
+
" https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3.py \\"
|
| 634 |
+
)
|
| 635 |
+
print(" input-dataset output-dataset --max-samples 10")
|
| 636 |
+
print("\nFor full help: uv run --with vllm==0.30.0 lighton-ocr3.py --help")
|
| 637 |
+
sys.exit(0)
|
| 638 |
+
|
| 639 |
+
parser = argparse.ArgumentParser(
|
| 640 |
+
description="Document OCR using LightOnOCR-3 (4B or 0.8B, plain or grounding mode)",
|
| 641 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 642 |
+
epilog="""
|
| 643 |
+
Examples:
|
| 644 |
+
uv run --with vllm==0.30.0 lighton-ocr3.py my-docs analyzed-docs
|
| 645 |
+
uv run --with vllm==0.30.0 lighton-ocr3.py docs results --mode grounding
|
| 646 |
+
uv run --with vllm==0.30.0 lighton-ocr3.py docs results --model lightonai/LightOnOCR-3-0.8B
|
| 647 |
+
""",
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
|
| 651 |
+
parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
|
| 652 |
+
parser.add_argument(
|
| 653 |
+
"--model",
|
| 654 |
+
default=DEFAULT_MODEL,
|
| 655 |
+
choices=MODELS,
|
| 656 |
+
help=f"Model checkpoint (default: {DEFAULT_MODEL})",
|
| 657 |
+
)
|
| 658 |
+
parser.add_argument(
|
| 659 |
+
"--mode",
|
| 660 |
+
default="plain",
|
| 661 |
+
choices=["plain", "grounding"],
|
| 662 |
+
help="plain = markdown transcription; grounding = labelled layout blocks "
|
| 663 |
+
"with boxes, parsed into --blocks-column (default: plain)",
|
| 664 |
+
)
|
| 665 |
+
parser.add_argument(
|
| 666 |
+
"--image-column",
|
| 667 |
+
default="image",
|
| 668 |
+
help="Column containing images (default: image)",
|
| 669 |
+
)
|
| 670 |
+
parser.add_argument(
|
| 671 |
+
"--batch-size",
|
| 672 |
+
type=int,
|
| 673 |
+
default=16,
|
| 674 |
+
help="Batch size for processing (default: 16)",
|
| 675 |
+
)
|
| 676 |
+
parser.add_argument(
|
| 677 |
+
"--max-model-len",
|
| 678 |
+
type=int,
|
| 679 |
+
default=16384,
|
| 680 |
+
help="Maximum model context length (default: 16384; model supports 262144). "
|
| 681 |
+
"A 2048px page is at most 4,096 image tokens.",
|
| 682 |
+
)
|
| 683 |
+
parser.add_argument(
|
| 684 |
+
"--max-tokens",
|
| 685 |
+
type=int,
|
| 686 |
+
default=DEFAULT_MAX_TOKENS,
|
| 687 |
+
help=f"Maximum tokens to generate (default: {DEFAULT_MAX_TOKENS}, the card's "
|
| 688 |
+
"vLLM example). Raise it for very dense pages in grounding mode.",
|
| 689 |
+
)
|
| 690 |
+
parser.add_argument(
|
| 691 |
+
"--temperature",
|
| 692 |
+
type=float,
|
| 693 |
+
default=DEFAULT_TEMPERATURE,
|
| 694 |
+
help=f"Sampling temperature (default: {DEFAULT_TEMPERATURE}, model card)",
|
| 695 |
+
)
|
| 696 |
+
parser.add_argument(
|
| 697 |
+
"--top-p",
|
| 698 |
+
type=float,
|
| 699 |
+
default=DEFAULT_TOP_P,
|
| 700 |
+
help=f"Top-p (default: {DEFAULT_TOP_P}, model card; LightOn's client uses 1.0)",
|
| 701 |
+
)
|
| 702 |
+
parser.add_argument(
|
| 703 |
+
"--longest-edge",
|
| 704 |
+
type=int,
|
| 705 |
+
default=DEFAULT_LONGEST_EDGE,
|
| 706 |
+
help=f"Downscale pages so the longest edge is at most this many pixels "
|
| 707 |
+
f"(default: {DEFAULT_LONGEST_EDGE}, the training render size)",
|
| 708 |
+
)
|
| 709 |
+
parser.add_argument(
|
| 710 |
+
"--no-fix-dollars",
|
| 711 |
+
action="store_true",
|
| 712 |
+
help="Keep the raw model output instead of repairing escaped dollar "
|
| 713 |
+
"delimiters (the official client repairs them by default)",
|
| 714 |
+
)
|
| 715 |
+
parser.add_argument(
|
| 716 |
+
"--gpu-memory-utilization",
|
| 717 |
+
type=float,
|
| 718 |
+
default=0.8,
|
| 719 |
+
help="GPU memory utilization (default: 0.8)",
|
| 720 |
+
)
|
| 721 |
+
parser.add_argument("--hf-token", help="Hugging Face API token")
|
| 722 |
+
parser.add_argument(
|
| 723 |
+
"--split", default="train", help="Dataset split to use (default: train)"
|
| 724 |
+
)
|
| 725 |
+
parser.add_argument(
|
| 726 |
+
"--max-samples",
|
| 727 |
+
type=int,
|
| 728 |
+
help="Maximum number of samples to process (for testing)",
|
| 729 |
+
)
|
| 730 |
+
parser.add_argument(
|
| 731 |
+
"--private", action="store_true", help="Make output dataset private"
|
| 732 |
+
)
|
| 733 |
+
parser.add_argument(
|
| 734 |
+
"--config",
|
| 735 |
+
help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
|
| 736 |
+
)
|
| 737 |
+
parser.add_argument(
|
| 738 |
+
"--create-pr",
|
| 739 |
+
action="store_true",
|
| 740 |
+
help="Create a pull request instead of pushing directly (for parallel benchmarking)",
|
| 741 |
+
)
|
| 742 |
+
parser.add_argument(
|
| 743 |
+
"--shuffle", action="store_true", help="Shuffle dataset before processing"
|
| 744 |
+
)
|
| 745 |
+
parser.add_argument(
|
| 746 |
+
"--seed",
|
| 747 |
+
type=int,
|
| 748 |
+
default=42,
|
| 749 |
+
help="Random seed for shuffling (default: 42)",
|
| 750 |
+
)
|
| 751 |
+
parser.add_argument(
|
| 752 |
+
"--output-column",
|
| 753 |
+
default="markdown",
|
| 754 |
+
help="Column name for output text (default: markdown)",
|
| 755 |
+
)
|
| 756 |
+
parser.add_argument(
|
| 757 |
+
"--blocks-column",
|
| 758 |
+
default="layout_blocks",
|
| 759 |
+
help="Column name for parsed layout blocks in grounding mode (default: layout_blocks)",
|
| 760 |
+
)
|
| 761 |
+
parser.add_argument(
|
| 762 |
+
"--overwrite",
|
| 763 |
+
action="store_true",
|
| 764 |
+
help="Replace the output column(s) if they already exist in the input dataset "
|
| 765 |
+
"(default: error out to avoid clobbering an existing column).",
|
| 766 |
+
)
|
| 767 |
+
parser.add_argument(
|
| 768 |
+
"--verbose",
|
| 769 |
+
action="store_true",
|
| 770 |
+
help="Log resolved package versions after processing (useful for pinning deps)",
|
| 771 |
+
)
|
| 772 |
+
|
| 773 |
+
args = parser.parse_args()
|
| 774 |
+
|
| 775 |
+
if args.max_tokens > args.max_model_len:
|
| 776 |
+
parser.error(
|
| 777 |
+
f"--max-tokens ({args.max_tokens}) must be <= --max-model-len ({args.max_model_len})"
|
| 778 |
+
)
|
| 779 |
+
|
| 780 |
+
main(
|
| 781 |
+
input_dataset=args.input_dataset,
|
| 782 |
+
output_dataset=args.output_dataset,
|
| 783 |
+
model=args.model,
|
| 784 |
+
mode=args.mode,
|
| 785 |
+
image_column=args.image_column,
|
| 786 |
+
batch_size=args.batch_size,
|
| 787 |
+
max_model_len=args.max_model_len,
|
| 788 |
+
max_tokens=args.max_tokens,
|
| 789 |
+
temperature=args.temperature,
|
| 790 |
+
top_p=args.top_p,
|
| 791 |
+
longest_edge=args.longest_edge,
|
| 792 |
+
no_fix_dollars=args.no_fix_dollars,
|
| 793 |
+
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 794 |
+
hf_token=args.hf_token,
|
| 795 |
+
split=args.split,
|
| 796 |
+
max_samples=args.max_samples,
|
| 797 |
+
private=args.private,
|
| 798 |
+
shuffle=args.shuffle,
|
| 799 |
+
seed=args.seed,
|
| 800 |
+
output_column=args.output_column,
|
| 801 |
+
blocks_column=args.blocks_column,
|
| 802 |
+
overwrite=args.overwrite,
|
| 803 |
+
verbose=args.verbose,
|
| 804 |
+
config=args.config,
|
| 805 |
+
create_pr=args.create_pr,
|
| 806 |
+
)
|
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-
|
| 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`.",
|
|
@@ -314,6 +314,58 @@
|
|
| 314 |
},
|
| 315 |
"image": "vllm/vllm-openai:v0.22.1"
|
| 316 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
"lighton-ocr2-server.py": {
|
| 318 |
"model_id": "lightonai/LightOnOCR-2-1B",
|
| 319 |
"params": "1B",
|
|
|
|
| 1 |
{
|
| 2 |
"_meta": {
|
| 3 |
"description": "Machine-readable catalog of the OCR recipes in this directory: script -> model, params, backend, support level, the tested Jobs launch config (the script's [tool.hf-jobs] header), and what the model's own card claims about language coverage. Human-readable language notes: LANGUAGES.md. Language evidence levels, strongest first: per-language-benchmark | count-claim | named-list | multilingual-unspecified | english-only | not-stated | not-applicable. Claims come from model cards (compiled 2026-07-15) - treat as claims, not guarantees.",
|
| 4 |
+
"updated": "2026-10-22",
|
| 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`.",
|
|
|
|
| 314 |
},
|
| 315 |
"image": "vllm/vllm-openai:v0.22.1"
|
| 316 |
},
|
| 317 |
+
"lighton-ocr3.py": {
|
| 318 |
+
"model_id": "lightonai/LightOnOCR-3-4B",
|
| 319 |
+
"params": "4B (or 0.8B via --model)",
|
| 320 |
+
"backend": "vllm",
|
| 321 |
+
"task": "ocr",
|
| 322 |
+
"output": "markdown; --mode grounding adds labelled layout blocks with 0-1000 boxes (layout_blocks JSON column)",
|
| 323 |
+
"license": "apache-2.0",
|
| 324 |
+
"languages": {
|
| 325 |
+
"evidence": "not-stated",
|
| 326 |
+
"notes": "LightOnOCR-3 cards give no language list (LightOnOCR-2 named 11)."
|
| 327 |
+
},
|
| 328 |
+
"support": "core",
|
| 329 |
+
"jobs": {
|
| 330 |
+
"image": "vllm/vllm-openai:v0.30.0",
|
| 331 |
+
"python": "/usr/bin/python3",
|
| 332 |
+
"env": {
|
| 333 |
+
"PYTHONPATH": "/usr/local/lib/python3.12/dist-packages"
|
| 334 |
+
},
|
| 335 |
+
"flavor": "a10g-small",
|
| 336 |
+
"secrets": [
|
| 337 |
+
"HF_TOKEN"
|
| 338 |
+
]
|
| 339 |
+
},
|
| 340 |
+
"image": "vllm/vllm-openai:v0.30.0",
|
| 341 |
+
"notes": "Also runs lightonai/LightOnOCR-3-0.8B. Not LightOnOCR-3-1B (Pixtral arch, different pins). vLLM 0.30.0 pinned: upstream reports 0.27.1 loops."
|
| 342 |
+
},
|
| 343 |
+
"lighton-ocr3-bucket.py": {
|
| 344 |
+
"model_id": "lightonai/LightOnOCR-3-4B",
|
| 345 |
+
"params": "4B (or 0.8B via --model)",
|
| 346 |
+
"backend": "vllm",
|
| 347 |
+
"task": "ocr",
|
| 348 |
+
"output": "one .md per image/PDF page in an output dir; --mode grounding adds a .json sidecar of layout blocks",
|
| 349 |
+
"license": "apache-2.0",
|
| 350 |
+
"languages": {
|
| 351 |
+
"evidence": "not-stated",
|
| 352 |
+
"notes": "LightOnOCR-3 cards give no language list (LightOnOCR-2 named 11)."
|
| 353 |
+
},
|
| 354 |
+
"support": "core",
|
| 355 |
+
"jobs": {
|
| 356 |
+
"image": "vllm/vllm-openai:v0.30.0",
|
| 357 |
+
"python": "/usr/bin/python3",
|
| 358 |
+
"env": {
|
| 359 |
+
"PYTHONPATH": "/usr/local/lib/python3.12/dist-packages"
|
| 360 |
+
},
|
| 361 |
+
"flavor": "a10g-small",
|
| 362 |
+
"secrets": [
|
| 363 |
+
"HF_TOKEN"
|
| 364 |
+
]
|
| 365 |
+
},
|
| 366 |
+
"image": "vllm/vllm-openai:v0.30.0",
|
| 367 |
+
"notes": "Bucket sibling of lighton-ocr3.py (same model, prompt, sampling). Input/output: hf://buckets/... URLs via bucketbag v0.3.1 (no mount) or directories. Reads .jp2; resume-by-skip."
|
| 368 |
+
},
|
| 369 |
"lighton-ocr2-server.py": {
|
| 370 |
"model_id": "lightonai/LightOnOCR-2-1B",
|
| 371 |
"params": "1B",
|