davanstrien HF Staff commited on
Commit
722b9f3
·
verified ·
1 Parent(s): 57f7548

Sync from GitHub via hub-sync

Browse files
Files changed (3) hide show
  1. CLAUDE.md +36 -2
  2. README.md +1 -1
  3. surya-ocr-bucket.py +1389 -0
CLAUDE.md CHANGED
@@ -339,8 +339,42 @@ import). Checked: no other `surya*` file in the repo.
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.
 
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.
README.md CHANGED
@@ -70,7 +70,7 @@ _Sorted by model size:_
70
  | `rolm-ocr.py` | [RolmOCR](https://huggingface.co/reducto/RolmOCR) | 7B | vLLM | Qwen2.5-VL based, general-purpose |
71
  | `numarkdown-ocr.py` | [NuMarkdown-8B](https://huggingface.co/numind/NuMarkdown-8B-Thinking) | 8B | vLLM | Reasoning-based OCR |
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
 
 
70
  | `rolm-ocr.py` | [RolmOCR](https://huggingface.co/reducto/RolmOCR) | 7B | vLLM | Qwen2.5-VL based, general-purpose |
71
  | `numarkdown-ocr.py` | [NuMarkdown-8B](https://huggingface.co/numind/NuMarkdown-8B-Thinking) | 8B | vLLM | Reasoning-based OCR |
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 · `surya-ocr-bucket.py` is the structured bucket recipe — OCR a bucket of files (no dataset round-trip) via either a FUSE mount **or** `huggingface_hub` batch-copy (`--io-mode mount|copy`), writing per-page `.md` + `.json` (`surya_blocks`) back to a bucket (resumable) and/or a pushed dataset · `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
 
surya-ocr-bucket.py ADDED
@@ -0,0 +1,1389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)