Sync from GitHub via hub-sync
Browse files- CLAUDE.md +10 -0
- README.md +1 -1
- lighton-ocr2-saturate.py +174 -0
- models.json +26 -0
- ovis-ocr2-saturate.py +235 -0
CLAUDE.md
CHANGED
|
@@ -273,6 +273,16 @@ ARM wheels) — if a nightly-recipe install fails on resolution, wait and retry
|
|
| 273 |
|
| 274 |
## Change log
|
| 275 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
- **2026-07-14** — added `ovis-ocr2.py` (`ATH-MaaS/OvisOCR2`, 0.9B Qwen3.5, 96.58 OmniDocBench v1.6,
|
| 277 |
Apache-2.0; stable vLLM ≥0.22.1, `gdn_prefill_backend="triton"`, card-exact prompt/postprocessing).
|
| 278 |
Smoke-tested green on the default uv image, a10g-small, resolved vLLM 0.25.1 (5/5 pages, tags filtered,
|
|
|
|
| 273 |
|
| 274 |
## Change log
|
| 275 |
|
| 276 |
+
- **2026-07-29** — added the first two **`-saturate.py` companions**: `lighton-ocr2-saturate.py` and
|
| 277 |
+
`ovis-ocr2-saturate.py`. Same model/prompt/sampling/post-processing as their `-server.py` siblings;
|
| 278 |
+
the driver half (concurrency, retries, output, resume) is the `saturate` package (pinned `>=0.1.1`,
|
| 279 |
+
the allowed *package*-dep pattern — no local imports). Each carries a `SERVING` dict at the top
|
| 280 |
+
(serve flags + client sampling + context-math assert) as the machine-readable tuning prior — the
|
| 281 |
+
runtime-consumed successor to the dropped `[tool.serving]` header idea. Output shape differs from
|
| 282 |
+
`-server.py`: a NEW dataset repo of `{id, markdown, …, error}` parquet rows keyed by input id
|
| 283 |
+
(resume = anti-join on id), not input+column push; failed pages become durable error rows
|
| 284 |
+
(`--retry-errors` heals), NOT `[OCR ERROR]` sentinels — the first recipes closing the
|
| 285 |
+
error-signalling gap noted in Conventions.
|
| 286 |
- **2026-07-14** — added `ovis-ocr2.py` (`ATH-MaaS/OvisOCR2`, 0.9B Qwen3.5, 96.58 OmniDocBench v1.6,
|
| 287 |
Apache-2.0; stable vLLM ≥0.22.1, `gdn_prefill_backend="triton"`, card-exact prompt/postprocessing).
|
| 288 |
Smoke-tested green on the default uv image, a10g-small, resolved vLLM 0.25.1 (5/5 pages, tags filtered,
|
README.md
CHANGED
|
@@ -33,7 +33,7 @@ This will:
|
|
| 33 |
|
| 34 |
## Serve a model as a live endpoint
|
| 35 |
|
| 36 |
-
The recipes here run as batch jobs. Some models also have a **`-server.py` sibling recipe** that runs the same dataset→dataset batch job through an in-job `vllm serve` + concurrent driver — measurably faster (continuous batching stays fed) and more robust (one bad image fails one request, not a whole batch); see [SERVING.md](SERVING.md) for the architecture, A/B numbers, and which models officially document server mode. To call a model interactively, from an agent, or with concurrent ad-hoc requests, you can instead run it as a temporary endpoint: [HF Jobs serving](https://huggingface.co/docs/hub/jobs-serving) exposes a port on a GPU Job, giving an OpenAI-compatible endpoint that runs until the job is cancelled or its `--timeout` is reached. See [serving-unlimited-ocr.md](serving-unlimited-ocr.md) for a worked example serving Baidu's [Unlimited-OCR](https://huggingface.co/baidu/Unlimited-OCR) — with vLLM (official image) or SGLang. To OCR a whole corpus of single-page images instead, the batch recipe `unlimited-ocr-vllm.py` is the better fit (it's single-image only). **Multi-page** documents need a server: both vLLM and SGLang read clean multi-page docs, but **SGLang is the more robust** — on hard/degraded scans vLLM multi-page hallucinated in our tests while SGLang held up.
|
| 37 |
|
| 38 |
## Models at a glance
|
| 39 |
|
|
|
|
| 33 |
|
| 34 |
## Serve a model as a live endpoint
|
| 35 |
|
| 36 |
+
The recipes here run as batch jobs. Some models also have a **`-server.py` sibling recipe** that runs the same dataset→dataset batch job through an in-job `vllm serve` + concurrent driver — measurably faster (continuous batching stays fed) and more robust (one bad image fails one request, not a whole batch); see [SERVING.md](SERVING.md) for the architecture, A/B numbers, and which models officially document server mode. A third lane is starting: **`-saturate.py` companions** ([`lighton-ocr2-saturate.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/lighton-ocr2-saturate.py), [`ovis-ocr2-saturate.py`](https://huggingface.co/datasets/uv-scripts/ocr/blob/main/ovis-ocr2-saturate.py)) keep the same model, prompt, and sampling but replace the hand-rolled driver half with the [saturate](https://github.com/davanstrien/saturate) library — adaptive concurrency (no `--concurrency` to tune), crash-safe resumable output (re-running skips finished rows), and durable per-row error records instead of `[OCR ERROR]` strings. Each carries a machine-readable `SERVING` dict (serve flags + sampling + context math) at the top of the script. To call a model interactively, from an agent, or with concurrent ad-hoc requests, you can instead run it as a temporary endpoint: [HF Jobs serving](https://huggingface.co/docs/hub/jobs-serving) exposes a port on a GPU Job, giving an OpenAI-compatible endpoint that runs until the job is cancelled or its `--timeout` is reached. See [serving-unlimited-ocr.md](serving-unlimited-ocr.md) for a worked example serving Baidu's [Unlimited-OCR](https://huggingface.co/baidu/Unlimited-OCR) — with vLLM (official image) or SGLang. To OCR a whole corpus of single-page images instead, the batch recipe `unlimited-ocr-vllm.py` is the better fit (it's single-image only). **Multi-page** documents need a server: both vLLM and SGLang read clean multi-page docs, but **SGLang is the more robust** — on hard/degraded scans vLLM multi-page hallucinated in our tests while SGLang held up.
|
| 37 |
|
| 38 |
## Models at a glance
|
| 39 |
|
lighton-ocr2-saturate.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "saturate[hf]>=0.1.1",
|
| 5 |
+
# "pillow>=10",
|
| 6 |
+
# ]
|
| 7 |
+
# ///
|
| 8 |
+
"""
|
| 9 |
+
Convert document images to markdown using LightOnOCR-2 via saturate.
|
| 10 |
+
|
| 11 |
+
Companion to `lighton-ocr2-server.py`: same model, same message shape, same
|
| 12 |
+
sampling, same in-job `vllm serve` — but the driver half (concurrency, retries,
|
| 13 |
+
output, resume) is the `saturate` library instead of hand-rolled code. What that
|
| 14 |
+
buys over the -server recipe:
|
| 15 |
+
|
| 16 |
+
- **Adaptive concurrency** — the window sizes itself from live engine signals
|
| 17 |
+
(no `--concurrency` flag to tune).
|
| 18 |
+
- **Crash-safe, resumable output** — results stream to the output repo as
|
| 19 |
+
parquet parts while the run is hot; re-running the same command skips
|
| 20 |
+
everything already done (exact anti-join on id). A 10k-page job that dies at
|
| 21 |
+
9k resumes at 9k.
|
| 22 |
+
- **Durable error rows** — a failed page is recorded as `{id, error}` instead of
|
| 23 |
+
an `[OCR ERROR]` string in the text column; `--retry-errors` re-admits only
|
| 24 |
+
those rows on a later run.
|
| 25 |
+
|
| 26 |
+
Run on HF Jobs (the script starts `vllm serve` itself; the --image flag
|
| 27 |
+
provides the `vllm` binary):
|
| 28 |
+
|
| 29 |
+
hf jobs uv run --detach --flavor a10g-small -s HF_TOKEN --timeout 4h \\
|
| 30 |
+
--image vllm/vllm-openai:latest \\
|
| 31 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr2-saturate.py \\
|
| 32 |
+
<input-dataset> <output-dataset>
|
| 33 |
+
|
| 34 |
+
Output layout (differs from the -server recipe, which pushes input+markdown):
|
| 35 |
+
the output repo holds `data/part-*.parquet` with rows
|
| 36 |
+
`{id, markdown, model, prompt_tokens, completion_tokens, error}` keyed by the
|
| 37 |
+
input row id (`--id-column`, or `<split>-<index>` by default). Read it with
|
| 38 |
+
`datasets.load_dataset(<output>, data_dir="data")` or `saturate.read_output`;
|
| 39 |
+
join back to the input on id. Run metadata lands in `data/completions/`.
|
| 40 |
+
|
| 41 |
+
Model: lightonai/LightOnOCR-2-1B (1B, Apache-2.0)
|
| 42 |
+
- Message is the image ONLY (no text prompt) — LightOnOCR-2's trained format.
|
| 43 |
+
- Images resized client-side so the longest dimension is 1540px (training
|
| 44 |
+
resolution at 200 DPI), same as the offline recipe.
|
| 45 |
+
- Sampling per the card: temperature 0.2, top_p 0.9, max_tokens 4096.
|
| 46 |
+
|
| 47 |
+
The SERVING dict below is the per-model tuning prior (serve flags + client
|
| 48 |
+
sampling + context math). Agents can `ast.literal_eval` it without running
|
| 49 |
+
the script; the script itself consumes it, so it cannot drift from reality.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
import argparse
|
| 53 |
+
import base64
|
| 54 |
+
import io
|
| 55 |
+
import sys
|
| 56 |
+
|
| 57 |
+
# Serving starting values for lightonai/LightOnOCR-2-1B. Per-value provenance:
|
| 58 |
+
# - serve_args: the model card's own `vllm serve` command, verbatim (the three
|
| 59 |
+
# cache/mm flags; OCR never reuses images, so those caches only cost memory).
|
| 60 |
+
# - max_model_len 8192: NOT in the card's serve command (card default = native
|
| 61 |
+
# 16384). House choice inherited from lighton-ocr2-server.py: halves the KV
|
| 62 |
+
# allocation on 24GB and still fits a 1540px page (~2.5k image tokens) + 4096
|
| 63 |
+
# output with headroom.
|
| 64 |
+
# - max_tokens/temperature/top_p: card's sampling example, verbatim.
|
| 65 |
+
# - target_size 1540: card's stated training resolution (200 DPI longest side).
|
| 66 |
+
# Throughput receipt (a10g-small): 0.955 img/s at 1k pages incl. streaming.
|
| 67 |
+
SERVING = {
|
| 68 |
+
"model": "lightonai/LightOnOCR-2-1B",
|
| 69 |
+
"image": "vllm/vllm-openai:latest",
|
| 70 |
+
"max_model_len": 8192,
|
| 71 |
+
"serve_args": [
|
| 72 |
+
"--limit-mm-per-prompt", '{"image": 1}',
|
| 73 |
+
"--mm-processor-cache-gb", "0",
|
| 74 |
+
"--no-enable-prefix-caching",
|
| 75 |
+
],
|
| 76 |
+
"max_tokens": 4096,
|
| 77 |
+
"temperature": 0.2,
|
| 78 |
+
"top_p": 0.9,
|
| 79 |
+
"target_size": 1540,
|
| 80 |
+
}
|
| 81 |
+
assert SERVING["max_tokens"] < SERVING["max_model_len"], (
|
| 82 |
+
"context math: max_tokens must leave room for the image tokens "
|
| 83 |
+
"(input + output <= max_model_len, or every request 400s)"
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def to_pil(value):
|
| 88 |
+
from PIL import Image
|
| 89 |
+
|
| 90 |
+
if isinstance(value, Image.Image):
|
| 91 |
+
return value
|
| 92 |
+
if isinstance(value, dict) and value.get("bytes"):
|
| 93 |
+
return Image.open(io.BytesIO(value["bytes"]))
|
| 94 |
+
if isinstance(value, (bytes, bytearray)):
|
| 95 |
+
return Image.open(io.BytesIO(value))
|
| 96 |
+
raise ValueError(f"unsupported image value: {type(value)}")
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def encode_image(value, target_size: int) -> str:
|
| 100 |
+
"""RGB-convert, resize longest dimension to target_size, return base64 PNG."""
|
| 101 |
+
from PIL import Image
|
| 102 |
+
|
| 103 |
+
img = to_pil(value).convert("RGB")
|
| 104 |
+
if target_size:
|
| 105 |
+
w, h = img.size
|
| 106 |
+
if max(w, h) != target_size:
|
| 107 |
+
scale = target_size / max(w, h)
|
| 108 |
+
img = img.resize((round(w * scale), round(h * scale)), Image.LANCZOS)
|
| 109 |
+
buf = io.BytesIO()
|
| 110 |
+
img.save(buf, format="PNG")
|
| 111 |
+
return base64.b64encode(buf.getvalue()).decode()
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def main():
|
| 115 |
+
ap = argparse.ArgumentParser(description="LightOnOCR-2 batch OCR via saturate")
|
| 116 |
+
ap.add_argument("input_dataset", help="Input dataset repo id (rows with an image column)")
|
| 117 |
+
ap.add_argument("output_dataset", help="Output dataset repo id (created if missing)")
|
| 118 |
+
ap.add_argument("--image-column", default="image")
|
| 119 |
+
ap.add_argument("--config", default=None, help="Dataset config name")
|
| 120 |
+
ap.add_argument("--split", default="train")
|
| 121 |
+
ap.add_argument("--id-column", default=None,
|
| 122 |
+
help="Column to use as row id (default: split-index ids)")
|
| 123 |
+
ap.add_argument("--limit", type=int, default=None)
|
| 124 |
+
ap.add_argument("--max-tokens", type=int, default=SERVING["max_tokens"])
|
| 125 |
+
ap.add_argument("--temperature", type=float, default=SERVING["temperature"])
|
| 126 |
+
ap.add_argument("--target-size", type=int, default=SERVING["target_size"])
|
| 127 |
+
ap.add_argument("--no-resize", action="store_true")
|
| 128 |
+
ap.add_argument("--retry-errors", action="store_true",
|
| 129 |
+
help="Re-admit rows whose only record is an error row")
|
| 130 |
+
args = ap.parse_args()
|
| 131 |
+
|
| 132 |
+
from saturate import Auto, Engine, dataset_rows, pump
|
| 133 |
+
|
| 134 |
+
target_size = 0 if args.no_resize else args.target_size
|
| 135 |
+
rows = dataset_rows(
|
| 136 |
+
args.input_dataset, config=args.config, split=args.split,
|
| 137 |
+
columns=[args.image_column], ids=args.id_column or "index", limit=args.limit,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
def to_request(row):
|
| 141 |
+
b64 = encode_image(row[args.image_column], target_size)
|
| 142 |
+
return {
|
| 143 |
+
"model": SERVING["model"],
|
| 144 |
+
"messages": [{"role": "user", "content": [
|
| 145 |
+
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}},
|
| 146 |
+
]}],
|
| 147 |
+
"temperature": args.temperature,
|
| 148 |
+
"top_p": SERVING["top_p"],
|
| 149 |
+
"max_tokens": args.max_tokens,
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
def parse(row, body):
|
| 153 |
+
usage = body.get("usage") or {}
|
| 154 |
+
return {
|
| 155 |
+
"markdown": body["choices"][0]["message"]["content"].strip(),
|
| 156 |
+
"model": SERVING["model"],
|
| 157 |
+
"prompt_tokens": usage.get("prompt_tokens"),
|
| 158 |
+
"completion_tokens": usage.get("completion_tokens"),
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
extra = ["--max-model-len", str(SERVING["max_model_len"]), *SERVING["serve_args"]]
|
| 162 |
+
output = f"hf://datasets/{args.output_dataset}/data"
|
| 163 |
+
with Engine(SERVING["model"], engine="vllm", extra_args=extra) as endpoint:
|
| 164 |
+
stats = pump(rows, to_request, parse, endpoint, output,
|
| 165 |
+
window=Auto(initial=8, max_limit=48),
|
| 166 |
+
retry_errors=args.retry_errors)
|
| 167 |
+
|
| 168 |
+
print(f"https://huggingface.co/datasets/{args.output_dataset} "
|
| 169 |
+
f"({stats.rows_processed} ok, {stats.rows_failed} error rows)", file=sys.stderr)
|
| 170 |
+
print("LIGHTON_OCR2_SATURATE " + stats.to_json(), flush=True)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
if __name__ == "__main__":
|
| 174 |
+
main()
|
models.json
CHANGED
|
@@ -129,6 +129,17 @@
|
|
| 129 |
"notes": "Server-mode sibling of ovis-ocr2.py: ~1.7x its inference throughput, per-request failure isolation. See SERVING.md.",
|
| 130 |
"languages": { "evidence": "not-stated" }
|
| 131 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
"lighton-ocr.py": {
|
| 133 |
"model_id": "lightonai/LightOnOCR-1B-1025",
|
| 134 |
"params": "1B",
|
|
@@ -170,6 +181,21 @@
|
|
| 170 |
"notes": "Adds zh/ja over v1; declared, not benchmarked per language."
|
| 171 |
}
|
| 172 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
"hunyuan-ocr.py": {
|
| 174 |
"model_id": "tencent/HunyuanOCR",
|
| 175 |
"revision": "f6af82ee007fe6091b29fb3bb287b491ead41c82",
|
|
|
|
| 129 |
"notes": "Server-mode sibling of ovis-ocr2.py: ~1.7x its inference throughput, per-request failure isolation. See SERVING.md.",
|
| 130 |
"languages": { "evidence": "not-stated" }
|
| 131 |
},
|
| 132 |
+
"ovis-ocr2-saturate.py": {
|
| 133 |
+
"model_id": "ATH-MaaS/OvisOCR2",
|
| 134 |
+
"params": "0.9B",
|
| 135 |
+
"backend": "saturate (in-job vllm serve + saturate pump)",
|
| 136 |
+
"image": "vllm/vllm-openai:latest",
|
| 137 |
+
"task": "ocr",
|
| 138 |
+
"output": "markdown + LaTeX + HTML tables",
|
| 139 |
+
"license": "apache-2.0",
|
| 140 |
+
"notes": "saturate companion of ovis-ocr2-server.py: same model/prompt/sampling/post-processing; the driver half (adaptive concurrency, retries, resumable parquet output, durable error rows) is the saturate library. SERVING dict at the top of the script is the machine-readable tuning prior.",
|
| 141 |
+
"languages": { "evidence": "not-stated" }
|
| 142 |
+
},
|
| 143 |
"lighton-ocr.py": {
|
| 144 |
"model_id": "lightonai/LightOnOCR-1B-1025",
|
| 145 |
"params": "1B",
|
|
|
|
| 181 |
"notes": "Adds zh/ja over v1; declared, not benchmarked per language."
|
| 182 |
}
|
| 183 |
},
|
| 184 |
+
"lighton-ocr2-saturate.py": {
|
| 185 |
+
"model_id": "lightonai/LightOnOCR-2-1B",
|
| 186 |
+
"params": "1B",
|
| 187 |
+
"backend": "saturate (in-job vllm serve + saturate pump)",
|
| 188 |
+
"image": "vllm/vllm-openai:latest",
|
| 189 |
+
"task": "ocr",
|
| 190 |
+
"output": "markdown",
|
| 191 |
+
"notes": "saturate companion of lighton-ocr2-server.py: same model/message shape/sampling; the driver half (adaptive concurrency, retries, resumable parquet output, durable error rows) is the saturate library. SERVING dict at the top of the script is the machine-readable tuning prior.",
|
| 192 |
+
"languages": {
|
| 193 |
+
"evidence": "named-list",
|
| 194 |
+
"count": 11,
|
| 195 |
+
"named": ["en", "fr", "de", "es", "it", "nl", "pt", "sv", "da", "zh", "ja"],
|
| 196 |
+
"notes": "Adds zh/ja over v1; declared, not benchmarked per language."
|
| 197 |
+
}
|
| 198 |
+
},
|
| 199 |
"hunyuan-ocr.py": {
|
| 200 |
"model_id": "tencent/HunyuanOCR",
|
| 201 |
"revision": "f6af82ee007fe6091b29fb3bb287b491ead41c82",
|
ovis-ocr2-saturate.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "saturate[hf]>=0.1.1",
|
| 5 |
+
# "pillow>=10",
|
| 6 |
+
# ]
|
| 7 |
+
# ///
|
| 8 |
+
"""
|
| 9 |
+
Convert document images to markdown using OvisOCR2 via saturate.
|
| 10 |
+
|
| 11 |
+
Companion to `ovis-ocr2-server.py`: same model, prompt, message shape, sampling,
|
| 12 |
+
and post-processing, same in-job `vllm serve` — but the driver half (concurrency,
|
| 13 |
+
retries, output, resume) is the `saturate` library instead of hand-rolled code.
|
| 14 |
+
What that buys over the -server recipe:
|
| 15 |
+
|
| 16 |
+
- **Adaptive concurrency** — the window sizes itself from live engine signals
|
| 17 |
+
(no `--concurrency` flag to tune).
|
| 18 |
+
- **Crash-safe, resumable output** — results stream to the output repo as
|
| 19 |
+
parquet parts while the run is hot; re-running the same command skips
|
| 20 |
+
everything already done (exact anti-join on id).
|
| 21 |
+
- **Durable error rows** — a failed page is recorded as `{id, error}` instead of
|
| 22 |
+
an `[OCR ERROR]` string in the text column; `--retry-errors` re-admits only
|
| 23 |
+
those rows on a later run.
|
| 24 |
+
|
| 25 |
+
Run on HF Jobs (the script starts `vllm serve` itself; the --image flag
|
| 26 |
+
provides the `vllm` binary):
|
| 27 |
+
|
| 28 |
+
hf jobs uv run --detach --flavor a10g-small -s HF_TOKEN --timeout 4h \\
|
| 29 |
+
--image vllm/vllm-openai:latest \\
|
| 30 |
+
https://huggingface.co/datasets/uv-scripts/ocr/raw/main/ovis-ocr2-saturate.py \\
|
| 31 |
+
<input-dataset> <output-dataset>
|
| 32 |
+
|
| 33 |
+
Output layout (differs from the -server recipe, which pushes input+markdown):
|
| 34 |
+
the output repo holds `data/part-*.parquet` with rows
|
| 35 |
+
`{id, markdown, model, prompt_tokens, completion_tokens, error}` keyed by the
|
| 36 |
+
input row id (`--id-column`, or `<split>-<index>` by default). Read it with
|
| 37 |
+
`datasets.load_dataset(<output>, data_dir="data")` or `saturate.read_output`;
|
| 38 |
+
join back to the input on id. Run metadata lands in `data/completions/`.
|
| 39 |
+
|
| 40 |
+
Model: ATH-MaaS/OvisOCR2 (0.9B, Apache-2.0, 96.58 OmniDocBench)
|
| 41 |
+
- The card's exact OCR prompt (leading newline included — outputs are tuned to
|
| 42 |
+
this wording), image before text, `enable_thinking=False` via
|
| 43 |
+
chat_template_kwargs (the Qwen3.5 template otherwise injects a thinking
|
| 44 |
+
preamble).
|
| 45 |
+
- Images downscaled client-side to the processor's max_pixels bound (8.3MP) and
|
| 46 |
+
sent as JPEG q95 — the same clamp the server would apply, moved client-side to
|
| 47 |
+
shrink the payload; min/max pixel bounds ride on the engine boot flag.
|
| 48 |
+
- Post-processing per the card: bbox `<img>` placeholder blocks dropped (keep
|
| 49 |
+
with --keep-image-tags) and degenerate trailing repeats trimmed.
|
| 50 |
+
|
| 51 |
+
The SERVING dict below is the per-model tuning prior (serve flags + client
|
| 52 |
+
sampling + context math). Agents can `ast.literal_eval` it without running
|
| 53 |
+
the script; the script itself consumes it, so it cannot drift from reality.
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
import argparse
|
| 57 |
+
import base64
|
| 58 |
+
import io
|
| 59 |
+
import math
|
| 60 |
+
import sys
|
| 61 |
+
|
| 62 |
+
# Serving starting values for ATH-MaaS/OvisOCR2. Per-value provenance:
|
| 63 |
+
# - The card documents OFFLINE inference only — no `vllm serve` command exists
|
| 64 |
+
# upstream. The whole server arrangement here (incl. serve_args) is the
|
| 65 |
+
# uv-scripts construction inherited from ovis-ocr2-server.py.
|
| 66 |
+
# - max_model_len 32768: house choice (card sets none; native ctx is 262144 —
|
| 67 |
+
# NEVER boot without a cap on 24GB, the full-context KV profile kills boot).
|
| 68 |
+
# - cache/mm flags: house OCR defaults (OCR never reuses images, so prefix/
|
| 69 |
+
# processor caches only cost memory).
|
| 70 |
+
# - mm-processor-kwargs pixel bounds: card's offline example, verbatim
|
| 71 |
+
# (min 448*448=200704, max 2880*2880=8294400), moved to the engine flag.
|
| 72 |
+
# - max_tokens 16384 / temperature 0.0: card's sampling, verbatim.
|
| 73 |
+
# Throughput receipt (a10g-small, 20 pages): 4,057 tok/s, window ramped to 32.
|
| 74 |
+
SERVING = {
|
| 75 |
+
"model": "ATH-MaaS/OvisOCR2",
|
| 76 |
+
"image": "vllm/vllm-openai:latest",
|
| 77 |
+
"max_model_len": 32768,
|
| 78 |
+
"serve_args": [
|
| 79 |
+
"--limit-mm-per-prompt", '{"image": 1}',
|
| 80 |
+
"--mm-processor-cache-gb", "0",
|
| 81 |
+
"--no-enable-prefix-caching",
|
| 82 |
+
"--mm-processor-kwargs",
|
| 83 |
+
'{"images_kwargs": {"min_pixels": 200704, "max_pixels": 8294400}}',
|
| 84 |
+
],
|
| 85 |
+
"max_tokens": 16384,
|
| 86 |
+
"temperature": 0.0,
|
| 87 |
+
"max_pixels": 8294400,
|
| 88 |
+
}
|
| 89 |
+
assert SERVING["max_tokens"] < SERVING["max_model_len"], (
|
| 90 |
+
"context math: max_tokens must leave room for the image tokens "
|
| 91 |
+
"(input + output <= max_model_len, or every request 400s)"
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
OCR_PROMPT = (
|
| 95 |
+
"\nExtract all readable content from the image in natural human reading order "
|
| 96 |
+
"and output the result as a single Markdown document. For charts or images, "
|
| 97 |
+
'represent them using an HTML image tag: <img src="images/bbox_{left}_{top}_{right}_{bottom}.jpg" />, '
|
| 98 |
+
"where left, top, right, bottom are bounding box coordinates scaled to [0, 1000). "
|
| 99 |
+
"Format formulas as LaTeX. Format tables as HTML: <table>...</table>. "
|
| 100 |
+
"Transcribe all other text as standard Markdown. Preserve the original text "
|
| 101 |
+
"without translation or paraphrasing."
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def to_pil(value):
|
| 106 |
+
from PIL import Image
|
| 107 |
+
|
| 108 |
+
if isinstance(value, Image.Image):
|
| 109 |
+
return value
|
| 110 |
+
if isinstance(value, dict) and value.get("bytes"):
|
| 111 |
+
return Image.open(io.BytesIO(value["bytes"]))
|
| 112 |
+
if isinstance(value, (bytes, bytearray)):
|
| 113 |
+
return Image.open(io.BytesIO(value))
|
| 114 |
+
raise ValueError(f"unsupported image value: {type(value)}")
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def encode_image(value, max_pixels: int) -> str:
|
| 118 |
+
"""RGB-convert, downscale to max_pixels if needed, return base64 JPEG q95."""
|
| 119 |
+
from PIL import Image
|
| 120 |
+
|
| 121 |
+
img = to_pil(value).convert("RGB")
|
| 122 |
+
w, h = img.size
|
| 123 |
+
if w * h > max_pixels:
|
| 124 |
+
scale = math.sqrt(max_pixels / (w * h))
|
| 125 |
+
img = img.resize((int(w * scale), int(h * scale)), Image.LANCZOS)
|
| 126 |
+
buf = io.BytesIO()
|
| 127 |
+
img.save(buf, format="JPEG", quality=95)
|
| 128 |
+
return base64.b64encode(buf.getvalue()).decode()
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def clean_truncated_repeats(
|
| 132 |
+
text: str,
|
| 133 |
+
min_text_len: int = 8000,
|
| 134 |
+
max_period: int = 200,
|
| 135 |
+
min_period: int = 1,
|
| 136 |
+
min_repeat_chars: int = 100,
|
| 137 |
+
min_repeat_times: int = 5,
|
| 138 |
+
) -> str:
|
| 139 |
+
"""Trim degenerate trailing repetition (verbatim port of the model card's cleanup)."""
|
| 140 |
+
n = len(text)
|
| 141 |
+
if n < min_text_len:
|
| 142 |
+
return text
|
| 143 |
+
|
| 144 |
+
max_period = min(max_period, n - 1)
|
| 145 |
+
for unit_len in range(min_period, max_period + 1):
|
| 146 |
+
if text[n - 1] != text[n - 1 - unit_len]:
|
| 147 |
+
continue
|
| 148 |
+
|
| 149 |
+
match_len = 1
|
| 150 |
+
idx = n - 2
|
| 151 |
+
while idx >= unit_len and text[idx] == text[idx - unit_len]:
|
| 152 |
+
match_len += 1
|
| 153 |
+
idx -= 1
|
| 154 |
+
|
| 155 |
+
total_len = match_len + unit_len
|
| 156 |
+
repeat_times = total_len // unit_len
|
| 157 |
+
tail_len = total_len % unit_len
|
| 158 |
+
|
| 159 |
+
if repeat_times >= min_repeat_times and total_len >= min_repeat_chars:
|
| 160 |
+
return text[: n - total_len + unit_len] + text[n - tail_len:]
|
| 161 |
+
|
| 162 |
+
return text
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def filter_image_tags(text: str) -> str:
|
| 166 |
+
blocks = text.split("\n\n")
|
| 167 |
+
return "\n\n".join(
|
| 168 |
+
b for b in blocks if not b.strip().startswith('<img src="images/bbox_')
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def main():
|
| 173 |
+
ap = argparse.ArgumentParser(description="OvisOCR2 batch OCR via saturate")
|
| 174 |
+
ap.add_argument("input_dataset", help="Input dataset repo id (rows with an image column)")
|
| 175 |
+
ap.add_argument("output_dataset", help="Output dataset repo id (created if missing)")
|
| 176 |
+
ap.add_argument("--image-column", default="image")
|
| 177 |
+
ap.add_argument("--config", default=None, help="Dataset config name")
|
| 178 |
+
ap.add_argument("--split", default="train")
|
| 179 |
+
ap.add_argument("--id-column", default=None,
|
| 180 |
+
help="Column to use as row id (default: split-index ids)")
|
| 181 |
+
ap.add_argument("--limit", type=int, default=None)
|
| 182 |
+
ap.add_argument("--max-tokens", type=int, default=SERVING["max_tokens"])
|
| 183 |
+
ap.add_argument("--keep-image-tags", action="store_true",
|
| 184 |
+
help="Keep the bbox <img> placeholder blocks in the output")
|
| 185 |
+
ap.add_argument("--retry-errors", action="store_true",
|
| 186 |
+
help="Re-admit rows whose only record is an error row")
|
| 187 |
+
args = ap.parse_args()
|
| 188 |
+
|
| 189 |
+
from saturate import Auto, Engine, dataset_rows, pump
|
| 190 |
+
|
| 191 |
+
rows = dataset_rows(
|
| 192 |
+
args.input_dataset, config=args.config, split=args.split,
|
| 193 |
+
columns=[args.image_column], ids=args.id_column or "index", limit=args.limit,
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
def to_request(row):
|
| 197 |
+
b64 = encode_image(row[args.image_column], SERVING["max_pixels"])
|
| 198 |
+
return {
|
| 199 |
+
"model": SERVING["model"],
|
| 200 |
+
"messages": [{"role": "user", "content": [
|
| 201 |
+
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64}"}},
|
| 202 |
+
{"type": "text", "text": OCR_PROMPT},
|
| 203 |
+
]}],
|
| 204 |
+
"temperature": SERVING["temperature"],
|
| 205 |
+
"max_tokens": args.max_tokens,
|
| 206 |
+
"chat_template_kwargs": {"enable_thinking": False},
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
def parse(row, body):
|
| 210 |
+
text = body["choices"][0]["message"]["content"].strip()
|
| 211 |
+
if not args.keep_image_tags:
|
| 212 |
+
text = filter_image_tags(text)
|
| 213 |
+
text = clean_truncated_repeats(text)
|
| 214 |
+
usage = body.get("usage") or {}
|
| 215 |
+
return {
|
| 216 |
+
"markdown": text,
|
| 217 |
+
"model": SERVING["model"],
|
| 218 |
+
"prompt_tokens": usage.get("prompt_tokens"),
|
| 219 |
+
"completion_tokens": usage.get("completion_tokens"),
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
extra = ["--max-model-len", str(SERVING["max_model_len"]), *SERVING["serve_args"]]
|
| 223 |
+
output = f"hf://datasets/{args.output_dataset}/data"
|
| 224 |
+
with Engine(SERVING["model"], engine="vllm", extra_args=extra) as endpoint:
|
| 225 |
+
stats = pump(rows, to_request, parse, endpoint, output,
|
| 226 |
+
window=Auto(initial=8, max_limit=48),
|
| 227 |
+
retry_errors=args.retry_errors)
|
| 228 |
+
|
| 229 |
+
print(f"https://huggingface.co/datasets/{args.output_dataset} "
|
| 230 |
+
f"({stats.rows_processed} ok, {stats.rows_failed} error rows)", file=sys.stderr)
|
| 231 |
+
print("OVIS_OCR2_SATURATE " + stats.to_json(), flush=True)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
if __name__ == "__main__":
|
| 235 |
+
main()
|