# /// script # requires-python = ">=3.10" # dependencies = [ # "surya-ocr", # "datasets>=3.1.0", # "huggingface-hub", # "pillow", # "toolz", # "tqdm", # ] # # [tool.hf-jobs] # image = "vllm/vllm-openai:v0.20.1" # python = "/usr/local/bin/python3" # env = { PYTHONPATH = "/usr/local/lib/python3.12/site-packages" } # flavor = "a10g-small" # secrets = ["HF_TOKEN"] # /// """ Document intelligence on images OR multi-page PDFs with Datalab's **Surya OCR 2** (`datalab-to/surya-ocr-2`, 650M, Qwen3.5-style). Surya is *structured* OCR: instead of a flat markdown blob, it returns per-block HTML with bounding boxes, reading order, and labels (equations in ``). This recipe writes **both**: --output-column (default `markdown`) flattened, reading-order text per row surya_blocks the full structured result as JSON (bbox / polygon / label / reading_order / confidence / html per block), one entry per page. Three tasks via `--task`: ocr (default) full-page OCR -> text + per-block HTML/bboxes layout layout regions -> labelled boxes + reading order table table structure -> HTML (mode `full`) or rows/cols/cells (mode `simple`, via --table-mode) Input is one document per row: --image-column COL (default `image`) one image per row --pdf-column COL PDF bytes per row (multi-page; honors --page-range). Pages are concatenated in the text column and kept per-page in `surya_blocks`. ENGINE: Surya normally spawns a vLLM **server** (Docker) — which can't run inside an HF Job. This script instead does **offline batch inference**: it injects a custom in-process backend into Surya's `SuryaInferenceManager` that runs vLLM's offline `LLM().chat()` engine (no server, no HTTP). Surya still owns all the prompting, image preprocessing, and HTML/bbox parsing — we only swap the transport. Run on the **`vllm/vllm-openai:v0.20.1`** image (Surya's known-good vLLM build; the model is the recent, version-sensitive `qwen3_5` architecture). LICENSE NOTE: Surya's *code* is Apache-2.0 but the *weights* are a modified OpenRAIL-M license — free for research, personal use, and startups under $5M funding/revenue, but restricted from competitive use against Datalab's API. Confirm you are within those terms. https://huggingface.co/datalab-to/surya-ocr-2 HF Jobs (the [tool.hf-jobs] header pins the vLLM image, interpreter, PYTHONPATH, flavor and HF_TOKEN secret; needs `hf` CLI 1.32+): hf jobs uv run \\ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/surya-ocr.py \\ INPUT_DATASET OUTPUT_DATASET \\ --max-samples 5 --shuffle --seed 42 On your own GPU: uv run --with vllm==0.20.1 surya-ocr.py INPUT_DATASET OUTPUT_DATASET ... Model: datalab-to/surya-ocr-2 (package: surya-ocr, https://github.com/datalab-to/surya) """ import argparse import io import json import logging import math import os import sys import tempfile import time from datetime import datetime, timezone from typing import Any, Dict, List, Optional, Tuple from urllib.request import urlopen from datasets import load_dataset from huggingface_hub import DatasetCard, login from PIL import Image from toolz import partition_all from tqdm import tqdm logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) DEFAULT_MODEL = "datalab-to/surya-ocr-2" # Surya's own vision-tiling bounds (from its vLLM backend), applied to the # offline engine too so preprocessing matches the server path exactly. MM_PROCESSOR_KWARGS = {"min_pixels": 3136, "max_pixels": 6291456} TASKS = ("ocr", "layout", "table") def check_cuda_availability() -> None: """Exit early with a clear message if there's no GPU.""" import torch if not torch.cuda.is_available(): logger.error("CUDA is not available. This script requires a GPU.") logger.error( "Run on Hugging Face Jobs with: hf jobs uv run