I need pull
#6
by visssoftjsc - opened
- AGENTS.md +0 -92
- CLAUDE.md +79 -600
- README.md +528 -155
- abot-ocr.py +0 -560
- deepseek-ocr-vllm.py +0 -4
- deepseek-ocr.py +3 -2
- deepseek-ocr2-vllm.py +0 -4
- demo.gif +0 -3
- 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
- lift-extract.py +0 -812
- 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 -1197
- pp-ocrv6.py +0 -1041
- qianfan-ocr.py +0 -632
- rolm-ocr.py +0 -4
- serving-unlimited-ocr.md +0 -97
- smoldocling-ocr.py +2 -20
- surya-ocr-bucket.py +0 -1389
- surya-ocr.py +0 -855
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 |
-
|
| 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 |
-
**Important notes:**
|
| 185 |
-
- Requires vLLM **nightly** (stable 0.15.1 does NOT include DeepSeek-OCR-2 support)
|
| 186 |
-
- The nightly index (`https://wheels.vllm.ai/nightly`) occasionally has transient build issues (e.g., only ARM wheels). If this happens, wait and retry.
|
| 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 |
|
|
@@ -202,185 +168,6 @@ hf jobs uv run --flavor l4x1 \
|
|
| 202 |
### PaddleOCR-VL (`paddleocr-vl.py`)
|
| 203 |
✅ Working
|
| 204 |
|
| 205 |
-
### lift (`lift-extract.py`)
|
| 206 |
-
✅ **Both backends validated on Jobs** (added 2026-06-22)
|
| 207 |
-
|
| 208 |
-
Datalab's `lift` (9B, Qwen3.5-based) for **schema-constrained** structured extraction:
|
| 209 |
-
image *or* multi-page PDF + JSON Schema → JSON. Sits alongside `nuextract3.py` /
|
| 210 |
-
`lfm2-vl-extract.py` in the structured-extraction group, but it's the only one that
|
| 211 |
-
ingests PDFs directly (one row = one document, multi-page collapsed into one extraction).
|
| 212 |
-
|
| 213 |
-
**Shared rendering** comes from lift: we reuse `lift.input.load_file` (auto-detects PDF vs
|
| 214 |
-
image by content; `pypdfium2`, DPI/min-dim, `--page-range`) via a temp file per row. Each row
|
| 215 |
-
→ a list of page images → one extraction. Both backends share this.
|
| 216 |
-
|
| 217 |
-
**Backends (`--method`)** — both **in-process, single command** (no server):
|
| 218 |
-
- `hf` (default): drives the `lift-pdf` package directly — `InferenceManager(method="hf")` →
|
| 219 |
-
`AutoModelForImageTextToText`, bf16, batches a list of `BatchInputItem` conversations with
|
| 220 |
-
left padding. **No** constrained decoding (plain `model.generate`); trusts lift's training.
|
| 221 |
-
Runs on the **default** uv image. Simplest path; best for small jobs.
|
| 222 |
-
- `vllm`: vLLM's **offline `LLM()` engine** + `llm.chat()` with structured outputs — the
|
| 223 |
-
repo's standard fast-batch pattern. We reproduce lift's *own* vLLM recipe (their `generate_vllm`)
|
| 224 |
-
rather than calling the package: `PROMPT_MAPPING["direct"]`, `scale_to_fit`,
|
| 225 |
-
`mm_processor_kwargs={min_pixels:3136,max_pixels:861696}`, and the guided JSON schema
|
| 226 |
-
(`json_schema_to_pydantic.create_model` → `make_properties_nullable` → `StructuredOutputsParams`,
|
| 227 |
-
with the version shim from `ocr-vllm-judge.py`). Sampling matches lift exactly: `temperature=0.0,
|
| 228 |
-
top_p=0.1, max_tokens=12384`. Needs the `vllm/vllm-openai` image (vLLM not in our deps; reused
|
| 229 |
-
from the image via `PYTHONPATH`, which also wins the torch version → no clash). **Not mirrored:**
|
| 230 |
-
lift's repeat-token retry loop (re-runs looped items at higher temp) — less critical here since
|
| 231 |
-
the grammar constraint already prevents runaway repetition.
|
| 232 |
-
|
| 233 |
-
> **History:** the first `--method vllm` used the package's path, which is an OpenAI *client* →
|
| 234 |
-
> server (lift's `lift_vllm` shells out to `sudo docker run`, unusable in a Job). We built+validated
|
| 235 |
-
> an auto-launched `vllm serve` subprocess for it, then replaced the whole thing with the offline
|
| 236 |
-
> `LLM()` engine — cleaner single command, no HTTP, and the repo's established pattern.
|
| 237 |
-
|
| 238 |
-
**Model id:** card repo is `datalab-to/lift` (9.65B, license `openrail`, not gated). The
|
| 239 |
-
installed package's internal default was `datalab-to/lift-extract`; we pin `--model
|
| 240 |
-
datalab-to/lift` via the `MODEL_CHECKPOINT` env (set *before* importing lift, since settings
|
| 241 |
-
read env at import). Confirmed in the smoke test: `datalab-to/lift` (commit `3129597…`) loads.
|
| 242 |
-
|
| 243 |
-
**Naming gotcha:** the script must NOT be named `lift.py` — that shadows the installed `lift`
|
| 244 |
-
package (`import lift` resolves to the script itself → `ImportError: cannot import name
|
| 245 |
-
'resolve_schema'`). Hence `lift-extract.py`. Hit this on the first Jobs run.
|
| 246 |
-
|
| 247 |
-
**License:** code Apache-2.0, **weights modified OpenRAIL-M** (research/personal/<$5M, no
|
| 248 |
-
competitive use vs Datalab API). Surfaced in the docstring, the README entry, and the output
|
| 249 |
-
dataset card.
|
| 250 |
-
|
| 251 |
-
**Benchmark both backends:** `--config hf --create-pr` vs `--config vllm --create-pr` into one
|
| 252 |
-
repo (same multi-config pattern as the other OCR scripts).
|
| 253 |
-
|
| 254 |
-
**Smoke-test results (2026-06-22, `davanstrien/ufo-ColPali`, 3 samples, a100-large):**
|
| 255 |
-
- **HF backend** (default image): 3/3 valid JSON, batched (1 chunk of 3 at `--batch-size 8`, no
|
| 256 |
-
padding/image-count issues), 1.8 min. Output `davanstrien/lift-smoke-hf`. Resolved
|
| 257 |
-
`lift-pdf==0.1.1, transformers==5.12.1, torch==2.12.1, datasets==5.0.0`.
|
| 258 |
-
- **vLLM offline backend** (`vllm/vllm-openai` image): `LLM()` engine loaded (weights 18 GiB /
|
| 259 |
-
59s via Xet high-perf), `llm.chat` batched all 3 prompts in one call (538 tok/s in), 3/3 valid
|
| 260 |
-
JSON via `StructuredOutputsParams`, clean engine shutdown, 5.2 min (engine init + torch.compile
|
| 261 |
-
warmup dominates at 3 samples; wins at scale). `vllm==0.23.0`, image's `torch==2.11.0+cu130` (no
|
| 262 |
-
clash). Output `davanstrien/lift-smoke-vllm-offline`.
|
| 263 |
-
- (The earlier server-subprocess vLLM also passed — `davanstrien/lift-smoke-vllm`, 5.3 min — but
|
| 264 |
-
was replaced by the offline engine; see History above.)
|
| 265 |
-
- **All paths produce valid schema-shaped JSON**, e.g.
|
| 266 |
-
`{"title": "OUT OF THIS WORLD UFO FlyBys in Middle Tennessee", "date": "Oct. 26, 1995"}`;
|
| 267 |
-
absent fields → `null` (nullable-leaf transform). `parse_error_rate: 0.0`. Outputs agree across
|
| 268 |
-
backends except minor low-temp content drift (offline-vLLM recovered a Spanish title hf left null).
|
| 269 |
-
|
| 270 |
-
**Still untested (lower risk — reuses lift's `load_file`, exercised on the image path):**
|
| 271 |
-
- PDF column path (`--pdf-column`, `--page-range`) on a real PDF-bytes dataset.
|
| 272 |
-
- `l4x1` for the hf backend (9B bf16 ≈ 19GB; default `a100-large` confirmed comfortable).
|
| 273 |
-
|
| 274 |
-
Requires Python ≥3.12 (lift-pdf constraint) — fine on the standard images.
|
| 275 |
-
|
| 276 |
-
### Surya OCR 2 (`surya-ocr.py`)
|
| 277 |
-
✅ **OCR + layout + table validated on Jobs** (added 2026-06-22)
|
| 278 |
-
|
| 279 |
-
Datalab's **Surya OCR 2** (`datalab-to/surya-ocr-2`, 650M, Qwen3.5-style) for **structured** OCR.
|
| 280 |
-
Unlike the flat-markdown scripts, it returns per-block HTML + bounding boxes + reading order. The
|
| 281 |
-
recipe writes **two columns**: `--output-column` (default `markdown`, flattened reading-order text)
|
| 282 |
-
**and** `surya_blocks` (the full structured result as JSON, one entry per page). `--task` switches
|
| 283 |
-
between `ocr` (RecognitionPredictor, full-page), `layout` (LayoutPredictor), and `table`
|
| 284 |
-
(TableRecPredictor; `--table-mode full` → HTML, `simple` → rows/cols/cells).
|
| 285 |
-
|
| 286 |
-
**Engine — offline vLLM batch, NO server (the whole trick).** Surya normally runs its VLM through a
|
| 287 |
-
**spawned server**: on GPU it `docker run`s `vllm/vllm-openai`, on CPU a `llama-server` subprocess
|
| 288 |
-
(`surya/inference/backends/{vllm,llamacpp}.py`). Docker-in-Docker isn't available inside a Job, so
|
| 289 |
-
the default path can't work. Instead we subclass Surya's `Backend` ABC
|
| 290 |
-
(`surya/inference/backends/base.py`: `start`/`stop`/`generate(batch)->List[BatchOutputItem]`) with an
|
| 291 |
-
in-process `OfflineVLLMBackend` that runs vLLM's offline `LLM().chat()` and inject it via
|
| 292 |
-
`manager.backend = ...` (bypassing `SuryaInferenceManager.__init__`'s autodetect). **Surya still owns
|
| 293 |
-
everything else** — prompts (`PROMPT_MAPPING`), image scaling (`scale_to_fit`), HTML/bbox parsing, the
|
| 294 |
-
repeat-loop fallback, the 0–1000→pixel bbox rescale, and the layout/table predictors — so we only swap
|
| 295 |
-
the transport. We reuse Surya's own `_build_messages`/`scale_to_fit`/`PROMPT_MAPPING` so the offline
|
| 296 |
-
path matches the server byte-for-byte. `mm_processor_kwargs={min_pixels:3136,max_pixels:6291456}`,
|
| 297 |
-
`dtype=bfloat16`, `max_model_len=18000`, sampling `temperature=0.0/top_p=0.1`, `logprobs=1` →
|
| 298 |
-
`mean_token_prob` → Surya's per-block `confidence`. Guided JSON (layout's `LAYOUT_JSON_SCHEMA`) maps to
|
| 299 |
-
`StructuredOutputsParams`/`GuidedDecodingParams` (same shim as `ocr-vllm-judge.py`). **Not mirrored:**
|
| 300 |
-
Surya's per-item repeat-token retry — its recognition layer already detects loops and falls back to
|
| 301 |
-
layout+block OCR, so the backend stays simple (like lift).
|
| 302 |
-
|
| 303 |
-
**⚠️ Image gotcha — pin `vllm/vllm-openai:v0.20.1` AND use the `site-packages` path.** Surya-2 is the
|
| 304 |
-
recent, **version-sensitive, hybrid (linear-attention) `qwen3_5`** architecture; v0.20.1 is Surya's
|
| 305 |
-
known-good vLLM. Unlike the other vLLM recipes (which use the unversioned image at
|
| 306 |
-
`/usr/bin/python3` + `dist-packages`), the **`:v0.20.1`** image puts python at `/usr/local/bin/python3`
|
| 307 |
-
and vLLM/torch at **`/usr/local/lib/python3.12/site-packages`**. The first smoke run used the old
|
| 308 |
-
`dist-packages` path → `No module named 'vllm'` → 0/5. Correct flags:
|
| 309 |
-
```bash
|
| 310 |
-
hf jobs uv run --flavor l4x1 -s HF_TOKEN \
|
| 311 |
-
--image vllm/vllm-openai:v0.20.1 --python /usr/local/bin/python3 \
|
| 312 |
-
-e PYTHONPATH=/usr/local/lib/python3.12/site-packages \
|
| 313 |
-
./ocr/surya-ocr.py davanstrien/ufo-ColPali OUTPUT --max-samples 5
|
| 314 |
-
```
|
| 315 |
-
`PYTHONPATH` is prepended ahead of the uv venv, so the **image's** torch 2.11.0+cu130 / transformers /
|
| 316 |
-
vLLM 0.20.1 win at import even though `surya-ocr` pulls its own torch into the venv (harmless, just a
|
| 317 |
-
wasted download). Confirmed via a probe job: vLLM at `…/site-packages/vllm`, python 3.12.13.
|
| 318 |
-
|
| 319 |
-
**Naming gotcha:** must be `surya-ocr.py`, never `surya.py` (would shadow the `surya` package on
|
| 320 |
-
import). Checked: no other `surya*` file in the repo.
|
| 321 |
-
|
| 322 |
-
**Smoke-test results (2026-06-22, `davanstrien/ufo-ColPali`, l4x1, `vllm/vllm-openai:v0.20.1`):**
|
| 323 |
-
- **ocr** (5 samples): 5/5 OK, 3.7 min (vLLM engine init ~113s incl. 34s compile + CUDA-graph capture,
|
| 324 |
-
then inference). `markdown` clean reading-order text; `surya_blocks` valid JSON with **pixel-space**
|
| 325 |
-
bboxes (e.g. `[21.6,65.5,30.9,343.4]` within `image_bbox=[0,0,618,1007]`), sequential `reading_order`,
|
| 326 |
-
canonical labels (PageHeader/SectionHeader/Text/…), `confidence` ~0.94 (logprobs path works), per-block
|
| 327 |
-
HTML (`<h1>`, `<sup>`, `<br/>`). Output `davanstrien/surya-smoke-ocr`. Resolved `vllm==0.20.1,
|
| 328 |
-
torch==2.11.0+cu130, transformers==5.7.0, surya-ocr==0.20.0`.
|
| 329 |
-
- **layout** (3 samples): 3/3 OK; `surya_blocks` = `LayoutResult` per page (bboxes with `label`/
|
| 330 |
-
`position`/`count`/`confidence`, guided-JSON enforced). Output `davanstrien/surya-smoke-layout`.
|
| 331 |
-
- **table** `--table-mode full` (3 samples): 3/3 OK; `TableResult` with `html` populated (rows/cols/cells
|
| 332 |
-
empty in full mode, by design). ufo-ColPali has no real tables, so use a table dataset for meaningful
|
| 333 |
-
output — the code path is what's validated. Output `davanstrien/surya-smoke-table`.
|
| 334 |
-
|
| 335 |
-
- **pdf** (`--pdf-column`/`--page-range`, real 14.8MB arXiv PDF, pages 0–2): 1/1 OK. Text
|
| 336 |
-
concatenates the 3 pages (title/authors/abstract of arXiv:2606.17162 extracted in reading order);
|
| 337 |
-
`surya_blocks` has **3 page entries** (`image_bbox=[0,0,1632,2112]` at 192 DPI) with sensible labels
|
| 338 |
-
(PageHeader/SectionHeader/Text/Picture/Diagram/Caption/ListGroup/…). Source built by wrapping the PDF
|
| 339 |
-
bytes into a `Value("binary")` column. Output `davanstrien/surya-smoke-pdf`.
|
| 340 |
-
|
| 341 |
-
**Still untested (low risk):** `--table-mode simple` (rows/cols/cells). Larger GPUs (l4x1 confirmed
|
| 342 |
-
comfortable for 650M).
|
| 343 |
-
|
| 344 |
-
### Bucket variant (`surya-ocr-bucket.py`) — issue #55 ✅
|
| 345 |
-
✅ **OCR a bucket of files directly, no dataset round-trip** (added 2026-06-22). Reuses the parent's
|
| 346 |
-
`OfflineVLLMBackend` / predictor dispatch / `serialize_pages` **verbatim**; grafts on the bucket I/O
|
| 347 |
-
from `pp-doclayout.py`. Two input strategies via `--io-mode {auto,mount,copy}`: **mount** reads off a
|
| 348 |
-
FUSE-mounted `/in` (`-v hf://buckets/<id>:/in:ro`); **copy** uses `huggingface_hub`
|
| 349 |
-
`list_bucket_tree` + `download_bucket_files` to batch-fetch each `--batch-size` chunk to temp, OCR, then
|
| 350 |
-
`shutil.rmtree` (peak disk = one batch — sidesteps the FUSE bulk-read stall). Two sinks (≥1, both
|
| 351 |
-
allowed): `--output-bucket` writes per-page `<rel>.md` + `<rel>.json` (`surya_blocks`) to a mounted dir
|
| 352 |
-
or `hf://buckets/...` URL (`batch_bucket_files`), **resume-by-skip keyed on the `.json`** (the parent
|
| 353 |
-
bucket recipes have no resume); `--output-dataset` buffers one row per file and `push_to_hub`. `.jp2` is
|
| 354 |
-
first-class (LoC/Chronicling America) with an `imagecodecs` fallback when the image's Pillow lacks
|
| 355 |
-
OpenJPEG.
|
| 356 |
-
|
| 357 |
-
**⚠️ Dependency gotcha (cost one job):** must pin **`surya-ocr==0.20.0`** in the PEP 723 header. Adding
|
| 358 |
-
`huggingface-hub>=1.6.0` (for the buckets API) loosened the resolve and uv backtracked to an ancient
|
| 359 |
-
surya without the `surya.inference` engine layout → `ModuleNotFoundError: No module named 'surya.inference'`.
|
| 360 |
-
Fix: pin surya, leave `huggingface-hub` unpinned — at runtime `PYTHONPATH` puts the pinned image's hub
|
| 361 |
-
(buckets API present) ahead of the venv, so there's no version tension.
|
| 362 |
-
|
| 363 |
-
**Smoke-tested on Jobs (2026-06-22, `davanstrien/chronicling-america-mirror-demo`, 1901 *The Commoner*
|
| 364 |
-
`.jp2`, l4x1):** copy→dataset, mount→mounted-bucket-files, copy→API-bucket-files, and resume re-run
|
| 365 |
-
(skip-all, no model load) all 8/8 OK with clean masthead/body OCR + valid pixel-space `surya_blocks`.
|
| 366 |
-
Mount-vs-copy benchmark (32-page seed-42 slice, l4x1, inference identical ~745s — confirms the I/O
|
| 367 |
-
split): **copy wins decisively** — listing **5.1s vs mount 134.2s** (FUSE `rglob` stats all 38k bucket
|
| 368 |
-
files; ~26×), batch-download I/O **57.6s vs FUSE-read 74.6s**. Mount *also* hit a transient
|
| 369 |
-
`Volume mount failed: init container exhausted retries` on the first attempt (needed a cold retry;
|
| 370 |
-
documented fresh-node CSI flake) — copy never mounts. → `auto` defaulting `hf://buckets/...` inputs to
|
| 371 |
-
**copy** is the right call (already the implemented default); mount stays for when the bucket is already
|
| 372 |
-
mounted or zero ephemeral disk is wanted.
|
| 373 |
-
|
| 374 |
-
**TODO(alto):** ALTO XML export from `surya_blocks` is its own follow-up issue (block-level
|
| 375 |
-
bbox→`HPOS/VPOS/WIDTH/HEIGHT`, label→`TextBlock`/`Illustration`, reading_order→order; line-level needs
|
| 376 |
-
Surya's `DetectionPredictor`; word-level out of scope). The test bucket ships CA's own ALTO `.xml` next
|
| 377 |
-
to each `.jp2` as a ready-made diff target.
|
| 378 |
-
|
| 379 |
-
**License:** code Apache-2.0, **weights modified OpenRAIL-M** (research/personal/<$5M, no competitive use
|
| 380 |
-
vs Datalab's API). Surfaced in the docstring, README entry, and output dataset card.
|
| 381 |
-
|
| 382 |
-
**Benchmark/compare:** `--config`/`--create-pr` push the same multi-config pattern as the other scripts.
|
| 383 |
-
|
| 384 |
---
|
| 385 |
|
| 386 |
## Future: OCR Smoke Test Dataset
|
|
@@ -421,314 +208,6 @@ uv run glm-ocr.py uv-scripts/ocr-smoke-test smoke-out --max-samples 5
|
|
| 421 |
|
| 422 |
---
|
| 423 |
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
**Status:** Working end-to-end (2026-02-14)
|
| 427 |
-
|
| 428 |
-
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`.
|
| 429 |
-
|
| 430 |
-
### Model Registry (4 models)
|
| 431 |
-
|
| 432 |
-
| Slug | Model ID | Size | Default GPU | Notes |
|
| 433 |
-
|------|----------|------|-------------|-------|
|
| 434 |
-
| `glm-ocr` | `zai-org/GLM-OCR` | 0.9B | l4x1 | |
|
| 435 |
-
| `deepseek-ocr` | `deepseek-ai/DeepSeek-OCR` | 4B | l4x1 | Auto-passes `--prompt-mode free` (no grounding tags) |
|
| 436 |
-
| `lighton-ocr-2` | `lightonai/LightOnOCR-2-1B` | 1B | a100-large | |
|
| 437 |
-
| `dots-ocr` | `rednote-hilab/dots.ocr` | 1.7B | l4x1 | Stable vLLM (>=0.9.1) |
|
| 438 |
-
|
| 439 |
-
Each model entry has a `default_args` list for model-specific flags (e.g., DeepSeek uses `["--prompt-mode", "free"]`).
|
| 440 |
-
|
| 441 |
-
### Workflow
|
| 442 |
-
```bash
|
| 443 |
-
# Launch all 4 models on same data
|
| 444 |
-
uv run ocr-bench-run.py source-dataset --output my-bench --max-samples 50
|
| 445 |
-
|
| 446 |
-
# Evaluate directly from PRs (no merge needed)
|
| 447 |
-
uv run ocr-elo-bench.py my-bench --from-prs --mode both
|
| 448 |
-
|
| 449 |
-
# Or merge + evaluate
|
| 450 |
-
uv run ocr-elo-bench.py my-bench --from-prs --merge-prs --mode both
|
| 451 |
-
|
| 452 |
-
# Other useful flags
|
| 453 |
-
uv run ocr-bench-run.py --list-models # Show registry table
|
| 454 |
-
uv run ocr-bench-run.py ... --dry-run # Preview without launching
|
| 455 |
-
uv run ocr-bench-run.py ... --wait # Poll until complete
|
| 456 |
-
uv run ocr-bench-run.py ... --models glm-ocr dots-ocr # Subset of models
|
| 457 |
-
```
|
| 458 |
-
|
| 459 |
-
### Eval script features (`ocr-elo-bench.py`)
|
| 460 |
-
- `--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
|
| 461 |
-
- `--merge-prs`: Auto-merges discovered PRs via `api.merge_pull_request()` before loading
|
| 462 |
-
- `--configs`: Manually specify which configs to load (for merged repos)
|
| 463 |
-
- `--mode both`: Runs pairwise ELO + pointwise scoring
|
| 464 |
-
- Flat mode (original behavior) still works when `--configs`/`--from-prs` not used
|
| 465 |
-
|
| 466 |
-
### Scripts pushed to Hub
|
| 467 |
-
All 4 scripts have been pushed to `uv-scripts/ocr` on the Hub with `--config`/`--create-pr` support:
|
| 468 |
-
- `glm-ocr.py` ✅
|
| 469 |
-
- `deepseek-ocr-vllm.py` ✅
|
| 470 |
-
- `lighton-ocr2.py` ✅
|
| 471 |
-
- `dots-ocr.py` ✅
|
| 472 |
-
|
| 473 |
-
### Benchmark Results
|
| 474 |
-
|
| 475 |
-
#### Run 1: NLS Medical History (2026-02-14) — Pilot
|
| 476 |
-
|
| 477 |
-
**Dataset:** `NationalLibraryOfScotland/medical-history-of-british-india` (10 samples, shuffled, seed 42)
|
| 478 |
-
**Output repo:** `davanstrien/ocr-bench-test` (4 open PRs)
|
| 479 |
-
**Judge:** `Qwen/Qwen2.5-VL-72B-Instruct` via HF Inference Providers
|
| 480 |
-
**Content:** Historical English, degraded scans of medical texts
|
| 481 |
-
|
| 482 |
-
**ELO (pairwise, 5 samples evaluated):**
|
| 483 |
-
1. DoTS.ocr — 1540 (67% win rate)
|
| 484 |
-
2. DeepSeek-OCR — 1539 (57%)
|
| 485 |
-
3. LightOnOCR-2 — 1486 (50%)
|
| 486 |
-
4. GLM-OCR — 1436 (29%)
|
| 487 |
-
|
| 488 |
-
**Pointwise (5 samples):**
|
| 489 |
-
1. DeepSeek-OCR — 5.0/5.0
|
| 490 |
-
2. GLM-OCR — 4.6
|
| 491 |
-
3. LightOnOCR-2 — 4.4
|
| 492 |
-
4. DoTS.ocr — 4.2
|
| 493 |
-
|
| 494 |
-
**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.
|
| 495 |
-
|
| 496 |
-
**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.
|
| 497 |
-
|
| 498 |
-
#### Run 2: Rubenstein Manuscript Catalog (2026-02-15) — First Full Benchmark
|
| 499 |
-
|
| 500 |
-
**Dataset:** `biglam/rubenstein-manuscript-catalog` (50 samples, shuffled, seed 42)
|
| 501 |
-
**Output repo:** `davanstrien/ocr-bench-rubenstein` (4 PRs)
|
| 502 |
-
**Judge:** Jury of 2 via `ocr-vllm-judge.py` — `Qwen/Qwen2.5-VL-7B-Instruct` + `Qwen/Qwen3-VL-8B-Instruct` on A100
|
| 503 |
-
**Content:** ~48K typewritten + handwritten manuscript catalog cards from Duke University (CC0)
|
| 504 |
-
|
| 505 |
-
**ELO (pairwise, 50 samples, 300 comparisons, 0 parse failures):**
|
| 506 |
-
|
| 507 |
-
| Rank | Model | ELO | W | L | T | Win% |
|
| 508 |
-
|------|-------|-----|---|---|---|------|
|
| 509 |
-
| 1 | LightOnOCR-2-1B | 1595 | 100 | 50 | 0 | 67% |
|
| 510 |
-
| 2 | DeepSeek-OCR | 1497 | 73 | 77 | 0 | 49% |
|
| 511 |
-
| 3 | GLM-OCR | 1471 | 57 | 93 | 0 | 38% |
|
| 512 |
-
| 4 | dots.ocr | 1437 | 70 | 80 | 0 | 47% |
|
| 513 |
-
|
| 514 |
-
**OCR job times** (all 50 samples each):
|
| 515 |
-
- dots-ocr: 5.3 min (L4)
|
| 516 |
-
- deepseek-ocr: 5.6 min (L4)
|
| 517 |
-
- glm-ocr: 5.7 min (L4)
|
| 518 |
-
- lighton-ocr-2: 6.4 min (A100)
|
| 519 |
-
|
| 520 |
-
**Key findings:**
|
| 521 |
-
- **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
|
| 522 |
-
- **Rankings are dataset-dependent**: NLS historical medical texts favored DoTS.ocr and DeepSeek-OCR; Rubenstein typewritten/handwritten cards favor LightOnOCR-2
|
| 523 |
-
- **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
|
| 524 |
-
- **50 samples gives meaningful separation**: Clear ELO gaps (1595 → 1497 → 1471 → 1437) unlike the noisy 5-sample pilot
|
| 525 |
-
- This validates the multi-dataset benchmark approach — no single dataset tells the whole story
|
| 526 |
-
|
| 527 |
-
#### Run 3: UFO-ColPali (2026-02-15) — Cross-Dataset Validation
|
| 528 |
-
|
| 529 |
-
**Dataset:** `davanstrien/ufo-ColPali` (50 samples, shuffled, seed 42)
|
| 530 |
-
**Output repo:** `davanstrien/ocr-bench-ufo` (4 PRs)
|
| 531 |
-
**Judge:** `Qwen/Qwen3-VL-30B-A3B-Instruct` via `ocr-vllm-judge.py` on A100 (updated prompt)
|
| 532 |
-
**Content:** Mixed modern documents (invoices, reports, forms, etc.)
|
| 533 |
-
|
| 534 |
-
**ELO (pairwise, 50 samples, 294 comparisons):**
|
| 535 |
-
|
| 536 |
-
| Rank | Model | ELO | W | L | T | Win% |
|
| 537 |
-
|------|-------|-----|---|---|---|------|
|
| 538 |
-
| 1 | DeepSeek-OCR | 1827 | 130 | 17 | 0 | 88% |
|
| 539 |
-
| 2 | dots.ocr | 1510 | 64 | 83 | 0 | 44% |
|
| 540 |
-
| 3 | LightOnOCR-2-1B | 1368 | 77 | 70 | 0 | 52% |
|
| 541 |
-
| 4 | GLM-OCR | 1294 | 23 | 124 | 0 | 16% |
|
| 542 |
-
|
| 543 |
-
**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.
|
| 544 |
-
|
| 545 |
-
#### Cross-Dataset Comparison (Human-Validated)
|
| 546 |
-
|
| 547 |
-
| Model | Rubenstein Human | Rubenstein Kimi | UFO Human | UFO 30B |
|
| 548 |
-
|-------|:---------------:|:---------------:|:---------:|:-------:|
|
| 549 |
-
| DeepSeek-OCR | **#1** | **#1** | **#1** | **#1** |
|
| 550 |
-
| GLM-OCR | #2 | #3 | #2 | #4 |
|
| 551 |
-
| LightOnOCR-2 | #4 | #2 | #3 | #3 |
|
| 552 |
-
| dots.ocr | #3 | #4 | #4 | #2 |
|
| 553 |
-
|
| 554 |
-
**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.
|
| 555 |
-
|
| 556 |
-
*Note: NLS pilot results (5 samples, 72B API judge) omitted — not comparable with newer methodology.*
|
| 557 |
-
|
| 558 |
-
### Known Issues / Next Steps
|
| 559 |
-
|
| 560 |
-
1. ✅ **More samples needed** — Done. Rubenstein run (2026-02-15) used 50 samples and produced clear ELO separation across all 4 models.
|
| 561 |
-
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.
|
| 562 |
-
3. **Auto-merge in coordinator** — `--wait` could auto-merge PRs after successful jobs. Not yet implemented.
|
| 563 |
-
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.
|
| 564 |
-
5. **Leaderboard Space** — See future section below.
|
| 565 |
-
6. ✅ **Result persistence** — `ocr-vllm-judge.py` now has `--save-results REPO_ID` flag. First dataset: `davanstrien/ocr-bench-rubenstein-judge`.
|
| 566 |
-
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.
|
| 567 |
-
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.
|
| 568 |
-
|
| 569 |
-
---
|
| 570 |
-
|
| 571 |
-
## Offline vLLM Judge (`ocr-vllm-judge.py`)
|
| 572 |
-
|
| 573 |
-
**Status:** Working end-to-end (2026-02-15)
|
| 574 |
-
|
| 575 |
-
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.
|
| 576 |
-
|
| 577 |
-
### Why use this over the API judge (`ocr-jury-bench.py`)?
|
| 578 |
-
|
| 579 |
-
| | API judge (`ocr-jury-bench.py`) | Offline judge (`ocr-vllm-judge.py`) |
|
| 580 |
-
|---|---|---|
|
| 581 |
-
| Parse failures | Needs retries for malformed JSON | 0 failures — vLLM structured output guarantees valid JSON |
|
| 582 |
-
| Network | Rate limits, timeouts, transient errors | Zero network calls |
|
| 583 |
-
| Cost | Per-token API pricing | Just GPU time |
|
| 584 |
-
| Judge models | Limited to Inference Providers catalog | Any vLLM-supported VLM |
|
| 585 |
-
| Jury mode | Sequential API calls per judge | Sequential model loading, batch inference per judge |
|
| 586 |
-
| Best for | Quick spot-checks, access to 72B models | Batch evaluation (50+ samples), reproducibility |
|
| 587 |
-
|
| 588 |
-
**Pushed to Hub:** `uv-scripts/ocr` as `ocr-vllm-judge.py` (2026-02-15)
|
| 589 |
-
|
| 590 |
-
### Test Results (2026-02-15)
|
| 591 |
-
|
| 592 |
-
**Test 1 — Single judge, 1 sample, L4:**
|
| 593 |
-
- Qwen2.5-VL-7B-Instruct, 6/6 comparisons, 0 parse failures
|
| 594 |
-
- Total time: ~3 min (including model download + warmup)
|
| 595 |
-
|
| 596 |
-
**Test 2 — Jury of 2, 3 samples, A100:**
|
| 597 |
-
- Qwen2.5-VL-7B + Qwen3-VL-8B, 15/15 comparisons, 0 parse failures
|
| 598 |
-
- GPU cleanup between models: successful (nanobind warnings are cosmetic)
|
| 599 |
-
- Majority vote aggregation working (`[2/2]` unanimous, `[1/2]` split)
|
| 600 |
-
- Total time: ~4 min (including both model downloads)
|
| 601 |
-
|
| 602 |
-
**Test 3 — Full benchmark, 50 samples, A100 (Rubenstein Manuscript Catalog):**
|
| 603 |
-
- Qwen2.5-VL-7B + Qwen3-VL-8B jury, 300/300 comparisons, 0 parse failures
|
| 604 |
-
- Input: `davanstrien/ocr-bench-rubenstein` (4 PRs from `ocr-bench-run.py`)
|
| 605 |
-
- Produced clear ELO rankings with meaningful separation
|
| 606 |
-
- See "Benchmark Results → Run 2" in the OCR Benchmark Coordinator section above
|
| 607 |
-
|
| 608 |
-
### Usage
|
| 609 |
-
|
| 610 |
-
```bash
|
| 611 |
-
# Single judge on L4
|
| 612 |
-
hf jobs uv run --flavor l4x1 -s HF_TOKEN \
|
| 613 |
-
ocr-vllm-judge.py davanstrien/ocr-bench-nls-50 --from-prs \
|
| 614 |
-
--judge-model Qwen/Qwen2.5-VL-7B-Instruct --max-samples 10
|
| 615 |
-
|
| 616 |
-
# Jury of 2 on A100 (recommended for jury mode)
|
| 617 |
-
hf jobs uv run --flavor a100-large -s HF_TOKEN \
|
| 618 |
-
ocr-vllm-judge.py davanstrien/ocr-bench-nls-50 --from-prs \
|
| 619 |
-
--judge-model Qwen/Qwen2.5-VL-7B-Instruct \
|
| 620 |
-
--judge-model Qwen/Qwen3-VL-8B-Instruct \
|
| 621 |
-
--max-samples 50
|
| 622 |
-
```
|
| 623 |
-
|
| 624 |
-
### Implementation Notes
|
| 625 |
-
- Comparisons built upfront on CPU as `NamedTuple`s, then batched to vLLM in single `llm.chat()` call
|
| 626 |
-
- Structured output via compatibility shim: `StructuredOutputsParams` (vLLM >= 0.12) → `GuidedDecodingParams` (older) → prompt-based fallback
|
| 627 |
-
- GPU cleanup between jury models: `destroy_model_parallel()` + `gc.collect()` + `torch.cuda.empty_cache()`
|
| 628 |
-
- Position bias mitigation: A/B order randomized per comparison
|
| 629 |
-
- A100 recommended for jury mode; L4 works for single 7B judge
|
| 630 |
-
|
| 631 |
-
### Next Steps
|
| 632 |
-
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.
|
| 633 |
-
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`.
|
| 634 |
-
3. **Integrate into `ocr-bench-run.py`** — Add `--eval` flag that auto-runs vLLM judge after OCR jobs complete
|
| 635 |
-
|
| 636 |
-
---
|
| 637 |
-
|
| 638 |
-
## Blind Human Eval (`ocr-human-eval.py`)
|
| 639 |
-
|
| 640 |
-
**Status:** Working (2026-02-15)
|
| 641 |
-
|
| 642 |
-
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.
|
| 643 |
-
|
| 644 |
-
### Usage
|
| 645 |
-
|
| 646 |
-
```bash
|
| 647 |
-
# Basic — blind human eval only
|
| 648 |
-
uv run ocr-human-eval.py davanstrien/ocr-bench-rubenstein --from-prs --max-samples 5
|
| 649 |
-
|
| 650 |
-
# With judge comparison — loads automated judge results for agreement analysis
|
| 651 |
-
uv run ocr-human-eval.py davanstrien/ocr-bench-rubenstein --from-prs \
|
| 652 |
-
--judge-results davanstrien/ocr-bench-rubenstein-judge --max-samples 5
|
| 653 |
-
```
|
| 654 |
-
|
| 655 |
-
### Features
|
| 656 |
-
- **Blind evaluation**: Two-tab design — Evaluate tab never shows model names, Results tab reveals rankings
|
| 657 |
-
- **Position bias mitigation**: A/B order randomly swapped per comparison
|
| 658 |
-
- **Resume support**: JSON annotations saved atomically after each vote; restart app to resume where you left off
|
| 659 |
-
- **Live agreement tracking**: Per-vote feedback shows running agreement with automated judge (when `--judge-results` provided)
|
| 660 |
-
- **Split-jury prioritization**: Comparisons where automated judges disagreed ("1/2" agreement) shown first — highest annotation value per vote
|
| 661 |
-
- **Image variety**: Round-robin interleaving by sample so you don't see the same document image repeatedly
|
| 662 |
-
- **Soft/hard disagreement analysis**: Distinguishes between harmless ties-vs-winner disagreements and genuine opposite-winner errors
|
| 663 |
-
|
| 664 |
-
### First Validation Results (Rubenstein, 30 annotations)
|
| 665 |
-
|
| 666 |
-
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.
|
| 667 |
-
|
| 668 |
-
Full results and analysis in `OCR-BENCHMARK.md` → "Human Validation" section.
|
| 669 |
-
|
| 670 |
-
### Next Steps
|
| 671 |
-
1. **Second dataset** — Run on NLS Medical History for cross-dataset human validation
|
| 672 |
-
2. **Multiple annotators** — Currently single-user; could support annotator ID for inter-annotator agreement
|
| 673 |
-
3. **Remaining LightOnOCR-2 gap** — Still #2 (Kimi) vs #4 (human). May need to investigate on more samples or strip commentary in preprocessing
|
| 674 |
-
|
| 675 |
-
---
|
| 676 |
-
|
| 677 |
-
## Future: Leaderboard HF Space
|
| 678 |
-
|
| 679 |
-
**Status:** Idea (noted 2026-02-14)
|
| 680 |
-
|
| 681 |
-
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.
|
| 682 |
-
|
| 683 |
-
**Design ideas:**
|
| 684 |
-
- Gradio or static Space displaying ELO ratings + pointwise scores
|
| 685 |
-
- `ocr-elo-bench.py` could push results to a dataset that the Space reads
|
| 686 |
-
- Or the Space itself could run evaluation on demand
|
| 687 |
-
- Show per-document comparisons (image + side-by-side OCR outputs)
|
| 688 |
-
- Historical tracking — how scores change across model versions
|
| 689 |
-
- Filter by document type (historical, modern, tables, formulas, multilingual)
|
| 690 |
-
|
| 691 |
-
**Open questions:**
|
| 692 |
-
- Should the eval script push structured results to a dataset (e.g., `uv-scripts/ocr-leaderboard-data`)?
|
| 693 |
-
- Static leaderboard (updated by CI/scheduled job) vs interactive (evaluate on demand)?
|
| 694 |
-
- Include sample outputs for qualitative comparison?
|
| 695 |
-
- How to handle different eval datasets (NLS medical history vs UFO vs others)?
|
| 696 |
-
|
| 697 |
-
---
|
| 698 |
-
|
| 699 |
-
## Incremental Uploads / Checkpoint Strategy — ON HOLD
|
| 700 |
-
|
| 701 |
-
**Status:** Waiting on HF Hub Buckets (noted 2026-02-20)
|
| 702 |
-
|
| 703 |
-
**Current state:**
|
| 704 |
-
- `glm-ocr.py` (v1): Simple batch-then-push. Works fine for most jobs.
|
| 705 |
-
- `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).
|
| 706 |
-
|
| 707 |
-
**Decision: Do NOT port v2 pattern to other scripts.** Wait for HF Hub Buckets instead.
|
| 708 |
-
|
| 709 |
-
**Why:** Two open PRs will likely make the v2 CommitScheduler approach obsolete:
|
| 710 |
-
- [huggingface_hub#3673](https://github.com/huggingface/huggingface_hub/pull/3673) — Buckets API: S3-like mutable object storage on HF, no git versioning overhead
|
| 711 |
-
- [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
|
| 712 |
-
|
| 713 |
-
**What Buckets would replace:** Once landed, incremental saves become one line per batch:
|
| 714 |
-
```python
|
| 715 |
-
batch_ds.to_parquet(f"hf://buckets/{user}/ocr-scratch/shard-{batch_num:05d}.parquet")
|
| 716 |
-
```
|
| 717 |
-
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`).
|
| 718 |
-
|
| 719 |
-
**Action items when Buckets ships:**
|
| 720 |
-
1. Test `hf://buckets/` fsspec writes on one script (glm-ocr is the guinea pig)
|
| 721 |
-
2. Verify: write performance, atomicity (partial writes visible?), auth propagation in HF Jobs
|
| 722 |
-
3. If it works, adopt as the standard pattern for all scripts — simple enough to inline (~20 lines)
|
| 723 |
-
4. Retire `glm-ocr-v2.py` CommitScheduler approach
|
| 724 |
-
|
| 725 |
-
**Until then:** v1 scripts stay as-is. `glm-ocr-v2.py` exists if someone needs resume on a very large job today.
|
| 726 |
-
|
| 727 |
-
---
|
| 728 |
-
|
| 729 |
-
**Last Updated:** 2026-02-20
|
| 730 |
**Watch PRs:**
|
| 731 |
-
-
|
| 732 |
-
- **HfFileSystem Buckets** ([#3807](https://github.com/huggingface/huggingface_hub/pull/3807)): fsspec support for `hf://buckets/` paths. Key for zero-boilerplate writes from scripts.
|
| 733 |
-
- DeepSeek-OCR-2 stable vLLM release: Currently only in nightly. Watch for vLLM 0.16.0 stable release on PyPI to remove nightly dependency.
|
| 734 |
-
- 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 |
|
|
|
|
| 168 |
### PaddleOCR-VL (`paddleocr-vl.py`)
|
| 169 |
✅ Working
|
| 170 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
| 8 |
-
|
| 9 |
|
| 10 |
-
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
## Quick Start
|
| 15 |
|
| 16 |
Run OCR on any dataset without needing your own GPU:
|
| 17 |
|
|
@@ -24,233 +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 |
-
The recipes here run as batch jobs. To call a model interactively, from an agent, or with concurrent ad-hoc requests, you can instead run it as a temporary endpoint: [HF Jobs serving](https://huggingface.co/docs/hub/jobs-serving) exposes a port on a GPU Job, giving an OpenAI-compatible endpoint that runs until the job is cancelled or its `--timeout` is reached. See [serving-unlimited-ocr.md](serving-unlimited-ocr.md) for a worked example serving Baidu's [Unlimited-OCR](https://huggingface.co/baidu/Unlimited-OCR) with SGLang.
|
| 37 |
-
|
| 38 |
-
## Models at a glance
|
| 39 |
-
|
| 40 |
-
**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:
|
| 41 |
-
|
| 42 |
-
```bash
|
| 43 |
-
hf datasets leaderboard allenai/olmOCR-bench
|
| 44 |
-
```
|
| 45 |
-
|
| 46 |
-
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.
|
| 47 |
-
|
| 48 |
-
_Sorted by model size:_
|
| 49 |
|
| 50 |
| Script | Model | Size | Backend | Notes |
|
| 51 |
|--------|-------|------|---------|-------|
|
| 52 |
-
| `pp-ocrv6.py` | [PP-OCRv6](https://huggingface.co/collections/PaddlePaddle/pp-ocrv6) | 1.5–34.5M | PaddleOCR (paddle) | **Smallest by far** — classical det+rec pipeline, not a VLM. Three tiers (`--model-tier tiny\|small\|medium`), plain-text output (not markdown). 50 langs. Runs on `t4-small`. Apache 2.0 |
|
| 53 |
-
| `falcon-ocr.py` | [Falcon-OCR](https://huggingface.co/tiiuae/Falcon-OCR) | 0.3B | falcon-perception | Smallest VLM in collection. #1 on multi-column docs and tables (olmOCR), Apache 2.0 |
|
| 54 |
| `smoldocling-ocr.py` | [SmolDocling](https://huggingface.co/ds4sd/SmolDocling-256M-preview) | 256M | Transformers | DocTags structured output |
|
| 55 |
-
| `surya-ocr.py` | [Surya OCR 2](https://huggingface.co/datalab-to/surya-ocr-2) | 0.65B | vLLM | **Structured** OCR + `--task layout\|table`: per-block HTML with bboxes & reading order in an extra `surya_blocks` column. 91 langs, top-under-3B on olmOCR-Bench. Modified OpenRAIL-M license. Needs the **pinned** `vllm/vllm-openai:v0.20.1` image |
|
| 56 |
| `glm-ocr.py` | [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) | 0.9B | vLLM | 94.62% OmniDocBench V1.5 |
|
| 57 |
| `paddleocr-vl.py` | [PaddleOCR-VL](https://huggingface.co/PaddlePaddle/PaddleOCR-VL) | 0.9B | Transformers | 4 task modes (ocr/table/formula/chart) |
|
| 58 |
| `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 |
|
| 59 |
-
| `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 |
|
| 60 |
| `lighton-ocr.py` | [LightOnOCR-1B](https://huggingface.co/lightonai/LightOnOCR-1B-1025) | 1B | vLLM | Fast, 3 vocab sizes |
|
| 61 |
| `lighton-ocr2.py` | [LightOnOCR-2-1B](https://huggingface.co/lightonai/LightOnOCR-2-1B) | 1B | vLLM | 7× faster than v1, RLVR trained |
|
| 62 |
| `hunyuan-ocr.py` | [HunyuanOCR](https://huggingface.co/tencent/HunyuanOCR) | 1B | vLLM | Lightweight VLM |
|
| 63 |
| `dots-ocr.py` | [DoTS.ocr](https://huggingface.co/Tencent/DoTS.ocr) | 1.7B | vLLM | 100+ languages |
|
| 64 |
| `firered-ocr.py` | [FireRed-OCR](https://huggingface.co/FireRedTeam/FireRed-OCR) | 2.1B | vLLM | Qwen3-VL fine-tune, Apache 2.0 |
|
| 65 |
-
| `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) |
|
| 66 |
| `nanonets-ocr.py` | [Nanonets-OCR-s](https://huggingface.co/nanonets/Nanonets-OCR-s) | 2B | vLLM | LaTeX, tables, forms |
|
| 67 |
-
| `dots-
|
| 68 |
| `nanonets-ocr2.py` | [Nanonets-OCR2-3B](https://huggingface.co/nanonets/Nanonets-OCR2-s) | 3B | vLLM | Next-gen, Qwen2.5-VL base |
|
| 69 |
| `deepseek-ocr-vllm.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | vLLM | 5 resolution + 5 prompt modes |
|
| 70 |
| `deepseek-ocr.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | Transformers | Same model, Transformers backend |
|
| 71 |
-
| `deepseek-ocr2-vllm.py` | [DeepSeek-OCR-2](https://huggingface.co/deepseek-ai/DeepSeek-OCR-2) | 3B | vLLM | Newer
|
| 72 |
-
| `nuextract3.py` | [NuExtract3](https://huggingface.co/numind/NuExtract3) | 4B | vLLM | Markdown OCR **+ schema-guided JSON extraction** (template/Pydantic). Needs `vllm/vllm-openai` image |
|
| 73 |
-
| `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 |
|
| 74 |
| `olmocr2-vllm.py` | [olmOCR-2-7B](https://huggingface.co/allenai/olmOCR-2-7B-1025-FP8) | 7B | vLLM | 82.4% olmOCR-Bench |
|
| 75 |
| `rolm-ocr.py` | [RolmOCR](https://huggingface.co/reducto/RolmOCR) | 7B | vLLM | Qwen2.5-VL based, general-purpose |
|
| 76 |
| `numarkdown-ocr.py` | [NuMarkdown-8B](https://huggingface.co/numind/NuMarkdown-8B-Thinking) | 8B | vLLM | Reasoning-based OCR |
|
| 77 |
|
| 78 |
-
|
| 79 |
|
| 80 |
-
|
| 81 |
|
| 82 |
-
|
| 83 |
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
-
|
| 87 |
-
|--------|-------|------|-------|--------|
|
| 88 |
-
| `lfm2-vl-extract.py` | [LFM2.5-VL-1.6B-Extract](https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B-Extract) | 1.6B | image | JSON |
|
| 89 |
-
| `nuextract3.py` | [NuExtract3](https://huggingface.co/numind/NuExtract3) | 4B | image | markdown **or** JSON |
|
| 90 |
-
| `lfm2-extract.py` | [LFM2-1.2B-Extract](https://huggingface.co/LiquidAI/LFM2-1.2B-Extract) | 1.2B | **text** | JSON / XML / YAML |
|
| 91 |
-
| `lift-extract.py` | [lift](https://huggingface.co/datalab-to/lift) | 9B | image **or** PDF | JSON |
|
| 92 |
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
-
|
| 96 |
|
| 97 |
```bash
|
| 98 |
-
#
|
| 99 |
-
hf jobs uv run --flavor l4x1 -
|
| 100 |
-
|
| 101 |
-
-
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
```
|
| 105 |
|
| 106 |
-
|
| 107 |
|
| 108 |
-
|
| 109 |
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
```bash
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
```
|
| 119 |
|
| 120 |
-
|
| 121 |
|
| 122 |
-
|
| 123 |
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
```
|
| 130 |
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
```bash
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
-
|
| 137 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/
|
| 138 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
```
|
| 140 |
|
| 141 |
-
|
| 142 |
|
| 143 |
-
|
| 144 |
|
| 145 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
-
|
| 148 |
-
|--------|-------------|
|
| 149 |
-
| `--image-column` | Column containing images (default: `image`) |
|
| 150 |
-
| `--output-column` | Output column name (default: `markdown`) |
|
| 151 |
-
| `--split` | Dataset split (default: `train`) |
|
| 152 |
-
| `--max-samples` | Limit number of samples (useful for testing) |
|
| 153 |
-
| `--private` | Make output dataset private |
|
| 154 |
-
| `--shuffle` | Shuffle dataset before processing |
|
| 155 |
-
| `--seed` | Random seed for shuffling (default: `42`) |
|
| 156 |
-
| `--batch-size` | Images per batch (default varies per model) |
|
| 157 |
-
| `--max-model-len` | Max context length (default varies per model) |
|
| 158 |
-
| `--max-tokens` | Max output tokens (default varies per model) |
|
| 159 |
-
| `--gpu-memory-utilization` | GPU memory fraction (default: `0.8`) |
|
| 160 |
-
| `--config` | Config name for Hub push (for benchmarking) |
|
| 161 |
-
| `--create-pr` | Push as PR instead of direct commit |
|
| 162 |
-
| `--verbose` | Log resolved package versions after run |
|
| 163 |
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
|
| 166 |
```bash
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
```
|
| 169 |
|
| 170 |
-
##
|
|
|
|
|
|
|
| 171 |
|
| 172 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
|
| 174 |
-
|
| 175 |
|
| 176 |
```bash
|
| 177 |
-
#
|
| 178 |
hf jobs uv run --flavor a100-large \
|
| 179 |
-
--image vllm/vllm-openai:latest \
|
| 180 |
-
--python /usr/bin/python3 \
|
| 181 |
-
-e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \
|
| 182 |
-s HF_TOKEN \
|
| 183 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/
|
| 184 |
-
|
|
|
|
|
|
|
| 185 |
|
| 186 |
-
#
|
| 187 |
hf jobs uv run --flavor a100-large \
|
| 188 |
-
--image vllm/vllm-openai:latest \
|
| 189 |
-
--python /usr/bin/python3 \
|
| 190 |
-
-e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \
|
| 191 |
-s HF_TOKEN \
|
| 192 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/
|
| 193 |
-
|
| 194 |
-
--
|
| 195 |
```
|
| 196 |
|
| 197 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
-
|
| 200 |
|
| 201 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
|
| 203 |
-
|
| 204 |
-
|--------|---------------|
|
| 205 |
-
| `surya-ocr.py` | `--task ocr\|layout\|table`, `--table-mode full\|simple`, `--pdf-column`/`--page-range`, `--blocks-column` |
|
| 206 |
-
| `pp-ocrv6.py` | `--model-tier tiny\|small\|medium` (1.5M–34.5M params) |
|
| 207 |
-
| `glm-ocr.py` | `--task ocr\|formula\|table` |
|
| 208 |
-
| `paddleocr-vl.py` | `--task-mode ocr\|table\|formula\|chart` |
|
| 209 |
-
| `paddleocr-vl-1.5.py` | `--task-mode ocr\|table\|formula\|chart\|spotting\|seal` |
|
| 210 |
-
| `paddleocr-vl-1.6.py` | `--task-mode ocr\|table\|formula` |
|
| 211 |
-
| `lighton-ocr.py` | `--vocab-size 151k\|32k\|16k` (smaller = faster on European languages) |
|
| 212 |
-
| `deepseek-ocr-vllm.py` | `--resolution-mode tiny\|small\|base\|large\|gundam`, `--prompt-mode document\|image\|free\|figure\|describe`; pass `-e UV_TORCH_BACKEND=auto` |
|
| 213 |
-
| `dots-ocr.py` | `--prompt-mode ocr\|layout-all\|layout-only` |
|
| 214 |
-
| `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` |
|
| 215 |
-
| `qianfan-ocr.py` | `--prompt-mode ocr\|table\|formula\|chart\|scene\|kie`, `--think` (Layout-as-Thought); `kie` needs `--custom-prompt` |
|
| 216 |
-
| `numarkdown-ocr.py` | `--include-thinking` (store the reasoning trace) |
|
| 217 |
-
| `nuextract3.py` | `--template` / `--schema` / `--enable-thinking` — see the NuExtract3 section above |
|
| 218 |
|
| 219 |
-
|
| 220 |
|
| 221 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
|
| 223 |
-
|
| 224 |
-
- **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:
|
| 225 |
-
```bash
|
| 226 |
-
uv run rolm-ocr.py my-dataset my-dataset --max-samples 100
|
| 227 |
-
uv run nanonets-ocr.py my-dataset my-dataset --max-samples 100 # appends
|
| 228 |
-
```
|
| 229 |
-
- **Reproducible sampling** — `--shuffle` (with `--seed`, default 42) draws a representative sample instead of the first N rows.
|
| 230 |
-
- **Automatic dataset cards** — every run writes a card with the model config, processing stats, column descriptions, and a reproduction command.
|
| 231 |
|
| 232 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
|
| 234 |
```bash
|
| 235 |
-
#
|
| 236 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr-vllm.py \
|
| 238 |
-
NationalLibraryOfScotland/Britain-and-UK-Handbooks-Dataset
|
| 239 |
-
--
|
|
|
|
|
|
|
|
|
|
| 240 |
|
| 241 |
-
#
|
| 242 |
-
hf jobs uv run --flavor l4x1
|
| 243 |
-
|
| 244 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
|
| 246 |
-
#
|
| 247 |
-
hf jobs uv run --flavor
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
--
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
```
|
| 252 |
|
| 253 |
-
|
| 254 |
|
| 255 |
```python
|
| 256 |
from huggingface_hub import run_uv_job
|
|
@@ -258,17 +612,36 @@ from huggingface_hub import run_uv_job
|
|
| 258 |
job = run_uv_job(
|
| 259 |
"https://huggingface.co/datasets/uv-scripts/ocr/raw/main/nanonets-ocr.py",
|
| 260 |
args=["input-dataset", "output-dataset", "--batch-size", "16"],
|
| 261 |
-
flavor="l4x1"
|
| 262 |
)
|
| 263 |
```
|
| 264 |
|
| 265 |
-
|
| 266 |
|
| 267 |
```bash
|
| 268 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 269 |
input-dataset output-dataset
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 270 |
```
|
| 271 |
|
| 272 |
-
|
| 273 |
|
| 274 |
-
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-ocr.py
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
# requires-python = ">=3.11"
|
| 3 |
# dependencies = [
|
| 4 |
# "datasets",
|
| 5 |
-
# "huggingface-hub",
|
| 6 |
# "pillow",
|
| 7 |
# "torch",
|
| 8 |
# "torchvision",
|
|
@@ -252,7 +252,8 @@ def main(
|
|
| 252 |
# Track processing start time
|
| 253 |
start_time = datetime.now()
|
| 254 |
|
| 255 |
-
|
|
|
|
| 256 |
|
| 257 |
# Login to HF if token provided
|
| 258 |
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
|
|
|
|
| 2 |
# requires-python = ">=3.11"
|
| 3 |
# dependencies = [
|
| 4 |
# "datasets",
|
| 5 |
+
# "huggingface-hub[hf_transfer]",
|
| 6 |
# "pillow",
|
| 7 |
# "torch",
|
| 8 |
# "torchvision",
|
|
|
|
| 252 |
# Track processing start time
|
| 253 |
start_time = datetime.now()
|
| 254 |
|
| 255 |
+
# Enable HF_TRANSFER for faster downloads
|
| 256 |
+
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
|
| 257 |
|
| 258 |
# Login to HF if token provided
|
| 259 |
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
|
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 |
|
demo.gif
DELETED
Git LFS Details
|
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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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
lift-extract.py
DELETED
|
@@ -1,812 +0,0 @@
|
|
| 1 |
-
# /// script
|
| 2 |
-
# requires-python = ">=3.12"
|
| 3 |
-
# dependencies = [
|
| 4 |
-
# "lift-pdf[hf]",
|
| 5 |
-
# "datasets>=3.1.0",
|
| 6 |
-
# "huggingface-hub",
|
| 7 |
-
# "pillow",
|
| 8 |
-
# "toolz",
|
| 9 |
-
# "tqdm",
|
| 10 |
-
# ]
|
| 11 |
-
# ///
|
| 12 |
-
"""
|
| 13 |
-
Extract structured JSON from document images OR multi-page PDFs using Datalab's
|
| 14 |
-
`lift` model (`datalab-to/lift`, 9B, Qwen3.5-based).
|
| 15 |
-
|
| 16 |
-
Unlike the markdown-OCR scripts here, lift does *schema-constrained* extraction:
|
| 17 |
-
you give it a JSON Schema, it returns a JSON object matching that schema. It
|
| 18 |
-
natively handles multi-page documents — a whole PDF is collapsed into a single
|
| 19 |
-
extraction.
|
| 20 |
-
|
| 21 |
-
Two in-process backends, selected with `--method` (no server, single command):
|
| 22 |
-
|
| 23 |
-
--method hf (default) Transformers via the `lift-pdf` package. Runs on the
|
| 24 |
-
default uv image. Simplest path; best for small jobs.
|
| 25 |
-
--method vllm vLLM's offline `LLM()` engine (`llm.chat`) with
|
| 26 |
-
structured-output decoding — the fast batched path the
|
| 27 |
-
other vLLM OCR scripts here use. Needs the
|
| 28 |
-
`vllm/vllm-openai` image (which ships vLLM). Reproduces
|
| 29 |
-
lift's own prompt + guided-JSON recipe against the
|
| 30 |
-
offline engine. Wins on large jobs via continuous batching.
|
| 31 |
-
|
| 32 |
-
Benchmark the two by pushing each to one repo with `--config hf` / `--config vllm`.
|
| 33 |
-
|
| 34 |
-
Input is one document per row:
|
| 35 |
-
--image-column COL (default `image`) one image per row -> one extraction
|
| 36 |
-
--pdf-column COL PDF bytes per row -> one extraction
|
| 37 |
-
(multi-page; respects --page-range)
|
| 38 |
-
|
| 39 |
-
Pass `--schema` as inline JSON, a URL, or a file path (standard JSON Schema):
|
| 40 |
-
|
| 41 |
-
--schema '{"type":"object","properties":{"invoice_number":{"type":"string"},
|
| 42 |
-
"total":{"type":"number"}},"required":["invoice_number"]}'
|
| 43 |
-
|
| 44 |
-
LICENSE NOTE: lift's *code* is Apache-2.0 but the *weights* are a modified
|
| 45 |
-
OpenRAIL-M license — free for research, personal use, and startups under $5M
|
| 46 |
-
funding/revenue, but restricted from competitive use against Datalab's API.
|
| 47 |
-
Confirm you are within those terms before using it. https://huggingface.co/datalab-to/lift
|
| 48 |
-
|
| 49 |
-
HF Jobs — HF backend (default image is fine; 9B needs a roomy GPU):
|
| 50 |
-
|
| 51 |
-
hf jobs uv run --flavor a100-large -s HF_TOKEN \\
|
| 52 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lift-extract.py \\
|
| 53 |
-
INPUT_DATASET OUTPUT_DATASET \\
|
| 54 |
-
--schema '{"type":"object","properties":{"title":{"type":"string"}}}' \\
|
| 55 |
-
--max-samples 5 --shuffle --seed 42
|
| 56 |
-
|
| 57 |
-
HF Jobs — vLLM offline backend (use the vllm image so vLLM is present):
|
| 58 |
-
|
| 59 |
-
hf jobs uv run --flavor a100-large -s HF_TOKEN \\
|
| 60 |
-
--image vllm/vllm-openai --python /usr/bin/python3 \\
|
| 61 |
-
-e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\
|
| 62 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lift-extract.py \\
|
| 63 |
-
INPUT_DATASET OUTPUT_DATASET --method vllm \\
|
| 64 |
-
--schema '{"type":"object","properties":{"title":{"type":"string"}}}' \\
|
| 65 |
-
--max-samples 5
|
| 66 |
-
|
| 67 |
-
Model: datalab-to/lift (package: lift-pdf, https://github.com/datalab-to/lift)
|
| 68 |
-
"""
|
| 69 |
-
|
| 70 |
-
import argparse
|
| 71 |
-
import base64
|
| 72 |
-
import io
|
| 73 |
-
import json
|
| 74 |
-
import logging
|
| 75 |
-
import os
|
| 76 |
-
import sys
|
| 77 |
-
import tempfile
|
| 78 |
-
import time
|
| 79 |
-
from datetime import datetime, timezone
|
| 80 |
-
from typing import Any, Dict, List, Optional, Tuple
|
| 81 |
-
from urllib.request import urlopen
|
| 82 |
-
|
| 83 |
-
from datasets import load_dataset
|
| 84 |
-
from huggingface_hub import DatasetCard, login
|
| 85 |
-
from PIL import Image
|
| 86 |
-
from toolz import partition_all
|
| 87 |
-
from tqdm import tqdm
|
| 88 |
-
|
| 89 |
-
logging.basicConfig(level=logging.INFO)
|
| 90 |
-
logger = logging.getLogger(__name__)
|
| 91 |
-
|
| 92 |
-
# The package default checkpoint drifts between releases (e.g. "datalab-to/lift-extract");
|
| 93 |
-
# pin to the canonical card repo so the script is stable across lift-pdf versions.
|
| 94 |
-
DEFAULT_MODEL = "datalab-to/lift"
|
| 95 |
-
DEFAULT_MAX_TOKENS = 12384 # lift-pdf's own MAX_OUTPUT_TOKENS default
|
| 96 |
-
|
| 97 |
-
# A processed document: (parsed JSON or None, error flag, raw model text).
|
| 98 |
-
DocResult = Tuple[Optional[Any], bool, str]
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
def check_cuda_availability() -> None:
|
| 102 |
-
"""Exit early with a clear message if there's no GPU."""
|
| 103 |
-
import torch
|
| 104 |
-
|
| 105 |
-
if not torch.cuda.is_available():
|
| 106 |
-
logger.error("CUDA is not available. This script requires a GPU.")
|
| 107 |
-
logger.error(
|
| 108 |
-
"Run on Hugging Face Jobs with: hf jobs uv run --flavor a100-large ..."
|
| 109 |
-
)
|
| 110 |
-
sys.exit(1)
|
| 111 |
-
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
def load_schema_arg(value: str) -> Dict[str, Any]:
|
| 115 |
-
"""Resolve --schema (inline JSON, a URL, or a file path) into a JSON Schema dict."""
|
| 116 |
-
text = value.strip()
|
| 117 |
-
if text.startswith(("http://", "https://")):
|
| 118 |
-
logger.info(f"Loading schema from URL: {text}")
|
| 119 |
-
text = urlopen(text).read().decode("utf-8") # noqa: S310
|
| 120 |
-
elif not text.startswith("{"):
|
| 121 |
-
# Looks like a path (inline JSON would start with "{"); read it if it exists.
|
| 122 |
-
if os.path.isfile(text):
|
| 123 |
-
logger.info(f"Loading schema from file: {text}")
|
| 124 |
-
with open(text) as f:
|
| 125 |
-
text = f.read()
|
| 126 |
-
try:
|
| 127 |
-
parsed = json.loads(text)
|
| 128 |
-
except json.JSONDecodeError as e:
|
| 129 |
-
raise ValueError(
|
| 130 |
-
f"Could not parse --schema as JSON (tried URL/path/inline): {e}"
|
| 131 |
-
) from e
|
| 132 |
-
if not isinstance(parsed, dict):
|
| 133 |
-
raise ValueError("--schema must be a JSON object (a JSON Schema).")
|
| 134 |
-
return parsed
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
def cell_to_bytes(cell: Any) -> bytes:
|
| 138 |
-
"""Normalize an HF dataset cell (image or document) to raw file bytes.
|
| 139 |
-
|
| 140 |
-
Handles decoded PIL images (Image feature), {"bytes"/"path"} dicts, raw bytes
|
| 141 |
-
(e.g. a binary PDF column), and string paths/URLs.
|
| 142 |
-
"""
|
| 143 |
-
if isinstance(cell, Image.Image):
|
| 144 |
-
buf = io.BytesIO()
|
| 145 |
-
cell.convert("RGB").save(buf, format="PNG")
|
| 146 |
-
return buf.getvalue()
|
| 147 |
-
if isinstance(cell, dict):
|
| 148 |
-
if cell.get("bytes"):
|
| 149 |
-
return cell["bytes"]
|
| 150 |
-
if cell.get("path"):
|
| 151 |
-
with open(cell["path"], "rb") as f:
|
| 152 |
-
return f.read()
|
| 153 |
-
raise ValueError(
|
| 154 |
-
f"Unsupported image/document dict (no bytes/path): {list(cell)}"
|
| 155 |
-
)
|
| 156 |
-
if isinstance(cell, (bytes, bytearray)):
|
| 157 |
-
return bytes(cell)
|
| 158 |
-
if isinstance(cell, str):
|
| 159 |
-
if cell.startswith(("http://", "https://")):
|
| 160 |
-
return urlopen(cell).read() # noqa: S310
|
| 161 |
-
with open(cell, "rb") as f:
|
| 162 |
-
return f.read()
|
| 163 |
-
raise ValueError(f"Unsupported cell type: {type(cell)}")
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
def load_document_images(
|
| 167 |
-
load_file, cell: Any, page_range: Optional[str]
|
| 168 |
-
) -> List[Image.Image]:
|
| 169 |
-
"""Render one dataset cell into the page images lift expects.
|
| 170 |
-
|
| 171 |
-
Reuses lift's own `load_file`, which auto-detects PDF vs image by content
|
| 172 |
-
(pypdfium2 for PDFs, with the model's DPI/min-dim and page-range handling).
|
| 173 |
-
"""
|
| 174 |
-
data = cell_to_bytes(cell)
|
| 175 |
-
# load_file detects type from content, so the temp file needs no extension.
|
| 176 |
-
with tempfile.NamedTemporaryFile(delete=False) as tmp:
|
| 177 |
-
tmp.write(data)
|
| 178 |
-
path = tmp.name
|
| 179 |
-
try:
|
| 180 |
-
config = {"page_range": page_range} if page_range else {}
|
| 181 |
-
return load_file(path, config)
|
| 182 |
-
finally:
|
| 183 |
-
os.unlink(path)
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
def pil_to_data_uri(img: Image.Image) -> str:
|
| 187 |
-
"""PNG data URI for an OpenAI-format image content block."""
|
| 188 |
-
if img.mode != "RGB":
|
| 189 |
-
img = img.convert("RGB")
|
| 190 |
-
buf = io.BytesIO()
|
| 191 |
-
img.save(buf, format="PNG")
|
| 192 |
-
return f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
def parse_json_output(text: str) -> Tuple[Optional[Any], bool]:
|
| 196 |
-
"""Return (parsed, ok). Strips ```json fences if present."""
|
| 197 |
-
stripped = text.strip()
|
| 198 |
-
if stripped.startswith("```"):
|
| 199 |
-
stripped = stripped.split("\n", 1)[-1] if "\n" in stripped else stripped[3:]
|
| 200 |
-
if stripped.endswith("```"):
|
| 201 |
-
stripped = stripped[:-3].rstrip()
|
| 202 |
-
try:
|
| 203 |
-
return json.loads(stripped), True
|
| 204 |
-
except (json.JSONDecodeError, ValueError):
|
| 205 |
-
return None, False
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
# --- HF backend (lift-pdf package, in-process Transformers) ---
|
| 209 |
-
def make_hf_processor(schema: Dict[str, Any], max_tokens: Optional[int]):
|
| 210 |
-
"""Load lift via the package's HF backend; return a batch-processing closure."""
|
| 211 |
-
from lift.model import InferenceManager
|
| 212 |
-
from lift.model.schema import BatchInputItem
|
| 213 |
-
|
| 214 |
-
logger.info("Loading lift via Transformers (method=hf)...")
|
| 215 |
-
manager = InferenceManager(method="hf")
|
| 216 |
-
|
| 217 |
-
def process(image_lists: List[List[Image.Image]]) -> List[DocResult]:
|
| 218 |
-
items = [
|
| 219 |
-
BatchInputItem(images=imgs, schema=schema, prompt_type="direct")
|
| 220 |
-
for imgs in image_lists
|
| 221 |
-
]
|
| 222 |
-
results = manager.generate(items, max_output_tokens=max_tokens)
|
| 223 |
-
return [(r.extraction, bool(r.error), r.raw) for r in results]
|
| 224 |
-
|
| 225 |
-
return process
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
# --- vLLM backend (offline LLM() engine + structured outputs) ---
|
| 229 |
-
def build_guided_schema(schema: Dict[str, Any]) -> Dict[str, Any]:
|
| 230 |
-
"""Reproduce lift's vLLM guided-decoding schema: JSON Schema -> pydantic ->
|
| 231 |
-
json_schema with every leaf made nullable (so absent fields can be null,
|
| 232 |
-
matching lift's own server-side behavior)."""
|
| 233 |
-
from json_schema_to_pydantic import create_model
|
| 234 |
-
from lift.model.vllm import make_properties_nullable
|
| 235 |
-
|
| 236 |
-
schema_model = create_model(schema)
|
| 237 |
-
json_schema = schema_model.model_json_schema()
|
| 238 |
-
make_properties_nullable(json_schema)
|
| 239 |
-
return json_schema
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
def make_sampling_params(json_schema: Dict[str, Any], max_tokens: int):
|
| 243 |
-
"""SamplingParams with structured JSON output, across vLLM API versions.
|
| 244 |
-
|
| 245 |
-
lift uses greedy-ish decoding (temperature 0.0, top_p 0.1).
|
| 246 |
-
"""
|
| 247 |
-
from vllm import SamplingParams
|
| 248 |
-
|
| 249 |
-
# vLLM >= 0.12
|
| 250 |
-
try:
|
| 251 |
-
from vllm.sampling_params import StructuredOutputsParams
|
| 252 |
-
|
| 253 |
-
return SamplingParams(
|
| 254 |
-
temperature=0.0,
|
| 255 |
-
top_p=0.1,
|
| 256 |
-
max_tokens=max_tokens,
|
| 257 |
-
structured_outputs=StructuredOutputsParams(json=json_schema),
|
| 258 |
-
)
|
| 259 |
-
except (ImportError, TypeError):
|
| 260 |
-
pass
|
| 261 |
-
# Older vLLM
|
| 262 |
-
try:
|
| 263 |
-
from vllm.sampling_params import GuidedDecodingParams
|
| 264 |
-
|
| 265 |
-
return SamplingParams(
|
| 266 |
-
temperature=0.0,
|
| 267 |
-
top_p=0.1,
|
| 268 |
-
max_tokens=max_tokens,
|
| 269 |
-
guided_decoding=GuidedDecodingParams(json=json_schema),
|
| 270 |
-
)
|
| 271 |
-
except (ImportError, TypeError):
|
| 272 |
-
pass
|
| 273 |
-
logger.warning(
|
| 274 |
-
"Structured output unavailable in this vLLM version; relying on lift's "
|
| 275 |
-
"training to emit valid JSON."
|
| 276 |
-
)
|
| 277 |
-
return SamplingParams(temperature=0.0, top_p=0.1, max_tokens=max_tokens)
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
def make_vllm_processor(
|
| 281 |
-
schema: Dict[str, Any],
|
| 282 |
-
model: str,
|
| 283 |
-
max_tokens: Optional[int],
|
| 284 |
-
max_model_len: int,
|
| 285 |
-
gpu_memory_utilization: float,
|
| 286 |
-
max_images_per_doc: int,
|
| 287 |
-
):
|
| 288 |
-
"""Load lift into vLLM's offline engine; return a batch-processing closure."""
|
| 289 |
-
try:
|
| 290 |
-
from vllm import LLM
|
| 291 |
-
except ImportError as e:
|
| 292 |
-
raise RuntimeError(
|
| 293 |
-
"--method vllm needs vLLM. Run on the vllm/vllm-openai image: "
|
| 294 |
-
"--image vllm/vllm-openai --python /usr/bin/python3 "
|
| 295 |
-
"-e PYTHONPATH=/usr/local/lib/python3.12/dist-packages"
|
| 296 |
-
) from e
|
| 297 |
-
from lift.model.util import scale_to_fit
|
| 298 |
-
from lift.prompts import PROMPT_MAPPING
|
| 299 |
-
|
| 300 |
-
json_schema = build_guided_schema(schema)
|
| 301 |
-
prompt = PROMPT_MAPPING["direct"].replace("{schema}", json.dumps(schema, indent=2))
|
| 302 |
-
|
| 303 |
-
logger.info("Loading lift via vLLM offline engine (method=vllm)...")
|
| 304 |
-
llm = LLM(
|
| 305 |
-
model=model,
|
| 306 |
-
trust_remote_code=True,
|
| 307 |
-
max_model_len=max_model_len,
|
| 308 |
-
gpu_memory_utilization=gpu_memory_utilization,
|
| 309 |
-
limit_mm_per_prompt={"image": max_images_per_doc},
|
| 310 |
-
# lift's own server-side image bounds, applied by the offline processor too.
|
| 311 |
-
mm_processor_kwargs={"min_pixels": 3136, "max_pixels": 861696},
|
| 312 |
-
)
|
| 313 |
-
sampling_params = make_sampling_params(
|
| 314 |
-
json_schema, max_tokens or DEFAULT_MAX_TOKENS
|
| 315 |
-
)
|
| 316 |
-
|
| 317 |
-
def process(image_lists: List[List[Image.Image]]) -> List[DocResult]:
|
| 318 |
-
messages = []
|
| 319 |
-
for imgs in image_lists:
|
| 320 |
-
content = [
|
| 321 |
-
{
|
| 322 |
-
"type": "image_url",
|
| 323 |
-
"image_url": {"url": pil_to_data_uri(scale_to_fit(img))},
|
| 324 |
-
}
|
| 325 |
-
for img in imgs
|
| 326 |
-
]
|
| 327 |
-
content.append({"type": "text", "text": prompt})
|
| 328 |
-
messages.append([{"role": "user", "content": content}])
|
| 329 |
-
outputs = llm.chat(
|
| 330 |
-
messages, sampling_params, chat_template_content_format="openai"
|
| 331 |
-
)
|
| 332 |
-
results: List[DocResult] = []
|
| 333 |
-
for o in outputs:
|
| 334 |
-
raw = o.outputs[0].text
|
| 335 |
-
parsed, ok = parse_json_output(raw)
|
| 336 |
-
results.append((parsed if ok else None, not ok, raw))
|
| 337 |
-
return results
|
| 338 |
-
|
| 339 |
-
return process
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
def create_dataset_card(
|
| 343 |
-
source_dataset: str,
|
| 344 |
-
model: str,
|
| 345 |
-
method: str,
|
| 346 |
-
schema: Dict[str, Any],
|
| 347 |
-
num_samples: int,
|
| 348 |
-
n_valid: int,
|
| 349 |
-
source_column: str,
|
| 350 |
-
is_pdf: bool,
|
| 351 |
-
page_range: Optional[str],
|
| 352 |
-
output_column: str,
|
| 353 |
-
split: str,
|
| 354 |
-
processing_time: str,
|
| 355 |
-
) -> str:
|
| 356 |
-
"""Build the output dataset card documenting the lift run."""
|
| 357 |
-
schema_block = json.dumps(schema, indent=2)
|
| 358 |
-
input_kind = "PDF documents" if is_pdf else "images"
|
| 359 |
-
col_desc = "PDF" if is_pdf else "image"
|
| 360 |
-
if page_range:
|
| 361 |
-
col_desc += f", pages {page_range}"
|
| 362 |
-
backend_desc = (
|
| 363 |
-
"vLLM offline engine" if method == "vllm" else "Transformers (lift-pdf)"
|
| 364 |
-
)
|
| 365 |
-
return f"""---
|
| 366 |
-
tags:
|
| 367 |
-
- ocr
|
| 368 |
-
- structured-extraction
|
| 369 |
-
- document-processing
|
| 370 |
-
- lift
|
| 371 |
-
- json
|
| 372 |
-
- uv-script
|
| 373 |
-
- generated
|
| 374 |
-
---
|
| 375 |
-
|
| 376 |
-
# lift structured extraction on {source_dataset}
|
| 377 |
-
|
| 378 |
-
Schema-constrained JSON extracted from {input_kind} in
|
| 379 |
-
[{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using
|
| 380 |
-
[lift](https://huggingface.co/{model}) (9B, Qwen3.5-based) by Datalab, via the
|
| 381 |
-
[`lift-pdf`](https://github.com/datalab-to/lift) package.
|
| 382 |
-
|
| 383 |
-
## Processing Details
|
| 384 |
-
|
| 385 |
-
- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
|
| 386 |
-
- **Model**: [{model}](https://huggingface.co/{model})
|
| 387 |
-
- **Backend**: `{method}` ({backend_desc})
|
| 388 |
-
- **Input column**: `{source_column}` ({col_desc})
|
| 389 |
-
- **Output column**: `{output_column}` (JSON string per row)
|
| 390 |
-
- **Split**: `{split}`
|
| 391 |
-
- **Samples**: {num_samples:,}
|
| 392 |
-
- **Valid JSON**: {n_valid:,} / {num_samples:,}
|
| 393 |
-
- **Processing time**: {processing_time}
|
| 394 |
-
- **Date**: {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}
|
| 395 |
-
|
| 396 |
-
### Extraction Schema
|
| 397 |
-
|
| 398 |
-
```json
|
| 399 |
-
{schema_block}
|
| 400 |
-
```
|
| 401 |
-
|
| 402 |
-
## License note
|
| 403 |
-
|
| 404 |
-
lift's code is Apache-2.0, but the model **weights** use a modified OpenRAIL-M
|
| 405 |
-
license: free for research, personal use, and startups under $5M funding/revenue,
|
| 406 |
-
restricted from competitive use against Datalab's API. See the
|
| 407 |
-
[model card](https://huggingface.co/{model}).
|
| 408 |
-
|
| 409 |
-
## Dataset Structure
|
| 410 |
-
|
| 411 |
-
Original columns plus:
|
| 412 |
-
- `{output_column}`: lift output (JSON string; raw text kept on parse failure)
|
| 413 |
-
- `inference_info`: JSON list tracking models applied to this dataset
|
| 414 |
-
|
| 415 |
-
Generated with [UV Scripts](https://huggingface.co/uv-scripts).
|
| 416 |
-
"""
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
def main(
|
| 420 |
-
input_dataset: str,
|
| 421 |
-
output_dataset: str,
|
| 422 |
-
schema_arg: str,
|
| 423 |
-
image_column: str = "image",
|
| 424 |
-
pdf_column: Optional[str] = None,
|
| 425 |
-
output_column: str = "extraction",
|
| 426 |
-
method: str = "hf",
|
| 427 |
-
page_range: Optional[str] = None,
|
| 428 |
-
split: str = "train",
|
| 429 |
-
max_samples: Optional[int] = None,
|
| 430 |
-
shuffle: bool = False,
|
| 431 |
-
seed: int = 42,
|
| 432 |
-
batch_size: int = 8,
|
| 433 |
-
max_tokens: Optional[int] = None,
|
| 434 |
-
max_model_len: int = 32768,
|
| 435 |
-
gpu_memory_utilization: float = 0.9,
|
| 436 |
-
max_images_per_doc: Optional[int] = None,
|
| 437 |
-
model: str = DEFAULT_MODEL,
|
| 438 |
-
private: bool = False,
|
| 439 |
-
config: Optional[str] = None,
|
| 440 |
-
create_pr: bool = False,
|
| 441 |
-
hf_token: Optional[str] = None,
|
| 442 |
-
verbose: bool = False,
|
| 443 |
-
) -> None:
|
| 444 |
-
# Unlock full Xet bandwidth for the 9B (~19GB) model download (repo convention).
|
| 445 |
-
os.environ["HF_XET_HIGH_PERFORMANCE"] = "1"
|
| 446 |
-
check_cuda_availability()
|
| 447 |
-
start_time = datetime.now(timezone.utc)
|
| 448 |
-
|
| 449 |
-
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
|
| 450 |
-
if HF_TOKEN:
|
| 451 |
-
login(token=HF_TOKEN)
|
| 452 |
-
|
| 453 |
-
schema = load_schema_arg(schema_arg)
|
| 454 |
-
|
| 455 |
-
# lift reads the checkpoint from env (pydantic-settings) at import time; set it first.
|
| 456 |
-
os.environ["MODEL_CHECKPOINT"] = model
|
| 457 |
-
|
| 458 |
-
# Import lift only after env is set so settings pick up the right checkpoint.
|
| 459 |
-
from lift import resolve_schema
|
| 460 |
-
from lift.input import load_file
|
| 461 |
-
|
| 462 |
-
schema = resolve_schema(schema) # validates and normalizes
|
| 463 |
-
fields = list(schema.get("properties", {}).keys())
|
| 464 |
-
|
| 465 |
-
source_column = pdf_column or image_column
|
| 466 |
-
is_pdf = pdf_column is not None
|
| 467 |
-
# vLLM caps images per prompt at init; PDFs need headroom for multiple pages.
|
| 468 |
-
if max_images_per_doc is None:
|
| 469 |
-
max_images_per_doc = 30 if is_pdf else 1
|
| 470 |
-
|
| 471 |
-
logger.info(f"Model: {model} Backend: {method}")
|
| 472 |
-
logger.info(f"Schema top-level fields: {fields}")
|
| 473 |
-
|
| 474 |
-
logger.info(f"Loading dataset: {input_dataset} (split={split})")
|
| 475 |
-
dataset = load_dataset(input_dataset, split=split)
|
| 476 |
-
if source_column not in dataset.column_names:
|
| 477 |
-
logger.error(
|
| 478 |
-
f"Column '{source_column}' not found. Available: {dataset.column_names}"
|
| 479 |
-
)
|
| 480 |
-
sys.exit(1)
|
| 481 |
-
if shuffle:
|
| 482 |
-
dataset = dataset.shuffle(seed=seed)
|
| 483 |
-
if max_samples:
|
| 484 |
-
dataset = dataset.select(range(min(max_samples, len(dataset))))
|
| 485 |
-
logger.info(f"Processing {len(dataset)} documents from column '{source_column}'")
|
| 486 |
-
|
| 487 |
-
if method == "vllm":
|
| 488 |
-
process_batch = make_vllm_processor(
|
| 489 |
-
schema,
|
| 490 |
-
model,
|
| 491 |
-
max_tokens,
|
| 492 |
-
max_model_len,
|
| 493 |
-
gpu_memory_utilization,
|
| 494 |
-
max_images_per_doc,
|
| 495 |
-
)
|
| 496 |
-
else:
|
| 497 |
-
process_batch = make_hf_processor(schema, max_tokens)
|
| 498 |
-
|
| 499 |
-
extractions: List[Optional[str]] = [None] * len(dataset)
|
| 500 |
-
error_flags: List[bool] = [True] * len(dataset)
|
| 501 |
-
|
| 502 |
-
chunks = list(partition_all(batch_size, range(len(dataset))))
|
| 503 |
-
for chunk in tqdm(chunks, desc="Extracting"):
|
| 504 |
-
chunk = list(chunk)
|
| 505 |
-
rendered: Dict[int, List[Image.Image]] = {}
|
| 506 |
-
for i in chunk:
|
| 507 |
-
try:
|
| 508 |
-
rendered[i] = load_document_images(
|
| 509 |
-
load_file, dataset[i][source_column], page_range
|
| 510 |
-
)
|
| 511 |
-
except Exception as e:
|
| 512 |
-
logger.warning(f"Row {i}: failed to load document: {e}")
|
| 513 |
-
extractions[i] = f"[LIFT LOAD ERROR] {e}"
|
| 514 |
-
error_flags[i] = True
|
| 515 |
-
if not rendered:
|
| 516 |
-
continue
|
| 517 |
-
|
| 518 |
-
idxs = list(rendered.keys())
|
| 519 |
-
try:
|
| 520 |
-
results = process_batch([rendered[i] for i in idxs])
|
| 521 |
-
except Exception as e:
|
| 522 |
-
logger.error(f"Batch generate failed: {e}")
|
| 523 |
-
for i in idxs:
|
| 524 |
-
extractions[i] = "[LIFT GENERATE ERROR]"
|
| 525 |
-
error_flags[i] = True
|
| 526 |
-
continue
|
| 527 |
-
|
| 528 |
-
for i, (parsed, err, raw) in zip(idxs, results):
|
| 529 |
-
if parsed is not None and not err:
|
| 530 |
-
extractions[i] = json.dumps(parsed, ensure_ascii=False)
|
| 531 |
-
error_flags[i] = False
|
| 532 |
-
else:
|
| 533 |
-
extractions[i] = raw if raw else "[LIFT EMPTY OUTPUT]"
|
| 534 |
-
error_flags[i] = True
|
| 535 |
-
|
| 536 |
-
n_valid = sum(not f for f in error_flags)
|
| 537 |
-
logger.info(f"Valid JSON: {n_valid}/{len(dataset)}")
|
| 538 |
-
|
| 539 |
-
dataset = dataset.add_column(output_column, extractions)
|
| 540 |
-
|
| 541 |
-
inference_entry = {
|
| 542 |
-
"model": model,
|
| 543 |
-
"model_name": "lift",
|
| 544 |
-
"column_name": output_column,
|
| 545 |
-
"task": "schema-constrained extraction",
|
| 546 |
-
"backend": method,
|
| 547 |
-
"fields": fields,
|
| 548 |
-
"page_range": page_range,
|
| 549 |
-
"parse_error_rate": (len(dataset) - n_valid) / len(dataset)
|
| 550 |
-
if len(dataset)
|
| 551 |
-
else 0.0,
|
| 552 |
-
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 553 |
-
"script": "lift-extract.py",
|
| 554 |
-
}
|
| 555 |
-
if "inference_info" in dataset.column_names:
|
| 556 |
-
|
| 557 |
-
def update_info(example):
|
| 558 |
-
try:
|
| 559 |
-
existing = (
|
| 560 |
-
json.loads(example["inference_info"])
|
| 561 |
-
if example["inference_info"]
|
| 562 |
-
else []
|
| 563 |
-
)
|
| 564 |
-
except (json.JSONDecodeError, TypeError):
|
| 565 |
-
existing = []
|
| 566 |
-
existing.append(inference_entry)
|
| 567 |
-
return {"inference_info": json.dumps(existing)}
|
| 568 |
-
|
| 569 |
-
dataset = dataset.map(update_info)
|
| 570 |
-
else:
|
| 571 |
-
dataset = dataset.add_column(
|
| 572 |
-
"inference_info", [json.dumps([inference_entry])] * len(dataset)
|
| 573 |
-
)
|
| 574 |
-
|
| 575 |
-
processing_time = (
|
| 576 |
-
f"{(datetime.now(timezone.utc) - start_time).total_seconds() / 60:.1f} min"
|
| 577 |
-
)
|
| 578 |
-
|
| 579 |
-
logger.info(f"Pushing to {output_dataset}")
|
| 580 |
-
max_retries = 3
|
| 581 |
-
for attempt in range(1, max_retries + 1):
|
| 582 |
-
try:
|
| 583 |
-
if attempt > 1:
|
| 584 |
-
logger.warning("Disabling XET (fallback to HTTP upload)")
|
| 585 |
-
os.environ["HF_HUB_DISABLE_XET"] = "1"
|
| 586 |
-
dataset.push_to_hub(
|
| 587 |
-
output_dataset,
|
| 588 |
-
private=private,
|
| 589 |
-
token=HF_TOKEN,
|
| 590 |
-
max_shard_size="500MB",
|
| 591 |
-
create_pr=create_pr,
|
| 592 |
-
**({"config_name": config} if config else {}),
|
| 593 |
-
commit_message=f"Add lift extraction results ({len(dataset)} samples)"
|
| 594 |
-
+ (f" [{config}]" if config else ""),
|
| 595 |
-
)
|
| 596 |
-
break
|
| 597 |
-
except Exception as e:
|
| 598 |
-
logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
|
| 599 |
-
if attempt < max_retries:
|
| 600 |
-
delay = 30 * (2 ** (attempt - 1))
|
| 601 |
-
logger.info(f"Retrying in {delay}s...")
|
| 602 |
-
time.sleep(delay)
|
| 603 |
-
else:
|
| 604 |
-
logger.error("All upload attempts failed. Results are lost.")
|
| 605 |
-
sys.exit(1)
|
| 606 |
-
|
| 607 |
-
try:
|
| 608 |
-
card = DatasetCard(
|
| 609 |
-
create_dataset_card(
|
| 610 |
-
source_dataset=input_dataset,
|
| 611 |
-
model=model,
|
| 612 |
-
method=method,
|
| 613 |
-
schema=schema,
|
| 614 |
-
num_samples=len(dataset),
|
| 615 |
-
n_valid=n_valid,
|
| 616 |
-
source_column=source_column,
|
| 617 |
-
is_pdf=is_pdf,
|
| 618 |
-
page_range=page_range,
|
| 619 |
-
output_column=output_column,
|
| 620 |
-
split=split,
|
| 621 |
-
processing_time=processing_time,
|
| 622 |
-
)
|
| 623 |
-
)
|
| 624 |
-
card.push_to_hub(output_dataset, token=HF_TOKEN)
|
| 625 |
-
except Exception as e:
|
| 626 |
-
logger.warning(f"Could not push dataset card: {e}")
|
| 627 |
-
|
| 628 |
-
logger.info("Done! lift extraction complete.")
|
| 629 |
-
logger.info(f"Dataset: https://huggingface.co/datasets/{output_dataset}")
|
| 630 |
-
logger.info(f"Processing time: {processing_time}")
|
| 631 |
-
|
| 632 |
-
if verbose:
|
| 633 |
-
import importlib.metadata
|
| 634 |
-
|
| 635 |
-
logger.info("--- Resolved package versions ---")
|
| 636 |
-
pkgs = ["lift-pdf", "transformers", "torch", "datasets", "pillow", "openai"]
|
| 637 |
-
if method == "vllm":
|
| 638 |
-
pkgs.append("vllm")
|
| 639 |
-
for pkg in pkgs:
|
| 640 |
-
try:
|
| 641 |
-
logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
|
| 642 |
-
except importlib.metadata.PackageNotFoundError:
|
| 643 |
-
logger.info(f" {pkg}: not installed")
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
if __name__ == "__main__":
|
| 647 |
-
if len(sys.argv) == 1:
|
| 648 |
-
print("lift — schema-constrained JSON extraction from images & PDFs (9B)")
|
| 649 |
-
print("\nUsage:")
|
| 650 |
-
print(" uv run lift-extract.py INPUT OUTPUT --schema SCHEMA [options]")
|
| 651 |
-
print("\nExamples:")
|
| 652 |
-
print(" # image column -> JSON")
|
| 653 |
-
print(" uv run lift-extract.py my-images my-fields \\")
|
| 654 |
-
print(
|
| 655 |
-
' --schema \'{"type":"object","properties":{"title":{"type":"string"}}}\''
|
| 656 |
-
)
|
| 657 |
-
print("\n # multi-page PDFs -> JSON (one extraction per document)")
|
| 658 |
-
print(
|
| 659 |
-
" uv run lift-extract.py my-pdfs my-fields --pdf-column pdf --page-range 0-5 \\"
|
| 660 |
-
)
|
| 661 |
-
print(" --schema schema.json")
|
| 662 |
-
print("\n --schema accepts inline JSON, a URL, or a file path.")
|
| 663 |
-
print(
|
| 664 |
-
" --method hf (default) | vllm (offline LLM engine; needs the vllm image)"
|
| 665 |
-
)
|
| 666 |
-
print("\nFor full help: uv run lift-extract.py --help")
|
| 667 |
-
sys.exit(0)
|
| 668 |
-
|
| 669 |
-
parser = argparse.ArgumentParser(
|
| 670 |
-
description="Schema-constrained JSON extraction from images & PDFs using datalab-to/lift",
|
| 671 |
-
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 672 |
-
epilog="""
|
| 673 |
-
Backends (both in-process, single command):
|
| 674 |
-
--method hf Transformers via lift-pdf (default). Simplest; default image.
|
| 675 |
-
--method vllm vLLM offline LLM() engine with structured outputs. Faster on
|
| 676 |
-
large jobs. Needs the vllm/vllm-openai image.
|
| 677 |
-
|
| 678 |
-
Input (one document per row):
|
| 679 |
-
--image-column COL one image per row (default: image)
|
| 680 |
-
--pdf-column COL PDF bytes per row (multi-page; honors --page-range)
|
| 681 |
-
""",
|
| 682 |
-
)
|
| 683 |
-
parser.add_argument(
|
| 684 |
-
"input_dataset", help="Input dataset ID from the Hugging Face Hub"
|
| 685 |
-
)
|
| 686 |
-
parser.add_argument(
|
| 687 |
-
"output_dataset", help="Output dataset ID for the Hugging Face Hub"
|
| 688 |
-
)
|
| 689 |
-
parser.add_argument(
|
| 690 |
-
"--schema",
|
| 691 |
-
required=True,
|
| 692 |
-
help="JSON Schema: inline JSON, a URL, or a file path",
|
| 693 |
-
)
|
| 694 |
-
parser.add_argument(
|
| 695 |
-
"--image-column", default="image", help="Image column (default: image)"
|
| 696 |
-
)
|
| 697 |
-
parser.add_argument(
|
| 698 |
-
"--pdf-column",
|
| 699 |
-
default=None,
|
| 700 |
-
help="PDF column (bytes/path). Mutually exclusive with --image-column.",
|
| 701 |
-
)
|
| 702 |
-
parser.add_argument(
|
| 703 |
-
"--output-column",
|
| 704 |
-
default="extraction",
|
| 705 |
-
help="Output column (default: extraction)",
|
| 706 |
-
)
|
| 707 |
-
parser.add_argument(
|
| 708 |
-
"--method",
|
| 709 |
-
choices=["hf", "vllm"],
|
| 710 |
-
default="hf",
|
| 711 |
-
help="Inference backend (default: hf)",
|
| 712 |
-
)
|
| 713 |
-
parser.add_argument(
|
| 714 |
-
"--page-range",
|
| 715 |
-
default=None,
|
| 716 |
-
help="Pages to extract from PDFs, e.g. '0-5,7' (PDF column only)",
|
| 717 |
-
)
|
| 718 |
-
parser.add_argument(
|
| 719 |
-
"--split", default="train", help="Dataset split (default: train)"
|
| 720 |
-
)
|
| 721 |
-
parser.add_argument(
|
| 722 |
-
"--max-samples", type=int, help="Limit number of documents (for testing)"
|
| 723 |
-
)
|
| 724 |
-
parser.add_argument(
|
| 725 |
-
"--shuffle", action="store_true", help="Shuffle before sampling"
|
| 726 |
-
)
|
| 727 |
-
parser.add_argument(
|
| 728 |
-
"--seed", type=int, default=42, help="Shuffle seed (default: 42)"
|
| 729 |
-
)
|
| 730 |
-
parser.add_argument(
|
| 731 |
-
"--batch-size",
|
| 732 |
-
type=int,
|
| 733 |
-
default=8,
|
| 734 |
-
help="Documents per generate() call (default: 8; lower for big multi-page PDFs)",
|
| 735 |
-
)
|
| 736 |
-
parser.add_argument(
|
| 737 |
-
"--max-tokens",
|
| 738 |
-
type=int,
|
| 739 |
-
default=None,
|
| 740 |
-
help=f"Max output tokens (default: lift's {DEFAULT_MAX_TOKENS})",
|
| 741 |
-
)
|
| 742 |
-
parser.add_argument(
|
| 743 |
-
"--max-model-len",
|
| 744 |
-
type=int,
|
| 745 |
-
default=32768,
|
| 746 |
-
help="vLLM context length (default: 32768; raise for long multi-page PDFs)",
|
| 747 |
-
)
|
| 748 |
-
parser.add_argument(
|
| 749 |
-
"--gpu-memory-utilization",
|
| 750 |
-
type=float,
|
| 751 |
-
default=0.9,
|
| 752 |
-
help="vLLM GPU memory fraction (default: 0.9)",
|
| 753 |
-
)
|
| 754 |
-
parser.add_argument(
|
| 755 |
-
"--max-images-per-doc",
|
| 756 |
-
type=int,
|
| 757 |
-
default=None,
|
| 758 |
-
help="vLLM images-per-prompt cap (default: 1 for images, 30 for PDFs)",
|
| 759 |
-
)
|
| 760 |
-
parser.add_argument(
|
| 761 |
-
"--model", default=DEFAULT_MODEL, help=f"Model ID (default: {DEFAULT_MODEL})"
|
| 762 |
-
)
|
| 763 |
-
parser.add_argument(
|
| 764 |
-
"--private", action="store_true", help="Make output dataset private"
|
| 765 |
-
)
|
| 766 |
-
parser.add_argument(
|
| 767 |
-
"--config",
|
| 768 |
-
default=None,
|
| 769 |
-
help="Config/subset name when pushing (for benchmarking backends in one repo)",
|
| 770 |
-
)
|
| 771 |
-
parser.add_argument(
|
| 772 |
-
"--create-pr",
|
| 773 |
-
action="store_true",
|
| 774 |
-
help="Push as a pull request instead of directly (for parallel benchmarking)",
|
| 775 |
-
)
|
| 776 |
-
parser.add_argument("--hf-token", help="Hugging Face API token (or set HF_TOKEN)")
|
| 777 |
-
parser.add_argument(
|
| 778 |
-
"--verbose",
|
| 779 |
-
action="store_true",
|
| 780 |
-
help="Log resolved package versions after processing",
|
| 781 |
-
)
|
| 782 |
-
|
| 783 |
-
args = parser.parse_args()
|
| 784 |
-
|
| 785 |
-
if args.pdf_column and args.image_column != "image":
|
| 786 |
-
parser.error("--image-column and --pdf-column are mutually exclusive.")
|
| 787 |
-
|
| 788 |
-
main(
|
| 789 |
-
input_dataset=args.input_dataset,
|
| 790 |
-
output_dataset=args.output_dataset,
|
| 791 |
-
schema_arg=args.schema,
|
| 792 |
-
image_column=args.image_column,
|
| 793 |
-
pdf_column=args.pdf_column,
|
| 794 |
-
output_column=args.output_column,
|
| 795 |
-
method=args.method,
|
| 796 |
-
page_range=args.page_range,
|
| 797 |
-
split=args.split,
|
| 798 |
-
max_samples=args.max_samples,
|
| 799 |
-
shuffle=args.shuffle,
|
| 800 |
-
seed=args.seed,
|
| 801 |
-
batch_size=args.batch_size,
|
| 802 |
-
max_tokens=args.max_tokens,
|
| 803 |
-
max_model_len=args.max_model_len,
|
| 804 |
-
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 805 |
-
max_images_per_doc=args.max_images_per_doc,
|
| 806 |
-
model=args.model,
|
| 807 |
-
private=args.private,
|
| 808 |
-
config=args.config,
|
| 809 |
-
create_pr=args.create_pr,
|
| 810 |
-
hf_token=args.hf_token,
|
| 811 |
-
verbose=args.verbose,
|
| 812 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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,1197 +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: Optional[Image.Image] # None for an unreadable row (placeholder)
|
| 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 |
-
failed = 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 |
-
# Still yield a placeholder so the output row stays aligned with
|
| 244 |
-
# the source row (the dataset sink writes layouts positionally).
|
| 245 |
-
failed += 1
|
| 246 |
-
logger.warning(
|
| 247 |
-
f"Unreadable image at row {i}: "
|
| 248 |
-
f"{type(e).__name__}: {e} — writing empty layout"
|
| 249 |
-
)
|
| 250 |
-
yield SourceItem(
|
| 251 |
-
key=f"row-{i:08d}",
|
| 252 |
-
image=None,
|
| 253 |
-
extras={"failed": True},
|
| 254 |
-
)
|
| 255 |
-
continue
|
| 256 |
-
yield SourceItem(
|
| 257 |
-
key=f"row-{i:08d}",
|
| 258 |
-
image=image,
|
| 259 |
-
extras={}, # original schema is preserved by the sink via the dataset ref
|
| 260 |
-
)
|
| 261 |
-
if failed:
|
| 262 |
-
logger.info(f"{failed} unreadable image(s) written as empty layouts")
|
| 263 |
-
|
| 264 |
-
return gen(), total, ds
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
SOURCE_PATHS_SNAPSHOT = "_source_paths.json"
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
def _bucket_snapshot_path(output_url: str) -> Tuple[str, str]:
|
| 271 |
-
"""Return (bucket_id, key) for the source-paths snapshot inside an output bucket."""
|
| 272 |
-
out_bucket_id, out_prefix = parse_bucket_url(output_url)
|
| 273 |
-
snapshot_key = (
|
| 274 |
-
f"{out_prefix}/{SOURCE_PATHS_SNAPSHOT}".lstrip("/")
|
| 275 |
-
if out_prefix
|
| 276 |
-
else SOURCE_PATHS_SNAPSHOT
|
| 277 |
-
)
|
| 278 |
-
return out_bucket_id, snapshot_key
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
def iter_bucket_images(
|
| 282 |
-
bucket_url: str,
|
| 283 |
-
shuffle: bool,
|
| 284 |
-
seed: int,
|
| 285 |
-
max_samples: Optional[int],
|
| 286 |
-
hf_token: Optional[str],
|
| 287 |
-
output_url: Optional[str] = None,
|
| 288 |
-
) -> Tuple[Iterator[SourceItem], int]:
|
| 289 |
-
"""Glob image files under a bucket prefix and stream them via HfFileSystem.
|
| 290 |
-
|
| 291 |
-
If `output_url` is a bucket, the resolved source-path list is snapshotted to
|
| 292 |
-
`<output>/_source_paths.json` on first run. Subsequent runs against the same
|
| 293 |
-
output prefix reuse that snapshot, so resume stays consistent even if the
|
| 294 |
-
source bucket grows or `--shuffle`/`--max-samples` would otherwise pick a
|
| 295 |
-
different subset on the second run.
|
| 296 |
-
"""
|
| 297 |
-
from huggingface_hub import HfApi, HfFileSystem
|
| 298 |
-
|
| 299 |
-
bucket_id, prefix = parse_bucket_url(bucket_url)
|
| 300 |
-
fs = HfFileSystem(token=hf_token)
|
| 301 |
-
base = f"{BUCKET_PREFIX}{bucket_id}/{prefix}".rstrip("/")
|
| 302 |
-
|
| 303 |
-
snapshot_bucket_id: Optional[str] = None
|
| 304 |
-
snapshot_key: Optional[str] = None
|
| 305 |
-
cached_paths: Optional[List[str]] = None
|
| 306 |
-
|
| 307 |
-
if output_url and is_bucket_url(output_url):
|
| 308 |
-
snapshot_bucket_id, snapshot_key = _bucket_snapshot_path(output_url)
|
| 309 |
-
snapshot_url = f"{BUCKET_PREFIX}{snapshot_bucket_id}/{snapshot_key}"
|
| 310 |
-
try:
|
| 311 |
-
with fs.open(snapshot_url, "rb") as f:
|
| 312 |
-
snapshot = json.load(f)
|
| 313 |
-
if snapshot.get("source_url") != bucket_url:
|
| 314 |
-
logger.warning(
|
| 315 |
-
f"Output prefix already has a snapshot referencing a "
|
| 316 |
-
f"different source ({snapshot.get('source_url')!r} vs "
|
| 317 |
-
f"{bucket_url!r}). Ignoring and re-listing."
|
| 318 |
-
)
|
| 319 |
-
else:
|
| 320 |
-
cached_paths = snapshot["paths"]
|
| 321 |
-
logger.info(
|
| 322 |
-
f"Reusing existing snapshot of {len(cached_paths)} source paths "
|
| 323 |
-
f"(written {snapshot.get('created_at', 'unknown')})"
|
| 324 |
-
)
|
| 325 |
-
except FileNotFoundError:
|
| 326 |
-
pass
|
| 327 |
-
except Exception as e:
|
| 328 |
-
logger.warning(f"Could not read existing snapshot ({e}); re-listing.")
|
| 329 |
-
|
| 330 |
-
if cached_paths is not None:
|
| 331 |
-
all_paths = cached_paths
|
| 332 |
-
else:
|
| 333 |
-
logger.info(f"Listing images under {base}")
|
| 334 |
-
all_paths = []
|
| 335 |
-
try:
|
| 336 |
-
for entry in fs.find(base, detail=False):
|
| 337 |
-
ext = Path(entry).suffix.lower()
|
| 338 |
-
if ext in IMAGE_EXTENSIONS:
|
| 339 |
-
all_paths.append(entry)
|
| 340 |
-
except FileNotFoundError as e:
|
| 341 |
-
raise ValueError(f"Bucket prefix not found: {base}") from e
|
| 342 |
-
|
| 343 |
-
if not all_paths:
|
| 344 |
-
raise ValueError(
|
| 345 |
-
f"No image files (any of {sorted(IMAGE_EXTENSIONS)}) under {base}"
|
| 346 |
-
)
|
| 347 |
-
|
| 348 |
-
all_paths.sort()
|
| 349 |
-
if shuffle:
|
| 350 |
-
rng = np.random.default_rng(seed)
|
| 351 |
-
rng.shuffle(all_paths)
|
| 352 |
-
if max_samples:
|
| 353 |
-
all_paths = all_paths[:max_samples]
|
| 354 |
-
|
| 355 |
-
# Persist the chosen list so resume runs see exactly this set.
|
| 356 |
-
if snapshot_bucket_id is not None and snapshot_key is not None:
|
| 357 |
-
api = HfApi(token=hf_token)
|
| 358 |
-
payload = {
|
| 359 |
-
"source_url": bucket_url,
|
| 360 |
-
"shuffle": shuffle,
|
| 361 |
-
"seed": seed,
|
| 362 |
-
"max_samples": max_samples,
|
| 363 |
-
"created_at": datetime.now(timezone.utc).isoformat(),
|
| 364 |
-
"paths": all_paths,
|
| 365 |
-
}
|
| 366 |
-
api.batch_bucket_files(
|
| 367 |
-
snapshot_bucket_id,
|
| 368 |
-
add=[(json.dumps(payload).encode(), snapshot_key)],
|
| 369 |
-
token=hf_token,
|
| 370 |
-
)
|
| 371 |
-
logger.info(
|
| 372 |
-
f"Wrote source-path snapshot ({len(all_paths)} paths) to "
|
| 373 |
-
f"hf://buckets/{snapshot_bucket_id}/{snapshot_key}"
|
| 374 |
-
)
|
| 375 |
-
|
| 376 |
-
total = len(all_paths)
|
| 377 |
-
logger.info(f"Found {total} images in bucket")
|
| 378 |
-
|
| 379 |
-
def key_for(path: str) -> str:
|
| 380 |
-
# Use the full bucket path (`buckets/<id>/<rel>`) as returned by
|
| 381 |
-
# fs.find. This is stable across reruns (so resume works), and the
|
| 382 |
-
# stored value in `source_path` is fully addressable — open via
|
| 383 |
-
# HfFileSystem directly with `hf://` re-prepended.
|
| 384 |
-
return path
|
| 385 |
-
|
| 386 |
-
def gen() -> Iterator[SourceItem]:
|
| 387 |
-
skipped = 0
|
| 388 |
-
for path in all_paths:
|
| 389 |
-
try:
|
| 390 |
-
with fs.open(path, "rb") as f:
|
| 391 |
-
data = f.read()
|
| 392 |
-
image = to_pil(data)
|
| 393 |
-
except (UnidentifiedImageError, OSError) as e:
|
| 394 |
-
skipped += 1
|
| 395 |
-
logger.warning(
|
| 396 |
-
f"Skipping unreadable image {path}: "
|
| 397 |
-
f"{type(e).__name__}: {e}"
|
| 398 |
-
)
|
| 399 |
-
continue
|
| 400 |
-
yield SourceItem(
|
| 401 |
-
key=key_for(path),
|
| 402 |
-
image=image,
|
| 403 |
-
extras={"__source_path": key_for(path)},
|
| 404 |
-
)
|
| 405 |
-
if skipped:
|
| 406 |
-
logger.info(f"Skipped {skipped} unreadable image(s) total")
|
| 407 |
-
|
| 408 |
-
return gen(), total
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
# ---------------------------------------------------------------------------
|
| 412 |
-
# Sinks
|
| 413 |
-
# ---------------------------------------------------------------------------
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
class DatasetRepoSink:
|
| 417 |
-
"""Buffer all results in memory, push once at end with dataset card + inference_info.
|
| 418 |
-
|
| 419 |
-
Two modes:
|
| 420 |
-
- `original_dataset` provided (dataset-repo source): preserve the source
|
| 421 |
-
schema (including Image-type columns) and just `add_column("layout", ...)`.
|
| 422 |
-
- `original_dataset` is None (bucket-image source): build a Dataset from
|
| 423 |
-
collected rows containing __source_path + layout.
|
| 424 |
-
"""
|
| 425 |
-
|
| 426 |
-
def __init__(
|
| 427 |
-
self,
|
| 428 |
-
repo_id: str,
|
| 429 |
-
*,
|
| 430 |
-
hf_token: Optional[str],
|
| 431 |
-
private: bool,
|
| 432 |
-
config: Optional[str],
|
| 433 |
-
create_pr: bool,
|
| 434 |
-
source_id: str,
|
| 435 |
-
original_dataset=None,
|
| 436 |
-
):
|
| 437 |
-
self.repo_id = repo_id
|
| 438 |
-
self.hf_token = hf_token
|
| 439 |
-
self.private = private
|
| 440 |
-
self.config = config
|
| 441 |
-
self.create_pr = create_pr
|
| 442 |
-
self.source_id = source_id
|
| 443 |
-
self.original_dataset = original_dataset
|
| 444 |
-
# Used when original_dataset is None: row-by-row buffer.
|
| 445 |
-
self._rows: List[Dict[str, Any]] = []
|
| 446 |
-
# Used when original_dataset is set: ordered layouts aligned with dataset rows.
|
| 447 |
-
self._layouts: List[str] = []
|
| 448 |
-
|
| 449 |
-
@property
|
| 450 |
-
def kind(self) -> str:
|
| 451 |
-
return "dataset"
|
| 452 |
-
|
| 453 |
-
def already_done(self) -> set:
|
| 454 |
-
return set() # dataset sink does a single push, no resume
|
| 455 |
-
|
| 456 |
-
def write(self, key: str, layout: List[Dict[str, Any]], extras: Dict[str, Any]) -> None:
|
| 457 |
-
layout_json = json.dumps(layout, ensure_ascii=False)
|
| 458 |
-
if self.original_dataset is not None:
|
| 459 |
-
self._layouts.append(layout_json)
|
| 460 |
-
return
|
| 461 |
-
row = {"__source_key": key, "layout": layout_json}
|
| 462 |
-
for k, v in extras.items():
|
| 463 |
-
if isinstance(v, (str, int, float, bool)) or v is None:
|
| 464 |
-
row[k] = v
|
| 465 |
-
self._rows.append(row)
|
| 466 |
-
|
| 467 |
-
def finalize(self, model_id: str, args_dict: Dict[str, Any]) -> None:
|
| 468 |
-
from datasets import Dataset
|
| 469 |
-
|
| 470 |
-
if self.original_dataset is not None:
|
| 471 |
-
if len(self._layouts) != len(self.original_dataset):
|
| 472 |
-
logger.warning(
|
| 473 |
-
f"Layout count ({len(self._layouts)}) != dataset rows "
|
| 474 |
-
f"({len(self.original_dataset)}); padding with empty layouts."
|
| 475 |
-
)
|
| 476 |
-
# Pad to keep add_column happy.
|
| 477 |
-
while len(self._layouts) < len(self.original_dataset):
|
| 478 |
-
self._layouts.append("[]")
|
| 479 |
-
ds = self.original_dataset.add_column("layout", self._layouts)
|
| 480 |
-
else:
|
| 481 |
-
if not self._rows:
|
| 482 |
-
logger.warning("No rows produced; nothing to push.")
|
| 483 |
-
return
|
| 484 |
-
ds = Dataset.from_list(self._rows)
|
| 485 |
-
if "__source_key" in ds.column_names:
|
| 486 |
-
ds = ds.rename_column("__source_key", "source_path")
|
| 487 |
-
|
| 488 |
-
inference_entry = build_inference_entry(model_id, args_dict)
|
| 489 |
-
|
| 490 |
-
if "inference_info" in ds.column_names:
|
| 491 |
-
logger.info("Updating existing inference_info column")
|
| 492 |
-
|
| 493 |
-
def _update(example):
|
| 494 |
-
try:
|
| 495 |
-
existing = (
|
| 496 |
-
json.loads(example["inference_info"])
|
| 497 |
-
if example["inference_info"]
|
| 498 |
-
else []
|
| 499 |
-
)
|
| 500 |
-
except (json.JSONDecodeError, TypeError):
|
| 501 |
-
existing = []
|
| 502 |
-
existing.append(inference_entry)
|
| 503 |
-
return {"inference_info": json.dumps(existing)}
|
| 504 |
-
|
| 505 |
-
ds = ds.map(_update)
|
| 506 |
-
else:
|
| 507 |
-
ds = ds.add_column(
|
| 508 |
-
"inference_info", [json.dumps([inference_entry])] * len(ds)
|
| 509 |
-
)
|
| 510 |
-
|
| 511 |
-
logger.info(f"Pushing {len(ds)} rows to {self.repo_id}")
|
| 512 |
-
push_kwargs = {
|
| 513 |
-
"private": self.private,
|
| 514 |
-
"token": self.hf_token,
|
| 515 |
-
"max_shard_size": "500MB",
|
| 516 |
-
"create_pr": self.create_pr,
|
| 517 |
-
"commit_message": f"Add PP-DocLayout layout predictions ({len(ds)} samples)"
|
| 518 |
-
+ (f" [{self.config}]" if self.config else ""),
|
| 519 |
-
}
|
| 520 |
-
if self.config:
|
| 521 |
-
push_kwargs["config_name"] = self.config
|
| 522 |
-
|
| 523 |
-
max_retries = 3
|
| 524 |
-
for attempt in range(1, max_retries + 1):
|
| 525 |
-
try:
|
| 526 |
-
if attempt > 1:
|
| 527 |
-
logger.warning("Disabling XET (fallback to HTTP upload)")
|
| 528 |
-
os.environ["HF_HUB_DISABLE_XET"] = "1"
|
| 529 |
-
ds.push_to_hub(self.repo_id, **push_kwargs)
|
| 530 |
-
break
|
| 531 |
-
except Exception as e:
|
| 532 |
-
logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
|
| 533 |
-
if attempt == max_retries:
|
| 534 |
-
logger.error("All upload attempts failed.")
|
| 535 |
-
raise
|
| 536 |
-
time.sleep(30 * (2 ** (attempt - 1)))
|
| 537 |
-
|
| 538 |
-
# Dataset card
|
| 539 |
-
from huggingface_hub import DatasetCard
|
| 540 |
-
|
| 541 |
-
card = DatasetCard(
|
| 542 |
-
create_dataset_card(
|
| 543 |
-
source=self.source_id,
|
| 544 |
-
model_name=args_dict["model_name"],
|
| 545 |
-
num_samples=len(ds),
|
| 546 |
-
processing_time=args_dict["processing_time"],
|
| 547 |
-
output_column="layout",
|
| 548 |
-
threshold=args_dict["threshold"],
|
| 549 |
-
layout_nms=args_dict["layout_nms"],
|
| 550 |
-
)
|
| 551 |
-
)
|
| 552 |
-
card.push_to_hub(self.repo_id, token=self.hf_token)
|
| 553 |
-
logger.info(
|
| 554 |
-
f"Done: https://huggingface.co/datasets/{self.repo_id}"
|
| 555 |
-
)
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
class BucketShardSink:
|
| 559 |
-
"""Write incremental parquet shards to a bucket prefix. Resumable."""
|
| 560 |
-
|
| 561 |
-
METADATA_FILE = "_metadata.json"
|
| 562 |
-
SHARD_PATTERN = "shard-{:05d}.parquet"
|
| 563 |
-
|
| 564 |
-
def __init__(
|
| 565 |
-
self,
|
| 566 |
-
bucket_url: str,
|
| 567 |
-
*,
|
| 568 |
-
hf_token: Optional[str],
|
| 569 |
-
shard_size: int,
|
| 570 |
-
include_images: bool,
|
| 571 |
-
resume: bool,
|
| 572 |
-
source_id: str,
|
| 573 |
-
):
|
| 574 |
-
from huggingface_hub import HfApi, HfFileSystem, create_bucket
|
| 575 |
-
|
| 576 |
-
self.bucket_url = bucket_url
|
| 577 |
-
self.bucket_id, self.prefix = parse_bucket_url(bucket_url)
|
| 578 |
-
self.hf_token = hf_token
|
| 579 |
-
self.shard_size = shard_size
|
| 580 |
-
self.include_images = include_images
|
| 581 |
-
self.resume = resume
|
| 582 |
-
self.source_id = source_id
|
| 583 |
-
|
| 584 |
-
self._api = HfApi(token=hf_token)
|
| 585 |
-
self._fs = HfFileSystem(token=hf_token)
|
| 586 |
-
|
| 587 |
-
# Make sure the bucket exists. Path inside the bucket is created lazily on first write.
|
| 588 |
-
try:
|
| 589 |
-
create_bucket(self.bucket_id, exist_ok=True, token=hf_token)
|
| 590 |
-
except Exception as e:
|
| 591 |
-
# If we don't have create rights but the bucket already exists, that's fine.
|
| 592 |
-
logger.warning(f"create_bucket('{self.bucket_id}') warning: {e}")
|
| 593 |
-
|
| 594 |
-
self._buffer: List[Dict[str, Any]] = []
|
| 595 |
-
self._next_shard_idx = self._discover_next_shard_idx()
|
| 596 |
-
self._completed_keys = self._discover_completed_keys() if resume else set()
|
| 597 |
-
if self._completed_keys:
|
| 598 |
-
logger.info(
|
| 599 |
-
f"Resume: found {len(self._completed_keys)} already-processed keys, will skip them"
|
| 600 |
-
)
|
| 601 |
-
|
| 602 |
-
@property
|
| 603 |
-
def kind(self) -> str:
|
| 604 |
-
return "bucket"
|
| 605 |
-
|
| 606 |
-
def already_done(self) -> set:
|
| 607 |
-
return self._completed_keys
|
| 608 |
-
|
| 609 |
-
# --- internal helpers ---
|
| 610 |
-
|
| 611 |
-
def _shard_path(self, idx: int) -> str:
|
| 612 |
-
return self._join(self.SHARD_PATTERN.format(idx))
|
| 613 |
-
|
| 614 |
-
def _join(self, name: str) -> str:
|
| 615 |
-
return f"{self.prefix}/{name}".lstrip("/") if self.prefix else name
|
| 616 |
-
|
| 617 |
-
def _list_existing_shards(self) -> List[str]:
|
| 618 |
-
try:
|
| 619 |
-
tree = self._api.list_bucket_tree(
|
| 620 |
-
self.bucket_id, prefix=self.prefix or None, recursive=True
|
| 621 |
-
)
|
| 622 |
-
except Exception:
|
| 623 |
-
return []
|
| 624 |
-
shards: List[str] = []
|
| 625 |
-
for item in tree:
|
| 626 |
-
path = getattr(item, "path", None)
|
| 627 |
-
ftype = getattr(item, "type", None)
|
| 628 |
-
if not path or ftype not in (None, "file"):
|
| 629 |
-
continue
|
| 630 |
-
base = Path(path).name
|
| 631 |
-
if base.startswith("shard-") and base.endswith(".parquet"):
|
| 632 |
-
shards.append(path)
|
| 633 |
-
return sorted(shards)
|
| 634 |
-
|
| 635 |
-
def _discover_next_shard_idx(self) -> int:
|
| 636 |
-
shards = self._list_existing_shards()
|
| 637 |
-
max_idx = -1
|
| 638 |
-
for s in shards:
|
| 639 |
-
stem = Path(s).stem # shard-00007
|
| 640 |
-
try:
|
| 641 |
-
max_idx = max(max_idx, int(stem.split("-")[-1]))
|
| 642 |
-
except ValueError:
|
| 643 |
-
continue
|
| 644 |
-
return max_idx + 1
|
| 645 |
-
|
| 646 |
-
def _discover_completed_keys(self) -> set:
|
| 647 |
-
import pyarrow.parquet as pq
|
| 648 |
-
|
| 649 |
-
keys: set = set()
|
| 650 |
-
for shard_path in self._list_existing_shards():
|
| 651 |
-
full = f"{BUCKET_PREFIX}{self.bucket_id}/{shard_path}"
|
| 652 |
-
try:
|
| 653 |
-
with self._fs.open(full, "rb") as f:
|
| 654 |
-
table = pq.read_table(f, columns=["__source_key"])
|
| 655 |
-
keys.update(table.column("__source_key").to_pylist())
|
| 656 |
-
except Exception as e:
|
| 657 |
-
logger.warning(f"Could not read keys from {shard_path}: {e}")
|
| 658 |
-
return keys
|
| 659 |
-
|
| 660 |
-
def _flush(self) -> None:
|
| 661 |
-
if not self._buffer:
|
| 662 |
-
return
|
| 663 |
-
import pyarrow as pa
|
| 664 |
-
import pyarrow.parquet as pq
|
| 665 |
-
|
| 666 |
-
# Build a stable schema. Skip the image column if not requested.
|
| 667 |
-
columns = ["__source_key", "layout"]
|
| 668 |
-
if self.include_images:
|
| 669 |
-
columns.append("__image_bytes")
|
| 670 |
-
# Carry through any extra string-coercible fields (e.g. __source_path).
|
| 671 |
-
extra_keys = sorted(
|
| 672 |
-
{k for row in self._buffer for k in row.keys() if k not in columns}
|
| 673 |
-
)
|
| 674 |
-
columns.extend(extra_keys)
|
| 675 |
-
|
| 676 |
-
table_dict = {c: [row.get(c) for row in self._buffer] for c in columns}
|
| 677 |
-
# pyarrow infers types from python objects; strings/bytes/lists handled fine.
|
| 678 |
-
table = pa.Table.from_pydict(table_dict)
|
| 679 |
-
|
| 680 |
-
buf = io.BytesIO()
|
| 681 |
-
pq.write_table(table, buf, compression="zstd")
|
| 682 |
-
data = buf.getvalue()
|
| 683 |
-
|
| 684 |
-
shard_remote = self._shard_path(self._next_shard_idx)
|
| 685 |
-
logger.info(
|
| 686 |
-
f"Writing shard {self._next_shard_idx} ({len(self._buffer)} rows, "
|
| 687 |
-
f"{len(data) / 1024 / 1024:.1f} MiB) to {shard_remote}"
|
| 688 |
-
)
|
| 689 |
-
self._api.batch_bucket_files(
|
| 690 |
-
self.bucket_id, add=[(data, shard_remote)], token=self.hf_token
|
| 691 |
-
)
|
| 692 |
-
self._next_shard_idx += 1
|
| 693 |
-
self._buffer.clear()
|
| 694 |
-
|
| 695 |
-
def write(self, key: str, layout: List[Dict[str, Any]], extras: Dict[str, Any]) -> None:
|
| 696 |
-
row: Dict[str, Any] = {
|
| 697 |
-
"__source_key": key,
|
| 698 |
-
"layout": json.dumps(layout, ensure_ascii=False),
|
| 699 |
-
}
|
| 700 |
-
if self.include_images and "__image_bytes" in extras:
|
| 701 |
-
row["__image_bytes"] = extras["__image_bytes"]
|
| 702 |
-
# Pass through string/numeric extras (skip raw PIL Image objects which
|
| 703 |
-
# the dataset source never injects directly into extras anyway).
|
| 704 |
-
for k, v in extras.items():
|
| 705 |
-
if k in row or k == "__image_bytes":
|
| 706 |
-
continue
|
| 707 |
-
if isinstance(v, (str, int, float, bool)) or v is None:
|
| 708 |
-
row[k] = v
|
| 709 |
-
self._buffer.append(row)
|
| 710 |
-
if len(self._buffer) >= self.shard_size:
|
| 711 |
-
self._flush()
|
| 712 |
-
|
| 713 |
-
def finalize(self, model_id: str, args_dict: Dict[str, Any]) -> None:
|
| 714 |
-
# Flush trailing rows.
|
| 715 |
-
self._flush()
|
| 716 |
-
# Write/update the metadata file alongside the shards.
|
| 717 |
-
meta = {
|
| 718 |
-
"model_id": model_id,
|
| 719 |
-
"model_name": args_dict["model_name"],
|
| 720 |
-
"task_mode": "layout-detection",
|
| 721 |
-
"source": self.source_id,
|
| 722 |
-
"threshold": args_dict["threshold"],
|
| 723 |
-
"layout_nms": args_dict["layout_nms"],
|
| 724 |
-
"shard_size": args_dict["shard_size"],
|
| 725 |
-
"include_images": self.include_images,
|
| 726 |
-
"last_run_at": datetime.now(timezone.utc).isoformat(),
|
| 727 |
-
"processing_time": args_dict.get("processing_time"),
|
| 728 |
-
}
|
| 729 |
-
meta_bytes = json.dumps(meta, indent=2).encode("utf-8")
|
| 730 |
-
meta_path = self._join(self.METADATA_FILE)
|
| 731 |
-
self._api.batch_bucket_files(
|
| 732 |
-
self.bucket_id, add=[(meta_bytes, meta_path)], token=self.hf_token
|
| 733 |
-
)
|
| 734 |
-
logger.info(
|
| 735 |
-
f"Done: https://huggingface.co/buckets/{self.bucket_id}"
|
| 736 |
-
+ (f"/{self.prefix}" if self.prefix else "")
|
| 737 |
-
)
|
| 738 |
-
|
| 739 |
-
|
| 740 |
-
# ---------------------------------------------------------------------------
|
| 741 |
-
# inference_info + dataset card
|
| 742 |
-
# ---------------------------------------------------------------------------
|
| 743 |
-
|
| 744 |
-
|
| 745 |
-
def build_inference_entry(model_id: str, args_dict: Dict[str, Any]) -> Dict[str, Any]:
|
| 746 |
-
return {
|
| 747 |
-
"model_id": "PaddlePaddle/" + args_dict["model_name"],
|
| 748 |
-
"model_name": args_dict["model_name"],
|
| 749 |
-
"model_size": MODEL_SIZES.get(args_dict["model_name"], "unknown"),
|
| 750 |
-
"task_mode": "layout-detection",
|
| 751 |
-
"column_name": "layout",
|
| 752 |
-
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 753 |
-
"threshold": args_dict["threshold"],
|
| 754 |
-
"layout_nms": args_dict["layout_nms"],
|
| 755 |
-
"backend": "paddleocr",
|
| 756 |
-
}
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
def create_dataset_card(
|
| 760 |
-
source: str,
|
| 761 |
-
model_name: str,
|
| 762 |
-
num_samples: int,
|
| 763 |
-
processing_time: str,
|
| 764 |
-
output_column: str,
|
| 765 |
-
threshold: float,
|
| 766 |
-
layout_nms: bool,
|
| 767 |
-
) -> str:
|
| 768 |
-
"""Render the dataset card markdown for the dataset-repo sink."""
|
| 769 |
-
if is_bucket_url(source):
|
| 770 |
-
source_link = f"[{source}]({source})"
|
| 771 |
-
else:
|
| 772 |
-
source_link = f"[{source}](https://huggingface.co/datasets/{source})"
|
| 773 |
-
|
| 774 |
-
return f"""---
|
| 775 |
-
tags:
|
| 776 |
-
- layout-detection
|
| 777 |
-
- document-processing
|
| 778 |
-
- paddleocr
|
| 779 |
-
- pp-doclayout
|
| 780 |
-
- uv-script
|
| 781 |
-
- generated
|
| 782 |
-
viewer: false
|
| 783 |
-
---
|
| 784 |
-
|
| 785 |
-
# Layout detection with {model_name}
|
| 786 |
-
|
| 787 |
-
Bounding-box layout predictions for images from {source_link}, produced by
|
| 788 |
-
PaddleOCR's [{model_name}](https://huggingface.co/PaddlePaddle/{model_name}).
|
| 789 |
-
|
| 790 |
-
## Processing details
|
| 791 |
-
|
| 792 |
-
- **Source**: {source_link}
|
| 793 |
-
- **Model**: PaddlePaddle/{model_name} ({MODEL_SIZES.get(model_name, "unknown")})
|
| 794 |
-
- **Samples**: {num_samples:,}
|
| 795 |
-
- **Processing time**: {processing_time}
|
| 796 |
-
- **Processing date**: {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}
|
| 797 |
-
- **Confidence threshold**: {threshold}
|
| 798 |
-
- **Layout NMS**: {"on" if layout_nms else "off"}
|
| 799 |
-
- **Output column**: `{output_column}` (JSON-encoded list of detections)
|
| 800 |
-
|
| 801 |
-
## Schema
|
| 802 |
-
|
| 803 |
-
Each row contains the original columns plus:
|
| 804 |
-
|
| 805 |
-
- `{output_column}`: JSON string. List of detections:
|
| 806 |
-
```json
|
| 807 |
-
[
|
| 808 |
-
{{"bbox": [x1, y1, x2, y2], "label": "text", "score": 0.97, "cls_id": 2}},
|
| 809 |
-
{{"bbox": [x1, y1, x2, y2], "label": "table", "score": 0.92, "cls_id": 5}}
|
| 810 |
-
]
|
| 811 |
-
```
|
| 812 |
-
Coordinates are in **original input-image pixel space** (top-left origin,
|
| 813 |
-
`[xmin, ymin, xmax, ymax]`).
|
| 814 |
-
- `inference_info`: JSON list tracking every model that has been applied to
|
| 815 |
-
this dataset (appended on each run).
|
| 816 |
-
|
| 817 |
-
## Usage
|
| 818 |
-
|
| 819 |
-
```python
|
| 820 |
-
import json
|
| 821 |
-
from datasets import load_dataset
|
| 822 |
-
|
| 823 |
-
ds = load_dataset("{{output_dataset_id}}", split="train")
|
| 824 |
-
detections = json.loads(ds[0]["{output_column}"])
|
| 825 |
-
for det in detections:
|
| 826 |
-
print(det["label"], det["score"], det["bbox"])
|
| 827 |
-
```
|
| 828 |
-
|
| 829 |
-
## Reproduction
|
| 830 |
-
|
| 831 |
-
```bash
|
| 832 |
-
hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
|
| 833 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/pp-doclayout.py \\
|
| 834 |
-
{source} <output> --model-name {model_name}
|
| 835 |
-
```
|
| 836 |
-
|
| 837 |
-
Generated with [UV Scripts](https://huggingface.co/uv-scripts).
|
| 838 |
-
"""
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
# ---------------------------------------------------------------------------
|
| 842 |
-
# Main
|
| 843 |
-
# ---------------------------------------------------------------------------
|
| 844 |
-
|
| 845 |
-
|
| 846 |
-
def resolve_device(device: str) -> str:
|
| 847 |
-
if device == "gpu":
|
| 848 |
-
try:
|
| 849 |
-
import paddle # noqa: F401
|
| 850 |
-
|
| 851 |
-
if paddle.device.is_compiled_with_cuda() and paddle.device.cuda.device_count() > 0:
|
| 852 |
-
logger.info(
|
| 853 |
-
f"GPU available: {paddle.device.cuda.device_count()} device(s)"
|
| 854 |
-
)
|
| 855 |
-
return "gpu"
|
| 856 |
-
logger.warning("No CUDA GPU detected; falling back to CPU.")
|
| 857 |
-
return "cpu"
|
| 858 |
-
except Exception as e:
|
| 859 |
-
logger.warning(f"GPU check failed ({e}); falling back to CPU.")
|
| 860 |
-
return "cpu"
|
| 861 |
-
return device
|
| 862 |
-
|
| 863 |
-
|
| 864 |
-
def main(args: argparse.Namespace) -> None:
|
| 865 |
-
from huggingface_hub import login
|
| 866 |
-
|
| 867 |
-
start_time = datetime.now()
|
| 868 |
-
hf_token = args.hf_token or os.environ.get("HF_TOKEN")
|
| 869 |
-
if hf_token:
|
| 870 |
-
login(token=hf_token)
|
| 871 |
-
|
| 872 |
-
device = resolve_device(args.device)
|
| 873 |
-
|
| 874 |
-
# ---------- source ----------
|
| 875 |
-
original_dataset = None
|
| 876 |
-
if is_bucket_url(args.input_source):
|
| 877 |
-
src_iter, total = iter_bucket_images(
|
| 878 |
-
args.input_source,
|
| 879 |
-
shuffle=args.shuffle,
|
| 880 |
-
seed=args.seed,
|
| 881 |
-
max_samples=args.max_samples,
|
| 882 |
-
hf_token=hf_token,
|
| 883 |
-
output_url=args.output_target,
|
| 884 |
-
)
|
| 885 |
-
else:
|
| 886 |
-
src_iter, total, original_dataset = iter_dataset_images(
|
| 887 |
-
args.input_source,
|
| 888 |
-
image_column=args.image_column,
|
| 889 |
-
split=args.split,
|
| 890 |
-
shuffle=args.shuffle,
|
| 891 |
-
seed=args.seed,
|
| 892 |
-
max_samples=args.max_samples,
|
| 893 |
-
)
|
| 894 |
-
|
| 895 |
-
# ---------- sink ----------
|
| 896 |
-
if is_bucket_url(args.output_target):
|
| 897 |
-
sink: Union[BucketShardSink, DatasetRepoSink] = BucketShardSink(
|
| 898 |
-
args.output_target,
|
| 899 |
-
hf_token=hf_token,
|
| 900 |
-
shard_size=args.shard_size,
|
| 901 |
-
include_images=args.include_images,
|
| 902 |
-
resume=not args.no_resume,
|
| 903 |
-
source_id=args.input_source,
|
| 904 |
-
)
|
| 905 |
-
else:
|
| 906 |
-
sink = DatasetRepoSink(
|
| 907 |
-
args.output_target,
|
| 908 |
-
hf_token=hf_token,
|
| 909 |
-
private=args.private,
|
| 910 |
-
config=args.config,
|
| 911 |
-
create_pr=args.create_pr,
|
| 912 |
-
source_id=args.input_source,
|
| 913 |
-
original_dataset=original_dataset,
|
| 914 |
-
)
|
| 915 |
-
|
| 916 |
-
completed = sink.already_done()
|
| 917 |
-
|
| 918 |
-
# ---------- model ----------
|
| 919 |
-
if args.model_name not in VALID_MODELS:
|
| 920 |
-
raise ValueError(
|
| 921 |
-
f"Invalid model {args.model_name!r}. Choose from: {VALID_MODELS}"
|
| 922 |
-
)
|
| 923 |
-
logger.info(f"Loading PaddleOCR LayoutDetection model: {args.model_name} on {device}")
|
| 924 |
-
# PaddleX gates `import cv2` at module load time on
|
| 925 |
-
# `is_dep_available("opencv-contrib-python")`, which checks
|
| 926 |
-
# `importlib.metadata.version(...)`. We ship `opencv-contrib-python-headless`
|
| 927 |
-
# (same `cv2`, no system libGL.so.1 needed) — but that's a different
|
| 928 |
-
# distribution name, so the gate fails and `cv2` is never bound, causing
|
| 929 |
-
# NameErrors deep inside paddlex modules. Patch the metadata lookup to
|
| 930 |
-
# alias the GUI cv2 distros to the headless variant before importing
|
| 931 |
-
# paddleocr; this lets paddlex's own `import cv2` succeed naturally.
|
| 932 |
-
import importlib.metadata as _metadata
|
| 933 |
-
|
| 934 |
-
_orig_metadata_version = _metadata.version
|
| 935 |
-
|
| 936 |
-
def _patched_metadata_version(dep_name):
|
| 937 |
-
if dep_name in ("opencv-contrib-python", "opencv-python"):
|
| 938 |
-
for headless_alias in (
|
| 939 |
-
"opencv-contrib-python-headless",
|
| 940 |
-
"opencv-python-headless",
|
| 941 |
-
):
|
| 942 |
-
try:
|
| 943 |
-
return _orig_metadata_version(headless_alias)
|
| 944 |
-
except _metadata.PackageNotFoundError:
|
| 945 |
-
continue
|
| 946 |
-
return _orig_metadata_version(dep_name)
|
| 947 |
-
|
| 948 |
-
_metadata.version = _patched_metadata_version
|
| 949 |
-
|
| 950 |
-
from paddleocr import LayoutDetection
|
| 951 |
-
|
| 952 |
-
model = LayoutDetection(model_name=args.model_name, device=device)
|
| 953 |
-
|
| 954 |
-
# ---------- loop ----------
|
| 955 |
-
processed = 0
|
| 956 |
-
skipped = 0
|
| 957 |
-
errors = 0
|
| 958 |
-
pbar = tqdm(src_iter, total=total, desc=f"Layout {args.model_name}")
|
| 959 |
-
for item in pbar:
|
| 960 |
-
if item.key in completed:
|
| 961 |
-
skipped += 1
|
| 962 |
-
continue
|
| 963 |
-
if item.extras.get("failed") or item.image is None:
|
| 964 |
-
# Unreadable source image — write an empty layout in position so the
|
| 965 |
-
# output stays row-aligned with the source dataset.
|
| 966 |
-
sink.write(item.key, [], {})
|
| 967 |
-
errors += 1
|
| 968 |
-
processed += 1
|
| 969 |
-
continue
|
| 970 |
-
try:
|
| 971 |
-
arr = pil_to_array(item.image)
|
| 972 |
-
results = model.predict(
|
| 973 |
-
arr,
|
| 974 |
-
batch_size=args.batch_size,
|
| 975 |
-
layout_nms=args.layout_nms,
|
| 976 |
-
)
|
| 977 |
-
if not results:
|
| 978 |
-
detections: List[Dict[str, Any]] = []
|
| 979 |
-
else:
|
| 980 |
-
detections = extract_detections(results[0])
|
| 981 |
-
if args.threshold and args.threshold > 0:
|
| 982 |
-
detections = [d for d in detections if d["score"] >= args.threshold]
|
| 983 |
-
except Exception as e:
|
| 984 |
-
logger.error(f"Error on {item.key}: {e}")
|
| 985 |
-
detections = []
|
| 986 |
-
errors += 1
|
| 987 |
-
|
| 988 |
-
extras = dict(item.extras)
|
| 989 |
-
if isinstance(sink, BucketShardSink) and args.include_images:
|
| 990 |
-
buf = io.BytesIO()
|
| 991 |
-
item.image.save(buf, format="PNG")
|
| 992 |
-
extras["__image_bytes"] = buf.getvalue()
|
| 993 |
-
|
| 994 |
-
sink.write(item.key, detections, extras)
|
| 995 |
-
processed += 1
|
| 996 |
-
|
| 997 |
-
duration = datetime.now() - start_time
|
| 998 |
-
processing_time_str = f"{duration.total_seconds() / 60:.2f} min"
|
| 999 |
-
logger.info(
|
| 1000 |
-
f"Processed {processed} (skipped {skipped}, errors {errors}) in {processing_time_str}"
|
| 1001 |
-
)
|
| 1002 |
-
|
| 1003 |
-
args_dict = {
|
| 1004 |
-
"model_name": args.model_name,
|
| 1005 |
-
"threshold": args.threshold,
|
| 1006 |
-
"layout_nms": args.layout_nms,
|
| 1007 |
-
"shard_size": args.shard_size,
|
| 1008 |
-
"processing_time": processing_time_str,
|
| 1009 |
-
}
|
| 1010 |
-
sink.finalize(model_id=f"PaddlePaddle/{args.model_name}", args_dict=args_dict)
|
| 1011 |
-
|
| 1012 |
-
if args.verbose:
|
| 1013 |
-
import importlib.metadata
|
| 1014 |
-
|
| 1015 |
-
logger.info("--- Resolved package versions ---")
|
| 1016 |
-
for pkg in [
|
| 1017 |
-
"paddlepaddle",
|
| 1018 |
-
"paddlepaddle-gpu",
|
| 1019 |
-
"paddleocr",
|
| 1020 |
-
"huggingface-hub",
|
| 1021 |
-
"datasets",
|
| 1022 |
-
"pyarrow",
|
| 1023 |
-
"pillow",
|
| 1024 |
-
"numpy",
|
| 1025 |
-
]:
|
| 1026 |
-
try:
|
| 1027 |
-
logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
|
| 1028 |
-
except importlib.metadata.PackageNotFoundError:
|
| 1029 |
-
logger.info(f" {pkg}: not installed")
|
| 1030 |
-
logger.info("--- End versions ---")
|
| 1031 |
-
|
| 1032 |
-
|
| 1033 |
-
# ---------------------------------------------------------------------------
|
| 1034 |
-
# CLI
|
| 1035 |
-
# ---------------------------------------------------------------------------
|
| 1036 |
-
|
| 1037 |
-
|
| 1038 |
-
def _print_usage_banner() -> None:
|
| 1039 |
-
print("=" * 80)
|
| 1040 |
-
print("PP-DocLayout layout detection")
|
| 1041 |
-
print("=" * 80)
|
| 1042 |
-
print(
|
| 1043 |
-
"\nDetect document layout regions (text/title/table/figure/formula/...)"
|
| 1044 |
-
)
|
| 1045 |
-
print("with PaddleOCR's PP-DocLayout-L (or M / S / plus-L variant).")
|
| 1046 |
-
print("\nModels:")
|
| 1047 |
-
for m in VALID_MODELS:
|
| 1048 |
-
print(f" {m:24s} {MODEL_SIZES.get(m, '')}")
|
| 1049 |
-
print("\nSources:")
|
| 1050 |
-
print(" - HF dataset repo: namespace/dataset")
|
| 1051 |
-
print(" - HF bucket of images: hf://buckets/namespace/bucket[/prefix]")
|
| 1052 |
-
print("\nSinks:")
|
| 1053 |
-
print(" - HF dataset repo (one push + dataset card):")
|
| 1054 |
-
print(" namespace/dataset")
|
| 1055 |
-
print(" - HF bucket (incremental shards, resumable):")
|
| 1056 |
-
print(" hf://buckets/namespace/bucket/run-name")
|
| 1057 |
-
print("\nExamples:")
|
| 1058 |
-
print("\n # Smoke test on L4 (dataset -> dataset)")
|
| 1059 |
-
print(" hf jobs uv run --flavor l4x1 -s HF_TOKEN https://huggingface.co/datasets/uv-scripts/ocr/raw/main/pp-doclayout.py \\")
|
| 1060 |
-
print(" davanstrien/ufo-ColPali pp-doclayout-smoke \\")
|
| 1061 |
-
print(" --max-samples 3 --shuffle --seed 42 --private")
|
| 1062 |
-
print("\n # Dataset -> bucket (incremental shards)")
|
| 1063 |
-
print(
|
| 1064 |
-
" hf jobs uv run --flavor l4x1 -s HF_TOKEN https://huggingface.co/datasets/uv-scripts/ocr/raw/main/pp-doclayout.py \\"
|
| 1065 |
-
)
|
| 1066 |
-
print(" davanstrien/ufo-ColPali \\")
|
| 1067 |
-
print(
|
| 1068 |
-
" hf://buckets/davanstrien/pp-doclayout-scratch/run1 \\"
|
| 1069 |
-
)
|
| 1070 |
-
print(" --max-samples 20 --shard-size 5")
|
| 1071 |
-
print("\n # Bucket of images -> dataset")
|
| 1072 |
-
print(
|
| 1073 |
-
" hf jobs uv run --flavor l4x1 -s HF_TOKEN https://huggingface.co/datasets/uv-scripts/ocr/raw/main/pp-doclayout.py \\"
|
| 1074 |
-
)
|
| 1075 |
-
print(
|
| 1076 |
-
" hf://buckets/davanstrien/pp-doclayout-images \\"
|
| 1077 |
-
)
|
| 1078 |
-
print(" pp-doclayout-from-bucket --private")
|
| 1079 |
-
print("\nFor full help, run: uv run pp-doclayout.py --help")
|
| 1080 |
-
print("=" * 80)
|
| 1081 |
-
|
| 1082 |
-
|
| 1083 |
-
def build_parser() -> argparse.ArgumentParser:
|
| 1084 |
-
p = argparse.ArgumentParser(
|
| 1085 |
-
description="PP-DocLayout layout detection over an HF dataset or bucket.",
|
| 1086 |
-
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 1087 |
-
)
|
| 1088 |
-
p.add_argument(
|
| 1089 |
-
"input_source",
|
| 1090 |
-
help="HF dataset id (namespace/dataset) OR hf://buckets/ns/bucket[/prefix]",
|
| 1091 |
-
)
|
| 1092 |
-
p.add_argument(
|
| 1093 |
-
"output_target",
|
| 1094 |
-
help="HF dataset id (namespace/dataset) OR hf://buckets/ns/bucket/run-name",
|
| 1095 |
-
)
|
| 1096 |
-
p.add_argument(
|
| 1097 |
-
"--model-name",
|
| 1098 |
-
default="PP-DocLayout-L",
|
| 1099 |
-
choices=VALID_MODELS,
|
| 1100 |
-
help="PaddleOCR layout model variant (default: PP-DocLayout-L)",
|
| 1101 |
-
)
|
| 1102 |
-
p.add_argument(
|
| 1103 |
-
"--device",
|
| 1104 |
-
default="gpu",
|
| 1105 |
-
choices=["gpu", "cpu"],
|
| 1106 |
-
help="Device for inference (default: gpu, falls back to cpu if CUDA missing)",
|
| 1107 |
-
)
|
| 1108 |
-
p.add_argument(
|
| 1109 |
-
"--batch-size",
|
| 1110 |
-
type=int,
|
| 1111 |
-
default=1,
|
| 1112 |
-
help="Per-image batch size passed to model.predict (default: 1)",
|
| 1113 |
-
)
|
| 1114 |
-
p.add_argument(
|
| 1115 |
-
"--threshold",
|
| 1116 |
-
type=float,
|
| 1117 |
-
default=0.5,
|
| 1118 |
-
help="Drop detections below this confidence (default: 0.5; 0 disables)",
|
| 1119 |
-
)
|
| 1120 |
-
p.add_argument(
|
| 1121 |
-
"--layout-nms",
|
| 1122 |
-
dest="layout_nms",
|
| 1123 |
-
action="store_true",
|
| 1124 |
-
default=True,
|
| 1125 |
-
help="Enable layout NMS (default: on)",
|
| 1126 |
-
)
|
| 1127 |
-
p.add_argument(
|
| 1128 |
-
"--no-layout-nms",
|
| 1129 |
-
dest="layout_nms",
|
| 1130 |
-
action="store_false",
|
| 1131 |
-
help="Disable layout NMS",
|
| 1132 |
-
)
|
| 1133 |
-
# Dataset-source-specific
|
| 1134 |
-
p.add_argument(
|
| 1135 |
-
"--image-column",
|
| 1136 |
-
default="image",
|
| 1137 |
-
help="Column containing images (dataset-repo source only, default: image)",
|
| 1138 |
-
)
|
| 1139 |
-
p.add_argument(
|
| 1140 |
-
"--split",
|
| 1141 |
-
default="train",
|
| 1142 |
-
help="Dataset split (dataset-repo source only, default: train)",
|
| 1143 |
-
)
|
| 1144 |
-
p.add_argument(
|
| 1145 |
-
"--max-samples", type=int, help="Limit number of samples (for testing)"
|
| 1146 |
-
)
|
| 1147 |
-
p.add_argument(
|
| 1148 |
-
"--shuffle", action="store_true", help="Shuffle source before processing"
|
| 1149 |
-
)
|
| 1150 |
-
p.add_argument(
|
| 1151 |
-
"--seed", type=int, default=42, help="Random seed for shuffle (default: 42)"
|
| 1152 |
-
)
|
| 1153 |
-
# Dataset-sink-specific
|
| 1154 |
-
p.add_argument(
|
| 1155 |
-
"--private", action="store_true", help="Private dataset output (dataset sink only)"
|
| 1156 |
-
)
|
| 1157 |
-
p.add_argument(
|
| 1158 |
-
"--config",
|
| 1159 |
-
help="Config/subset name when pushing to Hub (dataset sink only)",
|
| 1160 |
-
)
|
| 1161 |
-
p.add_argument(
|
| 1162 |
-
"--create-pr",
|
| 1163 |
-
action="store_true",
|
| 1164 |
-
help="Create PR instead of direct push (dataset sink only)",
|
| 1165 |
-
)
|
| 1166 |
-
# Bucket-sink-specific
|
| 1167 |
-
p.add_argument(
|
| 1168 |
-
"--shard-size",
|
| 1169 |
-
type=int,
|
| 1170 |
-
default=256,
|
| 1171 |
-
help="Rows per parquet shard for bucket sink (default: 256)",
|
| 1172 |
-
)
|
| 1173 |
-
p.add_argument(
|
| 1174 |
-
"--include-images",
|
| 1175 |
-
action="store_true",
|
| 1176 |
-
help="Embed source image bytes in bucket output shards (off by default)",
|
| 1177 |
-
)
|
| 1178 |
-
p.add_argument(
|
| 1179 |
-
"--no-resume",
|
| 1180 |
-
action="store_true",
|
| 1181 |
-
help="Disable resume scan when writing to a bucket sink",
|
| 1182 |
-
)
|
| 1183 |
-
# Auth + diagnostics
|
| 1184 |
-
p.add_argument("--hf-token", help="Hugging Face API token (else uses HF_TOKEN env)")
|
| 1185 |
-
p.add_argument(
|
| 1186 |
-
"--verbose",
|
| 1187 |
-
action="store_true",
|
| 1188 |
-
help="Log resolved package versions at the end",
|
| 1189 |
-
)
|
| 1190 |
-
return p
|
| 1191 |
-
|
| 1192 |
-
|
| 1193 |
-
if __name__ == "__main__":
|
| 1194 |
-
if len(sys.argv) == 1:
|
| 1195 |
-
_print_usage_banner()
|
| 1196 |
-
sys.exit(0)
|
| 1197 |
-
main(build_parser().parse_args())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ETED
|
@@ -1,1041 +0,0 @@
|
|
| 1 |
-
# /// script
|
| 2 |
-
# requires-python = ">=3.10"
|
| 3 |
-
# dependencies = [
|
| 4 |
-
# "paddlepaddle-gpu>=3.0.0",
|
| 5 |
-
# "paddleocr>=3.7.0",
|
| 6 |
-
# "paddlex[ocr]>=3.7.0",
|
| 7 |
-
# "opencv-contrib-python-headless",
|
| 8 |
-
# "datasets>=3.1.0",
|
| 9 |
-
# "huggingface-hub",
|
| 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). A matching
|
| 19 |
-
# # importlib.metadata patch in main() makes paddlex recognise the headless name.
|
| 20 |
-
# override-dependencies = [
|
| 21 |
-
# "opencv-contrib-python ; python_version < '0'",
|
| 22 |
-
# "opencv-python ; python_version < '0'",
|
| 23 |
-
# ]
|
| 24 |
-
#
|
| 25 |
-
# [[tool.uv.index]]
|
| 26 |
-
# name = "paddle"
|
| 27 |
-
# url = "https://www.paddlepaddle.org.cn/packages/stable/cu126/"
|
| 28 |
-
# explicit = true
|
| 29 |
-
#
|
| 30 |
-
# [tool.uv.sources]
|
| 31 |
-
# paddlepaddle-gpu = { index = "paddle" }
|
| 32 |
-
# ///
|
| 33 |
-
"""
|
| 34 |
-
OCR images with PP-OCRv6 — a lightweight detection+recognition pipeline from
|
| 35 |
-
PaddlePaddle. Three tiers from **1.5M to 34.5M parameters**.
|
| 36 |
-
|
| 37 |
-
Unlike the VLM-based OCR recipes here, PP-OCRv6 is a **classical det+rec pipeline**
|
| 38 |
-
that outputs **plain text** (not markdown). At 1.5M-34.5M params it's far smaller
|
| 39 |
-
than the VLM OCRs and runs on a cheap t4-small GPU.
|
| 40 |
-
|
| 41 |
-
Model tiers (pick with `--model-tier`):
|
| 42 |
-
tiny 1.5M params (0.4M det + 1.1M rec) 49 languages, ~73% recognition
|
| 43 |
-
small 7.7M params (2.5M det + 5.3M rec) 50 languages, ~81% recognition
|
| 44 |
-
medium 34.5M params (22M det + 19M rec) 50 languages, ~83% recognition
|
| 45 |
-
|
| 46 |
-
All tiers are Apache 2.0 licensed. Runs via PaddleOCR's default Paddle engine
|
| 47 |
-
(`paddle_static`) — same proven header pattern as `pp-doclayout.py`.
|
| 48 |
-
|
| 49 |
-
HF Jobs examples:
|
| 50 |
-
|
| 51 |
-
# Tiny on a cheap GPU
|
| 52 |
-
hf jobs uv run --flavor t4-small -s HF_TOKEN \\
|
| 53 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/pp-ocrv6.py \\
|
| 54 |
-
INPUT_DATASET OUTPUT_DATASET \\
|
| 55 |
-
--model-tier tiny --max-samples 5
|
| 56 |
-
|
| 57 |
-
# Medium on a small GPU (recommended for quality)
|
| 58 |
-
hf jobs uv run --flavor t4-small -s HF_TOKEN \\
|
| 59 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/pp-ocrv6.py \\
|
| 60 |
-
INPUT_DATASET OUTPUT_DATASET \\
|
| 61 |
-
--model-tier medium --max-samples 10
|
| 62 |
-
|
| 63 |
-
Models: PaddlePaddle/PP-OCRv6_<tier>_det + PP-OCRv6_<tier>_rec
|
| 64 |
-
Blog: https://huggingface.co/blog/PaddlePaddle/pp-ocrv6
|
| 65 |
-
"""
|
| 66 |
-
|
| 67 |
-
import argparse
|
| 68 |
-
import io
|
| 69 |
-
import json
|
| 70 |
-
import logging
|
| 71 |
-
import os
|
| 72 |
-
import time
|
| 73 |
-
from dataclasses import dataclass
|
| 74 |
-
from datetime import datetime, timezone
|
| 75 |
-
from pathlib import Path
|
| 76 |
-
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
|
| 77 |
-
|
| 78 |
-
import numpy as np
|
| 79 |
-
from PIL import Image, UnidentifiedImageError
|
| 80 |
-
from tqdm.auto import tqdm
|
| 81 |
-
|
| 82 |
-
logging.basicConfig(level=logging.INFO)
|
| 83 |
-
logger = logging.getLogger(__name__)
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
# ---------------------------------------------------------------------------
|
| 87 |
-
# Constants
|
| 88 |
-
# ---------------------------------------------------------------------------
|
| 89 |
-
|
| 90 |
-
TIER_MODELS = {
|
| 91 |
-
"tiny": ("PP-OCRv6_tiny_det", "PP-OCRv6_tiny_rec"),
|
| 92 |
-
"small": ("PP-OCRv6_small_det", "PP-OCRv6_small_rec"),
|
| 93 |
-
"medium": ("PP-OCRv6_medium_det", "PP-OCRv6_medium_rec"),
|
| 94 |
-
}
|
| 95 |
-
|
| 96 |
-
TIER_PARAMS = {
|
| 97 |
-
"tiny": "1.5M (0.4M det + 1.1M rec)",
|
| 98 |
-
"small": "7.7M (2.5M det + 5.3M rec)",
|
| 99 |
-
"medium": "34.5M (22M det + 19M rec)",
|
| 100 |
-
}
|
| 101 |
-
|
| 102 |
-
TIER_LANGUAGES = {
|
| 103 |
-
"tiny": "49 languages (zh, zh-Hant, en + 46 Latin-script — no Japanese)",
|
| 104 |
-
"small": "50 languages (zh, zh-Hant, en, ja + 46 Latin-script)",
|
| 105 |
-
"medium": "50 languages (zh, zh-Hant, en, ja + 46 Latin-script)",
|
| 106 |
-
}
|
| 107 |
-
|
| 108 |
-
TIER_REC = {
|
| 109 |
-
"tiny": 73.5,
|
| 110 |
-
"small": 81.3,
|
| 111 |
-
"medium": 83.2,
|
| 112 |
-
}
|
| 113 |
-
|
| 114 |
-
BUCKET_PREFIX = "hf://buckets/"
|
| 115 |
-
|
| 116 |
-
IMAGE_EXTENSIONS = {
|
| 117 |
-
".jpg", ".jpeg", ".png", ".tif", ".tiff", ".webp", ".bmp", ".jp2", ".j2k",
|
| 118 |
-
}
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
# ---------------------------------------------------------------------------
|
| 122 |
-
# URL helpers
|
| 123 |
-
# ---------------------------------------------------------------------------
|
| 124 |
-
|
| 125 |
-
def is_bucket_url(s: str) -> bool:
|
| 126 |
-
return s.startswith(BUCKET_PREFIX)
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
def parse_bucket_url(url: str) -> Tuple[str, str]:
|
| 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(f"Bucket URL must include namespace and bucket name: {url}")
|
| 136 |
-
bucket_id = f"{parts[0]}/{parts[1]}"
|
| 137 |
-
prefix = parts[2] if len(parts) > 2 else ""
|
| 138 |
-
return bucket_id, prefix
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
# ---------------------------------------------------------------------------
|
| 142 |
-
# Image helpers
|
| 143 |
-
# ---------------------------------------------------------------------------
|
| 144 |
-
|
| 145 |
-
def to_pil(image: Union[Image.Image, Dict[str, Any], str, bytes]) -> Image.Image:
|
| 146 |
-
if isinstance(image, Image.Image):
|
| 147 |
-
return image.convert("RGB")
|
| 148 |
-
if isinstance(image, dict) and "bytes" in image:
|
| 149 |
-
return Image.open(io.BytesIO(image["bytes"])).convert("RGB")
|
| 150 |
-
if isinstance(image, (bytes, bytearray)):
|
| 151 |
-
return Image.open(io.BytesIO(image)).convert("RGB")
|
| 152 |
-
if isinstance(image, str):
|
| 153 |
-
return Image.open(image).convert("RGB")
|
| 154 |
-
raise ValueError(f"Unsupported image type: {type(image)}")
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
def pil_to_array(pil_img: Image.Image) -> np.ndarray:
|
| 158 |
-
return np.asarray(pil_img, dtype=np.uint8)
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
# ---------------------------------------------------------------------------
|
| 162 |
-
# Result extraction
|
| 163 |
-
# ---------------------------------------------------------------------------
|
| 164 |
-
|
| 165 |
-
def extract_text(result: Any) -> Tuple[str, List[Dict[str, Any]]]:
|
| 166 |
-
"""Pull text and per-line details from a PaddleOCR predict result.
|
| 167 |
-
|
| 168 |
-
Returns (concatenated_text, per_line_details) where per_line_details is
|
| 169 |
-
a list of dicts with keys: text, score, bbox (4-point detection polygon as
|
| 170 |
-
[[x1,y1],[x2,y2],[x3,y3],[x4,y4]] in input-image pixel coordinates).
|
| 171 |
-
"""
|
| 172 |
-
payload = result.json if hasattr(result, "json") else result
|
| 173 |
-
res = payload.get("res", payload) if isinstance(payload, dict) else {}
|
| 174 |
-
rec_texts = res.get("rec_texts", []) or []
|
| 175 |
-
rec_scores = res.get("rec_scores", []) or []
|
| 176 |
-
dt_polys = res.get("dt_polys", []) or []
|
| 177 |
-
|
| 178 |
-
# Concatenate reading-order text lines (PaddleOCR returns them in order)
|
| 179 |
-
text = "\n".join(rec_texts)
|
| 180 |
-
|
| 181 |
-
per_line = []
|
| 182 |
-
for i, t in enumerate(rec_texts):
|
| 183 |
-
entry = {"text": t}
|
| 184 |
-
if i < len(rec_scores):
|
| 185 |
-
entry["score"] = float(rec_scores[i])
|
| 186 |
-
if i < len(dt_polys):
|
| 187 |
-
entry["bbox"] = [[float(c) for c in point] for point in dt_polys[i]]
|
| 188 |
-
per_line.append(entry)
|
| 189 |
-
|
| 190 |
-
return text, per_line
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
# ---------------------------------------------------------------------------
|
| 194 |
-
# Sources
|
| 195 |
-
# ---------------------------------------------------------------------------
|
| 196 |
-
|
| 197 |
-
@dataclass
|
| 198 |
-
class SourceItem:
|
| 199 |
-
key: str
|
| 200 |
-
image: Optional[Image.Image]
|
| 201 |
-
extras: Dict[str, Any]
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
def iter_dataset_images(
|
| 205 |
-
dataset_id: str,
|
| 206 |
-
image_column: str,
|
| 207 |
-
split: str,
|
| 208 |
-
shuffle: bool,
|
| 209 |
-
seed: int,
|
| 210 |
-
max_samples: Optional[int],
|
| 211 |
-
):
|
| 212 |
-
from datasets import load_dataset
|
| 213 |
-
|
| 214 |
-
logger.info(f"Loading dataset: {dataset_id} (split={split})")
|
| 215 |
-
ds = load_dataset(dataset_id, split=split)
|
| 216 |
-
|
| 217 |
-
if image_column not in ds.column_names:
|
| 218 |
-
raise ValueError(
|
| 219 |
-
f"Column '{image_column}' not found. Available: {ds.column_names}"
|
| 220 |
-
)
|
| 221 |
-
|
| 222 |
-
if shuffle:
|
| 223 |
-
logger.info(f"Shuffling with seed {seed}")
|
| 224 |
-
ds = ds.shuffle(seed=seed)
|
| 225 |
-
if max_samples:
|
| 226 |
-
ds = ds.select(range(min(max_samples, len(ds))))
|
| 227 |
-
logger.info(f"Limited to {len(ds)} samples")
|
| 228 |
-
|
| 229 |
-
total = len(ds)
|
| 230 |
-
|
| 231 |
-
def gen() -> Iterator[SourceItem]:
|
| 232 |
-
failed = 0
|
| 233 |
-
for i in range(total):
|
| 234 |
-
try:
|
| 235 |
-
row = ds[i]
|
| 236 |
-
image = to_pil(row[image_column])
|
| 237 |
-
except (UnidentifiedImageError, OSError) as e:
|
| 238 |
-
# Still yield a placeholder so the output row stays aligned with
|
| 239 |
-
# the source row (the dataset sink writes results positionally).
|
| 240 |
-
failed += 1
|
| 241 |
-
logger.warning(
|
| 242 |
-
f"Unreadable image at row {i}: {type(e).__name__}: {e} "
|
| 243 |
-
f"— writing empty result"
|
| 244 |
-
)
|
| 245 |
-
yield SourceItem(key=f"row-{i:08d}", image=None, extras={"failed": True})
|
| 246 |
-
continue
|
| 247 |
-
yield SourceItem(key=f"row-{i:08d}", image=image, extras={})
|
| 248 |
-
if failed:
|
| 249 |
-
logger.info(f"{failed} unreadable image(s) written as empty results")
|
| 250 |
-
|
| 251 |
-
return gen(), total, ds
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
SOURCE_PATHS_SNAPSHOT = "_source_paths.json"
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
def _bucket_snapshot_path(output_url: str) -> Tuple[str, str]:
|
| 258 |
-
out_bucket_id, out_prefix = parse_bucket_url(output_url)
|
| 259 |
-
snapshot_key = (
|
| 260 |
-
f"{out_prefix}/{SOURCE_PATHS_SNAPSHOT}".lstrip("/")
|
| 261 |
-
if out_prefix
|
| 262 |
-
else SOURCE_PATHS_SNAPSHOT
|
| 263 |
-
)
|
| 264 |
-
return out_bucket_id, snapshot_key
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
def iter_bucket_images(
|
| 268 |
-
bucket_url: str,
|
| 269 |
-
shuffle: bool,
|
| 270 |
-
seed: int,
|
| 271 |
-
max_samples: Optional[int],
|
| 272 |
-
hf_token: Optional[str],
|
| 273 |
-
output_url: Optional[str] = None,
|
| 274 |
-
) -> Tuple[Iterator[SourceItem], int]:
|
| 275 |
-
from huggingface_hub import HfApi, HfFileSystem
|
| 276 |
-
|
| 277 |
-
bucket_id, prefix = parse_bucket_url(bucket_url)
|
| 278 |
-
fs = HfFileSystem(token=hf_token)
|
| 279 |
-
base = f"{BUCKET_PREFIX}{bucket_id}/{prefix}".rstrip("/")
|
| 280 |
-
|
| 281 |
-
snapshot_bucket_id: Optional[str] = None
|
| 282 |
-
snapshot_key: Optional[str] = None
|
| 283 |
-
cached_paths: Optional[List[str]] = None
|
| 284 |
-
|
| 285 |
-
if output_url and is_bucket_url(output_url):
|
| 286 |
-
snapshot_bucket_id, snapshot_key = _bucket_snapshot_path(output_url)
|
| 287 |
-
snapshot_url = f"{BUCKET_PREFIX}{snapshot_bucket_id}/{snapshot_key}"
|
| 288 |
-
try:
|
| 289 |
-
with fs.open(snapshot_url, "rb") as f:
|
| 290 |
-
snapshot = json.load(f)
|
| 291 |
-
mismatches = []
|
| 292 |
-
if snapshot.get("source_url") != bucket_url:
|
| 293 |
-
mismatches.append(
|
| 294 |
-
f"source_url ({snapshot.get('source_url')!r} vs {bucket_url!r})"
|
| 295 |
-
)
|
| 296 |
-
if snapshot.get("shuffle") != shuffle:
|
| 297 |
-
mismatches.append(f"shuffle ({snapshot.get('shuffle')} vs {shuffle})")
|
| 298 |
-
if shuffle and snapshot.get("seed") != seed:
|
| 299 |
-
mismatches.append(f"seed ({snapshot.get('seed')} vs {seed})")
|
| 300 |
-
if snapshot.get("max_samples") != max_samples:
|
| 301 |
-
mismatches.append(
|
| 302 |
-
f"max_samples ({snapshot.get('max_samples')} vs {max_samples})"
|
| 303 |
-
)
|
| 304 |
-
if mismatches:
|
| 305 |
-
logger.warning(
|
| 306 |
-
"Existing snapshot params differ from this run ("
|
| 307 |
-
+ "; ".join(mismatches)
|
| 308 |
-
+ "); ignoring snapshot and re-listing."
|
| 309 |
-
)
|
| 310 |
-
else:
|
| 311 |
-
cached_paths = snapshot["paths"]
|
| 312 |
-
logger.info(
|
| 313 |
-
f"Reusing existing snapshot of {len(cached_paths)} source paths "
|
| 314 |
-
f"(written {snapshot.get('created_at', 'unknown')})"
|
| 315 |
-
)
|
| 316 |
-
except FileNotFoundError:
|
| 317 |
-
pass
|
| 318 |
-
except Exception as e:
|
| 319 |
-
logger.warning(f"Could not read existing snapshot ({e}); re-listing.")
|
| 320 |
-
|
| 321 |
-
if cached_paths is not None:
|
| 322 |
-
all_paths = cached_paths
|
| 323 |
-
else:
|
| 324 |
-
logger.info(f"Listing images under {base}")
|
| 325 |
-
all_paths = []
|
| 326 |
-
try:
|
| 327 |
-
for entry in fs.find(base, detail=False):
|
| 328 |
-
ext = Path(entry).suffix.lower()
|
| 329 |
-
if ext in IMAGE_EXTENSIONS:
|
| 330 |
-
all_paths.append(entry)
|
| 331 |
-
except FileNotFoundError as e:
|
| 332 |
-
raise ValueError(f"Bucket prefix not found: {base}") from e
|
| 333 |
-
|
| 334 |
-
if not all_paths:
|
| 335 |
-
raise ValueError(
|
| 336 |
-
f"No image files (any of {sorted(IMAGE_EXTENSIONS)}) under {base}"
|
| 337 |
-
)
|
| 338 |
-
|
| 339 |
-
all_paths.sort()
|
| 340 |
-
if shuffle:
|
| 341 |
-
rng = np.random.default_rng(seed)
|
| 342 |
-
rng.shuffle(all_paths)
|
| 343 |
-
if max_samples:
|
| 344 |
-
all_paths = all_paths[:max_samples]
|
| 345 |
-
|
| 346 |
-
if snapshot_bucket_id is not None and snapshot_key is not None:
|
| 347 |
-
api = HfApi(token=hf_token)
|
| 348 |
-
payload = {
|
| 349 |
-
"source_url": bucket_url,
|
| 350 |
-
"shuffle": shuffle,
|
| 351 |
-
"seed": seed,
|
| 352 |
-
"max_samples": max_samples,
|
| 353 |
-
"created_at": datetime.now(timezone.utc).isoformat(),
|
| 354 |
-
"paths": all_paths,
|
| 355 |
-
}
|
| 356 |
-
api.batch_bucket_files(
|
| 357 |
-
snapshot_bucket_id,
|
| 358 |
-
add=[(json.dumps(payload).encode(), snapshot_key)],
|
| 359 |
-
token=hf_token,
|
| 360 |
-
)
|
| 361 |
-
logger.info(
|
| 362 |
-
f"Wrote source-path snapshot ({len(all_paths)} paths) to "
|
| 363 |
-
f"hf://buckets/{snapshot_bucket_id}/{snapshot_key}"
|
| 364 |
-
)
|
| 365 |
-
|
| 366 |
-
total = len(all_paths)
|
| 367 |
-
logger.info(f"Found {total} images in bucket")
|
| 368 |
-
|
| 369 |
-
def key_for(path: str) -> str:
|
| 370 |
-
return path
|
| 371 |
-
|
| 372 |
-
def gen() -> Iterator[SourceItem]:
|
| 373 |
-
skipped = 0
|
| 374 |
-
for path in all_paths:
|
| 375 |
-
try:
|
| 376 |
-
with fs.open(path, "rb") as f:
|
| 377 |
-
data = f.read()
|
| 378 |
-
image = to_pil(data)
|
| 379 |
-
except (UnidentifiedImageError, OSError) as e:
|
| 380 |
-
skipped += 1
|
| 381 |
-
logger.warning(
|
| 382 |
-
f"Skipping unreadable image {path}: {type(e).__name__}: {e}"
|
| 383 |
-
)
|
| 384 |
-
continue
|
| 385 |
-
yield SourceItem(key=key_for(path), image=image, extras={})
|
| 386 |
-
if skipped:
|
| 387 |
-
logger.info(f"Skipped {skipped} unreadable image(s) total")
|
| 388 |
-
|
| 389 |
-
return gen(), total
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
# ---------------------------------------------------------------------------
|
| 393 |
-
# Sinks
|
| 394 |
-
# ---------------------------------------------------------------------------
|
| 395 |
-
|
| 396 |
-
class DatasetRepoSink:
|
| 397 |
-
def __init__(
|
| 398 |
-
self,
|
| 399 |
-
repo_id: str,
|
| 400 |
-
*,
|
| 401 |
-
hf_token: Optional[str],
|
| 402 |
-
private: bool,
|
| 403 |
-
config: Optional[str],
|
| 404 |
-
create_pr: bool,
|
| 405 |
-
source_id: str,
|
| 406 |
-
original_dataset=None,
|
| 407 |
-
):
|
| 408 |
-
self.repo_id = repo_id
|
| 409 |
-
self.hf_token = hf_token
|
| 410 |
-
self.private = private
|
| 411 |
-
self.config = config
|
| 412 |
-
self.create_pr = create_pr
|
| 413 |
-
self.source_id = source_id
|
| 414 |
-
self.original_dataset = original_dataset
|
| 415 |
-
self._texts: List[str] = []
|
| 416 |
-
self._blocks: List[str] = []
|
| 417 |
-
|
| 418 |
-
@property
|
| 419 |
-
def kind(self) -> str:
|
| 420 |
-
return "dataset"
|
| 421 |
-
|
| 422 |
-
def already_done(self) -> set:
|
| 423 |
-
return set()
|
| 424 |
-
|
| 425 |
-
def write(self, key: str, text: str, blocks: List[Dict[str, Any]]) -> None:
|
| 426 |
-
self._texts.append(text)
|
| 427 |
-
self._blocks.append(json.dumps(blocks, ensure_ascii=False))
|
| 428 |
-
|
| 429 |
-
def finalize(self, tier: str, det_model: str, rec_model: str, args_dict: Dict[str, Any]) -> None:
|
| 430 |
-
from datasets import Dataset
|
| 431 |
-
|
| 432 |
-
if self.original_dataset is not None:
|
| 433 |
-
if len(self._texts) != len(self.original_dataset):
|
| 434 |
-
logger.warning(
|
| 435 |
-
f"Text count ({len(self._texts)}) != dataset rows "
|
| 436 |
-
f"({len(self.original_dataset)}); padding with empty strings."
|
| 437 |
-
)
|
| 438 |
-
while len(self._texts) < len(self.original_dataset):
|
| 439 |
-
self._texts.append("")
|
| 440 |
-
self._blocks.append("[]")
|
| 441 |
-
ds = self.original_dataset.add_column("text", self._texts)
|
| 442 |
-
ds = ds.add_column("pp_ocr_blocks", self._blocks)
|
| 443 |
-
else:
|
| 444 |
-
if not self._texts:
|
| 445 |
-
logger.warning("No rows produced; nothing to push.")
|
| 446 |
-
return
|
| 447 |
-
ds = Dataset.from_list([
|
| 448 |
-
{"source_path": None, "text": t, "pp_ocr_blocks": b}
|
| 449 |
-
for t, b in zip(self._texts, self._blocks)
|
| 450 |
-
])
|
| 451 |
-
|
| 452 |
-
inference_entry = build_inference_entry(tier, det_model, rec_model, args_dict)
|
| 453 |
-
|
| 454 |
-
if "inference_info" in ds.column_names:
|
| 455 |
-
logger.info("Updating existing inference_info column")
|
| 456 |
-
|
| 457 |
-
def _update(example):
|
| 458 |
-
try:
|
| 459 |
-
existing = (
|
| 460 |
-
json.loads(example["inference_info"])
|
| 461 |
-
if example["inference_info"]
|
| 462 |
-
else []
|
| 463 |
-
)
|
| 464 |
-
except (json.JSONDecodeError, TypeError):
|
| 465 |
-
existing = []
|
| 466 |
-
existing.append(inference_entry)
|
| 467 |
-
return {"inference_info": json.dumps(existing)}
|
| 468 |
-
|
| 469 |
-
ds = ds.map(_update)
|
| 470 |
-
else:
|
| 471 |
-
ds = ds.add_column(
|
| 472 |
-
"inference_info", [json.dumps([inference_entry])] * len(ds)
|
| 473 |
-
)
|
| 474 |
-
|
| 475 |
-
logger.info(f"Pushing {len(ds)} rows to {self.repo_id}")
|
| 476 |
-
push_kwargs = {
|
| 477 |
-
"private": self.private,
|
| 478 |
-
"token": self.hf_token,
|
| 479 |
-
"max_shard_size": "500MB",
|
| 480 |
-
"create_pr": self.create_pr,
|
| 481 |
-
"commit_message": f"Add PP-OCRv6-{tier} OCR results ({len(ds)} samples)"
|
| 482 |
-
+ (f" [{self.config}]" if self.config else ""),
|
| 483 |
-
}
|
| 484 |
-
if self.config:
|
| 485 |
-
push_kwargs["config_name"] = self.config
|
| 486 |
-
|
| 487 |
-
max_retries = 3
|
| 488 |
-
for attempt in range(1, max_retries + 1):
|
| 489 |
-
try:
|
| 490 |
-
if attempt > 1:
|
| 491 |
-
logger.warning("Disabling XET (fallback to HTTP upload)")
|
| 492 |
-
os.environ["HF_HUB_DISABLE_XET"] = "1"
|
| 493 |
-
ds.push_to_hub(self.repo_id, **push_kwargs)
|
| 494 |
-
break
|
| 495 |
-
except Exception as e:
|
| 496 |
-
logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
|
| 497 |
-
if attempt == max_retries:
|
| 498 |
-
logger.error("All upload attempts failed.")
|
| 499 |
-
raise
|
| 500 |
-
time.sleep(30 * (2 ** (attempt - 1)))
|
| 501 |
-
|
| 502 |
-
from huggingface_hub import DatasetCard
|
| 503 |
-
|
| 504 |
-
card = DatasetCard(
|
| 505 |
-
create_dataset_card(
|
| 506 |
-
source=self.source_id,
|
| 507 |
-
tier=tier,
|
| 508 |
-
det_model=det_model,
|
| 509 |
-
rec_model=rec_model,
|
| 510 |
-
num_samples=len(ds),
|
| 511 |
-
processing_time=args_dict["processing_time"],
|
| 512 |
-
engine=args_dict.get("engine", "paddle_static"),
|
| 513 |
-
output_id=self.repo_id,
|
| 514 |
-
)
|
| 515 |
-
)
|
| 516 |
-
card.push_to_hub(self.repo_id, token=self.hf_token)
|
| 517 |
-
logger.info(f"Done: https://huggingface.co/datasets/{self.repo_id}")
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
class BucketShardSink:
|
| 521 |
-
METADATA_FILE = "_metadata.json"
|
| 522 |
-
SHARD_PATTERN = "shard-{:05d}.parquet"
|
| 523 |
-
|
| 524 |
-
def __init__(
|
| 525 |
-
self,
|
| 526 |
-
bucket_url: str,
|
| 527 |
-
*,
|
| 528 |
-
hf_token: Optional[str],
|
| 529 |
-
shard_size: int,
|
| 530 |
-
resume: bool,
|
| 531 |
-
source_id: str,
|
| 532 |
-
):
|
| 533 |
-
from huggingface_hub import HfApi, HfFileSystem, create_bucket
|
| 534 |
-
|
| 535 |
-
self.bucket_url = bucket_url
|
| 536 |
-
self.bucket_id, self.prefix = parse_bucket_url(bucket_url)
|
| 537 |
-
self.hf_token = hf_token
|
| 538 |
-
self.shard_size = shard_size
|
| 539 |
-
self.resume = resume
|
| 540 |
-
self.source_id = source_id
|
| 541 |
-
|
| 542 |
-
self._api = HfApi(token=hf_token)
|
| 543 |
-
self._fs = HfFileSystem(token=hf_token)
|
| 544 |
-
|
| 545 |
-
try:
|
| 546 |
-
create_bucket(self.bucket_id, exist_ok=True, token=hf_token)
|
| 547 |
-
except Exception as e:
|
| 548 |
-
logger.warning(f"create_bucket('{self.bucket_id}') warning: {e}")
|
| 549 |
-
|
| 550 |
-
self._buffer: List[Dict[str, Any]] = []
|
| 551 |
-
self._next_shard_idx = self._discover_next_shard_idx()
|
| 552 |
-
self._completed_keys = self._discover_completed_keys() if resume else set()
|
| 553 |
-
if self._completed_keys:
|
| 554 |
-
logger.info(
|
| 555 |
-
f"Resume: found {len(self._completed_keys)} already-processed keys, will skip them"
|
| 556 |
-
)
|
| 557 |
-
|
| 558 |
-
@property
|
| 559 |
-
def kind(self) -> str:
|
| 560 |
-
return "bucket"
|
| 561 |
-
|
| 562 |
-
def already_done(self) -> set:
|
| 563 |
-
return self._completed_keys
|
| 564 |
-
|
| 565 |
-
def _shard_path(self, idx: int) -> str:
|
| 566 |
-
return self._join(self.SHARD_PATTERN.format(idx))
|
| 567 |
-
|
| 568 |
-
def _join(self, name: str) -> str:
|
| 569 |
-
return f"{self.prefix}/{name}".lstrip("/") if self.prefix else name
|
| 570 |
-
|
| 571 |
-
def _list_existing_shards(self) -> List[str]:
|
| 572 |
-
try:
|
| 573 |
-
tree = self._api.list_bucket_tree(
|
| 574 |
-
self.bucket_id, prefix=self.prefix or None, recursive=True
|
| 575 |
-
)
|
| 576 |
-
except Exception:
|
| 577 |
-
return []
|
| 578 |
-
shards: List[str] = []
|
| 579 |
-
for item in tree:
|
| 580 |
-
path = getattr(item, "path", None)
|
| 581 |
-
ftype = getattr(item, "type", None)
|
| 582 |
-
if not path or ftype not in (None, "file"):
|
| 583 |
-
continue
|
| 584 |
-
base = Path(path).name
|
| 585 |
-
if base.startswith("shard-") and base.endswith(".parquet"):
|
| 586 |
-
shards.append(path)
|
| 587 |
-
return sorted(shards)
|
| 588 |
-
|
| 589 |
-
def _discover_next_shard_idx(self) -> int:
|
| 590 |
-
shards = self._list_existing_shards()
|
| 591 |
-
max_idx = -1
|
| 592 |
-
for s in shards:
|
| 593 |
-
stem = Path(s).stem
|
| 594 |
-
try:
|
| 595 |
-
max_idx = max(max_idx, int(stem.split("-")[-1]))
|
| 596 |
-
except ValueError:
|
| 597 |
-
continue
|
| 598 |
-
return max_idx + 1
|
| 599 |
-
|
| 600 |
-
def _discover_completed_keys(self) -> set:
|
| 601 |
-
import pyarrow.parquet as pq
|
| 602 |
-
|
| 603 |
-
keys: set = set()
|
| 604 |
-
for shard_path in self._list_existing_shards():
|
| 605 |
-
full = f"{BUCKET_PREFIX}{self.bucket_id}/{shard_path}"
|
| 606 |
-
try:
|
| 607 |
-
with self._fs.open(full, "rb") as f:
|
| 608 |
-
table = pq.read_table(f, columns=["__source_key"])
|
| 609 |
-
keys.update(table.column("__source_key").to_pylist())
|
| 610 |
-
except Exception as e:
|
| 611 |
-
logger.warning(f"Could not read keys from {shard_path}: {e}")
|
| 612 |
-
return keys
|
| 613 |
-
|
| 614 |
-
def _flush(self) -> None:
|
| 615 |
-
if not self._buffer:
|
| 616 |
-
return
|
| 617 |
-
import pyarrow as pa
|
| 618 |
-
import pyarrow.parquet as pq
|
| 619 |
-
|
| 620 |
-
columns = ["__source_key", "text", "pp_ocr_blocks"]
|
| 621 |
-
table_dict = {c: [row.get(c) for row in self._buffer] for c in columns}
|
| 622 |
-
table = pa.Table.from_pydict(table_dict)
|
| 623 |
-
|
| 624 |
-
buf = io.BytesIO()
|
| 625 |
-
pq.write_table(table, buf, compression="zstd")
|
| 626 |
-
data = buf.getvalue()
|
| 627 |
-
|
| 628 |
-
shard_remote = self._shard_path(self._next_shard_idx)
|
| 629 |
-
logger.info(
|
| 630 |
-
f"Writing shard {self._next_shard_idx} ({len(self._buffer)} rows, "
|
| 631 |
-
f"{len(data) / 1024 / 1024:.1f} MiB) to {shard_remote}"
|
| 632 |
-
)
|
| 633 |
-
self._api.batch_bucket_files(
|
| 634 |
-
self.bucket_id, add=[(data, shard_remote)], token=self.hf_token
|
| 635 |
-
)
|
| 636 |
-
self._next_shard_idx += 1
|
| 637 |
-
self._buffer.clear()
|
| 638 |
-
|
| 639 |
-
def write(self, key: str, text: str, blocks: List[Dict[str, Any]]) -> None:
|
| 640 |
-
row: Dict[str, Any] = {
|
| 641 |
-
"__source_key": key,
|
| 642 |
-
"text": text,
|
| 643 |
-
"pp_ocr_blocks": json.dumps(blocks, ensure_ascii=False),
|
| 644 |
-
}
|
| 645 |
-
self._buffer.append(row)
|
| 646 |
-
if len(self._buffer) >= self.shard_size:
|
| 647 |
-
self._flush()
|
| 648 |
-
|
| 649 |
-
def finalize(self, tier: str, det_model: str, rec_model: str, args_dict: Dict[str, Any]) -> None:
|
| 650 |
-
self._flush()
|
| 651 |
-
meta = {
|
| 652 |
-
"model": f"PP-OCRv6_{tier}",
|
| 653 |
-
"det_model": det_model,
|
| 654 |
-
"rec_model": rec_model,
|
| 655 |
-
"tier": tier,
|
| 656 |
-
"engine": "paddle_static",
|
| 657 |
-
"source": self.source_id,
|
| 658 |
-
"shard_size": args_dict["shard_size"],
|
| 659 |
-
"last_run_at": datetime.now(timezone.utc).isoformat(),
|
| 660 |
-
"processing_time": args_dict.get("processing_time"),
|
| 661 |
-
}
|
| 662 |
-
meta_bytes = json.dumps(meta, indent=2).encode("utf-8")
|
| 663 |
-
meta_path = self._join(self.METADATA_FILE)
|
| 664 |
-
self._api.batch_bucket_files(
|
| 665 |
-
self.bucket_id, add=[(meta_bytes, meta_path)], token=self.hf_token
|
| 666 |
-
)
|
| 667 |
-
logger.info(
|
| 668 |
-
f"Done: https://huggingface.co/buckets/{self.bucket_id}"
|
| 669 |
-
+ (f"/{self.prefix}" if self.prefix else "")
|
| 670 |
-
)
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
# ---------------------------------------------------------------------------
|
| 674 |
-
# inference_info + dataset card
|
| 675 |
-
# ---------------------------------------------------------------------------
|
| 676 |
-
|
| 677 |
-
def build_inference_entry(tier: str, det_model: str, rec_model: str, args_dict: Dict[str, Any]) -> Dict[str, Any]:
|
| 678 |
-
return {
|
| 679 |
-
"model_id": f"PaddlePaddle/PP-OCRv6_{tier}",
|
| 680 |
-
"det_model": det_model,
|
| 681 |
-
"rec_model": rec_model,
|
| 682 |
-
"tier": tier,
|
| 683 |
-
"params": TIER_PARAMS.get(tier, "unknown"),
|
| 684 |
-
"rec_accuracy_pct": TIER_REC.get(tier),
|
| 685 |
-
"languages": TIER_LANGUAGES.get(tier, ""),
|
| 686 |
-
"engine": "paddle_static",
|
| 687 |
-
"output_column": "text",
|
| 688 |
-
"blocks_column": "pp_ocr_blocks",
|
| 689 |
-
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 690 |
-
}
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
def create_dataset_card(
|
| 694 |
-
source: str,
|
| 695 |
-
tier: str,
|
| 696 |
-
det_model: str,
|
| 697 |
-
rec_model: str,
|
| 698 |
-
num_samples: int,
|
| 699 |
-
processing_time: str,
|
| 700 |
-
engine: str,
|
| 701 |
-
output_id: str,
|
| 702 |
-
) -> str:
|
| 703 |
-
tier_display = tier.upper() if tier == "tiny" else tier.capitalize()
|
| 704 |
-
if is_bucket_url(source):
|
| 705 |
-
source_link = f"[{source}]({source})"
|
| 706 |
-
else:
|
| 707 |
-
source_link = f"[{source}](https://huggingface.co/datasets/{source})"
|
| 708 |
-
|
| 709 |
-
return f"""---
|
| 710 |
-
tags:
|
| 711 |
-
- ocr
|
| 712 |
-
- text-recognition
|
| 713 |
-
- paddleocr
|
| 714 |
-
- pp-ocrv6
|
| 715 |
-
- uv-script
|
| 716 |
-
- generated
|
| 717 |
-
---
|
| 718 |
-
|
| 719 |
-
# OCR with PP-OCRv6 {tier_display}
|
| 720 |
-
|
| 721 |
-
Plain-text OCR results for images from {source_link}, produced by
|
| 722 |
-
PaddlePaddle's [PP-OCRv6](https://huggingface.co/collections/PaddlePaddle/pp-ocrv6)
|
| 723 |
-
{tier} pipeline ({TIER_PARAMS.get(tier, "unknown")}).
|
| 724 |
-
|
| 725 |
-
## Processing details
|
| 726 |
-
|
| 727 |
-
- **Source**: {source_link}
|
| 728 |
-
- **Model**: PP-OCRv6_{tier} ({det_model} + {rec_model})
|
| 729 |
-
- **Tier**: {tier} ({TIER_PARAMS.get(tier, "unknown")})
|
| 730 |
-
- **Recognition accuracy**: {TIER_REC.get(tier, "?"):.1f}%
|
| 731 |
-
- **Languages**: {TIER_LANGUAGES.get(tier, "")}
|
| 732 |
-
- **Engine**: {engine}
|
| 733 |
-
- **Samples**: {num_samples:,}
|
| 734 |
-
- **Processing time**: {processing_time}
|
| 735 |
-
- **Processing date**: {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}
|
| 736 |
-
- **License**: Apache 2.0 (models)
|
| 737 |
-
|
| 738 |
-
## Schema
|
| 739 |
-
|
| 740 |
-
Each row contains the original columns plus:
|
| 741 |
-
|
| 742 |
-
- `text`: Plain text extracted from the image (reading-order concatenation of
|
| 743 |
-
detected text lines, newline-separated).
|
| 744 |
-
- `pp_ocr_blocks`: JSON list, one dict per detected text line:
|
| 745 |
-
```json
|
| 746 |
-
[
|
| 747 |
-
{{
|
| 748 |
-
"text": "recognized text",
|
| 749 |
-
"score": 0.987,
|
| 750 |
-
"bbox": [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
|
| 751 |
-
}}
|
| 752 |
-
]
|
| 753 |
-
```
|
| 754 |
-
`score` is the recognition confidence and `bbox` is the detection polygon
|
| 755 |
-
(4-point quadrilateral in input-image pixel coordinates).
|
| 756 |
-
- `inference_info`: JSON list tracking every model applied to this dataset.
|
| 757 |
-
|
| 758 |
-
> **Note:** PP-OCRv6 is a classical detection+recognition pipeline, not a VLM.
|
| 759 |
-
> It outputs **plain text** rather than markdown. Per-line bounding boxes and
|
| 760 |
-
> confidence scores are available in `pp_ocr_blocks`.
|
| 761 |
-
|
| 762 |
-
## Usage
|
| 763 |
-
|
| 764 |
-
```python
|
| 765 |
-
import json
|
| 766 |
-
from datasets import load_dataset
|
| 767 |
-
|
| 768 |
-
ds = load_dataset("{output_id}", split="train")
|
| 769 |
-
print(ds[0]["text"])
|
| 770 |
-
for block in json.loads(ds[0]["pp_ocr_blocks"]):
|
| 771 |
-
print(block["text"], block["score"])
|
| 772 |
-
```
|
| 773 |
-
|
| 774 |
-
## Reproduction
|
| 775 |
-
|
| 776 |
-
```bash
|
| 777 |
-
hf jobs uv run --flavor t4-small -s HF_TOKEN \\
|
| 778 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/pp-ocrv6.py \\
|
| 779 |
-
{source} <output> --model-tier {tier}
|
| 780 |
-
```
|
| 781 |
-
|
| 782 |
-
Generated with [UV Scripts](https://huggingface.co/uv-scripts).
|
| 783 |
-
"""
|
| 784 |
-
|
| 785 |
-
|
| 786 |
-
# ---------------------------------------------------------------------------
|
| 787 |
-
# Main
|
| 788 |
-
# ---------------------------------------------------------------------------
|
| 789 |
-
|
| 790 |
-
def main(args: argparse.Namespace) -> None:
|
| 791 |
-
from huggingface_hub import login
|
| 792 |
-
|
| 793 |
-
start_time = datetime.now()
|
| 794 |
-
hf_token = args.hf_token or os.environ.get("HF_TOKEN")
|
| 795 |
-
if hf_token:
|
| 796 |
-
login(token=hf_token)
|
| 797 |
-
|
| 798 |
-
# ---------- tier → model names ----------
|
| 799 |
-
if args.model_tier not in TIER_MODELS:
|
| 800 |
-
raise ValueError(
|
| 801 |
-
f"Invalid tier {args.model_tier!r}. Choose from: {list(TIER_MODELS)}"
|
| 802 |
-
)
|
| 803 |
-
det_model, rec_model = TIER_MODELS[args.model_tier]
|
| 804 |
-
tier = args.model_tier
|
| 805 |
-
logger.info(f"PP-OCRv6 {tier}: {det_model} + {rec_model}")
|
| 806 |
-
|
| 807 |
-
# ---------- source ----------
|
| 808 |
-
original_dataset = None
|
| 809 |
-
if is_bucket_url(args.input_source):
|
| 810 |
-
src_iter, total = iter_bucket_images(
|
| 811 |
-
args.input_source,
|
| 812 |
-
shuffle=args.shuffle,
|
| 813 |
-
seed=args.seed,
|
| 814 |
-
max_samples=args.max_samples,
|
| 815 |
-
hf_token=hf_token,
|
| 816 |
-
output_url=args.output_target,
|
| 817 |
-
)
|
| 818 |
-
else:
|
| 819 |
-
src_iter, total, original_dataset = iter_dataset_images(
|
| 820 |
-
args.input_source,
|
| 821 |
-
image_column=args.image_column,
|
| 822 |
-
split=args.split,
|
| 823 |
-
shuffle=args.shuffle,
|
| 824 |
-
seed=args.seed,
|
| 825 |
-
max_samples=args.max_samples,
|
| 826 |
-
)
|
| 827 |
-
|
| 828 |
-
# ---------- sink ----------
|
| 829 |
-
if is_bucket_url(args.output_target):
|
| 830 |
-
sink: Union[BucketShardSink, DatasetRepoSink] = BucketShardSink(
|
| 831 |
-
args.output_target,
|
| 832 |
-
hf_token=hf_token,
|
| 833 |
-
shard_size=args.shard_size,
|
| 834 |
-
resume=not args.no_resume,
|
| 835 |
-
source_id=args.input_source,
|
| 836 |
-
)
|
| 837 |
-
else:
|
| 838 |
-
sink = DatasetRepoSink(
|
| 839 |
-
args.output_target,
|
| 840 |
-
hf_token=hf_token,
|
| 841 |
-
private=args.private,
|
| 842 |
-
config=args.config,
|
| 843 |
-
create_pr=args.create_pr,
|
| 844 |
-
source_id=args.input_source,
|
| 845 |
-
original_dataset=original_dataset,
|
| 846 |
-
)
|
| 847 |
-
|
| 848 |
-
completed = sink.already_done()
|
| 849 |
-
|
| 850 |
-
# ---------- model ----------
|
| 851 |
-
# PaddleX gates `import cv2` at module load time on
|
| 852 |
-
# `is_dep_available("opencv-contrib-python")`, which checks
|
| 853 |
-
# `importlib.metadata.version(...)`. We ship `opencv-contrib-python-headless`
|
| 854 |
-
# (same `cv2`, no system libGL.so.1 needed) — but that's a different
|
| 855 |
-
# distribution name, so the gate fails and the OCR pipeline's `ocr` extra
|
| 856 |
-
# check returns False. Patch the metadata lookup to alias the GUI cv2 distros
|
| 857 |
-
# to the headless variant before importing paddleocr; this lets paddlex's own
|
| 858 |
-
# `import cv2` succeed and `is_extra_available('ocr')` return True.
|
| 859 |
-
import importlib.metadata as _metadata
|
| 860 |
-
|
| 861 |
-
_orig_metadata_version = _metadata.version
|
| 862 |
-
|
| 863 |
-
def _patched_metadata_version(dep_name):
|
| 864 |
-
if dep_name in ("opencv-contrib-python", "opencv-python"):
|
| 865 |
-
for headless_alias in (
|
| 866 |
-
"opencv-contrib-python-headless",
|
| 867 |
-
"opencv-python-headless",
|
| 868 |
-
):
|
| 869 |
-
try:
|
| 870 |
-
return _orig_metadata_version(headless_alias)
|
| 871 |
-
except _metadata.PackageNotFoundError:
|
| 872 |
-
continue
|
| 873 |
-
return _orig_metadata_version(dep_name)
|
| 874 |
-
|
| 875 |
-
_metadata.version = _patched_metadata_version
|
| 876 |
-
|
| 877 |
-
# Silence the connectivity check for speed (not needed in a Job)
|
| 878 |
-
os.environ.setdefault("PADDLE_PDX_DISABLE_MODEL_SOURCE_CHECK", "True")
|
| 879 |
-
|
| 880 |
-
from paddleocr import PaddleOCR
|
| 881 |
-
|
| 882 |
-
ocr = PaddleOCR(
|
| 883 |
-
text_detection_model_name=det_model,
|
| 884 |
-
text_recognition_model_name=rec_model,
|
| 885 |
-
use_doc_orientation_classify=False,
|
| 886 |
-
use_doc_unwarping=False,
|
| 887 |
-
use_textline_orientation=False,
|
| 888 |
-
)
|
| 889 |
-
|
| 890 |
-
# ---------- loop ----------
|
| 891 |
-
processed = 0
|
| 892 |
-
skipped = 0
|
| 893 |
-
errors = 0
|
| 894 |
-
pbar = tqdm(src_iter, total=total, desc=f"PP-OCRv6 {tier}")
|
| 895 |
-
for item in pbar:
|
| 896 |
-
if item.key in completed:
|
| 897 |
-
skipped += 1
|
| 898 |
-
continue
|
| 899 |
-
if item.extras.get("failed") or item.image is None:
|
| 900 |
-
# Unreadable source image — write an empty result in position so the
|
| 901 |
-
# output stays row-aligned with the source dataset.
|
| 902 |
-
sink.write(item.key, "", [])
|
| 903 |
-
errors += 1
|
| 904 |
-
processed += 1
|
| 905 |
-
continue
|
| 906 |
-
try:
|
| 907 |
-
arr = pil_to_array(item.image)
|
| 908 |
-
result = ocr.predict(arr)
|
| 909 |
-
if result:
|
| 910 |
-
text, blocks = extract_text(result[0])
|
| 911 |
-
else:
|
| 912 |
-
text, blocks = "", []
|
| 913 |
-
except Exception as e:
|
| 914 |
-
logger.error(f"Error on {item.key}: {e}")
|
| 915 |
-
text, blocks = "", []
|
| 916 |
-
errors += 1
|
| 917 |
-
|
| 918 |
-
sink.write(item.key, text, blocks)
|
| 919 |
-
processed += 1
|
| 920 |
-
|
| 921 |
-
duration = datetime.now() - start_time
|
| 922 |
-
processing_time_str = f"{duration.total_seconds() / 60:.2f} min"
|
| 923 |
-
logger.info(
|
| 924 |
-
f"Processed {processed} (skipped {skipped}, errors {errors}) in {processing_time_str}"
|
| 925 |
-
)
|
| 926 |
-
|
| 927 |
-
args_dict = {
|
| 928 |
-
"tier": tier,
|
| 929 |
-
"det_model": det_model,
|
| 930 |
-
"rec_model": rec_model,
|
| 931 |
-
"engine": "paddle_static",
|
| 932 |
-
"shard_size": args.shard_size,
|
| 933 |
-
"processing_time": processing_time_str,
|
| 934 |
-
}
|
| 935 |
-
sink.finalize(
|
| 936 |
-
tier=tier,
|
| 937 |
-
det_model=det_model,
|
| 938 |
-
rec_model=rec_model,
|
| 939 |
-
args_dict=args_dict,
|
| 940 |
-
)
|
| 941 |
-
|
| 942 |
-
if args.verbose:
|
| 943 |
-
import importlib.metadata
|
| 944 |
-
|
| 945 |
-
logger.info("--- Resolved package versions ---")
|
| 946 |
-
for pkg in [
|
| 947 |
-
"paddleocr",
|
| 948 |
-
"paddlex",
|
| 949 |
-
"paddlepaddle-gpu",
|
| 950 |
-
"huggingface-hub",
|
| 951 |
-
"datasets",
|
| 952 |
-
"pillow",
|
| 953 |
-
"numpy",
|
| 954 |
-
]:
|
| 955 |
-
try:
|
| 956 |
-
logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
|
| 957 |
-
except importlib.metadata.PackageNotFoundError:
|
| 958 |
-
logger.info(f" {pkg}: not installed")
|
| 959 |
-
logger.info("--- End versions ---")
|
| 960 |
-
|
| 961 |
-
|
| 962 |
-
# ---------------------------------------------------------------------------
|
| 963 |
-
# CLI
|
| 964 |
-
# ---------------------------------------------------------------------------
|
| 965 |
-
|
| 966 |
-
def build_parser() -> argparse.ArgumentParser:
|
| 967 |
-
p = argparse.ArgumentParser(
|
| 968 |
-
description="PP-OCRv6 OCR over an HF dataset or bucket of images.",
|
| 969 |
-
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 970 |
-
)
|
| 971 |
-
p.add_argument(
|
| 972 |
-
"input_source",
|
| 973 |
-
help="HF dataset id (namespace/dataset) OR hf://buckets/ns/bucket[/prefix]",
|
| 974 |
-
)
|
| 975 |
-
p.add_argument(
|
| 976 |
-
"output_target",
|
| 977 |
-
help="HF dataset id (namespace/dataset) OR hf://buckets/ns/bucket/run-name",
|
| 978 |
-
)
|
| 979 |
-
p.add_argument(
|
| 980 |
-
"--model-tier",
|
| 981 |
-
default="medium",
|
| 982 |
-
choices=list(TIER_MODELS),
|
| 983 |
-
help="PP-OCRv6 model tier: tiny (1.5M), small (7.7M), medium (34.5M). Default: medium.",
|
| 984 |
-
)
|
| 985 |
-
# Dataset-source-specific
|
| 986 |
-
p.add_argument(
|
| 987 |
-
"--image-column",
|
| 988 |
-
default="image",
|
| 989 |
-
help="Column containing images (dataset-repo source only, default: image)",
|
| 990 |
-
)
|
| 991 |
-
p.add_argument(
|
| 992 |
-
"--split",
|
| 993 |
-
default="train",
|
| 994 |
-
help="Dataset split (dataset-repo source only, default: train)",
|
| 995 |
-
)
|
| 996 |
-
p.add_argument(
|
| 997 |
-
"--max-samples", type=int, help="Limit number of samples (for testing)"
|
| 998 |
-
)
|
| 999 |
-
p.add_argument(
|
| 1000 |
-
"--shuffle", action="store_true", help="Shuffle source before processing"
|
| 1001 |
-
)
|
| 1002 |
-
p.add_argument(
|
| 1003 |
-
"--seed", type=int, default=42, help="Random seed for shuffle (default: 42)"
|
| 1004 |
-
)
|
| 1005 |
-
# Dataset-sink-specific
|
| 1006 |
-
p.add_argument(
|
| 1007 |
-
"--private", action="store_true", help="Private dataset output (dataset sink only)"
|
| 1008 |
-
)
|
| 1009 |
-
p.add_argument(
|
| 1010 |
-
"--config",
|
| 1011 |
-
help="Config/subset name when pushing to Hub (dataset sink only)",
|
| 1012 |
-
)
|
| 1013 |
-
p.add_argument(
|
| 1014 |
-
"--create-pr",
|
| 1015 |
-
action="store_true",
|
| 1016 |
-
help="Create PR instead of direct push (dataset sink only)",
|
| 1017 |
-
)
|
| 1018 |
-
# Bucket-sink-specific
|
| 1019 |
-
p.add_argument(
|
| 1020 |
-
"--shard-size",
|
| 1021 |
-
type=int,
|
| 1022 |
-
default=256,
|
| 1023 |
-
help="Rows per parquet shard for bucket sink (default: 256)",
|
| 1024 |
-
)
|
| 1025 |
-
p.add_argument(
|
| 1026 |
-
"--no-resume",
|
| 1027 |
-
action="store_true",
|
| 1028 |
-
help="Disable resume scan when writing to a bucket sink",
|
| 1029 |
-
)
|
| 1030 |
-
# Auth + diagnostics
|
| 1031 |
-
p.add_argument("--hf-token", help="Hugging Face API token (else uses HF_TOKEN env)")
|
| 1032 |
-
p.add_argument(
|
| 1033 |
-
"--verbose",
|
| 1034 |
-
action="store_true",
|
| 1035 |
-
help="Log resolved package versions at the end",
|
| 1036 |
-
)
|
| 1037 |
-
return p
|
| 1038 |
-
|
| 1039 |
-
|
| 1040 |
-
if __name__ == "__main__":
|
| 1041 |
-
main(build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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 |
|
serving-unlimited-ocr.md
DELETED
|
@@ -1,97 +0,0 @@
|
|
| 1 |
-
# Serve Unlimited-OCR as a live endpoint on HF Jobs
|
| 2 |
-
|
| 3 |
-
The OCR recipes in this folder run as batch jobs (dataset in → dataset out). To call a model
|
| 4 |
-
interactively, from an agent, or with ad-hoc concurrent requests, you can instead run it as a
|
| 5 |
-
temporary HTTP endpoint. [HF Jobs serving](https://huggingface.co/docs/hub/jobs-serving) exposes a
|
| 6 |
-
port on a GPU Job, giving an OpenAI-compatible endpoint that runs until the job is cancelled or its
|
| 7 |
-
`--timeout` is reached.
|
| 8 |
-
|
| 9 |
-
This is a worked example for [baidu/Unlimited-OCR](https://huggingface.co/baidu/Unlimited-OCR)
|
| 10 |
-
(3B, MIT, based on DeepSeek-OCR; supports multi-page parsing in a single request). The model ships
|
| 11 |
-
its own SGLang build, so it runs on the stock `lmsysorg/sglang` image with the 12 MB wheel
|
| 12 |
-
installed at startup; no custom image is required.
|
| 13 |
-
|
| 14 |
-
## 1. Start the server
|
| 15 |
-
|
| 16 |
-
```bash
|
| 17 |
-
hf jobs run --detach --expose 10000 --flavor h200 -s HF_TOKEN --timeout 30m \
|
| 18 |
-
lmsysorg/sglang:latest -- \
|
| 19 |
-
bash -lc 'pip install --no-deps https://github.com/baidu/Unlimited-OCR/raw/main/wheel/sglang-0.0.0.dev11416+g92e8bb79e-py3-none-any.whl \
|
| 20 |
-
&& pip install -q kernels==0.11.7 \
|
| 21 |
-
&& python -m sglang.launch_server --model baidu/Unlimited-OCR --served-model-name Unlimited-OCR \
|
| 22 |
-
--attention-backend fa3 --page-size 1 --mem-fraction-static 0.8 --context-length 32768 \
|
| 23 |
-
--enable-custom-logit-processor --disable-overlap-schedule --skip-server-warmup \
|
| 24 |
-
--host 0.0.0.0 --port 10000'
|
| 25 |
-
```
|
| 26 |
-
|
| 27 |
-
Notes:
|
| 28 |
-
- `--` before `bash` is required, or the CLI parses `-lc` as its own flags.
|
| 29 |
-
- `--timeout` stops the endpoint (and billing) at the deadline; `hf jobs cancel <id>` stops it earlier.
|
| 30 |
-
- `fa3` requires a Hopper GPU (e.g. `h200`). The model is small, so the attention backend, not GPU
|
| 31 |
-
memory, determines the flavor. Run `hf jobs hardware` for available flavors.
|
| 32 |
-
- Follow startup with `hf jobs logs -f <id>`; the server is ready at `Application startup complete`
|
| 33 |
-
(about 3 minutes from a cold start).
|
| 34 |
-
|
| 35 |
-
## 2. Call it (OpenAI client; HF token as the API key)
|
| 36 |
-
|
| 37 |
-
The exposed port is at `https://<job_id>--10000.hf.jobs`; the OpenAI base URL is that plus `/v1`.
|
| 38 |
-
|
| 39 |
-
```python
|
| 40 |
-
import base64, os
|
| 41 |
-
from openai import OpenAI
|
| 42 |
-
|
| 43 |
-
client = OpenAI(base_url="https://<job_id>--10000.hf.jobs/v1", api_key=os.environ["HF_TOKEN"])
|
| 44 |
-
img = base64.b64encode(open("page.jpg", "rb").read()).decode()
|
| 45 |
-
|
| 46 |
-
r = client.chat.completions.create(
|
| 47 |
-
model="Unlimited-OCR",
|
| 48 |
-
messages=[{"role": "user", "content": [
|
| 49 |
-
{"type": "text", "text": "document parsing."},
|
| 50 |
-
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{img}"}},
|
| 51 |
-
]}],
|
| 52 |
-
temperature=0,
|
| 53 |
-
extra_body={"images_config": {"image_mode": "gundam"}}, # "gundam" (crop-tiling) or "base"
|
| 54 |
-
)
|
| 55 |
-
print(r.choices[0].message.content)
|
| 56 |
-
```
|
| 57 |
-
|
| 58 |
-
Output is layout-grounded markdown: each block is tagged `<|det|>type [x1,y1,x2,y2]<|/det|> text`,
|
| 59 |
-
with coordinates normalized to 0–1000. Remove the tags for plain text
|
| 60 |
-
(`re.sub(r'<\|det\|>.*?<\|/det\|>', '', text)`) or keep them for structure.
|
| 61 |
-
|
| 62 |
-
## 3. Multi-page / PDF
|
| 63 |
-
|
| 64 |
-
Send multiple page images in one request with the `Multi page parsing.` prompt and `image_mode="base"`:
|
| 65 |
-
|
| 66 |
-
```python
|
| 67 |
-
parts = [{"type": "text", "text": "Multi page parsing."}]
|
| 68 |
-
for page_png in page_images: # e.g. PDF pages rendered with pymupdf at ~150 dpi
|
| 69 |
-
b64 = base64.b64encode(open(page_png, "rb").read()).decode()
|
| 70 |
-
parts.append({"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}})
|
| 71 |
-
|
| 72 |
-
r = client.chat.completions.create(
|
| 73 |
-
model="Unlimited-OCR",
|
| 74 |
-
messages=[{"role": "user", "content": parts}],
|
| 75 |
-
temperature=0, max_tokens=16384,
|
| 76 |
-
extra_body={"images_config": {"image_mode": "base"}},
|
| 77 |
-
)
|
| 78 |
-
```
|
| 79 |
-
|
| 80 |
-
Pages are separated by `<PAGE>`; tables are returned as HTML and equations as LaTeX, with reading
|
| 81 |
-
order preserved across pages. The context length is 32k tokens, so split longer documents.
|
| 82 |
-
|
| 83 |
-
## 4. Concurrency
|
| 84 |
-
|
| 85 |
-
SGLang batches concurrent requests, so a client can send many requests in parallel to one endpoint;
|
| 86 |
-
the upstream [`infer.py`](https://github.com/baidu/Unlimited-OCR/blob/main/infer.py) uses a
|
| 87 |
-
`ThreadPoolExecutor` at `concurrency=8`. For a large corpus, a batch job that runs next to the data
|
| 88 |
-
(resumable, no network transfer) is usually a better fit than a client-to-endpoint loop.
|
| 89 |
-
|
| 90 |
-
## 5. Stop it
|
| 91 |
-
|
| 92 |
-
```bash
|
| 93 |
-
hf jobs cancel <job_id>
|
| 94 |
-
```
|
| 95 |
-
|
| 96 |
-
Billing is per-minute for the GPU flavor plus a small flat fee for the exposed port; scheduling time
|
| 97 |
-
is not billed. Run `hf jobs hardware` for current flavors and prices.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
surya-ocr-bucket.py
DELETED
|
@@ -1,1389 +0,0 @@
|
|
| 1 |
-
# /// script
|
| 2 |
-
# requires-python = ">=3.10"
|
| 3 |
-
# dependencies = [
|
| 4 |
-
# "surya-ocr==0.20.0",
|
| 5 |
-
# "datasets>=3.1.0",
|
| 6 |
-
# "huggingface-hub",
|
| 7 |
-
# "pillow",
|
| 8 |
-
# "imagecodecs",
|
| 9 |
-
# "toolz",
|
| 10 |
-
# "tqdm",
|
| 11 |
-
# ]
|
| 12 |
-
#
|
| 13 |
-
# # Pin surya-ocr to the known-good build (has the `surya.inference` engine layout
|
| 14 |
-
# # this recipe injects into); an unpinned/loosened resolve backtracks to an ancient
|
| 15 |
-
# # surya without it. huggingface-hub is left unpinned: at runtime PYTHONPATH puts the
|
| 16 |
-
# # pinned image's hub (with the buckets API) ahead of the venv, so no version tension.
|
| 17 |
-
# ///
|
| 18 |
-
"""
|
| 19 |
-
Structured OCR over a **bucket of document files** (images + PDFs) with Datalab's
|
| 20 |
-
**Surya OCR 2** (`datalab-to/surya-ocr-2`, 650M, Qwen3.5-style) — no dataset
|
| 21 |
-
round-trip. This is the bucket-native sibling of `surya-ocr.py` (which reads a Hub
|
| 22 |
-
dataset column). Point it straight at an HF bucket of `.jp2`/`.png`/`.pdf`/... files.
|
| 23 |
-
|
| 24 |
-
Like the parent it produces *structured* OCR: per-block HTML + bounding boxes +
|
| 25 |
-
reading order + confidence. `--task` switches between `ocr` (full-page text),
|
| 26 |
-
`layout` (labelled regions), and `table` (HTML / rows-cols-cells).
|
| 27 |
-
|
| 28 |
-
INPUT — two interchangeable I/O strategies (`--io-mode`, default `auto`):
|
| 29 |
-
mount bucket mounted read-only at /in via `-v hf://buckets/<id>:/in:ro`; files
|
| 30 |
-
are read straight off the FUSE mount. Zero ephemeral disk.
|
| 31 |
-
copy take a bucket id directly; the huggingface_hub library LISTs then batch-
|
| 32 |
-
DOWNLOADS each `--batch-size` chunk to local temp, OCRs it, writes output,
|
| 33 |
-
then deletes the temp batch. Avoids the known FUSE bulk-read stall; peak
|
| 34 |
-
disk = one batch. `auto` picks copy for an `hf://buckets/...` input, mount
|
| 35 |
-
for a local dir.
|
| 36 |
-
|
| 37 |
-
OUTPUT — one or both (>=1 required):
|
| 38 |
-
--output-bucket per page a `.md` (flattened reading-order text) AND a `.json`
|
| 39 |
-
(that page's structured `surya_blocks`), mirroring the input dir
|
| 40 |
-
structure, into a mounted dir OR an `hf://buckets/...` URL.
|
| 41 |
-
Streaming / O(1) memory, with resume-by-skip (a file whose
|
| 42 |
-
`.json` already exists is skipped) — the scalable path.
|
| 43 |
-
--output-dataset a parquet dataset pushed to the Hub (one row per file:
|
| 44 |
-
file_name / markdown / surya_blocks / inference_info), like the
|
| 45 |
-
parent recipe. Convenient; buffered in memory (no image bytes by
|
| 46 |
-
default — use `--include-images` to embed page images).
|
| 47 |
-
|
| 48 |
-
ENGINE: Surya normally spawns a vLLM **server** (Docker), which can't run inside an
|
| 49 |
-
HF Job. This injects a custom in-process backend into Surya's `SuryaInferenceManager`
|
| 50 |
-
that runs vLLM's offline `LLM().chat()` engine (no server). Surya still owns all the
|
| 51 |
-
prompting, image preprocessing, and HTML/bbox parsing — we only swap the transport.
|
| 52 |
-
|
| 53 |
-
LICENSE NOTE: Surya's *code* is Apache-2.0 but the *weights* are a modified
|
| 54 |
-
OpenRAIL-M license — free for research, personal use, and startups under $5M
|
| 55 |
-
funding/revenue, restricted from competitive use against Datalab's API. Confirm you
|
| 56 |
-
are within those terms. https://huggingface.co/datalab-to/surya-ocr-2
|
| 57 |
-
|
| 58 |
-
HF Jobs — MUST use the pinned vLLM image + the site-packages python path (the model
|
| 59 |
-
is the recent, version-sensitive `qwen3_5` architecture; v0.20.1 is Surya's
|
| 60 |
-
known-good build, and it puts python/vLLM under /usr/local, NOT /usr/bin):
|
| 61 |
-
|
| 62 |
-
# copy input -> dataset output
|
| 63 |
-
hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
|
| 64 |
-
--image vllm/vllm-openai:v0.20.1 --python /usr/local/bin/python3 \\
|
| 65 |
-
-e PYTHONPATH=/usr/local/lib/python3.12/site-packages \\
|
| 66 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/surya-ocr-bucket.py \\
|
| 67 |
-
hf://buckets/<ns>/<bucket> --io-mode copy --glob "*.jp2" \\
|
| 68 |
-
--output-dataset <ns>/<out> --private
|
| 69 |
-
|
| 70 |
-
# mount input -> per-file bucket output (mirrors dir structure)
|
| 71 |
-
hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
|
| 72 |
-
--image vllm/vllm-openai:v0.20.1 --python /usr/local/bin/python3 \\
|
| 73 |
-
-e PYTHONPATH=/usr/local/lib/python3.12/site-packages \\
|
| 74 |
-
-v hf://buckets/<ns>/<bucket>:/in:ro \\
|
| 75 |
-
-v hf://buckets/<ns>/<out-bucket>:/out \\
|
| 76 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/surya-ocr-bucket.py \\
|
| 77 |
-
/in --io-mode mount --glob "*.jp2" --output-bucket /out
|
| 78 |
-
|
| 79 |
-
Model: datalab-to/surya-ocr-2 (package: surya-ocr, https://github.com/datalab-to/surya)
|
| 80 |
-
"""
|
| 81 |
-
|
| 82 |
-
import argparse
|
| 83 |
-
import json
|
| 84 |
-
import logging
|
| 85 |
-
import math
|
| 86 |
-
import os
|
| 87 |
-
import shutil
|
| 88 |
-
import sys
|
| 89 |
-
import tempfile
|
| 90 |
-
import time
|
| 91 |
-
from contextlib import contextmanager
|
| 92 |
-
from dataclasses import dataclass
|
| 93 |
-
from datetime import datetime, timezone
|
| 94 |
-
from fnmatch import fnmatch
|
| 95 |
-
from pathlib import Path, PurePosixPath
|
| 96 |
-
from typing import Any, Dict, Iterator, List, Optional, Tuple
|
| 97 |
-
|
| 98 |
-
from PIL import Image, UnidentifiedImageError
|
| 99 |
-
from toolz import partition_all
|
| 100 |
-
from tqdm import tqdm
|
| 101 |
-
|
| 102 |
-
logging.basicConfig(level=logging.INFO)
|
| 103 |
-
logger = logging.getLogger(__name__)
|
| 104 |
-
|
| 105 |
-
DEFAULT_MODEL = "datalab-to/surya-ocr-2"
|
| 106 |
-
# Surya's own vision-tiling bounds (from its vLLM backend), applied to the
|
| 107 |
-
# offline engine too so preprocessing matches the server path exactly.
|
| 108 |
-
MM_PROCESSOR_KWARGS = {"min_pixels": 3136, "max_pixels": 6291456}
|
| 109 |
-
TASKS = ("ocr", "layout", "table")
|
| 110 |
-
# Extensions read by default. `.jp2`/`.j2k` are first-class: the canonical test
|
| 111 |
-
# corpus (Library of Congress / Chronicling America) is all JPEG-2000.
|
| 112 |
-
DEFAULT_EXTENSIONS = ".jp2,.j2k,.png,.jpg,.jpeg,.tiff,.tif,.bmp,.webp,.pdf"
|
| 113 |
-
JP2_EXTENSIONS = {".jp2", ".j2k"}
|
| 114 |
-
PDF_EXTENSION = ".pdf"
|
| 115 |
-
BUCKET_PREFIX = "hf://buckets/"
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
# ---------------------------------------------------------------------------
|
| 119 |
-
# GPU / page-range helpers (verbatim from surya-ocr.py)
|
| 120 |
-
# ---------------------------------------------------------------------------
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
def check_cuda_availability() -> None:
|
| 124 |
-
"""Exit early with a clear message if there's no GPU."""
|
| 125 |
-
import torch
|
| 126 |
-
|
| 127 |
-
if not torch.cuda.is_available():
|
| 128 |
-
logger.error("CUDA is not available. This script requires a GPU.")
|
| 129 |
-
logger.error(
|
| 130 |
-
"Run on Hugging Face Jobs with: hf jobs uv run --flavor l4x1 "
|
| 131 |
-
"--image vllm/vllm-openai:v0.20.1 ..."
|
| 132 |
-
)
|
| 133 |
-
sys.exit(1)
|
| 134 |
-
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
def parse_page_range(spec: Optional[str]) -> Optional[List[int]]:
|
| 138 |
-
"""Turn '0-3,5' into [0,1,2,3,5]. None/empty -> None (all pages)."""
|
| 139 |
-
if not spec:
|
| 140 |
-
return None
|
| 141 |
-
pages: List[int] = []
|
| 142 |
-
for part in spec.split(","):
|
| 143 |
-
part = part.strip()
|
| 144 |
-
if not part:
|
| 145 |
-
continue
|
| 146 |
-
if "-" in part:
|
| 147 |
-
lo, hi = part.split("-", 1)
|
| 148 |
-
pages.extend(range(int(lo), int(hi) + 1))
|
| 149 |
-
else:
|
| 150 |
-
pages.append(int(part))
|
| 151 |
-
return pages or None
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
# --- structured-output shim (vLLM API moved between versions) ---
|
| 155 |
-
def build_structured_outputs(schema: Dict[str, Any]) -> Dict[str, Any]:
|
| 156 |
-
"""SamplingParams kwargs for guided JSON, across vLLM versions (layout uses this)."""
|
| 157 |
-
try:
|
| 158 |
-
from vllm.sampling_params import StructuredOutputsParams # vLLM >= 0.12
|
| 159 |
-
|
| 160 |
-
return {"structured_outputs": StructuredOutputsParams(json=schema)}
|
| 161 |
-
except (ImportError, TypeError):
|
| 162 |
-
pass
|
| 163 |
-
try:
|
| 164 |
-
from vllm.sampling_params import GuidedDecodingParams # older vLLM
|
| 165 |
-
|
| 166 |
-
return {"guided_decoding": GuidedDecodingParams(json=schema)}
|
| 167 |
-
except (ImportError, TypeError):
|
| 168 |
-
pass
|
| 169 |
-
logger.warning(
|
| 170 |
-
"Guided JSON unavailable in this vLLM version; relying on the model."
|
| 171 |
-
)
|
| 172 |
-
return {}
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
def _mean_token_prob(completion_output) -> Optional[float]:
|
| 176 |
-
"""Mean exp(logprob) of the sampled tokens -> Surya's per-block `confidence`."""
|
| 177 |
-
lps = getattr(completion_output, "logprobs", None)
|
| 178 |
-
if not lps:
|
| 179 |
-
return None
|
| 180 |
-
probs: List[float] = []
|
| 181 |
-
for tid, lp_dict in zip(completion_output.token_ids, lps):
|
| 182 |
-
if not lp_dict:
|
| 183 |
-
continue
|
| 184 |
-
entry = lp_dict.get(tid)
|
| 185 |
-
if (
|
| 186 |
-
entry is None
|
| 187 |
-
): # sampled token not in the returned top-k; use the best we have
|
| 188 |
-
entry = max(lp_dict.values(), key=lambda e: e.logprob)
|
| 189 |
-
probs.append(math.exp(entry.logprob))
|
| 190 |
-
return sum(probs) / len(probs) if probs else None
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
# ---------------------------------------------------------------------------
|
| 194 |
-
# Offline vLLM backend + Surya manager (verbatim from surya-ocr.py)
|
| 195 |
-
# ---------------------------------------------------------------------------
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
class OfflineVLLMBackend:
|
| 199 |
-
"""Surya `Backend` (duck-typed) that runs vLLM's offline `LLM().chat()` engine.
|
| 200 |
-
|
| 201 |
-
Surya's predictors call `manager.generate(batch)` -> `backend.generate(batch)`;
|
| 202 |
-
we satisfy that contract in-process (no server). Surya keeps ownership of the
|
| 203 |
-
prompts (`PROMPT_MAPPING`), image scaling (`scale_to_fit`), and output parsing.
|
| 204 |
-
"""
|
| 205 |
-
|
| 206 |
-
name = "offline-vllm"
|
| 207 |
-
|
| 208 |
-
def __init__(
|
| 209 |
-
self,
|
| 210 |
-
model: str,
|
| 211 |
-
max_model_len: int,
|
| 212 |
-
gpu_memory_utilization: float,
|
| 213 |
-
dtype: str = "bfloat16",
|
| 214 |
-
max_tokens_default: int = 2048,
|
| 215 |
-
logprobs_default: bool = True,
|
| 216 |
-
):
|
| 217 |
-
self.model = model
|
| 218 |
-
self.max_model_len = max_model_len
|
| 219 |
-
self.gpu_memory_utilization = gpu_memory_utilization
|
| 220 |
-
self.dtype = dtype
|
| 221 |
-
self.max_tokens_default = max_tokens_default
|
| 222 |
-
self.logprobs_default = logprobs_default
|
| 223 |
-
self.llm = None
|
| 224 |
-
self._build_messages = None
|
| 225 |
-
self._scale_to_fit = None
|
| 226 |
-
self._prompt_mapping = None
|
| 227 |
-
|
| 228 |
-
def start(self):
|
| 229 |
-
from vllm import LLM
|
| 230 |
-
|
| 231 |
-
logger.info(
|
| 232 |
-
f"Loading {self.model} into vLLM offline engine (dtype={self.dtype})..."
|
| 233 |
-
)
|
| 234 |
-
self.llm = LLM(
|
| 235 |
-
model=self.model,
|
| 236 |
-
dtype=self.dtype,
|
| 237 |
-
max_model_len=self.max_model_len,
|
| 238 |
-
gpu_memory_utilization=self.gpu_memory_utilization,
|
| 239 |
-
mm_processor_kwargs=MM_PROCESSOR_KWARGS,
|
| 240 |
-
limit_mm_per_prompt={"image": 1},
|
| 241 |
-
)
|
| 242 |
-
# Reuse Surya's exact request shaping so the offline path matches the server.
|
| 243 |
-
from surya.inference.backends.openai_client import _build_messages
|
| 244 |
-
from surya.inference.prompts import PROMPT_MAPPING
|
| 245 |
-
from surya.inference.util import scale_to_fit
|
| 246 |
-
|
| 247 |
-
self._build_messages = _build_messages
|
| 248 |
-
self._scale_to_fit = scale_to_fit
|
| 249 |
-
self._prompt_mapping = PROMPT_MAPPING
|
| 250 |
-
return None
|
| 251 |
-
|
| 252 |
-
def stop(self) -> None:
|
| 253 |
-
self.llm = None
|
| 254 |
-
|
| 255 |
-
def _sampling_params(self, item):
|
| 256 |
-
from vllm import SamplingParams
|
| 257 |
-
|
| 258 |
-
max_tokens = item.max_tokens or self.max_tokens_default
|
| 259 |
-
want_logprobs = item.request_logprobs or self.logprobs_default
|
| 260 |
-
kwargs: Dict[str, Any] = dict(temperature=0.0, top_p=0.1, max_tokens=max_tokens)
|
| 261 |
-
if want_logprobs:
|
| 262 |
-
kwargs["logprobs"] = 1
|
| 263 |
-
if item.guided_json is not None:
|
| 264 |
-
kwargs.update(build_structured_outputs(item.guided_json))
|
| 265 |
-
return SamplingParams(**kwargs)
|
| 266 |
-
|
| 267 |
-
def generate(self, batch):
|
| 268 |
-
from surya.inference.schema import BatchOutputItem
|
| 269 |
-
|
| 270 |
-
if self.llm is None:
|
| 271 |
-
self.start()
|
| 272 |
-
if not batch:
|
| 273 |
-
return []
|
| 274 |
-
|
| 275 |
-
conversations = []
|
| 276 |
-
sampling_params = []
|
| 277 |
-
for item in batch:
|
| 278 |
-
prompt = item.prompt or self._prompt_mapping[item.prompt_type]
|
| 279 |
-
image = self._scale_to_fit(item.image)
|
| 280 |
-
conversations.append(self._build_messages(image, prompt))
|
| 281 |
-
sampling_params.append(self._sampling_params(item))
|
| 282 |
-
|
| 283 |
-
outputs = self.llm.chat(
|
| 284 |
-
conversations,
|
| 285 |
-
sampling_params,
|
| 286 |
-
chat_template_content_format="openai",
|
| 287 |
-
use_tqdm=False,
|
| 288 |
-
)
|
| 289 |
-
|
| 290 |
-
results = []
|
| 291 |
-
for item, out in zip(batch, outputs):
|
| 292 |
-
comp = out.outputs[0]
|
| 293 |
-
results.append(
|
| 294 |
-
BatchOutputItem(
|
| 295 |
-
raw=comp.text,
|
| 296 |
-
token_count=len(comp.token_ids),
|
| 297 |
-
error=False,
|
| 298 |
-
mean_token_prob=_mean_token_prob(comp),
|
| 299 |
-
logprobs=None,
|
| 300 |
-
metadata=item.metadata, # carries page_idx/block_idx — must round-trip
|
| 301 |
-
)
|
| 302 |
-
)
|
| 303 |
-
return results
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
def make_manager(backend: OfflineVLLMBackend):
|
| 307 |
-
"""A SuryaInferenceManager wired to our offline backend (bypassing autodetect)."""
|
| 308 |
-
from surya.inference import SuryaInferenceManager
|
| 309 |
-
|
| 310 |
-
manager = SuryaInferenceManager.__new__(SuryaInferenceManager)
|
| 311 |
-
manager.method = backend.name
|
| 312 |
-
manager.backend = backend
|
| 313 |
-
return manager
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
# ---------------------------------------------------------------------------
|
| 317 |
-
# Result serialization (verbatim from surya-ocr.py)
|
| 318 |
-
# ---------------------------------------------------------------------------
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
def _html_to_text(html: str) -> str:
|
| 322 |
-
from bs4 import BeautifulSoup
|
| 323 |
-
|
| 324 |
-
return BeautifulSoup(html, "html.parser").get_text(" ", strip=True)
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
def serialize_pages(task: str, pages: List[Any]) -> Tuple[str, List[Dict[str, Any]]]:
|
| 328 |
-
"""(text, structured-per-page) for one document's page results."""
|
| 329 |
-
structured = [p.model_dump(mode="json") for p in pages]
|
| 330 |
-
page_texts: List[str] = []
|
| 331 |
-
for page in pages:
|
| 332 |
-
if task == "ocr":
|
| 333 |
-
parts = []
|
| 334 |
-
for b in sorted(page.blocks, key=lambda b: b.reading_order):
|
| 335 |
-
if b.skipped or not b.html:
|
| 336 |
-
continue
|
| 337 |
-
txt = _html_to_text(b.html)
|
| 338 |
-
if txt:
|
| 339 |
-
parts.append(txt)
|
| 340 |
-
page_texts.append("\n".join(parts))
|
| 341 |
-
elif task == "layout":
|
| 342 |
-
# No OCR text in layout mode — emit a reading-order outline of labels.
|
| 343 |
-
page_texts.append(
|
| 344 |
-
"\n".join(
|
| 345 |
-
f"{b.position}: {b.label}"
|
| 346 |
-
for b in sorted(page.bboxes, key=lambda b: b.position)
|
| 347 |
-
)
|
| 348 |
-
)
|
| 349 |
-
else: # table
|
| 350 |
-
if page.html: # mode="full"
|
| 351 |
-
page_texts.append(page.html)
|
| 352 |
-
else: # mode="simple"
|
| 353 |
-
page_texts.append(f"{len(page.rows)} rows x {len(page.cols)} cols")
|
| 354 |
-
return "\n\n".join(page_texts), structured
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
def serialize_per_page(task: str, pages: List[Any]) -> List[Tuple[str, Dict[str, Any]]]:
|
| 358 |
-
"""Per-page (text, structured-dict). Reuses `serialize_pages` one page at a time
|
| 359 |
-
so the per-file dataset row and the per-page bucket files share one code path."""
|
| 360 |
-
out: List[Tuple[str, Dict[str, Any]]] = []
|
| 361 |
-
for page in pages:
|
| 362 |
-
text, structured = serialize_pages(task, [page])
|
| 363 |
-
out.append((text, structured[0]))
|
| 364 |
-
return out
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
# ---------------------------------------------------------------------------
|
| 368 |
-
# Bucket-URL helpers (verbatim from pp-doclayout.py)
|
| 369 |
-
# ---------------------------------------------------------------------------
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
def is_bucket_url(s: str) -> bool:
|
| 373 |
-
return s.startswith(BUCKET_PREFIX)
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
def parse_bucket_url(url: str) -> Tuple[str, str]:
|
| 377 |
-
"""Split `hf://buckets/ns/bucket/path/in/bucket` into (`ns/bucket`, `path/in/bucket`)."""
|
| 378 |
-
if not is_bucket_url(url):
|
| 379 |
-
raise ValueError(f"Not a bucket URL: {url}")
|
| 380 |
-
rest = url[len(BUCKET_PREFIX) :].strip("/")
|
| 381 |
-
parts = rest.split("/", 2)
|
| 382 |
-
if len(parts) < 2:
|
| 383 |
-
raise ValueError(f"Bucket URL must include namespace and bucket name: {url}")
|
| 384 |
-
bucket_id = f"{parts[0]}/{parts[1]}"
|
| 385 |
-
prefix = parts[2] if len(parts) > 2 else ""
|
| 386 |
-
return bucket_id, prefix
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
# ---------------------------------------------------------------------------
|
| 390 |
-
# Image / PDF loading
|
| 391 |
-
# ---------------------------------------------------------------------------
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
def open_image(path: Path) -> Image.Image:
|
| 395 |
-
"""Open one image as RGB. Falls back to imagecodecs for JPEG-2000, which the
|
| 396 |
-
image's bundled Pillow may not decode (no OpenJPEG)."""
|
| 397 |
-
try:
|
| 398 |
-
return Image.open(path).convert("RGB")
|
| 399 |
-
except (UnidentifiedImageError, OSError):
|
| 400 |
-
if path.suffix.lower() in JP2_EXTENSIONS:
|
| 401 |
-
import imagecodecs
|
| 402 |
-
|
| 403 |
-
arr = imagecodecs.imread(str(path))
|
| 404 |
-
logger.debug(f"Decoded {path.name} via imagecodecs (Pillow fallback)")
|
| 405 |
-
return Image.fromarray(arr).convert("RGB")
|
| 406 |
-
raise
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
def load_pages(
|
| 410 |
-
kind: str,
|
| 411 |
-
local_path: Path,
|
| 412 |
-
load_pdf,
|
| 413 |
-
page_indices: Optional[List[int]],
|
| 414 |
-
pdf_dpi: int,
|
| 415 |
-
) -> List[Image.Image]:
|
| 416 |
-
"""A local document file -> list of RGB page images (1 for an image, N for a PDF)."""
|
| 417 |
-
if kind == "pdf":
|
| 418 |
-
images, _ = load_pdf(str(local_path), page_indices, dpi=pdf_dpi)
|
| 419 |
-
return [im.convert("RGB") for im in images]
|
| 420 |
-
return [open_image(local_path)]
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
# ---------------------------------------------------------------------------
|
| 424 |
-
# File listing + sources (mount vs copy)
|
| 425 |
-
# ---------------------------------------------------------------------------
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
@dataclass
|
| 429 |
-
class FileRef:
|
| 430 |
-
"""One input document. `key`/`rel` are the source-relative POSIX path (stable
|
| 431 |
-
across runs -> resume) and drive output mirroring. `local_path` is set in mount
|
| 432 |
-
mode; `bucket_file`/`bucket_path` in copy mode."""
|
| 433 |
-
|
| 434 |
-
key: str
|
| 435 |
-
rel: PurePosixPath
|
| 436 |
-
kind: str # "image" | "pdf"
|
| 437 |
-
local_path: Optional[Path] = None
|
| 438 |
-
bucket_file: Any = None
|
| 439 |
-
bucket_path: Optional[str] = None
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
def classify(path_str: str, exts: set) -> Optional[str]:
|
| 443 |
-
"""Map a path to "pdf"/"image"/None using the allowed-extension set."""
|
| 444 |
-
ext = PurePosixPath(path_str).suffix.lower()
|
| 445 |
-
if ext == PDF_EXTENSION and PDF_EXTENSION in exts:
|
| 446 |
-
return "pdf"
|
| 447 |
-
if ext in exts:
|
| 448 |
-
return "image"
|
| 449 |
-
return None
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
def _shuffle_slice(
|
| 453 |
-
refs: List[FileRef], shuffle: bool, seed: int, max_samples: Optional[int]
|
| 454 |
-
) -> List[FileRef]:
|
| 455 |
-
refs.sort(key=lambda r: r.key)
|
| 456 |
-
if shuffle:
|
| 457 |
-
import random
|
| 458 |
-
|
| 459 |
-
random.Random(seed).shuffle(refs)
|
| 460 |
-
if max_samples:
|
| 461 |
-
refs = refs[:max_samples]
|
| 462 |
-
return refs
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
class MountSource:
|
| 466 |
-
"""Read files straight off a directory (a bucket mounted read-only at /in)."""
|
| 467 |
-
|
| 468 |
-
mode = "mount"
|
| 469 |
-
|
| 470 |
-
def __init__(self, root: Path, glob: str, exts: set):
|
| 471 |
-
self.root = root
|
| 472 |
-
self.glob = glob
|
| 473 |
-
self.exts = exts
|
| 474 |
-
|
| 475 |
-
def list_refs(
|
| 476 |
-
self, shuffle: bool, seed: int, max_samples: Optional[int]
|
| 477 |
-
) -> List[FileRef]:
|
| 478 |
-
refs: List[FileRef] = []
|
| 479 |
-
for path in self.root.rglob("*"):
|
| 480 |
-
if not path.is_file():
|
| 481 |
-
continue
|
| 482 |
-
rel = path.relative_to(self.root)
|
| 483 |
-
rel_posix = rel.as_posix()
|
| 484 |
-
kind = classify(rel_posix, self.exts)
|
| 485 |
-
if kind is None or not fnmatch(rel_posix, self.glob):
|
| 486 |
-
continue
|
| 487 |
-
refs.append(
|
| 488 |
-
FileRef(
|
| 489 |
-
key=rel_posix,
|
| 490 |
-
rel=PurePosixPath(rel_posix),
|
| 491 |
-
kind=kind,
|
| 492 |
-
local_path=path,
|
| 493 |
-
)
|
| 494 |
-
)
|
| 495 |
-
return _shuffle_slice(refs, shuffle, seed, max_samples)
|
| 496 |
-
|
| 497 |
-
@contextmanager
|
| 498 |
-
def materialize(
|
| 499 |
-
self, chunk: List[FileRef], load_pdf, page_indices, pdf_dpi
|
| 500 |
-
) -> Iterator[List[Tuple[FileRef, Optional[List[Image.Image]]]]]:
|
| 501 |
-
loaded: List[Tuple[FileRef, Optional[List[Image.Image]]]] = []
|
| 502 |
-
for ref in chunk:
|
| 503 |
-
loaded.append(
|
| 504 |
-
(
|
| 505 |
-
ref,
|
| 506 |
-
_safe_load(
|
| 507 |
-
ref.kind, ref.local_path, load_pdf, page_indices, pdf_dpi
|
| 508 |
-
),
|
| 509 |
-
)
|
| 510 |
-
)
|
| 511 |
-
yield loaded # nothing to clean up — reads are off the mount
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
class CopySource:
|
| 515 |
-
"""List + batch-download bucket files via huggingface_hub to local temp, then
|
| 516 |
-
delete the batch. The non-FUSE path (sidesteps the bulk-read stall)."""
|
| 517 |
-
|
| 518 |
-
mode = "copy"
|
| 519 |
-
|
| 520 |
-
def __init__(self, bucket_url: str, glob: str, exts: set, hf_token: Optional[str]):
|
| 521 |
-
from huggingface_hub import HfApi
|
| 522 |
-
|
| 523 |
-
self.bucket_id, self.prefix = parse_bucket_url(bucket_url)
|
| 524 |
-
self.glob = glob
|
| 525 |
-
self.exts = exts
|
| 526 |
-
self.hf_token = hf_token
|
| 527 |
-
self.api = HfApi(token=hf_token)
|
| 528 |
-
|
| 529 |
-
def list_refs(
|
| 530 |
-
self, shuffle: bool, seed: int, max_samples: Optional[int]
|
| 531 |
-
) -> List[FileRef]:
|
| 532 |
-
logger.info(
|
| 533 |
-
f"Listing bucket {self.bucket_id}"
|
| 534 |
-
+ (f"/{self.prefix}" if self.prefix else "")
|
| 535 |
-
)
|
| 536 |
-
refs: List[FileRef] = []
|
| 537 |
-
for item in self.api.list_bucket_tree(
|
| 538 |
-
self.bucket_id, prefix=self.prefix or None, recursive=True
|
| 539 |
-
):
|
| 540 |
-
path = getattr(item, "path", None)
|
| 541 |
-
if not path:
|
| 542 |
-
continue
|
| 543 |
-
kind = classify(path, self.exts)
|
| 544 |
-
if kind is None:
|
| 545 |
-
continue
|
| 546 |
-
rel = path[len(self.prefix) :].lstrip("/") if self.prefix else path
|
| 547 |
-
if not fnmatch(rel, self.glob):
|
| 548 |
-
continue
|
| 549 |
-
refs.append(
|
| 550 |
-
FileRef(
|
| 551 |
-
key=rel,
|
| 552 |
-
rel=PurePosixPath(rel),
|
| 553 |
-
kind=kind,
|
| 554 |
-
bucket_file=item,
|
| 555 |
-
bucket_path=path,
|
| 556 |
-
)
|
| 557 |
-
)
|
| 558 |
-
logger.info(f"Found {len(refs)} matching file(s) in bucket")
|
| 559 |
-
return _shuffle_slice(refs, shuffle, seed, max_samples)
|
| 560 |
-
|
| 561 |
-
@contextmanager
|
| 562 |
-
def materialize(
|
| 563 |
-
self, chunk: List[FileRef], load_pdf, page_indices, pdf_dpi
|
| 564 |
-
) -> Iterator[List[Tuple[FileRef, Optional[List[Image.Image]]]]]:
|
| 565 |
-
tmp = Path(tempfile.mkdtemp(prefix="surya-copy-"))
|
| 566 |
-
try:
|
| 567 |
-
# Pass the BucketFile objects from list_bucket_tree so download skips the
|
| 568 |
-
# per-file metadata HEAD. Local names are index-keyed to avoid collisions.
|
| 569 |
-
files = []
|
| 570 |
-
locals_: List[Path] = []
|
| 571 |
-
for i, ref in enumerate(chunk):
|
| 572 |
-
local = tmp / f"{i:05d}{PurePosixPath(ref.bucket_path).suffix}"
|
| 573 |
-
files.append((ref.bucket_file, str(local)))
|
| 574 |
-
locals_.append(local)
|
| 575 |
-
self.api.download_bucket_files(
|
| 576 |
-
self.bucket_id, files=files, token=self.hf_token
|
| 577 |
-
)
|
| 578 |
-
loaded: List[Tuple[FileRef, Optional[List[Image.Image]]]] = []
|
| 579 |
-
for ref, local in zip(chunk, locals_):
|
| 580 |
-
if not local.exists():
|
| 581 |
-
logger.warning(f"Download missing for {ref.key}; skipping")
|
| 582 |
-
loaded.append((ref, None))
|
| 583 |
-
continue
|
| 584 |
-
loaded.append(
|
| 585 |
-
(ref, _safe_load(ref.kind, local, load_pdf, page_indices, pdf_dpi))
|
| 586 |
-
)
|
| 587 |
-
yield loaded
|
| 588 |
-
finally:
|
| 589 |
-
shutil.rmtree(tmp, ignore_errors=True)
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
def _safe_load(
|
| 593 |
-
kind: str, local_path: Path, load_pdf, page_indices, pdf_dpi
|
| 594 |
-
) -> Optional[List[Image.Image]]:
|
| 595 |
-
try:
|
| 596 |
-
return load_pages(kind, local_path, load_pdf, page_indices, pdf_dpi)
|
| 597 |
-
except Exception as e: # noqa: BLE001 — a single bad file shouldn't kill the run
|
| 598 |
-
logger.warning(f"Failed to load {local_path.name}: {type(e).__name__}: {e}")
|
| 599 |
-
return None
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
# ---------------------------------------------------------------------------
|
| 603 |
-
# Sinks
|
| 604 |
-
# ---------------------------------------------------------------------------
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
class BucketFilesSink:
|
| 608 |
-
"""Per page, write `<rel>.md` + `<rel>.json` (PDFs: `<stem>/page_NNN.{md,json}`),
|
| 609 |
-
mirroring the input structure, to a mounted dir OR an `hf://buckets/...` URL.
|
| 610 |
-
Streaming / O(1) memory. Resume-by-skip keys on the `.json` (written last)."""
|
| 611 |
-
|
| 612 |
-
def __init__(self, output_target: str, hf_token: Optional[str], resume: bool):
|
| 613 |
-
self.resume = resume
|
| 614 |
-
self.api_mode = is_bucket_url(output_target)
|
| 615 |
-
if self.api_mode:
|
| 616 |
-
from huggingface_hub import HfApi
|
| 617 |
-
|
| 618 |
-
self.bucket_id, self.prefix = parse_bucket_url(output_target)
|
| 619 |
-
self.api = HfApi(token=hf_token)
|
| 620 |
-
self.token = hf_token
|
| 621 |
-
self._buffer: List[Tuple[bytes, str]] = []
|
| 622 |
-
self._existing = self._load_existing() if resume else set()
|
| 623 |
-
else:
|
| 624 |
-
self.root = Path(output_target)
|
| 625 |
-
self.root.mkdir(parents=True, exist_ok=True)
|
| 626 |
-
|
| 627 |
-
@property
|
| 628 |
-
def label(self) -> str:
|
| 629 |
-
return (
|
| 630 |
-
f"hf://buckets/{self.bucket_id}/{self.prefix}".rstrip("/")
|
| 631 |
-
if self.api_mode
|
| 632 |
-
else str(self.root)
|
| 633 |
-
)
|
| 634 |
-
|
| 635 |
-
def _join(self, rel: str) -> str:
|
| 636 |
-
return f"{self.prefix}/{rel}".lstrip("/") if self.prefix else rel
|
| 637 |
-
|
| 638 |
-
def _load_existing(self) -> set:
|
| 639 |
-
existing = set()
|
| 640 |
-
try:
|
| 641 |
-
for item in self.api.list_bucket_tree(
|
| 642 |
-
self.bucket_id, prefix=self.prefix or None, recursive=True
|
| 643 |
-
):
|
| 644 |
-
p = getattr(item, "path", None)
|
| 645 |
-
if p and p.endswith(".json"):
|
| 646 |
-
existing.add(p)
|
| 647 |
-
except Exception as e: # noqa: BLE001
|
| 648 |
-
logger.warning(f"Could not pre-list output bucket for resume: {e}")
|
| 649 |
-
if existing:
|
| 650 |
-
logger.info(f"Resume: {len(existing)} output file(s) already present")
|
| 651 |
-
return existing
|
| 652 |
-
|
| 653 |
-
def _page_targets(self, ref: FileRef, n_pages: int) -> List[Tuple[str, str]]:
|
| 654 |
-
if ref.kind == "pdf":
|
| 655 |
-
stem = ref.rel.with_suffix("")
|
| 656 |
-
return [
|
| 657 |
-
(
|
| 658 |
-
str(stem / f"page_{i + 1:03d}.md"),
|
| 659 |
-
str(stem / f"page_{i + 1:03d}.json"),
|
| 660 |
-
)
|
| 661 |
-
for i in range(n_pages)
|
| 662 |
-
]
|
| 663 |
-
return [(str(ref.rel.with_suffix(".md")), str(ref.rel.with_suffix(".json")))]
|
| 664 |
-
|
| 665 |
-
def is_done(self, ref: FileRef) -> bool:
|
| 666 |
-
# Resume applies to single-image files only; PDFs are re-rendered (idempotent
|
| 667 |
-
# overwrite) since page count isn't known without opening them.
|
| 668 |
-
if not self.resume or ref.kind == "pdf":
|
| 669 |
-
return False
|
| 670 |
-
json_rel = str(ref.rel.with_suffix(".json"))
|
| 671 |
-
if self.api_mode:
|
| 672 |
-
return self._join(json_rel) in self._existing
|
| 673 |
-
return (self.root / json_rel).exists()
|
| 674 |
-
|
| 675 |
-
def write_pages(
|
| 676 |
-
self,
|
| 677 |
-
ref: FileRef,
|
| 678 |
-
per_page: List[Tuple[str, Dict[str, Any]]],
|
| 679 |
-
pages: Optional[List[Image.Image]],
|
| 680 |
-
) -> None:
|
| 681 |
-
targets = self._page_targets(ref, len(per_page))
|
| 682 |
-
for (text, struct), (md_rel, json_rel) in zip(per_page, targets):
|
| 683 |
-
md_bytes = text.encode("utf-8")
|
| 684 |
-
json_bytes = json.dumps(struct, ensure_ascii=False).encode("utf-8")
|
| 685 |
-
if self.api_mode:
|
| 686 |
-
# .md first, .json last so a present .json marks the page complete.
|
| 687 |
-
self._buffer.append((md_bytes, self._join(md_rel)))
|
| 688 |
-
self._buffer.append((json_bytes, self._join(json_rel)))
|
| 689 |
-
else:
|
| 690 |
-
mp = self.root / md_rel
|
| 691 |
-
mp.parent.mkdir(parents=True, exist_ok=True)
|
| 692 |
-
mp.write_bytes(md_bytes)
|
| 693 |
-
(self.root / json_rel).write_bytes(json_bytes)
|
| 694 |
-
|
| 695 |
-
def write_error(self, ref: FileRef) -> None:
|
| 696 |
-
# Write nothing on error so the file is retried on the next (resumed) run.
|
| 697 |
-
pass
|
| 698 |
-
|
| 699 |
-
def flush(self) -> None:
|
| 700 |
-
if self.api_mode and self._buffer:
|
| 701 |
-
self.api.batch_bucket_files(
|
| 702 |
-
self.bucket_id, add=self._buffer, token=self.token
|
| 703 |
-
)
|
| 704 |
-
self._buffer = []
|
| 705 |
-
|
| 706 |
-
def finalize(self, summary: Dict[str, Any]) -> None:
|
| 707 |
-
self.flush()
|
| 708 |
-
logger.info(f"Bucket files written to {self.label}")
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
class DatasetSink:
|
| 712 |
-
"""Buffer one row per file, push a parquet dataset at the end (like surya-ocr.py)."""
|
| 713 |
-
|
| 714 |
-
def __init__(
|
| 715 |
-
self,
|
| 716 |
-
repo_id: str,
|
| 717 |
-
*,
|
| 718 |
-
hf_token: Optional[str],
|
| 719 |
-
private: bool,
|
| 720 |
-
config: Optional[str],
|
| 721 |
-
create_pr: bool,
|
| 722 |
-
include_images: bool,
|
| 723 |
-
output_column: str,
|
| 724 |
-
blocks_column: str,
|
| 725 |
-
):
|
| 726 |
-
self.repo_id = repo_id
|
| 727 |
-
self.hf_token = hf_token
|
| 728 |
-
self.private = private
|
| 729 |
-
self.config = config
|
| 730 |
-
self.create_pr = create_pr
|
| 731 |
-
self.include_images = include_images
|
| 732 |
-
self.output_column = output_column
|
| 733 |
-
self.blocks_column = blocks_column
|
| 734 |
-
self._rows: List[Dict[str, Any]] = []
|
| 735 |
-
|
| 736 |
-
def is_done(self, ref: FileRef) -> bool:
|
| 737 |
-
return False # single push at the end; no per-file resume
|
| 738 |
-
|
| 739 |
-
def write_pages(
|
| 740 |
-
self,
|
| 741 |
-
ref: FileRef,
|
| 742 |
-
per_page: List[Tuple[str, Dict[str, Any]]],
|
| 743 |
-
pages: Optional[List[Image.Image]],
|
| 744 |
-
) -> None:
|
| 745 |
-
row = {
|
| 746 |
-
"file_name": ref.key,
|
| 747 |
-
"num_pages": len(per_page),
|
| 748 |
-
self.output_column: "\n\n".join(t for t, _ in per_page),
|
| 749 |
-
self.blocks_column: json.dumps(
|
| 750 |
-
[s for _, s in per_page], ensure_ascii=False
|
| 751 |
-
),
|
| 752 |
-
}
|
| 753 |
-
if self.include_images and pages:
|
| 754 |
-
# First page only (keeps a single Image column); documented limitation.
|
| 755 |
-
row["image"] = pages[0]
|
| 756 |
-
self._rows.append(row)
|
| 757 |
-
|
| 758 |
-
def write_error(self, ref: FileRef) -> None:
|
| 759 |
-
self._rows.append(
|
| 760 |
-
{
|
| 761 |
-
"file_name": ref.key,
|
| 762 |
-
"num_pages": 0,
|
| 763 |
-
self.output_column: "[SURYA ERROR]",
|
| 764 |
-
self.blocks_column: None,
|
| 765 |
-
}
|
| 766 |
-
)
|
| 767 |
-
|
| 768 |
-
def flush(self) -> None:
|
| 769 |
-
pass # single push at finalize
|
| 770 |
-
|
| 771 |
-
def finalize(self, summary: Dict[str, Any]) -> None:
|
| 772 |
-
from datasets import Dataset
|
| 773 |
-
|
| 774 |
-
if not self._rows:
|
| 775 |
-
logger.warning("No rows produced; nothing to push to the dataset.")
|
| 776 |
-
return
|
| 777 |
-
|
| 778 |
-
inference_entry = {
|
| 779 |
-
"model": summary["model"],
|
| 780 |
-
"model_name": "surya-ocr-2",
|
| 781 |
-
"column_name": self.output_column,
|
| 782 |
-
"blocks_column": self.blocks_column,
|
| 783 |
-
"task": summary["task"],
|
| 784 |
-
"table_mode": summary["table_mode"] if summary["task"] == "table" else None,
|
| 785 |
-
"backend": "vllm-offline",
|
| 786 |
-
"source": summary["source"],
|
| 787 |
-
"io_mode": summary["io_mode"],
|
| 788 |
-
"glob": summary["glob"],
|
| 789 |
-
"page_range": summary["page_range"],
|
| 790 |
-
"error_rate": summary["error_rate"],
|
| 791 |
-
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 792 |
-
"script": "surya-ocr-bucket.py",
|
| 793 |
-
}
|
| 794 |
-
for row in self._rows:
|
| 795 |
-
row["inference_info"] = json.dumps([inference_entry])
|
| 796 |
-
|
| 797 |
-
ds = Dataset.from_list(self._rows)
|
| 798 |
-
if self.include_images and "image" in ds.column_names:
|
| 799 |
-
try:
|
| 800 |
-
from datasets import Image as HFImage
|
| 801 |
-
|
| 802 |
-
ds = ds.cast_column("image", HFImage())
|
| 803 |
-
except Exception as e: # noqa: BLE001
|
| 804 |
-
logger.warning(f"Could not cast image column: {e}")
|
| 805 |
-
|
| 806 |
-
logger.info(f"Pushing {len(ds)} rows to {self.repo_id}")
|
| 807 |
-
push_kwargs = {
|
| 808 |
-
"private": self.private,
|
| 809 |
-
"token": self.hf_token,
|
| 810 |
-
"max_shard_size": "500MB",
|
| 811 |
-
"create_pr": self.create_pr,
|
| 812 |
-
"commit_message": f"Add Surya OCR 2 {summary['task']} results ({len(ds)} files)"
|
| 813 |
-
+ (f" [{self.config}]" if self.config else ""),
|
| 814 |
-
}
|
| 815 |
-
if self.config:
|
| 816 |
-
push_kwargs["config_name"] = self.config
|
| 817 |
-
|
| 818 |
-
for attempt in range(1, 4):
|
| 819 |
-
try:
|
| 820 |
-
if attempt > 1:
|
| 821 |
-
logger.warning("Disabling XET (fallback to HTTP upload)")
|
| 822 |
-
os.environ["HF_HUB_DISABLE_XET"] = "1"
|
| 823 |
-
ds.push_to_hub(self.repo_id, **push_kwargs)
|
| 824 |
-
break
|
| 825 |
-
except Exception as e: # noqa: BLE001
|
| 826 |
-
logger.error(f"Upload attempt {attempt}/3 failed: {e}")
|
| 827 |
-
if attempt == 3:
|
| 828 |
-
logger.error("All upload attempts failed.")
|
| 829 |
-
raise
|
| 830 |
-
time.sleep(30 * (2 ** (attempt - 1)))
|
| 831 |
-
|
| 832 |
-
self._push_card(summary, len(ds))
|
| 833 |
-
logger.info(f"Dataset: https://huggingface.co/datasets/{self.repo_id}")
|
| 834 |
-
|
| 835 |
-
def _push_card(self, summary: Dict[str, Any], n_rows: int) -> None:
|
| 836 |
-
try:
|
| 837 |
-
from huggingface_hub import DatasetCard
|
| 838 |
-
|
| 839 |
-
card = DatasetCard(
|
| 840 |
-
_dataset_card(
|
| 841 |
-
source=summary["source"],
|
| 842 |
-
model=summary["model"],
|
| 843 |
-
task=summary["task"],
|
| 844 |
-
table_mode=summary["table_mode"],
|
| 845 |
-
io_mode=summary["io_mode"],
|
| 846 |
-
n_files=n_rows,
|
| 847 |
-
n_ok=summary["n_ok"],
|
| 848 |
-
output_column=self.output_column,
|
| 849 |
-
blocks_column=self.blocks_column,
|
| 850 |
-
processing_time=summary["processing_time"],
|
| 851 |
-
)
|
| 852 |
-
)
|
| 853 |
-
card.push_to_hub(self.repo_id, token=self.hf_token)
|
| 854 |
-
except Exception as e: # noqa: BLE001
|
| 855 |
-
logger.warning(f"Could not push dataset card: {e}")
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
def _dataset_card(
|
| 859 |
-
source: str,
|
| 860 |
-
model: str,
|
| 861 |
-
task: str,
|
| 862 |
-
table_mode: str,
|
| 863 |
-
io_mode: str,
|
| 864 |
-
n_files: int,
|
| 865 |
-
n_ok: int,
|
| 866 |
-
output_column: str,
|
| 867 |
-
blocks_column: str,
|
| 868 |
-
processing_time: str,
|
| 869 |
-
) -> str:
|
| 870 |
-
task_desc = {
|
| 871 |
-
"ocr": "full-page OCR (structured HTML + bounding boxes)",
|
| 872 |
-
"layout": "layout analysis (labelled regions + reading order)",
|
| 873 |
-
"table": f"table recognition (mode `{table_mode}`)",
|
| 874 |
-
}[task]
|
| 875 |
-
return f"""---
|
| 876 |
-
tags:
|
| 877 |
-
- ocr
|
| 878 |
-
- document-processing
|
| 879 |
-
- surya
|
| 880 |
-
- structured
|
| 881 |
-
- uv-script
|
| 882 |
-
- generated
|
| 883 |
-
---
|
| 884 |
-
|
| 885 |
-
# Surya OCR 2 ({task}) on {source}
|
| 886 |
-
|
| 887 |
-
{task_desc.capitalize()} over document files in the HF bucket
|
| 888 |
-
`{source}`, using [Surya OCR 2](https://huggingface.co/{model}) (650M, Qwen3.5-based)
|
| 889 |
-
by Datalab, via the [`surya-ocr`](https://github.com/datalab-to/surya) package, run
|
| 890 |
-
as **offline vLLM batch inference** on Hugging Face Jobs (`surya-ocr-bucket.py`).
|
| 891 |
-
|
| 892 |
-
## Processing Details
|
| 893 |
-
|
| 894 |
-
- **Source bucket**: `{source}`
|
| 895 |
-
- **Model**: [{model}](https://huggingface.co/{model})
|
| 896 |
-
- **Task**: `{task}`{f" (table mode `{table_mode}`)" if task == "table" else ""}
|
| 897 |
-
- **I/O mode**: `{io_mode}`
|
| 898 |
-
- **Text column**: `{output_column}` (flattened, reading-order text per file)
|
| 899 |
-
- **Structured column**: `{blocks_column}` (JSON: per-page blocks with bbox / polygon / label / reading_order / confidence / html)
|
| 900 |
-
- **Files**: {n_files:,}
|
| 901 |
-
- **Processed OK**: {n_ok:,} / {n_files:,}
|
| 902 |
-
- **Processing time**: {processing_time}
|
| 903 |
-
- **Date**: {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}
|
| 904 |
-
|
| 905 |
-
## License note
|
| 906 |
-
|
| 907 |
-
Surya's code is Apache-2.0, but the model **weights** use a modified OpenRAIL-M
|
| 908 |
-
license: free for research, personal use, and startups under $5M funding/revenue,
|
| 909 |
-
restricted from competitive use against Datalab's API. See the
|
| 910 |
-
[model card](https://huggingface.co/{model}).
|
| 911 |
-
|
| 912 |
-
## Dataset Structure
|
| 913 |
-
|
| 914 |
-
One row per source file:
|
| 915 |
-
- `file_name`: source-relative path in the bucket
|
| 916 |
-
- `num_pages`: pages OCR'd (1 for an image, N for a PDF)
|
| 917 |
-
- `{output_column}`: flattened text (OCR), label outline (layout), or table HTML (table)
|
| 918 |
-
- `{blocks_column}`: structured result as a JSON string (one entry per page)
|
| 919 |
-
- `inference_info`: JSON list tracking models applied
|
| 920 |
-
|
| 921 |
-
Generated with [UV Scripts](https://huggingface.co/uv-scripts).
|
| 922 |
-
"""
|
| 923 |
-
|
| 924 |
-
|
| 925 |
-
# ---------------------------------------------------------------------------
|
| 926 |
-
# Predictor + processing loop
|
| 927 |
-
# ---------------------------------------------------------------------------
|
| 928 |
-
|
| 929 |
-
|
| 930 |
-
def build_predictor(task: str, table_mode: str, manager):
|
| 931 |
-
"""Return a `run(images) -> page_results` closure (verbatim dispatch from parent)."""
|
| 932 |
-
if task == "ocr":
|
| 933 |
-
from surya.recognition import RecognitionPredictor
|
| 934 |
-
|
| 935 |
-
predictor = RecognitionPredictor(manager)
|
| 936 |
-
|
| 937 |
-
def run(images):
|
| 938 |
-
return predictor(images, full_page=True)
|
| 939 |
-
elif task == "layout":
|
| 940 |
-
from surya.layout import LayoutPredictor
|
| 941 |
-
|
| 942 |
-
predictor = LayoutPredictor(manager)
|
| 943 |
-
|
| 944 |
-
def run(images):
|
| 945 |
-
return predictor(images)
|
| 946 |
-
else: # table
|
| 947 |
-
from surya.table_rec import TableRecPredictor
|
| 948 |
-
|
| 949 |
-
predictor = TableRecPredictor(manager)
|
| 950 |
-
|
| 951 |
-
def run(images):
|
| 952 |
-
return predictor(images, mode=table_mode)
|
| 953 |
-
|
| 954 |
-
return run
|
| 955 |
-
|
| 956 |
-
|
| 957 |
-
def process(
|
| 958 |
-
refs: List[FileRef],
|
| 959 |
-
source,
|
| 960 |
-
run,
|
| 961 |
-
task: str,
|
| 962 |
-
sinks: List[Any],
|
| 963 |
-
batch_size: int,
|
| 964 |
-
load_pdf,
|
| 965 |
-
page_indices: Optional[List[int]],
|
| 966 |
-
pdf_dpi: int,
|
| 967 |
-
) -> Tuple[int, int, int, float, float]:
|
| 968 |
-
"""Resume-filter, then OCR file-by-file in batches.
|
| 969 |
-
|
| 970 |
-
Returns (processed, ok, errors, io_secs, inf_secs). `io_secs` is time spent
|
| 971 |
-
materializing batches (FUSE reads in mount mode; list-skip + batch download in
|
| 972 |
-
copy mode); `inf_secs` is engine time (incl. one-time model load on the first
|
| 973 |
-
batch). The split lets the mount-vs-copy benchmark isolate I/O from inference."""
|
| 974 |
-
pending = [r for r in refs if not all(s.is_done(r) for s in sinks)]
|
| 975 |
-
skipped = len(refs) - len(pending)
|
| 976 |
-
if skipped:
|
| 977 |
-
logger.info(f"Resume: skipping {skipped} already-complete file(s)")
|
| 978 |
-
logger.info(f"Processing {len(pending)} file(s)")
|
| 979 |
-
|
| 980 |
-
processed = ok = errors = 0
|
| 981 |
-
io_secs = inf_secs = 0.0
|
| 982 |
-
pbar = tqdm(total=len(pending), desc=f"Surya {task}")
|
| 983 |
-
for chunk in partition_all(batch_size, pending):
|
| 984 |
-
chunk = list(chunk)
|
| 985 |
-
t_io = time.monotonic()
|
| 986 |
-
with source.materialize(chunk, load_pdf, page_indices, pdf_dpi) as loaded:
|
| 987 |
-
io_secs += time.monotonic() - t_io
|
| 988 |
-
entries: List[Tuple[FileRef, List[Image.Image], int, int]] = []
|
| 989 |
-
flat: List[Image.Image] = []
|
| 990 |
-
for ref, pages in loaded:
|
| 991 |
-
if not pages:
|
| 992 |
-
for s in sinks:
|
| 993 |
-
s.write_error(ref)
|
| 994 |
-
errors += 1
|
| 995 |
-
processed += 1
|
| 996 |
-
pbar.update(1)
|
| 997 |
-
continue
|
| 998 |
-
entries.append((ref, pages, len(flat), len(pages)))
|
| 999 |
-
flat.extend(pages)
|
| 1000 |
-
|
| 1001 |
-
if flat:
|
| 1002 |
-
t_inf = time.monotonic()
|
| 1003 |
-
try:
|
| 1004 |
-
results = run(flat)
|
| 1005 |
-
except Exception as e: # noqa: BLE001
|
| 1006 |
-
logger.error(f"Batch generate failed: {e}")
|
| 1007 |
-
results = None
|
| 1008 |
-
inf_secs += time.monotonic() - t_inf
|
| 1009 |
-
|
| 1010 |
-
if results is None:
|
| 1011 |
-
for ref, _pages, _start, _count in entries:
|
| 1012 |
-
for s in sinks:
|
| 1013 |
-
s.write_error(ref)
|
| 1014 |
-
errors += 1
|
| 1015 |
-
processed += 1
|
| 1016 |
-
pbar.update(1)
|
| 1017 |
-
else:
|
| 1018 |
-
for ref, pages, start, count in entries:
|
| 1019 |
-
per_page = serialize_per_page(
|
| 1020 |
-
task, results[start : start + count]
|
| 1021 |
-
)
|
| 1022 |
-
for s in sinks:
|
| 1023 |
-
s.write_pages(ref, per_page, pages)
|
| 1024 |
-
ok += 1
|
| 1025 |
-
processed += 1
|
| 1026 |
-
pbar.update(1)
|
| 1027 |
-
|
| 1028 |
-
for s in sinks:
|
| 1029 |
-
s.flush()
|
| 1030 |
-
pbar.close()
|
| 1031 |
-
return processed, ok, errors, io_secs, inf_secs
|
| 1032 |
-
|
| 1033 |
-
|
| 1034 |
-
# ---------------------------------------------------------------------------
|
| 1035 |
-
# Main
|
| 1036 |
-
# ---------------------------------------------------------------------------
|
| 1037 |
-
|
| 1038 |
-
|
| 1039 |
-
def resolve_io_mode(io_mode: str, input_source: str) -> str:
|
| 1040 |
-
if io_mode == "auto":
|
| 1041 |
-
return "copy" if is_bucket_url(input_source) else "mount"
|
| 1042 |
-
return io_mode
|
| 1043 |
-
|
| 1044 |
-
|
| 1045 |
-
def main(args: argparse.Namespace) -> None:
|
| 1046 |
-
# Unlock full Xet bandwidth for the model download (repo convention).
|
| 1047 |
-
os.environ["HF_XET_HIGH_PERFORMANCE"] = "1"
|
| 1048 |
-
# Surya reads settings from env at import; pin the checkpoint and forbid any
|
| 1049 |
-
# server autostart (we inject our own offline backend instead).
|
| 1050 |
-
os.environ["SURYA_MODEL_CHECKPOINT"] = args.model
|
| 1051 |
-
os.environ["SURYA_INFERENCE_AUTOSTART"] = "False"
|
| 1052 |
-
|
| 1053 |
-
check_cuda_availability()
|
| 1054 |
-
start_time = datetime.now(timezone.utc)
|
| 1055 |
-
|
| 1056 |
-
hf_token = args.hf_token or os.environ.get("HF_TOKEN")
|
| 1057 |
-
if hf_token:
|
| 1058 |
-
from huggingface_hub import login
|
| 1059 |
-
|
| 1060 |
-
login(token=hf_token)
|
| 1061 |
-
|
| 1062 |
-
exts = {e.strip().lower() for e in args.extensions.split(",") if e.strip()}
|
| 1063 |
-
io_mode = resolve_io_mode(args.io_mode, args.input_source)
|
| 1064 |
-
|
| 1065 |
-
# ---------- source ----------
|
| 1066 |
-
if io_mode == "copy":
|
| 1067 |
-
if not is_bucket_url(args.input_source):
|
| 1068 |
-
logger.error("--io-mode copy requires an hf://buckets/... input.")
|
| 1069 |
-
sys.exit(1)
|
| 1070 |
-
source = CopySource(args.input_source, args.glob, exts, hf_token)
|
| 1071 |
-
else:
|
| 1072 |
-
root = Path(args.input_source)
|
| 1073 |
-
if not root.is_dir():
|
| 1074 |
-
logger.error(
|
| 1075 |
-
f"--io-mode mount requires an existing directory (got {root}). "
|
| 1076 |
-
"Mount the bucket with -v hf://buckets/<id>:/in:ro and pass /in."
|
| 1077 |
-
)
|
| 1078 |
-
sys.exit(1)
|
| 1079 |
-
source = MountSource(root, args.glob, exts)
|
| 1080 |
-
logger.info(f"I/O mode: {io_mode} Input: {args.input_source}")
|
| 1081 |
-
|
| 1082 |
-
# ---------- sinks ----------
|
| 1083 |
-
sinks: List[Any] = []
|
| 1084 |
-
if args.output_bucket:
|
| 1085 |
-
sinks.append(
|
| 1086 |
-
BucketFilesSink(args.output_bucket, hf_token, resume=not args.no_resume)
|
| 1087 |
-
)
|
| 1088 |
-
if args.output_dataset:
|
| 1089 |
-
sinks.append(
|
| 1090 |
-
DatasetSink(
|
| 1091 |
-
args.output_dataset,
|
| 1092 |
-
hf_token=hf_token,
|
| 1093 |
-
private=args.private,
|
| 1094 |
-
config=args.config,
|
| 1095 |
-
create_pr=args.create_pr,
|
| 1096 |
-
include_images=args.include_images,
|
| 1097 |
-
output_column=args.output_column,
|
| 1098 |
-
blocks_column=args.blocks_column,
|
| 1099 |
-
)
|
| 1100 |
-
)
|
| 1101 |
-
|
| 1102 |
-
# ---------- import Surya only after env is set ----------
|
| 1103 |
-
from surya.input.load import load_pdf
|
| 1104 |
-
from surya.settings import settings
|
| 1105 |
-
|
| 1106 |
-
page_indices = parse_page_range(args.page_range)
|
| 1107 |
-
pdf_dpi = args.pdf_dpi if args.pdf_dpi else settings.IMAGE_DPI_HIGHRES
|
| 1108 |
-
|
| 1109 |
-
t_list = time.monotonic()
|
| 1110 |
-
refs = source.list_refs(args.shuffle, args.seed, args.max_samples)
|
| 1111 |
-
list_secs = time.monotonic() - t_list
|
| 1112 |
-
if not refs:
|
| 1113 |
-
logger.error("No matching files found. Check --glob / --extensions / input.")
|
| 1114 |
-
sys.exit(1)
|
| 1115 |
-
logger.info(
|
| 1116 |
-
f"{len(refs)} file(s) listed in {list_secs:.1f}s | Model: {args.model} "
|
| 1117 |
-
f"Task: {args.task}"
|
| 1118 |
-
+ (f" (mode {args.table_mode})" if args.task == "table" else "")
|
| 1119 |
-
)
|
| 1120 |
-
|
| 1121 |
-
# ---------- engine ----------
|
| 1122 |
-
backend = OfflineVLLMBackend(
|
| 1123 |
-
model=args.model,
|
| 1124 |
-
max_model_len=args.max_model_len,
|
| 1125 |
-
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 1126 |
-
dtype=args.dtype,
|
| 1127 |
-
)
|
| 1128 |
-
manager = make_manager(backend)
|
| 1129 |
-
run = build_predictor(args.task, args.table_mode, manager)
|
| 1130 |
-
|
| 1131 |
-
processed, ok, errors, io_secs, inf_secs = process(
|
| 1132 |
-
refs,
|
| 1133 |
-
source,
|
| 1134 |
-
run,
|
| 1135 |
-
args.task,
|
| 1136 |
-
sinks,
|
| 1137 |
-
args.batch_size,
|
| 1138 |
-
load_pdf,
|
| 1139 |
-
page_indices,
|
| 1140 |
-
pdf_dpi,
|
| 1141 |
-
)
|
| 1142 |
-
|
| 1143 |
-
processing_time = (
|
| 1144 |
-
f"{(datetime.now(timezone.utc) - start_time).total_seconds() / 60:.1f} min"
|
| 1145 |
-
)
|
| 1146 |
-
logger.info(
|
| 1147 |
-
f"Processed {processed} (ok {ok}, errors {errors}) in {processing_time}"
|
| 1148 |
-
)
|
| 1149 |
-
# Benchmark breakdown: separate listing + per-batch I/O from engine time so the
|
| 1150 |
-
# mount-vs-copy comparison isn't swamped by (identical) inference + model load.
|
| 1151 |
-
pages_per_sec = ok / io_secs if io_secs else 0.0
|
| 1152 |
-
logger.info(
|
| 1153 |
-
f"[timing] io_mode={io_mode} list={list_secs:.1f}s io={io_secs:.1f}s "
|
| 1154 |
-
f"inference={inf_secs:.1f}s files={ok} io_files_per_sec={pages_per_sec:.2f}"
|
| 1155 |
-
)
|
| 1156 |
-
|
| 1157 |
-
summary = {
|
| 1158 |
-
"model": args.model,
|
| 1159 |
-
"task": args.task,
|
| 1160 |
-
"table_mode": args.table_mode,
|
| 1161 |
-
"source": args.input_source,
|
| 1162 |
-
"io_mode": io_mode,
|
| 1163 |
-
"glob": args.glob,
|
| 1164 |
-
"page_range": args.page_range,
|
| 1165 |
-
"n_ok": ok,
|
| 1166 |
-
"error_rate": (processed - ok) / processed if processed else 0.0,
|
| 1167 |
-
"processing_time": processing_time,
|
| 1168 |
-
}
|
| 1169 |
-
for s in sinks:
|
| 1170 |
-
s.finalize(summary)
|
| 1171 |
-
|
| 1172 |
-
logger.info("Done! Surya OCR 2 (bucket) complete.")
|
| 1173 |
-
|
| 1174 |
-
if args.verbose:
|
| 1175 |
-
import importlib.metadata
|
| 1176 |
-
|
| 1177 |
-
logger.info("--- Resolved package versions ---")
|
| 1178 |
-
for pkg in [
|
| 1179 |
-
"surya-ocr",
|
| 1180 |
-
"vllm",
|
| 1181 |
-
"transformers",
|
| 1182 |
-
"torch",
|
| 1183 |
-
"datasets",
|
| 1184 |
-
"huggingface-hub",
|
| 1185 |
-
"pillow",
|
| 1186 |
-
"imagecodecs",
|
| 1187 |
-
]:
|
| 1188 |
-
try:
|
| 1189 |
-
logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
|
| 1190 |
-
except importlib.metadata.PackageNotFoundError:
|
| 1191 |
-
logger.info(f" {pkg}: not installed")
|
| 1192 |
-
|
| 1193 |
-
|
| 1194 |
-
# ---------------------------------------------------------------------------
|
| 1195 |
-
# CLI
|
| 1196 |
-
# ---------------------------------------------------------------------------
|
| 1197 |
-
|
| 1198 |
-
|
| 1199 |
-
def build_parser() -> argparse.ArgumentParser:
|
| 1200 |
-
parser = argparse.ArgumentParser(
|
| 1201 |
-
description="Surya OCR 2 (650M): structured OCR / layout / tables over a bucket of files",
|
| 1202 |
-
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 1203 |
-
epilog="""
|
| 1204 |
-
I/O modes (--io-mode):
|
| 1205 |
-
auto copy for an hf://buckets/... input, mount for a local dir (default)
|
| 1206 |
-
mount read off a bucket mounted read-only at /in (-v hf://buckets/<id>:/in:ro)
|
| 1207 |
-
copy list + batch-download via huggingface_hub to temp, OCR, delete the batch
|
| 1208 |
-
|
| 1209 |
-
Outputs (at least one required):
|
| 1210 |
-
--output-bucket per-page .md + .json mirroring input structure (mounted dir or
|
| 1211 |
-
hf://buckets/... URL); resumable, O(1) memory
|
| 1212 |
-
--output-dataset parquet dataset push (one row per file)
|
| 1213 |
-
|
| 1214 |
-
Run on the vllm/vllm-openai:v0.20.1 image (offline vLLM batch; qwen3_5 is
|
| 1215 |
-
version-sensitive — the site-packages python path is load-bearing):
|
| 1216 |
-
--image vllm/vllm-openai:v0.20.1 --python /usr/local/bin/python3 \\
|
| 1217 |
-
-e PYTHONPATH=/usr/local/lib/python3.12/site-packages
|
| 1218 |
-
""",
|
| 1219 |
-
)
|
| 1220 |
-
parser.add_argument(
|
| 1221 |
-
"input_source",
|
| 1222 |
-
help="Mounted dir (e.g. /in) OR hf://buckets/<ns>/<bucket>[/prefix]",
|
| 1223 |
-
)
|
| 1224 |
-
parser.add_argument(
|
| 1225 |
-
"--io-mode",
|
| 1226 |
-
choices=["auto", "mount", "copy"],
|
| 1227 |
-
default="auto",
|
| 1228 |
-
help="Input I/O strategy (default: auto)",
|
| 1229 |
-
)
|
| 1230 |
-
parser.add_argument(
|
| 1231 |
-
"--glob",
|
| 1232 |
-
default="*",
|
| 1233 |
-
help="fnmatch pattern over the source-relative path (default: '*'; "
|
| 1234 |
-
"e.g. '*.jp2'). Applied on top of --extensions.",
|
| 1235 |
-
)
|
| 1236 |
-
parser.add_argument(
|
| 1237 |
-
"--extensions",
|
| 1238 |
-
default=DEFAULT_EXTENSIONS,
|
| 1239 |
-
help=f"Comma-separated file extensions to read (default: {DEFAULT_EXTENSIONS})",
|
| 1240 |
-
)
|
| 1241 |
-
parser.add_argument(
|
| 1242 |
-
"--output-bucket",
|
| 1243 |
-
default=None,
|
| 1244 |
-
help="Per-file .md + .json output: a mounted dir OR hf://buckets/<id>[/prefix]",
|
| 1245 |
-
)
|
| 1246 |
-
parser.add_argument(
|
| 1247 |
-
"--output-dataset",
|
| 1248 |
-
default=None,
|
| 1249 |
-
help="Output dataset repo ID (parquet, one row per file)",
|
| 1250 |
-
)
|
| 1251 |
-
parser.add_argument(
|
| 1252 |
-
"--no-resume",
|
| 1253 |
-
action="store_true",
|
| 1254 |
-
help="Disable resume-by-skip for --output-bucket (re-OCR everything)",
|
| 1255 |
-
)
|
| 1256 |
-
parser.add_argument(
|
| 1257 |
-
"--task", choices=TASKS, default="ocr", help="Task (default: ocr)"
|
| 1258 |
-
)
|
| 1259 |
-
parser.add_argument(
|
| 1260 |
-
"--table-mode",
|
| 1261 |
-
choices=["full", "simple"],
|
| 1262 |
-
default="full",
|
| 1263 |
-
help="Table task: 'full' = HTML, 'simple' = rows/cols/cells (default: full)",
|
| 1264 |
-
)
|
| 1265 |
-
parser.add_argument(
|
| 1266 |
-
"--page-range",
|
| 1267 |
-
default=None,
|
| 1268 |
-
help="Pages from PDFs, e.g. '0-5,7' (PDFs only)",
|
| 1269 |
-
)
|
| 1270 |
-
parser.add_argument(
|
| 1271 |
-
"--pdf-dpi",
|
| 1272 |
-
type=int,
|
| 1273 |
-
default=None,
|
| 1274 |
-
help="DPI for PDF rendering (default: Surya's IMAGE_DPI_HIGHRES)",
|
| 1275 |
-
)
|
| 1276 |
-
parser.add_argument(
|
| 1277 |
-
"--max-samples", type=int, help="Limit number of files (for testing)"
|
| 1278 |
-
)
|
| 1279 |
-
parser.add_argument(
|
| 1280 |
-
"--shuffle", action="store_true", help="Shuffle before sampling"
|
| 1281 |
-
)
|
| 1282 |
-
parser.add_argument(
|
| 1283 |
-
"--seed", type=int, default=42, help="Shuffle seed (default: 42)"
|
| 1284 |
-
)
|
| 1285 |
-
parser.add_argument(
|
| 1286 |
-
"--batch-size",
|
| 1287 |
-
type=int,
|
| 1288 |
-
default=16,
|
| 1289 |
-
help="Images per offline llm.chat batch AND per copy-mode download/cleanup unit (default: 16)",
|
| 1290 |
-
)
|
| 1291 |
-
parser.add_argument(
|
| 1292 |
-
"--max-model-len",
|
| 1293 |
-
type=int,
|
| 1294 |
-
default=18000,
|
| 1295 |
-
help="vLLM context length (default: 18000)",
|
| 1296 |
-
)
|
| 1297 |
-
parser.add_argument(
|
| 1298 |
-
"--gpu-memory-utilization",
|
| 1299 |
-
type=float,
|
| 1300 |
-
default=0.85,
|
| 1301 |
-
help="vLLM GPU memory fraction (default: 0.85)",
|
| 1302 |
-
)
|
| 1303 |
-
parser.add_argument(
|
| 1304 |
-
"--dtype",
|
| 1305 |
-
default="bfloat16",
|
| 1306 |
-
help="vLLM dtype (default: bfloat16; use float16 on T4/Turing)",
|
| 1307 |
-
)
|
| 1308 |
-
parser.add_argument(
|
| 1309 |
-
"--model", default=DEFAULT_MODEL, help=f"Model ID (default: {DEFAULT_MODEL})"
|
| 1310 |
-
)
|
| 1311 |
-
parser.add_argument(
|
| 1312 |
-
"--output-column",
|
| 1313 |
-
default="markdown",
|
| 1314 |
-
help="Dataset text column (default: markdown)",
|
| 1315 |
-
)
|
| 1316 |
-
parser.add_argument(
|
| 1317 |
-
"--blocks-column",
|
| 1318 |
-
default="surya_blocks",
|
| 1319 |
-
help="Dataset structured JSON column (default: surya_blocks)",
|
| 1320 |
-
)
|
| 1321 |
-
parser.add_argument(
|
| 1322 |
-
"--include-images",
|
| 1323 |
-
action="store_true",
|
| 1324 |
-
help="Embed the first page image in --output-dataset (memory-heavy)",
|
| 1325 |
-
)
|
| 1326 |
-
parser.add_argument(
|
| 1327 |
-
"--private", action="store_true", help="Make output dataset private"
|
| 1328 |
-
)
|
| 1329 |
-
parser.add_argument(
|
| 1330 |
-
"--config",
|
| 1331 |
-
default=None,
|
| 1332 |
-
help="Config/subset name when pushing (for benchmarking in one repo)",
|
| 1333 |
-
)
|
| 1334 |
-
parser.add_argument(
|
| 1335 |
-
"--create-pr",
|
| 1336 |
-
action="store_true",
|
| 1337 |
-
help="Push dataset as a pull request instead of directly",
|
| 1338 |
-
)
|
| 1339 |
-
parser.add_argument("--hf-token", help="Hugging Face API token (or set HF_TOKEN)")
|
| 1340 |
-
parser.add_argument(
|
| 1341 |
-
"--verbose",
|
| 1342 |
-
action="store_true",
|
| 1343 |
-
help="Log resolved package versions after processing",
|
| 1344 |
-
)
|
| 1345 |
-
return parser
|
| 1346 |
-
|
| 1347 |
-
|
| 1348 |
-
def _print_banner() -> None:
|
| 1349 |
-
print(
|
| 1350 |
-
"Surya OCR 2 (bucket) — structured OCR / layout / tables over a bucket of files (650M)"
|
| 1351 |
-
)
|
| 1352 |
-
print("\nUsage:")
|
| 1353 |
-
print(
|
| 1354 |
-
" uv run surya-ocr-bucket.py INPUT [--output-bucket ... | --output-dataset ...] [options]"
|
| 1355 |
-
)
|
| 1356 |
-
print("\nExamples:")
|
| 1357 |
-
print(" # copy a bucket of .jp2 -> a dataset")
|
| 1358 |
-
print(" uv run surya-ocr-bucket.py hf://buckets/me/news --io-mode copy \\")
|
| 1359 |
-
print(" --glob '*.jp2' --output-dataset me/news-ocr --private")
|
| 1360 |
-
print("\n # mount a bucket -> per-file .md + .json in an output bucket")
|
| 1361 |
-
print(" uv run surya-ocr-bucket.py /in --io-mode mount --output-bucket /out")
|
| 1362 |
-
print("\nRun on the vllm/vllm-openai:v0.20.1 image (offline vLLM batch):")
|
| 1363 |
-
print(" hf jobs uv run --flavor l4x1 -s HF_TOKEN \\")
|
| 1364 |
-
print(" --image vllm/vllm-openai:v0.20.1 --python /usr/local/bin/python3 \\")
|
| 1365 |
-
print(" -e PYTHONPATH=/usr/local/lib/python3.12/site-packages \\")
|
| 1366 |
-
print(" -v hf://buckets/me/news:/in:ro -v hf://buckets/me/news-ocr:/out \\")
|
| 1367 |
-
print(
|
| 1368 |
-
" https://huggingface.co/datasets/uv-scripts/ocr/raw/main/surya-ocr-bucket.py \\"
|
| 1369 |
-
)
|
| 1370 |
-
print(" /in --io-mode mount --glob '*.jp2' --output-bucket /out")
|
| 1371 |
-
print("\nFor full help: uv run surya-ocr-bucket.py --help")
|
| 1372 |
-
|
| 1373 |
-
|
| 1374 |
-
if __name__ == "__main__":
|
| 1375 |
-
if len(sys.argv) == 1:
|
| 1376 |
-
_print_banner()
|
| 1377 |
-
sys.exit(0)
|
| 1378 |
-
|
| 1379 |
-
args = build_parser().parse_args()
|
| 1380 |
-
if not args.output_bucket and not args.output_dataset:
|
| 1381 |
-
build_parser().error(
|
| 1382 |
-
"at least one of --output-bucket or --output-dataset is required"
|
| 1383 |
-
)
|
| 1384 |
-
if args.no_resume and not args.output_bucket:
|
| 1385 |
-
logger.warning("--no-resume has no effect without --output-bucket")
|
| 1386 |
-
if args.include_images and not args.output_dataset:
|
| 1387 |
-
logger.warning("--include-images has no effect without --output-dataset")
|
| 1388 |
-
|
| 1389 |
-
main(args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
surya-ocr.py
DELETED
|
@@ -1,855 +0,0 @@
|
|
| 1 |
-
# /// script
|
| 2 |
-
# requires-python = ">=3.10"
|
| 3 |
-
# dependencies = [
|
| 4 |
-
# "surya-ocr",
|
| 5 |
-
# "datasets>=3.1.0",
|
| 6 |
-
# "huggingface-hub",
|
| 7 |
-
# "pillow",
|
| 8 |
-
# "toolz",
|
| 9 |
-
# "tqdm",
|
| 10 |
-
# ]
|
| 11 |
-
# ///
|
| 12 |
-
"""
|
| 13 |
-
Document intelligence on images OR multi-page PDFs with Datalab's **Surya OCR 2**
|
| 14 |
-
(`datalab-to/surya-ocr-2`, 650M, Qwen3.5-style).
|
| 15 |
-
|
| 16 |
-
Surya is *structured* OCR: instead of a flat markdown blob, it returns per-block
|
| 17 |
-
HTML with bounding boxes, reading order, and labels (equations in `<math>`). This
|
| 18 |
-
recipe writes **both**:
|
| 19 |
-
|
| 20 |
-
--output-column (default `markdown`) flattened, reading-order text per row
|
| 21 |
-
surya_blocks the full structured result as JSON
|
| 22 |
-
(bbox / polygon / label / reading_order /
|
| 23 |
-
confidence / html per block), one entry
|
| 24 |
-
per page.
|
| 25 |
-
|
| 26 |
-
Three tasks via `--task`:
|
| 27 |
-
ocr (default) full-page OCR -> text + per-block HTML/bboxes
|
| 28 |
-
layout layout regions -> labelled boxes + reading order
|
| 29 |
-
table table structure -> HTML (mode `full`) or rows/cols/cells
|
| 30 |
-
(mode `simple`, via --table-mode)
|
| 31 |
-
|
| 32 |
-
Input is one document per row:
|
| 33 |
-
--image-column COL (default `image`) one image per row
|
| 34 |
-
--pdf-column COL PDF bytes per row (multi-page; honors
|
| 35 |
-
--page-range). Pages are concatenated in
|
| 36 |
-
the text column and kept per-page in
|
| 37 |
-
`surya_blocks`.
|
| 38 |
-
|
| 39 |
-
ENGINE: Surya normally spawns a vLLM **server** (Docker) — which can't run inside
|
| 40 |
-
an HF Job. This script instead does **offline batch inference**: it injects a
|
| 41 |
-
custom in-process backend into Surya's `SuryaInferenceManager` that runs vLLM's
|
| 42 |
-
offline `LLM().chat()` engine (no server, no HTTP). Surya still owns all the
|
| 43 |
-
prompting, image preprocessing, and HTML/bbox parsing — we only swap the
|
| 44 |
-
transport. Run on the **`vllm/vllm-openai:v0.20.1`** image (Surya's known-good
|
| 45 |
-
vLLM build; the model is the recent, version-sensitive `qwen3_5` architecture).
|
| 46 |
-
|
| 47 |
-
LICENSE NOTE: Surya's *code* is Apache-2.0 but the *weights* are a modified
|
| 48 |
-
OpenRAIL-M license — free for research, personal use, and startups under $5M
|
| 49 |
-
funding/revenue, but restricted from competitive use against Datalab's API.
|
| 50 |
-
Confirm you are within those terms. https://huggingface.co/datalab-to/surya-ocr-2
|
| 51 |
-
|
| 52 |
-
HF Jobs (use the pinned vLLM image so vLLM + qwen3_5 support are present):
|
| 53 |
-
|
| 54 |
-
hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
|
| 55 |
-
--image vllm/vllm-openai:v0.20.1 --python /usr/local/bin/python3 \\
|
| 56 |
-
-e PYTHONPATH=/usr/local/lib/python3.12/site-packages \\
|
| 57 |
-
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/surya-ocr.py \\
|
| 58 |
-
INPUT_DATASET OUTPUT_DATASET \\
|
| 59 |
-
--max-samples 5 --shuffle --seed 42
|
| 60 |
-
|
| 61 |
-
Model: datalab-to/surya-ocr-2 (package: surya-ocr, https://github.com/datalab-to/surya)
|
| 62 |
-
"""
|
| 63 |
-
|
| 64 |
-
import argparse
|
| 65 |
-
import io
|
| 66 |
-
import json
|
| 67 |
-
import logging
|
| 68 |
-
import math
|
| 69 |
-
import os
|
| 70 |
-
import sys
|
| 71 |
-
import tempfile
|
| 72 |
-
import time
|
| 73 |
-
from datetime import datetime, timezone
|
| 74 |
-
from typing import Any, Dict, List, Optional, Tuple
|
| 75 |
-
from urllib.request import urlopen
|
| 76 |
-
|
| 77 |
-
from datasets import load_dataset
|
| 78 |
-
from huggingface_hub import DatasetCard, login
|
| 79 |
-
from PIL import Image
|
| 80 |
-
from toolz import partition_all
|
| 81 |
-
from tqdm import tqdm
|
| 82 |
-
|
| 83 |
-
logging.basicConfig(level=logging.INFO)
|
| 84 |
-
logger = logging.getLogger(__name__)
|
| 85 |
-
|
| 86 |
-
DEFAULT_MODEL = "datalab-to/surya-ocr-2"
|
| 87 |
-
# Surya's own vision-tiling bounds (from its vLLM backend), applied to the
|
| 88 |
-
# offline engine too so preprocessing matches the server path exactly.
|
| 89 |
-
MM_PROCESSOR_KWARGS = {"min_pixels": 3136, "max_pixels": 6291456}
|
| 90 |
-
TASKS = ("ocr", "layout", "table")
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
def check_cuda_availability() -> None:
|
| 94 |
-
"""Exit early with a clear message if there's no GPU."""
|
| 95 |
-
import torch
|
| 96 |
-
|
| 97 |
-
if not torch.cuda.is_available():
|
| 98 |
-
logger.error("CUDA is not available. This script requires a GPU.")
|
| 99 |
-
logger.error(
|
| 100 |
-
"Run on Hugging Face Jobs with: hf jobs uv run --flavor l4x1 "
|
| 101 |
-
"--image vllm/vllm-openai:v0.20.1 ..."
|
| 102 |
-
)
|
| 103 |
-
sys.exit(1)
|
| 104 |
-
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
def parse_page_range(spec: Optional[str]) -> Optional[List[int]]:
|
| 108 |
-
"""Turn '0-3,5' into [0,1,2,3,5]. None/empty -> None (all pages)."""
|
| 109 |
-
if not spec:
|
| 110 |
-
return None
|
| 111 |
-
pages: List[int] = []
|
| 112 |
-
for part in spec.split(","):
|
| 113 |
-
part = part.strip()
|
| 114 |
-
if not part:
|
| 115 |
-
continue
|
| 116 |
-
if "-" in part:
|
| 117 |
-
lo, hi = part.split("-", 1)
|
| 118 |
-
pages.extend(range(int(lo), int(hi) + 1))
|
| 119 |
-
else:
|
| 120 |
-
pages.append(int(part))
|
| 121 |
-
return pages or None
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
def cell_to_bytes(cell: Any) -> bytes:
|
| 125 |
-
"""Normalize an HF dataset cell (image or document) to raw file bytes."""
|
| 126 |
-
if isinstance(cell, Image.Image):
|
| 127 |
-
buf = io.BytesIO()
|
| 128 |
-
cell.convert("RGB").save(buf, format="PNG")
|
| 129 |
-
return buf.getvalue()
|
| 130 |
-
if isinstance(cell, dict):
|
| 131 |
-
if cell.get("bytes"):
|
| 132 |
-
return cell["bytes"]
|
| 133 |
-
if cell.get("path"):
|
| 134 |
-
with open(cell["path"], "rb") as f:
|
| 135 |
-
return f.read()
|
| 136 |
-
raise ValueError(
|
| 137 |
-
f"Unsupported image/document dict (no bytes/path): {list(cell)}"
|
| 138 |
-
)
|
| 139 |
-
if isinstance(cell, (bytes, bytearray)):
|
| 140 |
-
return bytes(cell)
|
| 141 |
-
if isinstance(cell, str):
|
| 142 |
-
if cell.startswith(("http://", "https://")):
|
| 143 |
-
return urlopen(cell).read() # noqa: S310
|
| 144 |
-
with open(cell, "rb") as f:
|
| 145 |
-
return f.read()
|
| 146 |
-
raise ValueError(f"Unsupported cell type: {type(cell)}")
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
def cell_to_pil(cell: Any) -> Image.Image:
|
| 150 |
-
"""One image cell -> RGB PIL image."""
|
| 151 |
-
if isinstance(cell, Image.Image):
|
| 152 |
-
return cell.convert("RGB")
|
| 153 |
-
return Image.open(io.BytesIO(cell_to_bytes(cell))).convert("RGB")
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
def load_pdf_images(
|
| 157 |
-
load_pdf, cell: Any, page_indices: Optional[List[int]], dpi: int
|
| 158 |
-
) -> List[Image.Image]:
|
| 159 |
-
"""Render one PDF cell into page images via Surya's own pypdfium2 loader."""
|
| 160 |
-
data = cell_to_bytes(cell)
|
| 161 |
-
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as tmp:
|
| 162 |
-
tmp.write(data)
|
| 163 |
-
path = tmp.name
|
| 164 |
-
try:
|
| 165 |
-
images, _ = load_pdf(path, page_indices, dpi=dpi)
|
| 166 |
-
return [im.convert("RGB") for im in images]
|
| 167 |
-
finally:
|
| 168 |
-
os.unlink(path)
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
# --- structured-output shim (vLLM API moved between versions) ---
|
| 172 |
-
def build_structured_outputs(schema: Dict[str, Any]) -> Dict[str, Any]:
|
| 173 |
-
"""SamplingParams kwargs for guided JSON, across vLLM versions (layout uses this)."""
|
| 174 |
-
try:
|
| 175 |
-
from vllm.sampling_params import StructuredOutputsParams # vLLM >= 0.12
|
| 176 |
-
|
| 177 |
-
return {"structured_outputs": StructuredOutputsParams(json=schema)}
|
| 178 |
-
except (ImportError, TypeError):
|
| 179 |
-
pass
|
| 180 |
-
try:
|
| 181 |
-
from vllm.sampling_params import GuidedDecodingParams # older vLLM
|
| 182 |
-
|
| 183 |
-
return {"guided_decoding": GuidedDecodingParams(json=schema)}
|
| 184 |
-
except (ImportError, TypeError):
|
| 185 |
-
pass
|
| 186 |
-
logger.warning(
|
| 187 |
-
"Guided JSON unavailable in this vLLM version; relying on the model."
|
| 188 |
-
)
|
| 189 |
-
return {}
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
def _mean_token_prob(completion_output) -> Optional[float]:
|
| 193 |
-
"""Mean exp(logprob) of the sampled tokens -> Surya's per-block `confidence`."""
|
| 194 |
-
lps = getattr(completion_output, "logprobs", None)
|
| 195 |
-
if not lps:
|
| 196 |
-
return None
|
| 197 |
-
probs: List[float] = []
|
| 198 |
-
for tid, lp_dict in zip(completion_output.token_ids, lps):
|
| 199 |
-
if not lp_dict:
|
| 200 |
-
continue
|
| 201 |
-
entry = lp_dict.get(tid)
|
| 202 |
-
if (
|
| 203 |
-
entry is None
|
| 204 |
-
): # sampled token not in the returned top-k; use the best we have
|
| 205 |
-
entry = max(lp_dict.values(), key=lambda e: e.logprob)
|
| 206 |
-
probs.append(math.exp(entry.logprob))
|
| 207 |
-
return sum(probs) / len(probs) if probs else None
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
class OfflineVLLMBackend:
|
| 211 |
-
"""Surya `Backend` (duck-typed) that runs vLLM's offline `LLM().chat()` engine.
|
| 212 |
-
|
| 213 |
-
Surya's predictors call `manager.generate(batch)` -> `backend.generate(batch)`;
|
| 214 |
-
we satisfy that contract in-process (no server). Surya keeps ownership of the
|
| 215 |
-
prompts (`PROMPT_MAPPING`), image scaling (`scale_to_fit`), and output parsing.
|
| 216 |
-
"""
|
| 217 |
-
|
| 218 |
-
name = "offline-vllm"
|
| 219 |
-
|
| 220 |
-
def __init__(
|
| 221 |
-
self,
|
| 222 |
-
model: str,
|
| 223 |
-
max_model_len: int,
|
| 224 |
-
gpu_memory_utilization: float,
|
| 225 |
-
dtype: str = "bfloat16",
|
| 226 |
-
max_tokens_default: int = 2048,
|
| 227 |
-
logprobs_default: bool = True,
|
| 228 |
-
):
|
| 229 |
-
self.model = model
|
| 230 |
-
self.max_model_len = max_model_len
|
| 231 |
-
self.gpu_memory_utilization = gpu_memory_utilization
|
| 232 |
-
self.dtype = dtype
|
| 233 |
-
self.max_tokens_default = max_tokens_default
|
| 234 |
-
self.logprobs_default = logprobs_default
|
| 235 |
-
self.llm = None
|
| 236 |
-
self._build_messages = None
|
| 237 |
-
self._scale_to_fit = None
|
| 238 |
-
self._prompt_mapping = None
|
| 239 |
-
|
| 240 |
-
def start(self):
|
| 241 |
-
from vllm import LLM
|
| 242 |
-
|
| 243 |
-
logger.info(
|
| 244 |
-
f"Loading {self.model} into vLLM offline engine (dtype={self.dtype})..."
|
| 245 |
-
)
|
| 246 |
-
self.llm = LLM(
|
| 247 |
-
model=self.model,
|
| 248 |
-
dtype=self.dtype,
|
| 249 |
-
max_model_len=self.max_model_len,
|
| 250 |
-
gpu_memory_utilization=self.gpu_memory_utilization,
|
| 251 |
-
mm_processor_kwargs=MM_PROCESSOR_KWARGS,
|
| 252 |
-
limit_mm_per_prompt={"image": 1},
|
| 253 |
-
)
|
| 254 |
-
# Reuse Surya's exact request shaping so the offline path matches the server.
|
| 255 |
-
from surya.inference.backends.openai_client import _build_messages
|
| 256 |
-
from surya.inference.prompts import PROMPT_MAPPING
|
| 257 |
-
from surya.inference.util import scale_to_fit
|
| 258 |
-
|
| 259 |
-
self._build_messages = _build_messages
|
| 260 |
-
self._scale_to_fit = scale_to_fit
|
| 261 |
-
self._prompt_mapping = PROMPT_MAPPING
|
| 262 |
-
return None
|
| 263 |
-
|
| 264 |
-
def stop(self) -> None:
|
| 265 |
-
self.llm = None
|
| 266 |
-
|
| 267 |
-
def _sampling_params(self, item):
|
| 268 |
-
from vllm import SamplingParams
|
| 269 |
-
|
| 270 |
-
max_tokens = item.max_tokens or self.max_tokens_default
|
| 271 |
-
want_logprobs = item.request_logprobs or self.logprobs_default
|
| 272 |
-
kwargs: Dict[str, Any] = dict(temperature=0.0, top_p=0.1, max_tokens=max_tokens)
|
| 273 |
-
if want_logprobs:
|
| 274 |
-
kwargs["logprobs"] = 1
|
| 275 |
-
if item.guided_json is not None:
|
| 276 |
-
kwargs.update(build_structured_outputs(item.guided_json))
|
| 277 |
-
return SamplingParams(**kwargs)
|
| 278 |
-
|
| 279 |
-
def generate(self, batch):
|
| 280 |
-
from surya.inference.schema import BatchOutputItem
|
| 281 |
-
|
| 282 |
-
if self.llm is None:
|
| 283 |
-
self.start()
|
| 284 |
-
if not batch:
|
| 285 |
-
return []
|
| 286 |
-
|
| 287 |
-
conversations = []
|
| 288 |
-
sampling_params = []
|
| 289 |
-
for item in batch:
|
| 290 |
-
prompt = item.prompt or self._prompt_mapping[item.prompt_type]
|
| 291 |
-
image = self._scale_to_fit(item.image)
|
| 292 |
-
conversations.append(self._build_messages(image, prompt))
|
| 293 |
-
sampling_params.append(self._sampling_params(item))
|
| 294 |
-
|
| 295 |
-
outputs = self.llm.chat(
|
| 296 |
-
conversations,
|
| 297 |
-
sampling_params,
|
| 298 |
-
chat_template_content_format="openai",
|
| 299 |
-
use_tqdm=False,
|
| 300 |
-
)
|
| 301 |
-
|
| 302 |
-
results = []
|
| 303 |
-
for item, out in zip(batch, outputs):
|
| 304 |
-
comp = out.outputs[0]
|
| 305 |
-
results.append(
|
| 306 |
-
BatchOutputItem(
|
| 307 |
-
raw=comp.text,
|
| 308 |
-
token_count=len(comp.token_ids),
|
| 309 |
-
error=False,
|
| 310 |
-
mean_token_prob=_mean_token_prob(comp),
|
| 311 |
-
logprobs=None,
|
| 312 |
-
metadata=item.metadata, # carries page_idx/block_idx — must round-trip
|
| 313 |
-
)
|
| 314 |
-
)
|
| 315 |
-
return results
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
def make_manager(backend: OfflineVLLMBackend):
|
| 319 |
-
"""A SuryaInferenceManager wired to our offline backend (bypassing autodetect)."""
|
| 320 |
-
from surya.inference import SuryaInferenceManager
|
| 321 |
-
|
| 322 |
-
manager = SuryaInferenceManager.__new__(SuryaInferenceManager)
|
| 323 |
-
manager.method = backend.name
|
| 324 |
-
manager.backend = backend
|
| 325 |
-
return manager
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
# --- result serialization (text column + structured surya_blocks) ---
|
| 329 |
-
def _html_to_text(html: str) -> str:
|
| 330 |
-
from bs4 import BeautifulSoup
|
| 331 |
-
|
| 332 |
-
return BeautifulSoup(html, "html.parser").get_text(" ", strip=True)
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
def serialize_pages(task: str, pages: List[Any]) -> Tuple[str, List[Dict[str, Any]]]:
|
| 336 |
-
"""(text, structured-per-page) for one row's page results."""
|
| 337 |
-
structured = [p.model_dump(mode="json") for p in pages]
|
| 338 |
-
page_texts: List[str] = []
|
| 339 |
-
for page in pages:
|
| 340 |
-
if task == "ocr":
|
| 341 |
-
parts = []
|
| 342 |
-
for b in sorted(page.blocks, key=lambda b: b.reading_order):
|
| 343 |
-
if b.skipped or not b.html:
|
| 344 |
-
continue
|
| 345 |
-
txt = _html_to_text(b.html)
|
| 346 |
-
if txt:
|
| 347 |
-
parts.append(txt)
|
| 348 |
-
page_texts.append("\n".join(parts))
|
| 349 |
-
elif task == "layout":
|
| 350 |
-
# No OCR text in layout mode — emit a reading-order outline of labels.
|
| 351 |
-
page_texts.append(
|
| 352 |
-
"\n".join(
|
| 353 |
-
f"{b.position}: {b.label}"
|
| 354 |
-
for b in sorted(page.bboxes, key=lambda b: b.position)
|
| 355 |
-
)
|
| 356 |
-
)
|
| 357 |
-
else: # table
|
| 358 |
-
if page.html: # mode="full"
|
| 359 |
-
page_texts.append(page.html)
|
| 360 |
-
else: # mode="simple"
|
| 361 |
-
page_texts.append(f"{len(page.rows)} rows x {len(page.cols)} cols")
|
| 362 |
-
return "\n\n".join(page_texts), structured
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
def create_dataset_card(
|
| 366 |
-
source_dataset: str,
|
| 367 |
-
model: str,
|
| 368 |
-
task: str,
|
| 369 |
-
table_mode: str,
|
| 370 |
-
num_samples: int,
|
| 371 |
-
n_ok: int,
|
| 372 |
-
source_column: str,
|
| 373 |
-
is_pdf: bool,
|
| 374 |
-
page_range: Optional[str],
|
| 375 |
-
output_column: str,
|
| 376 |
-
blocks_column: str,
|
| 377 |
-
split: str,
|
| 378 |
-
processing_time: str,
|
| 379 |
-
) -> str:
|
| 380 |
-
input_kind = "PDF documents" if is_pdf else "images"
|
| 381 |
-
col_desc = "PDF" if is_pdf else "image"
|
| 382 |
-
if page_range:
|
| 383 |
-
col_desc += f", pages {page_range}"
|
| 384 |
-
task_desc = {
|
| 385 |
-
"ocr": "full-page OCR (structured HTML + bounding boxes)",
|
| 386 |
-
"layout": "layout analysis (labelled regions + reading order)",
|
| 387 |
-
"table": f"table recognition (mode `{table_mode}`)",
|
| 388 |
-
}[task]
|
| 389 |
-
return f"""---
|
| 390 |
-
tags:
|
| 391 |
-
- ocr
|
| 392 |
-
- document-processing
|
| 393 |
-
- surya
|
| 394 |
-
- structured
|
| 395 |
-
- uv-script
|
| 396 |
-
- generated
|
| 397 |
-
---
|
| 398 |
-
|
| 399 |
-
# Surya OCR 2 ({task}) on {source_dataset}
|
| 400 |
-
|
| 401 |
-
{task_desc.capitalize()} over {input_kind} in
|
| 402 |
-
[{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using
|
| 403 |
-
[Surya OCR 2](https://huggingface.co/{model}) (650M, Qwen3.5-based) by Datalab, via the
|
| 404 |
-
[`surya-ocr`](https://github.com/datalab-to/surya) package, run as **offline vLLM batch
|
| 405 |
-
inference** on Hugging Face Jobs.
|
| 406 |
-
|
| 407 |
-
## Processing Details
|
| 408 |
-
|
| 409 |
-
- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
|
| 410 |
-
- **Model**: [{model}](https://huggingface.co/{model})
|
| 411 |
-
- **Task**: `{task}`{f" (table mode `{table_mode}`)" if task == "table" else ""}
|
| 412 |
-
- **Input column**: `{source_column}` ({col_desc})
|
| 413 |
-
- **Text column**: `{output_column}` (flattened, reading-order text per row)
|
| 414 |
-
- **Structured column**: `{blocks_column}` (JSON: per-page blocks with bbox / polygon / label / reading_order / confidence / html)
|
| 415 |
-
- **Split**: `{split}`
|
| 416 |
-
- **Samples**: {num_samples:,}
|
| 417 |
-
- **Processed OK**: {n_ok:,} / {num_samples:,}
|
| 418 |
-
- **Processing time**: {processing_time}
|
| 419 |
-
- **Date**: {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}
|
| 420 |
-
|
| 421 |
-
## License note
|
| 422 |
-
|
| 423 |
-
Surya's code is Apache-2.0, but the model **weights** use a modified OpenRAIL-M
|
| 424 |
-
license: free for research, personal use, and startups under $5M funding/revenue,
|
| 425 |
-
restricted from competitive use against Datalab's API. See the
|
| 426 |
-
[model card](https://huggingface.co/{model}).
|
| 427 |
-
|
| 428 |
-
## Dataset Structure
|
| 429 |
-
|
| 430 |
-
Original columns plus:
|
| 431 |
-
- `{output_column}`: flattened text (OCR), label outline (layout), or table HTML (table)
|
| 432 |
-
- `{blocks_column}`: structured result as a JSON string (one entry per page)
|
| 433 |
-
- `inference_info`: JSON list tracking models applied to this dataset
|
| 434 |
-
|
| 435 |
-
Generated with [UV Scripts](https://huggingface.co/uv-scripts).
|
| 436 |
-
"""
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
def main(
|
| 440 |
-
input_dataset: str,
|
| 441 |
-
output_dataset: str,
|
| 442 |
-
task: str = "ocr",
|
| 443 |
-
table_mode: str = "full",
|
| 444 |
-
image_column: str = "image",
|
| 445 |
-
pdf_column: Optional[str] = None,
|
| 446 |
-
output_column: str = "markdown",
|
| 447 |
-
blocks_column: str = "surya_blocks",
|
| 448 |
-
page_range: Optional[str] = None,
|
| 449 |
-
split: str = "train",
|
| 450 |
-
max_samples: Optional[int] = None,
|
| 451 |
-
shuffle: bool = False,
|
| 452 |
-
seed: int = 42,
|
| 453 |
-
batch_size: int = 16,
|
| 454 |
-
max_model_len: int = 18000,
|
| 455 |
-
gpu_memory_utilization: float = 0.85,
|
| 456 |
-
dtype: str = "bfloat16",
|
| 457 |
-
model: str = DEFAULT_MODEL,
|
| 458 |
-
private: bool = False,
|
| 459 |
-
config: Optional[str] = None,
|
| 460 |
-
create_pr: bool = False,
|
| 461 |
-
hf_token: Optional[str] = None,
|
| 462 |
-
verbose: bool = False,
|
| 463 |
-
) -> None:
|
| 464 |
-
# Unlock full Xet bandwidth for the model download (repo convention).
|
| 465 |
-
os.environ["HF_XET_HIGH_PERFORMANCE"] = "1"
|
| 466 |
-
# Surya reads settings from env at import; pin the checkpoint and forbid any
|
| 467 |
-
# server autostart (we inject our own offline backend instead).
|
| 468 |
-
os.environ["SURYA_MODEL_CHECKPOINT"] = model
|
| 469 |
-
os.environ["SURYA_INFERENCE_AUTOSTART"] = "False"
|
| 470 |
-
|
| 471 |
-
check_cuda_availability()
|
| 472 |
-
start_time = datetime.now(timezone.utc)
|
| 473 |
-
|
| 474 |
-
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
|
| 475 |
-
if HF_TOKEN:
|
| 476 |
-
login(token=HF_TOKEN)
|
| 477 |
-
|
| 478 |
-
# Import Surya only after env is set.
|
| 479 |
-
from surya.input.load import load_pdf
|
| 480 |
-
from surya.settings import settings
|
| 481 |
-
|
| 482 |
-
source_column = pdf_column or image_column
|
| 483 |
-
is_pdf = pdf_column is not None
|
| 484 |
-
page_indices = parse_page_range(page_range)
|
| 485 |
-
pdf_dpi = settings.IMAGE_DPI_HIGHRES
|
| 486 |
-
|
| 487 |
-
logger.info(
|
| 488 |
-
f"Model: {model} Task: {task}"
|
| 489 |
-
+ (f" (mode {table_mode})" if task == "table" else "")
|
| 490 |
-
)
|
| 491 |
-
logger.info(f"Loading dataset: {input_dataset} (split={split})")
|
| 492 |
-
dataset = load_dataset(input_dataset, split=split)
|
| 493 |
-
if source_column not in dataset.column_names:
|
| 494 |
-
logger.error(
|
| 495 |
-
f"Column '{source_column}' not found. Available: {dataset.column_names}"
|
| 496 |
-
)
|
| 497 |
-
sys.exit(1)
|
| 498 |
-
if shuffle:
|
| 499 |
-
dataset = dataset.shuffle(seed=seed)
|
| 500 |
-
if max_samples:
|
| 501 |
-
dataset = dataset.select(range(min(max_samples, len(dataset))))
|
| 502 |
-
n = len(dataset)
|
| 503 |
-
logger.info(f"Processing {n} documents from column '{source_column}'")
|
| 504 |
-
|
| 505 |
-
# Build the offline engine + inject it into a Surya manager, then pick the predictor.
|
| 506 |
-
backend = OfflineVLLMBackend(
|
| 507 |
-
model=model,
|
| 508 |
-
max_model_len=max_model_len,
|
| 509 |
-
gpu_memory_utilization=gpu_memory_utilization,
|
| 510 |
-
dtype=dtype,
|
| 511 |
-
)
|
| 512 |
-
manager = make_manager(backend)
|
| 513 |
-
|
| 514 |
-
if task == "ocr":
|
| 515 |
-
from surya.recognition import RecognitionPredictor
|
| 516 |
-
|
| 517 |
-
predictor = RecognitionPredictor(manager)
|
| 518 |
-
|
| 519 |
-
def run(images):
|
| 520 |
-
return predictor(images, full_page=True)
|
| 521 |
-
elif task == "layout":
|
| 522 |
-
from surya.layout import LayoutPredictor
|
| 523 |
-
|
| 524 |
-
predictor = LayoutPredictor(manager)
|
| 525 |
-
|
| 526 |
-
def run(images):
|
| 527 |
-
return predictor(images)
|
| 528 |
-
else: # table
|
| 529 |
-
from surya.table_rec import TableRecPredictor
|
| 530 |
-
|
| 531 |
-
predictor = TableRecPredictor(manager)
|
| 532 |
-
|
| 533 |
-
def run(images):
|
| 534 |
-
return predictor(images, mode=table_mode)
|
| 535 |
-
|
| 536 |
-
texts: List[Optional[str]] = [None] * n
|
| 537 |
-
blocks: List[Optional[str]] = [None] * n
|
| 538 |
-
error_flags: List[bool] = [True] * n
|
| 539 |
-
|
| 540 |
-
for chunk in tqdm(list(partition_all(batch_size, range(n))), desc=f"Surya {task}"):
|
| 541 |
-
chunk = list(chunk)
|
| 542 |
-
flat_images: List[Image.Image] = []
|
| 543 |
-
spans: List[Tuple[int, int, int]] = [] # (row_idx, start, count)
|
| 544 |
-
for i in chunk:
|
| 545 |
-
try:
|
| 546 |
-
if is_pdf:
|
| 547 |
-
imgs = load_pdf_images(
|
| 548 |
-
load_pdf, dataset[i][source_column], page_indices, pdf_dpi
|
| 549 |
-
)
|
| 550 |
-
else:
|
| 551 |
-
imgs = [cell_to_pil(dataset[i][source_column])]
|
| 552 |
-
except Exception as e:
|
| 553 |
-
logger.warning(f"Row {i}: failed to load document: {e}")
|
| 554 |
-
texts[i] = f"[SURYA LOAD ERROR] {e}"
|
| 555 |
-
blocks[i] = None
|
| 556 |
-
continue
|
| 557 |
-
if not imgs:
|
| 558 |
-
texts[i] = "[SURYA EMPTY DOCUMENT]"
|
| 559 |
-
continue
|
| 560 |
-
spans.append((i, len(flat_images), len(imgs)))
|
| 561 |
-
flat_images.extend(imgs)
|
| 562 |
-
|
| 563 |
-
if not flat_images:
|
| 564 |
-
continue
|
| 565 |
-
try:
|
| 566 |
-
results = run(flat_images)
|
| 567 |
-
except Exception as e:
|
| 568 |
-
logger.error(f"Batch generate failed: {e}")
|
| 569 |
-
for i, _, _ in spans:
|
| 570 |
-
texts[i] = "[SURYA GENERATE ERROR]"
|
| 571 |
-
blocks[i] = None
|
| 572 |
-
continue
|
| 573 |
-
|
| 574 |
-
for i, start, count in spans:
|
| 575 |
-
page_results = results[start : start + count]
|
| 576 |
-
text, structured = serialize_pages(task, page_results)
|
| 577 |
-
texts[i] = text
|
| 578 |
-
blocks[i] = json.dumps(structured, ensure_ascii=False)
|
| 579 |
-
error_flags[i] = False
|
| 580 |
-
|
| 581 |
-
n_ok = sum(not f for f in error_flags)
|
| 582 |
-
logger.info(f"Processed OK: {n_ok}/{n}")
|
| 583 |
-
|
| 584 |
-
dataset = dataset.add_column(output_column, texts)
|
| 585 |
-
dataset = dataset.add_column(blocks_column, blocks)
|
| 586 |
-
|
| 587 |
-
inference_entry = {
|
| 588 |
-
"model": model,
|
| 589 |
-
"model_name": "surya-ocr-2",
|
| 590 |
-
"column_name": output_column,
|
| 591 |
-
"blocks_column": blocks_column,
|
| 592 |
-
"task": task,
|
| 593 |
-
"table_mode": table_mode if task == "table" else None,
|
| 594 |
-
"backend": "vllm-offline",
|
| 595 |
-
"page_range": page_range,
|
| 596 |
-
"error_rate": (n - n_ok) / n if n else 0.0,
|
| 597 |
-
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 598 |
-
"script": "surya-ocr.py",
|
| 599 |
-
}
|
| 600 |
-
if "inference_info" in dataset.column_names:
|
| 601 |
-
|
| 602 |
-
def update_info(example):
|
| 603 |
-
try:
|
| 604 |
-
existing = (
|
| 605 |
-
json.loads(example["inference_info"])
|
| 606 |
-
if example["inference_info"]
|
| 607 |
-
else []
|
| 608 |
-
)
|
| 609 |
-
except (json.JSONDecodeError, TypeError):
|
| 610 |
-
existing = []
|
| 611 |
-
existing.append(inference_entry)
|
| 612 |
-
return {"inference_info": json.dumps(existing)}
|
| 613 |
-
|
| 614 |
-
dataset = dataset.map(update_info)
|
| 615 |
-
else:
|
| 616 |
-
dataset = dataset.add_column(
|
| 617 |
-
"inference_info", [json.dumps([inference_entry])] * n
|
| 618 |
-
)
|
| 619 |
-
|
| 620 |
-
processing_time = (
|
| 621 |
-
f"{(datetime.now(timezone.utc) - start_time).total_seconds() / 60:.1f} min"
|
| 622 |
-
)
|
| 623 |
-
|
| 624 |
-
logger.info(f"Pushing to {output_dataset}")
|
| 625 |
-
max_retries = 3
|
| 626 |
-
for attempt in range(1, max_retries + 1):
|
| 627 |
-
try:
|
| 628 |
-
if attempt > 1:
|
| 629 |
-
logger.warning("Disabling XET (fallback to HTTP upload)")
|
| 630 |
-
os.environ["HF_HUB_DISABLE_XET"] = "1"
|
| 631 |
-
dataset.push_to_hub(
|
| 632 |
-
output_dataset,
|
| 633 |
-
private=private,
|
| 634 |
-
token=HF_TOKEN,
|
| 635 |
-
max_shard_size="500MB",
|
| 636 |
-
create_pr=create_pr,
|
| 637 |
-
**({"config_name": config} if config else {}),
|
| 638 |
-
commit_message=f"Add Surya OCR 2 {task} results ({n} samples)"
|
| 639 |
-
+ (f" [{config}]" if config else ""),
|
| 640 |
-
)
|
| 641 |
-
break
|
| 642 |
-
except Exception as e:
|
| 643 |
-
logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
|
| 644 |
-
if attempt < max_retries:
|
| 645 |
-
delay = 30 * (2 ** (attempt - 1))
|
| 646 |
-
logger.info(f"Retrying in {delay}s...")
|
| 647 |
-
time.sleep(delay)
|
| 648 |
-
else:
|
| 649 |
-
logger.error("All upload attempts failed. Results are lost.")
|
| 650 |
-
sys.exit(1)
|
| 651 |
-
|
| 652 |
-
try:
|
| 653 |
-
card = DatasetCard(
|
| 654 |
-
create_dataset_card(
|
| 655 |
-
source_dataset=input_dataset,
|
| 656 |
-
model=model,
|
| 657 |
-
task=task,
|
| 658 |
-
table_mode=table_mode,
|
| 659 |
-
num_samples=n,
|
| 660 |
-
n_ok=n_ok,
|
| 661 |
-
source_column=source_column,
|
| 662 |
-
is_pdf=is_pdf,
|
| 663 |
-
page_range=page_range,
|
| 664 |
-
output_column=output_column,
|
| 665 |
-
blocks_column=blocks_column,
|
| 666 |
-
split=split,
|
| 667 |
-
processing_time=processing_time,
|
| 668 |
-
)
|
| 669 |
-
)
|
| 670 |
-
card.push_to_hub(output_dataset, token=HF_TOKEN)
|
| 671 |
-
except Exception as e:
|
| 672 |
-
logger.warning(f"Could not push dataset card: {e}")
|
| 673 |
-
|
| 674 |
-
logger.info("Done! Surya OCR 2 complete.")
|
| 675 |
-
logger.info(f"Dataset: https://huggingface.co/datasets/{output_dataset}")
|
| 676 |
-
logger.info(f"Processing time: {processing_time}")
|
| 677 |
-
|
| 678 |
-
if verbose:
|
| 679 |
-
import importlib.metadata
|
| 680 |
-
|
| 681 |
-
logger.info("--- Resolved package versions ---")
|
| 682 |
-
for pkg in ["surya-ocr", "vllm", "transformers", "torch", "datasets", "pillow"]:
|
| 683 |
-
try:
|
| 684 |
-
logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
|
| 685 |
-
except importlib.metadata.PackageNotFoundError:
|
| 686 |
-
logger.info(f" {pkg}: not installed")
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
if __name__ == "__main__":
|
| 690 |
-
if len(sys.argv) == 1:
|
| 691 |
-
print(
|
| 692 |
-
"Surya OCR 2 — structured OCR / layout / tables from images & PDFs (650M)"
|
| 693 |
-
)
|
| 694 |
-
print("\nUsage:")
|
| 695 |
-
print(" uv run surya-ocr.py INPUT OUTPUT [--task ocr|layout|table] [options]")
|
| 696 |
-
print("\nExamples:")
|
| 697 |
-
print(" # full-page OCR -> text + structured surya_blocks")
|
| 698 |
-
print(" uv run surya-ocr.py my-images my-ocr")
|
| 699 |
-
print("\n # layout regions / table structure")
|
| 700 |
-
print(" uv run surya-ocr.py my-images my-layout --task layout")
|
| 701 |
-
print(" uv run surya-ocr.py my-tables my-tables-out --task table")
|
| 702 |
-
print("\n # multi-page PDFs")
|
| 703 |
-
print(" uv run surya-ocr.py my-pdfs my-ocr --pdf-column pdf --page-range 0-5")
|
| 704 |
-
print("\nRun on the vllm/vllm-openai:v0.20.1 image (offline vLLM batch).")
|
| 705 |
-
print("For full help: uv run surya-ocr.py --help")
|
| 706 |
-
sys.exit(0)
|
| 707 |
-
|
| 708 |
-
parser = argparse.ArgumentParser(
|
| 709 |
-
description="Surya OCR 2 (650M): structured OCR / layout / tables, offline vLLM batch",
|
| 710 |
-
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 711 |
-
epilog="""
|
| 712 |
-
Tasks (--task):
|
| 713 |
-
ocr full-page OCR -> reading-order text + per-block HTML/bboxes (default)
|
| 714 |
-
layout layout regions -> labelled boxes + reading order
|
| 715 |
-
table table structure -> HTML (--table-mode full) or rows/cols/cells (simple)
|
| 716 |
-
|
| 717 |
-
Output columns:
|
| 718 |
-
--output-column flattened text per row (default: markdown)
|
| 719 |
-
surya_blocks structured JSON per row (bbox/label/reading_order/confidence/html)
|
| 720 |
-
|
| 721 |
-
Input (one document per row):
|
| 722 |
-
--image-column COL one image per row (default: image)
|
| 723 |
-
--pdf-column COL PDF bytes per row (multi-page; honors --page-range)
|
| 724 |
-
|
| 725 |
-
Run on the vllm/vllm-openai:v0.20.1 image:
|
| 726 |
-
--image vllm/vllm-openai:v0.20.1 --python /usr/local/bin/python3 \\
|
| 727 |
-
-e PYTHONPATH=/usr/local/lib/python3.12/site-packages
|
| 728 |
-
""",
|
| 729 |
-
)
|
| 730 |
-
parser.add_argument(
|
| 731 |
-
"input_dataset", help="Input dataset ID from the Hugging Face Hub"
|
| 732 |
-
)
|
| 733 |
-
parser.add_argument(
|
| 734 |
-
"output_dataset", help="Output dataset ID for the Hugging Face Hub"
|
| 735 |
-
)
|
| 736 |
-
parser.add_argument(
|
| 737 |
-
"--task", choices=TASKS, default="ocr", help="Task (default: ocr)"
|
| 738 |
-
)
|
| 739 |
-
parser.add_argument(
|
| 740 |
-
"--table-mode",
|
| 741 |
-
choices=["full", "simple"],
|
| 742 |
-
default="full",
|
| 743 |
-
help="Table task: 'full' = HTML, 'simple' = rows/cols/cells (default: full)",
|
| 744 |
-
)
|
| 745 |
-
parser.add_argument(
|
| 746 |
-
"--image-column", default="image", help="Image column (default: image)"
|
| 747 |
-
)
|
| 748 |
-
parser.add_argument(
|
| 749 |
-
"--pdf-column",
|
| 750 |
-
default=None,
|
| 751 |
-
help="PDF column (bytes/path). Mutually exclusive with --image-column.",
|
| 752 |
-
)
|
| 753 |
-
parser.add_argument(
|
| 754 |
-
"--output-column",
|
| 755 |
-
default="markdown",
|
| 756 |
-
help="Text output column (default: markdown)",
|
| 757 |
-
)
|
| 758 |
-
parser.add_argument(
|
| 759 |
-
"--blocks-column",
|
| 760 |
-
default="surya_blocks",
|
| 761 |
-
help="Structured JSON output column (default: surya_blocks)",
|
| 762 |
-
)
|
| 763 |
-
parser.add_argument(
|
| 764 |
-
"--page-range",
|
| 765 |
-
default=None,
|
| 766 |
-
help="Pages from PDFs, e.g. '0-5,7' (PDF column only)",
|
| 767 |
-
)
|
| 768 |
-
parser.add_argument(
|
| 769 |
-
"--split", default="train", help="Dataset split (default: train)"
|
| 770 |
-
)
|
| 771 |
-
parser.add_argument(
|
| 772 |
-
"--max-samples", type=int, help="Limit number of documents (for testing)"
|
| 773 |
-
)
|
| 774 |
-
parser.add_argument(
|
| 775 |
-
"--shuffle", action="store_true", help="Shuffle before sampling"
|
| 776 |
-
)
|
| 777 |
-
parser.add_argument(
|
| 778 |
-
"--seed", type=int, default=42, help="Shuffle seed (default: 42)"
|
| 779 |
-
)
|
| 780 |
-
parser.add_argument(
|
| 781 |
-
"--batch-size",
|
| 782 |
-
type=int,
|
| 783 |
-
default=16,
|
| 784 |
-
help="Rows (images) per offline llm.chat batch (default: 16)",
|
| 785 |
-
)
|
| 786 |
-
parser.add_argument(
|
| 787 |
-
"--max-model-len",
|
| 788 |
-
type=int,
|
| 789 |
-
default=18000,
|
| 790 |
-
help="vLLM context length (default: 18000)",
|
| 791 |
-
)
|
| 792 |
-
parser.add_argument(
|
| 793 |
-
"--gpu-memory-utilization",
|
| 794 |
-
type=float,
|
| 795 |
-
default=0.85,
|
| 796 |
-
help="vLLM GPU memory fraction (default: 0.85)",
|
| 797 |
-
)
|
| 798 |
-
parser.add_argument(
|
| 799 |
-
"--dtype",
|
| 800 |
-
default="bfloat16",
|
| 801 |
-
help="vLLM dtype (default: bfloat16; use float16 on T4/Turing)",
|
| 802 |
-
)
|
| 803 |
-
parser.add_argument(
|
| 804 |
-
"--model", default=DEFAULT_MODEL, help=f"Model ID (default: {DEFAULT_MODEL})"
|
| 805 |
-
)
|
| 806 |
-
parser.add_argument(
|
| 807 |
-
"--private", action="store_true", help="Make output dataset private"
|
| 808 |
-
)
|
| 809 |
-
parser.add_argument(
|
| 810 |
-
"--config",
|
| 811 |
-
default=None,
|
| 812 |
-
help="Config/subset name when pushing (for benchmarking in one repo)",
|
| 813 |
-
)
|
| 814 |
-
parser.add_argument(
|
| 815 |
-
"--create-pr",
|
| 816 |
-
action="store_true",
|
| 817 |
-
help="Push as a pull request instead of directly",
|
| 818 |
-
)
|
| 819 |
-
parser.add_argument("--hf-token", help="Hugging Face API token (or set HF_TOKEN)")
|
| 820 |
-
parser.add_argument(
|
| 821 |
-
"--verbose",
|
| 822 |
-
action="store_true",
|
| 823 |
-
help="Log resolved package versions after processing",
|
| 824 |
-
)
|
| 825 |
-
|
| 826 |
-
args = parser.parse_args()
|
| 827 |
-
|
| 828 |
-
if args.pdf_column and args.image_column != "image":
|
| 829 |
-
parser.error("--image-column and --pdf-column are mutually exclusive.")
|
| 830 |
-
|
| 831 |
-
main(
|
| 832 |
-
input_dataset=args.input_dataset,
|
| 833 |
-
output_dataset=args.output_dataset,
|
| 834 |
-
task=args.task,
|
| 835 |
-
table_mode=args.table_mode,
|
| 836 |
-
image_column=args.image_column,
|
| 837 |
-
pdf_column=args.pdf_column,
|
| 838 |
-
output_column=args.output_column,
|
| 839 |
-
blocks_column=args.blocks_column,
|
| 840 |
-
page_range=args.page_range,
|
| 841 |
-
split=args.split,
|
| 842 |
-
max_samples=args.max_samples,
|
| 843 |
-
shuffle=args.shuffle,
|
| 844 |
-
seed=args.seed,
|
| 845 |
-
batch_size=args.batch_size,
|
| 846 |
-
max_model_len=args.max_model_len,
|
| 847 |
-
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 848 |
-
dtype=args.dtype,
|
| 849 |
-
model=args.model,
|
| 850 |
-
private=args.private,
|
| 851 |
-
config=args.config,
|
| 852 |
-
create_pr=args.create_pr,
|
| 853 |
-
hf_token=args.hf_token,
|
| 854 |
-
verbose=args.verbose,
|
| 855 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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