I need pull
#6
by visssoftjsc - opened
- AGENTS.md +0 -92
- CLAUDE.md +79 -421
- README.md +529 -143
- abot-ocr.py +0 -560
- deepseek-ocr-vllm.py +0 -4
- deepseek-ocr2-vllm.py +0 -4
- dots-mocr.py → dots-ocr-1.5.py +62 -115
- dots-ocr.py +0 -4
- examples/nls-index-card-v2.json +0 -13
- examples/nls-index-card-verbose.json +0 -13
- falcon-ocr-bucket.py +0 -303
- falcon-ocr.py +0 -433
- firered-ocr.py +7 -14
- glm-ocr-bucket.py +0 -369
- glm-ocr-v2.py +0 -4
- glm-ocr.py +0 -4
- hunyuan-ocr.py +0 -4
- lfm2-extract.py +0 -293
- lfm2-vl-extract.py +0 -324
- lighton-ocr.py +0 -4
- lighton-ocr2.py +0 -4
- nanonets-ocr.py +0 -4
- nanonets-ocr2.py +0 -4
- nuextract3.py +0 -749
- numarkdown-ocr.py +0 -4
- olmocr2-vllm.py +6 -21
- paddleocr-vl-1.6.py +0 -798
- paddleocr-vl.py +0 -4
- pp-doclayout.py +0 -1183
- qianfan-ocr.py +0 -632
- rolm-ocr.py +0 -4
- smoldocling-ocr.py +2 -20
AGENTS.md
DELETED
|
@@ -1,92 +0,0 @@
|
|
| 1 |
-
# For coding agents
|
| 2 |
-
|
| 3 |
-
This repo is a curated collection of ready-to-run OCR scripts — each one self-contained
|
| 4 |
-
via UV inline metadata, runnable over the network via `hf jobs uv run`. No clone, no
|
| 5 |
-
install, no setup.
|
| 6 |
-
|
| 7 |
-
## Don't rely on this doc — discover the current state
|
| 8 |
-
|
| 9 |
-
This file will go stale. Prefer these sources of truth:
|
| 10 |
-
|
| 11 |
-
- `hf jobs uv run --help` — job submission flags (volumes, secrets, flavors, timeouts)
|
| 12 |
-
- `hf jobs hardware` — current GPU flavors and pricing
|
| 13 |
-
- `hf auth whoami` — check HF token is set
|
| 14 |
-
- `hf jobs ps` / `hf jobs logs <id>` — monitor running jobs
|
| 15 |
-
- `ls` the repo to see which scripts actually exist (bucket variants especially)
|
| 16 |
-
- [README.md](./README.md) — the table of scripts with model sizes and notes
|
| 17 |
-
|
| 18 |
-
## Picking a script
|
| 19 |
-
|
| 20 |
-
The [README.md](./README.md) table lists every script with model size, backend, and
|
| 21 |
-
a short note. Axes that matter:
|
| 22 |
-
|
| 23 |
-
- **Model size** vs accuracy vs GPU cost. Smaller = cheaper per doc.
|
| 24 |
-
- **Backend**: vLLM scripts are usually fastest at scale. `transformers` and
|
| 25 |
-
`falcon-perception` are alternatives for specific models.
|
| 26 |
-
- **Task support**: most scripts do plain text; some expose `--task-mode`
|
| 27 |
-
(table, formula, layout, etc.) — check the script's own docstring.
|
| 28 |
-
|
| 29 |
-
For the authoritative benchmark numbers on any model in the table, query the model
|
| 30 |
-
card programmatically — every OCR model publishes eval results on its card:
|
| 31 |
-
|
| 32 |
-
from huggingface_hub import HfApi
|
| 33 |
-
info = HfApi().model_info("tiiuae/Falcon-OCR", expand=["evalResults"])
|
| 34 |
-
for r in info.eval_results:
|
| 35 |
-
print(r.dataset_id, r.value)
|
| 36 |
-
|
| 37 |
-
See the [leaderboard data guide](https://huggingface.co/docs/hub/en/leaderboard-data-guide)
|
| 38 |
-
for the full API. This is more reliable than any markdown table that might drift.
|
| 39 |
-
|
| 40 |
-
## Getting help from a specific script
|
| 41 |
-
|
| 42 |
-
Each script has a docstring at the top with a description and usage examples. To read it
|
| 43 |
-
without downloading:
|
| 44 |
-
|
| 45 |
-
curl -s https://huggingface.co/datasets/uv-scripts/ocr/raw/main/<script>.py | head -100
|
| 46 |
-
|
| 47 |
-
Or open the URL in a browser. Running `uv run <url> --help` locally may fail if the
|
| 48 |
-
script has GPU-only dependencies — reading the docstring is more reliable.
|
| 49 |
-
|
| 50 |
-
## The main pattern: dataset → dataset
|
| 51 |
-
|
| 52 |
-
Most scripts take an input HF dataset ID and push results to an output HF dataset ID:
|
| 53 |
-
|
| 54 |
-
hf jobs uv run --flavor l4x1 -s HF_TOKEN \
|
| 55 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/<script>.py \
|
| 56 |
-
<input-dataset-id> <output-dataset-id> [--max-samples N] [--shuffle]
|
| 57 |
-
|
| 58 |
-
The script adds a `markdown` column to the input dataset and pushes the merged result
|
| 59 |
-
to the output dataset ID on the Hub.
|
| 60 |
-
|
| 61 |
-
## Alternative: directory → directory (bucket variants)
|
| 62 |
-
|
| 63 |
-
A couple of scripts have `-bucket.py` variants (currently `falcon-ocr-bucket.py` and
|
| 64 |
-
`glm-ocr-bucket.py`) that read from a mounted directory and write one `.md` per image
|
| 65 |
-
(or per PDF page). Useful with HF Buckets via `-v`:
|
| 66 |
-
|
| 67 |
-
hf jobs uv run --flavor l4x1 -s HF_TOKEN \
|
| 68 |
-
-v hf://buckets/<user>/<input>:/input:ro \
|
| 69 |
-
-v hf://buckets/<user>/<output>:/output \
|
| 70 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/<script>-bucket.py \
|
| 71 |
-
/input /output
|
| 72 |
-
|
| 73 |
-
`ls` the repo to check whether a `-bucket.py` variant exists for the model you want
|
| 74 |
-
before assuming it's available.
|
| 75 |
-
|
| 76 |
-
## Common flags across dataset-mode scripts
|
| 77 |
-
|
| 78 |
-
Most scripts support: `--max-samples`, `--shuffle`, `--seed`, `--split`, `--image-column`,
|
| 79 |
-
`--output-column`, `--private`, `--config`, `--create-pr`, `--verbose`. Read the script's
|
| 80 |
-
docstring for the authoritative list — individual scripts may add model-specific options
|
| 81 |
-
like `--task-mode`.
|
| 82 |
-
|
| 83 |
-
## Gotchas
|
| 84 |
-
|
| 85 |
-
- **Secrets**: pass `-s HF_TOKEN` to forward the user's token into the job.
|
| 86 |
-
- **GPU required**: all scripts exit if CUDA isn't available. `l4x1` is the cheapest
|
| 87 |
-
GPU flavor and works for models up to ~3B. Check `hf jobs hardware` for current options.
|
| 88 |
-
- **First run is slow**: model download + `torch.compile` / vLLM warmup dominates small
|
| 89 |
-
runs. Cost per doc drops sharply past a few hundred images — test with `--max-samples 10`
|
| 90 |
-
first, then scale.
|
| 91 |
-
- **Don't poll jobs**: jobs run async. Submit once, check status later with
|
| 92 |
-
`hf jobs ps` or `hf jobs logs <id>`.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
CLAUDE.md
CHANGED
|
@@ -3,17 +3,10 @@
|
|
| 3 |
## Active Scripts
|
| 4 |
|
| 5 |
### DeepSeek-OCR v1 (`deepseek-ocr-vllm.py`)
|
| 6 |
-
✅ **Production Ready**
|
| 7 |
-
-
|
| 8 |
-
-
|
| 9 |
-
-
|
| 10 |
-
- See: https://docs.vllm.ai/projects/recipes/en/latest/DeepSeek/DeepSeek-OCR.html
|
| 11 |
-
|
| 12 |
-
**Known issue (vLLM nightly, 2026-02-12):** Some images trigger a crop dimension validation error:
|
| 13 |
-
```
|
| 14 |
-
ValueError: images_crop dim[2] expected 1024, got 640. Expected shape: ('bnp', 3, 1024, 1024), but got torch.Size([0, 3, 640, 640])
|
| 15 |
-
```
|
| 16 |
-
This is a vLLM bug: the preprocessor defaults to gundam mode (image_size=640), but the tensor validator expects 1024x1024 even when the crop batch is empty (dim 0). Hit 2/10 on `davanstrien/ufo-ColPali`, 0/10 on NLS Medical History. Likely depends on image aspect ratios. No upstream issue filed yet. Related feature request: [vllm#28160](https://github.com/vllm-project/vllm/issues/28160) (no way to control resolution mode via mm-processor-kwargs).
|
| 17 |
|
| 18 |
### LightOnOCR-2-1B (`lighton-ocr2.py`)
|
| 19 |
✅ **Production Ready** (Fixed 2026-01-29)
|
|
@@ -82,117 +75,90 @@ hf jobs uv run --flavor l4x1 \
|
|
| 82 |
- Backend: Transformers (single image processing)
|
| 83 |
- Requires: `transformers>=5.0.0`
|
| 84 |
|
| 85 |
-
##
|
| 86 |
-
✅ **Production Ready** (Fixed 2026-03-14)
|
| 87 |
-
|
| 88 |
-
**Status:** Working with vLLM 0.17.1 stable
|
| 89 |
-
|
| 90 |
-
**Model availability:** The v1.5 model is NOT on HF from the original authors. We mirrored it from ModelScope to `davanstrien/dots.ocr-1.5`. Original: https://modelscope.cn/models/rednote-hilab/dots.ocr-1.5. License: MIT-based (with supplementary terms for responsible use).
|
| 91 |
-
|
| 92 |
-
**Key fix (2026-03-14):** Must pass `chat_template_content_format="string"` to `llm.chat()`. The model's `tokenizer_config.json` chat template expects string content (not openai-format lists). Without this, the model generates empty output (~1 token then EOS). The separate `chat_template.json` file handles multimodal content but vLLM uses the tokenizer_config template by default.
|
| 93 |
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
``
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
```
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
- 3/3 samples on L4: OCR mode working, ~147 toks/s output
|
| 123 |
-
- 3/3 samples on L4: layout-all mode working, structured JSON with bboxes
|
| 124 |
-
- 10/10 samples on A100: layout-only mode on NLS Highland News, ~670 toks/s output
|
| 125 |
-
- Output datasets: `davanstrien/dots-ocr-1.5-smoke-test-v3`, `davanstrien/dots-ocr-1.5-layout-test`, `davanstrien/dots-ocr-1.5-nls-layout-test`
|
| 126 |
-
|
| 127 |
-
**Prompt modes:**
|
| 128 |
-
- `ocr` — text extraction (default)
|
| 129 |
-
- `layout-all` — layout + bboxes + categories + text (JSON)
|
| 130 |
-
- `layout-only` — layout + bboxes + categories only (JSON)
|
| 131 |
-
- `web-parsing` — webpage layout analysis (JSON) [new in v1.5]
|
| 132 |
-
- `scene-spotting` — scene text detection [new in v1.5]
|
| 133 |
-
- `grounding-ocr` — text from bounding box region [new in v1.5]
|
| 134 |
-
- `general` — free-form (use with `--custom-prompt`) [new in v1.5]
|
| 135 |
-
|
| 136 |
-
**Example usage:**
|
| 137 |
-
```bash
|
| 138 |
-
hf jobs uv run --flavor l4x1 \
|
| 139 |
-
-s HF_TOKEN \
|
| 140 |
-
/path/to/dots-ocr-1.5.py \
|
| 141 |
-
davanstrien/ufo-ColPali output-dataset \
|
| 142 |
-
--model davanstrien/dots.ocr-1.5 \
|
| 143 |
-
--max-samples 10 --shuffle --seed 42
|
| 144 |
```
|
| 145 |
|
| 146 |
-
**
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
- GitHub: https://github.com/rednote-hilab/dots.ocr
|
| 153 |
-
|
| 154 |
-
---
|
| 155 |
-
|
| 156 |
-
## Pending Development
|
| 157 |
-
|
| 158 |
-
### DeepSeek-OCR-2 (`deepseek-ocr2-vllm.py`)
|
| 159 |
-
✅ **Production Ready** (2026-02-12)
|
| 160 |
-
|
| 161 |
-
**Status:** Working with vLLM nightly (requires nightly for `DeepseekOCR2ForCausalLM` support, not yet in stable 0.15.1)
|
| 162 |
-
|
| 163 |
-
**What was done:**
|
| 164 |
-
- Rewrote the broken draft script (which used base64/llm.chat/resolution modes)
|
| 165 |
-
- Uses the same proven pattern as v1: `llm.generate()` with PIL images + `NGramPerReqLogitsProcessor`
|
| 166 |
-
- Key v2 addition: `limit_mm_per_prompt={"image": 1}` in LLM init
|
| 167 |
-
- Added `addict` and `matplotlib` as dependencies (required by model's HF custom code)
|
| 168 |
-
|
| 169 |
-
**Test results (2026-02-12):**
|
| 170 |
-
- 10/10 samples processed successfully on L4 GPU
|
| 171 |
-
- Processing time: 6.4 min (includes model download + warmup)
|
| 172 |
-
- Model: 6.33 GiB, ~475 toks/s input, ~246 toks/s output
|
| 173 |
-
- Output dataset: `davanstrien/deepseek-ocr2-nls-test`
|
| 174 |
-
|
| 175 |
-
**Example usage:**
|
| 176 |
-
```bash
|
| 177 |
-
hf jobs uv run --flavor l4x1 \
|
| 178 |
-
-s HF_TOKEN \
|
| 179 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr2-vllm.py \
|
| 180 |
-
NationalLibraryOfScotland/medical-history-of-british-india output-dataset \
|
| 181 |
-
--max-samples 10 --shuffle --seed 42
|
| 182 |
-
```
|
| 183 |
|
| 184 |
-
**
|
| 185 |
-
-
|
| 186 |
-
-
|
| 187 |
-
- Uses same API pattern as v1: `NGramPerReqLogitsProcessor`, `SamplingParams(temperature=0, skip_special_tokens=False)`, `extra_args` for ngram settings
|
| 188 |
|
| 189 |
**Model Information:**
|
| 190 |
- Model ID: `deepseek-ai/DeepSeek-OCR-2`
|
| 191 |
- Model Card: https://huggingface.co/deepseek-ai/DeepSeek-OCR-2
|
| 192 |
- GitHub: https://github.com/deepseek-ai/DeepSeek-OCR-2
|
| 193 |
- Parameters: 3B
|
| 194 |
-
-
|
| 195 |
-
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
## Other OCR Scripts
|
| 198 |
|
|
@@ -242,314 +208,6 @@ uv run glm-ocr.py uv-scripts/ocr-smoke-test smoke-out --max-samples 5
|
|
| 242 |
|
| 243 |
---
|
| 244 |
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
**Status:** Working end-to-end (2026-02-14)
|
| 248 |
-
|
| 249 |
-
Launches N OCR models on the same dataset via `run_uv_job()`, each pushing to a shared repo as a separate config via `--config/--create-pr`. Eval done separately with `ocr-elo-bench.py`.
|
| 250 |
-
|
| 251 |
-
### Model Registry (4 models)
|
| 252 |
-
|
| 253 |
-
| Slug | Model ID | Size | Default GPU | Notes |
|
| 254 |
-
|------|----------|------|-------------|-------|
|
| 255 |
-
| `glm-ocr` | `zai-org/GLM-OCR` | 0.9B | l4x1 | |
|
| 256 |
-
| `deepseek-ocr` | `deepseek-ai/DeepSeek-OCR` | 4B | l4x1 | Auto-passes `--prompt-mode free` (no grounding tags) |
|
| 257 |
-
| `lighton-ocr-2` | `lightonai/LightOnOCR-2-1B` | 1B | a100-large | |
|
| 258 |
-
| `dots-ocr` | `rednote-hilab/dots.ocr` | 1.7B | l4x1 | Stable vLLM (>=0.9.1) |
|
| 259 |
-
|
| 260 |
-
Each model entry has a `default_args` list for model-specific flags (e.g., DeepSeek uses `["--prompt-mode", "free"]`).
|
| 261 |
-
|
| 262 |
-
### Workflow
|
| 263 |
-
```bash
|
| 264 |
-
# Launch all 4 models on same data
|
| 265 |
-
uv run ocr-bench-run.py source-dataset --output my-bench --max-samples 50
|
| 266 |
-
|
| 267 |
-
# Evaluate directly from PRs (no merge needed)
|
| 268 |
-
uv run ocr-elo-bench.py my-bench --from-prs --mode both
|
| 269 |
-
|
| 270 |
-
# Or merge + evaluate
|
| 271 |
-
uv run ocr-elo-bench.py my-bench --from-prs --merge-prs --mode both
|
| 272 |
-
|
| 273 |
-
# Other useful flags
|
| 274 |
-
uv run ocr-bench-run.py --list-models # Show registry table
|
| 275 |
-
uv run ocr-bench-run.py ... --dry-run # Preview without launching
|
| 276 |
-
uv run ocr-bench-run.py ... --wait # Poll until complete
|
| 277 |
-
uv run ocr-bench-run.py ... --models glm-ocr dots-ocr # Subset of models
|
| 278 |
-
```
|
| 279 |
-
|
| 280 |
-
### Eval script features (`ocr-elo-bench.py`)
|
| 281 |
-
- `--from-prs`: Auto-discovers open PRs on the dataset repo, extracts config names from PR title `[config-name]` suffix, loads data from `refs/pr/N` without merging
|
| 282 |
-
- `--merge-prs`: Auto-merges discovered PRs via `api.merge_pull_request()` before loading
|
| 283 |
-
- `--configs`: Manually specify which configs to load (for merged repos)
|
| 284 |
-
- `--mode both`: Runs pairwise ELO + pointwise scoring
|
| 285 |
-
- Flat mode (original behavior) still works when `--configs`/`--from-prs` not used
|
| 286 |
-
|
| 287 |
-
### Scripts pushed to Hub
|
| 288 |
-
All 4 scripts have been pushed to `uv-scripts/ocr` on the Hub with `--config`/`--create-pr` support:
|
| 289 |
-
- `glm-ocr.py` ✅
|
| 290 |
-
- `deepseek-ocr-vllm.py` ✅
|
| 291 |
-
- `lighton-ocr2.py` ✅
|
| 292 |
-
- `dots-ocr.py` ✅
|
| 293 |
-
|
| 294 |
-
### Benchmark Results
|
| 295 |
-
|
| 296 |
-
#### Run 1: NLS Medical History (2026-02-14) — Pilot
|
| 297 |
-
|
| 298 |
-
**Dataset:** `NationalLibraryOfScotland/medical-history-of-british-india` (10 samples, shuffled, seed 42)
|
| 299 |
-
**Output repo:** `davanstrien/ocr-bench-test` (4 open PRs)
|
| 300 |
-
**Judge:** `Qwen/Qwen2.5-VL-72B-Instruct` via HF Inference Providers
|
| 301 |
-
**Content:** Historical English, degraded scans of medical texts
|
| 302 |
-
|
| 303 |
-
**ELO (pairwise, 5 samples evaluated):**
|
| 304 |
-
1. DoTS.ocr — 1540 (67% win rate)
|
| 305 |
-
2. DeepSeek-OCR — 1539 (57%)
|
| 306 |
-
3. LightOnOCR-2 — 1486 (50%)
|
| 307 |
-
4. GLM-OCR — 1436 (29%)
|
| 308 |
-
|
| 309 |
-
**Pointwise (5 samples):**
|
| 310 |
-
1. DeepSeek-OCR — 5.0/5.0
|
| 311 |
-
2. GLM-OCR — 4.6
|
| 312 |
-
3. LightOnOCR-2 — 4.4
|
| 313 |
-
4. DoTS.ocr — 4.2
|
| 314 |
-
|
| 315 |
-
**Key finding:** DeepSeek-OCR's `--prompt-mode document` produces grounding tags (`<|ref|>`, `<|det|>`) that the judge penalizes heavily. Switching to `--prompt-mode free` (now the default in the registry) made it jump from last place to top 2.
|
| 316 |
-
|
| 317 |
-
**Caveat:** 5 samples is far too few for stable rankings. The judge VLM is called once per comparison (pairwise) or once per model-sample (pointwise) via HF Inference Providers API.
|
| 318 |
-
|
| 319 |
-
#### Run 2: Rubenstein Manuscript Catalog (2026-02-15) — First Full Benchmark
|
| 320 |
-
|
| 321 |
-
**Dataset:** `biglam/rubenstein-manuscript-catalog` (50 samples, shuffled, seed 42)
|
| 322 |
-
**Output repo:** `davanstrien/ocr-bench-rubenstein` (4 PRs)
|
| 323 |
-
**Judge:** Jury of 2 via `ocr-vllm-judge.py` — `Qwen/Qwen2.5-VL-7B-Instruct` + `Qwen/Qwen3-VL-8B-Instruct` on A100
|
| 324 |
-
**Content:** ~48K typewritten + handwritten manuscript catalog cards from Duke University (CC0)
|
| 325 |
-
|
| 326 |
-
**ELO (pairwise, 50 samples, 300 comparisons, 0 parse failures):**
|
| 327 |
-
|
| 328 |
-
| Rank | Model | ELO | W | L | T | Win% |
|
| 329 |
-
|------|-------|-----|---|---|---|------|
|
| 330 |
-
| 1 | LightOnOCR-2-1B | 1595 | 100 | 50 | 0 | 67% |
|
| 331 |
-
| 2 | DeepSeek-OCR | 1497 | 73 | 77 | 0 | 49% |
|
| 332 |
-
| 3 | GLM-OCR | 1471 | 57 | 93 | 0 | 38% |
|
| 333 |
-
| 4 | dots.ocr | 1437 | 70 | 80 | 0 | 47% |
|
| 334 |
-
|
| 335 |
-
**OCR job times** (all 50 samples each):
|
| 336 |
-
- dots-ocr: 5.3 min (L4)
|
| 337 |
-
- deepseek-ocr: 5.6 min (L4)
|
| 338 |
-
- glm-ocr: 5.7 min (L4)
|
| 339 |
-
- lighton-ocr-2: 6.4 min (A100)
|
| 340 |
-
|
| 341 |
-
**Key findings:**
|
| 342 |
-
- **LightOnOCR-2-1B dominates** on manuscript catalog cards (67% win rate, 100-point ELO gap over 2nd place) — a very different result from the NLS pilot where it placed 3rd
|
| 343 |
-
- **Rankings are dataset-dependent**: NLS historical medical texts favored DoTS.ocr and DeepSeek-OCR; Rubenstein typewritten/handwritten cards favor LightOnOCR-2
|
| 344 |
-
- **Jury of small models works well**: 0 parse failures on 300 comparisons thanks to vLLM structured output (xgrammar). Majority voting between 2 judges provides robustness
|
| 345 |
-
- **50 samples gives meaningful separation**: Clear ELO gaps (1595 → 1497 → 1471 → 1437) unlike the noisy 5-sample pilot
|
| 346 |
-
- This validates the multi-dataset benchmark approach — no single dataset tells the whole story
|
| 347 |
-
|
| 348 |
-
#### Run 3: UFO-ColPali (2026-02-15) — Cross-Dataset Validation
|
| 349 |
-
|
| 350 |
-
**Dataset:** `davanstrien/ufo-ColPali` (50 samples, shuffled, seed 42)
|
| 351 |
-
**Output repo:** `davanstrien/ocr-bench-ufo` (4 PRs)
|
| 352 |
-
**Judge:** `Qwen/Qwen3-VL-30B-A3B-Instruct` via `ocr-vllm-judge.py` on A100 (updated prompt)
|
| 353 |
-
**Content:** Mixed modern documents (invoices, reports, forms, etc.)
|
| 354 |
-
|
| 355 |
-
**ELO (pairwise, 50 samples, 294 comparisons):**
|
| 356 |
-
|
| 357 |
-
| Rank | Model | ELO | W | L | T | Win% |
|
| 358 |
-
|------|-------|-----|---|---|---|------|
|
| 359 |
-
| 1 | DeepSeek-OCR | 1827 | 130 | 17 | 0 | 88% |
|
| 360 |
-
| 2 | dots.ocr | 1510 | 64 | 83 | 0 | 44% |
|
| 361 |
-
| 3 | LightOnOCR-2-1B | 1368 | 77 | 70 | 0 | 52% |
|
| 362 |
-
| 4 | GLM-OCR | 1294 | 23 | 124 | 0 | 16% |
|
| 363 |
-
|
| 364 |
-
**Human validation (30 comparisons):** DeepSeek-OCR #1 (same as judge), LightOnOCR-2 #3 (same). Middle pack (GLM-OCR #2 human / #4 judge, dots.ocr #4 human / #2 judge) shuffled.
|
| 365 |
-
|
| 366 |
-
#### Cross-Dataset Comparison (Human-Validated)
|
| 367 |
-
|
| 368 |
-
| Model | Rubenstein Human | Rubenstein Kimi | UFO Human | UFO 30B |
|
| 369 |
-
|-------|:---------------:|:---------------:|:---------:|:-------:|
|
| 370 |
-
| DeepSeek-OCR | **#1** | **#1** | **#1** | **#1** |
|
| 371 |
-
| GLM-OCR | #2 | #3 | #2 | #4 |
|
| 372 |
-
| LightOnOCR-2 | #4 | #2 | #3 | #3 |
|
| 373 |
-
| dots.ocr | #3 | #4 | #4 | #2 |
|
| 374 |
-
|
| 375 |
-
**Conclusion:** DeepSeek-OCR is consistently #1 across datasets and evaluation methods. Middle-pack rankings are dataset-dependent. Updated prompt fixed the LightOnOCR-2 overrating seen with old prompt/small judges.
|
| 376 |
-
|
| 377 |
-
*Note: NLS pilot results (5 samples, 72B API judge) omitted — not comparable with newer methodology.*
|
| 378 |
-
|
| 379 |
-
### Known Issues / Next Steps
|
| 380 |
-
|
| 381 |
-
1. ✅ **More samples needed** — Done. Rubenstein run (2026-02-15) used 50 samples and produced clear ELO separation across all 4 models.
|
| 382 |
-
2. ✅ **Smaller judge model** — Tested with Qwen VL 7B + Qwen3 VL 8B via `ocr-vllm-judge.py`. Works well with structured output (0 parse failures). Jury of small models compensates for individual model weakness. See "Offline vLLM Judge" section below.
|
| 383 |
-
3. **Auto-merge in coordinator** — `--wait` could auto-merge PRs after successful jobs. Not yet implemented.
|
| 384 |
-
4. **Adding more models** — `rolm-ocr.py` exists but needs `--config`/`--create-pr` added. `deepseek-ocr2-vllm.py`, `paddleocr-vl-1.5.py`, etc. could also be added to the registry.
|
| 385 |
-
5. **Leaderboard Space** — See future section below.
|
| 386 |
-
6. ✅ **Result persistence** — `ocr-vllm-judge.py` now has `--save-results REPO_ID` flag. First dataset: `davanstrien/ocr-bench-rubenstein-judge`.
|
| 387 |
-
7. **More diverse datasets** — Rankings are dataset-dependent (LightOnOCR-2 wins on Rubenstein, DoTS.ocr won pilot on NLS). Need benchmarks on tables, formulas, multilingual, and modern documents for a complete picture.
|
| 388 |
-
8. ✅ **Human validation** — `ocr-human-eval.py` completed on Rubenstein (30/30). Tested 3 judge configs. **Kimi K2.5 (170B) via Novita + updated prompt = best human agreement** (only judge to match human's #1). Now default in `ocr-jury-bench.py`. See `OCR-BENCHMARK.md` for full comparison.
|
| 389 |
-
|
| 390 |
-
---
|
| 391 |
-
|
| 392 |
-
## Offline vLLM Judge (`ocr-vllm-judge.py`)
|
| 393 |
-
|
| 394 |
-
**Status:** Working end-to-end (2026-02-15)
|
| 395 |
-
|
| 396 |
-
Runs pairwise OCR quality comparisons using a local VLM judge via vLLM's offline `LLM()` pattern. Supports jury mode (multiple models vote sequentially on the same GPU) with majority voting.
|
| 397 |
-
|
| 398 |
-
### Why use this over the API judge (`ocr-jury-bench.py`)?
|
| 399 |
-
|
| 400 |
-
| | API judge (`ocr-jury-bench.py`) | Offline judge (`ocr-vllm-judge.py`) |
|
| 401 |
-
|---|---|---|
|
| 402 |
-
| Parse failures | Needs retries for malformed JSON | 0 failures — vLLM structured output guarantees valid JSON |
|
| 403 |
-
| Network | Rate limits, timeouts, transient errors | Zero network calls |
|
| 404 |
-
| Cost | Per-token API pricing | Just GPU time |
|
| 405 |
-
| Judge models | Limited to Inference Providers catalog | Any vLLM-supported VLM |
|
| 406 |
-
| Jury mode | Sequential API calls per judge | Sequential model loading, batch inference per judge |
|
| 407 |
-
| Best for | Quick spot-checks, access to 72B models | Batch evaluation (50+ samples), reproducibility |
|
| 408 |
-
|
| 409 |
-
**Pushed to Hub:** `uv-scripts/ocr` as `ocr-vllm-judge.py` (2026-02-15)
|
| 410 |
-
|
| 411 |
-
### Test Results (2026-02-15)
|
| 412 |
-
|
| 413 |
-
**Test 1 — Single judge, 1 sample, L4:**
|
| 414 |
-
- Qwen2.5-VL-7B-Instruct, 6/6 comparisons, 0 parse failures
|
| 415 |
-
- Total time: ~3 min (including model download + warmup)
|
| 416 |
-
|
| 417 |
-
**Test 2 — Jury of 2, 3 samples, A100:**
|
| 418 |
-
- Qwen2.5-VL-7B + Qwen3-VL-8B, 15/15 comparisons, 0 parse failures
|
| 419 |
-
- GPU cleanup between models: successful (nanobind warnings are cosmetic)
|
| 420 |
-
- Majority vote aggregation working (`[2/2]` unanimous, `[1/2]` split)
|
| 421 |
-
- Total time: ~4 min (including both model downloads)
|
| 422 |
-
|
| 423 |
-
**Test 3 — Full benchmark, 50 samples, A100 (Rubenstein Manuscript Catalog):**
|
| 424 |
-
- Qwen2.5-VL-7B + Qwen3-VL-8B jury, 300/300 comparisons, 0 parse failures
|
| 425 |
-
- Input: `davanstrien/ocr-bench-rubenstein` (4 PRs from `ocr-bench-run.py`)
|
| 426 |
-
- Produced clear ELO rankings with meaningful separation
|
| 427 |
-
- See "Benchmark Results → Run 2" in the OCR Benchmark Coordinator section above
|
| 428 |
-
|
| 429 |
-
### Usage
|
| 430 |
-
|
| 431 |
-
```bash
|
| 432 |
-
# Single judge on L4
|
| 433 |
-
hf jobs uv run --flavor l4x1 -s HF_TOKEN \
|
| 434 |
-
ocr-vllm-judge.py davanstrien/ocr-bench-nls-50 --from-prs \
|
| 435 |
-
--judge-model Qwen/Qwen2.5-VL-7B-Instruct --max-samples 10
|
| 436 |
-
|
| 437 |
-
# Jury of 2 on A100 (recommended for jury mode)
|
| 438 |
-
hf jobs uv run --flavor a100-large -s HF_TOKEN \
|
| 439 |
-
ocr-vllm-judge.py davanstrien/ocr-bench-nls-50 --from-prs \
|
| 440 |
-
--judge-model Qwen/Qwen2.5-VL-7B-Instruct \
|
| 441 |
-
--judge-model Qwen/Qwen3-VL-8B-Instruct \
|
| 442 |
-
--max-samples 50
|
| 443 |
-
```
|
| 444 |
-
|
| 445 |
-
### Implementation Notes
|
| 446 |
-
- Comparisons built upfront on CPU as `NamedTuple`s, then batched to vLLM in single `llm.chat()` call
|
| 447 |
-
- Structured output via compatibility shim: `StructuredOutputsParams` (vLLM >= 0.12) → `GuidedDecodingParams` (older) → prompt-based fallback
|
| 448 |
-
- GPU cleanup between jury models: `destroy_model_parallel()` + `gc.collect()` + `torch.cuda.empty_cache()`
|
| 449 |
-
- Position bias mitigation: A/B order randomized per comparison
|
| 450 |
-
- A100 recommended for jury mode; L4 works for single 7B judge
|
| 451 |
-
|
| 452 |
-
### Next Steps
|
| 453 |
-
1. ✅ **Scale test** — Completed on Rubenstein Manuscript Catalog (50 samples, 300 comparisons, 0 parse failures). Rankings differ from API-based pilot (different dataset + judge), validating multi-dataset approach.
|
| 454 |
-
2. ✅ **Result persistence** — Added `--save-results REPO_ID` flag. Pushes 3 configs to HF Hub: `comparisons` (one row per pairwise comparison), `leaderboard` (ELO + win/loss/tie per model), `metadata` (source dataset, judge models, seed, timestamp). First dataset: `davanstrien/ocr-bench-rubenstein-judge`.
|
| 455 |
-
3. **Integrate into `ocr-bench-run.py`** — Add `--eval` flag that auto-runs vLLM judge after OCR jobs complete
|
| 456 |
-
|
| 457 |
-
---
|
| 458 |
-
|
| 459 |
-
## Blind Human Eval (`ocr-human-eval.py`)
|
| 460 |
-
|
| 461 |
-
**Status:** Working (2026-02-15)
|
| 462 |
-
|
| 463 |
-
Gradio app for blind A/B comparison of OCR outputs. Shows document image + two anonymized OCR outputs, human picks winner or tie. Computes ELO rankings from human annotations and optionally compares against automated judge results.
|
| 464 |
-
|
| 465 |
-
### Usage
|
| 466 |
-
|
| 467 |
-
```bash
|
| 468 |
-
# Basic — blind human eval only
|
| 469 |
-
uv run ocr-human-eval.py davanstrien/ocr-bench-rubenstein --from-prs --max-samples 5
|
| 470 |
-
|
| 471 |
-
# With judge comparison — loads automated judge results for agreement analysis
|
| 472 |
-
uv run ocr-human-eval.py davanstrien/ocr-bench-rubenstein --from-prs \
|
| 473 |
-
--judge-results davanstrien/ocr-bench-rubenstein-judge --max-samples 5
|
| 474 |
-
```
|
| 475 |
-
|
| 476 |
-
### Features
|
| 477 |
-
- **Blind evaluation**: Two-tab design — Evaluate tab never shows model names, Results tab reveals rankings
|
| 478 |
-
- **Position bias mitigation**: A/B order randomly swapped per comparison
|
| 479 |
-
- **Resume support**: JSON annotations saved atomically after each vote; restart app to resume where you left off
|
| 480 |
-
- **Live agreement tracking**: Per-vote feedback shows running agreement with automated judge (when `--judge-results` provided)
|
| 481 |
-
- **Split-jury prioritization**: Comparisons where automated judges disagreed ("1/2" agreement) shown first — highest annotation value per vote
|
| 482 |
-
- **Image variety**: Round-robin interleaving by sample so you don't see the same document image repeatedly
|
| 483 |
-
- **Soft/hard disagreement analysis**: Distinguishes between harmless ties-vs-winner disagreements and genuine opposite-winner errors
|
| 484 |
-
|
| 485 |
-
### First Validation Results (Rubenstein, 30 annotations)
|
| 486 |
-
|
| 487 |
-
Tested 3 judge configs against 30 human annotations. **Kimi K2.5 (170B) via Novita** is the only judge to match human's #1 pick (DeepSeek-OCR). Small models (7B/8B/30B) all overrate LightOnOCR-2 due to bias toward its commentary style. Updated prompt (prioritized faithfulness > completeness > accuracy) helps but model size is the bigger factor.
|
| 488 |
-
|
| 489 |
-
Full results and analysis in `OCR-BENCHMARK.md` → "Human Validation" section.
|
| 490 |
-
|
| 491 |
-
### Next Steps
|
| 492 |
-
1. **Second dataset** — Run on NLS Medical History for cross-dataset human validation
|
| 493 |
-
2. **Multiple annotators** — Currently single-user; could support annotator ID for inter-annotator agreement
|
| 494 |
-
3. **Remaining LightOnOCR-2 gap** — Still #2 (Kimi) vs #4 (human). May need to investigate on more samples or strip commentary in preprocessing
|
| 495 |
-
|
| 496 |
-
---
|
| 497 |
-
|
| 498 |
-
## Future: Leaderboard HF Space
|
| 499 |
-
|
| 500 |
-
**Status:** Idea (noted 2026-02-14)
|
| 501 |
-
|
| 502 |
-
Build a Hugging Face Space with a persistent leaderboard that gets updated after each benchmark run. This would give a public-facing view of OCR model quality.
|
| 503 |
-
|
| 504 |
-
**Design ideas:**
|
| 505 |
-
- Gradio or static Space displaying ELO ratings + pointwise scores
|
| 506 |
-
- `ocr-elo-bench.py` could push results to a dataset that the Space reads
|
| 507 |
-
- Or the Space itself could run evaluation on demand
|
| 508 |
-
- Show per-document comparisons (image + side-by-side OCR outputs)
|
| 509 |
-
- Historical tracking — how scores change across model versions
|
| 510 |
-
- Filter by document type (historical, modern, tables, formulas, multilingual)
|
| 511 |
-
|
| 512 |
-
**Open questions:**
|
| 513 |
-
- Should the eval script push structured results to a dataset (e.g., `uv-scripts/ocr-leaderboard-data`)?
|
| 514 |
-
- Static leaderboard (updated by CI/scheduled job) vs interactive (evaluate on demand)?
|
| 515 |
-
- Include sample outputs for qualitative comparison?
|
| 516 |
-
- How to handle different eval datasets (NLS medical history vs UFO vs others)?
|
| 517 |
-
|
| 518 |
-
---
|
| 519 |
-
|
| 520 |
-
## Incremental Uploads / Checkpoint Strategy — ON HOLD
|
| 521 |
-
|
| 522 |
-
**Status:** Waiting on HF Hub Buckets (noted 2026-02-20)
|
| 523 |
-
|
| 524 |
-
**Current state:**
|
| 525 |
-
- `glm-ocr.py` (v1): Simple batch-then-push. Works fine for most jobs.
|
| 526 |
-
- `glm-ocr-v2.py`: Adds CommitScheduler-based incremental uploads + checkpoint/resume. ~400 extra lines. Works but has tradeoffs (commit noise, `--create-pr` incompatible, complex resume metadata).
|
| 527 |
-
|
| 528 |
-
**Decision: Do NOT port v2 pattern to other scripts.** Wait for HF Hub Buckets instead.
|
| 529 |
-
|
| 530 |
-
**Why:** Two open PRs will likely make the v2 CommitScheduler approach obsolete:
|
| 531 |
-
- [huggingface_hub#3673](https://github.com/huggingface/huggingface_hub/pull/3673) — Buckets API: S3-like mutable object storage on HF, no git versioning overhead
|
| 532 |
-
- [huggingface_hub#3807](https://github.com/huggingface/huggingface_hub/pull/3807) — HfFileSystem support for buckets: fsspec-compatible, so pyarrow/pandas/datasets can read/write `hf://buckets/` paths directly
|
| 533 |
-
|
| 534 |
-
**What Buckets would replace:** Once landed, incremental saves become one line per batch:
|
| 535 |
-
```python
|
| 536 |
-
batch_ds.to_parquet(f"hf://buckets/{user}/ocr-scratch/shard-{batch_num:05d}.parquet")
|
| 537 |
-
```
|
| 538 |
-
No CommitScheduler, no CleanupScheduler, no resume metadata, no completed batch scanning. Just write to the bucket path via fsspec. Final step: read back from bucket, `push_to_hub` to a clean dataset repo (compatible with `--create-pr`).
|
| 539 |
-
|
| 540 |
-
**Action items when Buckets ships:**
|
| 541 |
-
1. Test `hf://buckets/` fsspec writes on one script (glm-ocr is the guinea pig)
|
| 542 |
-
2. Verify: write performance, atomicity (partial writes visible?), auth propagation in HF Jobs
|
| 543 |
-
3. If it works, adopt as the standard pattern for all scripts — simple enough to inline (~20 lines)
|
| 544 |
-
4. Retire `glm-ocr-v2.py` CommitScheduler approach
|
| 545 |
-
|
| 546 |
-
**Until then:** v1 scripts stay as-is. `glm-ocr-v2.py` exists if someone needs resume on a very large job today.
|
| 547 |
-
|
| 548 |
-
---
|
| 549 |
-
|
| 550 |
-
**Last Updated:** 2026-02-20
|
| 551 |
**Watch PRs:**
|
| 552 |
-
-
|
| 553 |
-
- **HfFileSystem Buckets** ([#3807](https://github.com/huggingface/huggingface_hub/pull/3807)): fsspec support for `hf://buckets/` paths. Key for zero-boilerplate writes from scripts.
|
| 554 |
-
- DeepSeek-OCR-2 stable vLLM release: Currently only in nightly. Watch for vLLM 0.16.0 stable release on PyPI to remove nightly dependency.
|
| 555 |
-
- nanobind leak warnings in vLLM structured output (xgrammar): Cosmetic only, does not affect results. May be fixed in future xgrammar release.
|
|
|
|
| 3 |
## Active Scripts
|
| 4 |
|
| 5 |
### DeepSeek-OCR v1 (`deepseek-ocr-vllm.py`)
|
| 6 |
+
✅ **Production Ready**
|
| 7 |
+
- Fully supported by vLLM
|
| 8 |
+
- Fast batch processing
|
| 9 |
+
- Tested and working on HF Jobs
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
### LightOnOCR-2-1B (`lighton-ocr2.py`)
|
| 12 |
✅ **Production Ready** (Fixed 2026-01-29)
|
|
|
|
| 75 |
- Backend: Transformers (single image processing)
|
| 76 |
- Requires: `transformers>=5.0.0`
|
| 77 |
|
| 78 |
+
## Pending Development
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
+
### DeepSeek-OCR-2 (Visual Causal Flow Architecture)
|
| 81 |
+
|
| 82 |
+
**Status:** ⏳ Waiting for vLLM upstream support
|
| 83 |
+
|
| 84 |
+
**Context:**
|
| 85 |
+
DeepSeek-OCR-2 is the next generation OCR model (3B parameters) with Visual Causal Flow architecture offering improved quality. We attempted to create a UV script (`deepseek-ocr2-vllm.py`) but encountered a blocker.
|
| 86 |
+
|
| 87 |
+
**Blocker:**
|
| 88 |
+
vLLM does not yet support `DeepseekOCR2ForCausalLM` architecture in the official release.
|
| 89 |
+
|
| 90 |
+
**PR to Watch:**
|
| 91 |
+
🔗 https://github.com/vllm-project/vllm/pull/33165
|
| 92 |
+
|
| 93 |
+
This PR adds DeepSeek-OCR-2 support but is currently:
|
| 94 |
+
- ⚠️ **Open** (not merged)
|
| 95 |
+
- Has unresolved review comments
|
| 96 |
+
- Pre-commit checks failing
|
| 97 |
+
- Issues: hardcoded parameters, device mismatch bugs, missing error handling
|
| 98 |
+
|
| 99 |
+
**What's Needed:**
|
| 100 |
+
1. PR #33165 needs to be reviewed, fixed, and merged
|
| 101 |
+
2. vLLM needs to release a version including the merge
|
| 102 |
+
3. Then we can add these dependencies to our script:
|
| 103 |
+
```python
|
| 104 |
+
# dependencies = [
|
| 105 |
+
# "datasets>=4.0.0",
|
| 106 |
+
# "huggingface-hub",
|
| 107 |
+
# "pillow",
|
| 108 |
+
# "vllm",
|
| 109 |
+
# "tqdm",
|
| 110 |
+
# "toolz",
|
| 111 |
+
# "torch",
|
| 112 |
+
# "addict",
|
| 113 |
+
# "matplotlib",
|
| 114 |
+
# ]
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
**Implementation Progress:**
|
| 118 |
+
- ✅ Created `deepseek-ocr2-vllm.py` script
|
| 119 |
+
- ✅ Fixed dependency issues (pyarrow, datasets>=4.0.0)
|
| 120 |
+
- ✅ Tested script structure on HF Jobs
|
| 121 |
+
- ❌ Blocked: vLLM doesn't recognize architecture
|
| 122 |
+
|
| 123 |
+
**Partial Implementation:**
|
| 124 |
+
The file `deepseek-ocr2-vllm.py` exists in this repo but is **not functional** until vLLM support lands. Consider it a draft.
|
| 125 |
+
|
| 126 |
+
**Testing Evidence:**
|
| 127 |
+
When we ran on HF Jobs, we got:
|
| 128 |
```
|
| 129 |
+
ValidationError: Model architectures ['DeepseekOCR2ForCausalLM'] are not supported for now.
|
| 130 |
+
Supported architectures: [...'DeepseekOCRForCausalLM'...]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
```
|
| 132 |
|
| 133 |
+
**Next Steps (when PR merges):**
|
| 134 |
+
1. Update `deepseek-ocr2-vllm.py` dependencies to include `addict` and `matplotlib`
|
| 135 |
+
2. Test on HF Jobs with small dataset (10 samples)
|
| 136 |
+
3. Verify output quality
|
| 137 |
+
4. Update README.md with DeepSeek-OCR-2 section
|
| 138 |
+
5. Document v1 vs v2 differences
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
+
**Alternative Approaches (if urgent):**
|
| 141 |
+
- Create transformers-based script (slower, no vLLM batching)
|
| 142 |
+
- Use DeepSeek's official repo setup (complex, not UV-script compatible)
|
|
|
|
| 143 |
|
| 144 |
**Model Information:**
|
| 145 |
- Model ID: `deepseek-ai/DeepSeek-OCR-2`
|
| 146 |
- Model Card: https://huggingface.co/deepseek-ai/DeepSeek-OCR-2
|
| 147 |
- GitHub: https://github.com/deepseek-ai/DeepSeek-OCR-2
|
| 148 |
- Parameters: 3B
|
| 149 |
+
- Resolution: (0-6)×768×768 + 1×1024×1024 patches
|
| 150 |
+
- Key improvement: Visual Causal Flow architecture
|
| 151 |
+
|
| 152 |
+
**Resolution Modes (for v2):**
|
| 153 |
+
```python
|
| 154 |
+
RESOLUTION_MODES = {
|
| 155 |
+
"tiny": {"base_size": 512, "image_size": 512, "crop_mode": False},
|
| 156 |
+
"small": {"base_size": 640, "image_size": 640, "crop_mode": False},
|
| 157 |
+
"base": {"base_size": 1024, "image_size": 768, "crop_mode": False}, # v2 optimized
|
| 158 |
+
"large": {"base_size": 1280, "image_size": 1024, "crop_mode": False},
|
| 159 |
+
"gundam": {"base_size": 1024, "image_size": 768, "crop_mode": True}, # v2 optimized
|
| 160 |
+
}
|
| 161 |
+
```
|
| 162 |
|
| 163 |
## Other OCR Scripts
|
| 164 |
|
|
|
|
| 208 |
|
| 209 |
---
|
| 210 |
|
| 211 |
+
**Last Updated:** 2026-02-12
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
**Watch PRs:**
|
| 213 |
+
- DeepSeek-OCR-2: https://github.com/vllm-project/vllm/pull/33165
|
|
|
|
|
|
|
|
|
README.md
CHANGED
|
@@ -1,17 +1,15 @@
|
|
| 1 |
---
|
| 2 |
viewer: false
|
| 3 |
-
tags: [uv-script, ocr,
|
| 4 |
---
|
| 5 |
|
| 6 |
# OCR UV Scripts
|
| 7 |
|
| 8 |
-
|
| 9 |
|
| 10 |
-
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
## Quick Start
|
| 15 |
|
| 16 |
Run OCR on any dataset without needing your own GPU:
|
| 17 |
|
|
@@ -24,220 +22,589 @@ hf jobs uv run --flavor l4x1 \
|
|
| 24 |
--max-samples 10
|
| 25 |
```
|
| 26 |
|
| 27 |
-
|
| 28 |
|
| 29 |
-
- Process
|
| 30 |
- Add OCR results as a new `markdown` column
|
| 31 |
- Push the results to a new dataset
|
| 32 |
- View results at: `https://huggingface.co/datasets/[your-output-dataset]`
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
**Start here:** for a quick first run, try **`lighton-ocr2.py`** (1B, very fast) or **`paddleocr-vl-1.6.py`** (0.9B, current OmniDocBench SOTA); for the smallest footprint, **`falcon-ocr.py`** (0.3B, strong on tables). Reach for a 7–8B model only when quality demands it. Several of these models sit on the public [olmOCR-Bench](https://huggingface.co/datasets/allenai/olmOCR-bench) — pull the live ranking from your terminal in one command:
|
| 37 |
-
|
| 38 |
-
```bash
|
| 39 |
-
hf datasets leaderboard allenai/olmOCR-bench
|
| 40 |
-
```
|
| 41 |
-
|
| 42 |
-
But which model wins on *your* documents is still document-dependent — so [ocr-bench](https://github.com/davanstrien/ocr-bench) builds a **per-collection leaderboard** for your own data (pairwise VLM-as-judge, optionally human-validated), using these scripts under the hood.
|
| 43 |
-
|
| 44 |
-
_Sorted by model size:_
|
| 45 |
|
| 46 |
| Script | Model | Size | Backend | Notes |
|
| 47 |
|--------|-------|------|---------|-------|
|
| 48 |
-
| `falcon-ocr.py` | [Falcon-OCR](https://huggingface.co/tiiuae/Falcon-OCR) | 0.3B | falcon-perception | Smallest in collection. #1 on multi-column docs and tables (olmOCR), Apache 2.0 |
|
| 49 |
| `smoldocling-ocr.py` | [SmolDocling](https://huggingface.co/ds4sd/SmolDocling-256M-preview) | 256M | Transformers | DocTags structured output |
|
| 50 |
| `glm-ocr.py` | [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) | 0.9B | vLLM | 94.62% OmniDocBench V1.5 |
|
| 51 |
| `paddleocr-vl.py` | [PaddleOCR-VL](https://huggingface.co/PaddlePaddle/PaddleOCR-VL) | 0.9B | Transformers | 4 task modes (ocr/table/formula/chart) |
|
| 52 |
| `paddleocr-vl-1.5.py` | [PaddleOCR-VL-1.5](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.5) | 0.9B | Transformers | 94.5% OmniDocBench, 6 task modes |
|
| 53 |
-
| `paddleocr-vl-1.6.py` | [PaddleOCR-VL-1.6](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.6) | 0.9B | vLLM | **96.33% OmniDocBench v1.6** (SOTA), drop-in upgrade of 1.5 |
|
| 54 |
| `lighton-ocr.py` | [LightOnOCR-1B](https://huggingface.co/lightonai/LightOnOCR-1B-1025) | 1B | vLLM | Fast, 3 vocab sizes |
|
| 55 |
| `lighton-ocr2.py` | [LightOnOCR-2-1B](https://huggingface.co/lightonai/LightOnOCR-2-1B) | 1B | vLLM | 7× faster than v1, RLVR trained |
|
| 56 |
| `hunyuan-ocr.py` | [HunyuanOCR](https://huggingface.co/tencent/HunyuanOCR) | 1B | vLLM | Lightweight VLM |
|
| 57 |
| `dots-ocr.py` | [DoTS.ocr](https://huggingface.co/Tencent/DoTS.ocr) | 1.7B | vLLM | 100+ languages |
|
| 58 |
| `firered-ocr.py` | [FireRed-OCR](https://huggingface.co/FireRedTeam/FireRed-OCR) | 2.1B | vLLM | Qwen3-VL fine-tune, Apache 2.0 |
|
| 59 |
-
| `abot-ocr.py` | [ABot-OCR](https://huggingface.co/acvlab/ABot-OCR) | 2B | vLLM | Qwen3-VL based, doc→Markdown (text/LaTeX/HTML tables). Needs `vllm/vllm-openai` image. [paper](https://arxiv.org/abs/2605.27978) |
|
| 60 |
| `nanonets-ocr.py` | [Nanonets-OCR-s](https://huggingface.co/nanonets/Nanonets-OCR-s) | 2B | vLLM | LaTeX, tables, forms |
|
| 61 |
-
| `dots-
|
| 62 |
| `nanonets-ocr2.py` | [Nanonets-OCR2-3B](https://huggingface.co/nanonets/Nanonets-OCR2-s) | 3B | vLLM | Next-gen, Qwen2.5-VL base |
|
| 63 |
| `deepseek-ocr-vllm.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | vLLM | 5 resolution + 5 prompt modes |
|
| 64 |
| `deepseek-ocr.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | Transformers | Same model, Transformers backend |
|
| 65 |
-
| `deepseek-ocr2-vllm.py` | [DeepSeek-OCR-2](https://huggingface.co/deepseek-ai/DeepSeek-OCR-2) | 3B | vLLM | Newer
|
| 66 |
-
| `nuextract3.py` | [NuExtract3](https://huggingface.co/numind/NuExtract3) | 4B | vLLM | Markdown OCR **+ schema-guided JSON extraction** (template/Pydantic). Needs `vllm/vllm-openai` image |
|
| 67 |
-
| `qianfan-ocr.py` | [Qianfan-OCR](https://huggingface.co/baidu/Qianfan-OCR) | 4.7B | vLLM | #1 OmniDocBench v1.5 (93.12), Layout-as-Thought, 192 languages |
|
| 68 |
| `olmocr2-vllm.py` | [olmOCR-2-7B](https://huggingface.co/allenai/olmOCR-2-7B-1025-FP8) | 7B | vLLM | 82.4% olmOCR-Bench |
|
| 69 |
| `rolm-ocr.py` | [RolmOCR](https://huggingface.co/reducto/RolmOCR) | 7B | vLLM | Qwen2.5-VL based, general-purpose |
|
| 70 |
| `numarkdown-ocr.py` | [NuMarkdown-8B](https://huggingface.co/numind/NuMarkdown-8B-Thinking) | 8B | vLLM | Reasoning-based OCR |
|
| 71 |
|
| 72 |
-
|
| 73 |
|
| 74 |
-
##
|
| 75 |
|
| 76 |
-
|
| 77 |
|
| 78 |
-
|
|
| 79 |
-
|--------|-------
|
| 80 |
-
| `
|
| 81 |
-
| `
|
| 82 |
-
| `
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
-
|
| 85 |
|
| 86 |
```bash
|
| 87 |
-
|
| 88 |
-
hf jobs uv run --flavor l4x1 --secrets HF_TOKEN \
|
| 89 |
-
--image vllm/vllm-openai --python /usr/bin/python3 \
|
| 90 |
-
-e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \
|
| 91 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lfm2-vl-extract.py \
|
| 92 |
-
my-images my-fields --schema '{"title": "the document title", "date": "any date shown"}'
|
| 93 |
```
|
| 94 |
|
| 95 |
-
##
|
| 96 |
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
| Script | Model | Size | Backend | Notes |
|
| 100 |
-
|--------|-------|------|---------|-------|
|
| 101 |
-
| `pp-doclayout.py` | [PP-DocLayout-L](https://huggingface.co/PaddlePaddle/PP-DocLayout-L) | 123M | paddleocr | Layout bboxes (no text). Bucket support: incremental parquet shards, resumable. |
|
| 102 |
|
| 103 |
```bash
|
|
|
|
| 104 |
hf jobs uv run --flavor l4x1 -s HF_TOKEN \
|
| 105 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
```
|
| 108 |
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
-
|
| 112 |
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
```
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
```
|
| 119 |
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
```bash
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
-
|
| 126 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
```
|
| 129 |
|
| 130 |
-
|
| 131 |
|
| 132 |
-
|
| 133 |
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
-
|
| 137 |
-
|--------|-------------|
|
| 138 |
-
| `--image-column` | Column containing images (default: `image`) |
|
| 139 |
-
| `--output-column` | Output column name (default: `markdown`) |
|
| 140 |
-
| `--split` | Dataset split (default: `train`) |
|
| 141 |
-
| `--max-samples` | Limit number of samples (useful for testing) |
|
| 142 |
-
| `--private` | Make output dataset private |
|
| 143 |
-
| `--shuffle` | Shuffle dataset before processing |
|
| 144 |
-
| `--seed` | Random seed for shuffling (default: `42`) |
|
| 145 |
-
| `--batch-size` | Images per batch (default varies per model) |
|
| 146 |
-
| `--max-model-len` | Max context length (default varies per model) |
|
| 147 |
-
| `--max-tokens` | Max output tokens (default varies per model) |
|
| 148 |
-
| `--gpu-memory-utilization` | GPU memory fraction (default: `0.8`) |
|
| 149 |
-
| `--config` | Config name for Hub push (for benchmarking) |
|
| 150 |
-
| `--create-pr` | Push as PR instead of direct commit |
|
| 151 |
-
| `--verbose` | Log resolved package versions after run |
|
| 152 |
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
```bash
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
```
|
| 158 |
|
| 159 |
-
##
|
| 160 |
|
| 161 |
-
[
|
| 162 |
|
| 163 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
```bash
|
| 166 |
-
#
|
| 167 |
hf jobs uv run --flavor a100-large \
|
| 168 |
-
--image vllm/vllm-openai:latest \
|
| 169 |
-
--python /usr/bin/python3 \
|
| 170 |
-
-e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \
|
| 171 |
-s HF_TOKEN \
|
| 172 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/
|
| 173 |
-
|
|
|
|
|
|
|
| 174 |
|
| 175 |
-
#
|
| 176 |
hf jobs uv run --flavor a100-large \
|
| 177 |
-
--image vllm/vllm-openai:latest \
|
| 178 |
-
--python /usr/bin/python3 \
|
| 179 |
-
-e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \
|
| 180 |
-s HF_TOKEN \
|
| 181 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/
|
| 182 |
-
|
| 183 |
-
--
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
```
|
| 185 |
|
| 186 |
-
|
|
|
|
|
|
|
| 187 |
|
| 188 |
-
|
|
|
|
|
|
|
| 189 |
|
| 190 |
-
|
|
|
|
|
|
|
| 191 |
|
| 192 |
-
|
| 193 |
-
|--------|---------------|
|
| 194 |
-
| `glm-ocr.py` | `--task ocr\|formula\|table` |
|
| 195 |
-
| `paddleocr-vl.py` | `--task-mode ocr\|table\|formula\|chart` |
|
| 196 |
-
| `paddleocr-vl-1.5.py` | `--task-mode ocr\|table\|formula\|chart\|spotting\|seal` |
|
| 197 |
-
| `paddleocr-vl-1.6.py` | `--task-mode ocr\|table\|formula` |
|
| 198 |
-
| `lighton-ocr.py` | `--vocab-size 151k\|32k\|16k` (smaller = faster on European languages) |
|
| 199 |
-
| `deepseek-ocr-vllm.py` | `--resolution-mode tiny\|small\|base\|large\|gundam`, `--prompt-mode document\|image\|free\|figure\|describe`; pass `-e UV_TORCH_BACKEND=auto` |
|
| 200 |
-
| `dots-ocr.py` | `--prompt-mode ocr\|layout-all\|layout-only` |
|
| 201 |
-
| `dots-mocr.py` | `--prompt-mode` (8: ocr, layout-all, layout-only, web-parsing, scene-spotting, grounding-ocr, svg, general); SVG: `--model rednote-hilab/dots.mocr-svg --prompt-mode svg` |
|
| 202 |
-
| `qianfan-ocr.py` | `--prompt-mode ocr\|table\|formula\|chart\|scene\|kie`, `--think` (Layout-as-Thought); `kie` needs `--custom-prompt` |
|
| 203 |
-
| `numarkdown-ocr.py` | `--include-thinking` (store the reasoning trace) |
|
| 204 |
-
| `nuextract3.py` | `--template` / `--schema` / `--enable-thinking` — see the NuExtract3 section above |
|
| 205 |
|
| 206 |
-
|
| 207 |
|
| 208 |
-
|
|
|
|
|
|
|
|
|
|
| 209 |
|
| 210 |
-
|
| 211 |
-
- **Multi-model comparison** — every script records `inference_info`, so you can run several models into the *same* dataset and compare. Point a second model at the same output repo:
|
| 212 |
-
```bash
|
| 213 |
-
uv run rolm-ocr.py my-dataset my-dataset --max-samples 100
|
| 214 |
-
uv run nanonets-ocr.py my-dataset my-dataset --max-samples 100 # appends
|
| 215 |
-
```
|
| 216 |
-
- **Reproducible sampling** — `--shuffle` (with `--seed`, default 42) draws a representative sample instead of the first N rows.
|
| 217 |
-
- **Automatic dataset cards** — every run writes a card with the model config, processing stats, column descriptions, and a reproduction command.
|
| 218 |
|
| 219 |
-
##
|
|
|
|
|
|
|
| 220 |
|
| 221 |
```bash
|
| 222 |
-
#
|
| 223 |
-
hf jobs uv run --flavor
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr-vllm.py \
|
| 225 |
-
NationalLibraryOfScotland/Britain-and-UK-Handbooks-Dataset
|
| 226 |
-
--
|
|
|
|
|
|
|
|
|
|
| 227 |
|
| 228 |
-
#
|
| 229 |
-
hf jobs uv run --flavor l4x1
|
| 230 |
-
|
| 231 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
|
| 233 |
-
#
|
| 234 |
-
hf jobs uv run --flavor
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
--
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
```
|
| 239 |
|
| 240 |
-
|
| 241 |
|
| 242 |
```python
|
| 243 |
from huggingface_hub import run_uv_job
|
|
@@ -245,17 +612,36 @@ from huggingface_hub import run_uv_job
|
|
| 245 |
job = run_uv_job(
|
| 246 |
"https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-ocr.py",
|
| 247 |
args=["input-dataset", "output-dataset", "--batch-size", "16"],
|
| 248 |
-
flavor="l4x1"
|
| 249 |
)
|
| 250 |
```
|
| 251 |
|
| 252 |
-
|
| 253 |
|
| 254 |
```bash
|
| 255 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
input-dataset output-dataset
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
```
|
| 258 |
|
| 259 |
-
|
| 260 |
|
| 261 |
-
Works with any
|
|
|
|
| 1 |
---
|
| 2 |
viewer: false
|
| 3 |
+
tags: [uv-script, ocr, vision-language-model, document-processing, hf-jobs]
|
| 4 |
---
|
| 5 |
|
| 6 |
# OCR UV Scripts
|
| 7 |
|
| 8 |
+
> Part of [uv-scripts](https://huggingface.co/uv-scripts) - ready-to-run ML tools powered by UV and HuggingFace Jobs.
|
| 9 |
|
| 10 |
+
14 OCR models from 0.9B to 8B parameters. Pick a model, point at your dataset, get markdown — no setup required.
|
| 11 |
|
| 12 |
+
## 🚀 Quick Start
|
|
|
|
|
|
|
| 13 |
|
| 14 |
Run OCR on any dataset without needing your own GPU:
|
| 15 |
|
|
|
|
| 22 |
--max-samples 10
|
| 23 |
```
|
| 24 |
|
| 25 |
+
That's it! The script will:
|
| 26 |
|
| 27 |
+
- Process first 10 images from your dataset
|
| 28 |
- Add OCR results as a new `markdown` column
|
| 29 |
- Push the results to a new dataset
|
| 30 |
- View results at: `https://huggingface.co/datasets/[your-output-dataset]`
|
| 31 |
|
| 32 |
+
<details><summary>All scripts at a glance (sorted by model size)</summary>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
| Script | Model | Size | Backend | Notes |
|
| 35 |
|--------|-------|------|---------|-------|
|
|
|
|
| 36 |
| `smoldocling-ocr.py` | [SmolDocling](https://huggingface.co/ds4sd/SmolDocling-256M-preview) | 256M | Transformers | DocTags structured output |
|
| 37 |
| `glm-ocr.py` | [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) | 0.9B | vLLM | 94.62% OmniDocBench V1.5 |
|
| 38 |
| `paddleocr-vl.py` | [PaddleOCR-VL](https://huggingface.co/PaddlePaddle/PaddleOCR-VL) | 0.9B | Transformers | 4 task modes (ocr/table/formula/chart) |
|
| 39 |
| `paddleocr-vl-1.5.py` | [PaddleOCR-VL-1.5](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.5) | 0.9B | Transformers | 94.5% OmniDocBench, 6 task modes |
|
|
|
|
| 40 |
| `lighton-ocr.py` | [LightOnOCR-1B](https://huggingface.co/lightonai/LightOnOCR-1B-1025) | 1B | vLLM | Fast, 3 vocab sizes |
|
| 41 |
| `lighton-ocr2.py` | [LightOnOCR-2-1B](https://huggingface.co/lightonai/LightOnOCR-2-1B) | 1B | vLLM | 7× faster than v1, RLVR trained |
|
| 42 |
| `hunyuan-ocr.py` | [HunyuanOCR](https://huggingface.co/tencent/HunyuanOCR) | 1B | vLLM | Lightweight VLM |
|
| 43 |
| `dots-ocr.py` | [DoTS.ocr](https://huggingface.co/Tencent/DoTS.ocr) | 1.7B | vLLM | 100+ languages |
|
| 44 |
| `firered-ocr.py` | [FireRed-OCR](https://huggingface.co/FireRedTeam/FireRed-OCR) | 2.1B | vLLM | Qwen3-VL fine-tune, Apache 2.0 |
|
|
|
|
| 45 |
| `nanonets-ocr.py` | [Nanonets-OCR-s](https://huggingface.co/nanonets/Nanonets-OCR-s) | 2B | vLLM | LaTeX, tables, forms |
|
| 46 |
+
| `dots-ocr-1.5.py` | [DoTS.ocr-1.5](https://huggingface.co/Tencent/DoTS.ocr-1.5) | 3B | vLLM | Updated multilingual model |
|
| 47 |
| `nanonets-ocr2.py` | [Nanonets-OCR2-3B](https://huggingface.co/nanonets/Nanonets-OCR2-s) | 3B | vLLM | Next-gen, Qwen2.5-VL base |
|
| 48 |
| `deepseek-ocr-vllm.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | vLLM | 5 resolution + 5 prompt modes |
|
| 49 |
| `deepseek-ocr.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | Transformers | Same model, Transformers backend |
|
| 50 |
+
| `deepseek-ocr2-vllm.py` | [DeepSeek-OCR-2](https://huggingface.co/deepseek-ai/DeepSeek-OCR-2) | 3B | vLLM | Newer, requires nightly vLLM |
|
|
|
|
|
|
|
| 51 |
| `olmocr2-vllm.py` | [olmOCR-2-7B](https://huggingface.co/allenai/olmOCR-2-7B-1025-FP8) | 7B | vLLM | 82.4% olmOCR-Bench |
|
| 52 |
| `rolm-ocr.py` | [RolmOCR](https://huggingface.co/reducto/RolmOCR) | 7B | vLLM | Qwen2.5-VL based, general-purpose |
|
| 53 |
| `numarkdown-ocr.py` | [NuMarkdown-8B](https://huggingface.co/numind/NuMarkdown-8B-Thinking) | 8B | vLLM | Reasoning-based OCR |
|
| 54 |
|
| 55 |
+
</details>
|
| 56 |
|
| 57 |
+
## Common Options
|
| 58 |
|
| 59 |
+
All scripts accept the same core flags. Model-specific defaults (batch size, context length, temperature) are tuned per model based on model card recommendations and can be overridden.
|
| 60 |
|
| 61 |
+
| Option | Description |
|
| 62 |
+
|--------|-------------|
|
| 63 |
+
| `--image-column` | Column containing images (default: `image`) |
|
| 64 |
+
| `--output-column` | Output column name (default: `markdown`) |
|
| 65 |
+
| `--split` | Dataset split (default: `train`) |
|
| 66 |
+
| `--max-samples` | Limit number of samples (useful for testing) |
|
| 67 |
+
| `--private` | Make output dataset private |
|
| 68 |
+
| `--shuffle` | Shuffle dataset before processing |
|
| 69 |
+
| `--seed` | Random seed for shuffling (default: `42`) |
|
| 70 |
+
| `--batch-size` | Images per batch (default varies per model) |
|
| 71 |
+
| `--max-model-len` | Max context length (default varies per model) |
|
| 72 |
+
| `--max-tokens` | Max output tokens (default varies per model) |
|
| 73 |
+
| `--gpu-memory-utilization` | GPU memory fraction (default: `0.8`) |
|
| 74 |
+
| `--config` | Config name for Hub push (for benchmarking) |
|
| 75 |
+
| `--create-pr` | Push as PR instead of direct commit |
|
| 76 |
+
| `--verbose` | Log resolved package versions after run |
|
| 77 |
|
| 78 |
+
Every script supports `--help` to see all available options:
|
| 79 |
|
| 80 |
```bash
|
| 81 |
+
uv run glm-ocr.py --help
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
```
|
| 83 |
|
| 84 |
+
## Example: GLM-OCR
|
| 85 |
|
| 86 |
+
[GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) (0.9B) scores 94.62% on OmniDocBench V1.5 and supports OCR, formula, and table extraction:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
```bash
|
| 89 |
+
# Basic OCR
|
| 90 |
hf jobs uv run --flavor l4x1 -s HF_TOKEN \
|
| 91 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \
|
| 92 |
+
my-documents my-ocr-output
|
| 93 |
+
|
| 94 |
+
# Table extraction
|
| 95 |
+
hf jobs uv run --flavor l4x1 -s HF_TOKEN \
|
| 96 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \
|
| 97 |
+
my-documents my-tables --task table
|
| 98 |
+
|
| 99 |
+
# Test on 10 samples first
|
| 100 |
+
hf jobs uv run --flavor l4x1 -s HF_TOKEN \
|
| 101 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \
|
| 102 |
+
my-documents my-test --max-samples 10
|
| 103 |
```
|
| 104 |
|
| 105 |
+
<details><summary>Detailed per-model documentation</summary>
|
| 106 |
+
|
| 107 |
+
### PaddleOCR-VL-1.5 (`paddleocr-vl-1.5.py`) — 6 task modes
|
| 108 |
+
|
| 109 |
+
OCR using [PaddlePaddle/PaddleOCR-VL-1.5](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.5) with 94.5% accuracy:
|
| 110 |
+
|
| 111 |
+
- **94.5% on OmniDocBench v1.5** (0.9B parameters)
|
| 112 |
+
- 🧩 **Ultra-compact** - Only 0.9B parameters
|
| 113 |
+
- 📝 **OCR mode** - General text extraction to markdown
|
| 114 |
+
- 📊 **Table mode** - HTML table recognition
|
| 115 |
+
- 📐 **Formula mode** - LaTeX mathematical notation
|
| 116 |
+
- 📈 **Chart mode** - Chart and diagram analysis
|
| 117 |
+
- 🔍 **Spotting mode** - Text spotting with localization (higher resolution)
|
| 118 |
+
- 🔖 **Seal mode** - Seal and stamp recognition
|
| 119 |
+
- 🌍 **Multilingual** - Support for multiple languages
|
| 120 |
|
| 121 |
+
**Task Modes:**
|
| 122 |
|
| 123 |
+
- `ocr`: General text extraction (default)
|
| 124 |
+
- `table`: Table extraction to HTML
|
| 125 |
+
- `formula`: Mathematical formula to LaTeX
|
| 126 |
+
- `chart`: Chart and diagram analysis
|
| 127 |
+
- `spotting`: Text spotting with localization
|
| 128 |
+
- `seal`: Seal and stamp recognition
|
| 129 |
|
| 130 |
+
**Quick start:**
|
| 131 |
+
|
| 132 |
+
```bash
|
| 133 |
+
# Basic OCR mode
|
| 134 |
+
hf jobs uv run --flavor l4x1 \
|
| 135 |
+
-s HF_TOKEN \
|
| 136 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl-1.5.py \
|
| 137 |
+
your-input-dataset your-output-dataset \
|
| 138 |
+
--max-samples 100
|
| 139 |
+
|
| 140 |
+
# Table extraction
|
| 141 |
+
hf jobs uv run --flavor l4x1 \
|
| 142 |
+
-s HF_TOKEN \
|
| 143 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl-1.5.py \
|
| 144 |
+
documents tables-extracted \
|
| 145 |
+
--task-mode table
|
| 146 |
+
|
| 147 |
+
# Seal recognition
|
| 148 |
+
hf jobs uv run --flavor l4x1 \
|
| 149 |
+
-s HF_TOKEN \
|
| 150 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl-1.5.py \
|
| 151 |
+
documents seals-extracted \
|
| 152 |
+
--task-mode seal
|
| 153 |
```
|
| 154 |
+
|
| 155 |
+
### PaddleOCR-VL (`paddleocr-vl.py`) 🎯 Smallest model with task-specific modes!
|
| 156 |
+
|
| 157 |
+
Ultra-compact OCR using [PaddlePaddle/PaddleOCR-VL](https://huggingface.co/PaddlePaddle/PaddleOCR-VL) with only 0.9B parameters:
|
| 158 |
+
|
| 159 |
+
- 🎯 **Smallest model** - Only 0.9B parameters (even smaller than LightOnOCR!)
|
| 160 |
+
- 📝 **OCR mode** - General text extraction to markdown
|
| 161 |
+
- 📊 **Table mode** - HTML table recognition and extraction
|
| 162 |
+
- 📐 **Formula mode** - LaTeX mathematical notation
|
| 163 |
+
- 📈 **Chart mode** - Structured chart and diagram analysis
|
| 164 |
+
- 🌍 **Multilingual** - Support for multiple languages
|
| 165 |
+
- ⚡ **Fast initialization** - Tiny model size for quick startup
|
| 166 |
+
- 🔧 **ERNIE-4.5 based** - Different architecture from Qwen models
|
| 167 |
+
|
| 168 |
+
**Task Modes:**
|
| 169 |
+
|
| 170 |
+
- `ocr`: General text extraction (default)
|
| 171 |
+
- `table`: Table extraction to HTML
|
| 172 |
+
- `formula`: Mathematical formula to LaTeX
|
| 173 |
+
- `chart`: Chart and diagram analysis
|
| 174 |
+
|
| 175 |
+
**Quick start:**
|
| 176 |
+
|
| 177 |
+
```bash
|
| 178 |
+
# Basic OCR mode
|
| 179 |
+
hf jobs uv run --flavor l4x1 \
|
| 180 |
+
-s HF_TOKEN \
|
| 181 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl.py \
|
| 182 |
+
your-input-dataset your-output-dataset \
|
| 183 |
+
--max-samples 100
|
| 184 |
+
|
| 185 |
+
# Table extraction
|
| 186 |
+
hf jobs uv run --flavor l4x1 \
|
| 187 |
+
-s HF_TOKEN \
|
| 188 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl.py \
|
| 189 |
+
documents tables-extracted \
|
| 190 |
+
--task-mode table \
|
| 191 |
+
--batch-size 32
|
| 192 |
```
|
| 193 |
|
| 194 |
+
### GLM-OCR (`glm-ocr.py`) 🏆 SOTA on OmniDocBench V1.5!
|
| 195 |
+
|
| 196 |
+
Compact high-performance OCR using [zai-org/GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) with 0.9B parameters:
|
| 197 |
+
|
| 198 |
+
- 🏆 **94.62% on OmniDocBench V1.5** - #1 overall ranking
|
| 199 |
+
- 🧠 **Multi-Token Prediction** - MTP loss + stable full-task RL for quality
|
| 200 |
+
- 📝 **Text recognition** - Clean markdown output
|
| 201 |
+
- 📐 **Formula recognition** - LaTeX mathematical notation
|
| 202 |
+
- 📊 **Table recognition** - Structured table extraction
|
| 203 |
+
- 🌍 **Multilingual** - zh, en, fr, es, ru, de, ja, ko
|
| 204 |
+
- ⚡ **Compact** - Only 0.9B parameters, MIT licensed
|
| 205 |
+
- 🔧 **CogViT + GLM** - Visual encoder with efficient token downsampling
|
| 206 |
+
|
| 207 |
+
**Task Modes:**
|
| 208 |
+
|
| 209 |
+
- `ocr`: Text recognition (default)
|
| 210 |
+
- `formula`: LaTeX formula recognition
|
| 211 |
+
- `table`: Table extraction
|
| 212 |
+
|
| 213 |
+
**Quick start:**
|
| 214 |
|
| 215 |
```bash
|
| 216 |
+
# Basic OCR
|
| 217 |
+
hf jobs uv run --flavor l4x1 \
|
| 218 |
+
-s HF_TOKEN \
|
| 219 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \
|
| 220 |
+
your-input-dataset your-output-dataset \
|
| 221 |
+
--max-samples 100
|
| 222 |
+
|
| 223 |
+
# Formula recognition
|
| 224 |
+
hf jobs uv run --flavor l4x1 \
|
| 225 |
+
-s HF_TOKEN \
|
| 226 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \
|
| 227 |
+
scientific-papers formulas-extracted \
|
| 228 |
+
--task formula
|
| 229 |
+
|
| 230 |
+
# Table extraction
|
| 231 |
+
hf jobs uv run --flavor l4x1 \
|
| 232 |
+
-s HF_TOKEN \
|
| 233 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \
|
| 234 |
+
documents tables-extracted \
|
| 235 |
+
--task table
|
| 236 |
```
|
| 237 |
|
| 238 |
+
### LightOnOCR (`lighton-ocr.py`) ⚡ Good one to test first since it's small and fast!
|
| 239 |
|
| 240 |
+
Fast and compact OCR using [lightonai/LightOnOCR-1B-1025](https://huggingface.co/lightonai/LightOnOCR-1B-1025):
|
| 241 |
|
| 242 |
+
- ⚡ **Fastest**: 5.71 pages/sec on H100, ~6.25 images/sec on A100 with batch_size=4096
|
| 243 |
+
- 🎯 **Compact**: Only 1B parameters - quick to download and initialize
|
| 244 |
+
- 🌍 **Multilingual**: 3 vocabulary sizes for different use cases
|
| 245 |
+
- 📐 **LaTeX formulas**: Mathematical notation in LaTeX format
|
| 246 |
+
- 📊 **Table extraction**: Markdown table format
|
| 247 |
+
- 📝 **Document structure**: Preserves hierarchy and layout
|
| 248 |
+
- 🚀 **Production-ready**: 76.1% benchmark score, used in production
|
| 249 |
|
| 250 |
+
**Vocabulary sizes:**
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
|
| 252 |
+
- `151k`: Full vocabulary, all languages (default)
|
| 253 |
+
- `32k`: European languages, ~12% faster decoding
|
| 254 |
+
- `16k`: European languages, ~12% faster decoding
|
| 255 |
+
|
| 256 |
+
**Quick start:**
|
| 257 |
|
| 258 |
```bash
|
| 259 |
+
# Test on 100 samples with English text (32k vocab is fastest for European languages)
|
| 260 |
+
hf jobs uv run --flavor l4x1 \
|
| 261 |
+
-s HF_TOKEN \
|
| 262 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr.py \
|
| 263 |
+
your-input-dataset your-output-dataset \
|
| 264 |
+
--vocab-size 32k \
|
| 265 |
+
--batch-size 32 \
|
| 266 |
+
--max-samples 100
|
| 267 |
+
|
| 268 |
+
# Full production run on A100 (can handle huge batches!)
|
| 269 |
+
hf jobs uv run --flavor a100-large \
|
| 270 |
+
-s HF_TOKEN \
|
| 271 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr.py \
|
| 272 |
+
your-input-dataset your-output-dataset \
|
| 273 |
+
--vocab-size 32k \
|
| 274 |
+
--batch-size 4096 \
|
| 275 |
+
--temperature 0.0
|
| 276 |
```
|
| 277 |
|
| 278 |
+
### LightOnOCR-2 (`lighton-ocr2.py`) ⚡ Fastest OCR model!
|
| 279 |
|
| 280 |
+
Next-generation fast OCR using [lightonai/LightOnOCR-2-1B](https://huggingface.co/lightonai/LightOnOCR-2-1B) with RLVR training:
|
| 281 |
|
| 282 |
+
- ⚡ **7× faster than v1**: 42.8 pages/sec on H100 (vs 5.71 for v1)
|
| 283 |
+
- 🎯 **Higher accuracy**: 83.2% on OlmOCR-Bench (+7.1% vs v1)
|
| 284 |
+
- 🧠 **RLVR trained**: Eliminates repetition loops and formatting errors
|
| 285 |
+
- 📚 **Better dataset**: 2.5× larger training data with cleaner annotations
|
| 286 |
+
- 🌍 **Multilingual**: Optimized for European languages
|
| 287 |
+
- 📐 **LaTeX formulas**: Mathematical notation support
|
| 288 |
+
- 📊 **Table extraction**: Markdown table format
|
| 289 |
+
- 💪 **Production-ready**: Outperforms models 9× larger
|
| 290 |
+
|
| 291 |
+
**Quick start:**
|
| 292 |
|
| 293 |
```bash
|
| 294 |
+
# Test on 100 samples
|
| 295 |
hf jobs uv run --flavor a100-large \
|
|
|
|
|
|
|
|
|
|
| 296 |
-s HF_TOKEN \
|
| 297 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr2.py \
|
| 298 |
+
your-input-dataset your-output-dataset \
|
| 299 |
+
--batch-size 32 \
|
| 300 |
+
--max-samples 100
|
| 301 |
|
| 302 |
+
# Full production run
|
| 303 |
hf jobs uv run --flavor a100-large \
|
|
|
|
|
|
|
|
|
|
| 304 |
-s HF_TOKEN \
|
| 305 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr2.py \
|
| 306 |
+
your-input-dataset your-output-dataset \
|
| 307 |
+
--batch-size 32
|
| 308 |
+
```
|
| 309 |
+
|
| 310 |
+
### DeepSeek-OCR (`deepseek-ocr-vllm.py`)
|
| 311 |
+
|
| 312 |
+
Advanced document OCR using [deepseek-ai/DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) with visual-text compression:
|
| 313 |
+
|
| 314 |
+
- 📐 **LaTeX equations** - Mathematical formulas in LaTeX format
|
| 315 |
+
- 📊 **Tables** - Extracted as HTML/markdown
|
| 316 |
+
- 📝 **Document structure** - Headers, lists, formatting preserved
|
| 317 |
+
- 🖼️ **Image grounding** - Spatial layout with bounding boxes
|
| 318 |
+
- 🔍 **Complex layouts** - Multi-column and hierarchical structures
|
| 319 |
+
- 🌍 **Multilingual** - Multiple language support
|
| 320 |
+
- 🎚️ **Resolution modes** - 5 presets for speed/quality trade-offs
|
| 321 |
+
- 💬 **Prompt modes** - 5 presets for different OCR tasks
|
| 322 |
+
- ⚡ **Fast batch processing** - vLLM acceleration
|
| 323 |
+
|
| 324 |
+
**Resolution Modes:**
|
| 325 |
+
|
| 326 |
+
- `tiny` (512×512): Fast, 64 vision tokens
|
| 327 |
+
- `small` (640×640): Balanced, 100 vision tokens
|
| 328 |
+
- `base` (1024×1024): High quality, 256 vision tokens
|
| 329 |
+
- `large` (1280×1280): Maximum quality, 400 vision tokens
|
| 330 |
+
- `gundam` (dynamic): Adaptive multi-tile (default)
|
| 331 |
+
|
| 332 |
+
**Prompt Modes:**
|
| 333 |
+
|
| 334 |
+
- `document`: Convert to markdown with grounding (default)
|
| 335 |
+
- `image`: OCR any image with grounding
|
| 336 |
+
- `free`: Fast OCR without layout
|
| 337 |
+
- `figure`: Parse figures from documents
|
| 338 |
+
- `describe`: Detailed image descriptions
|
| 339 |
+
|
| 340 |
+
### RolmOCR (`rolm-ocr.py`)
|
| 341 |
+
|
| 342 |
+
Fast general-purpose OCR using [reducto/RolmOCR](https://huggingface.co/reducto/RolmOCR) based on Qwen2.5-VL-7B:
|
| 343 |
+
|
| 344 |
+
- 🚀 **Fast extraction** - Optimized for speed and efficiency
|
| 345 |
+
- 📄 **Plain text output** - Clean, natural text representation
|
| 346 |
+
- 💪 **General-purpose** - Works well on various document types
|
| 347 |
+
- 🔥 **Large context** - Handles up to 16K tokens
|
| 348 |
+
- ⚡ **Batch optimized** - Efficient processing with vLLM
|
| 349 |
+
|
| 350 |
+
### Nanonets OCR (`nanonets-ocr.py`)
|
| 351 |
+
|
| 352 |
+
State-of-the-art document OCR using [nanonets/Nanonets-OCR-s](https://huggingface.co/nanonets/Nanonets-OCR-s) that handles:
|
| 353 |
+
|
| 354 |
+
- 📐 **LaTeX equations** - Mathematical formulas preserved
|
| 355 |
+
- 📊 **Tables** - Extracted as HTML format
|
| 356 |
+
- 📝 **Document structure** - Headers, lists, formatting maintained
|
| 357 |
+
- 🖼️ **Images** - Captions and descriptions included
|
| 358 |
+
- ☑️ **Forms** - Checkboxes rendered as ☐/☑
|
| 359 |
+
|
| 360 |
+
### Nanonets OCR2 (`nanonets-ocr2.py`)
|
| 361 |
+
|
| 362 |
+
Next-generation Nanonets OCR using [nanonets/Nanonets-OCR2-3B](https://huggingface.co/nanonets/Nanonets-OCR2-3B) with improved accuracy:
|
| 363 |
+
|
| 364 |
+
- 🎯 **Enhanced quality** - 3.75B parameters for superior OCR accuracy
|
| 365 |
+
- 📐 **LaTeX equations** - Mathematical formulas preserved in LaTeX format
|
| 366 |
+
- 📊 **Advanced tables** - Improved HTML table extraction
|
| 367 |
+
- 📝 **Document structure** - Headers, lists, formatting maintained
|
| 368 |
+
- 🖼️ **Smart image captions** - Intelligent descriptions and captions
|
| 369 |
+
- ☑️ **Forms** - Checkboxes rendered as ☐/☑
|
| 370 |
+
- 🌍 **Multilingual** - Enhanced language support
|
| 371 |
+
- 🔧 **Based on Qwen2.5-VL** - Built on state-of-the-art vision-language model
|
| 372 |
+
|
| 373 |
+
### SmolDocling (`smoldocling-ocr.py`)
|
| 374 |
+
|
| 375 |
+
Ultra-compact document understanding using [ds4sd/SmolDocling-256M-preview](https://huggingface.co/ds4sd/SmolDocling-256M-preview) with only 256M parameters:
|
| 376 |
+
|
| 377 |
+
- 🏷️ **DocTags format** - Efficient XML-like representation
|
| 378 |
+
- 💻 **Code blocks** - Preserves indentation and syntax
|
| 379 |
+
- 🔢 **Formulas** - Mathematical expressions with layout
|
| 380 |
+
- 📊 **Tables & charts** - Structured data extraction
|
| 381 |
+
- 📐 **Layout preservation** - Bounding boxes and spatial info
|
| 382 |
+
- ⚡ **Ultra-fast** - Tiny model size for quick inference
|
| 383 |
+
|
| 384 |
+
### NuMarkdown (`numarkdown-ocr.py`)
|
| 385 |
+
|
| 386 |
+
Advanced reasoning-based OCR using [numind/NuMarkdown-8B-Thinking](https://huggingface.co/numind/NuMarkdown-8B-Thinking) that analyzes documents before converting to markdown:
|
| 387 |
+
|
| 388 |
+
- 🧠 **Reasoning Process** - Thinks through document layout before generation
|
| 389 |
+
- 📊 **Complex Tables** - Superior table extraction and formatting
|
| 390 |
+
- 📐 **Mathematical Formulas** - Accurate LaTeX/math notation preservation
|
| 391 |
+
- 🔍 **Multi-column Layouts** - Handles complex document structures
|
| 392 |
+
- ✨ **Thinking Traces** - Optional inclusion of reasoning process with `--include-thinking`
|
| 393 |
+
|
| 394 |
+
### DoTS.ocr (`dots-ocr.py`)
|
| 395 |
+
|
| 396 |
+
Compact multilingual OCR using [rednote-hilab/dots.ocr](https://huggingface.co/rednote-hilab/dots.ocr) with only 1.7B parameters:
|
| 397 |
+
|
| 398 |
+
- 🌍 **100+ Languages** - Extensive multilingual support
|
| 399 |
+
- 📝 **Simple OCR** - Clean text extraction (default mode)
|
| 400 |
+
- 📊 **Layout Analysis** - Optional structured output with bboxes and categories
|
| 401 |
+
- 📐 **Formula recognition** - LaTeX format support
|
| 402 |
+
- 🎯 **Compact** - Only 1.7B parameters, efficient on smaller GPUs
|
| 403 |
+
- 🔀 **Flexible prompts** - Switch between OCR, layout-all, and layout-only modes
|
| 404 |
+
|
| 405 |
+
### FireRed-OCR (`firered-ocr.py`)
|
| 406 |
+
|
| 407 |
+
Document OCR using [FireRedTeam/FireRed-OCR](https://huggingface.co/FireRedTeam/FireRed-OCR), a 2.1B model fine-tuned from Qwen3-VL-2B-Instruct:
|
| 408 |
+
|
| 409 |
+
- 📝 **Structured Markdown** - Preserves headings, paragraphs, lists
|
| 410 |
+
- 📐 **LaTeX formulas** - Inline and block math support
|
| 411 |
+
- 📊 **HTML tables** - Table extraction with `<table>` tags
|
| 412 |
+
- 🪶 **Lightweight** - 2.1B parameters, runs on L4 GPU
|
| 413 |
+
- 📜 **Apache 2.0** - Permissive license
|
| 414 |
+
|
| 415 |
+
**Quick start:**
|
| 416 |
+
|
| 417 |
+
```bash
|
| 418 |
+
hf jobs uv run --flavor l4x1 \
|
| 419 |
+
-s HF_TOKEN \
|
| 420 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/firered-ocr.py \
|
| 421 |
+
your-input-dataset your-output-dataset \
|
| 422 |
+
--max-samples 100
|
| 423 |
+
```
|
| 424 |
+
|
| 425 |
+
### olmOCR2 (`olmocr2-vllm.py`)
|
| 426 |
+
|
| 427 |
+
High-quality document OCR using [allenai/olmOCR-2-7B-1025-FP8](https://huggingface.co/allenai/olmOCR-2-7B-1025-FP8) optimized with GRPO reinforcement learning:
|
| 428 |
+
|
| 429 |
+
- 🎯 **High accuracy** - 82.4 ± 1.1 on olmOCR-Bench (84.9% on math)
|
| 430 |
+
- 📐 **LaTeX equations** - Mathematical formulas in LaTeX format
|
| 431 |
+
- 📊 **Table extraction** - Structured table recognition
|
| 432 |
+
- 📑 **Multi-column layouts** - Complex document structures
|
| 433 |
+
- 🗜️ **FP8 quantized** - Efficient 8B model for faster inference
|
| 434 |
+
- 📜 **Degraded scans** - Works well on old/historical documents
|
| 435 |
+
- 📝 **Long text extraction** - Headers, footers, and full document content
|
| 436 |
+
- 🧩 **YAML metadata** - Structured front matter (language, rotation, content type)
|
| 437 |
+
- 🚀 **Based on Qwen2.5-VL-7B** - Fine-tuned with reinforcement learning
|
| 438 |
+
|
| 439 |
+
## 🆕 New Features
|
| 440 |
+
|
| 441 |
+
### Multi-Model Comparison Support
|
| 442 |
+
|
| 443 |
+
All scripts now include `inference_info` tracking for comparing multiple OCR models:
|
| 444 |
+
|
| 445 |
+
```bash
|
| 446 |
+
# First model
|
| 447 |
+
uv run rolm-ocr.py my-dataset my-dataset --max-samples 100
|
| 448 |
+
|
| 449 |
+
# Second model (appends to same dataset)
|
| 450 |
+
uv run nanonets-ocr.py my-dataset my-dataset --max-samples 100
|
| 451 |
+
|
| 452 |
+
# View all models used
|
| 453 |
+
python -c "import json; from datasets import load_dataset; ds = load_dataset('my-dataset'); print(json.loads(ds[0]['inference_info']))"
|
| 454 |
```
|
| 455 |
|
| 456 |
+
### Random Sampling
|
| 457 |
+
|
| 458 |
+
Get representative samples with the new `--shuffle` flag:
|
| 459 |
|
| 460 |
+
```bash
|
| 461 |
+
# Random 50 samples instead of first 50
|
| 462 |
+
uv run rolm-ocr.py ordered-dataset output --max-samples 50 --shuffle
|
| 463 |
|
| 464 |
+
# Reproducible random sampling
|
| 465 |
+
uv run nanonets-ocr.py dataset output --max-samples 100 --shuffle --seed 42
|
| 466 |
+
```
|
| 467 |
|
| 468 |
+
### Automatic Dataset Cards
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 469 |
|
| 470 |
+
Every OCR run now generates comprehensive dataset documentation including:
|
| 471 |
|
| 472 |
+
- Model configuration and parameters
|
| 473 |
+
- Processing statistics
|
| 474 |
+
- Column descriptions
|
| 475 |
+
- Reproduction instructions
|
| 476 |
|
| 477 |
+
## 💻 Usage Examples
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 478 |
|
| 479 |
+
### Run on HuggingFace Jobs (Recommended)
|
| 480 |
+
|
| 481 |
+
No GPU? No problem! Run on HF infrastructure:
|
| 482 |
|
| 483 |
```bash
|
| 484 |
+
# PaddleOCR-VL - Smallest model (0.9B) with task modes
|
| 485 |
+
hf jobs uv run --flavor l4x1 \
|
| 486 |
+
--secrets HF_TOKEN \
|
| 487 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl.py \
|
| 488 |
+
your-input-dataset your-output-dataset \
|
| 489 |
+
--task-mode ocr \
|
| 490 |
+
--max-samples 100
|
| 491 |
+
|
| 492 |
+
# PaddleOCR-VL - Extract tables from documents
|
| 493 |
+
hf jobs uv run --flavor l4x1 \
|
| 494 |
+
--secrets HF_TOKEN \
|
| 495 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl.py \
|
| 496 |
+
documents tables-dataset \
|
| 497 |
+
--task-mode table
|
| 498 |
+
|
| 499 |
+
# PaddleOCR-VL - Formula recognition
|
| 500 |
+
hf jobs uv run --flavor l4x1 \
|
| 501 |
+
--secrets HF_TOKEN \
|
| 502 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl.py \
|
| 503 |
+
scientific-papers formulas-extracted \
|
| 504 |
+
--task-mode formula \
|
| 505 |
+
--batch-size 32
|
| 506 |
+
|
| 507 |
+
# GLM-OCR - SOTA 0.9B model (94.62% OmniDocBench)
|
| 508 |
+
hf jobs uv run --flavor l4x1 \
|
| 509 |
+
-s HF_TOKEN \
|
| 510 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \
|
| 511 |
+
your-input-dataset your-output-dataset \
|
| 512 |
+
--batch-size 16 \
|
| 513 |
+
--max-samples 100
|
| 514 |
+
|
| 515 |
+
# DeepSeek-OCR - Real-world example (National Library of Scotland handbooks)
|
| 516 |
+
hf jobs uv run --flavor a100-large \
|
| 517 |
+
-s HF_TOKEN \
|
| 518 |
+
-e UV_TORCH_BACKEND=auto \
|
| 519 |
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr-vllm.py \
|
| 520 |
+
NationalLibraryOfScotland/Britain-and-UK-Handbooks-Dataset \
|
| 521 |
+
davanstrien/handbooks-deep-ocr \
|
| 522 |
+
--max-samples 100 \
|
| 523 |
+
--shuffle \
|
| 524 |
+
--resolution-mode large
|
| 525 |
|
| 526 |
+
# DeepSeek-OCR - Fast testing with tiny mode
|
| 527 |
+
hf jobs uv run --flavor l4x1 \
|
| 528 |
+
-s HF_TOKEN \
|
| 529 |
+
-e UV_TORCH_BACKEND=auto \
|
| 530 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr-vllm.py \
|
| 531 |
+
your-input-dataset your-output-dataset \
|
| 532 |
+
--max-samples 10 \
|
| 533 |
+
--resolution-mode tiny
|
| 534 |
|
| 535 |
+
# DeepSeek-OCR - Parse figures from scientific papers
|
| 536 |
+
hf jobs uv run --flavor a100-large \
|
| 537 |
+
-s HF_TOKEN \
|
| 538 |
+
-e UV_TORCH_BACKEND=auto \
|
| 539 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr-vllm.py \
|
| 540 |
+
scientific-papers figures-extracted \
|
| 541 |
+
--prompt-mode figure
|
| 542 |
+
|
| 543 |
+
# Basic OCR job with Nanonets
|
| 544 |
+
hf jobs uv run --flavor l4x1 \
|
| 545 |
+
--secrets HF_TOKEN \
|
| 546 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-ocr.py \
|
| 547 |
+
your-input-dataset your-output-dataset
|
| 548 |
+
|
| 549 |
+
# DoTS.ocr - Multilingual OCR with compact 1.7B model
|
| 550 |
+
hf jobs uv run --flavor a100-large \
|
| 551 |
+
--secrets HF_TOKEN \
|
| 552 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/dots-ocr.py \
|
| 553 |
+
davanstrien/ufo-ColPali \
|
| 554 |
+
your-username/ufo-ocr \
|
| 555 |
+
--batch-size 256 \
|
| 556 |
+
--max-samples 1000 \
|
| 557 |
+
--shuffle
|
| 558 |
+
|
| 559 |
+
# Real example with UFO dataset 🛸
|
| 560 |
+
hf jobs uv run \
|
| 561 |
+
--flavor a10g-large \
|
| 562 |
+
--secrets HF_TOKEN \
|
| 563 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-ocr.py \
|
| 564 |
+
davanstrien/ufo-ColPali \
|
| 565 |
+
your-username/ufo-ocr \
|
| 566 |
+
--image-column image \
|
| 567 |
+
--max-model-len 16384 \
|
| 568 |
+
--batch-size 128
|
| 569 |
+
|
| 570 |
+
# Nanonets OCR2 - Next-gen quality with 3B model
|
| 571 |
+
hf jobs uv run \
|
| 572 |
+
--flavor l4x1 \
|
| 573 |
+
--secrets HF_TOKEN \
|
| 574 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-ocr2.py \
|
| 575 |
+
your-input-dataset \
|
| 576 |
+
your-output-dataset \
|
| 577 |
+
--batch-size 16
|
| 578 |
+
|
| 579 |
+
# NuMarkdown with reasoning traces for complex documents
|
| 580 |
+
hf jobs uv run \
|
| 581 |
+
--flavor l4x4 \
|
| 582 |
+
--secrets HF_TOKEN \
|
| 583 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/numarkdown-ocr.py \
|
| 584 |
+
your-input-dataset your-output-dataset \
|
| 585 |
+
--max-samples 50 \
|
| 586 |
+
--include-thinking \
|
| 587 |
+
--shuffle
|
| 588 |
+
|
| 589 |
+
# olmOCR2 - High-quality OCR with YAML metadata
|
| 590 |
+
hf jobs uv run \
|
| 591 |
+
--flavor a100-large \
|
| 592 |
+
--secrets HF_TOKEN \
|
| 593 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/olmocr2-vllm.py \
|
| 594 |
+
your-input-dataset your-output-dataset \
|
| 595 |
+
--batch-size 16 \
|
| 596 |
+
--max-samples 100
|
| 597 |
+
|
| 598 |
+
# Private dataset with custom settings
|
| 599 |
+
hf jobs uv run --flavor l40sx1 \
|
| 600 |
+
--secrets HF_TOKEN \
|
| 601 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-ocr.py \
|
| 602 |
+
private-input private-output \
|
| 603 |
+
--private \
|
| 604 |
+
--batch-size 32
|
| 605 |
```
|
| 606 |
|
| 607 |
+
### Python API
|
| 608 |
|
| 609 |
```python
|
| 610 |
from huggingface_hub import run_uv_job
|
|
|
|
| 612 |
job = run_uv_job(
|
| 613 |
"https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-ocr.py",
|
| 614 |
args=["input-dataset", "output-dataset", "--batch-size", "16"],
|
| 615 |
+
flavor="l4x1"
|
| 616 |
)
|
| 617 |
```
|
| 618 |
|
| 619 |
+
### Run Locally (Requires GPU)
|
| 620 |
|
| 621 |
```bash
|
| 622 |
+
# Clone and run
|
| 623 |
+
git clone https://huggingface.co/datasets/uv-scripts/ocr
|
| 624 |
+
cd ocr
|
| 625 |
+
uv run nanonets-ocr.py input-dataset output-dataset
|
| 626 |
+
|
| 627 |
+
# Or run directly from URL
|
| 628 |
+
uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-ocr.py \
|
| 629 |
input-dataset output-dataset
|
| 630 |
+
|
| 631 |
+
# PaddleOCR-VL for task-specific OCR (smallest model!)
|
| 632 |
+
uv run paddleocr-vl.py documents extracted --task-mode ocr
|
| 633 |
+
uv run paddleocr-vl.py papers tables --task-mode table # Extract tables
|
| 634 |
+
uv run paddleocr-vl.py textbooks formulas --task-mode formula # LaTeX formulas
|
| 635 |
+
|
| 636 |
+
# RolmOCR for fast text extraction
|
| 637 |
+
uv run rolm-ocr.py documents extracted-text
|
| 638 |
+
uv run rolm-ocr.py images texts --shuffle --max-samples 100 # Random sample
|
| 639 |
+
|
| 640 |
+
# Nanonets OCR2 for highest quality
|
| 641 |
+
uv run nanonets-ocr2.py documents ocr-results
|
| 642 |
+
|
| 643 |
```
|
| 644 |
|
| 645 |
+
</details>
|
| 646 |
|
| 647 |
+
Works with any HuggingFace dataset containing images — documents, forms, receipts, books, handwriting.
|
abot-ocr.py
DELETED
|
@@ -1,560 +0,0 @@
|
|
| 1 |
-
# /// script
|
| 2 |
-
# requires-python = ">=3.11"
|
| 3 |
-
# dependencies = [
|
| 4 |
-
# "datasets>=4.0.0",
|
| 5 |
-
# "huggingface-hub",
|
| 6 |
-
# "pillow",
|
| 7 |
-
# "vllm>=0.15.1",
|
| 8 |
-
# "tqdm",
|
| 9 |
-
# "toolz",
|
| 10 |
-
# "torch",
|
| 11 |
-
# ]
|
| 12 |
-
#
|
| 13 |
-
# ///
|
| 14 |
-
|
| 15 |
-
"""
|
| 16 |
-
Convert document images to Markdown using ABot-OCR with vLLM.
|
| 17 |
-
|
| 18 |
-
ABot-OCR (acvlab/ABot-OCR) is a compact Qwen3-VL-based document OCR model that
|
| 19 |
-
converts PDF/document page images into structured Markdown, including:
|
| 20 |
-
- Text with original document structure (headings, paragraphs, lists)
|
| 21 |
-
- Mathematical formulas in LaTeX (inline \\( \\) and block \\[ \\])
|
| 22 |
-
- Tables in HTML (<table>…</table>)
|
| 23 |
-
|
| 24 |
-
Model: https://huggingface.co/acvlab/ABot-OCR
|
| 25 |
-
Paper: https://arxiv.org/abs/2605.27978
|
| 26 |
-
Code: https://github.com/amap-cvlab/ABot-OCR
|
| 27 |
-
|
| 28 |
-
HF Jobs note: ABot-OCR (Qwen3-VL) uses vLLM's flashinfer sampler, which needs CUDA
|
| 29 |
-
kernels the default uv-script image can't build ("Could not find nvcc"). Run on Jobs
|
| 30 |
-
with the pre-built vLLM image so the kernels are reused (same image-mode pattern as
|
| 31 |
-
nuextract3.py / paddleocr-vl-1.6.py):
|
| 32 |
-
--image vllm/vllm-openai:latest
|
| 33 |
-
--python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages
|
| 34 |
-
"""
|
| 35 |
-
|
| 36 |
-
import argparse
|
| 37 |
-
import base64
|
| 38 |
-
import io
|
| 39 |
-
import json
|
| 40 |
-
import logging
|
| 41 |
-
import os
|
| 42 |
-
import sys
|
| 43 |
-
from typing import Any, Dict, List, Union
|
| 44 |
-
from datetime import datetime
|
| 45 |
-
|
| 46 |
-
import torch
|
| 47 |
-
from datasets import load_dataset
|
| 48 |
-
from huggingface_hub import DatasetCard, login
|
| 49 |
-
from PIL import Image
|
| 50 |
-
from toolz import partition_all
|
| 51 |
-
from tqdm.auto import tqdm
|
| 52 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 53 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 54 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 55 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 56 |
-
from vllm import LLM, SamplingParams
|
| 57 |
-
|
| 58 |
-
logging.basicConfig(level=logging.INFO)
|
| 59 |
-
logger = logging.getLogger(__name__)
|
| 60 |
-
|
| 61 |
-
# ABot-OCR's recommended document→Markdown prompt (from the model's reference
|
| 62 |
-
# inference script; LaTeX delimiters de-mangled to proper \( \) and \[ \]).
|
| 63 |
-
DEFAULT_PROMPT = r"""You are an AI assistant specialized in converting PDF images to Markdown format. Please follow these instructions for the conversion:
|
| 64 |
-
|
| 65 |
-
1. Text Processing:
|
| 66 |
-
- Accurately recognize all text content in the PDF image without guessing or inferring.
|
| 67 |
-
- Convert the recognized text into Markdown format.
|
| 68 |
-
- Maintain the original document structure, including headings, paragraphs, lists, etc.
|
| 69 |
-
|
| 70 |
-
2. Mathematical Formula Processing:
|
| 71 |
-
- Convert all mathematical formulas to LaTeX format.
|
| 72 |
-
- Enclose inline formulas with \( \). For example: This is an inline formula \( E = mc^2 \)
|
| 73 |
-
- Enclose block formulas with \[ \]. For example: \[ \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} \]
|
| 74 |
-
|
| 75 |
-
3. Table Processing:
|
| 76 |
-
- Convert tables to HTML format.
|
| 77 |
-
- Wrap the entire table with <table> and </table>.
|
| 78 |
-
|
| 79 |
-
4. Figure Handling:
|
| 80 |
-
- Ignore figures content in the PDF image. Do not attempt to describe or convert images.
|
| 81 |
-
|
| 82 |
-
5. Output Format:
|
| 83 |
-
- Ensure the output Markdown document has a clear structure with appropriate line breaks between elements.
|
| 84 |
-
- For complex layouts, try to maintain the original document's structure and format as closely as possible.
|
| 85 |
-
|
| 86 |
-
Please strictly follow these guidelines to ensure accuracy and consistency in the conversion. Your task is to accurately convert the content of the PDF image into Markdown format without adding any extra explanations or comments."""
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
def check_cuda_availability():
|
| 90 |
-
"""Check if CUDA is available and exit if not."""
|
| 91 |
-
if not torch.cuda.is_available():
|
| 92 |
-
logger.error("CUDA is not available. This script requires a GPU.")
|
| 93 |
-
logger.error("Please run on a machine with a CUDA-capable GPU.")
|
| 94 |
-
sys.exit(1)
|
| 95 |
-
else:
|
| 96 |
-
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
def post_process_text(text: str, threshold: int = 8000) -> str:
|
| 100 |
-
"""Trim runaway repetition loops that VLM OCR can fall into on dense pages.
|
| 101 |
-
|
| 102 |
-
Mirrors ABot-OCR's reference post-processing: if the tail of a long output
|
| 103 |
-
repeats the same short substring many times, collapse it to a single copy.
|
| 104 |
-
"""
|
| 105 |
-
n = len(text)
|
| 106 |
-
if n < threshold:
|
| 107 |
-
return text
|
| 108 |
-
for length in range(2, n // 10 + 1):
|
| 109 |
-
candidate = text[-length:]
|
| 110 |
-
count = 0
|
| 111 |
-
i = n - length
|
| 112 |
-
while i >= 0 and text[i:i + length] == candidate:
|
| 113 |
-
count += 1
|
| 114 |
-
i -= length
|
| 115 |
-
if count >= 10:
|
| 116 |
-
return text[: n - length * (count - 1)]
|
| 117 |
-
return text
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
def make_ocr_message(
|
| 121 |
-
image: Union[Image.Image, Dict[str, Any], str],
|
| 122 |
-
prompt: str = DEFAULT_PROMPT,
|
| 123 |
-
) -> List[Dict]:
|
| 124 |
-
"""Create a vLLM chat message for OCR processing."""
|
| 125 |
-
# Convert to PIL Image if needed
|
| 126 |
-
if isinstance(image, Image.Image):
|
| 127 |
-
pil_img = image
|
| 128 |
-
elif isinstance(image, dict) and "bytes" in image:
|
| 129 |
-
pil_img = Image.open(io.BytesIO(image["bytes"]))
|
| 130 |
-
elif isinstance(image, str):
|
| 131 |
-
pil_img = Image.open(image)
|
| 132 |
-
else:
|
| 133 |
-
raise ValueError(f"Unsupported image type: {type(image)}")
|
| 134 |
-
|
| 135 |
-
if pil_img.mode != "RGB":
|
| 136 |
-
pil_img = pil_img.convert("RGB")
|
| 137 |
-
|
| 138 |
-
# Convert to base64 data URI
|
| 139 |
-
buf = io.BytesIO()
|
| 140 |
-
pil_img.save(buf, format="PNG")
|
| 141 |
-
data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
|
| 142 |
-
|
| 143 |
-
return [
|
| 144 |
-
{
|
| 145 |
-
"role": "user",
|
| 146 |
-
"content": [
|
| 147 |
-
{"type": "image_url", "image_url": {"url": data_uri}},
|
| 148 |
-
{"type": "text", "text": prompt},
|
| 149 |
-
],
|
| 150 |
-
}
|
| 151 |
-
]
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
def create_dataset_card(
|
| 155 |
-
source_dataset: str,
|
| 156 |
-
model: str,
|
| 157 |
-
num_samples: int,
|
| 158 |
-
processing_time: str,
|
| 159 |
-
batch_size: int,
|
| 160 |
-
max_model_len: int,
|
| 161 |
-
max_tokens: int,
|
| 162 |
-
gpu_memory_utilization: float,
|
| 163 |
-
image_column: str = "image",
|
| 164 |
-
split: str = "train",
|
| 165 |
-
) -> str:
|
| 166 |
-
"""Create a dataset card documenting the OCR process."""
|
| 167 |
-
model_name = model.split("/")[-1]
|
| 168 |
-
|
| 169 |
-
return f"""---
|
| 170 |
-
tags:
|
| 171 |
-
- ocr
|
| 172 |
-
- document-processing
|
| 173 |
-
- abot
|
| 174 |
-
- abot-ocr
|
| 175 |
-
- markdown
|
| 176 |
-
- uv-script
|
| 177 |
-
- generated
|
| 178 |
-
---
|
| 179 |
-
|
| 180 |
-
# Document OCR using {model_name}
|
| 181 |
-
|
| 182 |
-
This dataset contains Markdown-formatted OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using [ABot-OCR](https://huggingface.co/{model}).
|
| 183 |
-
|
| 184 |
-
## Processing Details
|
| 185 |
-
|
| 186 |
-
- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
|
| 187 |
-
- **Model**: [{model}](https://huggingface.co/{model})
|
| 188 |
-
- **Paper**: [arxiv.org/abs/2605.27978](https://arxiv.org/abs/2605.27978)
|
| 189 |
-
- **Number of Samples**: {num_samples:,}
|
| 190 |
-
- **Processing Time**: {processing_time}
|
| 191 |
-
- **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
|
| 192 |
-
|
| 193 |
-
### Configuration
|
| 194 |
-
|
| 195 |
-
- **Image Column**: `{image_column}`
|
| 196 |
-
- **Output Column**: `markdown`
|
| 197 |
-
- **Dataset Split**: `{split}`
|
| 198 |
-
- **Batch Size**: {batch_size}
|
| 199 |
-
- **Max Model Length**: {max_model_len:,} tokens
|
| 200 |
-
- **Max Output Tokens**: {max_tokens:,}
|
| 201 |
-
- **GPU Memory Utilization**: {gpu_memory_utilization:.1%}
|
| 202 |
-
|
| 203 |
-
## Model Information
|
| 204 |
-
|
| 205 |
-
ABot-OCR is a compact Qwen3-VL-based document OCR model that converts page images to Markdown:
|
| 206 |
-
- 📐 **LaTeX equations** — inline `\\( \\)` and block `\\[ \\]`
|
| 207 |
-
- 📊 **Tables** — extracted as HTML (`<table>…</table>`)
|
| 208 |
-
- 📝 **Document structure** — headings, paragraphs, and lists preserved
|
| 209 |
-
|
| 210 |
-
## Dataset Structure
|
| 211 |
-
|
| 212 |
-
The dataset contains all original columns plus:
|
| 213 |
-
- `markdown`: The extracted text in Markdown format with preserved structure
|
| 214 |
-
- `inference_info`: JSON list tracking all OCR models applied to this dataset
|
| 215 |
-
|
| 216 |
-
## Usage
|
| 217 |
-
|
| 218 |
-
```python
|
| 219 |
-
from datasets import load_dataset
|
| 220 |
-
|
| 221 |
-
dataset = load_dataset("{{{{output_dataset_id}}}}", split="{split}")
|
| 222 |
-
for example in dataset:
|
| 223 |
-
print(example["markdown"])
|
| 224 |
-
break
|
| 225 |
-
```
|
| 226 |
-
|
| 227 |
-
## Reproduction
|
| 228 |
-
|
| 229 |
-
This dataset was generated using the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) ABot-OCR script:
|
| 230 |
-
|
| 231 |
-
```bash
|
| 232 |
-
uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/abot-ocr.py \\
|
| 233 |
-
{source_dataset} \\
|
| 234 |
-
<output-dataset> \\
|
| 235 |
-
--image-column {image_column} \\
|
| 236 |
-
--batch-size {batch_size} \\
|
| 237 |
-
--max-model-len {max_model_len} \\
|
| 238 |
-
--max-tokens {max_tokens} \\
|
| 239 |
-
--gpu-memory-utilization {gpu_memory_utilization}
|
| 240 |
-
```
|
| 241 |
-
|
| 242 |
-
Generated with 🤖 [UV Scripts](https://huggingface.co/uv-scripts)
|
| 243 |
-
"""
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
def main(
|
| 247 |
-
input_dataset: str,
|
| 248 |
-
output_dataset: str,
|
| 249 |
-
image_column: str = "image",
|
| 250 |
-
batch_size: int = 16,
|
| 251 |
-
model: str = "acvlab/ABot-OCR",
|
| 252 |
-
max_model_len: int = 16384,
|
| 253 |
-
max_tokens: int = 8192,
|
| 254 |
-
gpu_memory_utilization: float = 0.8,
|
| 255 |
-
hf_token: str = None,
|
| 256 |
-
split: str = "train",
|
| 257 |
-
max_samples: int = None,
|
| 258 |
-
private: bool = False,
|
| 259 |
-
shuffle: bool = False,
|
| 260 |
-
seed: int = 42,
|
| 261 |
-
verbose: bool = False,
|
| 262 |
-
):
|
| 263 |
-
"""Process images from a HF dataset through the ABot-OCR model."""
|
| 264 |
-
|
| 265 |
-
# Check CUDA availability first
|
| 266 |
-
check_cuda_availability()
|
| 267 |
-
|
| 268 |
-
# Track processing start time
|
| 269 |
-
start_time = datetime.now()
|
| 270 |
-
|
| 271 |
-
# Enable high-performance Xet downloads
|
| 272 |
-
os.environ["HF_XET_HIGH_PERFORMANCE"] = "1"
|
| 273 |
-
|
| 274 |
-
# Login to HF if token provided
|
| 275 |
-
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
|
| 276 |
-
if HF_TOKEN:
|
| 277 |
-
login(token=HF_TOKEN)
|
| 278 |
-
|
| 279 |
-
# Load dataset
|
| 280 |
-
logger.info(f"Loading dataset: {input_dataset}")
|
| 281 |
-
dataset = load_dataset(input_dataset, split=split)
|
| 282 |
-
|
| 283 |
-
# Validate image column
|
| 284 |
-
if image_column not in dataset.column_names:
|
| 285 |
-
raise ValueError(
|
| 286 |
-
f"Column '{image_column}' not found. Available: {dataset.column_names}"
|
| 287 |
-
)
|
| 288 |
-
|
| 289 |
-
# Shuffle if requested
|
| 290 |
-
if shuffle:
|
| 291 |
-
logger.info(f"Shuffling dataset with seed {seed}")
|
| 292 |
-
dataset = dataset.shuffle(seed=seed)
|
| 293 |
-
|
| 294 |
-
# Limit samples if requested
|
| 295 |
-
if max_samples:
|
| 296 |
-
dataset = dataset.select(range(min(max_samples, len(dataset))))
|
| 297 |
-
logger.info(f"Limited to {len(dataset)} samples")
|
| 298 |
-
|
| 299 |
-
# Initialize vLLM
|
| 300 |
-
logger.info(f"Initializing vLLM with model: {model}")
|
| 301 |
-
llm = LLM(
|
| 302 |
-
model=model,
|
| 303 |
-
trust_remote_code=True,
|
| 304 |
-
max_model_len=max_model_len,
|
| 305 |
-
gpu_memory_utilization=gpu_memory_utilization,
|
| 306 |
-
limit_mm_per_prompt={"image": 1},
|
| 307 |
-
enforce_eager=True, # avoid warmup kernel compilation (no nvcc in the image)
|
| 308 |
-
)
|
| 309 |
-
|
| 310 |
-
sampling_params = SamplingParams(
|
| 311 |
-
temperature=0.0, # Deterministic for OCR
|
| 312 |
-
max_tokens=max_tokens,
|
| 313 |
-
)
|
| 314 |
-
|
| 315 |
-
# Process images in batches
|
| 316 |
-
all_markdown = []
|
| 317 |
-
|
| 318 |
-
logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
|
| 319 |
-
|
| 320 |
-
for batch_indices in tqdm(
|
| 321 |
-
partition_all(batch_size, range(len(dataset))),
|
| 322 |
-
total=(len(dataset) + batch_size - 1) // batch_size,
|
| 323 |
-
desc="OCR processing",
|
| 324 |
-
):
|
| 325 |
-
batch_indices = list(batch_indices)
|
| 326 |
-
batch_images = [dataset[i][image_column] for i in batch_indices]
|
| 327 |
-
|
| 328 |
-
try:
|
| 329 |
-
batch_messages = [make_ocr_message(img) for img in batch_images]
|
| 330 |
-
outputs = llm.chat(batch_messages, sampling_params)
|
| 331 |
-
for output in outputs:
|
| 332 |
-
markdown_text = post_process_text(output.outputs[0].text.strip())
|
| 333 |
-
all_markdown.append(markdown_text)
|
| 334 |
-
except Exception as e:
|
| 335 |
-
logger.error(f"Error processing batch: {e}")
|
| 336 |
-
all_markdown.extend(["[OCR FAILED]"] * len(batch_images))
|
| 337 |
-
|
| 338 |
-
# Add markdown column to dataset
|
| 339 |
-
logger.info("Adding markdown column to dataset")
|
| 340 |
-
dataset = dataset.add_column("markdown", all_markdown)
|
| 341 |
-
|
| 342 |
-
# Handle inference_info tracking
|
| 343 |
-
logger.info("Updating inference_info...")
|
| 344 |
-
|
| 345 |
-
inference_entry = {
|
| 346 |
-
"model_id": model,
|
| 347 |
-
"model_name": "ABot-OCR",
|
| 348 |
-
"column_name": "markdown",
|
| 349 |
-
"timestamp": datetime.now().isoformat(),
|
| 350 |
-
"batch_size": batch_size,
|
| 351 |
-
"max_tokens": max_tokens,
|
| 352 |
-
"gpu_memory_utilization": gpu_memory_utilization,
|
| 353 |
-
"max_model_len": max_model_len,
|
| 354 |
-
"script": "abot-ocr.py",
|
| 355 |
-
"script_url": "https://huggingface.co/datasets/uv-scripts/ocr/raw/main/abot-ocr.py",
|
| 356 |
-
}
|
| 357 |
-
|
| 358 |
-
if "inference_info" in dataset.column_names:
|
| 359 |
-
logger.info("Updating existing inference_info column")
|
| 360 |
-
|
| 361 |
-
def update_inference_info(example):
|
| 362 |
-
try:
|
| 363 |
-
existing_info = (
|
| 364 |
-
json.loads(example["inference_info"])
|
| 365 |
-
if example["inference_info"]
|
| 366 |
-
else []
|
| 367 |
-
)
|
| 368 |
-
except (json.JSONDecodeError, TypeError):
|
| 369 |
-
existing_info = []
|
| 370 |
-
existing_info.append(inference_entry)
|
| 371 |
-
return {"inference_info": json.dumps(existing_info)}
|
| 372 |
-
|
| 373 |
-
dataset = dataset.map(update_inference_info)
|
| 374 |
-
else:
|
| 375 |
-
logger.info("Creating new inference_info column")
|
| 376 |
-
inference_list = [json.dumps([inference_entry])] * len(dataset)
|
| 377 |
-
dataset = dataset.add_column("inference_info", inference_list)
|
| 378 |
-
|
| 379 |
-
# Push to hub
|
| 380 |
-
logger.info(f"Pushing to {output_dataset}")
|
| 381 |
-
dataset.push_to_hub(output_dataset, private=private, token=HF_TOKEN)
|
| 382 |
-
|
| 383 |
-
# Calculate processing time
|
| 384 |
-
end_time = datetime.now()
|
| 385 |
-
processing_duration = end_time - start_time
|
| 386 |
-
processing_time = f"{processing_duration.total_seconds() / 60:.1f} minutes"
|
| 387 |
-
|
| 388 |
-
# Create and push dataset card
|
| 389 |
-
logger.info("Creating dataset card...")
|
| 390 |
-
card_content = create_dataset_card(
|
| 391 |
-
source_dataset=input_dataset,
|
| 392 |
-
model=model,
|
| 393 |
-
num_samples=len(dataset),
|
| 394 |
-
processing_time=processing_time,
|
| 395 |
-
batch_size=batch_size,
|
| 396 |
-
max_model_len=max_model_len,
|
| 397 |
-
max_tokens=max_tokens,
|
| 398 |
-
gpu_memory_utilization=gpu_memory_utilization,
|
| 399 |
-
image_column=image_column,
|
| 400 |
-
split=split,
|
| 401 |
-
)
|
| 402 |
-
|
| 403 |
-
card = DatasetCard(card_content)
|
| 404 |
-
card.push_to_hub(output_dataset, token=HF_TOKEN)
|
| 405 |
-
logger.info("✅ Dataset card created and pushed!")
|
| 406 |
-
|
| 407 |
-
logger.info("✅ OCR conversion complete!")
|
| 408 |
-
logger.info(
|
| 409 |
-
f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
|
| 410 |
-
)
|
| 411 |
-
|
| 412 |
-
if verbose:
|
| 413 |
-
import importlib.metadata
|
| 414 |
-
|
| 415 |
-
logger.info("--- Resolved package versions ---")
|
| 416 |
-
for pkg in ["vllm", "transformers", "torch", "datasets", "pyarrow", "pillow"]:
|
| 417 |
-
try:
|
| 418 |
-
logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
|
| 419 |
-
except importlib.metadata.PackageNotFoundError:
|
| 420 |
-
logger.info(f" {pkg}: not installed")
|
| 421 |
-
logger.info("--- End versions ---")
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
if __name__ == "__main__":
|
| 425 |
-
# Show example usage if no arguments
|
| 426 |
-
if len(sys.argv) == 1:
|
| 427 |
-
print("=" * 80)
|
| 428 |
-
print("ABot-OCR to Markdown Converter")
|
| 429 |
-
print("=" * 80)
|
| 430 |
-
print("\nConverts document images to structured Markdown using the")
|
| 431 |
-
print("ABot-OCR model (Qwen3-VL based) with vLLM acceleration.")
|
| 432 |
-
print("\nFeatures:")
|
| 433 |
-
print("- Document structure preserved (headings, paragraphs, lists)")
|
| 434 |
-
print("- LaTeX equation recognition (inline \\( \\) and block \\[ \\])")
|
| 435 |
-
print("- Table extraction as HTML")
|
| 436 |
-
print("\nExample usage:")
|
| 437 |
-
print("\n1. Basic OCR conversion:")
|
| 438 |
-
print(" uv run abot-ocr.py document-images markdown-docs")
|
| 439 |
-
print("\n2. Process a subset for testing:")
|
| 440 |
-
print(" uv run abot-ocr.py large-dataset test-output --max-samples 10")
|
| 441 |
-
print("\n3. Running on HF Jobs (use the pre-built vLLM image for flashinfer kernels):")
|
| 442 |
-
print(" hf jobs uv run --flavor l4x1 \\")
|
| 443 |
-
print(" --image vllm/vllm-openai:latest \\")
|
| 444 |
-
print(
|
| 445 |
-
" --python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\"
|
| 446 |
-
)
|
| 447 |
-
print(" -s HF_TOKEN \\")
|
| 448 |
-
print(
|
| 449 |
-
" https://huggingface.co/datasets/uv-scripts/ocr/raw/main/abot-ocr.py \\"
|
| 450 |
-
)
|
| 451 |
-
print(" your-document-dataset \\")
|
| 452 |
-
print(" your-markdown-output \\")
|
| 453 |
-
print(" --max-samples 10")
|
| 454 |
-
print("\n" + "=" * 80)
|
| 455 |
-
print("\nFor full help, run: uv run abot-ocr.py --help")
|
| 456 |
-
sys.exit(0)
|
| 457 |
-
|
| 458 |
-
parser = argparse.ArgumentParser(
|
| 459 |
-
description="OCR images to Markdown using ABot-OCR (Qwen3-VL)",
|
| 460 |
-
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 461 |
-
epilog="""
|
| 462 |
-
Examples:
|
| 463 |
-
# Basic usage
|
| 464 |
-
uv run abot-ocr.py my-images-dataset ocr-results
|
| 465 |
-
|
| 466 |
-
# With specific image column
|
| 467 |
-
uv run abot-ocr.py documents extracted-text --image-column scan
|
| 468 |
-
|
| 469 |
-
# Process subset for testing
|
| 470 |
-
uv run abot-ocr.py large-dataset test-output --max-samples 100
|
| 471 |
-
|
| 472 |
-
# Random sample from ordered dataset
|
| 473 |
-
uv run abot-ocr.py ordered-dataset random-sample --max-samples 50 --shuffle
|
| 474 |
-
""",
|
| 475 |
-
)
|
| 476 |
-
|
| 477 |
-
parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
|
| 478 |
-
parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
|
| 479 |
-
parser.add_argument(
|
| 480 |
-
"--image-column",
|
| 481 |
-
default="image",
|
| 482 |
-
help="Column containing images (default: image)",
|
| 483 |
-
)
|
| 484 |
-
parser.add_argument(
|
| 485 |
-
"--batch-size",
|
| 486 |
-
type=int,
|
| 487 |
-
default=16,
|
| 488 |
-
help="Batch size for processing (default: 16)",
|
| 489 |
-
)
|
| 490 |
-
parser.add_argument(
|
| 491 |
-
"--model",
|
| 492 |
-
default="acvlab/ABot-OCR",
|
| 493 |
-
help="Model to use (default: acvlab/ABot-OCR)",
|
| 494 |
-
)
|
| 495 |
-
parser.add_argument(
|
| 496 |
-
"--max-model-len",
|
| 497 |
-
type=int,
|
| 498 |
-
default=16384,
|
| 499 |
-
help="Maximum model context length (default: 16384)",
|
| 500 |
-
)
|
| 501 |
-
parser.add_argument(
|
| 502 |
-
"--max-tokens",
|
| 503 |
-
type=int,
|
| 504 |
-
default=8192,
|
| 505 |
-
help="Maximum tokens to generate (default: 8192)",
|
| 506 |
-
)
|
| 507 |
-
parser.add_argument(
|
| 508 |
-
"--gpu-memory-utilization",
|
| 509 |
-
type=float,
|
| 510 |
-
default=0.8,
|
| 511 |
-
help="GPU memory utilization (default: 0.8)",
|
| 512 |
-
)
|
| 513 |
-
parser.add_argument("--hf-token", help="Hugging Face API token")
|
| 514 |
-
parser.add_argument(
|
| 515 |
-
"--split", default="train", help="Dataset split to use (default: train)"
|
| 516 |
-
)
|
| 517 |
-
parser.add_argument(
|
| 518 |
-
"--max-samples",
|
| 519 |
-
type=int,
|
| 520 |
-
help="Maximum number of samples to process (for testing)",
|
| 521 |
-
)
|
| 522 |
-
parser.add_argument(
|
| 523 |
-
"--private", action="store_true", help="Make output dataset private"
|
| 524 |
-
)
|
| 525 |
-
parser.add_argument(
|
| 526 |
-
"--shuffle",
|
| 527 |
-
action="store_true",
|
| 528 |
-
help="Shuffle the dataset before processing (useful for random sampling)",
|
| 529 |
-
)
|
| 530 |
-
parser.add_argument(
|
| 531 |
-
"--seed",
|
| 532 |
-
type=int,
|
| 533 |
-
default=42,
|
| 534 |
-
help="Random seed for shuffling (default: 42)",
|
| 535 |
-
)
|
| 536 |
-
parser.add_argument(
|
| 537 |
-
"--verbose",
|
| 538 |
-
action="store_true",
|
| 539 |
-
help="Log resolved package versions after processing (useful for pinning deps)",
|
| 540 |
-
)
|
| 541 |
-
|
| 542 |
-
args = parser.parse_args()
|
| 543 |
-
|
| 544 |
-
main(
|
| 545 |
-
input_dataset=args.input_dataset,
|
| 546 |
-
output_dataset=args.output_dataset,
|
| 547 |
-
image_column=args.image_column,
|
| 548 |
-
batch_size=args.batch_size,
|
| 549 |
-
model=args.model,
|
| 550 |
-
max_model_len=args.max_model_len,
|
| 551 |
-
max_tokens=args.max_tokens,
|
| 552 |
-
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 553 |
-
hf_token=args.hf_token,
|
| 554 |
-
split=args.split,
|
| 555 |
-
max_samples=args.max_samples,
|
| 556 |
-
private=args.private,
|
| 557 |
-
shuffle=args.shuffle,
|
| 558 |
-
seed=args.seed,
|
| 559 |
-
verbose=args.verbose,
|
| 560 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
deepseek-ocr-vllm.py
CHANGED
|
@@ -48,10 +48,6 @@ from huggingface_hub import DatasetCard, login
|
|
| 48 |
from PIL import Image
|
| 49 |
from toolz import partition_all
|
| 50 |
from tqdm.auto import tqdm
|
| 51 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 52 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 53 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 54 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 55 |
from vllm import LLM, SamplingParams
|
| 56 |
from vllm.model_executor.models.deepseek_ocr import NGramPerReqLogitsProcessor
|
| 57 |
|
|
|
|
| 48 |
from PIL import Image
|
| 49 |
from toolz import partition_all
|
| 50 |
from tqdm.auto import tqdm
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
from vllm import LLM, SamplingParams
|
| 52 |
from vllm.model_executor.models.deepseek_ocr import NGramPerReqLogitsProcessor
|
| 53 |
|
deepseek-ocr2-vllm.py
CHANGED
|
@@ -59,10 +59,6 @@ from huggingface_hub import DatasetCard, login
|
|
| 59 |
from PIL import Image
|
| 60 |
from toolz import partition_all
|
| 61 |
from tqdm.auto import tqdm
|
| 62 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 63 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 64 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 65 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 66 |
from vllm import LLM, SamplingParams
|
| 67 |
from vllm.model_executor.models.deepseek_ocr import NGramPerReqLogitsProcessor
|
| 68 |
|
|
|
|
| 59 |
from PIL import Image
|
| 60 |
from toolz import partition_all
|
| 61 |
from tqdm.auto import tqdm
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
from vllm import LLM, SamplingParams
|
| 63 |
from vllm.model_executor.models.deepseek_ocr import NGramPerReqLogitsProcessor
|
| 64 |
|
dots-mocr.py → dots-ocr-1.5.py
RENAMED
|
@@ -13,27 +13,23 @@
|
|
| 13 |
# ///
|
| 14 |
|
| 15 |
"""
|
| 16 |
-
Convert document images to markdown using
|
| 17 |
|
| 18 |
-
|
| 19 |
-
on 100+ languages.
|
| 20 |
-
|
| 21 |
-
grounding, recognition, semantic understanding, and interactive dialogue.
|
| 22 |
|
| 23 |
Features:
|
| 24 |
- Multilingual support (100+ languages)
|
| 25 |
- Table extraction and formatting
|
| 26 |
- Formula recognition
|
| 27 |
- Layout-aware text extraction
|
| 28 |
-
- Web screen parsing
|
| 29 |
-
- Scene text spotting
|
| 30 |
-
- SVG code generation (
|
| 31 |
-
|
| 32 |
-
Model: rednote-hilab/dots.
|
| 33 |
-
|
| 34 |
-
vLLM: Officially integrated since v0.11.0
|
| 35 |
-
GitHub: https://github.com/rednote-hilab/dots.mocr
|
| 36 |
-
Paper: https://arxiv.org/abs/2603.13032
|
| 37 |
"""
|
| 38 |
|
| 39 |
import argparse
|
|
@@ -50,13 +46,9 @@ from typing import Any, Dict, List, Union
|
|
| 50 |
import torch
|
| 51 |
from datasets import load_dataset
|
| 52 |
from huggingface_hub import DatasetCard, login
|
| 53 |
-
from PIL import Image
|
| 54 |
from toolz import partition_all
|
| 55 |
from tqdm.auto import tqdm
|
| 56 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 57 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 58 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 59 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 60 |
from vllm import LLM, SamplingParams
|
| 61 |
|
| 62 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -64,8 +56,8 @@ logger = logging.getLogger(__name__)
|
|
| 64 |
|
| 65 |
|
| 66 |
# ────────────────────────────────────────────────────────────────
|
| 67 |
-
#
|
| 68 |
-
# Source: https://github.com/rednote-hilab/dots.
|
| 69 |
# ────────────────────────────────────────────────────────────────
|
| 70 |
|
| 71 |
PROMPT_TEMPLATES = {
|
|
@@ -88,19 +80,11 @@ PROMPT_TEMPLATES = {
|
|
| 88 |
|
| 89 |
5. Final Output: The entire output must be a single JSON object.
|
| 90 |
""",
|
| 91 |
-
# NOTE: Bboxes from layout-all/layout-only are in the resized image coordinate
|
| 92 |
-
# space (Qwen2VLImageProcessor smart_resize: max_pixels=11289600, factor=28),
|
| 93 |
-
# NOT original image coordinates. To map back, compute:
|
| 94 |
-
# resized_h, resized_w = smart_resize(orig_h, orig_w)
|
| 95 |
-
# scale_x, scale_y = orig_w / resized_w, orig_h / resized_h
|
| 96 |
"layout-only": """Please output the layout information from this PDF image, including each layout's bbox and its category. The bbox should be in the format [x1, y1, x2, y2]. The layout categories for the PDF document include ['Caption', 'Footnote', 'Formula', 'List-item', 'Page-footer', 'Page-header', 'Picture', 'Section-header', 'Table', 'Text', 'Title']. Do not output the corresponding text. The layout result should be in JSON format.""",
|
|
|
|
| 97 |
"web-parsing": """Parsing the layout info of this webpage image with format json:\n""",
|
| 98 |
"scene-spotting": """Detect and recognize the text in the image.""",
|
| 99 |
"grounding-ocr": """Extract text from the given bounding box on the image (format: [x1, y1, x2, y2]).\nBounding Box:\n""",
|
| 100 |
-
# SVG code generation — {width} and {height} are replaced with actual image dimensions.
|
| 101 |
-
# For best results, use --model rednote-hilab/dots.mocr-svg
|
| 102 |
-
# Uses higher temperature (0.9) and top_p (1.0) per official recommendation.
|
| 103 |
-
"svg": """Please generate the SVG code based on the image. viewBox="0 0 {width} {height}" """,
|
| 104 |
"general": """ """,
|
| 105 |
}
|
| 106 |
|
|
@@ -133,12 +117,6 @@ def make_ocr_message(
|
|
| 133 |
# Convert to RGB
|
| 134 |
pil_img = pil_img.convert("RGB")
|
| 135 |
|
| 136 |
-
# For SVG mode, inject actual image dimensions into the prompt
|
| 137 |
-
if "{width}" in prompt and "{height}" in prompt:
|
| 138 |
-
prompt = prompt.replace("{width}", str(pil_img.width)).replace(
|
| 139 |
-
"{height}", str(pil_img.height)
|
| 140 |
-
)
|
| 141 |
-
|
| 142 |
# Convert to base64 data URI
|
| 143 |
buf = io.BytesIO()
|
| 144 |
pil_img.save(buf, format="PNG")
|
|
@@ -176,7 +154,7 @@ def create_dataset_card(
|
|
| 176 |
tags:
|
| 177 |
- ocr
|
| 178 |
- document-processing
|
| 179 |
-
- dots-
|
| 180 |
- multilingual
|
| 181 |
- markdown
|
| 182 |
- uv-script
|
|
@@ -185,7 +163,7 @@ tags:
|
|
| 185 |
|
| 186 |
# Document OCR using {model_name}
|
| 187 |
|
| 188 |
-
This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using
|
| 189 |
|
| 190 |
## Processing Details
|
| 191 |
|
|
@@ -208,14 +186,13 @@ This dataset contains OCR results from images in [{source_dataset}](https://hugg
|
|
| 208 |
|
| 209 |
## Model Information
|
| 210 |
|
| 211 |
-
|
| 212 |
- 100+ Languages — Multilingual document support
|
| 213 |
- Table extraction — Structured data recognition
|
| 214 |
- Formulas — Mathematical notation preservation
|
| 215 |
- Layout-aware — Reading order and structure preservation
|
| 216 |
- Web screen parsing — Webpage layout analysis
|
| 217 |
- Scene text spotting — Text detection in natural scenes
|
| 218 |
-
- SVG code generation — Charts, UI layouts, scientific figures to SVG
|
| 219 |
|
| 220 |
## Dataset Structure
|
| 221 |
|
|
@@ -245,10 +222,10 @@ for info in inference_info:
|
|
| 245 |
|
| 246 |
## Reproduction
|
| 247 |
|
| 248 |
-
This dataset was generated using the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr)
|
| 249 |
|
| 250 |
```bash
|
| 251 |
-
uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/dots-
|
| 252 |
{source_dataset} \\
|
| 253 |
<output-dataset> \\
|
| 254 |
--image-column {image_column} \\
|
|
@@ -268,7 +245,7 @@ def main(
|
|
| 268 |
output_dataset: str,
|
| 269 |
image_column: str = "image",
|
| 270 |
batch_size: int = 16,
|
| 271 |
-
model: str = "rednote-hilab/dots.
|
| 272 |
max_model_len: int = 24000,
|
| 273 |
max_tokens: int = 24000,
|
| 274 |
gpu_memory_utilization: float = 0.9,
|
|
@@ -287,7 +264,7 @@ def main(
|
|
| 287 |
top_p: float = 0.9,
|
| 288 |
verbose: bool = False,
|
| 289 |
):
|
| 290 |
-
"""Process images from HF dataset through
|
| 291 |
|
| 292 |
# Check CUDA availability first
|
| 293 |
check_cuda_availability()
|
|
@@ -338,12 +315,6 @@ def main(
|
|
| 338 |
gpu_memory_utilization=gpu_memory_utilization,
|
| 339 |
)
|
| 340 |
|
| 341 |
-
# SVG mode uses higher temperature/top_p per official recommendation
|
| 342 |
-
if prompt_mode == "svg" and temperature == 0.1 and top_p == 0.9:
|
| 343 |
-
logger.info("SVG mode: using recommended temperature=0.9, top_p=1.0")
|
| 344 |
-
temperature = 0.9
|
| 345 |
-
top_p = 1.0
|
| 346 |
-
|
| 347 |
sampling_params = SamplingParams(
|
| 348 |
temperature=temperature,
|
| 349 |
top_p=top_p,
|
|
@@ -359,35 +330,17 @@ def main(
|
|
| 359 |
for batch_indices in tqdm(
|
| 360 |
partition_all(batch_size, range(len(dataset))),
|
| 361 |
total=(len(dataset) + batch_size - 1) // batch_size,
|
| 362 |
-
desc="
|
| 363 |
):
|
| 364 |
batch_indices = list(batch_indices)
|
| 365 |
-
|
| 366 |
-
# Fetch images first, with per-batch fallback for unreadable files.
|
| 367 |
-
# One corrupt image used to take down the entire run via the list
|
| 368 |
-
# comprehension; now we mark the whole batch as skipped and continue.
|
| 369 |
-
try:
|
| 370 |
-
batch_images = [dataset[i][image_column] for i in batch_indices]
|
| 371 |
-
except (UnidentifiedImageError, OSError) as e:
|
| 372 |
-
logger.warning(
|
| 373 |
-
f"Skipping batch of {len(batch_indices)} — unreadable image "
|
| 374 |
-
f"in batch: {type(e).__name__}: {e}"
|
| 375 |
-
)
|
| 376 |
-
all_outputs.extend(
|
| 377 |
-
["[OCR SKIPPED — UNREADABLE IMAGE]"] * len(batch_indices)
|
| 378 |
-
)
|
| 379 |
-
continue
|
| 380 |
|
| 381 |
try:
|
| 382 |
# Create messages for batch
|
| 383 |
batch_messages = [make_ocr_message(img, prompt) for img in batch_images]
|
| 384 |
|
| 385 |
-
# Process with vLLM
|
| 386 |
-
outputs = llm.chat(
|
| 387 |
-
batch_messages,
|
| 388 |
-
sampling_params,
|
| 389 |
-
chat_template_content_format="string",
|
| 390 |
-
)
|
| 391 |
|
| 392 |
# Extract outputs
|
| 393 |
for output in outputs:
|
|
@@ -410,7 +363,7 @@ def main(
|
|
| 410 |
# Handle inference_info tracking (for multi-model comparisons)
|
| 411 |
inference_entry = {
|
| 412 |
"model_id": model,
|
| 413 |
-
"model_name": "
|
| 414 |
"column_name": output_column,
|
| 415 |
"timestamp": datetime.now().isoformat(),
|
| 416 |
"prompt_mode": prompt_mode if not custom_prompt else "custom",
|
|
@@ -491,7 +444,7 @@ def main(
|
|
| 491 |
card = DatasetCard(card_content)
|
| 492 |
card.push_to_hub(output_dataset, token=HF_TOKEN)
|
| 493 |
|
| 494 |
-
logger.info("
|
| 495 |
logger.info(
|
| 496 |
f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
|
| 497 |
)
|
|
@@ -513,83 +466,77 @@ if __name__ == "__main__":
|
|
| 513 |
# Show example usage if no arguments
|
| 514 |
if len(sys.argv) == 1:
|
| 515 |
print("=" * 80)
|
| 516 |
-
print("
|
| 517 |
print("=" * 80)
|
| 518 |
-
print("\n3B multilingual OCR model
|
| 519 |
print("\nFeatures:")
|
| 520 |
print("- Multilingual support (100+ languages)")
|
| 521 |
print("- Fast processing with vLLM")
|
| 522 |
print("- Table extraction and formatting")
|
| 523 |
print("- Formula recognition")
|
| 524 |
print("- Layout-aware text extraction")
|
| 525 |
-
print("- Web screen parsing")
|
| 526 |
-
print("- Scene text spotting")
|
| 527 |
-
print("- SVG code generation (charts, UI, figures)")
|
| 528 |
print("\nPrompt modes:")
|
| 529 |
-
print(" ocr
|
| 530 |
-
print(" layout-all
|
| 531 |
-
print(" layout-only
|
| 532 |
-
print(" web-parsing
|
| 533 |
print(" scene-spotting - Scene text detection")
|
| 534 |
-
print(" grounding-ocr
|
| 535 |
-
print("
|
| 536 |
-
print(" general - Free-form (use with --custom-prompt)")
|
| 537 |
print("\nExample usage:")
|
| 538 |
print("\n1. Basic OCR:")
|
| 539 |
-
print(" uv run dots-
|
| 540 |
-
print("\n2.
|
| 541 |
-
print(
|
| 542 |
-
|
| 543 |
-
)
|
| 544 |
-
print("\n3. Web screen parsing:")
|
| 545 |
-
print(" uv run dots-mocr.py screenshots parsed --prompt-mode web-parsing")
|
| 546 |
print("\n4. Layout analysis with structure:")
|
| 547 |
-
print(" uv run dots-
|
| 548 |
print("\n5. Running on HF Jobs:")
|
| 549 |
print(" hf jobs uv run --flavor l4x1 \\")
|
| 550 |
print(" -s HF_TOKEN \\")
|
| 551 |
print(
|
| 552 |
-
" https://huggingface.co/datasets/uv-scripts/ocr/raw/main/dots-
|
| 553 |
)
|
| 554 |
print(" input-dataset output-dataset")
|
| 555 |
print("\n" + "=" * 80)
|
| 556 |
-
print("\nFor full help, run: uv run dots-
|
| 557 |
sys.exit(0)
|
| 558 |
|
| 559 |
parser = argparse.ArgumentParser(
|
| 560 |
-
description="Document OCR using
|
| 561 |
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 562 |
epilog="""
|
| 563 |
-
Prompt Modes (official
|
| 564 |
ocr - Simple text extraction (default)
|
| 565 |
layout-all - Layout analysis with bboxes, categories, and text (JSON output)
|
| 566 |
layout-only - Layout detection with bboxes and categories only (JSON output)
|
| 567 |
-
web-parsing - Webpage layout analysis (JSON output)
|
| 568 |
-
scene-spotting - Scene text detection and recognition
|
| 569 |
-
grounding-ocr - Extract text from bounding box region
|
| 570 |
-
|
| 571 |
-
general - Free-form QA (use with --custom-prompt)
|
| 572 |
|
| 573 |
SVG Code Generation:
|
| 574 |
-
|
| 575 |
-
--
|
| 576 |
-
SVG mode automatically uses temperature=0.9, top_p=1.0 unless overridden.
|
| 577 |
|
| 578 |
Examples:
|
| 579 |
# Basic text OCR (default)
|
| 580 |
-
uv run dots-
|
| 581 |
-
|
| 582 |
-
# SVG generation with optimized variant
|
| 583 |
-
uv run dots-mocr.py charts svg-out --prompt-mode svg --model rednote-hilab/dots.mocr-svg
|
| 584 |
|
| 585 |
# Web screen parsing
|
| 586 |
-
uv run dots-
|
|
|
|
|
|
|
|
|
|
| 587 |
|
| 588 |
# Full layout analysis with structure
|
| 589 |
-
uv run dots-
|
| 590 |
|
| 591 |
# Random sampling for testing
|
| 592 |
-
uv run dots-
|
| 593 |
""",
|
| 594 |
)
|
| 595 |
|
|
@@ -608,8 +555,8 @@ Examples:
|
|
| 608 |
)
|
| 609 |
parser.add_argument(
|
| 610 |
"--model",
|
| 611 |
-
default="rednote-hilab/dots.
|
| 612 |
-
help="Model to use (default: rednote-hilab/dots.
|
| 613 |
)
|
| 614 |
parser.add_argument(
|
| 615 |
"--max-model-len",
|
|
|
|
| 13 |
# ///
|
| 14 |
|
| 15 |
"""
|
| 16 |
+
Convert document images to markdown using DoTS.ocr-1.5 with vLLM.
|
| 17 |
|
| 18 |
+
DoTS.ocr-1.5 is a 3B multilingual document parsing model with SOTA performance
|
| 19 |
+
on 100+ languages. Compared to v1 (1.7B), it adds web screen parsing, scene text
|
| 20 |
+
spotting, SVG code generation, and stronger multilingual document parsing.
|
|
|
|
| 21 |
|
| 22 |
Features:
|
| 23 |
- Multilingual support (100+ languages)
|
| 24 |
- Table extraction and formatting
|
| 25 |
- Formula recognition
|
| 26 |
- Layout-aware text extraction
|
| 27 |
+
- Web screen parsing (NEW in v1.5)
|
| 28 |
+
- Scene text spotting (NEW in v1.5)
|
| 29 |
+
- SVG code generation (requires dots.ocr-1.5-svg variant)
|
| 30 |
+
|
| 31 |
+
Model: rednote-hilab/dots.ocr-1.5
|
| 32 |
+
vLLM: Officially supported (same DotsOCRForCausalLM architecture as v1)
|
|
|
|
|
|
|
|
|
|
| 33 |
"""
|
| 34 |
|
| 35 |
import argparse
|
|
|
|
| 46 |
import torch
|
| 47 |
from datasets import load_dataset
|
| 48 |
from huggingface_hub import DatasetCard, login
|
| 49 |
+
from PIL import Image
|
| 50 |
from toolz import partition_all
|
| 51 |
from tqdm.auto import tqdm
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
from vllm import LLM, SamplingParams
|
| 53 |
|
| 54 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 56 |
|
| 57 |
|
| 58 |
# ────────────────────────────────────────────────────────────────
|
| 59 |
+
# DoTS OCR 1.5 Prompt Templates (from official dots.ocr repo)
|
| 60 |
+
# Source: https://github.com/rednote-hilab/dots.ocr/blob/master/dots_ocr/utils/prompts.py
|
| 61 |
# ────────────────────────────────────────────────────────────────
|
| 62 |
|
| 63 |
PROMPT_TEMPLATES = {
|
|
|
|
| 80 |
|
| 81 |
5. Final Output: The entire output must be a single JSON object.
|
| 82 |
""",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
"layout-only": """Please output the layout information from this PDF image, including each layout's bbox and its category. The bbox should be in the format [x1, y1, x2, y2]. The layout categories for the PDF document include ['Caption', 'Footnote', 'Formula', 'List-item', 'Page-footer', 'Page-header', 'Picture', 'Section-header', 'Table', 'Text', 'Title']. Do not output the corresponding text. The layout result should be in JSON format.""",
|
| 84 |
+
# NEW in v1.5:
|
| 85 |
"web-parsing": """Parsing the layout info of this webpage image with format json:\n""",
|
| 86 |
"scene-spotting": """Detect and recognize the text in the image.""",
|
| 87 |
"grounding-ocr": """Extract text from the given bounding box on the image (format: [x1, y1, x2, y2]).\nBounding Box:\n""",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
"general": """ """,
|
| 89 |
}
|
| 90 |
|
|
|
|
| 117 |
# Convert to RGB
|
| 118 |
pil_img = pil_img.convert("RGB")
|
| 119 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
# Convert to base64 data URI
|
| 121 |
buf = io.BytesIO()
|
| 122 |
pil_img.save(buf, format="PNG")
|
|
|
|
| 154 |
tags:
|
| 155 |
- ocr
|
| 156 |
- document-processing
|
| 157 |
+
- dots-ocr-1.5
|
| 158 |
- multilingual
|
| 159 |
- markdown
|
| 160 |
- uv-script
|
|
|
|
| 163 |
|
| 164 |
# Document OCR using {model_name}
|
| 165 |
|
| 166 |
+
This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using DoTS.ocr-1.5, a 3B multilingual model with SOTA document parsing.
|
| 167 |
|
| 168 |
## Processing Details
|
| 169 |
|
|
|
|
| 186 |
|
| 187 |
## Model Information
|
| 188 |
|
| 189 |
+
DoTS.ocr-1.5 is a 3B multilingual document parsing model that excels at:
|
| 190 |
- 100+ Languages — Multilingual document support
|
| 191 |
- Table extraction — Structured data recognition
|
| 192 |
- Formulas — Mathematical notation preservation
|
| 193 |
- Layout-aware — Reading order and structure preservation
|
| 194 |
- Web screen parsing — Webpage layout analysis
|
| 195 |
- Scene text spotting — Text detection in natural scenes
|
|
|
|
| 196 |
|
| 197 |
## Dataset Structure
|
| 198 |
|
|
|
|
| 222 |
|
| 223 |
## Reproduction
|
| 224 |
|
| 225 |
+
This dataset was generated using the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) DoTS OCR 1.5 script:
|
| 226 |
|
| 227 |
```bash
|
| 228 |
+
uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/dots-ocr-1.5.py \\
|
| 229 |
{source_dataset} \\
|
| 230 |
<output-dataset> \\
|
| 231 |
--image-column {image_column} \\
|
|
|
|
| 245 |
output_dataset: str,
|
| 246 |
image_column: str = "image",
|
| 247 |
batch_size: int = 16,
|
| 248 |
+
model: str = "rednote-hilab/dots.ocr-1.5",
|
| 249 |
max_model_len: int = 24000,
|
| 250 |
max_tokens: int = 24000,
|
| 251 |
gpu_memory_utilization: float = 0.9,
|
|
|
|
| 264 |
top_p: float = 0.9,
|
| 265 |
verbose: bool = False,
|
| 266 |
):
|
| 267 |
+
"""Process images from HF dataset through DoTS.ocr-1.5 model."""
|
| 268 |
|
| 269 |
# Check CUDA availability first
|
| 270 |
check_cuda_availability()
|
|
|
|
| 315 |
gpu_memory_utilization=gpu_memory_utilization,
|
| 316 |
)
|
| 317 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
sampling_params = SamplingParams(
|
| 319 |
temperature=temperature,
|
| 320 |
top_p=top_p,
|
|
|
|
| 330 |
for batch_indices in tqdm(
|
| 331 |
partition_all(batch_size, range(len(dataset))),
|
| 332 |
total=(len(dataset) + batch_size - 1) // batch_size,
|
| 333 |
+
desc="DoTS.ocr-1.5 processing",
|
| 334 |
):
|
| 335 |
batch_indices = list(batch_indices)
|
| 336 |
+
batch_images = [dataset[i][image_column] for i in batch_indices]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
|
| 338 |
try:
|
| 339 |
# Create messages for batch
|
| 340 |
batch_messages = [make_ocr_message(img, prompt) for img in batch_images]
|
| 341 |
|
| 342 |
+
# Process with vLLM
|
| 343 |
+
outputs = llm.chat(batch_messages, sampling_params)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
|
| 345 |
# Extract outputs
|
| 346 |
for output in outputs:
|
|
|
|
| 363 |
# Handle inference_info tracking (for multi-model comparisons)
|
| 364 |
inference_entry = {
|
| 365 |
"model_id": model,
|
| 366 |
+
"model_name": "DoTS.ocr-1.5",
|
| 367 |
"column_name": output_column,
|
| 368 |
"timestamp": datetime.now().isoformat(),
|
| 369 |
"prompt_mode": prompt_mode if not custom_prompt else "custom",
|
|
|
|
| 444 |
card = DatasetCard(card_content)
|
| 445 |
card.push_to_hub(output_dataset, token=HF_TOKEN)
|
| 446 |
|
| 447 |
+
logger.info("DoTS.ocr-1.5 processing complete!")
|
| 448 |
logger.info(
|
| 449 |
f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
|
| 450 |
)
|
|
|
|
| 466 |
# Show example usage if no arguments
|
| 467 |
if len(sys.argv) == 1:
|
| 468 |
print("=" * 80)
|
| 469 |
+
print("DoTS.ocr-1.5 Document Processing")
|
| 470 |
print("=" * 80)
|
| 471 |
+
print("\n3B multilingual OCR model supporting 100+ languages")
|
| 472 |
print("\nFeatures:")
|
| 473 |
print("- Multilingual support (100+ languages)")
|
| 474 |
print("- Fast processing with vLLM")
|
| 475 |
print("- Table extraction and formatting")
|
| 476 |
print("- Formula recognition")
|
| 477 |
print("- Layout-aware text extraction")
|
| 478 |
+
print("- Web screen parsing (NEW in v1.5)")
|
| 479 |
+
print("- Scene text spotting (NEW in v1.5)")
|
|
|
|
| 480 |
print("\nPrompt modes:")
|
| 481 |
+
print(" ocr - Text extraction (default)")
|
| 482 |
+
print(" layout-all - Layout + bboxes + text (JSON)")
|
| 483 |
+
print(" layout-only - Layout + bboxes only (JSON)")
|
| 484 |
+
print(" web-parsing - Webpage layout analysis (JSON)")
|
| 485 |
print(" scene-spotting - Scene text detection")
|
| 486 |
+
print(" grounding-ocr - Text from bounding box region")
|
| 487 |
+
print(" general - Free-form (use with --custom-prompt)")
|
|
|
|
| 488 |
print("\nExample usage:")
|
| 489 |
print("\n1. Basic OCR:")
|
| 490 |
+
print(" uv run dots-ocr-1.5.py input-dataset output-dataset")
|
| 491 |
+
print("\n2. Web screen parsing:")
|
| 492 |
+
print(" uv run dots-ocr-1.5.py screenshots parsed --prompt-mode web-parsing")
|
| 493 |
+
print("\n3. Scene text spotting:")
|
| 494 |
+
print(" uv run dots-ocr-1.5.py photos detected --prompt-mode scene-spotting")
|
|
|
|
|
|
|
| 495 |
print("\n4. Layout analysis with structure:")
|
| 496 |
+
print(" uv run dots-ocr-1.5.py papers analyzed --prompt-mode layout-all")
|
| 497 |
print("\n5. Running on HF Jobs:")
|
| 498 |
print(" hf jobs uv run --flavor l4x1 \\")
|
| 499 |
print(" -s HF_TOKEN \\")
|
| 500 |
print(
|
| 501 |
+
" https://huggingface.co/datasets/uv-scripts/ocr/raw/main/dots-ocr-1.5.py \\"
|
| 502 |
)
|
| 503 |
print(" input-dataset output-dataset")
|
| 504 |
print("\n" + "=" * 80)
|
| 505 |
+
print("\nFor full help, run: uv run dots-ocr-1.5.py --help")
|
| 506 |
sys.exit(0)
|
| 507 |
|
| 508 |
parser = argparse.ArgumentParser(
|
| 509 |
+
description="Document OCR using DoTS.ocr-1.5 (3B multilingual model)",
|
| 510 |
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 511 |
epilog="""
|
| 512 |
+
Prompt Modes (official DoTS.ocr-1.5 prompts):
|
| 513 |
ocr - Simple text extraction (default)
|
| 514 |
layout-all - Layout analysis with bboxes, categories, and text (JSON output)
|
| 515 |
layout-only - Layout detection with bboxes and categories only (JSON output)
|
| 516 |
+
web-parsing - Webpage layout analysis (JSON output) [NEW in v1.5]
|
| 517 |
+
scene-spotting - Scene text detection and recognition [NEW in v1.5]
|
| 518 |
+
grounding-ocr - Extract text from bounding box region [NEW in v1.5]
|
| 519 |
+
general - Free-form QA (use with --custom-prompt) [NEW in v1.5]
|
|
|
|
| 520 |
|
| 521 |
SVG Code Generation:
|
| 522 |
+
For SVG output, use --model rednote-hilab/dots.ocr-1.5-svg with:
|
| 523 |
+
--custom-prompt 'Please generate the SVG code based on the image.'
|
|
|
|
| 524 |
|
| 525 |
Examples:
|
| 526 |
# Basic text OCR (default)
|
| 527 |
+
uv run dots-ocr-1.5.py my-docs analyzed-docs
|
|
|
|
|
|
|
|
|
|
| 528 |
|
| 529 |
# Web screen parsing
|
| 530 |
+
uv run dots-ocr-1.5.py screenshots parsed --prompt-mode web-parsing
|
| 531 |
+
|
| 532 |
+
# Scene text spotting
|
| 533 |
+
uv run dots-ocr-1.5.py photos spotted --prompt-mode scene-spotting
|
| 534 |
|
| 535 |
# Full layout analysis with structure
|
| 536 |
+
uv run dots-ocr-1.5.py papers structured --prompt-mode layout-all
|
| 537 |
|
| 538 |
# Random sampling for testing
|
| 539 |
+
uv run dots-ocr-1.5.py large-dataset test --max-samples 50 --shuffle
|
| 540 |
""",
|
| 541 |
)
|
| 542 |
|
|
|
|
| 555 |
)
|
| 556 |
parser.add_argument(
|
| 557 |
"--model",
|
| 558 |
+
default="rednote-hilab/dots.ocr-1.5",
|
| 559 |
+
help="Model to use (default: rednote-hilab/dots.ocr-1.5)",
|
| 560 |
)
|
| 561 |
parser.add_argument(
|
| 562 |
"--max-model-len",
|
dots-ocr.py
CHANGED
|
@@ -45,10 +45,6 @@ from huggingface_hub import DatasetCard, login
|
|
| 45 |
from PIL import Image
|
| 46 |
from toolz import partition_all
|
| 47 |
from tqdm.auto import tqdm
|
| 48 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 49 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 50 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 51 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 52 |
from vllm import LLM, SamplingParams
|
| 53 |
|
| 54 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 45 |
from PIL import Image
|
| 46 |
from toolz import partition_all
|
| 47 |
from tqdm.auto import tqdm
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
from vllm import LLM, SamplingParams
|
| 49 |
|
| 50 |
logging.basicConfig(level=logging.INFO)
|
examples/nls-index-card-v2.json
DELETED
|
@@ -1,13 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"image_type": ["index_card", "verso", "cover", "blank", "other"],
|
| 3 |
-
"heading": "verbatim-string",
|
| 4 |
-
"heading_type": ["person", "family", "corporate", "geographic", "subject"],
|
| 5 |
-
"epithet": "string",
|
| 6 |
-
"entries": [
|
| 7 |
-
{
|
| 8 |
-
"ms_no": "verbatim-string",
|
| 9 |
-
"folios": ["verbatim-string"],
|
| 10 |
-
"description": "string"
|
| 11 |
-
}
|
| 12 |
-
]
|
| 13 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
examples/nls-index-card-verbose.json
DELETED
|
@@ -1,13 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"image_type": ["index_card", "verso", "cover", "blank", "other"],
|
| 3 |
-
"main_heading_name": "verbatim-string",
|
| 4 |
-
"heading_category": ["person", "family", "corporate", "geographic", "subject"],
|
| 5 |
-
"epithet_title_or_occupation": "string",
|
| 6 |
-
"manuscript_references": [
|
| 7 |
-
{
|
| 8 |
-
"manuscript_number": "verbatim-string",
|
| 9 |
-
"folio_references": ["verbatim-string"],
|
| 10 |
-
"entry_description_with_date": "string"
|
| 11 |
-
}
|
| 12 |
-
]
|
| 13 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
falcon-ocr-bucket.py
DELETED
|
@@ -1,303 +0,0 @@
|
|
| 1 |
-
# /// script
|
| 2 |
-
# requires-python = ">=3.11"
|
| 3 |
-
# dependencies = [
|
| 4 |
-
# "pillow",
|
| 5 |
-
# "pymupdf",
|
| 6 |
-
# "torch>=2.5",
|
| 7 |
-
# "torchvision",
|
| 8 |
-
# "falcon-perception[ocr]",
|
| 9 |
-
# ]
|
| 10 |
-
# ///
|
| 11 |
-
|
| 12 |
-
"""
|
| 13 |
-
OCR images and PDFs from a directory using Falcon OCR, writing markdown files.
|
| 14 |
-
|
| 15 |
-
Designed to work with HF Buckets mounted as volumes via `hf jobs uv run -v ...`.
|
| 16 |
-
Reads images/PDFs from INPUT_DIR, runs Falcon OCR via the optimized falcon-perception
|
| 17 |
-
engine (CUDA graphs + paged inference), and writes one .md file per image (or per
|
| 18 |
-
PDF page) to OUTPUT_DIR, preserving directory structure.
|
| 19 |
-
|
| 20 |
-
Input: Output:
|
| 21 |
-
/input/page1.png -> /output/page1.md
|
| 22 |
-
/input/report.pdf -> /output/report/page_001.md
|
| 23 |
-
(3 pages) /output/report/page_002.md
|
| 24 |
-
/output/report/page_003.md
|
| 25 |
-
/input/sub/photo.jpg -> /output/sub/photo.md
|
| 26 |
-
|
| 27 |
-
Examples:
|
| 28 |
-
|
| 29 |
-
# Local test
|
| 30 |
-
uv run falcon-ocr-bucket.py ./test-images ./test-output
|
| 31 |
-
|
| 32 |
-
# HF Jobs with bucket volumes
|
| 33 |
-
hf jobs uv run --flavor l4x1 \\
|
| 34 |
-
-s HF_TOKEN \\
|
| 35 |
-
-v hf://buckets/user/ocr-input:/input:ro \\
|
| 36 |
-
-v hf://buckets/user/ocr-output:/output \\
|
| 37 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/falcon-ocr-bucket.py \\
|
| 38 |
-
/input /output
|
| 39 |
-
|
| 40 |
-
Model: tiiuae/Falcon-OCR (0.3B, 80.3% olmOCR, Apache 2.0)
|
| 41 |
-
Backend: falcon-perception (OCRInferenceEngine with CUDA graphs)
|
| 42 |
-
"""
|
| 43 |
-
|
| 44 |
-
import argparse
|
| 45 |
-
import logging
|
| 46 |
-
import sys
|
| 47 |
-
import time
|
| 48 |
-
from pathlib import Path
|
| 49 |
-
|
| 50 |
-
import torch
|
| 51 |
-
from PIL import Image
|
| 52 |
-
|
| 53 |
-
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
| 54 |
-
logger = logging.getLogger(__name__)
|
| 55 |
-
|
| 56 |
-
MODEL_ID = "tiiuae/Falcon-OCR"
|
| 57 |
-
IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".tiff", ".tif", ".bmp", ".webp"}
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
def check_cuda_availability():
|
| 61 |
-
if not torch.cuda.is_available():
|
| 62 |
-
logger.error("CUDA is not available. This script requires a GPU.")
|
| 63 |
-
sys.exit(1)
|
| 64 |
-
logger.info(f"CUDA available. GPU: {torch.cuda.get_device_name(0)}")
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
def discover_files(input_dir: Path, limit: int | None = None) -> list[Path]:
|
| 68 |
-
"""Discover image and PDF files under input_dir.
|
| 69 |
-
|
| 70 |
-
Without `limit`, returns the full sorted list (deterministic order).
|
| 71 |
-
With `limit`, stops scanning once `limit` matching files are found
|
| 72 |
-
and returns them in filesystem order (much faster on huge mounted
|
| 73 |
-
buckets, but ordering is not deterministic).
|
| 74 |
-
"""
|
| 75 |
-
files = []
|
| 76 |
-
iterator = (
|
| 77 |
-
input_dir.rglob("*") if limit is not None else sorted(input_dir.rglob("*"))
|
| 78 |
-
)
|
| 79 |
-
for path in iterator:
|
| 80 |
-
if not path.is_file():
|
| 81 |
-
continue
|
| 82 |
-
ext = path.suffix.lower()
|
| 83 |
-
if ext in IMAGE_EXTENSIONS or ext == ".pdf":
|
| 84 |
-
files.append(path)
|
| 85 |
-
if limit is not None and len(files) >= limit:
|
| 86 |
-
break
|
| 87 |
-
return files
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
def prepare_images(
|
| 91 |
-
files: list[Path], input_dir: Path, output_dir: Path, pdf_dpi: int
|
| 92 |
-
) -> list[tuple[Image.Image, Path]]:
|
| 93 |
-
import fitz # pymupdf
|
| 94 |
-
|
| 95 |
-
items: list[tuple[Image.Image, Path]] = []
|
| 96 |
-
|
| 97 |
-
for file_path in files:
|
| 98 |
-
rel = file_path.relative_to(input_dir)
|
| 99 |
-
ext = file_path.suffix.lower()
|
| 100 |
-
|
| 101 |
-
if ext == ".pdf":
|
| 102 |
-
pdf_output_dir = output_dir / rel.with_suffix("")
|
| 103 |
-
try:
|
| 104 |
-
doc = fitz.open(file_path)
|
| 105 |
-
num_pages = len(doc)
|
| 106 |
-
logger.info(f"PDF: {rel} ({num_pages} pages)")
|
| 107 |
-
for page_num in range(num_pages):
|
| 108 |
-
page = doc[page_num]
|
| 109 |
-
zoom = pdf_dpi / 72.0
|
| 110 |
-
mat = fitz.Matrix(zoom, zoom)
|
| 111 |
-
pix = page.get_pixmap(matrix=mat)
|
| 112 |
-
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
|
| 113 |
-
md_path = pdf_output_dir / f"page_{page_num + 1:03d}.md"
|
| 114 |
-
items.append((img, md_path))
|
| 115 |
-
doc.close()
|
| 116 |
-
except Exception as e:
|
| 117 |
-
logger.error(f"Failed to open PDF {rel}: {e}")
|
| 118 |
-
else:
|
| 119 |
-
try:
|
| 120 |
-
img = Image.open(file_path).convert("RGB")
|
| 121 |
-
md_path = output_dir / rel.with_suffix(".md")
|
| 122 |
-
items.append((img, md_path))
|
| 123 |
-
except Exception as e:
|
| 124 |
-
logger.error(f"Failed to open image {rel}: {e}")
|
| 125 |
-
|
| 126 |
-
return items
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
def main():
|
| 130 |
-
parser = argparse.ArgumentParser(
|
| 131 |
-
description="OCR images/PDFs from a directory using Falcon OCR, output markdown files.",
|
| 132 |
-
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 133 |
-
epilog=__doc__,
|
| 134 |
-
)
|
| 135 |
-
parser.add_argument("input_dir", help="Directory containing images and/or PDFs")
|
| 136 |
-
parser.add_argument("output_dir", help="Directory to write markdown output files")
|
| 137 |
-
parser.add_argument(
|
| 138 |
-
"--batch-size", type=int, default=8, help="Images per batch (default: 8)",
|
| 139 |
-
)
|
| 140 |
-
parser.add_argument(
|
| 141 |
-
"--pdf-dpi", type=int, default=300,
|
| 142 |
-
help="DPI for PDF page rendering (default: 300)",
|
| 143 |
-
)
|
| 144 |
-
parser.add_argument(
|
| 145 |
-
"--no-compile", action="store_true", help="Disable torch.compile",
|
| 146 |
-
)
|
| 147 |
-
parser.add_argument(
|
| 148 |
-
"--no-cudagraph", action="store_true", help="Disable CUDA graph capture",
|
| 149 |
-
)
|
| 150 |
-
parser.add_argument(
|
| 151 |
-
"--max-samples", type=int, default=None,
|
| 152 |
-
help="Limit number of input files to discover. Stops scanning early "
|
| 153 |
-
"once the limit is reached (much faster on large mounted buckets). "
|
| 154 |
-
"Applied before PDF page expansion. With --max-samples set, file "
|
| 155 |
-
"ordering is filesystem-dependent rather than sorted.",
|
| 156 |
-
)
|
| 157 |
-
parser.add_argument(
|
| 158 |
-
"--verbose", action="store_true", help="Print resolved package versions",
|
| 159 |
-
)
|
| 160 |
-
|
| 161 |
-
args = parser.parse_args()
|
| 162 |
-
|
| 163 |
-
check_cuda_availability()
|
| 164 |
-
|
| 165 |
-
input_dir = Path(args.input_dir)
|
| 166 |
-
output_dir = Path(args.output_dir)
|
| 167 |
-
|
| 168 |
-
if not input_dir.is_dir():
|
| 169 |
-
logger.error(f"Input directory does not exist: {input_dir}")
|
| 170 |
-
sys.exit(1)
|
| 171 |
-
|
| 172 |
-
output_dir.mkdir(parents=True, exist_ok=True)
|
| 173 |
-
|
| 174 |
-
start_time = time.time()
|
| 175 |
-
|
| 176 |
-
# Discover files
|
| 177 |
-
if args.max_samples is not None:
|
| 178 |
-
logger.info(
|
| 179 |
-
f"Scanning {input_dir} for up to {args.max_samples} images/PDFs "
|
| 180 |
-
f"(early termination, --max-samples)..."
|
| 181 |
-
)
|
| 182 |
-
else:
|
| 183 |
-
logger.info(f"Scanning {input_dir} for images and PDFs...")
|
| 184 |
-
files = discover_files(input_dir, limit=args.max_samples)
|
| 185 |
-
if not files:
|
| 186 |
-
logger.error(f"No image or PDF files found in {input_dir}")
|
| 187 |
-
sys.exit(1)
|
| 188 |
-
|
| 189 |
-
pdf_count = sum(1 for f in files if f.suffix.lower() == ".pdf")
|
| 190 |
-
img_count = len(files) - pdf_count
|
| 191 |
-
logger.info(f"Found {img_count} image(s) and {pdf_count} PDF(s)")
|
| 192 |
-
|
| 193 |
-
# Prepare images
|
| 194 |
-
logger.info("Preparing images (rendering PDFs)...")
|
| 195 |
-
items = prepare_images(files, input_dir, output_dir, args.pdf_dpi)
|
| 196 |
-
if not items:
|
| 197 |
-
logger.error("No processable images after preparation")
|
| 198 |
-
sys.exit(1)
|
| 199 |
-
|
| 200 |
-
logger.info(f"Total images to OCR: {len(items)}")
|
| 201 |
-
|
| 202 |
-
# Load model
|
| 203 |
-
logger.info(f"Loading {MODEL_ID} via falcon-perception engine...")
|
| 204 |
-
from falcon_perception import load_and_prepare_model
|
| 205 |
-
from falcon_perception.data import ImageProcessor
|
| 206 |
-
from falcon_perception.paged_ocr_inference import OCRInferenceEngine
|
| 207 |
-
|
| 208 |
-
do_compile = not args.no_compile
|
| 209 |
-
do_cudagraph = not args.no_cudagraph
|
| 210 |
-
|
| 211 |
-
model, tokenizer, model_args = load_and_prepare_model(
|
| 212 |
-
hf_model_id=MODEL_ID,
|
| 213 |
-
device="cuda",
|
| 214 |
-
dtype="bfloat16",
|
| 215 |
-
compile=do_compile,
|
| 216 |
-
)
|
| 217 |
-
|
| 218 |
-
image_processor = ImageProcessor(patch_size=16, merge_size=1)
|
| 219 |
-
engine = OCRInferenceEngine(
|
| 220 |
-
model, tokenizer, image_processor, capture_cudagraph=do_cudagraph
|
| 221 |
-
)
|
| 222 |
-
logger.info(f"Engine loaded. compile={do_compile}, cudagraph={do_cudagraph}")
|
| 223 |
-
|
| 224 |
-
# Process in batches
|
| 225 |
-
errors = 0
|
| 226 |
-
processed = 0
|
| 227 |
-
total = len(items)
|
| 228 |
-
batch_size = args.batch_size
|
| 229 |
-
|
| 230 |
-
for batch_start in range(0, total, batch_size):
|
| 231 |
-
batch_end = min(batch_start + batch_size, total)
|
| 232 |
-
batch = items[batch_start:batch_end]
|
| 233 |
-
batch_num = batch_start // batch_size + 1
|
| 234 |
-
total_batches = (total + batch_size - 1) // batch_size
|
| 235 |
-
|
| 236 |
-
logger.info(f"Batch {batch_num}/{total_batches} ({processed}/{total} done)")
|
| 237 |
-
|
| 238 |
-
try:
|
| 239 |
-
batch_images = [img for img, _ in batch]
|
| 240 |
-
texts = engine.generate_plain(images=batch_images, use_tqdm=False)
|
| 241 |
-
|
| 242 |
-
for (_, md_path), text in zip(batch, texts):
|
| 243 |
-
md_path.parent.mkdir(parents=True, exist_ok=True)
|
| 244 |
-
md_path.write_text(text.strip(), encoding="utf-8")
|
| 245 |
-
processed += 1
|
| 246 |
-
|
| 247 |
-
except Exception as e:
|
| 248 |
-
logger.error(f"Batch {batch_num} failed: {e}")
|
| 249 |
-
for _, md_path in batch:
|
| 250 |
-
md_path.parent.mkdir(parents=True, exist_ok=True)
|
| 251 |
-
md_path.write_text(f"[OCR ERROR: {e}]", encoding="utf-8")
|
| 252 |
-
errors += len(batch)
|
| 253 |
-
processed += len(batch)
|
| 254 |
-
|
| 255 |
-
elapsed = time.time() - start_time
|
| 256 |
-
elapsed_str = f"{elapsed / 60:.1f} min" if elapsed > 60 else f"{elapsed:.1f}s"
|
| 257 |
-
|
| 258 |
-
logger.info("=" * 50)
|
| 259 |
-
logger.info(f"Done! Processed {total} images in {elapsed_str}")
|
| 260 |
-
logger.info(f" Output: {output_dir}")
|
| 261 |
-
logger.info(f" Errors: {errors}")
|
| 262 |
-
if total > 0:
|
| 263 |
-
logger.info(f" Speed: {total / elapsed:.2f} images/sec")
|
| 264 |
-
|
| 265 |
-
if args.verbose:
|
| 266 |
-
import importlib.metadata
|
| 267 |
-
|
| 268 |
-
logger.info("--- Package versions ---")
|
| 269 |
-
for pkg in ["falcon-perception", "torch", "pillow", "pymupdf"]:
|
| 270 |
-
try:
|
| 271 |
-
logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
|
| 272 |
-
except importlib.metadata.PackageNotFoundError:
|
| 273 |
-
logger.info(f" {pkg}: not installed")
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
if __name__ == "__main__":
|
| 277 |
-
if len(sys.argv) == 1:
|
| 278 |
-
print("=" * 60)
|
| 279 |
-
print("Falcon OCR Bucket Script")
|
| 280 |
-
print("=" * 60)
|
| 281 |
-
print(f"\nModel: {MODEL_ID} (0.3B, Apache 2.0)")
|
| 282 |
-
print("OCR images/PDFs from a directory -> markdown files.")
|
| 283 |
-
print("Designed for HF Buckets mounted as volumes.")
|
| 284 |
-
print()
|
| 285 |
-
print("Usage:")
|
| 286 |
-
print(" uv run falcon-ocr-bucket.py INPUT_DIR OUTPUT_DIR")
|
| 287 |
-
print()
|
| 288 |
-
print("Examples:")
|
| 289 |
-
print(" uv run falcon-ocr-bucket.py ./images ./output")
|
| 290 |
-
print()
|
| 291 |
-
print("HF Jobs with bucket volumes:")
|
| 292 |
-
print(" hf jobs uv run --flavor l4x1 -s HF_TOKEN \\")
|
| 293 |
-
print(" -v hf://buckets/user/ocr-input:/input:ro \\")
|
| 294 |
-
print(" -v hf://buckets/user/ocr-output:/output \\")
|
| 295 |
-
print(
|
| 296 |
-
" https://huggingface.co/datasets/uv-scripts/ocr/raw/main/falcon-ocr-bucket.py \\"
|
| 297 |
-
)
|
| 298 |
-
print(" /input /output")
|
| 299 |
-
print()
|
| 300 |
-
print("For full help: uv run falcon-ocr-bucket.py --help")
|
| 301 |
-
sys.exit(0)
|
| 302 |
-
|
| 303 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
falcon-ocr.py
DELETED
|
@@ -1,433 +0,0 @@
|
|
| 1 |
-
# /// script
|
| 2 |
-
# requires-python = ">=3.11"
|
| 3 |
-
# dependencies = [
|
| 4 |
-
# "datasets",
|
| 5 |
-
# "huggingface-hub",
|
| 6 |
-
# "pillow",
|
| 7 |
-
# "torch>=2.5",
|
| 8 |
-
# "torchvision",
|
| 9 |
-
# "falcon-perception",
|
| 10 |
-
# ]
|
| 11 |
-
# ///
|
| 12 |
-
|
| 13 |
-
"""
|
| 14 |
-
Convert document images to text using Falcon OCR with the falcon-perception engine.
|
| 15 |
-
|
| 16 |
-
Uses the optimized OCRInferenceEngine with CUDA graphs and paged inference
|
| 17 |
-
for much faster throughput than the raw transformers API.
|
| 18 |
-
|
| 19 |
-
Features:
|
| 20 |
-
- Compact: Only 0.3B parameters
|
| 21 |
-
- Fast: Optimized inference with CUDA graphs
|
| 22 |
-
- Multi-format: Plain text, LaTeX formulas, HTML tables
|
| 23 |
-
- Layout-aware: Optional 2-stage pipeline (layout detection + per-region OCR)
|
| 24 |
-
|
| 25 |
-
Model: tiiuae/Falcon-OCR
|
| 26 |
-
Backend: falcon-perception (OCRInferenceEngine)
|
| 27 |
-
License: Apache 2.0
|
| 28 |
-
|
| 29 |
-
Examples:
|
| 30 |
-
# Basic text OCR
|
| 31 |
-
uv run falcon-ocr.py input-dataset output-dataset
|
| 32 |
-
|
| 33 |
-
# Test with small sample
|
| 34 |
-
uv run falcon-ocr.py dataset test --max-samples 5 --shuffle
|
| 35 |
-
|
| 36 |
-
# Run on HF Jobs with GPU
|
| 37 |
-
hf jobs uv run --flavor l4x1 \\
|
| 38 |
-
-s HF_TOKEN \\
|
| 39 |
-
falcon-ocr.py \\
|
| 40 |
-
input-dataset output-dataset --max-samples 10
|
| 41 |
-
"""
|
| 42 |
-
|
| 43 |
-
import argparse
|
| 44 |
-
import io
|
| 45 |
-
import json
|
| 46 |
-
import logging
|
| 47 |
-
import os
|
| 48 |
-
import sys
|
| 49 |
-
import time
|
| 50 |
-
from datetime import datetime
|
| 51 |
-
from typing import Any, Dict, Union
|
| 52 |
-
|
| 53 |
-
import torch
|
| 54 |
-
from datasets import load_dataset
|
| 55 |
-
from huggingface_hub import DatasetCard, login
|
| 56 |
-
from PIL import Image
|
| 57 |
-
|
| 58 |
-
logging.basicConfig(level=logging.INFO)
|
| 59 |
-
logger = logging.getLogger(__name__)
|
| 60 |
-
|
| 61 |
-
MODEL_ID = "tiiuae/Falcon-OCR"
|
| 62 |
-
|
| 63 |
-
TASK_MODES = {
|
| 64 |
-
"plain": "Full-page text extraction",
|
| 65 |
-
}
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
def check_cuda_availability():
|
| 69 |
-
if not torch.cuda.is_available():
|
| 70 |
-
logger.error("CUDA is not available. This script requires a GPU.")
|
| 71 |
-
logger.error("For cloud execution, use HF Jobs with --flavor l4x1 or similar.")
|
| 72 |
-
sys.exit(1)
|
| 73 |
-
else:
|
| 74 |
-
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
def prepare_image(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:
|
| 78 |
-
if isinstance(image, Image.Image):
|
| 79 |
-
pil_img = image
|
| 80 |
-
elif isinstance(image, dict) and "bytes" in image:
|
| 81 |
-
pil_img = Image.open(io.BytesIO(image["bytes"]))
|
| 82 |
-
elif isinstance(image, str):
|
| 83 |
-
pil_img = Image.open(image)
|
| 84 |
-
else:
|
| 85 |
-
raise ValueError(f"Unsupported image type: {type(image)}")
|
| 86 |
-
return pil_img.convert("RGB")
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
def create_dataset_card(
|
| 90 |
-
source_dataset: str,
|
| 91 |
-
task_mode: str,
|
| 92 |
-
num_samples: int,
|
| 93 |
-
processing_time: str,
|
| 94 |
-
image_column: str = "image",
|
| 95 |
-
split: str = "train",
|
| 96 |
-
) -> str:
|
| 97 |
-
task_description = TASK_MODES[task_mode]
|
| 98 |
-
return f"""---
|
| 99 |
-
tags:
|
| 100 |
-
- ocr
|
| 101 |
-
- document-processing
|
| 102 |
-
- falcon-ocr
|
| 103 |
-
- {task_mode}
|
| 104 |
-
- uv-script
|
| 105 |
-
- generated
|
| 106 |
-
---
|
| 107 |
-
|
| 108 |
-
# Document Processing using Falcon OCR ({task_mode} mode)
|
| 109 |
-
|
| 110 |
-
This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using [Falcon OCR](https://huggingface.co/tiiuae/Falcon-OCR), a 0.3B early-fusion vision-language model.
|
| 111 |
-
|
| 112 |
-
## Processing Details
|
| 113 |
-
|
| 114 |
-
- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
|
| 115 |
-
- **Model**: [{MODEL_ID}](https://huggingface.co/{MODEL_ID})
|
| 116 |
-
- **Task Mode**: `{task_mode}` - {task_description}
|
| 117 |
-
- **Number of Samples**: {num_samples:,}
|
| 118 |
-
- **Processing Time**: {processing_time}
|
| 119 |
-
- **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
|
| 120 |
-
- **Backend**: falcon-perception (OCRInferenceEngine)
|
| 121 |
-
|
| 122 |
-
## Reproduction
|
| 123 |
-
|
| 124 |
-
```bash
|
| 125 |
-
uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/falcon-ocr.py \\
|
| 126 |
-
{source_dataset} \\
|
| 127 |
-
<output-dataset> \\
|
| 128 |
-
--task-mode {task_mode} \\
|
| 129 |
-
--image-column {image_column}
|
| 130 |
-
```
|
| 131 |
-
|
| 132 |
-
Generated with [UV Scripts](https://huggingface.co/uv-scripts)
|
| 133 |
-
"""
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
def main(
|
| 137 |
-
input_dataset: str,
|
| 138 |
-
output_dataset: str,
|
| 139 |
-
image_column: str = "image",
|
| 140 |
-
task_mode: str = "plain",
|
| 141 |
-
hf_token: str = None,
|
| 142 |
-
split: str = "train",
|
| 143 |
-
max_samples: int = None,
|
| 144 |
-
private: bool = False,
|
| 145 |
-
shuffle: bool = False,
|
| 146 |
-
seed: int = 42,
|
| 147 |
-
output_column: str = "markdown",
|
| 148 |
-
config: str = None,
|
| 149 |
-
create_pr: bool = False,
|
| 150 |
-
compile: bool = True,
|
| 151 |
-
cudagraph: bool = True,
|
| 152 |
-
progress: bool = False,
|
| 153 |
-
verbose: bool = False,
|
| 154 |
-
):
|
| 155 |
-
check_cuda_availability()
|
| 156 |
-
start_time = datetime.now()
|
| 157 |
-
|
| 158 |
-
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
|
| 159 |
-
if HF_TOKEN:
|
| 160 |
-
login(token=HF_TOKEN)
|
| 161 |
-
|
| 162 |
-
if task_mode not in TASK_MODES:
|
| 163 |
-
raise ValueError(
|
| 164 |
-
f"Invalid task_mode '{task_mode}'. Choose from: {list(TASK_MODES.keys())}"
|
| 165 |
-
)
|
| 166 |
-
|
| 167 |
-
logger.info(f"Task mode: {task_mode} - {TASK_MODES[task_mode]}")
|
| 168 |
-
logger.info(f"Output column: {output_column}")
|
| 169 |
-
|
| 170 |
-
# Load dataset
|
| 171 |
-
logger.info(f"Loading dataset: {input_dataset}")
|
| 172 |
-
dataset = load_dataset(input_dataset, split=split)
|
| 173 |
-
|
| 174 |
-
if image_column not in dataset.column_names:
|
| 175 |
-
raise ValueError(
|
| 176 |
-
f"Column '{image_column}' not found. Available: {dataset.column_names}"
|
| 177 |
-
)
|
| 178 |
-
|
| 179 |
-
if shuffle:
|
| 180 |
-
logger.info(f"Shuffling dataset with seed {seed}")
|
| 181 |
-
dataset = dataset.shuffle(seed=seed)
|
| 182 |
-
|
| 183 |
-
if max_samples:
|
| 184 |
-
dataset = dataset.select(range(min(max_samples, len(dataset))))
|
| 185 |
-
logger.info(f"Limited to {len(dataset)} samples")
|
| 186 |
-
|
| 187 |
-
# Load model using falcon-perception
|
| 188 |
-
logger.info(f"Loading model: {MODEL_ID} via falcon-perception engine")
|
| 189 |
-
from falcon_perception import load_and_prepare_model
|
| 190 |
-
from falcon_perception.data import ImageProcessor
|
| 191 |
-
from falcon_perception.paged_ocr_inference import OCRInferenceEngine
|
| 192 |
-
|
| 193 |
-
model, tokenizer, model_args = load_and_prepare_model(
|
| 194 |
-
hf_model_id=MODEL_ID,
|
| 195 |
-
device="cuda",
|
| 196 |
-
dtype="bfloat16",
|
| 197 |
-
compile=compile,
|
| 198 |
-
)
|
| 199 |
-
|
| 200 |
-
image_processor = ImageProcessor(patch_size=16, merge_size=1)
|
| 201 |
-
engine = OCRInferenceEngine(
|
| 202 |
-
model, tokenizer, image_processor, capture_cudagraph=cudagraph
|
| 203 |
-
)
|
| 204 |
-
logger.info(f"Engine loaded. compile={compile}, cudagraph={cudagraph}")
|
| 205 |
-
|
| 206 |
-
# Prepare all images
|
| 207 |
-
logger.info(f"Processing {len(dataset)} images...")
|
| 208 |
-
all_outputs = []
|
| 209 |
-
|
| 210 |
-
# Batch plain OCR for better throughput
|
| 211 |
-
batch_size = 8
|
| 212 |
-
total_batches = (len(dataset) + batch_size - 1) // batch_size
|
| 213 |
-
for batch_idx, batch_start in enumerate(range(0, len(dataset), batch_size), 1):
|
| 214 |
-
batch_end = min(batch_start + batch_size, len(dataset))
|
| 215 |
-
logger.info(f"Batch {batch_idx}/{total_batches} ({batch_start}/{len(dataset)} done)")
|
| 216 |
-
batch_images = []
|
| 217 |
-
for i in range(batch_start, batch_end):
|
| 218 |
-
try:
|
| 219 |
-
batch_images.append(prepare_image(dataset[i][image_column]))
|
| 220 |
-
except Exception as e:
|
| 221 |
-
logger.error(f"Error preparing image {i}: {e}")
|
| 222 |
-
batch_images.append(Image.new("RGB", (100, 100)))
|
| 223 |
-
|
| 224 |
-
try:
|
| 225 |
-
texts = engine.generate_plain(
|
| 226 |
-
images=batch_images, use_tqdm=progress
|
| 227 |
-
)
|
| 228 |
-
all_outputs.extend(texts)
|
| 229 |
-
except Exception as e:
|
| 230 |
-
logger.error(f"Error processing batch {batch_start}-{batch_end}: {e}")
|
| 231 |
-
all_outputs.extend(
|
| 232 |
-
[f"[OCR ERROR: {str(e)[:200]}]"] * len(batch_images)
|
| 233 |
-
)
|
| 234 |
-
|
| 235 |
-
# Calculate processing time
|
| 236 |
-
processing_duration = datetime.now() - start_time
|
| 237 |
-
processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
|
| 238 |
-
|
| 239 |
-
# Add output column
|
| 240 |
-
logger.info(f"Adding '{output_column}' column to dataset")
|
| 241 |
-
dataset = dataset.add_column(output_column, all_outputs)
|
| 242 |
-
|
| 243 |
-
# Track inference info
|
| 244 |
-
inference_entry = {
|
| 245 |
-
"model_id": MODEL_ID,
|
| 246 |
-
"model_name": "Falcon-OCR",
|
| 247 |
-
"model_size": "0.3B",
|
| 248 |
-
"task_mode": task_mode,
|
| 249 |
-
"column_name": output_column,
|
| 250 |
-
"timestamp": datetime.now().isoformat(),
|
| 251 |
-
"backend": "falcon-perception",
|
| 252 |
-
}
|
| 253 |
-
|
| 254 |
-
if "inference_info" in dataset.column_names:
|
| 255 |
-
def update_inference_info(example):
|
| 256 |
-
try:
|
| 257 |
-
existing_info = (
|
| 258 |
-
json.loads(example["inference_info"])
|
| 259 |
-
if example["inference_info"]
|
| 260 |
-
else []
|
| 261 |
-
)
|
| 262 |
-
except (json.JSONDecodeError, TypeError):
|
| 263 |
-
existing_info = []
|
| 264 |
-
existing_info.append(inference_entry)
|
| 265 |
-
return {"inference_info": json.dumps(existing_info)}
|
| 266 |
-
|
| 267 |
-
dataset = dataset.map(update_inference_info)
|
| 268 |
-
else:
|
| 269 |
-
inference_list = [json.dumps([inference_entry])] * len(dataset)
|
| 270 |
-
dataset = dataset.add_column("inference_info", inference_list)
|
| 271 |
-
|
| 272 |
-
# Push to hub
|
| 273 |
-
logger.info(f"Pushing to {output_dataset}")
|
| 274 |
-
max_retries = 3
|
| 275 |
-
for attempt in range(1, max_retries + 1):
|
| 276 |
-
try:
|
| 277 |
-
if attempt > 1:
|
| 278 |
-
logger.warning("Disabling XET (fallback to HTTP upload)")
|
| 279 |
-
os.environ["HF_HUB_DISABLE_XET"] = "1"
|
| 280 |
-
dataset.push_to_hub(
|
| 281 |
-
output_dataset,
|
| 282 |
-
private=private,
|
| 283 |
-
token=HF_TOKEN,
|
| 284 |
-
max_shard_size="500MB",
|
| 285 |
-
**({"config_name": config} if config else {}),
|
| 286 |
-
create_pr=create_pr,
|
| 287 |
-
commit_message=f"Add {MODEL_ID} OCR results ({len(dataset)} samples)"
|
| 288 |
-
+ (f" [{config}]" if config else ""),
|
| 289 |
-
)
|
| 290 |
-
break
|
| 291 |
-
except Exception as e:
|
| 292 |
-
logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
|
| 293 |
-
if attempt < max_retries:
|
| 294 |
-
delay = 30 * (2 ** (attempt - 1))
|
| 295 |
-
logger.info(f"Retrying in {delay}s...")
|
| 296 |
-
time.sleep(delay)
|
| 297 |
-
else:
|
| 298 |
-
logger.error("All upload attempts failed. OCR results are lost.")
|
| 299 |
-
sys.exit(1)
|
| 300 |
-
|
| 301 |
-
# Create and push dataset card
|
| 302 |
-
logger.info("Creating dataset card")
|
| 303 |
-
card_content = create_dataset_card(
|
| 304 |
-
source_dataset=input_dataset,
|
| 305 |
-
task_mode=task_mode,
|
| 306 |
-
num_samples=len(dataset),
|
| 307 |
-
processing_time=processing_time_str,
|
| 308 |
-
image_column=image_column,
|
| 309 |
-
split=split,
|
| 310 |
-
)
|
| 311 |
-
card = DatasetCard(card_content)
|
| 312 |
-
card.push_to_hub(output_dataset, token=HF_TOKEN)
|
| 313 |
-
|
| 314 |
-
logger.info("Falcon OCR processing complete!")
|
| 315 |
-
logger.info(
|
| 316 |
-
f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
|
| 317 |
-
)
|
| 318 |
-
logger.info(f"Processing time: {processing_time_str}")
|
| 319 |
-
logger.info(
|
| 320 |
-
f"Speed: {len(dataset) / processing_duration.total_seconds():.2f} images/sec"
|
| 321 |
-
)
|
| 322 |
-
|
| 323 |
-
if verbose:
|
| 324 |
-
import importlib.metadata
|
| 325 |
-
|
| 326 |
-
logger.info("--- Resolved package versions ---")
|
| 327 |
-
for pkg in [
|
| 328 |
-
"falcon-perception", "transformers", "torch", "datasets", "pillow"
|
| 329 |
-
]:
|
| 330 |
-
try:
|
| 331 |
-
logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
|
| 332 |
-
except importlib.metadata.PackageNotFoundError:
|
| 333 |
-
logger.info(f" {pkg}: not installed")
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
if __name__ == "__main__":
|
| 337 |
-
if len(sys.argv) == 1:
|
| 338 |
-
print("=" * 70)
|
| 339 |
-
print("Falcon OCR - 0.3B Document OCR (falcon-perception engine)")
|
| 340 |
-
print("=" * 70)
|
| 341 |
-
print(f"\nModel: {MODEL_ID}")
|
| 342 |
-
print("License: Apache 2.0")
|
| 343 |
-
print("\nTask Modes:")
|
| 344 |
-
for mode, description in TASK_MODES.items():
|
| 345 |
-
print(f" {mode:10} - {description}")
|
| 346 |
-
print("\nExamples:")
|
| 347 |
-
print(" uv run falcon-ocr.py input-dataset output-dataset")
|
| 348 |
-
print(" uv run falcon-ocr.py dense-docs output --task-mode layout")
|
| 349 |
-
print("\nFor full help: uv run falcon-ocr.py --help")
|
| 350 |
-
sys.exit(0)
|
| 351 |
-
|
| 352 |
-
parser = argparse.ArgumentParser(
|
| 353 |
-
description="Document OCR using Falcon OCR (0.3B, falcon-perception engine)",
|
| 354 |
-
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 355 |
-
epilog=__doc__,
|
| 356 |
-
)
|
| 357 |
-
|
| 358 |
-
parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
|
| 359 |
-
parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
|
| 360 |
-
parser.add_argument(
|
| 361 |
-
"--image-column", default="image",
|
| 362 |
-
help="Column containing images (default: image)",
|
| 363 |
-
)
|
| 364 |
-
parser.add_argument(
|
| 365 |
-
"--task-mode", choices=list(TASK_MODES.keys()), default="plain",
|
| 366 |
-
help="Task type: plain (default), layout",
|
| 367 |
-
)
|
| 368 |
-
parser.add_argument("--hf-token", help="Hugging Face API token")
|
| 369 |
-
parser.add_argument(
|
| 370 |
-
"--split", default="train", help="Dataset split (default: train)",
|
| 371 |
-
)
|
| 372 |
-
parser.add_argument(
|
| 373 |
-
"--max-samples", type=int,
|
| 374 |
-
help="Maximum number of samples to process (for testing)",
|
| 375 |
-
)
|
| 376 |
-
parser.add_argument(
|
| 377 |
-
"--private", action="store_true", help="Make output dataset private",
|
| 378 |
-
)
|
| 379 |
-
parser.add_argument(
|
| 380 |
-
"--shuffle", action="store_true", help="Shuffle dataset before processing",
|
| 381 |
-
)
|
| 382 |
-
parser.add_argument(
|
| 383 |
-
"--seed", type=int, default=42, help="Random seed for shuffling (default: 42)",
|
| 384 |
-
)
|
| 385 |
-
parser.add_argument(
|
| 386 |
-
"--output-column", default="markdown",
|
| 387 |
-
help="Column name for output text (default: markdown)",
|
| 388 |
-
)
|
| 389 |
-
parser.add_argument(
|
| 390 |
-
"--config",
|
| 391 |
-
help="Config/subset name for Hub (for benchmarking multiple models)",
|
| 392 |
-
)
|
| 393 |
-
parser.add_argument(
|
| 394 |
-
"--create-pr", action="store_true",
|
| 395 |
-
help="Create a pull request instead of pushing directly",
|
| 396 |
-
)
|
| 397 |
-
parser.add_argument(
|
| 398 |
-
"--no-compile", action="store_true",
|
| 399 |
-
help="Disable torch.compile",
|
| 400 |
-
)
|
| 401 |
-
parser.add_argument(
|
| 402 |
-
"--no-cudagraph", action="store_true",
|
| 403 |
-
help="Disable CUDA graph capture",
|
| 404 |
-
)
|
| 405 |
-
parser.add_argument(
|
| 406 |
-
"--progress", action="store_true",
|
| 407 |
-
help="Show per-image progress bar from the inference engine",
|
| 408 |
-
)
|
| 409 |
-
parser.add_argument(
|
| 410 |
-
"--verbose", action="store_true", help="Log resolved package versions",
|
| 411 |
-
)
|
| 412 |
-
|
| 413 |
-
args = parser.parse_args()
|
| 414 |
-
|
| 415 |
-
main(
|
| 416 |
-
input_dataset=args.input_dataset,
|
| 417 |
-
output_dataset=args.output_dataset,
|
| 418 |
-
image_column=args.image_column,
|
| 419 |
-
task_mode=args.task_mode,
|
| 420 |
-
hf_token=args.hf_token,
|
| 421 |
-
split=args.split,
|
| 422 |
-
max_samples=args.max_samples,
|
| 423 |
-
private=args.private,
|
| 424 |
-
shuffle=args.shuffle,
|
| 425 |
-
seed=args.seed,
|
| 426 |
-
output_column=args.output_column,
|
| 427 |
-
config=args.config,
|
| 428 |
-
create_pr=args.create_pr,
|
| 429 |
-
compile=not args.no_compile,
|
| 430 |
-
cudagraph=not args.no_cudagraph,
|
| 431 |
-
progress=args.progress,
|
| 432 |
-
verbose=args.verbose,
|
| 433 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
firered-ocr.py
CHANGED
|
@@ -39,10 +39,6 @@ from huggingface_hub import DatasetCard, login
|
|
| 39 |
from PIL import Image
|
| 40 |
from toolz import partition_all
|
| 41 |
from tqdm.auto import tqdm
|
| 42 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 43 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 44 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 45 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 46 |
from vllm import LLM, SamplingParams
|
| 47 |
|
| 48 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -108,10 +104,10 @@ def make_ocr_message(
|
|
| 108 |
# Convert to RGB
|
| 109 |
pil_img = pil_img.convert("RGB")
|
| 110 |
|
| 111 |
-
# Convert to base64 data URI
|
| 112 |
buf = io.BytesIO()
|
| 113 |
-
pil_img.save(buf, format="
|
| 114 |
-
data_uri = f"data:image/
|
| 115 |
|
| 116 |
# Return message in vLLM format
|
| 117 |
return [
|
|
@@ -232,7 +228,7 @@ def main(
|
|
| 232 |
image_column: str = "image",
|
| 233 |
batch_size: int = 16,
|
| 234 |
model: str = "FireRedTeam/FireRed-OCR",
|
| 235 |
-
max_model_len: int =
|
| 236 |
max_tokens: int = 8192,
|
| 237 |
gpu_memory_utilization: float = 0.8,
|
| 238 |
hf_token: str = None,
|
|
@@ -339,10 +335,7 @@ def main(
|
|
| 339 |
processing_duration = datetime.now() - start_time
|
| 340 |
processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
|
| 341 |
|
| 342 |
-
# Add output column to dataset
|
| 343 |
-
if output_column in dataset.column_names:
|
| 344 |
-
logger.info(f"Removing existing '{output_column}' column before adding new results")
|
| 345 |
-
dataset = dataset.remove_columns([output_column])
|
| 346 |
logger.info(f"Adding '{output_column}' column to dataset")
|
| 347 |
dataset = dataset.add_column(output_column, all_outputs)
|
| 348 |
|
|
@@ -487,8 +480,8 @@ Examples:
|
|
| 487 |
parser.add_argument(
|
| 488 |
"--max-model-len",
|
| 489 |
type=int,
|
| 490 |
-
default=
|
| 491 |
-
help="Maximum model context length (default:
|
| 492 |
)
|
| 493 |
parser.add_argument(
|
| 494 |
"--max-tokens",
|
|
|
|
| 39 |
from PIL import Image
|
| 40 |
from toolz import partition_all
|
| 41 |
from tqdm.auto import tqdm
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
from vllm import LLM, SamplingParams
|
| 43 |
|
| 44 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 104 |
# Convert to RGB
|
| 105 |
pil_img = pil_img.convert("RGB")
|
| 106 |
|
| 107 |
+
# Convert to base64 data URI
|
| 108 |
buf = io.BytesIO()
|
| 109 |
+
pil_img.save(buf, format="PNG")
|
| 110 |
+
data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
|
| 111 |
|
| 112 |
# Return message in vLLM format
|
| 113 |
return [
|
|
|
|
| 228 |
image_column: str = "image",
|
| 229 |
batch_size: int = 16,
|
| 230 |
model: str = "FireRedTeam/FireRed-OCR",
|
| 231 |
+
max_model_len: int = 8192,
|
| 232 |
max_tokens: int = 8192,
|
| 233 |
gpu_memory_utilization: float = 0.8,
|
| 234 |
hf_token: str = None,
|
|
|
|
| 335 |
processing_duration = datetime.now() - start_time
|
| 336 |
processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
|
| 337 |
|
| 338 |
+
# Add output column to dataset
|
|
|
|
|
|
|
|
|
|
| 339 |
logger.info(f"Adding '{output_column}' column to dataset")
|
| 340 |
dataset = dataset.add_column(output_column, all_outputs)
|
| 341 |
|
|
|
|
| 480 |
parser.add_argument(
|
| 481 |
"--max-model-len",
|
| 482 |
type=int,
|
| 483 |
+
default=8192,
|
| 484 |
+
help="Maximum model context length (default: 8192)",
|
| 485 |
)
|
| 486 |
parser.add_argument(
|
| 487 |
"--max-tokens",
|
glm-ocr-bucket.py
DELETED
|
@@ -1,369 +0,0 @@
|
|
| 1 |
-
# /// script
|
| 2 |
-
# requires-python = ">=3.11"
|
| 3 |
-
# dependencies = [
|
| 4 |
-
# "pillow",
|
| 5 |
-
# "pymupdf",
|
| 6 |
-
# "vllm",
|
| 7 |
-
# "torch",
|
| 8 |
-
# ]
|
| 9 |
-
#
|
| 10 |
-
# [[tool.uv.index]]
|
| 11 |
-
# url = "https://wheels.vllm.ai/nightly/cu129"
|
| 12 |
-
#
|
| 13 |
-
# [tool.uv]
|
| 14 |
-
# prerelease = "allow"
|
| 15 |
-
# override-dependencies = ["transformers>=5.1.0"]
|
| 16 |
-
# ///
|
| 17 |
-
|
| 18 |
-
"""
|
| 19 |
-
OCR images and PDFs from a directory using GLM-OCR, writing markdown files.
|
| 20 |
-
|
| 21 |
-
Designed to work with HF Buckets mounted as volumes via `hf jobs uv run -v ...`
|
| 22 |
-
(requires huggingface_hub with PR #3936 volume mounting support).
|
| 23 |
-
|
| 24 |
-
The script reads images/PDFs from INPUT_DIR, runs GLM-OCR via vLLM, and writes
|
| 25 |
-
one .md file per image (or per PDF page) to OUTPUT_DIR, preserving directory structure.
|
| 26 |
-
|
| 27 |
-
Input: Output:
|
| 28 |
-
/input/page1.png → /output/page1.md
|
| 29 |
-
/input/report.pdf → /output/report/page_001.md
|
| 30 |
-
(3 pages) /output/report/page_002.md
|
| 31 |
-
/output/report/page_003.md
|
| 32 |
-
/input/sub/photo.jpg → /output/sub/photo.md
|
| 33 |
-
|
| 34 |
-
Examples:
|
| 35 |
-
|
| 36 |
-
# Local test
|
| 37 |
-
uv run glm-ocr-bucket.py ./test-images ./test-output
|
| 38 |
-
|
| 39 |
-
# HF Jobs with bucket volumes (PR #3936)
|
| 40 |
-
hf jobs uv run --flavor l4x1 \\
|
| 41 |
-
-s HF_TOKEN \\
|
| 42 |
-
-v bucket/user/ocr-input:/input:ro \\
|
| 43 |
-
-v bucket/user/ocr-output:/output \\
|
| 44 |
-
glm-ocr-bucket.py /input /output
|
| 45 |
-
|
| 46 |
-
Model: zai-org/GLM-OCR (0.9B, 94.62% OmniDocBench V1.5, MIT licensed)
|
| 47 |
-
"""
|
| 48 |
-
|
| 49 |
-
import argparse
|
| 50 |
-
import base64
|
| 51 |
-
import io
|
| 52 |
-
import logging
|
| 53 |
-
import sys
|
| 54 |
-
import time
|
| 55 |
-
from pathlib import Path
|
| 56 |
-
|
| 57 |
-
import torch
|
| 58 |
-
from PIL import Image
|
| 59 |
-
import os
|
| 60 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 61 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 62 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 63 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 64 |
-
from vllm import LLM, SamplingParams
|
| 65 |
-
|
| 66 |
-
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
| 67 |
-
logger = logging.getLogger(__name__)
|
| 68 |
-
|
| 69 |
-
MODEL = "zai-org/GLM-OCR"
|
| 70 |
-
|
| 71 |
-
TASK_PROMPTS = {
|
| 72 |
-
"ocr": "Text Recognition:",
|
| 73 |
-
"formula": "Formula Recognition:",
|
| 74 |
-
"table": "Table Recognition:",
|
| 75 |
-
}
|
| 76 |
-
|
| 77 |
-
IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".tiff", ".tif", ".bmp", ".webp"}
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
def check_cuda_availability():
|
| 81 |
-
if not torch.cuda.is_available():
|
| 82 |
-
logger.error("CUDA is not available. This script requires a GPU.")
|
| 83 |
-
sys.exit(1)
|
| 84 |
-
logger.info(f"CUDA available. GPU: {torch.cuda.get_device_name(0)}")
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
def make_ocr_message(image: Image.Image, task: str = "ocr") -> list[dict]:
|
| 88 |
-
"""Create chat message for GLM-OCR from a PIL Image."""
|
| 89 |
-
image = image.convert("RGB")
|
| 90 |
-
buf = io.BytesIO()
|
| 91 |
-
image.save(buf, format="PNG")
|
| 92 |
-
data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
|
| 93 |
-
|
| 94 |
-
return [
|
| 95 |
-
{
|
| 96 |
-
"role": "user",
|
| 97 |
-
"content": [
|
| 98 |
-
{"type": "image_url", "image_url": {"url": data_uri}},
|
| 99 |
-
{"type": "text", "text": TASK_PROMPTS.get(task, TASK_PROMPTS["ocr"])},
|
| 100 |
-
],
|
| 101 |
-
}
|
| 102 |
-
]
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
def discover_files(input_dir: Path) -> list[Path]:
|
| 106 |
-
"""Walk input_dir recursively, returning sorted list of image and PDF files."""
|
| 107 |
-
files = []
|
| 108 |
-
for path in sorted(input_dir.rglob("*")):
|
| 109 |
-
if not path.is_file():
|
| 110 |
-
continue
|
| 111 |
-
ext = path.suffix.lower()
|
| 112 |
-
if ext in IMAGE_EXTENSIONS or ext == ".pdf":
|
| 113 |
-
files.append(path)
|
| 114 |
-
return files
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
def prepare_images(
|
| 118 |
-
files: list[Path], input_dir: Path, output_dir: Path, pdf_dpi: int
|
| 119 |
-
) -> list[tuple[Image.Image, Path]]:
|
| 120 |
-
"""
|
| 121 |
-
Convert discovered files into (PIL.Image, output_md_path) pairs.
|
| 122 |
-
|
| 123 |
-
Images map 1:1. PDFs expand to one image per page in a subdirectory.
|
| 124 |
-
"""
|
| 125 |
-
import fitz # pymupdf
|
| 126 |
-
|
| 127 |
-
items: list[tuple[Image.Image, Path]] = []
|
| 128 |
-
|
| 129 |
-
for file_path in files:
|
| 130 |
-
rel = file_path.relative_to(input_dir)
|
| 131 |
-
ext = file_path.suffix.lower()
|
| 132 |
-
|
| 133 |
-
if ext == ".pdf":
|
| 134 |
-
# PDF → one .md per page in a subdirectory named after the PDF
|
| 135 |
-
pdf_output_dir = output_dir / rel.with_suffix("")
|
| 136 |
-
try:
|
| 137 |
-
doc = fitz.open(file_path)
|
| 138 |
-
num_pages = len(doc)
|
| 139 |
-
logger.info(f"PDF: {rel} ({num_pages} pages)")
|
| 140 |
-
for page_num in range(num_pages):
|
| 141 |
-
page = doc[page_num]
|
| 142 |
-
# Render at specified DPI
|
| 143 |
-
zoom = pdf_dpi / 72.0
|
| 144 |
-
mat = fitz.Matrix(zoom, zoom)
|
| 145 |
-
pix = page.get_pixmap(matrix=mat)
|
| 146 |
-
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
|
| 147 |
-
md_path = pdf_output_dir / f"page_{page_num + 1:03d}.md"
|
| 148 |
-
items.append((img, md_path))
|
| 149 |
-
doc.close()
|
| 150 |
-
except Exception as e:
|
| 151 |
-
logger.error(f"Failed to open PDF {rel}: {e}")
|
| 152 |
-
else:
|
| 153 |
-
# Image �� single .md
|
| 154 |
-
try:
|
| 155 |
-
img = Image.open(file_path).convert("RGB")
|
| 156 |
-
md_path = output_dir / rel.with_suffix(".md")
|
| 157 |
-
items.append((img, md_path))
|
| 158 |
-
except Exception as e:
|
| 159 |
-
logger.error(f"Failed to open image {rel}: {e}")
|
| 160 |
-
|
| 161 |
-
return items
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
def main():
|
| 165 |
-
parser = argparse.ArgumentParser(
|
| 166 |
-
description="OCR images/PDFs from a directory using GLM-OCR, output markdown files.",
|
| 167 |
-
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 168 |
-
epilog="""
|
| 169 |
-
Task modes:
|
| 170 |
-
ocr Text recognition to markdown (default)
|
| 171 |
-
formula LaTeX formula recognition
|
| 172 |
-
table Table extraction (HTML)
|
| 173 |
-
|
| 174 |
-
Examples:
|
| 175 |
-
uv run glm-ocr-bucket.py ./images ./output
|
| 176 |
-
uv run glm-ocr-bucket.py /input /output --task table --pdf-dpi 200
|
| 177 |
-
|
| 178 |
-
HF Jobs with bucket volumes (requires huggingface_hub PR #3936):
|
| 179 |
-
hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
|
| 180 |
-
-v bucket/user/input-bucket:/input:ro \\
|
| 181 |
-
-v bucket/user/output-bucket:/output \\
|
| 182 |
-
glm-ocr-bucket.py /input /output
|
| 183 |
-
""",
|
| 184 |
-
)
|
| 185 |
-
parser.add_argument("input_dir", help="Directory containing images and/or PDFs")
|
| 186 |
-
parser.add_argument("output_dir", help="Directory to write markdown output files")
|
| 187 |
-
parser.add_argument(
|
| 188 |
-
"--task",
|
| 189 |
-
choices=["ocr", "formula", "table"],
|
| 190 |
-
default="ocr",
|
| 191 |
-
help="OCR task mode (default: ocr)",
|
| 192 |
-
)
|
| 193 |
-
parser.add_argument(
|
| 194 |
-
"--batch-size", type=int, default=16, help="Batch size for vLLM (default: 16)"
|
| 195 |
-
)
|
| 196 |
-
parser.add_argument(
|
| 197 |
-
"--max-model-len",
|
| 198 |
-
type=int,
|
| 199 |
-
default=8192,
|
| 200 |
-
help="Max model context length (default: 8192)",
|
| 201 |
-
)
|
| 202 |
-
parser.add_argument(
|
| 203 |
-
"--max-tokens",
|
| 204 |
-
type=int,
|
| 205 |
-
default=8192,
|
| 206 |
-
help="Max output tokens (default: 8192)",
|
| 207 |
-
)
|
| 208 |
-
parser.add_argument(
|
| 209 |
-
"--gpu-memory-utilization",
|
| 210 |
-
type=float,
|
| 211 |
-
default=0.8,
|
| 212 |
-
help="GPU memory utilization (default: 0.8)",
|
| 213 |
-
)
|
| 214 |
-
parser.add_argument(
|
| 215 |
-
"--pdf-dpi",
|
| 216 |
-
type=int,
|
| 217 |
-
default=300,
|
| 218 |
-
help="DPI for PDF page rendering (default: 300)",
|
| 219 |
-
)
|
| 220 |
-
parser.add_argument(
|
| 221 |
-
"--temperature",
|
| 222 |
-
type=float,
|
| 223 |
-
default=0.01,
|
| 224 |
-
help="Sampling temperature (default: 0.01)",
|
| 225 |
-
)
|
| 226 |
-
parser.add_argument(
|
| 227 |
-
"--top-p", type=float, default=0.00001, help="Top-p sampling (default: 0.00001)"
|
| 228 |
-
)
|
| 229 |
-
parser.add_argument(
|
| 230 |
-
"--repetition-penalty",
|
| 231 |
-
type=float,
|
| 232 |
-
default=1.1,
|
| 233 |
-
help="Repetition penalty (default: 1.1)",
|
| 234 |
-
)
|
| 235 |
-
parser.add_argument(
|
| 236 |
-
"--verbose",
|
| 237 |
-
action="store_true",
|
| 238 |
-
help="Print resolved package versions",
|
| 239 |
-
)
|
| 240 |
-
|
| 241 |
-
args = parser.parse_args()
|
| 242 |
-
|
| 243 |
-
check_cuda_availability()
|
| 244 |
-
|
| 245 |
-
input_dir = Path(args.input_dir)
|
| 246 |
-
output_dir = Path(args.output_dir)
|
| 247 |
-
|
| 248 |
-
if not input_dir.is_dir():
|
| 249 |
-
logger.error(f"Input directory does not exist: {input_dir}")
|
| 250 |
-
sys.exit(1)
|
| 251 |
-
|
| 252 |
-
output_dir.mkdir(parents=True, exist_ok=True)
|
| 253 |
-
|
| 254 |
-
# Discover and prepare
|
| 255 |
-
start_time = time.time()
|
| 256 |
-
|
| 257 |
-
logger.info(f"Scanning {input_dir} for images and PDFs...")
|
| 258 |
-
files = discover_files(input_dir)
|
| 259 |
-
if not files:
|
| 260 |
-
logger.error(f"No image or PDF files found in {input_dir}")
|
| 261 |
-
sys.exit(1)
|
| 262 |
-
|
| 263 |
-
pdf_count = sum(1 for f in files if f.suffix.lower() == ".pdf")
|
| 264 |
-
img_count = len(files) - pdf_count
|
| 265 |
-
logger.info(f"Found {img_count} image(s) and {pdf_count} PDF(s)")
|
| 266 |
-
|
| 267 |
-
logger.info("Preparing images (rendering PDFs)...")
|
| 268 |
-
items = prepare_images(files, input_dir, output_dir, args.pdf_dpi)
|
| 269 |
-
if not items:
|
| 270 |
-
logger.error("No processable images after preparation")
|
| 271 |
-
sys.exit(1)
|
| 272 |
-
|
| 273 |
-
logger.info(f"Total images to OCR: {len(items)}")
|
| 274 |
-
|
| 275 |
-
# Init vLLM
|
| 276 |
-
logger.info(f"Initializing vLLM with {MODEL}...")
|
| 277 |
-
llm = LLM(
|
| 278 |
-
model=MODEL,
|
| 279 |
-
trust_remote_code=True,
|
| 280 |
-
max_model_len=args.max_model_len,
|
| 281 |
-
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 282 |
-
limit_mm_per_prompt={"image": 1},
|
| 283 |
-
)
|
| 284 |
-
|
| 285 |
-
sampling_params = SamplingParams(
|
| 286 |
-
temperature=args.temperature,
|
| 287 |
-
top_p=args.top_p,
|
| 288 |
-
max_tokens=args.max_tokens,
|
| 289 |
-
repetition_penalty=args.repetition_penalty,
|
| 290 |
-
)
|
| 291 |
-
|
| 292 |
-
# Process in batches
|
| 293 |
-
errors = 0
|
| 294 |
-
processed = 0
|
| 295 |
-
total = len(items)
|
| 296 |
-
|
| 297 |
-
for batch_start in range(0, total, args.batch_size):
|
| 298 |
-
batch_end = min(batch_start + args.batch_size, total)
|
| 299 |
-
batch = items[batch_start:batch_end]
|
| 300 |
-
batch_num = batch_start // args.batch_size + 1
|
| 301 |
-
total_batches = (total + args.batch_size - 1) // args.batch_size
|
| 302 |
-
|
| 303 |
-
logger.info(f"Batch {batch_num}/{total_batches} ({processed}/{total} done)")
|
| 304 |
-
|
| 305 |
-
try:
|
| 306 |
-
messages = [make_ocr_message(img, task=args.task) for img, _ in batch]
|
| 307 |
-
outputs = llm.chat(messages, sampling_params)
|
| 308 |
-
|
| 309 |
-
for (_, md_path), output in zip(batch, outputs):
|
| 310 |
-
text = output.outputs[0].text.strip()
|
| 311 |
-
md_path.parent.mkdir(parents=True, exist_ok=True)
|
| 312 |
-
md_path.write_text(text, encoding="utf-8")
|
| 313 |
-
processed += 1
|
| 314 |
-
|
| 315 |
-
except Exception as e:
|
| 316 |
-
logger.error(f"Batch {batch_num} failed: {e}")
|
| 317 |
-
# Write error markers for failed batch
|
| 318 |
-
for _, md_path in batch:
|
| 319 |
-
md_path.parent.mkdir(parents=True, exist_ok=True)
|
| 320 |
-
md_path.write_text(f"[OCR ERROR: {e}]", encoding="utf-8")
|
| 321 |
-
errors += len(batch)
|
| 322 |
-
processed += len(batch)
|
| 323 |
-
|
| 324 |
-
elapsed = time.time() - start_time
|
| 325 |
-
elapsed_str = f"{elapsed / 60:.1f} min" if elapsed > 60 else f"{elapsed:.1f}s"
|
| 326 |
-
|
| 327 |
-
logger.info("=" * 50)
|
| 328 |
-
logger.info(f"Done! Processed {total} images in {elapsed_str}")
|
| 329 |
-
logger.info(f" Output: {output_dir}")
|
| 330 |
-
logger.info(f" Errors: {errors}")
|
| 331 |
-
if total > 0:
|
| 332 |
-
logger.info(f" Speed: {total / elapsed:.2f} images/sec")
|
| 333 |
-
|
| 334 |
-
if args.verbose:
|
| 335 |
-
import importlib.metadata
|
| 336 |
-
|
| 337 |
-
logger.info("--- Package versions ---")
|
| 338 |
-
for pkg in ["vllm", "transformers", "torch", "pillow", "pymupdf"]:
|
| 339 |
-
try:
|
| 340 |
-
logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
|
| 341 |
-
except importlib.metadata.PackageNotFoundError:
|
| 342 |
-
logger.info(f" {pkg}: not installed")
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
if __name__ == "__main__":
|
| 346 |
-
if len(sys.argv) == 1:
|
| 347 |
-
print("=" * 60)
|
| 348 |
-
print("GLM-OCR Bucket Script")
|
| 349 |
-
print("=" * 60)
|
| 350 |
-
print("\nOCR images/PDFs from a directory → markdown files.")
|
| 351 |
-
print("Designed for HF Buckets mounted as volumes (PR #3936).")
|
| 352 |
-
print()
|
| 353 |
-
print("Usage:")
|
| 354 |
-
print(" uv run glm-ocr-bucket.py INPUT_DIR OUTPUT_DIR")
|
| 355 |
-
print()
|
| 356 |
-
print("Examples:")
|
| 357 |
-
print(" uv run glm-ocr-bucket.py ./images ./output")
|
| 358 |
-
print(" uv run glm-ocr-bucket.py /input /output --task table")
|
| 359 |
-
print()
|
| 360 |
-
print("HF Jobs with bucket volumes:")
|
| 361 |
-
print(" hf jobs uv run --flavor l4x1 -s HF_TOKEN \\")
|
| 362 |
-
print(" -v bucket/user/ocr-input:/input:ro \\")
|
| 363 |
-
print(" -v bucket/user/ocr-output:/output \\")
|
| 364 |
-
print(" glm-ocr-bucket.py /input /output")
|
| 365 |
-
print()
|
| 366 |
-
print("For full help: uv run glm-ocr-bucket.py --help")
|
| 367 |
-
sys.exit(0)
|
| 368 |
-
|
| 369 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
glm-ocr-v2.py
CHANGED
|
@@ -69,10 +69,6 @@ from datasets import load_dataset
|
|
| 69 |
from huggingface_hub import CommitScheduler, DatasetCard, HfApi, login
|
| 70 |
from PIL import Image
|
| 71 |
from toolz import partition_all
|
| 72 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 73 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 74 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 75 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 76 |
from vllm import LLM, SamplingParams
|
| 77 |
|
| 78 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 69 |
from huggingface_hub import CommitScheduler, DatasetCard, HfApi, login
|
| 70 |
from PIL import Image
|
| 71 |
from toolz import partition_all
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
from vllm import LLM, SamplingParams
|
| 73 |
|
| 74 |
logging.basicConfig(level=logging.INFO)
|
glm-ocr.py
CHANGED
|
@@ -60,10 +60,6 @@ from datasets import load_dataset
|
|
| 60 |
from huggingface_hub import DatasetCard, login
|
| 61 |
from PIL import Image
|
| 62 |
from toolz import partition_all
|
| 63 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 64 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 65 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 66 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 67 |
from vllm import LLM, SamplingParams
|
| 68 |
|
| 69 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 60 |
from huggingface_hub import DatasetCard, login
|
| 61 |
from PIL import Image
|
| 62 |
from toolz import partition_all
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
from vllm import LLM, SamplingParams
|
| 64 |
|
| 65 |
logging.basicConfig(level=logging.INFO)
|
hunyuan-ocr.py
CHANGED
|
@@ -49,10 +49,6 @@ from huggingface_hub import DatasetCard, login
|
|
| 49 |
from PIL import Image
|
| 50 |
from toolz import partition_all
|
| 51 |
from tqdm.auto import tqdm
|
| 52 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 53 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 54 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 55 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 56 |
from vllm import LLM, SamplingParams
|
| 57 |
|
| 58 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 49 |
from PIL import Image
|
| 50 |
from toolz import partition_all
|
| 51 |
from tqdm.auto import tqdm
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
from vllm import LLM, SamplingParams
|
| 53 |
|
| 54 |
logging.basicConfig(level=logging.INFO)
|
lfm2-extract.py
DELETED
|
@@ -1,293 +0,0 @@
|
|
| 1 |
-
# /// script
|
| 2 |
-
# requires-python = ">=3.11"
|
| 3 |
-
# dependencies = [
|
| 4 |
-
# "datasets>=4.0.0",
|
| 5 |
-
# "huggingface-hub",
|
| 6 |
-
# "vllm",
|
| 7 |
-
# "transformers",
|
| 8 |
-
# "tqdm",
|
| 9 |
-
# "toolz",
|
| 10 |
-
# "torch",
|
| 11 |
-
# ]
|
| 12 |
-
# ///
|
| 13 |
-
"""
|
| 14 |
-
Extract structured data (JSON / XML / YAML) from text using LiquidAI's LFM2-1.2B-Extract.
|
| 15 |
-
|
| 16 |
-
LFM2-1.2B-Extract is a compact 1.2B text-only model purpose-built for turning unstructured
|
| 17 |
-
documents into structured data: give it a schema, it returns JSON, XML, or YAML. It reports
|
| 18 |
-
beating Gemma 3 27B (22x larger) on syntax validity / format accuracy / faithfulness, and
|
| 19 |
-
is multilingual (en, ar, zh, fr, de, ja, ko, pt, es).
|
| 20 |
-
|
| 21 |
-
This is the *text* counterpart to `lfm2-vl-extract.py` (which extracts from images). Pair them:
|
| 22 |
-
OCR a page to markdown with one of the OCR recipes, then extract fields from that text here.
|
| 23 |
-
|
| 24 |
-
Pass `--schema` as inline text/JSON, a URL, or a file path describing the structure to extract:
|
| 25 |
-
|
| 26 |
-
--schema '{"invoice_number": "string", "total": "number", "line_items": "array"}'
|
| 27 |
-
|
| 28 |
-
Model: https://huggingface.co/LiquidAI/LFM2-1.2B-Extract
|
| 29 |
-
Docs: https://docs.liquid.ai/deployment/gpu-inference/vllm
|
| 30 |
-
|
| 31 |
-
HF Jobs note: run on the vLLM image so the CUDA toolkit + prebuilt FlashInfer kernels are
|
| 32 |
-
present and startup is fast (it reuses the image's CUDA-matched vLLM build):
|
| 33 |
-
|
| 34 |
-
hf jobs uv run --flavor l4x1 --secrets HF_TOKEN \
|
| 35 |
-
--image vllm/vllm-openai --python /usr/bin/python3 \
|
| 36 |
-
-e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \
|
| 37 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lfm2-extract.py \
|
| 38 |
-
INPUT OUTPUT --text-column text --schema '{"field": "description"}'
|
| 39 |
-
|
| 40 |
-
It also runs on the default uv image, just with a slower first-time vLLM build. Deps are left
|
| 41 |
-
unpinned so uv resolves a recent vLLM; FlashInfer sampling is disabled (see below) so the engine
|
| 42 |
-
never JIT-compiles a kernel that needs nvcc — absent from the default image.
|
| 43 |
-
"""
|
| 44 |
-
|
| 45 |
-
import argparse
|
| 46 |
-
import json
|
| 47 |
-
import logging
|
| 48 |
-
import os
|
| 49 |
-
import sys
|
| 50 |
-
from datetime import datetime, timezone
|
| 51 |
-
from typing import List, Optional
|
| 52 |
-
from urllib.request import urlopen
|
| 53 |
-
|
| 54 |
-
# Disable vLLM's FlashInfer sampler before the engine starts: it JIT-compiles at warmup and
|
| 55 |
-
# needs nvcc (absent from the default uv image). Harmless for greedy decoding.
|
| 56 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 57 |
-
|
| 58 |
-
import torch
|
| 59 |
-
from datasets import load_dataset
|
| 60 |
-
from huggingface_hub import DatasetCard, login
|
| 61 |
-
from toolz import partition_all
|
| 62 |
-
from tqdm import tqdm
|
| 63 |
-
from vllm import LLM, SamplingParams
|
| 64 |
-
|
| 65 |
-
logging.basicConfig(level=logging.INFO)
|
| 66 |
-
logger = logging.getLogger(__name__)
|
| 67 |
-
|
| 68 |
-
DEFAULT_MODEL = "LiquidAI/LFM2-1.2B-Extract"
|
| 69 |
-
FORMATS = {"json": "JSON", "xml": "XML", "yaml": "YAML"}
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
def check_cuda_availability() -> None:
|
| 73 |
-
if not torch.cuda.is_available():
|
| 74 |
-
logger.error("CUDA is not available. This script requires a GPU.")
|
| 75 |
-
logger.error("Run on Hugging Face Jobs with: hf jobs uv run --flavor l4x1 ...")
|
| 76 |
-
sys.exit(1)
|
| 77 |
-
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name()}")
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
def load_text_arg(value: str) -> str:
|
| 81 |
-
"""Resolve --schema (inline text/JSON, URL, or file path) into a string."""
|
| 82 |
-
text = value.strip()
|
| 83 |
-
if text.startswith("http://") or text.startswith("https://"):
|
| 84 |
-
logger.info(f"Loading schema from URL: {text}")
|
| 85 |
-
return urlopen(text).read().decode("utf-8").strip()
|
| 86 |
-
if os.path.exists(text):
|
| 87 |
-
logger.info(f"Loading schema from file: {text}")
|
| 88 |
-
with open(text) as f:
|
| 89 |
-
return f.read().strip()
|
| 90 |
-
return text
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
def build_system_prompt(schema_text: str, fmt: str) -> str:
|
| 94 |
-
return f"Return data as a {FORMATS[fmt]} object with the following schema:\n\n{schema_text}"
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
def parse_output(text: str, fmt: str) -> tuple[str, bool]:
|
| 98 |
-
"""Strip code fences; for JSON, validate. Returns (cleaned_text, is_valid)."""
|
| 99 |
-
stripped = text.strip()
|
| 100 |
-
if stripped.startswith("```"):
|
| 101 |
-
stripped = stripped.split("\n", 1)[-1]
|
| 102 |
-
if stripped.endswith("```"):
|
| 103 |
-
stripped = stripped.rsplit("```", 1)[0]
|
| 104 |
-
stripped = stripped.strip()
|
| 105 |
-
if fmt == "json":
|
| 106 |
-
try:
|
| 107 |
-
return json.dumps(json.loads(stripped), ensure_ascii=False), True
|
| 108 |
-
except (json.JSONDecodeError, ValueError):
|
| 109 |
-
return stripped, False
|
| 110 |
-
return stripped, True # xml/yaml: store as-is (no strict validator)
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
def main(
|
| 114 |
-
input_dataset: str,
|
| 115 |
-
output_dataset: str,
|
| 116 |
-
schema: str,
|
| 117 |
-
text_column: str = "text",
|
| 118 |
-
output_column: str = "extraction",
|
| 119 |
-
output_format: str = "json",
|
| 120 |
-
split: str = "train",
|
| 121 |
-
max_samples: Optional[int] = None,
|
| 122 |
-
shuffle: bool = False,
|
| 123 |
-
seed: int = 42,
|
| 124 |
-
batch_size: int = 32,
|
| 125 |
-
model: str = DEFAULT_MODEL,
|
| 126 |
-
max_model_len: int = 8192,
|
| 127 |
-
max_tokens: int = 4096,
|
| 128 |
-
private: bool = False,
|
| 129 |
-
hf_token: Optional[str] = None,
|
| 130 |
-
) -> None:
|
| 131 |
-
check_cuda_availability()
|
| 132 |
-
if output_format not in FORMATS:
|
| 133 |
-
logger.error(f"--format must be one of {list(FORMATS)}; got {output_format}")
|
| 134 |
-
sys.exit(1)
|
| 135 |
-
|
| 136 |
-
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
|
| 137 |
-
if HF_TOKEN:
|
| 138 |
-
login(token=HF_TOKEN)
|
| 139 |
-
|
| 140 |
-
schema_text = load_text_arg(schema)
|
| 141 |
-
system_prompt = build_system_prompt(schema_text, output_format)
|
| 142 |
-
|
| 143 |
-
logger.info(f"Loading dataset: {input_dataset} (split={split})")
|
| 144 |
-
dataset = load_dataset(input_dataset, split=split)
|
| 145 |
-
if shuffle:
|
| 146 |
-
dataset = dataset.shuffle(seed=seed)
|
| 147 |
-
if max_samples:
|
| 148 |
-
dataset = dataset.select(range(min(max_samples, len(dataset))))
|
| 149 |
-
logger.info(f"Processing {len(dataset)} examples; format={output_format}")
|
| 150 |
-
|
| 151 |
-
if text_column not in dataset.column_names:
|
| 152 |
-
logger.error(f"Text column '{text_column}' not found. Columns: {dataset.column_names}")
|
| 153 |
-
sys.exit(1)
|
| 154 |
-
|
| 155 |
-
logger.info(f"Loading model: {model}")
|
| 156 |
-
llm = LLM(model=model, max_model_len=max_model_len, enforce_eager=True)
|
| 157 |
-
sampling_params = SamplingParams(temperature=0.0, max_tokens=max_tokens)
|
| 158 |
-
|
| 159 |
-
all_outputs: List[str] = []
|
| 160 |
-
n_valid = 0
|
| 161 |
-
texts = dataset[text_column]
|
| 162 |
-
for batch in tqdm(list(partition_all(batch_size, texts)), desc="Extracting"):
|
| 163 |
-
batch_messages = [
|
| 164 |
-
[
|
| 165 |
-
{"role": "system", "content": system_prompt},
|
| 166 |
-
{"role": "user", "content": str(doc)},
|
| 167 |
-
]
|
| 168 |
-
for doc in batch
|
| 169 |
-
]
|
| 170 |
-
outputs = llm.chat(batch_messages, sampling_params)
|
| 171 |
-
for out in outputs:
|
| 172 |
-
cleaned, ok = parse_output(out.outputs[0].text, output_format)
|
| 173 |
-
n_valid += int(ok)
|
| 174 |
-
all_outputs.append(cleaned)
|
| 175 |
-
|
| 176 |
-
logger.info(f"Valid {output_format.upper()}: {n_valid}/{len(all_outputs)}")
|
| 177 |
-
dataset = dataset.add_column(output_column, all_outputs)
|
| 178 |
-
|
| 179 |
-
inference_entry = {
|
| 180 |
-
"model": model,
|
| 181 |
-
"column_name": output_column,
|
| 182 |
-
"task": "structured extraction",
|
| 183 |
-
"format": output_format,
|
| 184 |
-
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 185 |
-
"script": "lfm2-extract.py",
|
| 186 |
-
}
|
| 187 |
-
if "inference_info" in dataset.column_names:
|
| 188 |
-
def update_info(example):
|
| 189 |
-
try:
|
| 190 |
-
existing = json.loads(example["inference_info"]) if example["inference_info"] else []
|
| 191 |
-
except (json.JSONDecodeError, TypeError):
|
| 192 |
-
existing = []
|
| 193 |
-
existing.append(inference_entry)
|
| 194 |
-
return {"inference_info": json.dumps(existing)}
|
| 195 |
-
dataset = dataset.map(update_info)
|
| 196 |
-
else:
|
| 197 |
-
dataset = dataset.add_column(
|
| 198 |
-
"inference_info", [json.dumps([inference_entry])] * len(dataset)
|
| 199 |
-
)
|
| 200 |
-
|
| 201 |
-
logger.info(f"Pushing to {output_dataset}")
|
| 202 |
-
dataset.push_to_hub(output_dataset, private=private, token=HF_TOKEN)
|
| 203 |
-
|
| 204 |
-
card_text = f"""---
|
| 205 |
-
tags:
|
| 206 |
-
- uv-script
|
| 207 |
-
- extraction
|
| 208 |
-
- lfm2
|
| 209 |
-
- {output_format}
|
| 210 |
-
---
|
| 211 |
-
|
| 212 |
-
# Structured extraction with LFM2-1.2B-Extract
|
| 213 |
-
|
| 214 |
-
`{output_format.upper()}` extracted from the `{text_column}` column of
|
| 215 |
-
[{input_dataset}](https://huggingface.co/datasets/{input_dataset})
|
| 216 |
-
using [{model}](https://huggingface.co/{model}).
|
| 217 |
-
|
| 218 |
-
- **Source**: `{input_dataset}` (split `{split}`, column `{text_column}`)
|
| 219 |
-
- **Model**: `{model}`
|
| 220 |
-
- **Format**: `{output_format}`
|
| 221 |
-
- **Output column**: `{output_column}`
|
| 222 |
-
- **Valid {output_format.upper()}**: {n_valid}/{len(all_outputs)}
|
| 223 |
-
- **Date**: {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}
|
| 224 |
-
|
| 225 |
-
Generated with the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) `lfm2-extract.py` script.
|
| 226 |
-
"""
|
| 227 |
-
try:
|
| 228 |
-
DatasetCard(card_text).push_to_hub(output_dataset, token=HF_TOKEN)
|
| 229 |
-
except Exception as e:
|
| 230 |
-
logger.warning(f"Could not push dataset card: {e}")
|
| 231 |
-
|
| 232 |
-
logger.info("Done! Extraction complete.")
|
| 233 |
-
logger.info(f"Dataset: https://huggingface.co/datasets/{output_dataset}")
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
if __name__ == "__main__":
|
| 237 |
-
if len(sys.argv) == 1:
|
| 238 |
-
print("LFM2-1.2B-Extract — structured extraction (JSON/XML/YAML) from text")
|
| 239 |
-
print("\nUsage:")
|
| 240 |
-
print(" uv run lfm2-extract.py INPUT OUTPUT --schema SCHEMA [--text-column text] [--format json]")
|
| 241 |
-
print("\nExample:")
|
| 242 |
-
print(' uv run lfm2-extract.py my-docs my-fields \\')
|
| 243 |
-
print(' --text-column markdown \\')
|
| 244 |
-
print(' --schema \'{"title": "the title", "date": "any date", "summary": "one sentence"}\'')
|
| 245 |
-
print("\n --schema accepts inline text/JSON, a URL, or a file path.")
|
| 246 |
-
print("\nFor full help: uv run lfm2-extract.py --help")
|
| 247 |
-
sys.exit(0)
|
| 248 |
-
|
| 249 |
-
parser = argparse.ArgumentParser(
|
| 250 |
-
description="Structured extraction (JSON/XML/YAML) from text using LFM2-1.2B-Extract",
|
| 251 |
-
)
|
| 252 |
-
parser.add_argument("input_dataset", help="Input dataset ID (with a text column)")
|
| 253 |
-
parser.add_argument("output_dataset", help="Output dataset ID")
|
| 254 |
-
parser.add_argument(
|
| 255 |
-
"--schema", required=True,
|
| 256 |
-
help="Structure to extract: inline text/JSON, a URL, or a file path",
|
| 257 |
-
)
|
| 258 |
-
parser.add_argument("--text-column", default="text", help="Text column (default: text)")
|
| 259 |
-
parser.add_argument("--output-column", default="extraction", help="Output column (default: extraction)")
|
| 260 |
-
parser.add_argument(
|
| 261 |
-
"--format", dest="output_format", default="json", choices=list(FORMATS),
|
| 262 |
-
help="Output format (default: json)",
|
| 263 |
-
)
|
| 264 |
-
parser.add_argument("--split", default="train", help="Dataset split (default: train)")
|
| 265 |
-
parser.add_argument("--max-samples", type=int, help="Limit number of samples")
|
| 266 |
-
parser.add_argument("--shuffle", action="store_true", help="Shuffle before sampling")
|
| 267 |
-
parser.add_argument("--seed", type=int, default=42, help="Shuffle seed (default: 42)")
|
| 268 |
-
parser.add_argument("--batch-size", type=int, default=32, help="Batch size (default: 32)")
|
| 269 |
-
parser.add_argument("--model", default=DEFAULT_MODEL, help=f"Model (default: {DEFAULT_MODEL})")
|
| 270 |
-
parser.add_argument("--max-model-len", type=int, default=8192, help="Max context length (default: 8192)")
|
| 271 |
-
parser.add_argument("--max-tokens", type=int, default=4096, help="Max output tokens (default: 4096)")
|
| 272 |
-
parser.add_argument("--private", action="store_true", help="Make output dataset private")
|
| 273 |
-
parser.add_argument("--hf-token", help="HF token (or set HF_TOKEN)")
|
| 274 |
-
args = parser.parse_args()
|
| 275 |
-
|
| 276 |
-
main(
|
| 277 |
-
input_dataset=args.input_dataset,
|
| 278 |
-
output_dataset=args.output_dataset,
|
| 279 |
-
schema=args.schema,
|
| 280 |
-
text_column=args.text_column,
|
| 281 |
-
output_column=args.output_column,
|
| 282 |
-
output_format=args.output_format,
|
| 283 |
-
split=args.split,
|
| 284 |
-
max_samples=args.max_samples,
|
| 285 |
-
shuffle=args.shuffle,
|
| 286 |
-
seed=args.seed,
|
| 287 |
-
batch_size=args.batch_size,
|
| 288 |
-
model=args.model,
|
| 289 |
-
max_model_len=args.max_model_len,
|
| 290 |
-
max_tokens=args.max_tokens,
|
| 291 |
-
private=args.private,
|
| 292 |
-
hf_token=args.hf_token,
|
| 293 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
lfm2-vl-extract.py
DELETED
|
@@ -1,324 +0,0 @@
|
|
| 1 |
-
# /// script
|
| 2 |
-
# requires-python = ">=3.11"
|
| 3 |
-
# dependencies = [
|
| 4 |
-
# "datasets>=4.0.0",
|
| 5 |
-
# "huggingface-hub",
|
| 6 |
-
# "pillow",
|
| 7 |
-
# "vllm",
|
| 8 |
-
# "transformers",
|
| 9 |
-
# "tqdm",
|
| 10 |
-
# "toolz",
|
| 11 |
-
# "torch",
|
| 12 |
-
# ]
|
| 13 |
-
# ///
|
| 14 |
-
"""
|
| 15 |
-
Extract structured JSON from images using LiquidAI's LFM2.5-VL-1.6B-Extract with vLLM.
|
| 16 |
-
|
| 17 |
-
LFM2.5-VL-1.6B-Extract (1.6B = LFM2 1.2B LM + SigLIP2 0.4B vision) is a compact
|
| 18 |
-
vision-language model purpose-built for *schema-guided* extraction: you give it a
|
| 19 |
-
list of fields, it returns a flat JSON object with those fields filled from the image.
|
| 20 |
-
It reports 99.6 JSON-validity / F1 on its benchmark, beating similarly-sized VLMs.
|
| 21 |
-
|
| 22 |
-
Unlike the markdown-OCR scripts here, this one needs a SCHEMA (a field list). Pass
|
| 23 |
-
`--schema` as inline JSON, a URL, or a file path, mapping field names to short
|
| 24 |
-
descriptions:
|
| 25 |
-
|
| 26 |
-
--schema '{"invoice_number": "the invoice number", "total": "the total amount"}'
|
| 27 |
-
|
| 28 |
-
Model: https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-Extract
|
| 29 |
-
Docs: https://docs.liquid.ai/deployment/gpu-inference/vllm
|
| 30 |
-
|
| 31 |
-
HF Jobs note: run on the vLLM image so the CUDA toolkit + prebuilt FlashInfer kernels
|
| 32 |
-
are present and startup is fast (it reuses the image's CUDA-matched vLLM build):
|
| 33 |
-
|
| 34 |
-
hf jobs uv run --flavor l4x1 --secrets HF_TOKEN \
|
| 35 |
-
--image vllm/vllm-openai --python /usr/bin/python3 \
|
| 36 |
-
-e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \
|
| 37 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lfm2-vl-extract.py \
|
| 38 |
-
INPUT OUTPUT --schema '{"title": "the document title", "date": "any date shown"}'
|
| 39 |
-
|
| 40 |
-
It also runs on the default uv image, just with a slower first-time vLLM build. Deps are
|
| 41 |
-
left unpinned so uv resolves a vLLM that supports the LFM2-VL (transformers 5) architecture,
|
| 42 |
-
and FlashInfer sampling is disabled (VLLM_USE_FLASHINFER_SAMPLER=0, see below) so the engine
|
| 43 |
-
never JIT-compiles a kernel that needs nvcc — absent from the default image.
|
| 44 |
-
"""
|
| 45 |
-
|
| 46 |
-
import argparse
|
| 47 |
-
import base64
|
| 48 |
-
import io
|
| 49 |
-
import json
|
| 50 |
-
import logging
|
| 51 |
-
import os
|
| 52 |
-
import sys
|
| 53 |
-
from datetime import datetime, timezone
|
| 54 |
-
from typing import Any, Dict, List, Optional, Union
|
| 55 |
-
from urllib.request import urlopen
|
| 56 |
-
|
| 57 |
-
# Disable vLLM's FlashInfer top-k/top-p sampler before the engine starts: it JIT-compiles
|
| 58 |
-
# at warmup and needs nvcc (absent from the default uv image). Harmless for greedy decoding.
|
| 59 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 60 |
-
|
| 61 |
-
import torch
|
| 62 |
-
from datasets import load_dataset
|
| 63 |
-
from huggingface_hub import DatasetCard, login
|
| 64 |
-
from PIL import Image
|
| 65 |
-
from toolz import partition_all
|
| 66 |
-
from tqdm import tqdm
|
| 67 |
-
from vllm import LLM, SamplingParams
|
| 68 |
-
|
| 69 |
-
logging.basicConfig(level=logging.INFO)
|
| 70 |
-
logger = logging.getLogger(__name__)
|
| 71 |
-
|
| 72 |
-
DEFAULT_MODEL = "LiquidAI/LFM2.5-VL-1.6B-Extract"
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
def check_cuda_availability() -> None:
|
| 76 |
-
if not torch.cuda.is_available():
|
| 77 |
-
logger.error("CUDA is not available. This script requires a GPU.")
|
| 78 |
-
logger.error("Run on Hugging Face Jobs with: hf jobs uv run --flavor l4x1 ...")
|
| 79 |
-
sys.exit(1)
|
| 80 |
-
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name()}")
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
def load_schema_arg(value: str) -> Dict[str, str]:
|
| 84 |
-
"""Resolve --schema (inline JSON, URL, or file path) into a {field: description} dict."""
|
| 85 |
-
text = value.strip()
|
| 86 |
-
if text.startswith("http://") or text.startswith("https://"):
|
| 87 |
-
logger.info(f"Loading schema from URL: {text}")
|
| 88 |
-
text = urlopen(text).read().decode("utf-8")
|
| 89 |
-
elif not text.startswith("{") and not text.startswith("["):
|
| 90 |
-
if os.path.exists(text):
|
| 91 |
-
logger.info(f"Loading schema from file: {text}")
|
| 92 |
-
with open(text) as f:
|
| 93 |
-
text = f.read()
|
| 94 |
-
parsed = json.loads(text)
|
| 95 |
-
# Accept {"field": "description"} or ["field1", "field2"]
|
| 96 |
-
if isinstance(parsed, list):
|
| 97 |
-
return {str(field): "" for field in parsed}
|
| 98 |
-
if isinstance(parsed, dict):
|
| 99 |
-
return {str(k): str(v) for k, v in parsed.items()}
|
| 100 |
-
raise ValueError("--schema must be a JSON object {field: description} or a JSON list of field names.")
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
def build_system_prompt(schema: Dict[str, str]) -> str:
|
| 104 |
-
"""LFM2.5-VL-Extract prompt: a field list in the system message → flat JSON out."""
|
| 105 |
-
lines = []
|
| 106 |
-
for field, desc in schema.items():
|
| 107 |
-
lines.append(f"{field}: {desc}" if desc else field)
|
| 108 |
-
fields_block = "\n".join(lines)
|
| 109 |
-
return (
|
| 110 |
-
f"Extract the following from the image:\n\n{fields_block}\n\n"
|
| 111 |
-
"Respond with only a JSON object."
|
| 112 |
-
)
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
def image_to_data_uri(image: Union[Image.Image, Dict[str, Any], str]) -> str:
|
| 116 |
-
if isinstance(image, dict) and "bytes" in image:
|
| 117 |
-
image = Image.open(io.BytesIO(image["bytes"]))
|
| 118 |
-
elif isinstance(image, str):
|
| 119 |
-
image = Image.open(image)
|
| 120 |
-
if image.mode != "RGB":
|
| 121 |
-
image = image.convert("RGB")
|
| 122 |
-
buf = io.BytesIO()
|
| 123 |
-
image.save(buf, format="PNG")
|
| 124 |
-
return f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
def make_message(image: Any, system_prompt: str) -> List[Dict]:
|
| 128 |
-
data_uri = image_to_data_uri(image)
|
| 129 |
-
return [
|
| 130 |
-
{"role": "system", "content": system_prompt},
|
| 131 |
-
{"role": "user", "content": [{"type": "image_url", "image_url": {"url": data_uri}}]},
|
| 132 |
-
]
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
def parse_json_output(text: str) -> tuple[Optional[Any], bool]:
|
| 136 |
-
"""Return (parsed, ok). Strips ```json fences if present."""
|
| 137 |
-
stripped = text.strip()
|
| 138 |
-
if stripped.startswith("```"):
|
| 139 |
-
stripped = stripped.split("\n", 1)[-1]
|
| 140 |
-
if stripped.endswith("```"):
|
| 141 |
-
stripped = stripped.rsplit("```", 1)[0]
|
| 142 |
-
stripped = stripped.strip()
|
| 143 |
-
try:
|
| 144 |
-
return json.loads(stripped), True
|
| 145 |
-
except (json.JSONDecodeError, ValueError):
|
| 146 |
-
return None, False
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
def main(
|
| 150 |
-
input_dataset: str,
|
| 151 |
-
output_dataset: str,
|
| 152 |
-
schema: str,
|
| 153 |
-
image_column: str = "image",
|
| 154 |
-
output_column: str = "extraction",
|
| 155 |
-
split: str = "train",
|
| 156 |
-
max_samples: Optional[int] = None,
|
| 157 |
-
shuffle: bool = False,
|
| 158 |
-
seed: int = 42,
|
| 159 |
-
batch_size: int = 16,
|
| 160 |
-
model: str = DEFAULT_MODEL,
|
| 161 |
-
max_model_len: int = 4096,
|
| 162 |
-
max_tokens: int = 1024,
|
| 163 |
-
private: bool = False,
|
| 164 |
-
hf_token: Optional[str] = None,
|
| 165 |
-
) -> None:
|
| 166 |
-
check_cuda_availability()
|
| 167 |
-
|
| 168 |
-
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
|
| 169 |
-
if HF_TOKEN:
|
| 170 |
-
login(token=HF_TOKEN)
|
| 171 |
-
|
| 172 |
-
schema_dict = load_schema_arg(schema)
|
| 173 |
-
system_prompt = build_system_prompt(schema_dict)
|
| 174 |
-
logger.info(f"Extraction fields: {list(schema_dict.keys())}")
|
| 175 |
-
|
| 176 |
-
logger.info(f"Loading dataset: {input_dataset} (split={split})")
|
| 177 |
-
dataset = load_dataset(input_dataset, split=split)
|
| 178 |
-
if shuffle:
|
| 179 |
-
dataset = dataset.shuffle(seed=seed)
|
| 180 |
-
if max_samples:
|
| 181 |
-
dataset = dataset.select(range(min(max_samples, len(dataset))))
|
| 182 |
-
logger.info(f"Processing {len(dataset)} examples")
|
| 183 |
-
|
| 184 |
-
if image_column not in dataset.column_names:
|
| 185 |
-
logger.error(f"Image column '{image_column}' not found. Columns: {dataset.column_names}")
|
| 186 |
-
sys.exit(1)
|
| 187 |
-
|
| 188 |
-
logger.info(f"Loading model: {model}")
|
| 189 |
-
llm = LLM(
|
| 190 |
-
model=model,
|
| 191 |
-
max_model_len=max_model_len,
|
| 192 |
-
limit_mm_per_prompt={"image": 1},
|
| 193 |
-
enforce_eager=True,
|
| 194 |
-
)
|
| 195 |
-
sampling_params = SamplingParams(temperature=0.0, max_tokens=max_tokens)
|
| 196 |
-
|
| 197 |
-
all_outputs: List[str] = []
|
| 198 |
-
n_valid = 0
|
| 199 |
-
images = dataset[image_column]
|
| 200 |
-
for batch in tqdm(list(partition_all(batch_size, images)), desc="Extracting"):
|
| 201 |
-
batch_messages = [make_message(img, system_prompt) for img in batch]
|
| 202 |
-
outputs = llm.chat(batch_messages, sampling_params)
|
| 203 |
-
for out in outputs:
|
| 204 |
-
text = out.outputs[0].text.strip()
|
| 205 |
-
parsed, ok = parse_json_output(text)
|
| 206 |
-
if ok:
|
| 207 |
-
n_valid += 1
|
| 208 |
-
all_outputs.append(json.dumps(parsed, ensure_ascii=False))
|
| 209 |
-
else:
|
| 210 |
-
all_outputs.append(text) # keep raw on parse failure
|
| 211 |
-
|
| 212 |
-
logger.info(f"Valid JSON: {n_valid}/{len(all_outputs)}")
|
| 213 |
-
|
| 214 |
-
dataset = dataset.add_column(output_column, all_outputs)
|
| 215 |
-
|
| 216 |
-
inference_entry = {
|
| 217 |
-
"model": model,
|
| 218 |
-
"column_name": output_column,
|
| 219 |
-
"task": "schema-guided extraction",
|
| 220 |
-
"fields": list(schema_dict.keys()),
|
| 221 |
-
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 222 |
-
"script": "lfm2-vl-extract.py",
|
| 223 |
-
}
|
| 224 |
-
if "inference_info" in dataset.column_names:
|
| 225 |
-
def update_info(example):
|
| 226 |
-
try:
|
| 227 |
-
existing = json.loads(example["inference_info"]) if example["inference_info"] else []
|
| 228 |
-
except (json.JSONDecodeError, TypeError):
|
| 229 |
-
existing = []
|
| 230 |
-
existing.append(inference_entry)
|
| 231 |
-
return {"inference_info": json.dumps(existing)}
|
| 232 |
-
dataset = dataset.map(update_info)
|
| 233 |
-
else:
|
| 234 |
-
dataset = dataset.add_column(
|
| 235 |
-
"inference_info", [json.dumps([inference_entry])] * len(dataset)
|
| 236 |
-
)
|
| 237 |
-
|
| 238 |
-
logger.info(f"Pushing to {output_dataset}")
|
| 239 |
-
dataset.push_to_hub(output_dataset, private=private, token=HF_TOKEN)
|
| 240 |
-
|
| 241 |
-
card_text = f"""---
|
| 242 |
-
tags:
|
| 243 |
-
- uv-script
|
| 244 |
-
- extraction
|
| 245 |
-
- lfm2-vl
|
| 246 |
-
- json
|
| 247 |
-
---
|
| 248 |
-
|
| 249 |
-
# Structured extraction with LFM2.5-VL-1.6B-Extract
|
| 250 |
-
|
| 251 |
-
JSON fields extracted from images in [{input_dataset}](https://huggingface.co/datasets/{input_dataset})
|
| 252 |
-
using [{model}](https://huggingface.co/{model}).
|
| 253 |
-
|
| 254 |
-
- **Source**: `{input_dataset}` (split `{split}`)
|
| 255 |
-
- **Model**: `{model}`
|
| 256 |
-
- **Fields**: {", ".join(f"`{k}`" for k in schema_dict.keys())}
|
| 257 |
-
- **Output column**: `{output_column}` (JSON string per row)
|
| 258 |
-
- **Valid JSON**: {n_valid}/{len(all_outputs)}
|
| 259 |
-
- **Date**: {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}
|
| 260 |
-
|
| 261 |
-
Generated with the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) `lfm2-vl-extract.py` script.
|
| 262 |
-
"""
|
| 263 |
-
try:
|
| 264 |
-
card = DatasetCard(card_text)
|
| 265 |
-
card.push_to_hub(output_dataset, token=HF_TOKEN)
|
| 266 |
-
except Exception as e:
|
| 267 |
-
logger.warning(f"Could not push dataset card: {e}")
|
| 268 |
-
|
| 269 |
-
logger.info("Done! Extraction complete.")
|
| 270 |
-
logger.info(f"Dataset: https://huggingface.co/datasets/{output_dataset}")
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
if __name__ == "__main__":
|
| 274 |
-
if len(sys.argv) == 1:
|
| 275 |
-
print("LFM2.5-VL-1.6B-Extract — schema-guided JSON extraction from images")
|
| 276 |
-
print("\nUsage:")
|
| 277 |
-
print(" uv run lfm2-vl-extract.py INPUT OUTPUT --schema SCHEMA [options]")
|
| 278 |
-
print("\nExample:")
|
| 279 |
-
print(' uv run lfm2-vl-extract.py my-images my-extractions \\')
|
| 280 |
-
print(' --schema \'{"title": "the document title", "date": "any date shown"}\'')
|
| 281 |
-
print("\n --schema accepts inline JSON, a URL, or a file path.")
|
| 282 |
-
print("\nFor full help: uv run lfm2-vl-extract.py --help")
|
| 283 |
-
sys.exit(0)
|
| 284 |
-
|
| 285 |
-
parser = argparse.ArgumentParser(
|
| 286 |
-
description="Schema-guided JSON extraction from images using LFM2.5-VL-1.6B-Extract",
|
| 287 |
-
)
|
| 288 |
-
parser.add_argument("input_dataset", help="Input dataset ID (with images)")
|
| 289 |
-
parser.add_argument("output_dataset", help="Output dataset ID")
|
| 290 |
-
parser.add_argument(
|
| 291 |
-
"--schema", required=True,
|
| 292 |
-
help="Fields to extract: inline JSON {field: description}, a URL, or a file path",
|
| 293 |
-
)
|
| 294 |
-
parser.add_argument("--image-column", default="image", help="Image column (default: image)")
|
| 295 |
-
parser.add_argument("--output-column", default="extraction", help="Output column (default: extraction)")
|
| 296 |
-
parser.add_argument("--split", default="train", help="Dataset split (default: train)")
|
| 297 |
-
parser.add_argument("--max-samples", type=int, help="Limit number of samples")
|
| 298 |
-
parser.add_argument("--shuffle", action="store_true", help="Shuffle before sampling")
|
| 299 |
-
parser.add_argument("--seed", type=int, default=42, help="Shuffle seed (default: 42)")
|
| 300 |
-
parser.add_argument("--batch-size", type=int, default=16, help="Batch size (default: 16)")
|
| 301 |
-
parser.add_argument("--model", default=DEFAULT_MODEL, help=f"Model (default: {DEFAULT_MODEL})")
|
| 302 |
-
parser.add_argument("--max-model-len", type=int, default=4096, help="Max context length (default: 4096)")
|
| 303 |
-
parser.add_argument("--max-tokens", type=int, default=1024, help="Max output tokens (default: 1024)")
|
| 304 |
-
parser.add_argument("--private", action="store_true", help="Make output dataset private")
|
| 305 |
-
parser.add_argument("--hf-token", help="HF token (or set HF_TOKEN)")
|
| 306 |
-
args = parser.parse_args()
|
| 307 |
-
|
| 308 |
-
main(
|
| 309 |
-
input_dataset=args.input_dataset,
|
| 310 |
-
output_dataset=args.output_dataset,
|
| 311 |
-
schema=args.schema,
|
| 312 |
-
image_column=args.image_column,
|
| 313 |
-
output_column=args.output_column,
|
| 314 |
-
split=args.split,
|
| 315 |
-
max_samples=args.max_samples,
|
| 316 |
-
shuffle=args.shuffle,
|
| 317 |
-
seed=args.seed,
|
| 318 |
-
batch_size=args.batch_size,
|
| 319 |
-
model=args.model,
|
| 320 |
-
max_model_len=args.max_model_len,
|
| 321 |
-
max_tokens=args.max_tokens,
|
| 322 |
-
private=args.private,
|
| 323 |
-
hf_token=args.hf_token,
|
| 324 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
lighton-ocr.py
CHANGED
|
@@ -57,10 +57,6 @@ from huggingface_hub import DatasetCard, login
|
|
| 57 |
from PIL import Image
|
| 58 |
from toolz import partition_all
|
| 59 |
from tqdm.auto import tqdm
|
| 60 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 61 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 62 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 63 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 64 |
from vllm import LLM, SamplingParams
|
| 65 |
|
| 66 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 57 |
from PIL import Image
|
| 58 |
from toolz import partition_all
|
| 59 |
from tqdm.auto import tqdm
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
from vllm import LLM, SamplingParams
|
| 61 |
|
| 62 |
logging.basicConfig(level=logging.INFO)
|
lighton-ocr2.py
CHANGED
|
@@ -53,10 +53,6 @@ from huggingface_hub import DatasetCard, login
|
|
| 53 |
from PIL import Image
|
| 54 |
from toolz import partition_all
|
| 55 |
from tqdm.auto import tqdm
|
| 56 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 57 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 58 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 59 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 60 |
from vllm import LLM, SamplingParams
|
| 61 |
|
| 62 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 53 |
from PIL import Image
|
| 54 |
from toolz import partition_all
|
| 55 |
from tqdm.auto import tqdm
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
from vllm import LLM, SamplingParams
|
| 57 |
|
| 58 |
logging.basicConfig(level=logging.INFO)
|
nanonets-ocr.py
CHANGED
|
@@ -40,10 +40,6 @@ from huggingface_hub import DatasetCard, login
|
|
| 40 |
from PIL import Image
|
| 41 |
from toolz import partition_all
|
| 42 |
from tqdm.auto import tqdm
|
| 43 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 44 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 45 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 46 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 47 |
from vllm import LLM, SamplingParams
|
| 48 |
from datetime import datetime
|
| 49 |
|
|
|
|
| 40 |
from PIL import Image
|
| 41 |
from toolz import partition_all
|
| 42 |
from tqdm.auto import tqdm
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
from vllm import LLM, SamplingParams
|
| 44 |
from datetime import datetime
|
| 45 |
|
nanonets-ocr2.py
CHANGED
|
@@ -44,10 +44,6 @@ from huggingface_hub import DatasetCard, login
|
|
| 44 |
from PIL import Image
|
| 45 |
from toolz import partition_all
|
| 46 |
from tqdm.auto import tqdm
|
| 47 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 48 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 49 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 50 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 51 |
from vllm import LLM, SamplingParams
|
| 52 |
|
| 53 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 44 |
from PIL import Image
|
| 45 |
from toolz import partition_all
|
| 46 |
from tqdm.auto import tqdm
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
from vllm import LLM, SamplingParams
|
| 48 |
|
| 49 |
logging.basicConfig(level=logging.INFO)
|
nuextract3.py
DELETED
|
@@ -1,749 +0,0 @@
|
|
| 1 |
-
# /// script
|
| 2 |
-
# requires-python = ">=3.11"
|
| 3 |
-
# dependencies = [
|
| 4 |
-
# "datasets>=3.1.0",
|
| 5 |
-
# "huggingface-hub",
|
| 6 |
-
# "pillow",
|
| 7 |
-
# "vllm",
|
| 8 |
-
# "toolz",
|
| 9 |
-
# "torch",
|
| 10 |
-
# "numind",
|
| 11 |
-
# ]
|
| 12 |
-
# ///
|
| 13 |
-
|
| 14 |
-
"""
|
| 15 |
-
Convert document images to markdown OR extract structured JSON using NuExtract3 with vLLM.
|
| 16 |
-
|
| 17 |
-
NuExtract3 is a 4B Qwen3.5-based VLM for document understanding. It does two things:
|
| 18 |
-
|
| 19 |
-
1. Document-to-Markdown OCR (default): images -> clean markdown with HTML tables,
|
| 20 |
-
LaTeX math, and <figure> tags.
|
| 21 |
-
2. Schema-guided structured extraction: images + a JSON template -> JSON output
|
| 22 |
-
shaped exactly like the template. Useful for invoices, receipts, forms, contracts.
|
| 23 |
-
|
| 24 |
-
Modes are selected via flags:
|
| 25 |
-
- (no flags) -> markdown OCR
|
| 26 |
-
- --mode content -> plain-content extraction
|
| 27 |
-
- --template SOURCE -> structured extraction with a NuExtract template
|
| 28 |
-
- --schema SOURCE -> structured extraction with a JSON Schema
|
| 29 |
-
(auto-converted via numind.nuextract_utils)
|
| 30 |
-
- --instructions STR -> free-text guidance passed through to the model
|
| 31 |
-
(output-format rules, branch routing, etc.).
|
| 32 |
-
Combines with any of the modes above.
|
| 33 |
-
See https://huggingface.co/numind/NuExtract3#instructions
|
| 34 |
-
|
| 35 |
-
--template / --schema each accept inline JSON, a URL, or a local file path, so a
|
| 36 |
-
schema can be hosted (e.g. on an HF dataset's raw URL) and reused across jobs:
|
| 37 |
-
--template https://huggingface.co/datasets/ORG/REPO/raw/main/card.json
|
| 38 |
-
|
| 39 |
-
HF Jobs invocation (recommended): use the vllm/vllm-openai:latest image so the
|
| 40 |
-
pre-built CUDA kernels (flashinfer etc.) are reused — the default uv-script
|
| 41 |
-
image lacks nvcc and flashinfer's JIT compile fails at engine warmup.
|
| 42 |
-
|
| 43 |
-
hf jobs uv run \\
|
| 44 |
-
--image vllm/vllm-openai:latest \\
|
| 45 |
-
--flavor a100-large \\
|
| 46 |
-
--python /usr/bin/python3 \\
|
| 47 |
-
-e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\
|
| 48 |
-
-s HF_TOKEN \\
|
| 49 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nuextract3.py \\
|
| 50 |
-
INPUT_DATASET OUTPUT_DATASET --max-samples 5 --shuffle --seed 42
|
| 51 |
-
|
| 52 |
-
Model: numind/NuExtract3
|
| 53 |
-
License: Apache-2.0
|
| 54 |
-
"""
|
| 55 |
-
|
| 56 |
-
import argparse
|
| 57 |
-
import base64
|
| 58 |
-
import io
|
| 59 |
-
import json
|
| 60 |
-
import logging
|
| 61 |
-
import os
|
| 62 |
-
import sys
|
| 63 |
-
import time
|
| 64 |
-
from datetime import datetime
|
| 65 |
-
from pathlib import Path
|
| 66 |
-
from typing import Any, Dict, List, Optional, Union
|
| 67 |
-
|
| 68 |
-
import torch
|
| 69 |
-
from datasets import load_dataset
|
| 70 |
-
from huggingface_hub import DatasetCard, login
|
| 71 |
-
from PIL import Image
|
| 72 |
-
from toolz import partition_all
|
| 73 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 74 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 75 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 76 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 77 |
-
from vllm import LLM, SamplingParams
|
| 78 |
-
|
| 79 |
-
logging.basicConfig(level=logging.INFO)
|
| 80 |
-
logger = logging.getLogger(__name__)
|
| 81 |
-
|
| 82 |
-
MODEL_DEFAULT = "numind/NuExtract3"
|
| 83 |
-
MODEL_NAME = "NuExtract3"
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
def check_cuda_availability():
|
| 87 |
-
"""Check if CUDA is available and exit if not."""
|
| 88 |
-
if not torch.cuda.is_available():
|
| 89 |
-
logger.error("CUDA is not available. This script requires a GPU.")
|
| 90 |
-
logger.error("Please run on a machine with a CUDA-capable GPU.")
|
| 91 |
-
sys.exit(1)
|
| 92 |
-
else:
|
| 93 |
-
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
def load_template_arg(value: Optional[str]) -> Optional[Dict[str, Any]]:
|
| 97 |
-
"""Load a NuExtract template/JSON Schema from inline JSON, a URL, or a file path."""
|
| 98 |
-
if value is None:
|
| 99 |
-
return None
|
| 100 |
-
text = value
|
| 101 |
-
if value.startswith(("http://", "https://")):
|
| 102 |
-
import urllib.request
|
| 103 |
-
|
| 104 |
-
with urllib.request.urlopen(value) as resp: # noqa: S310
|
| 105 |
-
text = resp.read().decode("utf-8")
|
| 106 |
-
elif "{" not in value:
|
| 107 |
-
# Inline JSON often exceeds the OS filename limit, so only probe the
|
| 108 |
-
# filesystem when the value doesn't look like JSON; treat OSError as
|
| 109 |
-
# "not a path".
|
| 110 |
-
try:
|
| 111 |
-
candidate_path = Path(value)
|
| 112 |
-
if candidate_path.is_file():
|
| 113 |
-
text = candidate_path.read_text()
|
| 114 |
-
except OSError:
|
| 115 |
-
pass
|
| 116 |
-
try:
|
| 117 |
-
return json.loads(text)
|
| 118 |
-
except json.JSONDecodeError as e:
|
| 119 |
-
raise ValueError(
|
| 120 |
-
f"Could not parse template/schema as JSON (tried URL/path/inline): {e}"
|
| 121 |
-
) from e
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
def resolve_template(
|
| 125 |
-
template_arg: Optional[str],
|
| 126 |
-
schema_arg: Optional[str],
|
| 127 |
-
) -> Optional[Dict[str, Any]]:
|
| 128 |
-
"""Resolve --template / --schema into a NuExtract template dict, or None."""
|
| 129 |
-
if template_arg and schema_arg:
|
| 130 |
-
raise ValueError("--template and --schema are mutually exclusive.")
|
| 131 |
-
|
| 132 |
-
if template_arg is not None:
|
| 133 |
-
return load_template_arg(template_arg)
|
| 134 |
-
|
| 135 |
-
if schema_arg is not None:
|
| 136 |
-
schema = load_template_arg(schema_arg)
|
| 137 |
-
try:
|
| 138 |
-
from numind.nuextract_utils import convert_json_schema_to_nuextract_template
|
| 139 |
-
except ImportError as e:
|
| 140 |
-
raise RuntimeError(
|
| 141 |
-
"--schema requires the `numind` package. "
|
| 142 |
-
"It should be listed in this script's PEP 723 dependencies."
|
| 143 |
-
) from e
|
| 144 |
-
template, dropped = convert_json_schema_to_nuextract_template(schema)
|
| 145 |
-
if dropped:
|
| 146 |
-
logger.warning(
|
| 147 |
-
f"numind dropped {len(dropped)} unsupported branches from the JSON Schema: "
|
| 148 |
-
f"{dropped}"
|
| 149 |
-
)
|
| 150 |
-
return template
|
| 151 |
-
|
| 152 |
-
return None
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
def image_to_data_uri(image: Union[Image.Image, Dict[str, Any], str]) -> str:
|
| 156 |
-
"""Normalize an HF dataset image cell to a PNG data URI."""
|
| 157 |
-
if isinstance(image, Image.Image):
|
| 158 |
-
pil_img = image
|
| 159 |
-
elif isinstance(image, dict) and "bytes" in image:
|
| 160 |
-
pil_img = Image.open(io.BytesIO(image["bytes"]))
|
| 161 |
-
elif isinstance(image, str):
|
| 162 |
-
pil_img = Image.open(image)
|
| 163 |
-
else:
|
| 164 |
-
raise ValueError(f"Unsupported image type: {type(image)}")
|
| 165 |
-
|
| 166 |
-
pil_img = pil_img.convert("RGB")
|
| 167 |
-
buf = io.BytesIO()
|
| 168 |
-
pil_img.save(buf, format="PNG")
|
| 169 |
-
return f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
def make_message(image: Union[Image.Image, Dict[str, Any], str]) -> List[Dict]:
|
| 173 |
-
"""Build an OpenAI-format chat message containing one image."""
|
| 174 |
-
data_uri = image_to_data_uri(image)
|
| 175 |
-
return [
|
| 176 |
-
{
|
| 177 |
-
"role": "user",
|
| 178 |
-
"content": [
|
| 179 |
-
{"type": "image_url", "image_url": {"url": data_uri}},
|
| 180 |
-
],
|
| 181 |
-
}
|
| 182 |
-
]
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
def split_thinking(text: str) -> tuple[Optional[str], str]:
|
| 186 |
-
"""Return (reasoning, answer) if <think>...</think> is present, else (None, text)."""
|
| 187 |
-
if "<think>" in text and "</think>" in text:
|
| 188 |
-
reasoning = text.split("<think>", 1)[1].split("</think>", 1)[0].strip()
|
| 189 |
-
answer = text.split("</think>", 1)[1].strip()
|
| 190 |
-
return reasoning, answer
|
| 191 |
-
return None, text.strip()
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
def parse_json_output(text: str) -> tuple[Optional[Any], bool]:
|
| 195 |
-
"""Parse an extraction output; strip ``` fences as the model card describes.
|
| 196 |
-
|
| 197 |
-
Returns (parsed_value, parse_error). On failure, parsed_value is None.
|
| 198 |
-
"""
|
| 199 |
-
stripped = text.strip()
|
| 200 |
-
if stripped.startswith("```"):
|
| 201 |
-
stripped = stripped.split("\n", 1)[-1] if "\n" in stripped else stripped[3:]
|
| 202 |
-
if stripped.endswith("```"):
|
| 203 |
-
stripped = stripped[:-3].rstrip()
|
| 204 |
-
try:
|
| 205 |
-
return json.loads(stripped), False
|
| 206 |
-
except json.JSONDecodeError:
|
| 207 |
-
return None, True
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
def create_dataset_card(
|
| 211 |
-
source_dataset: str,
|
| 212 |
-
model: str,
|
| 213 |
-
num_samples: int,
|
| 214 |
-
processing_time: str,
|
| 215 |
-
mode_label: str,
|
| 216 |
-
template: Optional[Dict[str, Any]],
|
| 217 |
-
enable_thinking: bool,
|
| 218 |
-
temperature: float,
|
| 219 |
-
output_column: str,
|
| 220 |
-
image_column: str,
|
| 221 |
-
split: str,
|
| 222 |
-
) -> str:
|
| 223 |
-
"""Create a dataset card documenting the NuExtract3 run."""
|
| 224 |
-
model_name = model.split("/")[-1]
|
| 225 |
-
template_block = ""
|
| 226 |
-
if template is not None:
|
| 227 |
-
template_block = (
|
| 228 |
-
"\n### Extraction Template\n\n```json\n"
|
| 229 |
-
+ json.dumps(template, indent=2)
|
| 230 |
-
+ "\n```\n"
|
| 231 |
-
)
|
| 232 |
-
|
| 233 |
-
return f"""---
|
| 234 |
-
tags:
|
| 235 |
-
- ocr
|
| 236 |
-
- structured-extraction
|
| 237 |
-
- document-processing
|
| 238 |
-
- nuextract3
|
| 239 |
-
- markdown
|
| 240 |
-
- uv-script
|
| 241 |
-
- generated
|
| 242 |
-
---
|
| 243 |
-
|
| 244 |
-
# {model_name} on {source_dataset}
|
| 245 |
-
|
| 246 |
-
This dataset contains outputs from [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) processed with [NuExtract3](https://huggingface.co/{model}), a 4B vision-language model for document understanding.
|
| 247 |
-
|
| 248 |
-
## Processing Details
|
| 249 |
-
|
| 250 |
-
- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
|
| 251 |
-
- **Model**: [{model}](https://huggingface.co/{model})
|
| 252 |
-
- **Mode**: {mode_label}
|
| 253 |
-
- **Number of Samples**: {num_samples:,}
|
| 254 |
-
- **Processing Time**: {processing_time}
|
| 255 |
-
- **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
|
| 256 |
-
|
| 257 |
-
### Configuration
|
| 258 |
-
|
| 259 |
-
- **Image Column**: `{image_column}`
|
| 260 |
-
- **Output Column**: `{output_column}`
|
| 261 |
-
- **Dataset Split**: `{split}`
|
| 262 |
-
- **Temperature**: {temperature}
|
| 263 |
-
- **Thinking Mode**: {"enabled" if enable_thinking else "disabled"}
|
| 264 |
-
{template_block}
|
| 265 |
-
## Dataset Structure
|
| 266 |
-
|
| 267 |
-
Original columns plus:
|
| 268 |
-
- `{output_column}`: NuExtract3 output ({"JSON string" if template else "markdown"})
|
| 269 |
-
- `inference_info`: JSON list tracking models applied to this dataset
|
| 270 |
-
{"- `" + output_column + "_reasoning`: model's thinking trace (when enabled)" if enable_thinking else ""}
|
| 271 |
-
|
| 272 |
-
Generated with [UV Scripts](https://huggingface.co/uv-scripts)
|
| 273 |
-
"""
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
def main(
|
| 277 |
-
input_dataset: str,
|
| 278 |
-
output_dataset: str,
|
| 279 |
-
image_column: str = "image",
|
| 280 |
-
batch_size: int = 16,
|
| 281 |
-
max_model_len: int = 16384,
|
| 282 |
-
max_tokens: int = 8192,
|
| 283 |
-
gpu_memory_utilization: float = 0.8,
|
| 284 |
-
mode: str = "markdown",
|
| 285 |
-
template_arg: Optional[str] = None,
|
| 286 |
-
schema_arg: Optional[str] = None,
|
| 287 |
-
enable_thinking: bool = False,
|
| 288 |
-
instructions: Optional[str] = None,
|
| 289 |
-
temperature: Optional[float] = None,
|
| 290 |
-
model: str = MODEL_DEFAULT,
|
| 291 |
-
hf_token: str = None,
|
| 292 |
-
split: str = "train",
|
| 293 |
-
max_samples: int = None,
|
| 294 |
-
private: bool = False,
|
| 295 |
-
shuffle: bool = False,
|
| 296 |
-
seed: int = 42,
|
| 297 |
-
output_column: Optional[str] = None,
|
| 298 |
-
verbose: bool = False,
|
| 299 |
-
config: str = None,
|
| 300 |
-
create_pr: bool = False,
|
| 301 |
-
):
|
| 302 |
-
"""Process images from an HF dataset through NuExtract3."""
|
| 303 |
-
|
| 304 |
-
check_cuda_availability()
|
| 305 |
-
start_time = datetime.now()
|
| 306 |
-
|
| 307 |
-
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
|
| 308 |
-
if HF_TOKEN:
|
| 309 |
-
login(token=HF_TOKEN)
|
| 310 |
-
|
| 311 |
-
template = resolve_template(template_arg, schema_arg)
|
| 312 |
-
extraction_mode = template is not None
|
| 313 |
-
mode_label = "structured-extraction" if extraction_mode else mode
|
| 314 |
-
|
| 315 |
-
if output_column is None:
|
| 316 |
-
output_column = "extraction" if extraction_mode else "markdown"
|
| 317 |
-
|
| 318 |
-
if temperature is None:
|
| 319 |
-
temperature = 0.6 if enable_thinking else 0.2
|
| 320 |
-
|
| 321 |
-
logger.info(f"Using model: {model}")
|
| 322 |
-
logger.info(f"Mode: {mode_label}")
|
| 323 |
-
logger.info(f"Thinking: {enable_thinking} Temperature: {temperature}")
|
| 324 |
-
if extraction_mode:
|
| 325 |
-
logger.info(f"Template: {json.dumps(template, indent=2)}")
|
| 326 |
-
|
| 327 |
-
logger.info(f"Loading dataset: {input_dataset}")
|
| 328 |
-
dataset = load_dataset(input_dataset, split=split)
|
| 329 |
-
|
| 330 |
-
if image_column not in dataset.column_names:
|
| 331 |
-
raise ValueError(
|
| 332 |
-
f"Column '{image_column}' not found. Available: {dataset.column_names}"
|
| 333 |
-
)
|
| 334 |
-
|
| 335 |
-
if shuffle:
|
| 336 |
-
logger.info(f"Shuffling dataset with seed {seed}")
|
| 337 |
-
dataset = dataset.shuffle(seed=seed)
|
| 338 |
-
|
| 339 |
-
if max_samples:
|
| 340 |
-
dataset = dataset.select(range(min(max_samples, len(dataset))))
|
| 341 |
-
logger.info(f"Limited to {len(dataset)} samples")
|
| 342 |
-
|
| 343 |
-
logger.info("Initializing vLLM with NuExtract3")
|
| 344 |
-
logger.info("This may take a few minutes on first run...")
|
| 345 |
-
llm = LLM(
|
| 346 |
-
model=model,
|
| 347 |
-
trust_remote_code=True,
|
| 348 |
-
max_model_len=max_model_len,
|
| 349 |
-
gpu_memory_utilization=gpu_memory_utilization,
|
| 350 |
-
limit_mm_per_prompt={"image": 1},
|
| 351 |
-
)
|
| 352 |
-
|
| 353 |
-
sampling_params = SamplingParams(
|
| 354 |
-
temperature=temperature,
|
| 355 |
-
max_tokens=max_tokens,
|
| 356 |
-
)
|
| 357 |
-
|
| 358 |
-
chat_template_kwargs: Dict[str, Any] = {"enable_thinking": enable_thinking}
|
| 359 |
-
if extraction_mode:
|
| 360 |
-
chat_template_kwargs["template"] = json.dumps(template, indent=4)
|
| 361 |
-
else:
|
| 362 |
-
chat_template_kwargs["mode"] = mode
|
| 363 |
-
if instructions:
|
| 364 |
-
chat_template_kwargs["instructions"] = instructions
|
| 365 |
-
|
| 366 |
-
logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
|
| 367 |
-
logger.info(f"Output will be written to column: {output_column}")
|
| 368 |
-
|
| 369 |
-
all_outputs: List[str] = []
|
| 370 |
-
all_reasoning: List[Optional[str]] = []
|
| 371 |
-
all_parse_errors: List[bool] = []
|
| 372 |
-
total_batches = (len(dataset) + batch_size - 1) // batch_size
|
| 373 |
-
processed = 0
|
| 374 |
-
|
| 375 |
-
for batch_num, batch_indices in enumerate(
|
| 376 |
-
partition_all(batch_size, range(len(dataset))), 1
|
| 377 |
-
):
|
| 378 |
-
batch_indices = list(batch_indices)
|
| 379 |
-
batch_images = [dataset[i][image_column] for i in batch_indices]
|
| 380 |
-
|
| 381 |
-
logger.info(
|
| 382 |
-
f"Batch {batch_num}/{total_batches} "
|
| 383 |
-
f"({processed}/{len(dataset)} images done)"
|
| 384 |
-
)
|
| 385 |
-
|
| 386 |
-
try:
|
| 387 |
-
batch_messages = [make_message(img) for img in batch_images]
|
| 388 |
-
outputs = llm.chat(
|
| 389 |
-
batch_messages,
|
| 390 |
-
sampling_params,
|
| 391 |
-
chat_template_kwargs=chat_template_kwargs,
|
| 392 |
-
chat_template_content_format="openai",
|
| 393 |
-
)
|
| 394 |
-
|
| 395 |
-
for output in outputs:
|
| 396 |
-
raw_text = output.outputs[0].text
|
| 397 |
-
reasoning, answer = split_thinking(raw_text)
|
| 398 |
-
|
| 399 |
-
if extraction_mode:
|
| 400 |
-
parsed, parse_error = parse_json_output(answer)
|
| 401 |
-
stored = (
|
| 402 |
-
json.dumps(parsed, ensure_ascii=False)
|
| 403 |
-
if parsed is not None
|
| 404 |
-
else answer
|
| 405 |
-
)
|
| 406 |
-
all_outputs.append(stored)
|
| 407 |
-
all_parse_errors.append(parse_error)
|
| 408 |
-
else:
|
| 409 |
-
all_outputs.append(answer)
|
| 410 |
-
all_parse_errors.append(False)
|
| 411 |
-
|
| 412 |
-
all_reasoning.append(reasoning)
|
| 413 |
-
|
| 414 |
-
processed += len(batch_images)
|
| 415 |
-
|
| 416 |
-
except Exception as e:
|
| 417 |
-
logger.error(f"Error processing batch: {e}")
|
| 418 |
-
all_outputs.extend(["[NUEXTRACT3 ERROR]"] * len(batch_images))
|
| 419 |
-
all_reasoning.extend([None] * len(batch_images))
|
| 420 |
-
all_parse_errors.extend([True] * len(batch_images))
|
| 421 |
-
processed += len(batch_images)
|
| 422 |
-
|
| 423 |
-
processing_duration = datetime.now() - start_time
|
| 424 |
-
processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
|
| 425 |
-
|
| 426 |
-
logger.info(f"Adding '{output_column}' column to dataset")
|
| 427 |
-
dataset = dataset.add_column(output_column, all_outputs)
|
| 428 |
-
|
| 429 |
-
if enable_thinking and any(r is not None for r in all_reasoning):
|
| 430 |
-
reasoning_col = f"{output_column}_reasoning"
|
| 431 |
-
logger.info(f"Adding '{reasoning_col}' column to dataset")
|
| 432 |
-
dataset = dataset.add_column(reasoning_col, all_reasoning)
|
| 433 |
-
|
| 434 |
-
if extraction_mode:
|
| 435 |
-
parse_error_count = sum(all_parse_errors)
|
| 436 |
-
if parse_error_count:
|
| 437 |
-
logger.warning(
|
| 438 |
-
f"{parse_error_count}/{len(all_parse_errors)} extractions failed to parse as JSON"
|
| 439 |
-
)
|
| 440 |
-
|
| 441 |
-
inference_entry = {
|
| 442 |
-
"model_id": model,
|
| 443 |
-
"model_name": MODEL_NAME,
|
| 444 |
-
"column_name": output_column,
|
| 445 |
-
"timestamp": datetime.now().isoformat(),
|
| 446 |
-
"mode": mode_label,
|
| 447 |
-
"has_template": extraction_mode,
|
| 448 |
-
"enable_thinking": enable_thinking,
|
| 449 |
-
"temperature": temperature,
|
| 450 |
-
"max_tokens": max_tokens,
|
| 451 |
-
}
|
| 452 |
-
if extraction_mode:
|
| 453 |
-
inference_entry["parse_error_rate"] = (
|
| 454 |
-
sum(all_parse_errors) / len(all_parse_errors) if all_parse_errors else 0.0
|
| 455 |
-
)
|
| 456 |
-
|
| 457 |
-
if "inference_info" in dataset.column_names:
|
| 458 |
-
logger.info("Updating existing inference_info column")
|
| 459 |
-
|
| 460 |
-
def update_inference_info(example):
|
| 461 |
-
try:
|
| 462 |
-
existing_info = (
|
| 463 |
-
json.loads(example["inference_info"])
|
| 464 |
-
if example["inference_info"]
|
| 465 |
-
else []
|
| 466 |
-
)
|
| 467 |
-
except (json.JSONDecodeError, TypeError):
|
| 468 |
-
existing_info = []
|
| 469 |
-
existing_info.append(inference_entry)
|
| 470 |
-
return {"inference_info": json.dumps(existing_info)}
|
| 471 |
-
|
| 472 |
-
dataset = dataset.map(update_inference_info)
|
| 473 |
-
else:
|
| 474 |
-
logger.info("Creating new inference_info column")
|
| 475 |
-
inference_list = [json.dumps([inference_entry])] * len(dataset)
|
| 476 |
-
dataset = dataset.add_column("inference_info", inference_list)
|
| 477 |
-
|
| 478 |
-
logger.info(f"Pushing to {output_dataset}")
|
| 479 |
-
max_retries = 3
|
| 480 |
-
for attempt in range(1, max_retries + 1):
|
| 481 |
-
try:
|
| 482 |
-
if attempt > 1:
|
| 483 |
-
logger.warning("Disabling XET (fallback to HTTP upload)")
|
| 484 |
-
os.environ["HF_HUB_DISABLE_XET"] = "1"
|
| 485 |
-
dataset.push_to_hub(
|
| 486 |
-
output_dataset,
|
| 487 |
-
private=private,
|
| 488 |
-
token=HF_TOKEN,
|
| 489 |
-
max_shard_size="500MB",
|
| 490 |
-
**({"config_name": config} if config else {}),
|
| 491 |
-
create_pr=create_pr,
|
| 492 |
-
commit_message=f"Add {model} {mode_label} results ({len(dataset)} samples)"
|
| 493 |
-
+ (f" [{config}]" if config else ""),
|
| 494 |
-
)
|
| 495 |
-
break
|
| 496 |
-
except Exception as e:
|
| 497 |
-
logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
|
| 498 |
-
if attempt < max_retries:
|
| 499 |
-
delay = 30 * (2 ** (attempt - 1))
|
| 500 |
-
logger.info(f"Retrying in {delay}s...")
|
| 501 |
-
time.sleep(delay)
|
| 502 |
-
else:
|
| 503 |
-
logger.error("All upload attempts failed. Results are lost.")
|
| 504 |
-
sys.exit(1)
|
| 505 |
-
|
| 506 |
-
logger.info("Creating dataset card")
|
| 507 |
-
card_content = create_dataset_card(
|
| 508 |
-
source_dataset=input_dataset,
|
| 509 |
-
model=model,
|
| 510 |
-
num_samples=len(dataset),
|
| 511 |
-
processing_time=processing_time_str,
|
| 512 |
-
mode_label=mode_label,
|
| 513 |
-
template=template,
|
| 514 |
-
enable_thinking=enable_thinking,
|
| 515 |
-
temperature=temperature,
|
| 516 |
-
output_column=output_column,
|
| 517 |
-
image_column=image_column,
|
| 518 |
-
split=split,
|
| 519 |
-
)
|
| 520 |
-
card = DatasetCard(card_content)
|
| 521 |
-
card.push_to_hub(output_dataset, token=HF_TOKEN)
|
| 522 |
-
|
| 523 |
-
logger.info("Done! NuExtract3 processing complete.")
|
| 524 |
-
logger.info(
|
| 525 |
-
f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
|
| 526 |
-
)
|
| 527 |
-
logger.info(f"Processing time: {processing_time_str}")
|
| 528 |
-
logger.info(
|
| 529 |
-
f"Processing speed: {len(dataset) / processing_duration.total_seconds():.2f} images/sec"
|
| 530 |
-
)
|
| 531 |
-
|
| 532 |
-
if verbose:
|
| 533 |
-
import importlib.metadata
|
| 534 |
-
|
| 535 |
-
logger.info("--- Resolved package versions ---")
|
| 536 |
-
for pkg in [
|
| 537 |
-
"vllm",
|
| 538 |
-
"transformers",
|
| 539 |
-
"torch",
|
| 540 |
-
"datasets",
|
| 541 |
-
"pyarrow",
|
| 542 |
-
"pillow",
|
| 543 |
-
"numind",
|
| 544 |
-
]:
|
| 545 |
-
try:
|
| 546 |
-
logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
|
| 547 |
-
except importlib.metadata.PackageNotFoundError:
|
| 548 |
-
logger.info(f" {pkg}: not installed")
|
| 549 |
-
logger.info("--- End versions ---")
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
if __name__ == "__main__":
|
| 553 |
-
if len(sys.argv) == 1:
|
| 554 |
-
print("=" * 70)
|
| 555 |
-
print("NuExtract3 - Document-to-Markdown + Structured Extraction (4B)")
|
| 556 |
-
print("=" * 70)
|
| 557 |
-
print("\nModes:")
|
| 558 |
-
print(" markdown - Image -> markdown (default)")
|
| 559 |
-
print(" content - Image -> plain content")
|
| 560 |
-
print(" --template / --schema - Image -> JSON shaped like the template")
|
| 561 |
-
print("\nExamples:")
|
| 562 |
-
print("\n1. Markdown OCR:")
|
| 563 |
-
print(" uv run nuextract3.py input-dataset output-dataset")
|
| 564 |
-
print("\n2. Structured extraction with an inline template:")
|
| 565 |
-
print(" uv run nuextract3.py input output \\")
|
| 566 |
-
print(' --template \'{"title": "verbatim-string", "date": "date"}\'')
|
| 567 |
-
print("\n3. Structured extraction from a JSON Schema (e.g. Pydantic):")
|
| 568 |
-
print(" uv run nuextract3.py input output --schema schema.json")
|
| 569 |
-
print("\n (--template / --schema also accept a URL or a local file path)")
|
| 570 |
-
print("\n4. Reasoning mode for harder documents:")
|
| 571 |
-
print(" uv run nuextract3.py input output --enable-thinking")
|
| 572 |
-
print("\n5. Test with 10 samples:")
|
| 573 |
-
print(" uv run nuextract3.py large-ds test --max-samples 10 --shuffle")
|
| 574 |
-
print("\n6. Running on HF Jobs (use vllm/vllm-openai image for built kernels):")
|
| 575 |
-
print(" hf jobs uv run --flavor a100-large \\")
|
| 576 |
-
print(" --image vllm/vllm-openai:latest \\")
|
| 577 |
-
print(" --python /usr/bin/python3 \\")
|
| 578 |
-
print(" -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\")
|
| 579 |
-
print(" -s HF_TOKEN \\")
|
| 580 |
-
print(
|
| 581 |
-
" https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nuextract3.py \\"
|
| 582 |
-
)
|
| 583 |
-
print(" input-dataset output-dataset --batch-size 16")
|
| 584 |
-
print("\nFor full help: uv run nuextract3.py --help")
|
| 585 |
-
sys.exit(0)
|
| 586 |
-
|
| 587 |
-
parser = argparse.ArgumentParser(
|
| 588 |
-
description="NuExtract3: document-to-markdown + schema-guided JSON extraction (4B VLM)",
|
| 589 |
-
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 590 |
-
epilog="""
|
| 591 |
-
Modes:
|
| 592 |
-
(default) Markdown OCR (image -> clean markdown)
|
| 593 |
-
--mode content
|
| 594 |
-
Plain-content extraction (less structured than markdown)
|
| 595 |
-
--template PATH_OR_JSON
|
| 596 |
-
Structured extraction with a NuExtract template
|
| 597 |
-
--schema PATH_OR_JSON
|
| 598 |
-
Structured extraction from a JSON Schema
|
| 599 |
-
(e.g. Pydantic Model.model_json_schema())
|
| 600 |
-
|
| 601 |
-
Examples:
|
| 602 |
-
uv run nuextract3.py my-docs analyzed-docs
|
| 603 |
-
uv run nuextract3.py receipts extracted \\
|
| 604 |
-
--template '{"store": "verbatim-string", "total": "number"}'
|
| 605 |
-
uv run nuextract3.py contracts extracted --schema contract_schema.json
|
| 606 |
-
uv run nuextract3.py hard-docs out --enable-thinking
|
| 607 |
-
""",
|
| 608 |
-
)
|
| 609 |
-
|
| 610 |
-
parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
|
| 611 |
-
parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
|
| 612 |
-
parser.add_argument(
|
| 613 |
-
"--image-column",
|
| 614 |
-
default="image",
|
| 615 |
-
help="Column containing images (default: image)",
|
| 616 |
-
)
|
| 617 |
-
parser.add_argument(
|
| 618 |
-
"--batch-size",
|
| 619 |
-
type=int,
|
| 620 |
-
default=16,
|
| 621 |
-
help="Batch size for processing (default: 16)",
|
| 622 |
-
)
|
| 623 |
-
parser.add_argument(
|
| 624 |
-
"--max-model-len",
|
| 625 |
-
type=int,
|
| 626 |
-
default=16384,
|
| 627 |
-
help="Maximum model context length (default: 16384)",
|
| 628 |
-
)
|
| 629 |
-
parser.add_argument(
|
| 630 |
-
"--max-tokens",
|
| 631 |
-
type=int,
|
| 632 |
-
default=8192,
|
| 633 |
-
help="Maximum tokens to generate (default: 8192)",
|
| 634 |
-
)
|
| 635 |
-
parser.add_argument(
|
| 636 |
-
"--gpu-memory-utilization",
|
| 637 |
-
type=float,
|
| 638 |
-
default=0.8,
|
| 639 |
-
help="GPU memory utilization (default: 0.8)",
|
| 640 |
-
)
|
| 641 |
-
parser.add_argument(
|
| 642 |
-
"--mode",
|
| 643 |
-
choices=["markdown", "content"],
|
| 644 |
-
default="markdown",
|
| 645 |
-
help="OCR mode when no template/schema is given (default: markdown)",
|
| 646 |
-
)
|
| 647 |
-
parser.add_argument(
|
| 648 |
-
"--template",
|
| 649 |
-
help="NuExtract template: inline JSON, a URL, or a file path",
|
| 650 |
-
)
|
| 651 |
-
parser.add_argument(
|
| 652 |
-
"--schema",
|
| 653 |
-
help="JSON Schema to auto-convert: inline JSON, a URL, or a file path",
|
| 654 |
-
)
|
| 655 |
-
parser.add_argument(
|
| 656 |
-
"--enable-thinking",
|
| 657 |
-
action="store_true",
|
| 658 |
-
help="Enable reasoning mode (slower, better on hard documents)",
|
| 659 |
-
)
|
| 660 |
-
parser.add_argument(
|
| 661 |
-
"--instructions",
|
| 662 |
-
default=None,
|
| 663 |
-
help=(
|
| 664 |
-
"Free-text instructions passed to NuExtract via "
|
| 665 |
-
"chat_template_kwargs.instructions (e.g. routing guidance across "
|
| 666 |
-
"optional schema branches, output-format rules). "
|
| 667 |
-
"See https://huggingface.co/numind/NuExtract3#instructions"
|
| 668 |
-
),
|
| 669 |
-
)
|
| 670 |
-
parser.add_argument(
|
| 671 |
-
"--temperature",
|
| 672 |
-
type=float,
|
| 673 |
-
default=None,
|
| 674 |
-
help="Sampling temperature (default: 0.2 non-thinking, 0.6 thinking)",
|
| 675 |
-
)
|
| 676 |
-
parser.add_argument(
|
| 677 |
-
"--model",
|
| 678 |
-
default=MODEL_DEFAULT,
|
| 679 |
-
help=f"Model ID (default: {MODEL_DEFAULT})",
|
| 680 |
-
)
|
| 681 |
-
parser.add_argument("--hf-token", help="Hugging Face API token")
|
| 682 |
-
parser.add_argument(
|
| 683 |
-
"--split", default="train", help="Dataset split to use (default: train)"
|
| 684 |
-
)
|
| 685 |
-
parser.add_argument(
|
| 686 |
-
"--max-samples",
|
| 687 |
-
type=int,
|
| 688 |
-
help="Maximum number of samples to process (for testing)",
|
| 689 |
-
)
|
| 690 |
-
parser.add_argument(
|
| 691 |
-
"--private", action="store_true", help="Make output dataset private"
|
| 692 |
-
)
|
| 693 |
-
parser.add_argument(
|
| 694 |
-
"--config",
|
| 695 |
-
help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
|
| 696 |
-
)
|
| 697 |
-
parser.add_argument(
|
| 698 |
-
"--create-pr",
|
| 699 |
-
action="store_true",
|
| 700 |
-
help="Create a pull request instead of pushing directly (for parallel benchmarking)",
|
| 701 |
-
)
|
| 702 |
-
parser.add_argument(
|
| 703 |
-
"--shuffle", action="store_true", help="Shuffle dataset before processing"
|
| 704 |
-
)
|
| 705 |
-
parser.add_argument(
|
| 706 |
-
"--seed",
|
| 707 |
-
type=int,
|
| 708 |
-
default=42,
|
| 709 |
-
help="Random seed for shuffling (default: 42)",
|
| 710 |
-
)
|
| 711 |
-
parser.add_argument(
|
| 712 |
-
"--output-column",
|
| 713 |
-
default=None,
|
| 714 |
-
help="Column name for output (default: 'markdown' in OCR mode, 'extraction' in template mode)",
|
| 715 |
-
)
|
| 716 |
-
parser.add_argument(
|
| 717 |
-
"--verbose",
|
| 718 |
-
action="store_true",
|
| 719 |
-
help="Log resolved package versions after processing",
|
| 720 |
-
)
|
| 721 |
-
|
| 722 |
-
args = parser.parse_args()
|
| 723 |
-
|
| 724 |
-
main(
|
| 725 |
-
input_dataset=args.input_dataset,
|
| 726 |
-
output_dataset=args.output_dataset,
|
| 727 |
-
image_column=args.image_column,
|
| 728 |
-
batch_size=args.batch_size,
|
| 729 |
-
max_model_len=args.max_model_len,
|
| 730 |
-
max_tokens=args.max_tokens,
|
| 731 |
-
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 732 |
-
mode=args.mode,
|
| 733 |
-
template_arg=args.template,
|
| 734 |
-
schema_arg=args.schema,
|
| 735 |
-
enable_thinking=args.enable_thinking,
|
| 736 |
-
instructions=args.instructions,
|
| 737 |
-
temperature=args.temperature,
|
| 738 |
-
model=args.model,
|
| 739 |
-
hf_token=args.hf_token,
|
| 740 |
-
split=args.split,
|
| 741 |
-
max_samples=args.max_samples,
|
| 742 |
-
private=args.private,
|
| 743 |
-
shuffle=args.shuffle,
|
| 744 |
-
seed=args.seed,
|
| 745 |
-
output_column=args.output_column,
|
| 746 |
-
verbose=args.verbose,
|
| 747 |
-
config=args.config,
|
| 748 |
-
create_pr=args.create_pr,
|
| 749 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
numarkdown-ocr.py
CHANGED
|
@@ -47,10 +47,6 @@ from huggingface_hub import DatasetCard, login
|
|
| 47 |
from PIL import Image
|
| 48 |
from toolz import partition_all
|
| 49 |
from tqdm.auto import tqdm
|
| 50 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 51 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 52 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 53 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 54 |
from vllm import LLM, SamplingParams
|
| 55 |
|
| 56 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 47 |
from PIL import Image
|
| 48 |
from toolz import partition_all
|
| 49 |
from tqdm.auto import tqdm
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
from vllm import LLM, SamplingParams
|
| 51 |
|
| 52 |
logging.basicConfig(level=logging.INFO)
|
olmocr2-vllm.py
CHANGED
|
@@ -50,11 +50,8 @@ from huggingface_hub import DatasetCard, login
|
|
| 50 |
from PIL import Image
|
| 51 |
from toolz import partition_all
|
| 52 |
from tqdm.auto import tqdm
|
| 53 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 54 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 55 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 56 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 57 |
from vllm import LLM, SamplingParams
|
|
|
|
| 58 |
|
| 59 |
logging.basicConfig(level=logging.INFO)
|
| 60 |
logger = logging.getLogger(__name__)
|
|
@@ -368,25 +365,13 @@ def main(
|
|
| 368 |
"stop": ["<|im_end|>", "<|endoftext|>"],
|
| 369 |
}
|
| 370 |
|
| 371 |
-
# Add guided decoding if requested (enforces YAML front matter structure)
|
| 372 |
-
# vLLM 0.22.x renamed this API: GuidedDecodingParams (guided_decoding=) →
|
| 373 |
-
# StructuredOutputsParams (structured_outputs=). Import lazily + shim so the
|
| 374 |
-
# default path (guided_decoding=False) never touches the moved symbol.
|
| 375 |
if guided_decoding:
|
| 376 |
logger.info("Enabling guided decoding with YAML front matter regex")
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
sampling_params_kwargs["structured_outputs"] = StructuredOutputsParams(
|
| 382 |
-
regex=front_matter_regex
|
| 383 |
-
)
|
| 384 |
-
except ImportError:
|
| 385 |
-
from vllm.sampling_params import GuidedDecodingParams
|
| 386 |
-
|
| 387 |
-
sampling_params_kwargs["guided_decoding"] = GuidedDecodingParams(
|
| 388 |
-
regex=front_matter_regex
|
| 389 |
-
)
|
| 390 |
|
| 391 |
sampling_params = SamplingParams(**sampling_params_kwargs)
|
| 392 |
|
|
|
|
| 50 |
from PIL import Image
|
| 51 |
from toolz import partition_all
|
| 52 |
from tqdm.auto import tqdm
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
from vllm import LLM, SamplingParams
|
| 54 |
+
from vllm.sampling_params import GuidedDecodingParams
|
| 55 |
|
| 56 |
logging.basicConfig(level=logging.INFO)
|
| 57 |
logger = logging.getLogger(__name__)
|
|
|
|
| 365 |
"stop": ["<|im_end|>", "<|endoftext|>"],
|
| 366 |
}
|
| 367 |
|
| 368 |
+
# Add guided decoding if requested (enforces YAML front matter structure)
|
|
|
|
|
|
|
|
|
|
| 369 |
if guided_decoding:
|
| 370 |
logger.info("Enabling guided decoding with YAML front matter regex")
|
| 371 |
+
guided_params = GuidedDecodingParams(
|
| 372 |
+
regex=r"---\nprimary_language: (?:[a-z]{2}|null)\nis_rotation_valid: (?:True|False|true|false)\nrotation_correction: (?:0|90|180|270)\nis_table: (?:True|False|true|false)\nis_diagram: (?:True|False|true|false)\n(?:---|---\n[\s\S]+)"
|
| 373 |
+
)
|
| 374 |
+
sampling_params_kwargs["guided_decoding"] = guided_params
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 375 |
|
| 376 |
sampling_params = SamplingParams(**sampling_params_kwargs)
|
| 377 |
|
paddleocr-vl-1.6.py
DELETED
|
@@ -1,798 +0,0 @@
|
|
| 1 |
-
# /// script
|
| 2 |
-
# requires-python = ">=3.11"
|
| 3 |
-
# dependencies = [
|
| 4 |
-
# "datasets>=4.0.0",
|
| 5 |
-
# "huggingface-hub",
|
| 6 |
-
# "pillow",
|
| 7 |
-
# "vllm>=0.15.1",
|
| 8 |
-
# "tqdm",
|
| 9 |
-
# "toolz",
|
| 10 |
-
# "torch",
|
| 11 |
-
# "pyarrow",
|
| 12 |
-
# "transformers",
|
| 13 |
-
# ]
|
| 14 |
-
# ///
|
| 15 |
-
|
| 16 |
-
"""
|
| 17 |
-
Convert document images to text/tables/formulas using PaddleOCR-VL-1.6 with vLLM.
|
| 18 |
-
|
| 19 |
-
PaddleOCR-VL-1.6 is a compact 0.9B OCR model that reaches a new SOTA of 96.33% on
|
| 20 |
-
OmniDocBench v1.6. It combines a NaViT-style dynamic resolution visual encoder with
|
| 21 |
-
the ERNIE-4.5-0.3B language model and is a plug-and-play upgrade of PaddleOCR-VL-1.5.
|
| 22 |
-
|
| 23 |
-
Features:
|
| 24 |
-
- 🎯 SOTA: 96.33% on OmniDocBench v1.6 (0.9B params, smallest top-tier OCR model)
|
| 25 |
-
- 📝 OCR mode: General text extraction to markdown
|
| 26 |
-
- 📊 Table mode: HTML table recognition and extraction
|
| 27 |
-
- 📐 Formula mode: LaTeX mathematical notation
|
| 28 |
-
- 📈 Chart mode: Structured chart analysis
|
| 29 |
-
- 🔍 Spotting mode: Text spotting with localization
|
| 30 |
-
- 🔖 Seal mode: Seal/stamp recognition
|
| 31 |
-
- 🌍 Multilingual support (en/zh + more)
|
| 32 |
-
- 🔧 Based on ERNIE-4.5 (different from Qwen-based models)
|
| 33 |
-
|
| 34 |
-
Model: PaddlePaddle/PaddleOCR-VL-1.6
|
| 35 |
-
Backend: vLLM offline (batch inference)
|
| 36 |
-
|
| 37 |
-
HF Jobs note: PaddleOCR-VL-1.6 is supported by stable vLLM, but on HF Jobs you must run
|
| 38 |
-
with the pre-built vLLM image so flashinfer's CUDA kernels are reused. The default
|
| 39 |
-
uv-script image has the CUDA runtime but no `nvcc`, so vLLM's flashinfer sampler crashes
|
| 40 |
-
at warmup with "Could not find nvcc". Use image-mode (see the example at the bottom):
|
| 41 |
-
--image vllm/vllm-openai:latest --flavor a100-large
|
| 42 |
-
--python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages
|
| 43 |
-
This is the same image-mode pattern as nuextract3.py. Verified end-to-end on a100-large
|
| 44 |
-
(2026-06-01): 5/5 clean markdown on davanstrien/ufo-ColPali, ~194 tok/s, 0 errors.
|
| 45 |
-
"""
|
| 46 |
-
|
| 47 |
-
import argparse
|
| 48 |
-
import base64
|
| 49 |
-
import io
|
| 50 |
-
import json
|
| 51 |
-
import logging
|
| 52 |
-
import math
|
| 53 |
-
import os
|
| 54 |
-
import sys
|
| 55 |
-
import time
|
| 56 |
-
from typing import Any, Dict, List, Union
|
| 57 |
-
from datetime import datetime
|
| 58 |
-
|
| 59 |
-
import torch
|
| 60 |
-
from datasets import load_dataset
|
| 61 |
-
from huggingface_hub import DatasetCard, login
|
| 62 |
-
from PIL import Image
|
| 63 |
-
from toolz import partition_all
|
| 64 |
-
from tqdm.auto import tqdm
|
| 65 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 66 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 67 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 68 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 69 |
-
from vllm import LLM, SamplingParams
|
| 70 |
-
|
| 71 |
-
logging.basicConfig(level=logging.INFO)
|
| 72 |
-
logger = logging.getLogger(__name__)
|
| 73 |
-
|
| 74 |
-
MODEL_ID = "PaddlePaddle/PaddleOCR-VL-1.6"
|
| 75 |
-
|
| 76 |
-
# Task mode configurations from official PaddleOCR-VL documentation
|
| 77 |
-
TASK_MODES = {
|
| 78 |
-
"ocr": "OCR:",
|
| 79 |
-
"table": "Table Recognition:",
|
| 80 |
-
"formula": "Formula Recognition:",
|
| 81 |
-
"chart": "Chart Recognition:",
|
| 82 |
-
"spotting": "Spotting:",
|
| 83 |
-
"seal": "Seal Recognition:",
|
| 84 |
-
}
|
| 85 |
-
|
| 86 |
-
# Task descriptions for dataset card
|
| 87 |
-
TASK_DESCRIPTIONS = {
|
| 88 |
-
"ocr": "General text extraction to markdown format",
|
| 89 |
-
"table": "Table extraction to HTML format",
|
| 90 |
-
"formula": "Mathematical formula recognition to LaTeX",
|
| 91 |
-
"chart": "Chart and diagram analysis",
|
| 92 |
-
"spotting": "Text spotting with localization",
|
| 93 |
-
"seal": "Seal and stamp recognition",
|
| 94 |
-
}
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
def check_cuda_availability():
|
| 98 |
-
"""Check if CUDA is available and exit if not."""
|
| 99 |
-
if not torch.cuda.is_available():
|
| 100 |
-
logger.error("CUDA is not available. This script requires a GPU.")
|
| 101 |
-
logger.error("Please run on a machine with a CUDA-capable GPU.")
|
| 102 |
-
sys.exit(1)
|
| 103 |
-
else:
|
| 104 |
-
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
def smart_resize(
|
| 108 |
-
height: int,
|
| 109 |
-
width: int,
|
| 110 |
-
factor: int = 28,
|
| 111 |
-
min_pixels: int = 28 * 28 * 130,
|
| 112 |
-
max_pixels: int = 28 * 28 * 1280,
|
| 113 |
-
) -> tuple[int, int]:
|
| 114 |
-
"""
|
| 115 |
-
PaddleOCR-VL's intelligent resize logic.
|
| 116 |
-
|
| 117 |
-
Rescales the image so that:
|
| 118 |
-
1. Both dimensions are divisible by 'factor' (28)
|
| 119 |
-
2. Total pixels are within [min_pixels, max_pixels]
|
| 120 |
-
3. Aspect ratio is maintained as closely as possible
|
| 121 |
-
|
| 122 |
-
Args:
|
| 123 |
-
height: Original image height
|
| 124 |
-
width: Original image width
|
| 125 |
-
factor: Dimension divisibility factor (default: 28)
|
| 126 |
-
min_pixels: Minimum total pixels (default: 100,880)
|
| 127 |
-
max_pixels: Maximum total pixels (default: 1,003,520)
|
| 128 |
-
|
| 129 |
-
Returns:
|
| 130 |
-
Tuple of (new_height, new_width)
|
| 131 |
-
"""
|
| 132 |
-
if height < factor:
|
| 133 |
-
width = round((width * factor) / height)
|
| 134 |
-
height = factor
|
| 135 |
-
|
| 136 |
-
if width < factor:
|
| 137 |
-
height = round((height * factor) / width)
|
| 138 |
-
width = factor
|
| 139 |
-
|
| 140 |
-
if max(height, width) / min(height, width) > 200:
|
| 141 |
-
logger.warning(
|
| 142 |
-
f"Extreme aspect ratio detected: {max(height, width) / min(height, width):.1f}"
|
| 143 |
-
)
|
| 144 |
-
# Continue anyway, but warn about potential issues
|
| 145 |
-
|
| 146 |
-
h_bar = round(height / factor) * factor
|
| 147 |
-
w_bar = round(width / factor) * factor
|
| 148 |
-
|
| 149 |
-
if h_bar * w_bar > max_pixels:
|
| 150 |
-
beta = math.sqrt((height * width) / max_pixels)
|
| 151 |
-
h_bar = math.floor(height / beta / factor) * factor
|
| 152 |
-
w_bar = math.floor(width / beta / factor) * factor
|
| 153 |
-
elif h_bar * w_bar < min_pixels:
|
| 154 |
-
beta = math.sqrt(min_pixels / (height * width))
|
| 155 |
-
h_bar = math.ceil(height * beta / factor) * factor
|
| 156 |
-
w_bar = math.ceil(width * beta / factor) * factor
|
| 157 |
-
|
| 158 |
-
return h_bar, w_bar
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
def make_ocr_message(
|
| 162 |
-
image: Union[Image.Image, Dict[str, Any], str],
|
| 163 |
-
task_mode: str = "ocr",
|
| 164 |
-
apply_smart_resize: bool = True,
|
| 165 |
-
) -> List[Dict]:
|
| 166 |
-
"""
|
| 167 |
-
Create chat message for PaddleOCR-VL processing.
|
| 168 |
-
|
| 169 |
-
PaddleOCR-VL expects a specific format with the task prefix after the image.
|
| 170 |
-
"""
|
| 171 |
-
# Convert to PIL Image if needed
|
| 172 |
-
if isinstance(image, Image.Image):
|
| 173 |
-
pil_img = image
|
| 174 |
-
elif isinstance(image, dict) and "bytes" in image:
|
| 175 |
-
pil_img = Image.open(io.BytesIO(image["bytes"]))
|
| 176 |
-
elif isinstance(image, str):
|
| 177 |
-
pil_img = Image.open(image)
|
| 178 |
-
else:
|
| 179 |
-
raise ValueError(f"Unsupported image type: {type(image)}")
|
| 180 |
-
|
| 181 |
-
# Convert to RGB
|
| 182 |
-
pil_img = pil_img.convert("RGB")
|
| 183 |
-
|
| 184 |
-
# Apply smart resize if requested. Spotting benefits from higher resolution
|
| 185 |
-
# (per the model card), so allow more pixels in that mode.
|
| 186 |
-
if apply_smart_resize:
|
| 187 |
-
original_size = pil_img.size
|
| 188 |
-
max_pixels = 28 * 28 * (2048 if task_mode == "spotting" else 1280)
|
| 189 |
-
new_height, new_width = smart_resize(
|
| 190 |
-
pil_img.height, pil_img.width, max_pixels=max_pixels
|
| 191 |
-
)
|
| 192 |
-
if (new_width, new_height) != (pil_img.width, pil_img.height):
|
| 193 |
-
pil_img = pil_img.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
| 194 |
-
logger.debug(f"Resized image from {original_size} to {pil_img.size}")
|
| 195 |
-
|
| 196 |
-
# Convert to base64 data URI
|
| 197 |
-
buf = io.BytesIO()
|
| 198 |
-
pil_img.save(buf, format="PNG")
|
| 199 |
-
data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
|
| 200 |
-
|
| 201 |
-
# PaddleOCR-VL message format: image first, then task prefix
|
| 202 |
-
return [
|
| 203 |
-
{
|
| 204 |
-
"role": "user",
|
| 205 |
-
"content": [
|
| 206 |
-
{"type": "image_url", "image_url": {"url": data_uri}},
|
| 207 |
-
{"type": "text", "text": TASK_MODES[task_mode]},
|
| 208 |
-
],
|
| 209 |
-
}
|
| 210 |
-
]
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
def create_dataset_card(
|
| 214 |
-
source_dataset: str,
|
| 215 |
-
model: str,
|
| 216 |
-
task_mode: str,
|
| 217 |
-
num_samples: int,
|
| 218 |
-
processing_time: str,
|
| 219 |
-
batch_size: int,
|
| 220 |
-
max_model_len: int,
|
| 221 |
-
max_tokens: int,
|
| 222 |
-
gpu_memory_utilization: float,
|
| 223 |
-
temperature: float,
|
| 224 |
-
apply_smart_resize: bool,
|
| 225 |
-
image_column: str = "image",
|
| 226 |
-
split: str = "train",
|
| 227 |
-
) -> str:
|
| 228 |
-
"""Create a dataset card documenting the OCR process."""
|
| 229 |
-
task_description = TASK_DESCRIPTIONS[task_mode]
|
| 230 |
-
|
| 231 |
-
return f"""---
|
| 232 |
-
tags:
|
| 233 |
-
- ocr
|
| 234 |
-
- document-processing
|
| 235 |
-
- paddleocr-vl
|
| 236 |
-
- paddleocr-vl-1.6
|
| 237 |
-
- {task_mode}
|
| 238 |
-
- uv-script
|
| 239 |
-
- generated
|
| 240 |
-
---
|
| 241 |
-
|
| 242 |
-
# Document Processing using PaddleOCR-VL-1.6 ({task_mode.upper()} mode)
|
| 243 |
-
|
| 244 |
-
This dataset contains {task_mode.upper()} results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using PaddleOCR-VL-1.6, an ultra-compact 0.9B OCR model (96.33% SOTA on OmniDocBench v1.6).
|
| 245 |
-
|
| 246 |
-
## Processing Details
|
| 247 |
-
|
| 248 |
-
- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
|
| 249 |
-
- **Model**: [{model}](https://huggingface.co/{model})
|
| 250 |
-
- **Task Mode**: `{task_mode}` - {task_description}
|
| 251 |
-
- **Number of Samples**: {num_samples:,}
|
| 252 |
-
- **Processing Time**: {processing_time}
|
| 253 |
-
- **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
|
| 254 |
-
|
| 255 |
-
### Configuration
|
| 256 |
-
|
| 257 |
-
- **Image Column**: `{image_column}`
|
| 258 |
-
- **Output Column**: `markdown`
|
| 259 |
-
- **Dataset Split**: `{split}`
|
| 260 |
-
- **Batch Size**: {batch_size}
|
| 261 |
-
- **Smart Resize**: {"Enabled" if apply_smart_resize else "Disabled"}
|
| 262 |
-
- **Max Model Length**: {max_model_len:,} tokens
|
| 263 |
-
- **Max Output Tokens**: {max_tokens:,}
|
| 264 |
-
- **Temperature**: {temperature}
|
| 265 |
-
- **GPU Memory Utilization**: {gpu_memory_utilization:.1%}
|
| 266 |
-
|
| 267 |
-
## Model Information
|
| 268 |
-
|
| 269 |
-
PaddleOCR-VL-1.6 is a state-of-the-art, resource-efficient model tailored for document parsing:
|
| 270 |
-
- 🎯 **SOTA** - 96.33% on OmniDocBench v1.6
|
| 271 |
-
- 🧩 **Ultra-compact** - Only 0.9B parameters
|
| 272 |
-
- 📝 **OCR mode** - General text extraction
|
| 273 |
-
- 📊 **Table mode** - HTML table recognition
|
| 274 |
-
- 📐 **Formula mode** - LaTeX mathematical notation
|
| 275 |
-
- 📈 **Chart mode** - Structured chart analysis
|
| 276 |
-
- 🔍 **Spotting mode** - Text spotting with localization
|
| 277 |
-
- 🔖 **Seal mode** - Seal/stamp recognition
|
| 278 |
-
- 🌍 **Multilingual** - Support for multiple languages
|
| 279 |
-
- 🔧 **ERNIE-4.5 based** - Different architecture from Qwen models
|
| 280 |
-
|
| 281 |
-
### Task Modes
|
| 282 |
-
|
| 283 |
-
- **OCR**: Extract text content to markdown format
|
| 284 |
-
- **Table Recognition**: Extract tables to HTML format
|
| 285 |
-
- **Formula Recognition**: Extract mathematical formulas to LaTeX
|
| 286 |
-
- **Chart Recognition**: Analyze and describe charts/diagrams
|
| 287 |
-
- **Spotting**: Text spotting with localization
|
| 288 |
-
- **Seal Recognition**: Seal and stamp recognition
|
| 289 |
-
|
| 290 |
-
## Dataset Structure
|
| 291 |
-
|
| 292 |
-
The dataset contains all original columns plus:
|
| 293 |
-
- `markdown`: The extracted content based on task mode
|
| 294 |
-
- `inference_info`: JSON list tracking all OCR models applied to this dataset
|
| 295 |
-
|
| 296 |
-
## Usage
|
| 297 |
-
|
| 298 |
-
```python
|
| 299 |
-
from datasets import load_dataset
|
| 300 |
-
import json
|
| 301 |
-
|
| 302 |
-
# Load the dataset
|
| 303 |
-
dataset = load_dataset("{{output_dataset_id}}", split="{split}")
|
| 304 |
-
|
| 305 |
-
# Access the extracted content
|
| 306 |
-
for example in dataset:
|
| 307 |
-
print(example["markdown"])
|
| 308 |
-
break
|
| 309 |
-
|
| 310 |
-
# View all OCR models applied to this dataset
|
| 311 |
-
inference_info = json.loads(dataset[0]["inference_info"])
|
| 312 |
-
for info in inference_info:
|
| 313 |
-
print(f"Task: {{info['task_mode']}} - Model: {{info['model_id']}}")
|
| 314 |
-
```
|
| 315 |
-
|
| 316 |
-
## Reproduction
|
| 317 |
-
|
| 318 |
-
This dataset was generated using the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) PaddleOCR-VL-1.6 script.
|
| 319 |
-
On HF Jobs, run with the pre-built vLLM image (image-mode) so flashinfer kernels are reused:
|
| 320 |
-
|
| 321 |
-
```bash
|
| 322 |
-
hf jobs uv run \\
|
| 323 |
-
--image vllm/vllm-openai:latest --flavor a100-large \\
|
| 324 |
-
--python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\
|
| 325 |
-
-s HF_TOKEN \\
|
| 326 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl-1.6.py \\
|
| 327 |
-
{source_dataset} \\
|
| 328 |
-
<output-dataset> \\
|
| 329 |
-
--task-mode {task_mode} \\
|
| 330 |
-
--image-column {image_column} \\
|
| 331 |
-
--batch-size {batch_size} \\
|
| 332 |
-
--max-model-len {max_model_len} \\
|
| 333 |
-
--max-tokens {max_tokens} \\
|
| 334 |
-
--gpu-memory-utilization {gpu_memory_utilization}
|
| 335 |
-
```
|
| 336 |
-
|
| 337 |
-
## Performance
|
| 338 |
-
|
| 339 |
-
- **Model Size**: 0.9B parameters (smallest among top-tier OCR models)
|
| 340 |
-
- **Processing Speed**: ~{num_samples / (float(processing_time.split()[0]) * 60):.2f} images/second
|
| 341 |
-
- **Architecture**: NaViT visual encoder + ERNIE-4.5-0.3B language model
|
| 342 |
-
|
| 343 |
-
Generated with 🤖 [UV Scripts](https://huggingface.co/uv-scripts)
|
| 344 |
-
"""
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
def main(
|
| 348 |
-
input_dataset: str,
|
| 349 |
-
output_dataset: str,
|
| 350 |
-
image_column: str = "image",
|
| 351 |
-
batch_size: int = 16,
|
| 352 |
-
task_mode: str = "ocr",
|
| 353 |
-
max_model_len: int = 8192,
|
| 354 |
-
max_tokens: int = 4096,
|
| 355 |
-
temperature: float = 0.0,
|
| 356 |
-
gpu_memory_utilization: float = 0.8,
|
| 357 |
-
apply_smart_resize: bool = True,
|
| 358 |
-
hf_token: str = None,
|
| 359 |
-
split: str = "train",
|
| 360 |
-
max_samples: int = None,
|
| 361 |
-
private: bool = False,
|
| 362 |
-
shuffle: bool = False,
|
| 363 |
-
seed: int = 42,
|
| 364 |
-
output_column: str = None,
|
| 365 |
-
config: str = None,
|
| 366 |
-
create_pr: bool = False,
|
| 367 |
-
verbose: bool = False,
|
| 368 |
-
):
|
| 369 |
-
"""Process images from HF dataset through PaddleOCR-VL-1.6 model."""
|
| 370 |
-
|
| 371 |
-
# Check CUDA availability first
|
| 372 |
-
check_cuda_availability()
|
| 373 |
-
|
| 374 |
-
# Track processing start time
|
| 375 |
-
start_time = datetime.now()
|
| 376 |
-
|
| 377 |
-
# Enable high-performance Xet downloads
|
| 378 |
-
os.environ["HF_XET_HIGH_PERFORMANCE"] = "1"
|
| 379 |
-
|
| 380 |
-
# Login to HF if token provided
|
| 381 |
-
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
|
| 382 |
-
if HF_TOKEN:
|
| 383 |
-
login(token=HF_TOKEN)
|
| 384 |
-
|
| 385 |
-
# Validate task mode
|
| 386 |
-
if task_mode not in TASK_MODES:
|
| 387 |
-
raise ValueError(
|
| 388 |
-
f"Invalid task_mode '{task_mode}'. Choose from: {list(TASK_MODES.keys())}"
|
| 389 |
-
)
|
| 390 |
-
|
| 391 |
-
# Default output column is 'markdown' for consistency across scripts
|
| 392 |
-
if output_column is None:
|
| 393 |
-
output_column = "markdown"
|
| 394 |
-
|
| 395 |
-
logger.info(f"Using task mode: {task_mode} - {TASK_DESCRIPTIONS[task_mode]}")
|
| 396 |
-
logger.info(f"Output will be written to column: {output_column}")
|
| 397 |
-
|
| 398 |
-
# Load dataset
|
| 399 |
-
logger.info(f"Loading dataset: {input_dataset}")
|
| 400 |
-
dataset = load_dataset(input_dataset, split=split)
|
| 401 |
-
|
| 402 |
-
# Validate image column
|
| 403 |
-
if image_column not in dataset.column_names:
|
| 404 |
-
raise ValueError(
|
| 405 |
-
f"Column '{image_column}' not found. Available: {dataset.column_names}"
|
| 406 |
-
)
|
| 407 |
-
|
| 408 |
-
# Shuffle if requested
|
| 409 |
-
if shuffle:
|
| 410 |
-
logger.info(f"Shuffling dataset with seed {seed}")
|
| 411 |
-
dataset = dataset.shuffle(seed=seed)
|
| 412 |
-
|
| 413 |
-
# Limit samples if requested
|
| 414 |
-
if max_samples:
|
| 415 |
-
dataset = dataset.select(range(min(max_samples, len(dataset))))
|
| 416 |
-
logger.info(f"Limited to {len(dataset)} samples")
|
| 417 |
-
|
| 418 |
-
# Initialize vLLM model
|
| 419 |
-
logger.info(f"Initializing vLLM with {MODEL_ID}")
|
| 420 |
-
logger.info("This may take a minute on first run (model is only 0.9B)...")
|
| 421 |
-
|
| 422 |
-
try:
|
| 423 |
-
llm = LLM(
|
| 424 |
-
model=MODEL_ID,
|
| 425 |
-
trust_remote_code=True,
|
| 426 |
-
max_model_len=max_model_len,
|
| 427 |
-
gpu_memory_utilization=gpu_memory_utilization,
|
| 428 |
-
limit_mm_per_prompt={"image": 1},
|
| 429 |
-
max_num_batched_tokens=16384,
|
| 430 |
-
enable_prefix_caching=False,
|
| 431 |
-
enforce_eager=True,
|
| 432 |
-
)
|
| 433 |
-
except Exception as e:
|
| 434 |
-
logger.error(f"Failed to initialize PaddleOCR-VL-1.6 with vLLM: {e}")
|
| 435 |
-
logger.error(
|
| 436 |
-
"On HF Jobs, run with the pre-built vLLM image so flashinfer kernels are "
|
| 437 |
-
"reused (the default uv-script image has no nvcc):"
|
| 438 |
-
)
|
| 439 |
-
logger.error(
|
| 440 |
-
" --image vllm/vllm-openai:latest --flavor a100-large "
|
| 441 |
-
"--python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages"
|
| 442 |
-
)
|
| 443 |
-
sys.exit(1)
|
| 444 |
-
|
| 445 |
-
# Sampling parameters - deterministic for OCR
|
| 446 |
-
sampling_params = SamplingParams(
|
| 447 |
-
temperature=temperature,
|
| 448 |
-
max_tokens=max_tokens,
|
| 449 |
-
)
|
| 450 |
-
|
| 451 |
-
logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
|
| 452 |
-
if apply_smart_resize:
|
| 453 |
-
logger.info("Smart resize enabled (PaddleOCR-VL's adaptive resolution)")
|
| 454 |
-
|
| 455 |
-
# Process images in batches
|
| 456 |
-
all_outputs = []
|
| 457 |
-
|
| 458 |
-
for batch_indices in tqdm(
|
| 459 |
-
partition_all(batch_size, range(len(dataset))),
|
| 460 |
-
total=(len(dataset) + batch_size - 1) // batch_size,
|
| 461 |
-
desc=f"PaddleOCR-VL-1.6 {task_mode.upper()} processing",
|
| 462 |
-
):
|
| 463 |
-
batch_indices = list(batch_indices)
|
| 464 |
-
batch_images = [dataset[i][image_column] for i in batch_indices]
|
| 465 |
-
|
| 466 |
-
try:
|
| 467 |
-
# Create messages for batch with task-specific prefix
|
| 468 |
-
batch_messages = [
|
| 469 |
-
make_ocr_message(
|
| 470 |
-
img, task_mode=task_mode, apply_smart_resize=apply_smart_resize
|
| 471 |
-
)
|
| 472 |
-
for img in batch_images
|
| 473 |
-
]
|
| 474 |
-
|
| 475 |
-
# Process with vLLM
|
| 476 |
-
outputs = llm.chat(batch_messages, sampling_params)
|
| 477 |
-
|
| 478 |
-
# Extract outputs
|
| 479 |
-
for output in outputs:
|
| 480 |
-
text = output.outputs[0].text.strip()
|
| 481 |
-
all_outputs.append(text)
|
| 482 |
-
|
| 483 |
-
except Exception as e:
|
| 484 |
-
logger.error(f"Error processing batch: {e}")
|
| 485 |
-
# Add error placeholders for failed batch
|
| 486 |
-
all_outputs.extend([f"[{task_mode.upper()} ERROR]"] * len(batch_images))
|
| 487 |
-
|
| 488 |
-
# Calculate processing time
|
| 489 |
-
processing_duration = datetime.now() - start_time
|
| 490 |
-
processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
|
| 491 |
-
|
| 492 |
-
# Add output column to dataset
|
| 493 |
-
logger.info(f"Adding '{output_column}' column to dataset")
|
| 494 |
-
dataset = dataset.add_column(output_column, all_outputs)
|
| 495 |
-
|
| 496 |
-
# Handle inference_info tracking (for multi-model comparisons)
|
| 497 |
-
inference_entry = {
|
| 498 |
-
"model_id": MODEL_ID,
|
| 499 |
-
"model_name": "PaddleOCR-VL-1.6",
|
| 500 |
-
"model_size": "0.9B",
|
| 501 |
-
"task_mode": task_mode,
|
| 502 |
-
"column_name": output_column,
|
| 503 |
-
"timestamp": datetime.now().isoformat(),
|
| 504 |
-
"temperature": temperature,
|
| 505 |
-
"max_tokens": max_tokens,
|
| 506 |
-
"smart_resize": apply_smart_resize,
|
| 507 |
-
"backend": "vllm",
|
| 508 |
-
}
|
| 509 |
-
|
| 510 |
-
if "inference_info" in dataset.column_names:
|
| 511 |
-
# Append to existing inference info
|
| 512 |
-
logger.info("Updating existing inference_info column")
|
| 513 |
-
|
| 514 |
-
def update_inference_info(example):
|
| 515 |
-
try:
|
| 516 |
-
existing_info = (
|
| 517 |
-
json.loads(example["inference_info"])
|
| 518 |
-
if example["inference_info"]
|
| 519 |
-
else []
|
| 520 |
-
)
|
| 521 |
-
except (json.JSONDecodeError, TypeError):
|
| 522 |
-
existing_info = []
|
| 523 |
-
|
| 524 |
-
existing_info.append(inference_entry)
|
| 525 |
-
return {"inference_info": json.dumps(existing_info)}
|
| 526 |
-
|
| 527 |
-
dataset = dataset.map(update_inference_info)
|
| 528 |
-
else:
|
| 529 |
-
# Create new inference_info column
|
| 530 |
-
logger.info("Creating new inference_info column")
|
| 531 |
-
inference_list = [json.dumps([inference_entry])] * len(dataset)
|
| 532 |
-
dataset = dataset.add_column("inference_info", inference_list)
|
| 533 |
-
|
| 534 |
-
# Push to hub with retry and XET fallback
|
| 535 |
-
logger.info(f"Pushing to {output_dataset}")
|
| 536 |
-
max_retries = 3
|
| 537 |
-
for attempt in range(1, max_retries + 1):
|
| 538 |
-
try:
|
| 539 |
-
if attempt > 1:
|
| 540 |
-
logger.warning("Disabling XET (fallback to HTTP upload)")
|
| 541 |
-
os.environ["HF_HUB_DISABLE_XET"] = "1"
|
| 542 |
-
dataset.push_to_hub(
|
| 543 |
-
output_dataset,
|
| 544 |
-
private=private,
|
| 545 |
-
token=HF_TOKEN,
|
| 546 |
-
max_shard_size="500MB",
|
| 547 |
-
**({"config_name": config} if config else {}),
|
| 548 |
-
create_pr=create_pr,
|
| 549 |
-
commit_message=f"Add {MODEL_ID} OCR results ({len(dataset)} samples)"
|
| 550 |
-
+ (f" [{config}]" if config else ""),
|
| 551 |
-
)
|
| 552 |
-
break
|
| 553 |
-
except Exception as e:
|
| 554 |
-
logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
|
| 555 |
-
if attempt < max_retries:
|
| 556 |
-
delay = 30 * (2 ** (attempt - 1))
|
| 557 |
-
logger.info(f"Retrying in {delay}s...")
|
| 558 |
-
time.sleep(delay)
|
| 559 |
-
else:
|
| 560 |
-
logger.error("All upload attempts failed. OCR results are lost.")
|
| 561 |
-
sys.exit(1)
|
| 562 |
-
|
| 563 |
-
# Create and push dataset card (skip when creating a PR to avoid touching main)
|
| 564 |
-
if not create_pr:
|
| 565 |
-
logger.info("Creating dataset card")
|
| 566 |
-
card_content = create_dataset_card(
|
| 567 |
-
source_dataset=input_dataset,
|
| 568 |
-
model=MODEL_ID,
|
| 569 |
-
task_mode=task_mode,
|
| 570 |
-
num_samples=len(dataset),
|
| 571 |
-
processing_time=processing_time_str,
|
| 572 |
-
batch_size=batch_size,
|
| 573 |
-
max_model_len=max_model_len,
|
| 574 |
-
max_tokens=max_tokens,
|
| 575 |
-
gpu_memory_utilization=gpu_memory_utilization,
|
| 576 |
-
temperature=temperature,
|
| 577 |
-
apply_smart_resize=apply_smart_resize,
|
| 578 |
-
image_column=image_column,
|
| 579 |
-
split=split,
|
| 580 |
-
)
|
| 581 |
-
|
| 582 |
-
card = DatasetCard(card_content)
|
| 583 |
-
card.push_to_hub(output_dataset, token=HF_TOKEN)
|
| 584 |
-
|
| 585 |
-
logger.info("✅ PaddleOCR-VL-1.6 processing complete!")
|
| 586 |
-
logger.info(
|
| 587 |
-
f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
|
| 588 |
-
)
|
| 589 |
-
logger.info(f"Processing time: {processing_time_str}")
|
| 590 |
-
logger.info(f"Task mode: {task_mode} - {TASK_DESCRIPTIONS[task_mode]}")
|
| 591 |
-
|
| 592 |
-
if verbose:
|
| 593 |
-
import importlib.metadata
|
| 594 |
-
|
| 595 |
-
logger.info("--- Resolved package versions ---")
|
| 596 |
-
for pkg in ["vllm", "transformers", "torch", "datasets", "pyarrow", "pillow"]:
|
| 597 |
-
try:
|
| 598 |
-
logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
|
| 599 |
-
except importlib.metadata.PackageNotFoundError:
|
| 600 |
-
logger.info(f" {pkg}: not installed")
|
| 601 |
-
logger.info("--- End versions ---")
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
if __name__ == "__main__":
|
| 605 |
-
# Show example usage if no arguments
|
| 606 |
-
if len(sys.argv) == 1:
|
| 607 |
-
print("=" * 80)
|
| 608 |
-
print("PaddleOCR-VL-1.6 Document Processing")
|
| 609 |
-
print("=" * 80)
|
| 610 |
-
print("\nUltra-compact 0.9B OCR model (96.33% SOTA on OmniDocBench v1.6)")
|
| 611 |
-
print("\nFeatures:")
|
| 612 |
-
print("- 🎯 SOTA - 96.33% on OmniDocBench v1.6 (0.9B params)")
|
| 613 |
-
print("- 📝 OCR mode - General text extraction")
|
| 614 |
-
print("- 📊 Table mode - HTML table recognition")
|
| 615 |
-
print("- 📐 Formula mode - LaTeX mathematical notation")
|
| 616 |
-
print("- 📈 Chart mode - Structured chart analysis")
|
| 617 |
-
print("- 🔍 Spotting mode - Text spotting with localization")
|
| 618 |
-
print("- 🔖 Seal mode - Seal/stamp recognition")
|
| 619 |
-
print("- 🌍 Multilingual support")
|
| 620 |
-
print("- 🔧 Based on ERNIE-4.5 (unique architecture)")
|
| 621 |
-
print("\nTask Modes:")
|
| 622 |
-
for mode, description in TASK_DESCRIPTIONS.items():
|
| 623 |
-
print(f" {mode:8} - {description}")
|
| 624 |
-
print("\nExample usage:")
|
| 625 |
-
print("\n1. Basic OCR (default mode):")
|
| 626 |
-
print(" uv run paddleocr-vl-1.6.py input-dataset output-dataset")
|
| 627 |
-
print("\n2. Table extraction:")
|
| 628 |
-
print(" uv run paddleocr-vl-1.6.py docs tables-extracted --task-mode table")
|
| 629 |
-
print("\n3. Formula recognition:")
|
| 630 |
-
print(
|
| 631 |
-
" uv run paddleocr-vl-1.6.py papers formulas --task-mode formula --batch-size 32"
|
| 632 |
-
)
|
| 633 |
-
print("\n4. Chart analysis:")
|
| 634 |
-
print(" uv run paddleocr-vl-1.6.py diagrams charts-analyzed --task-mode chart")
|
| 635 |
-
print("\n5. Test with small sample:")
|
| 636 |
-
print(" uv run paddleocr-vl-1.6.py dataset test --max-samples 10 --shuffle")
|
| 637 |
-
print("\n6. Running on HF Jobs (image-mode required — see note below):")
|
| 638 |
-
print(" hf jobs uv run \\")
|
| 639 |
-
print(" --image vllm/vllm-openai:latest --flavor a100-large \\")
|
| 640 |
-
print(
|
| 641 |
-
" --python /usr/bin/python3 -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\"
|
| 642 |
-
)
|
| 643 |
-
print(" -s HF_TOKEN \\")
|
| 644 |
-
print(
|
| 645 |
-
" https://huggingface.co/datasets/uv-scripts/ocr/raw/main/paddleocr-vl-1.6.py \\"
|
| 646 |
-
)
|
| 647 |
-
print(" input-dataset output-dataset --task-mode ocr")
|
| 648 |
-
print("\n NOTE: the default uv-script image has no nvcc, so vLLM's flashinfer")
|
| 649 |
-
print(" sampler crashes at warmup. The vllm/vllm-openai image ships the kernels.")
|
| 650 |
-
print("\n" + "=" * 80)
|
| 651 |
-
print("\nFor full help, run: uv run paddleocr-vl-1.6.py --help")
|
| 652 |
-
sys.exit(0)
|
| 653 |
-
|
| 654 |
-
parser = argparse.ArgumentParser(
|
| 655 |
-
description="Document processing using PaddleOCR-VL-1.6 (0.9B SOTA OCR model)",
|
| 656 |
-
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 657 |
-
epilog="""
|
| 658 |
-
Task Modes:
|
| 659 |
-
ocr General text extraction to markdown (default)
|
| 660 |
-
table Table extraction to HTML format
|
| 661 |
-
formula Mathematical formula recognition to LaTeX
|
| 662 |
-
chart Chart and diagram analysis
|
| 663 |
-
spotting Text spotting with localization
|
| 664 |
-
seal Seal and stamp recognition
|
| 665 |
-
|
| 666 |
-
Examples:
|
| 667 |
-
# Basic text OCR
|
| 668 |
-
uv run paddleocr-vl-1.6.py my-docs analyzed-docs
|
| 669 |
-
|
| 670 |
-
# Extract tables from documents
|
| 671 |
-
uv run paddleocr-vl-1.6.py papers tables --task-mode table
|
| 672 |
-
|
| 673 |
-
# Recognize mathematical formulas
|
| 674 |
-
uv run paddleocr-vl-1.6.py textbooks formulas --task-mode formula
|
| 675 |
-
|
| 676 |
-
# Analyze charts and diagrams
|
| 677 |
-
uv run paddleocr-vl-1.6.py reports charts --task-mode chart
|
| 678 |
-
|
| 679 |
-
# Test with random sampling
|
| 680 |
-
uv run paddleocr-vl-1.6.py large-dataset test --max-samples 50 --shuffle --task-mode ocr
|
| 681 |
-
|
| 682 |
-
# Disable smart resize for original resolution
|
| 683 |
-
uv run paddleocr-vl-1.6.py images output --no-smart-resize
|
| 684 |
-
""",
|
| 685 |
-
)
|
| 686 |
-
|
| 687 |
-
parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
|
| 688 |
-
parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
|
| 689 |
-
parser.add_argument(
|
| 690 |
-
"--image-column",
|
| 691 |
-
default="image",
|
| 692 |
-
help="Column containing images (default: image)",
|
| 693 |
-
)
|
| 694 |
-
parser.add_argument(
|
| 695 |
-
"--batch-size",
|
| 696 |
-
type=int,
|
| 697 |
-
default=16,
|
| 698 |
-
help="Batch size for processing (default: 16)",
|
| 699 |
-
)
|
| 700 |
-
parser.add_argument(
|
| 701 |
-
"--task-mode",
|
| 702 |
-
choices=list(TASK_MODES.keys()),
|
| 703 |
-
default="ocr",
|
| 704 |
-
help="Task type: ocr (default), table, formula, chart, spotting, or seal",
|
| 705 |
-
)
|
| 706 |
-
parser.add_argument(
|
| 707 |
-
"--max-model-len",
|
| 708 |
-
type=int,
|
| 709 |
-
default=8192,
|
| 710 |
-
help="Maximum model context length (default: 8192)",
|
| 711 |
-
)
|
| 712 |
-
parser.add_argument(
|
| 713 |
-
"--max-tokens",
|
| 714 |
-
type=int,
|
| 715 |
-
default=4096,
|
| 716 |
-
help="Maximum tokens to generate (default: 4096)",
|
| 717 |
-
)
|
| 718 |
-
parser.add_argument(
|
| 719 |
-
"--temperature",
|
| 720 |
-
type=float,
|
| 721 |
-
default=0.0,
|
| 722 |
-
help="Sampling temperature (default: 0.0 for deterministic)",
|
| 723 |
-
)
|
| 724 |
-
parser.add_argument(
|
| 725 |
-
"--gpu-memory-utilization",
|
| 726 |
-
type=float,
|
| 727 |
-
default=0.8,
|
| 728 |
-
help="GPU memory utilization (default: 0.8)",
|
| 729 |
-
)
|
| 730 |
-
parser.add_argument(
|
| 731 |
-
"--no-smart-resize",
|
| 732 |
-
action="store_true",
|
| 733 |
-
help="Disable PaddleOCR-VL's smart resize, use original image size",
|
| 734 |
-
)
|
| 735 |
-
parser.add_argument("--hf-token", help="Hugging Face API token")
|
| 736 |
-
parser.add_argument(
|
| 737 |
-
"--split", default="train", help="Dataset split to use (default: train)"
|
| 738 |
-
)
|
| 739 |
-
parser.add_argument(
|
| 740 |
-
"--max-samples",
|
| 741 |
-
type=int,
|
| 742 |
-
help="Maximum number of samples to process (for testing)",
|
| 743 |
-
)
|
| 744 |
-
parser.add_argument(
|
| 745 |
-
"--private", action="store_true", help="Make output dataset private"
|
| 746 |
-
)
|
| 747 |
-
parser.add_argument(
|
| 748 |
-
"--shuffle", action="store_true", help="Shuffle dataset before processing"
|
| 749 |
-
)
|
| 750 |
-
parser.add_argument(
|
| 751 |
-
"--seed",
|
| 752 |
-
type=int,
|
| 753 |
-
default=42,
|
| 754 |
-
help="Random seed for shuffling (default: 42)",
|
| 755 |
-
)
|
| 756 |
-
parser.add_argument(
|
| 757 |
-
"--output-column",
|
| 758 |
-
help="Column name for output (default: markdown)",
|
| 759 |
-
)
|
| 760 |
-
parser.add_argument(
|
| 761 |
-
"--config",
|
| 762 |
-
help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
|
| 763 |
-
)
|
| 764 |
-
parser.add_argument(
|
| 765 |
-
"--create-pr",
|
| 766 |
-
action="store_true",
|
| 767 |
-
help="Create a pull request instead of pushing directly (for parallel benchmarking)",
|
| 768 |
-
)
|
| 769 |
-
parser.add_argument(
|
| 770 |
-
"--verbose",
|
| 771 |
-
action="store_true",
|
| 772 |
-
help="Log resolved package versions after processing (useful for pinning deps)",
|
| 773 |
-
)
|
| 774 |
-
|
| 775 |
-
args = parser.parse_args()
|
| 776 |
-
|
| 777 |
-
main(
|
| 778 |
-
input_dataset=args.input_dataset,
|
| 779 |
-
output_dataset=args.output_dataset,
|
| 780 |
-
image_column=args.image_column,
|
| 781 |
-
batch_size=args.batch_size,
|
| 782 |
-
task_mode=args.task_mode,
|
| 783 |
-
max_model_len=args.max_model_len,
|
| 784 |
-
max_tokens=args.max_tokens,
|
| 785 |
-
temperature=args.temperature,
|
| 786 |
-
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 787 |
-
apply_smart_resize=not args.no_smart_resize,
|
| 788 |
-
hf_token=args.hf_token,
|
| 789 |
-
split=args.split,
|
| 790 |
-
max_samples=args.max_samples,
|
| 791 |
-
private=args.private,
|
| 792 |
-
shuffle=args.shuffle,
|
| 793 |
-
seed=args.seed,
|
| 794 |
-
output_column=args.output_column,
|
| 795 |
-
config=args.config,
|
| 796 |
-
create_pr=args.create_pr,
|
| 797 |
-
verbose=args.verbose,
|
| 798 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
paddleocr-vl.py
CHANGED
|
@@ -56,10 +56,6 @@ from huggingface_hub import DatasetCard, login
|
|
| 56 |
from PIL import Image
|
| 57 |
from toolz import partition_all
|
| 58 |
from tqdm.auto import tqdm
|
| 59 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 60 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 61 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 62 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 63 |
from vllm import LLM, SamplingParams
|
| 64 |
|
| 65 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 56 |
from PIL import Image
|
| 57 |
from toolz import partition_all
|
| 58 |
from tqdm.auto import tqdm
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
from vllm import LLM, SamplingParams
|
| 60 |
|
| 61 |
logging.basicConfig(level=logging.INFO)
|
pp-doclayout.py
DELETED
|
@@ -1,1183 +0,0 @@
|
|
| 1 |
-
# /// script
|
| 2 |
-
# requires-python = ">=3.10"
|
| 3 |
-
# dependencies = [
|
| 4 |
-
# "paddlepaddle-gpu>=3.0.0",
|
| 5 |
-
# "paddleocr>=3.0.0",
|
| 6 |
-
# "opencv-contrib-python-headless",
|
| 7 |
-
# "datasets>=4.0.0",
|
| 8 |
-
# "huggingface-hub>=1.6.0",
|
| 9 |
-
# "pyarrow>=15.0",
|
| 10 |
-
# "pillow",
|
| 11 |
-
# "numpy",
|
| 12 |
-
# "tqdm",
|
| 13 |
-
# ]
|
| 14 |
-
#
|
| 15 |
-
# [tool.uv]
|
| 16 |
-
# # PaddleOCR/PaddleX pull in opencv-contrib-python (full) which needs system
|
| 17 |
-
# # libGL.so.1 — not present in the slim uv-on-bookworm image used by HF Jobs.
|
| 18 |
-
# # Swap to the headless cv2 variant (same `import cv2`, no GUI deps).
|
| 19 |
-
# override-dependencies = [
|
| 20 |
-
# "opencv-contrib-python ; python_version < '0'",
|
| 21 |
-
# "opencv-python ; python_version < '0'",
|
| 22 |
-
# ]
|
| 23 |
-
#
|
| 24 |
-
# [[tool.uv.index]]
|
| 25 |
-
# name = "paddle"
|
| 26 |
-
# url = "https://www.paddlepaddle.org.cn/packages/stable/cu126/"
|
| 27 |
-
# explicit = true
|
| 28 |
-
#
|
| 29 |
-
# [tool.uv.sources]
|
| 30 |
-
# paddlepaddle-gpu = { index = "paddle" }
|
| 31 |
-
# ///
|
| 32 |
-
|
| 33 |
-
"""
|
| 34 |
-
Detect document layout regions (text/title/table/figure/formula/...) with PP-DocLayout-L.
|
| 35 |
-
|
| 36 |
-
Runs PaddleOCR's PP-DocLayout-L (or M / S / plus-L variant) over an image source
|
| 37 |
-
and emits per-image bounding-box predictions. Unlike the OCR scripts in this repo
|
| 38 |
-
this does NOT extract text — it only locates and classifies regions.
|
| 39 |
-
|
| 40 |
-
Source can be:
|
| 41 |
-
- HF dataset repo (default): "namespace/dataset"
|
| 42 |
-
- HF bucket of image files: "hf://buckets/namespace/bucket/optional/prefix"
|
| 43 |
-
|
| 44 |
-
Sink can be:
|
| 45 |
-
- HF dataset repo (default): "namespace/dataset" (one push at end + dataset card)
|
| 46 |
-
- HF bucket: "hf://buckets/namespace/bucket/run-name" (incremental parquet
|
| 47 |
-
shards, resumable, no git overhead)
|
| 48 |
-
|
| 49 |
-
Output schema (column `layout` is a JSON string):
|
| 50 |
-
[{"bbox": [x1, y1, x2, y2], "label": "text", "score": 0.97, "cls_id": 2}, ...]
|
| 51 |
-
|
| 52 |
-
Coordinates are in the original input-image pixel space.
|
| 53 |
-
|
| 54 |
-
Example commands:
|
| 55 |
-
|
| 56 |
-
# Dataset -> dataset (smoke on L4)
|
| 57 |
-
hf jobs uv run --flavor l4x1 -s HF_TOKEN https://huggingface.co/datasets/uv-scripts/ocr/raw/main/pp-doclayout.py \\
|
| 58 |
-
davanstrien/ufo-ColPali pp-doclayout-smoke \\
|
| 59 |
-
--max-samples 3 --shuffle --seed 42 --private
|
| 60 |
-
|
| 61 |
-
# Dataset -> bucket (incremental shards, resumable)
|
| 62 |
-
hf buckets create davanstrien/pp-doclayout-scratch --exist-ok
|
| 63 |
-
hf jobs uv run --flavor l4x1 -s HF_TOKEN https://huggingface.co/datasets/uv-scripts/ocr/raw/main/pp-doclayout.py \\
|
| 64 |
-
davanstrien/ufo-ColPali \\
|
| 65 |
-
hf://buckets/davanstrien/pp-doclayout-scratch/run1 \\
|
| 66 |
-
--max-samples 20 --shard-size 5
|
| 67 |
-
|
| 68 |
-
# Bucket of images -> dataset
|
| 69 |
-
hf jobs uv run --flavor l4x1 -s HF_TOKEN https://huggingface.co/datasets/uv-scripts/ocr/raw/main/pp-doclayout.py \\
|
| 70 |
-
hf://buckets/davanstrien/pp-doclayout-images \\
|
| 71 |
-
pp-doclayout-from-bucket --private
|
| 72 |
-
"""
|
| 73 |
-
|
| 74 |
-
import argparse
|
| 75 |
-
import io
|
| 76 |
-
import json
|
| 77 |
-
import logging
|
| 78 |
-
import os
|
| 79 |
-
import sys
|
| 80 |
-
import time
|
| 81 |
-
from dataclasses import dataclass
|
| 82 |
-
from datetime import datetime, timezone
|
| 83 |
-
from pathlib import Path
|
| 84 |
-
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
|
| 85 |
-
|
| 86 |
-
import numpy as np
|
| 87 |
-
from PIL import Image, UnidentifiedImageError
|
| 88 |
-
from tqdm.auto import tqdm
|
| 89 |
-
|
| 90 |
-
logging.basicConfig(level=logging.INFO)
|
| 91 |
-
logger = logging.getLogger(__name__)
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
# ---------------------------------------------------------------------------
|
| 95 |
-
# Constants
|
| 96 |
-
# ---------------------------------------------------------------------------
|
| 97 |
-
|
| 98 |
-
VALID_MODELS = [
|
| 99 |
-
"PP-DocLayout-L",
|
| 100 |
-
"PP-DocLayout-M",
|
| 101 |
-
"PP-DocLayout-S",
|
| 102 |
-
"PP-DocLayout_plus-L",
|
| 103 |
-
]
|
| 104 |
-
|
| 105 |
-
MODEL_SIZES = {
|
| 106 |
-
"PP-DocLayout-L": "~123M params (RT-DETR-L backbone)",
|
| 107 |
-
"PP-DocLayout-M": "~22M params (PicoDet-M)",
|
| 108 |
-
"PP-DocLayout-S": "~4M params (PicoDet-S)",
|
| 109 |
-
"PP-DocLayout_plus-L": "~123M params, 20-class plus variant",
|
| 110 |
-
}
|
| 111 |
-
|
| 112 |
-
IMAGE_EXTENSIONS = {
|
| 113 |
-
".jpg", ".jpeg", ".png", ".tif", ".tiff", ".webp", ".bmp", ".jp2", ".j2k",
|
| 114 |
-
}
|
| 115 |
-
|
| 116 |
-
BUCKET_PREFIX = "hf://buckets/"
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
# ---------------------------------------------------------------------------
|
| 120 |
-
# URL helpers
|
| 121 |
-
# ---------------------------------------------------------------------------
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
def is_bucket_url(s: str) -> bool:
|
| 125 |
-
return s.startswith(BUCKET_PREFIX)
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
def parse_bucket_url(url: str) -> Tuple[str, str]:
|
| 129 |
-
"""Split `hf://buckets/ns/bucket/path/in/bucket` into (`ns/bucket`, `path/in/bucket`)."""
|
| 130 |
-
if not is_bucket_url(url):
|
| 131 |
-
raise ValueError(f"Not a bucket URL: {url}")
|
| 132 |
-
rest = url[len(BUCKET_PREFIX) :].strip("/")
|
| 133 |
-
parts = rest.split("/", 2)
|
| 134 |
-
if len(parts) < 2:
|
| 135 |
-
raise ValueError(
|
| 136 |
-
f"Bucket URL must include namespace and bucket name: {url}"
|
| 137 |
-
)
|
| 138 |
-
bucket_id = f"{parts[0]}/{parts[1]}"
|
| 139 |
-
prefix = parts[2] if len(parts) > 2 else ""
|
| 140 |
-
return bucket_id, prefix
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
# ---------------------------------------------------------------------------
|
| 144 |
-
# Image helpers
|
| 145 |
-
# ---------------------------------------------------------------------------
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
def to_pil(image: Union[Image.Image, Dict[str, Any], str, bytes]) -> Image.Image:
|
| 149 |
-
if isinstance(image, Image.Image):
|
| 150 |
-
return image.convert("RGB")
|
| 151 |
-
if isinstance(image, dict) and "bytes" in image:
|
| 152 |
-
return Image.open(io.BytesIO(image["bytes"])).convert("RGB")
|
| 153 |
-
if isinstance(image, (bytes, bytearray)):
|
| 154 |
-
return Image.open(io.BytesIO(image)).convert("RGB")
|
| 155 |
-
if isinstance(image, str):
|
| 156 |
-
return Image.open(image).convert("RGB")
|
| 157 |
-
raise ValueError(f"Unsupported image type: {type(image)}")
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
def pil_to_array(pil_img: Image.Image) -> np.ndarray:
|
| 161 |
-
"""RGB PIL -> uint8 ndarray. PaddleOCR's predict() accepts numpy arrays directly."""
|
| 162 |
-
return np.asarray(pil_img, dtype=np.uint8)
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
# ---------------------------------------------------------------------------
|
| 166 |
-
# Result extraction
|
| 167 |
-
# ---------------------------------------------------------------------------
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
def extract_detections(result: Any) -> List[Dict[str, Any]]:
|
| 171 |
-
"""Pull a clean list of detections out of a paddleocr LayoutDetection result."""
|
| 172 |
-
payload = result.json
|
| 173 |
-
res = payload.get("res", payload) if isinstance(payload, dict) else {}
|
| 174 |
-
boxes = res.get("boxes", []) if isinstance(res, dict) else []
|
| 175 |
-
detections = []
|
| 176 |
-
for box in boxes:
|
| 177 |
-
coord = box.get("coordinate") or box.get("bbox") or []
|
| 178 |
-
coord = [float(x) for x in coord]
|
| 179 |
-
detections.append(
|
| 180 |
-
{
|
| 181 |
-
"bbox": coord,
|
| 182 |
-
"label": box.get("label"),
|
| 183 |
-
"score": float(box.get("score", 0.0)),
|
| 184 |
-
"cls_id": int(box.get("cls_id", -1)),
|
| 185 |
-
}
|
| 186 |
-
)
|
| 187 |
-
return detections
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
# ---------------------------------------------------------------------------
|
| 191 |
-
# Sources
|
| 192 |
-
# ---------------------------------------------------------------------------
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
@dataclass
|
| 196 |
-
class SourceItem:
|
| 197 |
-
key: str # stable identifier per image (used for dedup/resume)
|
| 198 |
-
image: Image.Image
|
| 199 |
-
extras: Dict[str, Any] # original row fields (only populated for dataset source)
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
def iter_dataset_images(
|
| 203 |
-
dataset_id: str,
|
| 204 |
-
image_column: str,
|
| 205 |
-
split: str,
|
| 206 |
-
shuffle: bool,
|
| 207 |
-
seed: int,
|
| 208 |
-
max_samples: Optional[int],
|
| 209 |
-
):
|
| 210 |
-
"""Iterate (key, PIL) pairs from an HF dataset repo.
|
| 211 |
-
|
| 212 |
-
Returns: (iterator, total, dataset_reference). The dataset reference is the
|
| 213 |
-
post-shuffle/post-select Dataset, kept around so the dataset-repo sink can
|
| 214 |
-
`add_column("layout", ...)` and preserve the original schema (especially
|
| 215 |
-
Image-type columns).
|
| 216 |
-
"""
|
| 217 |
-
from datasets import load_dataset
|
| 218 |
-
|
| 219 |
-
logger.info(f"Loading dataset: {dataset_id} (split={split})")
|
| 220 |
-
ds = load_dataset(dataset_id, split=split)
|
| 221 |
-
|
| 222 |
-
if image_column not in ds.column_names:
|
| 223 |
-
raise ValueError(
|
| 224 |
-
f"Column '{image_column}' not found. Available: {ds.column_names}"
|
| 225 |
-
)
|
| 226 |
-
|
| 227 |
-
if shuffle:
|
| 228 |
-
logger.info(f"Shuffling with seed {seed}")
|
| 229 |
-
ds = ds.shuffle(seed=seed)
|
| 230 |
-
if max_samples:
|
| 231 |
-
ds = ds.select(range(min(max_samples, len(ds))))
|
| 232 |
-
logger.info(f"Limited to {len(ds)} samples")
|
| 233 |
-
|
| 234 |
-
total = len(ds)
|
| 235 |
-
|
| 236 |
-
def gen() -> Iterator[SourceItem]:
|
| 237 |
-
skipped = 0
|
| 238 |
-
for i in range(total):
|
| 239 |
-
try:
|
| 240 |
-
row = ds[i]
|
| 241 |
-
image = to_pil(row[image_column])
|
| 242 |
-
except (UnidentifiedImageError, OSError) as e:
|
| 243 |
-
skipped += 1
|
| 244 |
-
logger.warning(
|
| 245 |
-
f"Skipping unreadable image at row {i}: "
|
| 246 |
-
f"{type(e).__name__}: {e}"
|
| 247 |
-
)
|
| 248 |
-
continue
|
| 249 |
-
yield SourceItem(
|
| 250 |
-
key=f"row-{i:08d}",
|
| 251 |
-
image=image,
|
| 252 |
-
extras={}, # original schema is preserved by the sink via the dataset ref
|
| 253 |
-
)
|
| 254 |
-
if skipped:
|
| 255 |
-
logger.info(f"Skipped {skipped} unreadable image(s) total")
|
| 256 |
-
|
| 257 |
-
return gen(), total, ds
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
SOURCE_PATHS_SNAPSHOT = "_source_paths.json"
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
def _bucket_snapshot_path(output_url: str) -> Tuple[str, str]:
|
| 264 |
-
"""Return (bucket_id, key) for the source-paths snapshot inside an output bucket."""
|
| 265 |
-
out_bucket_id, out_prefix = parse_bucket_url(output_url)
|
| 266 |
-
snapshot_key = (
|
| 267 |
-
f"{out_prefix}/{SOURCE_PATHS_SNAPSHOT}".lstrip("/")
|
| 268 |
-
if out_prefix
|
| 269 |
-
else SOURCE_PATHS_SNAPSHOT
|
| 270 |
-
)
|
| 271 |
-
return out_bucket_id, snapshot_key
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
def iter_bucket_images(
|
| 275 |
-
bucket_url: str,
|
| 276 |
-
shuffle: bool,
|
| 277 |
-
seed: int,
|
| 278 |
-
max_samples: Optional[int],
|
| 279 |
-
hf_token: Optional[str],
|
| 280 |
-
output_url: Optional[str] = None,
|
| 281 |
-
) -> Tuple[Iterator[SourceItem], int]:
|
| 282 |
-
"""Glob image files under a bucket prefix and stream them via HfFileSystem.
|
| 283 |
-
|
| 284 |
-
If `output_url` is a bucket, the resolved source-path list is snapshotted to
|
| 285 |
-
`<output>/_source_paths.json` on first run. Subsequent runs against the same
|
| 286 |
-
output prefix reuse that snapshot, so resume stays consistent even if the
|
| 287 |
-
source bucket grows or `--shuffle`/`--max-samples` would otherwise pick a
|
| 288 |
-
different subset on the second run.
|
| 289 |
-
"""
|
| 290 |
-
from huggingface_hub import HfApi, HfFileSystem
|
| 291 |
-
|
| 292 |
-
bucket_id, prefix = parse_bucket_url(bucket_url)
|
| 293 |
-
fs = HfFileSystem(token=hf_token)
|
| 294 |
-
base = f"{BUCKET_PREFIX}{bucket_id}/{prefix}".rstrip("/")
|
| 295 |
-
|
| 296 |
-
snapshot_bucket_id: Optional[str] = None
|
| 297 |
-
snapshot_key: Optional[str] = None
|
| 298 |
-
cached_paths: Optional[List[str]] = None
|
| 299 |
-
|
| 300 |
-
if output_url and is_bucket_url(output_url):
|
| 301 |
-
snapshot_bucket_id, snapshot_key = _bucket_snapshot_path(output_url)
|
| 302 |
-
snapshot_url = f"{BUCKET_PREFIX}{snapshot_bucket_id}/{snapshot_key}"
|
| 303 |
-
try:
|
| 304 |
-
with fs.open(snapshot_url, "rb") as f:
|
| 305 |
-
snapshot = json.load(f)
|
| 306 |
-
if snapshot.get("source_url") != bucket_url:
|
| 307 |
-
logger.warning(
|
| 308 |
-
f"Output prefix already has a snapshot referencing a "
|
| 309 |
-
f"different source ({snapshot.get('source_url')!r} vs "
|
| 310 |
-
f"{bucket_url!r}). Ignoring and re-listing."
|
| 311 |
-
)
|
| 312 |
-
else:
|
| 313 |
-
cached_paths = snapshot["paths"]
|
| 314 |
-
logger.info(
|
| 315 |
-
f"Reusing existing snapshot of {len(cached_paths)} source paths "
|
| 316 |
-
f"(written {snapshot.get('created_at', 'unknown')})"
|
| 317 |
-
)
|
| 318 |
-
except FileNotFoundError:
|
| 319 |
-
pass
|
| 320 |
-
except Exception as e:
|
| 321 |
-
logger.warning(f"Could not read existing snapshot ({e}); re-listing.")
|
| 322 |
-
|
| 323 |
-
if cached_paths is not None:
|
| 324 |
-
all_paths = cached_paths
|
| 325 |
-
else:
|
| 326 |
-
logger.info(f"Listing images under {base}")
|
| 327 |
-
all_paths = []
|
| 328 |
-
try:
|
| 329 |
-
for entry in fs.find(base, detail=False):
|
| 330 |
-
ext = Path(entry).suffix.lower()
|
| 331 |
-
if ext in IMAGE_EXTENSIONS:
|
| 332 |
-
all_paths.append(entry)
|
| 333 |
-
except FileNotFoundError as e:
|
| 334 |
-
raise ValueError(f"Bucket prefix not found: {base}") from e
|
| 335 |
-
|
| 336 |
-
if not all_paths:
|
| 337 |
-
raise ValueError(
|
| 338 |
-
f"No image files (any of {sorted(IMAGE_EXTENSIONS)}) under {base}"
|
| 339 |
-
)
|
| 340 |
-
|
| 341 |
-
all_paths.sort()
|
| 342 |
-
if shuffle:
|
| 343 |
-
rng = np.random.default_rng(seed)
|
| 344 |
-
rng.shuffle(all_paths)
|
| 345 |
-
if max_samples:
|
| 346 |
-
all_paths = all_paths[:max_samples]
|
| 347 |
-
|
| 348 |
-
# Persist the chosen list so resume runs see exactly this set.
|
| 349 |
-
if snapshot_bucket_id is not None and snapshot_key is not None:
|
| 350 |
-
api = HfApi(token=hf_token)
|
| 351 |
-
payload = {
|
| 352 |
-
"source_url": bucket_url,
|
| 353 |
-
"shuffle": shuffle,
|
| 354 |
-
"seed": seed,
|
| 355 |
-
"max_samples": max_samples,
|
| 356 |
-
"created_at": datetime.now(timezone.utc).isoformat(),
|
| 357 |
-
"paths": all_paths,
|
| 358 |
-
}
|
| 359 |
-
api.batch_bucket_files(
|
| 360 |
-
snapshot_bucket_id,
|
| 361 |
-
add=[(json.dumps(payload).encode(), snapshot_key)],
|
| 362 |
-
token=hf_token,
|
| 363 |
-
)
|
| 364 |
-
logger.info(
|
| 365 |
-
f"Wrote source-path snapshot ({len(all_paths)} paths) to "
|
| 366 |
-
f"hf://buckets/{snapshot_bucket_id}/{snapshot_key}"
|
| 367 |
-
)
|
| 368 |
-
|
| 369 |
-
total = len(all_paths)
|
| 370 |
-
logger.info(f"Found {total} images in bucket")
|
| 371 |
-
|
| 372 |
-
def key_for(path: str) -> str:
|
| 373 |
-
# Use the full bucket path (`buckets/<id>/<rel>`) as returned by
|
| 374 |
-
# fs.find. This is stable across reruns (so resume works), and the
|
| 375 |
-
# stored value in `source_path` is fully addressable — open via
|
| 376 |
-
# HfFileSystem directly with `hf://` re-prepended.
|
| 377 |
-
return path
|
| 378 |
-
|
| 379 |
-
def gen() -> Iterator[SourceItem]:
|
| 380 |
-
skipped = 0
|
| 381 |
-
for path in all_paths:
|
| 382 |
-
try:
|
| 383 |
-
with fs.open(path, "rb") as f:
|
| 384 |
-
data = f.read()
|
| 385 |
-
image = to_pil(data)
|
| 386 |
-
except (UnidentifiedImageError, OSError) as e:
|
| 387 |
-
skipped += 1
|
| 388 |
-
logger.warning(
|
| 389 |
-
f"Skipping unreadable image {path}: "
|
| 390 |
-
f"{type(e).__name__}: {e}"
|
| 391 |
-
)
|
| 392 |
-
continue
|
| 393 |
-
yield SourceItem(
|
| 394 |
-
key=key_for(path),
|
| 395 |
-
image=image,
|
| 396 |
-
extras={"__source_path": key_for(path)},
|
| 397 |
-
)
|
| 398 |
-
if skipped:
|
| 399 |
-
logger.info(f"Skipped {skipped} unreadable image(s) total")
|
| 400 |
-
|
| 401 |
-
return gen(), total
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
# ---------------------------------------------------------------------------
|
| 405 |
-
# Sinks
|
| 406 |
-
# ---------------------------------------------------------------------------
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
class DatasetRepoSink:
|
| 410 |
-
"""Buffer all results in memory, push once at end with dataset card + inference_info.
|
| 411 |
-
|
| 412 |
-
Two modes:
|
| 413 |
-
- `original_dataset` provided (dataset-repo source): preserve the source
|
| 414 |
-
schema (including Image-type columns) and just `add_column("layout", ...)`.
|
| 415 |
-
- `original_dataset` is None (bucket-image source): build a Dataset from
|
| 416 |
-
collected rows containing __source_path + layout.
|
| 417 |
-
"""
|
| 418 |
-
|
| 419 |
-
def __init__(
|
| 420 |
-
self,
|
| 421 |
-
repo_id: str,
|
| 422 |
-
*,
|
| 423 |
-
hf_token: Optional[str],
|
| 424 |
-
private: bool,
|
| 425 |
-
config: Optional[str],
|
| 426 |
-
create_pr: bool,
|
| 427 |
-
source_id: str,
|
| 428 |
-
original_dataset=None,
|
| 429 |
-
):
|
| 430 |
-
self.repo_id = repo_id
|
| 431 |
-
self.hf_token = hf_token
|
| 432 |
-
self.private = private
|
| 433 |
-
self.config = config
|
| 434 |
-
self.create_pr = create_pr
|
| 435 |
-
self.source_id = source_id
|
| 436 |
-
self.original_dataset = original_dataset
|
| 437 |
-
# Used when original_dataset is None: row-by-row buffer.
|
| 438 |
-
self._rows: List[Dict[str, Any]] = []
|
| 439 |
-
# Used when original_dataset is set: ordered layouts aligned with dataset rows.
|
| 440 |
-
self._layouts: List[str] = []
|
| 441 |
-
|
| 442 |
-
@property
|
| 443 |
-
def kind(self) -> str:
|
| 444 |
-
return "dataset"
|
| 445 |
-
|
| 446 |
-
def already_done(self) -> set:
|
| 447 |
-
return set() # dataset sink does a single push, no resume
|
| 448 |
-
|
| 449 |
-
def write(self, key: str, layout: List[Dict[str, Any]], extras: Dict[str, Any]) -> None:
|
| 450 |
-
layout_json = json.dumps(layout, ensure_ascii=False)
|
| 451 |
-
if self.original_dataset is not None:
|
| 452 |
-
self._layouts.append(layout_json)
|
| 453 |
-
return
|
| 454 |
-
row = {"__source_key": key, "layout": layout_json}
|
| 455 |
-
for k, v in extras.items():
|
| 456 |
-
if isinstance(v, (str, int, float, bool)) or v is None:
|
| 457 |
-
row[k] = v
|
| 458 |
-
self._rows.append(row)
|
| 459 |
-
|
| 460 |
-
def finalize(self, model_id: str, args_dict: Dict[str, Any]) -> None:
|
| 461 |
-
from datasets import Dataset
|
| 462 |
-
|
| 463 |
-
if self.original_dataset is not None:
|
| 464 |
-
if len(self._layouts) != len(self.original_dataset):
|
| 465 |
-
logger.warning(
|
| 466 |
-
f"Layout count ({len(self._layouts)}) != dataset rows "
|
| 467 |
-
f"({len(self.original_dataset)}); padding with empty layouts."
|
| 468 |
-
)
|
| 469 |
-
# Pad to keep add_column happy.
|
| 470 |
-
while len(self._layouts) < len(self.original_dataset):
|
| 471 |
-
self._layouts.append("[]")
|
| 472 |
-
ds = self.original_dataset.add_column("layout", self._layouts)
|
| 473 |
-
else:
|
| 474 |
-
if not self._rows:
|
| 475 |
-
logger.warning("No rows produced; nothing to push.")
|
| 476 |
-
return
|
| 477 |
-
ds = Dataset.from_list(self._rows)
|
| 478 |
-
if "__source_key" in ds.column_names:
|
| 479 |
-
ds = ds.rename_column("__source_key", "source_path")
|
| 480 |
-
|
| 481 |
-
inference_entry = build_inference_entry(model_id, args_dict)
|
| 482 |
-
|
| 483 |
-
if "inference_info" in ds.column_names:
|
| 484 |
-
logger.info("Updating existing inference_info column")
|
| 485 |
-
|
| 486 |
-
def _update(example):
|
| 487 |
-
try:
|
| 488 |
-
existing = (
|
| 489 |
-
json.loads(example["inference_info"])
|
| 490 |
-
if example["inference_info"]
|
| 491 |
-
else []
|
| 492 |
-
)
|
| 493 |
-
except (json.JSONDecodeError, TypeError):
|
| 494 |
-
existing = []
|
| 495 |
-
existing.append(inference_entry)
|
| 496 |
-
return {"inference_info": json.dumps(existing)}
|
| 497 |
-
|
| 498 |
-
ds = ds.map(_update)
|
| 499 |
-
else:
|
| 500 |
-
ds = ds.add_column(
|
| 501 |
-
"inference_info", [json.dumps([inference_entry])] * len(ds)
|
| 502 |
-
)
|
| 503 |
-
|
| 504 |
-
logger.info(f"Pushing {len(ds)} rows to {self.repo_id}")
|
| 505 |
-
push_kwargs = {
|
| 506 |
-
"private": self.private,
|
| 507 |
-
"token": self.hf_token,
|
| 508 |
-
"max_shard_size": "500MB",
|
| 509 |
-
"create_pr": self.create_pr,
|
| 510 |
-
"commit_message": f"Add PP-DocLayout layout predictions ({len(ds)} samples)"
|
| 511 |
-
+ (f" [{self.config}]" if self.config else ""),
|
| 512 |
-
}
|
| 513 |
-
if self.config:
|
| 514 |
-
push_kwargs["config_name"] = self.config
|
| 515 |
-
|
| 516 |
-
max_retries = 3
|
| 517 |
-
for attempt in range(1, max_retries + 1):
|
| 518 |
-
try:
|
| 519 |
-
if attempt > 1:
|
| 520 |
-
logger.warning("Disabling XET (fallback to HTTP upload)")
|
| 521 |
-
os.environ["HF_HUB_DISABLE_XET"] = "1"
|
| 522 |
-
ds.push_to_hub(self.repo_id, **push_kwargs)
|
| 523 |
-
break
|
| 524 |
-
except Exception as e:
|
| 525 |
-
logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
|
| 526 |
-
if attempt == max_retries:
|
| 527 |
-
logger.error("All upload attempts failed.")
|
| 528 |
-
raise
|
| 529 |
-
time.sleep(30 * (2 ** (attempt - 1)))
|
| 530 |
-
|
| 531 |
-
# Dataset card
|
| 532 |
-
from huggingface_hub import DatasetCard
|
| 533 |
-
|
| 534 |
-
card = DatasetCard(
|
| 535 |
-
create_dataset_card(
|
| 536 |
-
source=self.source_id,
|
| 537 |
-
model_name=args_dict["model_name"],
|
| 538 |
-
num_samples=len(ds),
|
| 539 |
-
processing_time=args_dict["processing_time"],
|
| 540 |
-
output_column="layout",
|
| 541 |
-
threshold=args_dict["threshold"],
|
| 542 |
-
layout_nms=args_dict["layout_nms"],
|
| 543 |
-
)
|
| 544 |
-
)
|
| 545 |
-
card.push_to_hub(self.repo_id, token=self.hf_token)
|
| 546 |
-
logger.info(
|
| 547 |
-
f"Done: https://huggingface.co/datasets/{self.repo_id}"
|
| 548 |
-
)
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
class BucketShardSink:
|
| 552 |
-
"""Write incremental parquet shards to a bucket prefix. Resumable."""
|
| 553 |
-
|
| 554 |
-
METADATA_FILE = "_metadata.json"
|
| 555 |
-
SHARD_PATTERN = "shard-{:05d}.parquet"
|
| 556 |
-
|
| 557 |
-
def __init__(
|
| 558 |
-
self,
|
| 559 |
-
bucket_url: str,
|
| 560 |
-
*,
|
| 561 |
-
hf_token: Optional[str],
|
| 562 |
-
shard_size: int,
|
| 563 |
-
include_images: bool,
|
| 564 |
-
resume: bool,
|
| 565 |
-
source_id: str,
|
| 566 |
-
):
|
| 567 |
-
from huggingface_hub import HfApi, HfFileSystem, create_bucket
|
| 568 |
-
|
| 569 |
-
self.bucket_url = bucket_url
|
| 570 |
-
self.bucket_id, self.prefix = parse_bucket_url(bucket_url)
|
| 571 |
-
self.hf_token = hf_token
|
| 572 |
-
self.shard_size = shard_size
|
| 573 |
-
self.include_images = include_images
|
| 574 |
-
self.resume = resume
|
| 575 |
-
self.source_id = source_id
|
| 576 |
-
|
| 577 |
-
self._api = HfApi(token=hf_token)
|
| 578 |
-
self._fs = HfFileSystem(token=hf_token)
|
| 579 |
-
|
| 580 |
-
# Make sure the bucket exists. Path inside the bucket is created lazily on first write.
|
| 581 |
-
try:
|
| 582 |
-
create_bucket(self.bucket_id, exist_ok=True, token=hf_token)
|
| 583 |
-
except Exception as e:
|
| 584 |
-
# If we don't have create rights but the bucket already exists, that's fine.
|
| 585 |
-
logger.warning(f"create_bucket('{self.bucket_id}') warning: {e}")
|
| 586 |
-
|
| 587 |
-
self._buffer: List[Dict[str, Any]] = []
|
| 588 |
-
self._next_shard_idx = self._discover_next_shard_idx()
|
| 589 |
-
self._completed_keys = self._discover_completed_keys() if resume else set()
|
| 590 |
-
if self._completed_keys:
|
| 591 |
-
logger.info(
|
| 592 |
-
f"Resume: found {len(self._completed_keys)} already-processed keys, will skip them"
|
| 593 |
-
)
|
| 594 |
-
|
| 595 |
-
@property
|
| 596 |
-
def kind(self) -> str:
|
| 597 |
-
return "bucket"
|
| 598 |
-
|
| 599 |
-
def already_done(self) -> set:
|
| 600 |
-
return self._completed_keys
|
| 601 |
-
|
| 602 |
-
# --- internal helpers ---
|
| 603 |
-
|
| 604 |
-
def _shard_path(self, idx: int) -> str:
|
| 605 |
-
return self._join(self.SHARD_PATTERN.format(idx))
|
| 606 |
-
|
| 607 |
-
def _join(self, name: str) -> str:
|
| 608 |
-
return f"{self.prefix}/{name}".lstrip("/") if self.prefix else name
|
| 609 |
-
|
| 610 |
-
def _list_existing_shards(self) -> List[str]:
|
| 611 |
-
try:
|
| 612 |
-
tree = self._api.list_bucket_tree(
|
| 613 |
-
self.bucket_id, prefix=self.prefix or None, recursive=True
|
| 614 |
-
)
|
| 615 |
-
except Exception:
|
| 616 |
-
return []
|
| 617 |
-
shards: List[str] = []
|
| 618 |
-
for item in tree:
|
| 619 |
-
path = getattr(item, "path", None)
|
| 620 |
-
ftype = getattr(item, "type", None)
|
| 621 |
-
if not path or ftype not in (None, "file"):
|
| 622 |
-
continue
|
| 623 |
-
base = Path(path).name
|
| 624 |
-
if base.startswith("shard-") and base.endswith(".parquet"):
|
| 625 |
-
shards.append(path)
|
| 626 |
-
return sorted(shards)
|
| 627 |
-
|
| 628 |
-
def _discover_next_shard_idx(self) -> int:
|
| 629 |
-
shards = self._list_existing_shards()
|
| 630 |
-
max_idx = -1
|
| 631 |
-
for s in shards:
|
| 632 |
-
stem = Path(s).stem # shard-00007
|
| 633 |
-
try:
|
| 634 |
-
max_idx = max(max_idx, int(stem.split("-")[-1]))
|
| 635 |
-
except ValueError:
|
| 636 |
-
continue
|
| 637 |
-
return max_idx + 1
|
| 638 |
-
|
| 639 |
-
def _discover_completed_keys(self) -> set:
|
| 640 |
-
import pyarrow.parquet as pq
|
| 641 |
-
|
| 642 |
-
keys: set = set()
|
| 643 |
-
for shard_path in self._list_existing_shards():
|
| 644 |
-
full = f"{BUCKET_PREFIX}{self.bucket_id}/{shard_path}"
|
| 645 |
-
try:
|
| 646 |
-
with self._fs.open(full, "rb") as f:
|
| 647 |
-
table = pq.read_table(f, columns=["__source_key"])
|
| 648 |
-
keys.update(table.column("__source_key").to_pylist())
|
| 649 |
-
except Exception as e:
|
| 650 |
-
logger.warning(f"Could not read keys from {shard_path}: {e}")
|
| 651 |
-
return keys
|
| 652 |
-
|
| 653 |
-
def _flush(self) -> None:
|
| 654 |
-
if not self._buffer:
|
| 655 |
-
return
|
| 656 |
-
import pyarrow as pa
|
| 657 |
-
import pyarrow.parquet as pq
|
| 658 |
-
|
| 659 |
-
# Build a stable schema. Skip the image column if not requested.
|
| 660 |
-
columns = ["__source_key", "layout"]
|
| 661 |
-
if self.include_images:
|
| 662 |
-
columns.append("__image_bytes")
|
| 663 |
-
# Carry through any extra string-coercible fields (e.g. __source_path).
|
| 664 |
-
extra_keys = sorted(
|
| 665 |
-
{k for row in self._buffer for k in row.keys() if k not in columns}
|
| 666 |
-
)
|
| 667 |
-
columns.extend(extra_keys)
|
| 668 |
-
|
| 669 |
-
table_dict = {c: [row.get(c) for row in self._buffer] for c in columns}
|
| 670 |
-
# pyarrow infers types from python objects; strings/bytes/lists handled fine.
|
| 671 |
-
table = pa.Table.from_pydict(table_dict)
|
| 672 |
-
|
| 673 |
-
buf = io.BytesIO()
|
| 674 |
-
pq.write_table(table, buf, compression="zstd")
|
| 675 |
-
data = buf.getvalue()
|
| 676 |
-
|
| 677 |
-
shard_remote = self._shard_path(self._next_shard_idx)
|
| 678 |
-
logger.info(
|
| 679 |
-
f"Writing shard {self._next_shard_idx} ({len(self._buffer)} rows, "
|
| 680 |
-
f"{len(data) / 1024 / 1024:.1f} MiB) to {shard_remote}"
|
| 681 |
-
)
|
| 682 |
-
self._api.batch_bucket_files(
|
| 683 |
-
self.bucket_id, add=[(data, shard_remote)], token=self.hf_token
|
| 684 |
-
)
|
| 685 |
-
self._next_shard_idx += 1
|
| 686 |
-
self._buffer.clear()
|
| 687 |
-
|
| 688 |
-
def write(self, key: str, layout: List[Dict[str, Any]], extras: Dict[str, Any]) -> None:
|
| 689 |
-
row: Dict[str, Any] = {
|
| 690 |
-
"__source_key": key,
|
| 691 |
-
"layout": json.dumps(layout, ensure_ascii=False),
|
| 692 |
-
}
|
| 693 |
-
if self.include_images and "__image_bytes" in extras:
|
| 694 |
-
row["__image_bytes"] = extras["__image_bytes"]
|
| 695 |
-
# Pass through string/numeric extras (skip raw PIL Image objects which
|
| 696 |
-
# the dataset source never injects directly into extras anyway).
|
| 697 |
-
for k, v in extras.items():
|
| 698 |
-
if k in row or k == "__image_bytes":
|
| 699 |
-
continue
|
| 700 |
-
if isinstance(v, (str, int, float, bool)) or v is None:
|
| 701 |
-
row[k] = v
|
| 702 |
-
self._buffer.append(row)
|
| 703 |
-
if len(self._buffer) >= self.shard_size:
|
| 704 |
-
self._flush()
|
| 705 |
-
|
| 706 |
-
def finalize(self, model_id: str, args_dict: Dict[str, Any]) -> None:
|
| 707 |
-
# Flush trailing rows.
|
| 708 |
-
self._flush()
|
| 709 |
-
# Write/update the metadata file alongside the shards.
|
| 710 |
-
meta = {
|
| 711 |
-
"model_id": model_id,
|
| 712 |
-
"model_name": args_dict["model_name"],
|
| 713 |
-
"task_mode": "layout-detection",
|
| 714 |
-
"source": self.source_id,
|
| 715 |
-
"threshold": args_dict["threshold"],
|
| 716 |
-
"layout_nms": args_dict["layout_nms"],
|
| 717 |
-
"shard_size": args_dict["shard_size"],
|
| 718 |
-
"include_images": self.include_images,
|
| 719 |
-
"last_run_at": datetime.now(timezone.utc).isoformat(),
|
| 720 |
-
"processing_time": args_dict.get("processing_time"),
|
| 721 |
-
}
|
| 722 |
-
meta_bytes = json.dumps(meta, indent=2).encode("utf-8")
|
| 723 |
-
meta_path = self._join(self.METADATA_FILE)
|
| 724 |
-
self._api.batch_bucket_files(
|
| 725 |
-
self.bucket_id, add=[(meta_bytes, meta_path)], token=self.hf_token
|
| 726 |
-
)
|
| 727 |
-
logger.info(
|
| 728 |
-
f"Done: https://huggingface.co/buckets/{self.bucket_id}"
|
| 729 |
-
+ (f"/{self.prefix}" if self.prefix else "")
|
| 730 |
-
)
|
| 731 |
-
|
| 732 |
-
|
| 733 |
-
# ---------------------------------------------------------------------------
|
| 734 |
-
# inference_info + dataset card
|
| 735 |
-
# ---------------------------------------------------------------------------
|
| 736 |
-
|
| 737 |
-
|
| 738 |
-
def build_inference_entry(model_id: str, args_dict: Dict[str, Any]) -> Dict[str, Any]:
|
| 739 |
-
return {
|
| 740 |
-
"model_id": "PaddlePaddle/" + args_dict["model_name"],
|
| 741 |
-
"model_name": args_dict["model_name"],
|
| 742 |
-
"model_size": MODEL_SIZES.get(args_dict["model_name"], "unknown"),
|
| 743 |
-
"task_mode": "layout-detection",
|
| 744 |
-
"column_name": "layout",
|
| 745 |
-
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 746 |
-
"threshold": args_dict["threshold"],
|
| 747 |
-
"layout_nms": args_dict["layout_nms"],
|
| 748 |
-
"backend": "paddleocr",
|
| 749 |
-
}
|
| 750 |
-
|
| 751 |
-
|
| 752 |
-
def create_dataset_card(
|
| 753 |
-
source: str,
|
| 754 |
-
model_name: str,
|
| 755 |
-
num_samples: int,
|
| 756 |
-
processing_time: str,
|
| 757 |
-
output_column: str,
|
| 758 |
-
threshold: float,
|
| 759 |
-
layout_nms: bool,
|
| 760 |
-
) -> str:
|
| 761 |
-
"""Render the dataset card markdown for the dataset-repo sink."""
|
| 762 |
-
if is_bucket_url(source):
|
| 763 |
-
source_link = f"[{source}]({source})"
|
| 764 |
-
else:
|
| 765 |
-
source_link = f"[{source}](https://huggingface.co/datasets/{source})"
|
| 766 |
-
|
| 767 |
-
return f"""---
|
| 768 |
-
tags:
|
| 769 |
-
- layout-detection
|
| 770 |
-
- document-processing
|
| 771 |
-
- paddleocr
|
| 772 |
-
- pp-doclayout
|
| 773 |
-
- uv-script
|
| 774 |
-
- generated
|
| 775 |
-
viewer: false
|
| 776 |
-
---
|
| 777 |
-
|
| 778 |
-
# Layout detection with {model_name}
|
| 779 |
-
|
| 780 |
-
Bounding-box layout predictions for images from {source_link}, produced by
|
| 781 |
-
PaddleOCR's [{model_name}](https://huggingface.co/PaddlePaddle/{model_name}).
|
| 782 |
-
|
| 783 |
-
## Processing details
|
| 784 |
-
|
| 785 |
-
- **Source**: {source_link}
|
| 786 |
-
- **Model**: PaddlePaddle/{model_name} ({MODEL_SIZES.get(model_name, "unknown")})
|
| 787 |
-
- **Samples**: {num_samples:,}
|
| 788 |
-
- **Processing time**: {processing_time}
|
| 789 |
-
- **Processing date**: {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}
|
| 790 |
-
- **Confidence threshold**: {threshold}
|
| 791 |
-
- **Layout NMS**: {"on" if layout_nms else "off"}
|
| 792 |
-
- **Output column**: `{output_column}` (JSON-encoded list of detections)
|
| 793 |
-
|
| 794 |
-
## Schema
|
| 795 |
-
|
| 796 |
-
Each row contains the original columns plus:
|
| 797 |
-
|
| 798 |
-
- `{output_column}`: JSON string. List of detections:
|
| 799 |
-
```json
|
| 800 |
-
[
|
| 801 |
-
{{"bbox": [x1, y1, x2, y2], "label": "text", "score": 0.97, "cls_id": 2}},
|
| 802 |
-
{{"bbox": [x1, y1, x2, y2], "label": "table", "score": 0.92, "cls_id": 5}}
|
| 803 |
-
]
|
| 804 |
-
```
|
| 805 |
-
Coordinates are in **original input-image pixel space** (top-left origin,
|
| 806 |
-
`[xmin, ymin, xmax, ymax]`).
|
| 807 |
-
- `inference_info`: JSON list tracking every model that has been applied to
|
| 808 |
-
this dataset (appended on each run).
|
| 809 |
-
|
| 810 |
-
## Usage
|
| 811 |
-
|
| 812 |
-
```python
|
| 813 |
-
import json
|
| 814 |
-
from datasets import load_dataset
|
| 815 |
-
|
| 816 |
-
ds = load_dataset("{{output_dataset_id}}", split="train")
|
| 817 |
-
detections = json.loads(ds[0]["{output_column}"])
|
| 818 |
-
for det in detections:
|
| 819 |
-
print(det["label"], det["score"], det["bbox"])
|
| 820 |
-
```
|
| 821 |
-
|
| 822 |
-
## Reproduction
|
| 823 |
-
|
| 824 |
-
```bash
|
| 825 |
-
hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
|
| 826 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/pp-doclayout.py \\
|
| 827 |
-
{source} <output> --model-name {model_name}
|
| 828 |
-
```
|
| 829 |
-
|
| 830 |
-
Generated with [UV Scripts](https://huggingface.co/uv-scripts).
|
| 831 |
-
"""
|
| 832 |
-
|
| 833 |
-
|
| 834 |
-
# ---------------------------------------------------------------------------
|
| 835 |
-
# Main
|
| 836 |
-
# ---------------------------------------------------------------------------
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
def resolve_device(device: str) -> str:
|
| 840 |
-
if device == "gpu":
|
| 841 |
-
try:
|
| 842 |
-
import paddle # noqa: F401
|
| 843 |
-
|
| 844 |
-
if paddle.device.is_compiled_with_cuda() and paddle.device.cuda.device_count() > 0:
|
| 845 |
-
logger.info(
|
| 846 |
-
f"GPU available: {paddle.device.cuda.device_count()} device(s)"
|
| 847 |
-
)
|
| 848 |
-
return "gpu"
|
| 849 |
-
logger.warning("No CUDA GPU detected; falling back to CPU.")
|
| 850 |
-
return "cpu"
|
| 851 |
-
except Exception as e:
|
| 852 |
-
logger.warning(f"GPU check failed ({e}); falling back to CPU.")
|
| 853 |
-
return "cpu"
|
| 854 |
-
return device
|
| 855 |
-
|
| 856 |
-
|
| 857 |
-
def main(args: argparse.Namespace) -> None:
|
| 858 |
-
from huggingface_hub import login
|
| 859 |
-
|
| 860 |
-
start_time = datetime.now()
|
| 861 |
-
hf_token = args.hf_token or os.environ.get("HF_TOKEN")
|
| 862 |
-
if hf_token:
|
| 863 |
-
login(token=hf_token)
|
| 864 |
-
|
| 865 |
-
device = resolve_device(args.device)
|
| 866 |
-
|
| 867 |
-
# ---------- source ----------
|
| 868 |
-
original_dataset = None
|
| 869 |
-
if is_bucket_url(args.input_source):
|
| 870 |
-
src_iter, total = iter_bucket_images(
|
| 871 |
-
args.input_source,
|
| 872 |
-
shuffle=args.shuffle,
|
| 873 |
-
seed=args.seed,
|
| 874 |
-
max_samples=args.max_samples,
|
| 875 |
-
hf_token=hf_token,
|
| 876 |
-
output_url=args.output_target,
|
| 877 |
-
)
|
| 878 |
-
else:
|
| 879 |
-
src_iter, total, original_dataset = iter_dataset_images(
|
| 880 |
-
args.input_source,
|
| 881 |
-
image_column=args.image_column,
|
| 882 |
-
split=args.split,
|
| 883 |
-
shuffle=args.shuffle,
|
| 884 |
-
seed=args.seed,
|
| 885 |
-
max_samples=args.max_samples,
|
| 886 |
-
)
|
| 887 |
-
|
| 888 |
-
# ---------- sink ----------
|
| 889 |
-
if is_bucket_url(args.output_target):
|
| 890 |
-
sink: Union[BucketShardSink, DatasetRepoSink] = BucketShardSink(
|
| 891 |
-
args.output_target,
|
| 892 |
-
hf_token=hf_token,
|
| 893 |
-
shard_size=args.shard_size,
|
| 894 |
-
include_images=args.include_images,
|
| 895 |
-
resume=not args.no_resume,
|
| 896 |
-
source_id=args.input_source,
|
| 897 |
-
)
|
| 898 |
-
else:
|
| 899 |
-
sink = DatasetRepoSink(
|
| 900 |
-
args.output_target,
|
| 901 |
-
hf_token=hf_token,
|
| 902 |
-
private=args.private,
|
| 903 |
-
config=args.config,
|
| 904 |
-
create_pr=args.create_pr,
|
| 905 |
-
source_id=args.input_source,
|
| 906 |
-
original_dataset=original_dataset,
|
| 907 |
-
)
|
| 908 |
-
|
| 909 |
-
completed = sink.already_done()
|
| 910 |
-
|
| 911 |
-
# ---------- model ----------
|
| 912 |
-
if args.model_name not in VALID_MODELS:
|
| 913 |
-
raise ValueError(
|
| 914 |
-
f"Invalid model {args.model_name!r}. Choose from: {VALID_MODELS}"
|
| 915 |
-
)
|
| 916 |
-
logger.info(f"Loading PaddleOCR LayoutDetection model: {args.model_name} on {device}")
|
| 917 |
-
# PaddleX gates `import cv2` at module load time on
|
| 918 |
-
# `is_dep_available("opencv-contrib-python")`, which checks
|
| 919 |
-
# `importlib.metadata.version(...)`. We ship `opencv-contrib-python-headless`
|
| 920 |
-
# (same `cv2`, no system libGL.so.1 needed) — but that's a different
|
| 921 |
-
# distribution name, so the gate fails and `cv2` is never bound, causing
|
| 922 |
-
# NameErrors deep inside paddlex modules. Patch the metadata lookup to
|
| 923 |
-
# alias the GUI cv2 distros to the headless variant before importing
|
| 924 |
-
# paddleocr; this lets paddlex's own `import cv2` succeed naturally.
|
| 925 |
-
import importlib.metadata as _metadata
|
| 926 |
-
|
| 927 |
-
_orig_metadata_version = _metadata.version
|
| 928 |
-
|
| 929 |
-
def _patched_metadata_version(dep_name):
|
| 930 |
-
if dep_name in ("opencv-contrib-python", "opencv-python"):
|
| 931 |
-
for headless_alias in (
|
| 932 |
-
"opencv-contrib-python-headless",
|
| 933 |
-
"opencv-python-headless",
|
| 934 |
-
):
|
| 935 |
-
try:
|
| 936 |
-
return _orig_metadata_version(headless_alias)
|
| 937 |
-
except _metadata.PackageNotFoundError:
|
| 938 |
-
continue
|
| 939 |
-
return _orig_metadata_version(dep_name)
|
| 940 |
-
|
| 941 |
-
_metadata.version = _patched_metadata_version
|
| 942 |
-
|
| 943 |
-
from paddleocr import LayoutDetection
|
| 944 |
-
|
| 945 |
-
model = LayoutDetection(model_name=args.model_name, device=device)
|
| 946 |
-
|
| 947 |
-
# ---------- loop ----------
|
| 948 |
-
processed = 0
|
| 949 |
-
skipped = 0
|
| 950 |
-
errors = 0
|
| 951 |
-
pbar = tqdm(src_iter, total=total, desc=f"Layout {args.model_name}")
|
| 952 |
-
for item in pbar:
|
| 953 |
-
if item.key in completed:
|
| 954 |
-
skipped += 1
|
| 955 |
-
continue
|
| 956 |
-
try:
|
| 957 |
-
arr = pil_to_array(item.image)
|
| 958 |
-
results = model.predict(
|
| 959 |
-
arr,
|
| 960 |
-
batch_size=args.batch_size,
|
| 961 |
-
layout_nms=args.layout_nms,
|
| 962 |
-
)
|
| 963 |
-
if not results:
|
| 964 |
-
detections: List[Dict[str, Any]] = []
|
| 965 |
-
else:
|
| 966 |
-
detections = extract_detections(results[0])
|
| 967 |
-
if args.threshold and args.threshold > 0:
|
| 968 |
-
detections = [d for d in detections if d["score"] >= args.threshold]
|
| 969 |
-
except Exception as e:
|
| 970 |
-
logger.error(f"Error on {item.key}: {e}")
|
| 971 |
-
detections = []
|
| 972 |
-
errors += 1
|
| 973 |
-
|
| 974 |
-
extras = dict(item.extras)
|
| 975 |
-
if isinstance(sink, BucketShardSink) and args.include_images:
|
| 976 |
-
buf = io.BytesIO()
|
| 977 |
-
item.image.save(buf, format="PNG")
|
| 978 |
-
extras["__image_bytes"] = buf.getvalue()
|
| 979 |
-
|
| 980 |
-
sink.write(item.key, detections, extras)
|
| 981 |
-
processed += 1
|
| 982 |
-
|
| 983 |
-
duration = datetime.now() - start_time
|
| 984 |
-
processing_time_str = f"{duration.total_seconds() / 60:.2f} min"
|
| 985 |
-
logger.info(
|
| 986 |
-
f"Processed {processed} (skipped {skipped}, errors {errors}) in {processing_time_str}"
|
| 987 |
-
)
|
| 988 |
-
|
| 989 |
-
args_dict = {
|
| 990 |
-
"model_name": args.model_name,
|
| 991 |
-
"threshold": args.threshold,
|
| 992 |
-
"layout_nms": args.layout_nms,
|
| 993 |
-
"shard_size": args.shard_size,
|
| 994 |
-
"processing_time": processing_time_str,
|
| 995 |
-
}
|
| 996 |
-
sink.finalize(model_id=f"PaddlePaddle/{args.model_name}", args_dict=args_dict)
|
| 997 |
-
|
| 998 |
-
if args.verbose:
|
| 999 |
-
import importlib.metadata
|
| 1000 |
-
|
| 1001 |
-
logger.info("--- Resolved package versions ---")
|
| 1002 |
-
for pkg in [
|
| 1003 |
-
"paddlepaddle",
|
| 1004 |
-
"paddlepaddle-gpu",
|
| 1005 |
-
"paddleocr",
|
| 1006 |
-
"huggingface-hub",
|
| 1007 |
-
"datasets",
|
| 1008 |
-
"pyarrow",
|
| 1009 |
-
"pillow",
|
| 1010 |
-
"numpy",
|
| 1011 |
-
]:
|
| 1012 |
-
try:
|
| 1013 |
-
logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
|
| 1014 |
-
except importlib.metadata.PackageNotFoundError:
|
| 1015 |
-
logger.info(f" {pkg}: not installed")
|
| 1016 |
-
logger.info("--- End versions ---")
|
| 1017 |
-
|
| 1018 |
-
|
| 1019 |
-
# ---------------------------------------------------------------------------
|
| 1020 |
-
# CLI
|
| 1021 |
-
# ---------------------------------------------------------------------------
|
| 1022 |
-
|
| 1023 |
-
|
| 1024 |
-
def _print_usage_banner() -> None:
|
| 1025 |
-
print("=" * 80)
|
| 1026 |
-
print("PP-DocLayout layout detection")
|
| 1027 |
-
print("=" * 80)
|
| 1028 |
-
print(
|
| 1029 |
-
"\nDetect document layout regions (text/title/table/figure/formula/...)"
|
| 1030 |
-
)
|
| 1031 |
-
print("with PaddleOCR's PP-DocLayout-L (or M / S / plus-L variant).")
|
| 1032 |
-
print("\nModels:")
|
| 1033 |
-
for m in VALID_MODELS:
|
| 1034 |
-
print(f" {m:24s} {MODEL_SIZES.get(m, '')}")
|
| 1035 |
-
print("\nSources:")
|
| 1036 |
-
print(" - HF dataset repo: namespace/dataset")
|
| 1037 |
-
print(" - HF bucket of images: hf://buckets/namespace/bucket[/prefix]")
|
| 1038 |
-
print("\nSinks:")
|
| 1039 |
-
print(" - HF dataset repo (one push + dataset card):")
|
| 1040 |
-
print(" namespace/dataset")
|
| 1041 |
-
print(" - HF bucket (incremental shards, resumable):")
|
| 1042 |
-
print(" hf://buckets/namespace/bucket/run-name")
|
| 1043 |
-
print("\nExamples:")
|
| 1044 |
-
print("\n # Smoke test on L4 (dataset -> dataset)")
|
| 1045 |
-
print(" hf jobs uv run --flavor l4x1 -s HF_TOKEN https://huggingface.co/datasets/uv-scripts/ocr/raw/main/pp-doclayout.py \\")
|
| 1046 |
-
print(" davanstrien/ufo-ColPali pp-doclayout-smoke \\")
|
| 1047 |
-
print(" --max-samples 3 --shuffle --seed 42 --private")
|
| 1048 |
-
print("\n # Dataset -> bucket (incremental shards)")
|
| 1049 |
-
print(
|
| 1050 |
-
" hf jobs uv run --flavor l4x1 -s HF_TOKEN https://huggingface.co/datasets/uv-scripts/ocr/raw/main/pp-doclayout.py \\"
|
| 1051 |
-
)
|
| 1052 |
-
print(" davanstrien/ufo-ColPali \\")
|
| 1053 |
-
print(
|
| 1054 |
-
" hf://buckets/davanstrien/pp-doclayout-scratch/run1 \\"
|
| 1055 |
-
)
|
| 1056 |
-
print(" --max-samples 20 --shard-size 5")
|
| 1057 |
-
print("\n # Bucket of images -> dataset")
|
| 1058 |
-
print(
|
| 1059 |
-
" hf jobs uv run --flavor l4x1 -s HF_TOKEN https://huggingface.co/datasets/uv-scripts/ocr/raw/main/pp-doclayout.py \\"
|
| 1060 |
-
)
|
| 1061 |
-
print(
|
| 1062 |
-
" hf://buckets/davanstrien/pp-doclayout-images \\"
|
| 1063 |
-
)
|
| 1064 |
-
print(" pp-doclayout-from-bucket --private")
|
| 1065 |
-
print("\nFor full help, run: uv run pp-doclayout.py --help")
|
| 1066 |
-
print("=" * 80)
|
| 1067 |
-
|
| 1068 |
-
|
| 1069 |
-
def build_parser() -> argparse.ArgumentParser:
|
| 1070 |
-
p = argparse.ArgumentParser(
|
| 1071 |
-
description="PP-DocLayout layout detection over an HF dataset or bucket.",
|
| 1072 |
-
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 1073 |
-
)
|
| 1074 |
-
p.add_argument(
|
| 1075 |
-
"input_source",
|
| 1076 |
-
help="HF dataset id (namespace/dataset) OR hf://buckets/ns/bucket[/prefix]",
|
| 1077 |
-
)
|
| 1078 |
-
p.add_argument(
|
| 1079 |
-
"output_target",
|
| 1080 |
-
help="HF dataset id (namespace/dataset) OR hf://buckets/ns/bucket/run-name",
|
| 1081 |
-
)
|
| 1082 |
-
p.add_argument(
|
| 1083 |
-
"--model-name",
|
| 1084 |
-
default="PP-DocLayout-L",
|
| 1085 |
-
choices=VALID_MODELS,
|
| 1086 |
-
help="PaddleOCR layout model variant (default: PP-DocLayout-L)",
|
| 1087 |
-
)
|
| 1088 |
-
p.add_argument(
|
| 1089 |
-
"--device",
|
| 1090 |
-
default="gpu",
|
| 1091 |
-
choices=["gpu", "cpu"],
|
| 1092 |
-
help="Device for inference (default: gpu, falls back to cpu if CUDA missing)",
|
| 1093 |
-
)
|
| 1094 |
-
p.add_argument(
|
| 1095 |
-
"--batch-size",
|
| 1096 |
-
type=int,
|
| 1097 |
-
default=1,
|
| 1098 |
-
help="Per-image batch size passed to model.predict (default: 1)",
|
| 1099 |
-
)
|
| 1100 |
-
p.add_argument(
|
| 1101 |
-
"--threshold",
|
| 1102 |
-
type=float,
|
| 1103 |
-
default=0.5,
|
| 1104 |
-
help="Drop detections below this confidence (default: 0.5; 0 disables)",
|
| 1105 |
-
)
|
| 1106 |
-
p.add_argument(
|
| 1107 |
-
"--layout-nms",
|
| 1108 |
-
dest="layout_nms",
|
| 1109 |
-
action="store_true",
|
| 1110 |
-
default=True,
|
| 1111 |
-
help="Enable layout NMS (default: on)",
|
| 1112 |
-
)
|
| 1113 |
-
p.add_argument(
|
| 1114 |
-
"--no-layout-nms",
|
| 1115 |
-
dest="layout_nms",
|
| 1116 |
-
action="store_false",
|
| 1117 |
-
help="Disable layout NMS",
|
| 1118 |
-
)
|
| 1119 |
-
# Dataset-source-specific
|
| 1120 |
-
p.add_argument(
|
| 1121 |
-
"--image-column",
|
| 1122 |
-
default="image",
|
| 1123 |
-
help="Column containing images (dataset-repo source only, default: image)",
|
| 1124 |
-
)
|
| 1125 |
-
p.add_argument(
|
| 1126 |
-
"--split",
|
| 1127 |
-
default="train",
|
| 1128 |
-
help="Dataset split (dataset-repo source only, default: train)",
|
| 1129 |
-
)
|
| 1130 |
-
p.add_argument(
|
| 1131 |
-
"--max-samples", type=int, help="Limit number of samples (for testing)"
|
| 1132 |
-
)
|
| 1133 |
-
p.add_argument(
|
| 1134 |
-
"--shuffle", action="store_true", help="Shuffle source before processing"
|
| 1135 |
-
)
|
| 1136 |
-
p.add_argument(
|
| 1137 |
-
"--seed", type=int, default=42, help="Random seed for shuffle (default: 42)"
|
| 1138 |
-
)
|
| 1139 |
-
# Dataset-sink-specific
|
| 1140 |
-
p.add_argument(
|
| 1141 |
-
"--private", action="store_true", help="Private dataset output (dataset sink only)"
|
| 1142 |
-
)
|
| 1143 |
-
p.add_argument(
|
| 1144 |
-
"--config",
|
| 1145 |
-
help="Config/subset name when pushing to Hub (dataset sink only)",
|
| 1146 |
-
)
|
| 1147 |
-
p.add_argument(
|
| 1148 |
-
"--create-pr",
|
| 1149 |
-
action="store_true",
|
| 1150 |
-
help="Create PR instead of direct push (dataset sink only)",
|
| 1151 |
-
)
|
| 1152 |
-
# Bucket-sink-specific
|
| 1153 |
-
p.add_argument(
|
| 1154 |
-
"--shard-size",
|
| 1155 |
-
type=int,
|
| 1156 |
-
default=256,
|
| 1157 |
-
help="Rows per parquet shard for bucket sink (default: 256)",
|
| 1158 |
-
)
|
| 1159 |
-
p.add_argument(
|
| 1160 |
-
"--include-images",
|
| 1161 |
-
action="store_true",
|
| 1162 |
-
help="Embed source image bytes in bucket output shards (off by default)",
|
| 1163 |
-
)
|
| 1164 |
-
p.add_argument(
|
| 1165 |
-
"--no-resume",
|
| 1166 |
-
action="store_true",
|
| 1167 |
-
help="Disable resume scan when writing to a bucket sink",
|
| 1168 |
-
)
|
| 1169 |
-
# Auth + diagnostics
|
| 1170 |
-
p.add_argument("--hf-token", help="Hugging Face API token (else uses HF_TOKEN env)")
|
| 1171 |
-
p.add_argument(
|
| 1172 |
-
"--verbose",
|
| 1173 |
-
action="store_true",
|
| 1174 |
-
help="Log resolved package versions at the end",
|
| 1175 |
-
)
|
| 1176 |
-
return p
|
| 1177 |
-
|
| 1178 |
-
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
qianfan-ocr.py
DELETED
|
@@ -1,632 +0,0 @@
|
|
| 1 |
-
# /// script
|
| 2 |
-
# requires-python = ">=3.11"
|
| 3 |
-
# dependencies = [
|
| 4 |
-
# "datasets>=4.0.0",
|
| 5 |
-
# "huggingface-hub",
|
| 6 |
-
# "pillow",
|
| 7 |
-
# "vllm>=0.15.1",
|
| 8 |
-
# "tqdm",
|
| 9 |
-
# "toolz",
|
| 10 |
-
# "torch",
|
| 11 |
-
# ]
|
| 12 |
-
# ///
|
| 13 |
-
|
| 14 |
-
"""
|
| 15 |
-
Convert document images to markdown using Qianfan-OCR with vLLM.
|
| 16 |
-
|
| 17 |
-
Qianfan-OCR is a 4.7B end-to-end document intelligence model from Baidu,
|
| 18 |
-
built on InternVL architecture with Qianfan-ViT encoder + Qwen3-4B LLM.
|
| 19 |
-
|
| 20 |
-
Features:
|
| 21 |
-
- #1 end-to-end model on OmniDocBench v1.5 (93.12) and OlmOCR Bench (79.8)
|
| 22 |
-
- Layout-as-Thought: optional reasoning phase for complex layouts via --think
|
| 23 |
-
- 192 language support (Latin, CJK, Arabic, Cyrillic, and more)
|
| 24 |
-
- Multiple task modes: OCR, table (HTML), formula (LaTeX), chart, scene text
|
| 25 |
-
- Key information extraction with custom prompts
|
| 26 |
-
- 1.024 PPS on A100 with W8A8 quantization
|
| 27 |
-
|
| 28 |
-
Model: baidu/Qianfan-OCR
|
| 29 |
-
License: Apache 2.0
|
| 30 |
-
Paper: https://arxiv.org/abs/2603.13398
|
| 31 |
-
"""
|
| 32 |
-
|
| 33 |
-
import argparse
|
| 34 |
-
import base64
|
| 35 |
-
import io
|
| 36 |
-
import json
|
| 37 |
-
import logging
|
| 38 |
-
import os
|
| 39 |
-
import sys
|
| 40 |
-
import time
|
| 41 |
-
from datetime import datetime
|
| 42 |
-
from typing import Any, Dict, List, Union
|
| 43 |
-
|
| 44 |
-
import torch
|
| 45 |
-
from datasets import load_dataset
|
| 46 |
-
from huggingface_hub import DatasetCard, login
|
| 47 |
-
from PIL import Image
|
| 48 |
-
from toolz import partition_all
|
| 49 |
-
from tqdm.auto import tqdm
|
| 50 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 51 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 52 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 53 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 54 |
-
from vllm import LLM, SamplingParams
|
| 55 |
-
|
| 56 |
-
logging.basicConfig(level=logging.INFO)
|
| 57 |
-
logger = logging.getLogger(__name__)
|
| 58 |
-
|
| 59 |
-
MODEL = "baidu/Qianfan-OCR"
|
| 60 |
-
|
| 61 |
-
PROMPT_TEMPLATES = {
|
| 62 |
-
"ocr": "Parse this document to Markdown.",
|
| 63 |
-
"table": "Extract tables to HTML format.",
|
| 64 |
-
"formula": "Extract formulas to LaTeX.",
|
| 65 |
-
"chart": "What trends are shown in this chart?",
|
| 66 |
-
"scene": "Extract all visible text from the image.",
|
| 67 |
-
"kie": None, # requires --custom-prompt
|
| 68 |
-
}
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
def check_cuda_availability():
|
| 72 |
-
"""Check if CUDA is available and exit if not."""
|
| 73 |
-
if not torch.cuda.is_available():
|
| 74 |
-
logger.error("CUDA is not available. This script requires a GPU.")
|
| 75 |
-
sys.exit(1)
|
| 76 |
-
else:
|
| 77 |
-
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
def extract_content_from_thinking(text: str, include_thinking: bool = False) -> str:
|
| 81 |
-
"""
|
| 82 |
-
Extract final content from Qianfan-OCR's Layout-as-Thought output.
|
| 83 |
-
|
| 84 |
-
When --think is enabled, the model generates layout analysis inside
|
| 85 |
-
<think>...</think> tags before the final markdown output.
|
| 86 |
-
"""
|
| 87 |
-
if include_thinking:
|
| 88 |
-
return text.strip()
|
| 89 |
-
|
| 90 |
-
# If no thinking tags, return as-is
|
| 91 |
-
if "<think>" not in text:
|
| 92 |
-
return text.strip()
|
| 93 |
-
|
| 94 |
-
# Extract everything after </think>
|
| 95 |
-
think_end = text.find("</think>")
|
| 96 |
-
if think_end != -1:
|
| 97 |
-
return text[think_end + 8 :].strip()
|
| 98 |
-
|
| 99 |
-
# Thinking started but never closed — return full text
|
| 100 |
-
logger.warning("Found <think> but no </think>, returning full text")
|
| 101 |
-
return text.strip()
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
def make_ocr_message(
|
| 105 |
-
image: Union[Image.Image, Dict[str, Any], str],
|
| 106 |
-
prompt: str,
|
| 107 |
-
) -> List[Dict]:
|
| 108 |
-
"""Create vLLM chat message with image and prompt."""
|
| 109 |
-
if isinstance(image, Image.Image):
|
| 110 |
-
pil_img = image
|
| 111 |
-
elif isinstance(image, dict) and "bytes" in image:
|
| 112 |
-
pil_img = Image.open(io.BytesIO(image["bytes"]))
|
| 113 |
-
elif isinstance(image, str):
|
| 114 |
-
pil_img = Image.open(image)
|
| 115 |
-
else:
|
| 116 |
-
raise ValueError(f"Unsupported image type: {type(image)}")
|
| 117 |
-
|
| 118 |
-
pil_img = pil_img.convert("RGB")
|
| 119 |
-
|
| 120 |
-
buf = io.BytesIO()
|
| 121 |
-
pil_img.save(buf, format="PNG")
|
| 122 |
-
data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
|
| 123 |
-
|
| 124 |
-
return [
|
| 125 |
-
{
|
| 126 |
-
"role": "user",
|
| 127 |
-
"content": [
|
| 128 |
-
{"type": "image_url", "image_url": {"url": data_uri}},
|
| 129 |
-
{"type": "text", "text": prompt},
|
| 130 |
-
],
|
| 131 |
-
}
|
| 132 |
-
]
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
def create_dataset_card(
|
| 136 |
-
source_dataset: str,
|
| 137 |
-
model: str,
|
| 138 |
-
num_samples: int,
|
| 139 |
-
processing_time: str,
|
| 140 |
-
batch_size: int,
|
| 141 |
-
max_model_len: int,
|
| 142 |
-
max_tokens: int,
|
| 143 |
-
gpu_memory_utilization: float,
|
| 144 |
-
prompt_mode: str,
|
| 145 |
-
think: bool,
|
| 146 |
-
include_thinking: bool,
|
| 147 |
-
image_column: str = "image",
|
| 148 |
-
split: str = "train",
|
| 149 |
-
) -> str:
|
| 150 |
-
"""Create a dataset card documenting the OCR process."""
|
| 151 |
-
model_name = model.split("/")[-1]
|
| 152 |
-
|
| 153 |
-
return f"""---
|
| 154 |
-
tags:
|
| 155 |
-
- ocr
|
| 156 |
-
- document-processing
|
| 157 |
-
- qianfan-ocr
|
| 158 |
-
- markdown
|
| 159 |
-
- uv-script
|
| 160 |
-
- generated
|
| 161 |
-
---
|
| 162 |
-
|
| 163 |
-
# Document OCR using {model_name}
|
| 164 |
-
|
| 165 |
-
This dataset contains OCR results from [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using Qianfan-OCR, Baidu's 4.7B end-to-end document intelligence model.
|
| 166 |
-
|
| 167 |
-
## Processing Details
|
| 168 |
-
|
| 169 |
-
- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
|
| 170 |
-
- **Model**: [{model}](https://huggingface.co/{model})
|
| 171 |
-
- **Number of Samples**: {num_samples:,}
|
| 172 |
-
- **Processing Time**: {processing_time}
|
| 173 |
-
- **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
|
| 174 |
-
|
| 175 |
-
### Configuration
|
| 176 |
-
|
| 177 |
-
- **Image Column**: `{image_column}`
|
| 178 |
-
- **Output Column**: `markdown`
|
| 179 |
-
- **Dataset Split**: `{split}`
|
| 180 |
-
- **Batch Size**: {batch_size}
|
| 181 |
-
- **Prompt Mode**: {prompt_mode}
|
| 182 |
-
- **Layout-as-Thought**: {"Enabled" if think else "Disabled"}
|
| 183 |
-
- **Thinking Traces**: {"Included" if include_thinking else "Excluded"}
|
| 184 |
-
- **Max Model Length**: {max_model_len:,} tokens
|
| 185 |
-
- **Max Output Tokens**: {max_tokens:,}
|
| 186 |
-
- **GPU Memory Utilization**: {gpu_memory_utilization:.1%}
|
| 187 |
-
|
| 188 |
-
## Model Information
|
| 189 |
-
|
| 190 |
-
Qianfan-OCR key capabilities:
|
| 191 |
-
- #1 end-to-end model on OmniDocBench v1.5 (93.12)
|
| 192 |
-
- #1 on OlmOCR Bench (79.8)
|
| 193 |
-
- 192 language support
|
| 194 |
-
- Layout-as-Thought reasoning for complex documents
|
| 195 |
-
- Document parsing, table extraction, formula recognition, chart understanding
|
| 196 |
-
- Key information extraction
|
| 197 |
-
|
| 198 |
-
## Dataset Structure
|
| 199 |
-
|
| 200 |
-
The dataset contains all original columns plus:
|
| 201 |
-
- `markdown`: The extracted text in markdown format
|
| 202 |
-
- `inference_info`: JSON list tracking all OCR models applied
|
| 203 |
-
|
| 204 |
-
## Reproduction
|
| 205 |
-
|
| 206 |
-
```bash
|
| 207 |
-
uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/qianfan-ocr.py \\
|
| 208 |
-
{source_dataset} \\
|
| 209 |
-
<output-dataset> \\
|
| 210 |
-
--image-column {image_column} \\
|
| 211 |
-
--prompt-mode {prompt_mode} \\
|
| 212 |
-
--batch-size {batch_size}{" --think" if think else ""}
|
| 213 |
-
```
|
| 214 |
-
|
| 215 |
-
Generated with [UV Scripts](https://huggingface.co/uv-scripts)
|
| 216 |
-
"""
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
def main(
|
| 220 |
-
input_dataset: str,
|
| 221 |
-
output_dataset: str,
|
| 222 |
-
image_column: str = "image",
|
| 223 |
-
batch_size: int = 8,
|
| 224 |
-
max_model_len: int = 16384,
|
| 225 |
-
max_tokens: int = 8192,
|
| 226 |
-
temperature: float = 0.0,
|
| 227 |
-
top_p: float = 1.0,
|
| 228 |
-
gpu_memory_utilization: float = 0.85,
|
| 229 |
-
hf_token: str = None,
|
| 230 |
-
split: str = "train",
|
| 231 |
-
max_samples: int = None,
|
| 232 |
-
private: bool = False,
|
| 233 |
-
shuffle: bool = False,
|
| 234 |
-
seed: int = 42,
|
| 235 |
-
prompt_mode: str = "ocr",
|
| 236 |
-
think: bool = False,
|
| 237 |
-
include_thinking: bool = False,
|
| 238 |
-
custom_prompt: str = None,
|
| 239 |
-
output_column: str = "markdown",
|
| 240 |
-
config: str = None,
|
| 241 |
-
create_pr: bool = False,
|
| 242 |
-
verbose: bool = False,
|
| 243 |
-
):
|
| 244 |
-
"""Process images from HF dataset through Qianfan-OCR model."""
|
| 245 |
-
|
| 246 |
-
check_cuda_availability()
|
| 247 |
-
start_time = datetime.now()
|
| 248 |
-
|
| 249 |
-
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
|
| 250 |
-
if HF_TOKEN:
|
| 251 |
-
login(token=HF_TOKEN)
|
| 252 |
-
|
| 253 |
-
# Build prompt
|
| 254 |
-
if custom_prompt:
|
| 255 |
-
prompt = custom_prompt
|
| 256 |
-
logger.info(f"Using custom prompt: {prompt[:80]}...")
|
| 257 |
-
else:
|
| 258 |
-
if prompt_mode == "kie":
|
| 259 |
-
logger.error("--prompt-mode kie requires --custom-prompt")
|
| 260 |
-
sys.exit(1)
|
| 261 |
-
prompt = PROMPT_TEMPLATES[prompt_mode]
|
| 262 |
-
logger.info(f"Using prompt mode: {prompt_mode}")
|
| 263 |
-
|
| 264 |
-
if think:
|
| 265 |
-
prompt = prompt + "<think>"
|
| 266 |
-
logger.info("Layout-as-Thought enabled (appending <think> to prompt)")
|
| 267 |
-
|
| 268 |
-
logger.info(f"Using model: {MODEL}")
|
| 269 |
-
|
| 270 |
-
# Load dataset
|
| 271 |
-
logger.info(f"Loading dataset: {input_dataset}")
|
| 272 |
-
dataset = load_dataset(input_dataset, split=split)
|
| 273 |
-
|
| 274 |
-
if image_column not in dataset.column_names:
|
| 275 |
-
raise ValueError(
|
| 276 |
-
f"Column '{image_column}' not found. Available: {dataset.column_names}"
|
| 277 |
-
)
|
| 278 |
-
|
| 279 |
-
if shuffle:
|
| 280 |
-
logger.info(f"Shuffling dataset with seed {seed}")
|
| 281 |
-
dataset = dataset.shuffle(seed=seed)
|
| 282 |
-
|
| 283 |
-
if max_samples:
|
| 284 |
-
dataset = dataset.select(range(min(max_samples, len(dataset))))
|
| 285 |
-
logger.info(f"Limited to {len(dataset)} samples")
|
| 286 |
-
|
| 287 |
-
# Initialize vLLM
|
| 288 |
-
logger.info("Initializing vLLM with Qianfan-OCR")
|
| 289 |
-
logger.info("This may take a few minutes on first run...")
|
| 290 |
-
llm = LLM(
|
| 291 |
-
model=MODEL,
|
| 292 |
-
trust_remote_code=True,
|
| 293 |
-
max_model_len=max_model_len,
|
| 294 |
-
gpu_memory_utilization=gpu_memory_utilization,
|
| 295 |
-
limit_mm_per_prompt={"image": 1},
|
| 296 |
-
enforce_eager=False,
|
| 297 |
-
)
|
| 298 |
-
|
| 299 |
-
sampling_params = SamplingParams(
|
| 300 |
-
temperature=temperature,
|
| 301 |
-
top_p=top_p,
|
| 302 |
-
max_tokens=max_tokens,
|
| 303 |
-
)
|
| 304 |
-
|
| 305 |
-
logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
|
| 306 |
-
logger.info(f"Output will be written to column: {output_column}")
|
| 307 |
-
|
| 308 |
-
# Process images in batches
|
| 309 |
-
all_outputs = []
|
| 310 |
-
|
| 311 |
-
for batch_indices in tqdm(
|
| 312 |
-
partition_all(batch_size, range(len(dataset))),
|
| 313 |
-
total=(len(dataset) + batch_size - 1) // batch_size,
|
| 314 |
-
desc="Qianfan-OCR processing",
|
| 315 |
-
):
|
| 316 |
-
batch_indices = list(batch_indices)
|
| 317 |
-
batch_images = [dataset[i][image_column] for i in batch_indices]
|
| 318 |
-
|
| 319 |
-
try:
|
| 320 |
-
batch_messages = [make_ocr_message(img, prompt) for img in batch_images]
|
| 321 |
-
outputs = llm.chat(batch_messages, sampling_params)
|
| 322 |
-
|
| 323 |
-
for output in outputs:
|
| 324 |
-
text = output.outputs[0].text.strip()
|
| 325 |
-
if think:
|
| 326 |
-
text = extract_content_from_thinking(text, include_thinking)
|
| 327 |
-
all_outputs.append(text)
|
| 328 |
-
|
| 329 |
-
except Exception as e:
|
| 330 |
-
logger.error(f"Error processing batch: {e}")
|
| 331 |
-
all_outputs.extend(["[OCR ERROR]"] * len(batch_images))
|
| 332 |
-
|
| 333 |
-
# Calculate processing time
|
| 334 |
-
processing_duration = datetime.now() - start_time
|
| 335 |
-
processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
|
| 336 |
-
|
| 337 |
-
# Add output column
|
| 338 |
-
logger.info(f"Adding '{output_column}' column to dataset")
|
| 339 |
-
dataset = dataset.add_column(output_column, all_outputs)
|
| 340 |
-
|
| 341 |
-
# Handle inference_info tracking
|
| 342 |
-
inference_entry = {
|
| 343 |
-
"model_id": MODEL,
|
| 344 |
-
"model_name": "Qianfan-OCR",
|
| 345 |
-
"column_name": output_column,
|
| 346 |
-
"timestamp": datetime.now().isoformat(),
|
| 347 |
-
"prompt_mode": prompt_mode if not custom_prompt else "custom",
|
| 348 |
-
"think": think,
|
| 349 |
-
"temperature": temperature,
|
| 350 |
-
"max_tokens": max_tokens,
|
| 351 |
-
}
|
| 352 |
-
|
| 353 |
-
if "inference_info" in dataset.column_names:
|
| 354 |
-
logger.info("Updating existing inference_info column")
|
| 355 |
-
|
| 356 |
-
def update_inference_info(example):
|
| 357 |
-
try:
|
| 358 |
-
existing_info = (
|
| 359 |
-
json.loads(example["inference_info"])
|
| 360 |
-
if example["inference_info"]
|
| 361 |
-
else []
|
| 362 |
-
)
|
| 363 |
-
except (json.JSONDecodeError, TypeError):
|
| 364 |
-
existing_info = []
|
| 365 |
-
existing_info.append(inference_entry)
|
| 366 |
-
return {"inference_info": json.dumps(existing_info)}
|
| 367 |
-
|
| 368 |
-
dataset = dataset.map(update_inference_info)
|
| 369 |
-
else:
|
| 370 |
-
logger.info("Creating new inference_info column")
|
| 371 |
-
inference_list = [json.dumps([inference_entry])] * len(dataset)
|
| 372 |
-
dataset = dataset.add_column("inference_info", inference_list)
|
| 373 |
-
|
| 374 |
-
# Push to hub with retry and XET fallback
|
| 375 |
-
logger.info(f"Pushing to {output_dataset}")
|
| 376 |
-
commit_msg = f"Add Qianfan-OCR results ({len(dataset)} samples)" + (
|
| 377 |
-
f" [{config}]" if config else ""
|
| 378 |
-
)
|
| 379 |
-
max_retries = 3
|
| 380 |
-
for attempt in range(1, max_retries + 1):
|
| 381 |
-
try:
|
| 382 |
-
if attempt > 1:
|
| 383 |
-
logger.warning("Disabling XET (fallback to HTTP upload)")
|
| 384 |
-
os.environ["HF_HUB_DISABLE_XET"] = "1"
|
| 385 |
-
dataset.push_to_hub(
|
| 386 |
-
output_dataset,
|
| 387 |
-
private=private,
|
| 388 |
-
token=HF_TOKEN,
|
| 389 |
-
max_shard_size="500MB",
|
| 390 |
-
**({"config_name": config} if config else {}),
|
| 391 |
-
create_pr=create_pr,
|
| 392 |
-
commit_message=commit_msg,
|
| 393 |
-
)
|
| 394 |
-
break
|
| 395 |
-
except Exception as e:
|
| 396 |
-
logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
|
| 397 |
-
if attempt < max_retries:
|
| 398 |
-
delay = 30 * (2 ** (attempt - 1))
|
| 399 |
-
logger.info(f"Retrying in {delay}s...")
|
| 400 |
-
time.sleep(delay)
|
| 401 |
-
else:
|
| 402 |
-
logger.error("All upload attempts failed. OCR results are lost.")
|
| 403 |
-
sys.exit(1)
|
| 404 |
-
|
| 405 |
-
# Create and push dataset card (skip when creating PR to avoid conflicts)
|
| 406 |
-
if not create_pr:
|
| 407 |
-
logger.info("Creating dataset card")
|
| 408 |
-
card_content = create_dataset_card(
|
| 409 |
-
source_dataset=input_dataset,
|
| 410 |
-
model=MODEL,
|
| 411 |
-
num_samples=len(dataset),
|
| 412 |
-
processing_time=processing_time_str,
|
| 413 |
-
batch_size=batch_size,
|
| 414 |
-
max_model_len=max_model_len,
|
| 415 |
-
max_tokens=max_tokens,
|
| 416 |
-
gpu_memory_utilization=gpu_memory_utilization,
|
| 417 |
-
prompt_mode=prompt_mode if not custom_prompt else "custom",
|
| 418 |
-
think=think,
|
| 419 |
-
include_thinking=include_thinking,
|
| 420 |
-
image_column=image_column,
|
| 421 |
-
split=split,
|
| 422 |
-
)
|
| 423 |
-
card = DatasetCard(card_content)
|
| 424 |
-
card.push_to_hub(output_dataset, token=HF_TOKEN)
|
| 425 |
-
|
| 426 |
-
logger.info("Qianfan-OCR processing complete!")
|
| 427 |
-
logger.info(
|
| 428 |
-
f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
|
| 429 |
-
)
|
| 430 |
-
logger.info(f"Processing time: {processing_time_str}")
|
| 431 |
-
logger.info(
|
| 432 |
-
f"Processing speed: {len(dataset) / processing_duration.total_seconds():.2f} images/sec"
|
| 433 |
-
)
|
| 434 |
-
|
| 435 |
-
if verbose:
|
| 436 |
-
import importlib.metadata
|
| 437 |
-
|
| 438 |
-
logger.info("--- Resolved package versions ---")
|
| 439 |
-
for pkg in ["vllm", "transformers", "torch", "datasets", "pyarrow", "pillow"]:
|
| 440 |
-
try:
|
| 441 |
-
logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
|
| 442 |
-
except importlib.metadata.PackageNotFoundError:
|
| 443 |
-
logger.info(f" {pkg}: not installed")
|
| 444 |
-
logger.info("--- End versions ---")
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
if __name__ == "__main__":
|
| 448 |
-
if len(sys.argv) == 1:
|
| 449 |
-
print("=" * 80)
|
| 450 |
-
print("Qianfan-OCR - End-to-End Document Intelligence")
|
| 451 |
-
print("=" * 80)
|
| 452 |
-
print("\n4.7B model from Baidu, #1 on OmniDocBench v1.5 (93.12)")
|
| 453 |
-
print("\nFeatures:")
|
| 454 |
-
print("- #1 end-to-end model on OmniDocBench v1.5 and OlmOCR Bench")
|
| 455 |
-
print("- Layout-as-Thought reasoning for complex documents (--think)")
|
| 456 |
-
print("- 192 language support")
|
| 457 |
-
print("- Multiple modes: OCR, table (HTML), formula (LaTeX), chart, scene text")
|
| 458 |
-
print("- Key information extraction with custom prompts")
|
| 459 |
-
print("\nExample usage:")
|
| 460 |
-
print("\n1. Basic OCR:")
|
| 461 |
-
print(" uv run qianfan-ocr.py input-dataset output-dataset")
|
| 462 |
-
print("\n2. With Layout-as-Thought (complex documents):")
|
| 463 |
-
print(" uv run qianfan-ocr.py docs output --think")
|
| 464 |
-
print("\n3. Table extraction:")
|
| 465 |
-
print(" uv run qianfan-ocr.py docs output --prompt-mode table")
|
| 466 |
-
print("\n4. Formula extraction:")
|
| 467 |
-
print(" uv run qianfan-ocr.py docs output --prompt-mode formula")
|
| 468 |
-
print("\n5. Key information extraction:")
|
| 469 |
-
print(
|
| 470 |
-
' uv run qianfan-ocr.py invoices output --prompt-mode kie --custom-prompt "Extract: name, date, total. Output JSON."'
|
| 471 |
-
)
|
| 472 |
-
print("\n6. Running on HF Jobs:")
|
| 473 |
-
print(" hf jobs uv run --flavor l4x1 \\")
|
| 474 |
-
print(" -s HF_TOKEN \\")
|
| 475 |
-
print(
|
| 476 |
-
" https://huggingface.co/datasets/uv-scripts/ocr/raw/main/qianfan-ocr.py \\"
|
| 477 |
-
)
|
| 478 |
-
print(" input-dataset output-dataset --max-samples 10")
|
| 479 |
-
print("\nFor full help, run: uv run qianfan-ocr.py --help")
|
| 480 |
-
sys.exit(0)
|
| 481 |
-
|
| 482 |
-
parser = argparse.ArgumentParser(
|
| 483 |
-
description="Document OCR using Qianfan-OCR (4.7B, #1 on OmniDocBench v1.5)",
|
| 484 |
-
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 485 |
-
epilog="""
|
| 486 |
-
Prompt modes:
|
| 487 |
-
ocr Document parsing to Markdown (default)
|
| 488 |
-
table Table extraction to HTML format
|
| 489 |
-
formula Formula recognition to LaTeX
|
| 490 |
-
chart Chart understanding and analysis
|
| 491 |
-
scene Scene text extraction
|
| 492 |
-
kie Key information extraction (requires --custom-prompt)
|
| 493 |
-
|
| 494 |
-
Examples:
|
| 495 |
-
uv run qianfan-ocr.py my-docs analyzed-docs
|
| 496 |
-
uv run qianfan-ocr.py docs output --think --max-samples 50
|
| 497 |
-
uv run qianfan-ocr.py docs output --prompt-mode table
|
| 498 |
-
uv run qianfan-ocr.py invoices data --prompt-mode kie --custom-prompt "Extract: name, date, total."
|
| 499 |
-
""",
|
| 500 |
-
)
|
| 501 |
-
|
| 502 |
-
parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
|
| 503 |
-
parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
|
| 504 |
-
parser.add_argument(
|
| 505 |
-
"--image-column",
|
| 506 |
-
default="image",
|
| 507 |
-
help="Column containing images (default: image)",
|
| 508 |
-
)
|
| 509 |
-
parser.add_argument(
|
| 510 |
-
"--batch-size",
|
| 511 |
-
type=int,
|
| 512 |
-
default=8,
|
| 513 |
-
help="Batch size for processing (default: 8)",
|
| 514 |
-
)
|
| 515 |
-
parser.add_argument(
|
| 516 |
-
"--max-model-len",
|
| 517 |
-
type=int,
|
| 518 |
-
default=16384,
|
| 519 |
-
help="Maximum model context length (default: 16384, reduce to 8192 if OOM on L4)",
|
| 520 |
-
)
|
| 521 |
-
parser.add_argument(
|
| 522 |
-
"--max-tokens",
|
| 523 |
-
type=int,
|
| 524 |
-
default=8192,
|
| 525 |
-
help="Maximum tokens to generate (default: 8192)",
|
| 526 |
-
)
|
| 527 |
-
parser.add_argument(
|
| 528 |
-
"--temperature",
|
| 529 |
-
type=float,
|
| 530 |
-
default=0.0,
|
| 531 |
-
help="Sampling temperature (default: 0.0, deterministic)",
|
| 532 |
-
)
|
| 533 |
-
parser.add_argument(
|
| 534 |
-
"--top-p",
|
| 535 |
-
type=float,
|
| 536 |
-
default=1.0,
|
| 537 |
-
help="Top-p sampling parameter (default: 1.0)",
|
| 538 |
-
)
|
| 539 |
-
parser.add_argument(
|
| 540 |
-
"--gpu-memory-utilization",
|
| 541 |
-
type=float,
|
| 542 |
-
default=0.85,
|
| 543 |
-
help="GPU memory utilization (default: 0.85)",
|
| 544 |
-
)
|
| 545 |
-
parser.add_argument("--hf-token", help="Hugging Face API token")
|
| 546 |
-
parser.add_argument(
|
| 547 |
-
"--split", default="train", help="Dataset split to use (default: train)"
|
| 548 |
-
)
|
| 549 |
-
parser.add_argument(
|
| 550 |
-
"--max-samples",
|
| 551 |
-
type=int,
|
| 552 |
-
help="Maximum number of samples to process (for testing)",
|
| 553 |
-
)
|
| 554 |
-
parser.add_argument(
|
| 555 |
-
"--private", action="store_true", help="Make output dataset private"
|
| 556 |
-
)
|
| 557 |
-
parser.add_argument(
|
| 558 |
-
"--shuffle", action="store_true", help="Shuffle dataset before processing"
|
| 559 |
-
)
|
| 560 |
-
parser.add_argument(
|
| 561 |
-
"--seed",
|
| 562 |
-
type=int,
|
| 563 |
-
default=42,
|
| 564 |
-
help="Random seed for shuffling (default: 42)",
|
| 565 |
-
)
|
| 566 |
-
parser.add_argument(
|
| 567 |
-
"--prompt-mode",
|
| 568 |
-
choices=list(PROMPT_TEMPLATES.keys()),
|
| 569 |
-
default="ocr",
|
| 570 |
-
help="Prompt mode (default: ocr)",
|
| 571 |
-
)
|
| 572 |
-
parser.add_argument(
|
| 573 |
-
"--think",
|
| 574 |
-
action="store_true",
|
| 575 |
-
help="Enable Layout-as-Thought reasoning (appends <think> to prompt)",
|
| 576 |
-
)
|
| 577 |
-
parser.add_argument(
|
| 578 |
-
"--include-thinking",
|
| 579 |
-
action="store_true",
|
| 580 |
-
help="Include thinking traces in output (default: only final content)",
|
| 581 |
-
)
|
| 582 |
-
parser.add_argument(
|
| 583 |
-
"--custom-prompt",
|
| 584 |
-
help="Custom prompt text (overrides --prompt-mode)",
|
| 585 |
-
)
|
| 586 |
-
parser.add_argument(
|
| 587 |
-
"--output-column",
|
| 588 |
-
default="markdown",
|
| 589 |
-
help="Column name for output text (default: markdown)",
|
| 590 |
-
)
|
| 591 |
-
parser.add_argument(
|
| 592 |
-
"--config",
|
| 593 |
-
help="Config/subset name when pushing to Hub (for benchmarking multiple models)",
|
| 594 |
-
)
|
| 595 |
-
parser.add_argument(
|
| 596 |
-
"--create-pr",
|
| 597 |
-
action="store_true",
|
| 598 |
-
help="Create a pull request instead of pushing directly",
|
| 599 |
-
)
|
| 600 |
-
parser.add_argument(
|
| 601 |
-
"--verbose",
|
| 602 |
-
action="store_true",
|
| 603 |
-
help="Log resolved package versions after processing",
|
| 604 |
-
)
|
| 605 |
-
|
| 606 |
-
args = parser.parse_args()
|
| 607 |
-
|
| 608 |
-
main(
|
| 609 |
-
input_dataset=args.input_dataset,
|
| 610 |
-
output_dataset=args.output_dataset,
|
| 611 |
-
image_column=args.image_column,
|
| 612 |
-
batch_size=args.batch_size,
|
| 613 |
-
max_model_len=args.max_model_len,
|
| 614 |
-
max_tokens=args.max_tokens,
|
| 615 |
-
temperature=args.temperature,
|
| 616 |
-
top_p=args.top_p,
|
| 617 |
-
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 618 |
-
hf_token=args.hf_token,
|
| 619 |
-
split=args.split,
|
| 620 |
-
max_samples=args.max_samples,
|
| 621 |
-
private=args.private,
|
| 622 |
-
shuffle=args.shuffle,
|
| 623 |
-
seed=args.seed,
|
| 624 |
-
prompt_mode=args.prompt_mode,
|
| 625 |
-
think=args.think,
|
| 626 |
-
include_thinking=args.include_thinking,
|
| 627 |
-
custom_prompt=args.custom_prompt,
|
| 628 |
-
output_column=args.output_column,
|
| 629 |
-
config=args.config,
|
| 630 |
-
create_pr=args.create_pr,
|
| 631 |
-
verbose=args.verbose,
|
| 632 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
rolm-ocr.py
CHANGED
|
@@ -40,10 +40,6 @@ from huggingface_hub import DatasetCard, login
|
|
| 40 |
from PIL import Image
|
| 41 |
from toolz import partition_all
|
| 42 |
from tqdm.auto import tqdm
|
| 43 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 44 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 45 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 46 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 47 |
from vllm import LLM, SamplingParams
|
| 48 |
from datetime import datetime
|
| 49 |
|
|
|
|
| 40 |
from PIL import Image
|
| 41 |
from toolz import partition_all
|
| 42 |
from tqdm.auto import tqdm
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
from vllm import LLM, SamplingParams
|
| 44 |
from datetime import datetime
|
| 45 |
|
smoldocling-ocr.py
CHANGED
|
@@ -42,13 +42,9 @@ from typing import Any, Dict, Union
|
|
| 42 |
import torch
|
| 43 |
from datasets import load_dataset
|
| 44 |
from huggingface_hub import DatasetCard, login
|
| 45 |
-
from PIL import Image
|
| 46 |
from toolz import partition_all
|
| 47 |
from tqdm.auto import tqdm
|
| 48 |
-
# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
|
| 49 |
-
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 50 |
-
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 51 |
-
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 52 |
from vllm import LLM, SamplingParams
|
| 53 |
|
| 54 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -303,21 +299,7 @@ def main(
|
|
| 303 |
desc="OCR processing",
|
| 304 |
):
|
| 305 |
batch_indices = list(batch_indices)
|
| 306 |
-
|
| 307 |
-
# Fetch images first, with per-batch fallback for unreadable files.
|
| 308 |
-
# One corrupt image used to take down the entire run via the list
|
| 309 |
-
# comprehension; now we mark the whole batch as skipped and continue.
|
| 310 |
-
try:
|
| 311 |
-
batch_images = [dataset[i][image_column] for i in batch_indices]
|
| 312 |
-
except (UnidentifiedImageError, OSError) as e:
|
| 313 |
-
logger.warning(
|
| 314 |
-
f"Skipping batch of {len(batch_indices)} — unreadable image "
|
| 315 |
-
f"in batch: {type(e).__name__}: {e}"
|
| 316 |
-
)
|
| 317 |
-
all_output.extend(
|
| 318 |
-
["[OCR SKIPPED — UNREADABLE IMAGE]"] * len(batch_indices)
|
| 319 |
-
)
|
| 320 |
-
continue
|
| 321 |
|
| 322 |
try:
|
| 323 |
# Prepare inputs for batch
|
|
|
|
| 42 |
import torch
|
| 43 |
from datasets import load_dataset
|
| 44 |
from huggingface_hub import DatasetCard, login
|
| 45 |
+
from PIL import Image
|
| 46 |
from toolz import partition_all
|
| 47 |
from tqdm.auto import tqdm
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
from vllm import LLM, SamplingParams
|
| 49 |
|
| 50 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 299 |
desc="OCR processing",
|
| 300 |
):
|
| 301 |
batch_indices = list(batch_indices)
|
| 302 |
+
batch_images = [dataset[i][image_column] for i in batch_indices]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
|
| 304 |
try:
|
| 305 |
# Prepare inputs for batch
|