Sync from GitHub via hub-sync
Browse files- CLAUDE.md +74 -0
- README.md +4 -0
- surya-ocr.py +855 -0
CLAUDE.md
CHANGED
|
@@ -273,6 +273,80 @@ repo (same multi-config pattern as the other OCR scripts).
|
|
| 273 |
|
| 274 |
Requires Python ≥3.12 (lift-pdf constraint) — fine on the standard images.
|
| 275 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
---
|
| 277 |
|
| 278 |
## Future: OCR Smoke Test Dataset
|
|
|
|
| 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). A **bucket** variant (`surya-ocr-bucket.py`, mount a bucket of real PDF *files* →
|
| 343 |
+
output, like `glm-ocr-bucket.py`) is a natural follow-up — distinct I/O from this dataset-column recipe.
|
| 344 |
+
|
| 345 |
+
**License:** code Apache-2.0, **weights modified OpenRAIL-M** (research/personal/<$5M, no competitive use
|
| 346 |
+
vs Datalab's API). Surfaced in the docstring, README entry, and output dataset card.
|
| 347 |
+
|
| 348 |
+
**Benchmark/compare:** `--config`/`--create-pr` push the same multi-config pattern as the other scripts.
|
| 349 |
+
|
| 350 |
---
|
| 351 |
|
| 352 |
## Future: OCR Smoke Test Dataset
|
README.md
CHANGED
|
@@ -47,6 +47,7 @@ _Sorted by model size:_
|
|
| 47 |
|--------|-------|------|---------|-------|
|
| 48 |
| `falcon-ocr.py` | [Falcon-OCR](https://huggingface.co/tiiuae/Falcon-OCR) | 0.3B | falcon-perception | Smallest in collection. #1 on multi-column docs and tables (olmOCR), Apache 2.0 |
|
| 49 |
| `smoldocling-ocr.py` | [SmolDocling](https://huggingface.co/ds4sd/SmolDocling-256M-preview) | 256M | Transformers | DocTags structured output |
|
|
|
|
| 50 |
| `glm-ocr.py` | [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) | 0.9B | vLLM | 94.62% OmniDocBench V1.5 |
|
| 51 |
| `paddleocr-vl.py` | [PaddleOCR-VL](https://huggingface.co/PaddlePaddle/PaddleOCR-VL) | 0.9B | Transformers | 4 task modes (ocr/table/formula/chart) |
|
| 52 |
| `paddleocr-vl-1.5.py` | [PaddleOCR-VL-1.5](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.5) | 0.9B | Transformers | 94.5% OmniDocBench, 6 task modes |
|
|
@@ -71,6 +72,8 @@ _Sorted by model size:_
|
|
| 71 |
|
| 72 |
**Variants & tools** (same models, different I/O): `glm-ocr-v2.py` adds checkpoint/resume for very large jobs · `glm-ocr-bucket.py` and `falcon-ocr-bucket.py` read images/PDFs from a mounted bucket and write one `.md` per page · `ocr-vllm-judge.py` runs pairwise OCR-quality comparisons.
|
| 73 |
|
|
|
|
|
|
|
| 74 |
## Structured extraction (image or text → JSON)
|
| 75 |
|
| 76 |
Most scripts here output markdown. These take a **schema** and return **structured data** instead — give them the fields you want, they fill them in:
|
|
@@ -194,6 +197,7 @@ Beyond the shared flags, some models add their own. Run `--help` on any script f
|
|
| 194 |
|
| 195 |
| Script | Extra options |
|
| 196 |
|--------|---------------|
|
|
|
|
| 197 |
| `glm-ocr.py` | `--task ocr\|formula\|table` |
|
| 198 |
| `paddleocr-vl.py` | `--task-mode ocr\|table\|formula\|chart` |
|
| 199 |
| `paddleocr-vl-1.5.py` | `--task-mode ocr\|table\|formula\|chart\|spotting\|seal` |
|
|
|
|
| 47 |
|--------|-------|------|---------|-------|
|
| 48 |
| `falcon-ocr.py` | [Falcon-OCR](https://huggingface.co/tiiuae/Falcon-OCR) | 0.3B | falcon-perception | Smallest in collection. #1 on multi-column docs and tables (olmOCR), Apache 2.0 |
|
| 49 |
| `smoldocling-ocr.py` | [SmolDocling](https://huggingface.co/ds4sd/SmolDocling-256M-preview) | 256M | Transformers | DocTags structured output |
|
| 50 |
+
| `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 |
|
| 51 |
| `glm-ocr.py` | [GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) | 0.9B | vLLM | 94.62% OmniDocBench V1.5 |
|
| 52 |
| `paddleocr-vl.py` | [PaddleOCR-VL](https://huggingface.co/PaddlePaddle/PaddleOCR-VL) | 0.9B | Transformers | 4 task modes (ocr/table/formula/chart) |
|
| 53 |
| `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 |
|
|
|
|
| 72 |
|
| 73 |
**Variants & tools** (same models, different I/O): `glm-ocr-v2.py` adds checkpoint/resume for very large jobs · `glm-ocr-bucket.py` and `falcon-ocr-bucket.py` read images/PDFs from a mounted bucket and write one `.md` per page · `ocr-vllm-judge.py` runs pairwise OCR-quality comparisons.
|
| 74 |
|
| 75 |
+
`surya-ocr.py` is the structured outlier: besides the flattened text column it writes a `surya_blocks` JSON column (per-block HTML + bounding boxes + reading order), and `--task` switches between OCR, `layout`, and `table`. It runs as **offline vLLM batch** (no server) and must use the **pinned** `vllm/vllm-openai:v0.20.1` image — its `qwen3_5` architecture is recent and version-sensitive, and that image puts vLLM at `/usr/local/lib/python3.12/site-packages` (use `--python /usr/local/bin/python3`; the exact command is in the script's docstring). Weights are **modified OpenRAIL-M**.
|
| 76 |
+
|
| 77 |
## Structured extraction (image or text → JSON)
|
| 78 |
|
| 79 |
Most scripts here output markdown. These take a **schema** and return **structured data** instead — give them the fields you want, they fill them in:
|
|
|
|
| 197 |
|
| 198 |
| Script | Extra options |
|
| 199 |
|--------|---------------|
|
| 200 |
+
| `surya-ocr.py` | `--task ocr\|layout\|table`, `--table-mode full\|simple`, `--pdf-column`/`--page-range`, `--blocks-column` |
|
| 201 |
| `glm-ocr.py` | `--task ocr\|formula\|table` |
|
| 202 |
| `paddleocr-vl.py` | `--task-mode ocr\|table\|formula\|chart` |
|
| 203 |
| `paddleocr-vl-1.5.py` | `--task-mode ocr\|table\|formula\|chart\|spotting\|seal` |
|
surya-ocr.py
ADDED
|
@@ -0,0 +1,855 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
)
|