diff --git a/AGENTS.md b/AGENTS.md deleted file mode 100644 index d7f5150e0faf6cdc893eb15413952e4d52f6208f..0000000000000000000000000000000000000000 --- a/AGENTS.md +++ /dev/null @@ -1,109 +0,0 @@ -# For coding agents - -This repo is a curated collection of ready-to-run OCR scripts — each one self-contained -via UV inline metadata, runnable over the network via `hf jobs uv run`. No clone, no -install, no setup. - -## Don't rely on this doc — discover the current state - -This file will go stale. Prefer these sources of truth: - -- `hf jobs uv run --help` — job submission flags (volumes, secrets, flavors, timeouts) -- `hf jobs hardware` — current GPU flavors and pricing -- `hf auth whoami` — check HF token is set -- `hf jobs ps` / `hf jobs logs ` — monitor running jobs -- `ls` the repo to see which scripts actually exist (bucket variants especially) -- [README.md](./README.md) — the table of scripts with model sizes and notes - -## Picking a script - -The [README.md](./README.md) table lists every script with model size, backend, and -a short note. Axes that matter: - -- **Model size** vs accuracy vs GPU cost. Smaller = cheaper per doc. -- **Backend**: vLLM scripts are usually fastest at scale. `transformers` and - `falcon-perception` are alternatives for specific models. -- **Task support**: most scripts do plain text; some expose `--task-mode` - (table, formula, layout, etc.) — check the script's own docstring. -- **Language coverage**: [`models.json`](./models.json) maps every script to its model, - params, backend, required image pins, and what the model card claims about languages — - with an `evidence` level (`per-language-benchmark` beats a bare `multilingual` tag). - Human-readable version: [LANGUAGES.md](./LANGUAGES.md). - -For the authoritative benchmark numbers on any model in the table, query the model -card programmatically — every OCR model publishes eval results on its card: - - from huggingface_hub import HfApi - info = HfApi().model_info("tiiuae/Falcon-OCR", expand=["evalResults"]) - for r in info.eval_results: - print(r.dataset_id, r.value) - -See the [leaderboard data guide](https://huggingface.co/docs/hub/en/leaderboard-data-guide) -for the full API. This is more reliable than any markdown table that might drift. - -## Getting help from a specific script - -Each script has a docstring at the top with a description and usage examples. To read it -without downloading: - - curl -s https://huggingface.co/datasets/uv-scripts/ocr/raw/main/""" - - -class LiveView: - """Finished pages and run counters, served as a web page from inside the Job (`--live-port`).""" - - def __init__(self, port: int, model: str, pages_total, keep: int = 240, stale_s: float = 1800): - self.model, self.pages_total = model, pages_total - self.pages = collections.deque(maxlen=keep) # finished pages, newest last - self.images: dict[str, bytes] = {} # key -> JPEG, for prepared and kept pages - self.prepared: dict[str, tuple[str, float]] = {} # row id -> (image key, time prepared) - self.stale_s = stale_s # a prepared page not back after this long failed or was dropped - self.lock = threading.Lock() - self.made = self.seq = self.pages_done = self.words = 0 - self.booted = time.time() - self.started = None # first page prepared: the rate and the clock leave out the server start - self.finished = None - self.done_times = collections.deque() # when each recent page finished, for the rolling rate - self.gpu_name = None - live = self - - class Handler(BaseHTTPRequestHandler): - def do_GET(self): - try: - if self.path.startswith("/feed.json"): - try: - since = int(self.path.partition("since=")[2] or 0) - except ValueError: - since = 0 - self.reply(json.dumps(live.feed(since)).encode(), "application/json") - elif self.path.startswith("/img/"): - with live.lock: - jpeg = live.images.get(self.path[len("/img/"):].partition("?")[0]) - if jpeg is None: - self.send_error(404) - else: - self.reply(jpeg, "image/jpeg", cache="max-age=86400") - else: - self.reply(LIVE_PAGE.encode(), "text/html; charset=utf-8") - except (BrokenPipeError, ConnectionResetError): - pass # the viewer closed the tab mid-reply - - def reply(self, body: bytes, ctype: str, cache: str = "no-store"): - self.send_response(200) - self.send_header("Content-Type", ctype) - self.send_header("Cache-Control", cache) - self.end_headers() - self.wfile.write(body) - - def log_message(self, *args): # keep the Job log for the OCR run - pass - - class Server(ThreadingHTTPServer): - request_queue_size = 128 # a tab asks for several page images at once - - server = Server(("0.0.0.0", port), Handler) - threading.Thread(target=server.serve_forever, daemon=True).start() - threading.Thread(target=self.name_gpu, daemon=True).start() - # An exposed Job port is served at https://--.hf.jobs. - where = (f"https://{os.environ['JOB_ID']}--{port}.hf.jobs (needs --expose-public {port})" - if os.environ.get("JOB_ID") else f"http://localhost:{port}") - print(f"Live view: {where}", file=sys.stderr, flush=True) - - def name_gpu(self): - try: - out = subprocess.run(["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"], - capture_output=True, text=True, timeout=10, check=True).stdout.splitlines() - except (OSError, subprocess.SubprocessError): - return - if len(out) == 1: # the page says "one ": leave it out on a multi-GPU flavor - with self.lock: - self.gpu_name = out[0].strip() - - def add_thumbnail(self, row_id: str, image): - thumb = image.copy() - thumb.thumbnail((480, 480)) - buffer = io.BytesIO() - thumb.save(buffer, format="JPEG", quality=78) - with self.lock: - if self.started is None: - self.started = time.time() - self.made += 1 - key = f"{self.made}.jpg" - self.images[key] = buffer.getvalue() - old = self.prepared.get(row_id) - if old: # prepared again for a retry: drop the earlier copy - self.images.pop(old[0], None) - self.prepared[row_id] = (key, time.time()) - - def add_page(self, row_id: str, text: str): - now = time.time() - tail = row_id.rsplit(":", 1)[-1] - with self.lock: - key, _ = self.prepared.pop(row_id, ("", now)) - if len(self.pages) == self.pages.maxlen: # the oldest kept page leaves: drop its image - self.images.pop(self.pages[0]["img"], None) - words = len(text.split()) - self.seq += 1 - self.pages_done += 1 - self.words += words - self.done_times.append(now) - self.pages.append({"seq": self.seq, "img": key, "text": text[:700], "words": words, - "n": int(tail) + 1 if tail.isdigit() else None}) - - def finish(self): - with self.lock: - self.finished = time.time() - - def feed(self, since: int) -> dict: - now = time.time() - with self.lock: - for row_id, (key, t) in list(self.prepared.items()): - if now - t > self.stale_s: - del self.prepared[row_id] - self.images.pop(key, None) - while self.done_times and now - self.done_times[0] > 10: - self.done_times.popleft() - end = self.finished or now - reading_s = end - self.started if self.started else 0 - rate = len(self.done_times) / 10 if reading_s >= 10 and not self.finished else 0 - phase = "Finished" if self.finished else "Reading pages" if self.pages_done else \ - "Preparing the first pages" if self.started else "Starting the model server" - return {"stats": {"model": self.model, "gpu_name": self.gpu_name, "phase": phase, - "reading": self.pages_done > 0, "finished": self.finished is not None, - "uptime_s": round(now - self.booted), "reading_s": round(reading_s), - "pages_total": self.pages_total, "pages_done": self.pages_done, - "words": self.words, "rate_pps": round(rate, 1)}, - "pages": [p for p in self.pages if p["seq"] > since][-120:]} - - -def main(): - ap = argparse.ArgumentParser(description="LightOnOCR-3 batch OCR via saturate, with a live view") - ap.add_argument("input_dataset", help="Input dataset repo id (rows with an image column)") - ap.add_argument("output_dataset", help="Output dataset repo id (created private if missing)") - ap.add_argument("--model", default=SERVING["models"][0], choices=SERVING["models"]) - ap.add_argument("--mode", default="plain", choices=["plain", "grounding"], - help="plain = markdown; grounding = labelled layout blocks with 0-1000 boxes") - ap.add_argument("--image-column", default="image") - ap.add_argument("--config", default=None, help="Dataset config name") - ap.add_argument("--split", default="train") - ap.add_argument("--id-column", default=None, - help="Column to use as row id (default: split-index ids)") - ap.add_argument("--max-samples", "--limit", dest="limit", type=int, default=None, - help="Process only the first N rows (smoke test)") - ap.add_argument("--max-tokens", type=int, default=SERVING["max_tokens"], - help="Output cap per page (default 4096, the model card's)") - ap.add_argument("--temperature", type=float, default=SERVING["temperature"]) - ap.add_argument("--top-p", type=float, default=SERVING["top_p"], - help="Default 0.9, the model card's; LightOn's client uses 1.0") - ap.add_argument("--longest-edge", type=int, default=SERVING["longest_edge"], - help="Downscale pages to at most this many pixels on the longest edge") - ap.add_argument("--no-fix-dollars", action="store_true", - help="Keep the model's text in `markdown` without repairing escaped dollars") - ap.add_argument("--repair-max-tokens", type=int, default=0, - help="Re-send pages that hit --max-tokens once, with this cap and " - "temperature 0.1, into repair/ (default 0: off; 8192 suggested)") - ap.add_argument("--window", default="auto", - help="Pages in flight: 'auto' (saturate adapts it) or a fixed number") - ap.add_argument("--prepare-workers", type=int, default=None, - help="Threads that decode, resize and encode pages (default: CPU_CORES)") - ap.add_argument("--serve-args", default="", - help="Extra `vllm serve` flags, one quoted string, e.g. " - "\"--max-num-batched-tokens 16384\"") - ap.add_argument("--retry-errors", action="store_true", - help="Re-admit rows whose only record is an error row") - ap.add_argument("--live-port", type=int, default=None, - help="Serve the live view on this port (on Jobs, also pass --expose-public " - "with the same port)") - args = ap.parse_args() - - user_serve_args = shlex.split(args.serve_args) - if args.longest_edge < 1: - ap.error("--longest-edge must be at least 1") - try: # --serve-args may set its own --max-model-len; vLLM uses the last one given - context = int(flag_value(user_serve_args, "--max-model-len") or SERVING["context"]) - except ValueError: - ap.error("--max-model-len in --serve-args must be a whole number of tokens") - room = context - max_image_tokens(args.longest_edge) - 64 - for flag, value in (("--max-tokens", args.max_tokens), ("--repair-max-tokens", args.repair_max_tokens)): - if value > room: - ap.error(f"{flag} {value} can overflow the {context}-token context with a " - f"{args.longest_edge} px page; use at most {room}") - if args.max_tokens < 1: - ap.error("--max-tokens must be at least 1") - if args.repair_max_tokens and args.repair_max_tokens <= args.max_tokens: - ap.error("--repair-max-tokens must be larger than --max-tokens") - if args.window != "auto" and not (args.window.isdigit() and int(args.window) >= 1): - ap.error("--window must be 'auto' or a number of at least 1") - - import pyarrow as pa - from saturate import Auto, Engine, Fixed, dataset_rows, pump - - if args.id_column is None: - ids = "index" - elif args.id_column in ("index", "content"): - # saturate reads these two names as id strategies, so a column with one of them - # needs a callable. It returns the raw value, so saturate still refuses a null id. - def ids(example): - return example[args.id_column] - else: - ids = args.id_column - - rows = dataset_rows( - args.input_dataset, config=args.config, split=args.split, - columns=[args.image_column], ids=ids, limit=args.limit, - ) - - # Declared, so a part holding only error rows has the same columns as the rest - # (datasets.load_dataset reads every part with one schema). - schema = pa.schema([ - ("id", pa.string()), ("error", pa.string()), ("markdown", pa.string()), ("raw", pa.string()), - ("finish_reason", pa.string()), ("layout_blocks", pa.string()), ("model", pa.string()), - ("prompt_tokens", pa.int64()), ("completion_tokens", pa.int64()), - ]) # fmt: skip - - # Pages that hit --max-tokens, kept on local disk for the repair pass: those truncated - # in this run (stashed in parse) and those saved as truncated by an earlier, interrupted - # run (stashed as the stream passes them; the main pass skips them). - repair_dir = tempfile.mkdtemp(prefix="lighton-ocr3-repair-") if args.repair_max_tokens else None - earlier = saved_truncations(args.output_dataset) if repair_dir else set() - truncated = [] - - def stash(row_id, image): - path = os.path.join(repair_dir, hashlib.sha1(row_id.encode()).hexdigest() + ".png") - with open(path, "wb") as handle: - handle.write(page_png(image, args.longest_edge)) - truncated.append((row_id, path)) - - live = None - if args.live_port: - live = LiveView(args.live_port, args.model, - count_pages(args.input_dataset, args.config, args.split, args.limit)) - - def to_request(row): - image = fitted_page(row[args.image_column], args.longest_edge) - if live: - live.add_thumbnail(row["__id"], image) - return chat_request(args.model, png_bytes(image), args.mode, args.max_tokens, args.temperature, args.top_p) - - def make_parse(stash_truncated: bool): - def parse(row, body): - choice = body["choices"][0] - raw = (choice["message"].get("content") or "").strip() - markdown, blocks = postprocess(raw, args.mode, fix_dollars=not args.no_fix_dollars) - usage = body.get("usage") or {} - if stash_truncated and choice.get("finish_reason") == "length": - stash(row["__id"], row[args.image_column]) - if live and "__id" in row: # repair rows carry no id: the live view shows the main pass - live.add_page(row["__id"], markdown) - return { - "markdown": markdown, - "raw": raw, - "finish_reason": choice.get("finish_reason"), - "layout_blocks": blocks, - "model": args.model, - "prompt_tokens": usage.get("prompt_tokens"), - "completion_tokens": usage.get("completion_tokens"), - } - return parse - - def with_ids(source): - # Keep each row's id on the row, so parse can name the page it stashes for repair. - for row_id, row in source: - if row_id in earlier: - stash(row_id, row[args.image_column]) - yield row_id, {**row, "__id": row_id} - - cap = window_cap() - if args.window == "auto": - window = Auto(initial=min(64, cap), max_limit=cap) - print(f"window: auto, at most {cap} pages in flight (host memory)", file=sys.stderr) - else: - window = Fixed(int(args.window)) - if int(args.window) > cap: - print(f"warning: --window {args.window} is above the {cap} pages this machine's " - "memory allows; the Job may run out of memory", file=sys.stderr) - cores = max(1, int(float(os.environ.get("CPU_CORES") or "4"))) - workers = args.prepare_workers if args.prepare_workers is not None else cores - extra = [ - "--max-model-len", str(SERVING["context"]), - *SERVING["serve_args"], - *user_serve_args, - ] - # Several API server processes share the image decoding and preprocessing, which one - # process cannot keep up with on a fast GPU. Only where there are cores to spare. - if cores >= SERVING["api_servers_min_cores"] and flag_value(extra, "--api-server-count") is None: - extra += ["--api-server-count", str(SERVING["api_servers"])] - print(f"server: --api-server-count {SERVING['api_servers']} ({cores} CPU cores)", file=sys.stderr) - - output = f"hf://datasets/{args.output_dataset}/data" - with Engine(args.model, engine="vllm", extra_args=extra) as endpoint: - stats = pump(with_ids(rows), to_request, make_parse(bool(repair_dir)), - endpoint, output, window=window, prepare_workers=workers, - retry_errors=args.retry_errors, schema=schema) - print("LIGHTON_OCR3_SATURATE " + stats.to_json(), flush=True) - if live: - live.finish() - - if repair_dir and truncated: - print(f"repair: re-sending {len(truncated)} pages that hit --max-tokens " - f"with a cap of {args.repair_max_tokens}", file=sys.stderr, flush=True) - - def repair_rows(): - for row_id, path in truncated: - with open(path, "rb") as handle: - yield row_id, {"png": handle.read()} - - def repair_request(row): - return chat_request(args.model, row["png"], args.mode, args.repair_max_tokens, - SERVING["repair_temperature"], args.top_p) - - repair_stats = pump(repair_rows(), repair_request, make_parse(False), endpoint, - f"hf://datasets/{args.output_dataset}/repair", window=window, - retry_errors=args.retry_errors, schema=schema) - print("LIGHTON_OCR3_SATURATE_REPAIR " + repair_stats.to_json(), flush=True) - - print(f"https://huggingface.co/datasets/{args.output_dataset} " - f"({stats.rows_processed} ok, {stats.rows_failed} error rows, " - f"{len(truncated) if repair_dir else 'n/a'} truncated pages re-sent to repair/)", file=sys.stderr) - if live: - time.sleep(20) # the Job (and this page) ends with the script: let open tabs fetch the final numbers - - -if __name__ == "__main__": - main() diff --git a/lighton-ocr3-saturate.py b/lighton-ocr3-saturate.py deleted file mode 100644 index 4c6ea4520e68bfec0d7e2a7620dd8230036715e1..0000000000000000000000000000000000000000 --- a/lighton-ocr3-saturate.py +++ /dev/null @@ -1,475 +0,0 @@ -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "saturate[hf]==0.3.0", -# "pillow>=10", -# # LightOn's official client, pinned to a commit (not on PyPI). Used for its page -# # resize, grounding parser and dollar-delimiter repair so outputs match upstream. -# "lightonocr @ https://github.com/lightonai/LightOnOCR/archive/36755d461be079737860a5f03ae0c803501269e9.tar.gz", -# ] -# -# [tool.hf-jobs] -# image = "vllm/vllm-openai:v0.30.0" -# flavor = "a10g-small" -# timeout = "4h" -# secrets = ["HF_TOKEN"] -# /// -""" -Convert document images to markdown (or layout blocks) using LightOnOCR-3 via saturate. - -Same model, prompt modes, sampling and page preparation as `lighton-ocr3.py`, but the -script starts `vllm serve` in the Job and the `saturate` library sends the pages to it: -many pages in flight, resumable parquet output and durable error rows. Use this recipe -for large runs. - -Run on HF Jobs. The script starts the server itself; its [tool.hf-jobs] header declares -the image that provides `vllm`, the hardware and the HF_TOKEN secret (`hf` CLI 1.32+). -Flags on the command line override the header: - - hf jobs uv run --detach \\ - https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3-saturate.py \\ - - -Smoke test first with --max-samples 10. Layout blocks with labels and boxes: - - hf jobs uv run --detach \\ - https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3-saturate.py \\ - --mode grounding - -Output: the output repo holds `data/part-*.parquet` with rows -`{id, markdown, raw, finish_reason, layout_blocks, model, prompt_tokens, completion_tokens, -error}` keyed by the input row id (`--id-column`, or `:::<000000000>` -by default). Read it with `saturate.read_output`, which keeps one row per id (a success -over an earlier error). `datasets.load_dataset(, data_dir="data")` returns every -record, so after a --retry-errors run it also holds the old error rows: drop rows with an -`error` before you join back to the input on id. Re-running the same command skips -finished rows; --retry-errors re-admits failed ones. - -`finish_reason` = "length" marks a page that hit --max-tokens (long tables, or the model -repeating a line). --repair-max-tokens N sends those pages once more, at the end of the -run, with a cap of N tokens and temperature 0.1, and writes the results to `repair/` -(`load_dataset(, data_dir="repair")`); join on id and prefer the repair row where -its finish_reason is "stop". A restarted run also repairs the pages that an earlier, -interrupted run saved as truncated. - -Models (Apache-2.0): - lightonai/LightOnOCR-3-0.8B (default) 85.5 olmOCR-Bench, 74.6 ParseBench - lightonai/LightOnOCR-3-4B 86.3 olmOCR-Bench, 75.1 ParseBench -LightOnOCR-3-1B is not supported: it keeps the LightOnOCR-2 (Pixtral) architecture, and -LightOn reports that transformers 5.17 (the version in the vLLM 0.30.0 image) breaks it. - -Upstream settings kept: -- Serve flags: the LightOnOCR README's flags for the 0.8B and 4B (`--max-model-len 18000`, - thinking off, `--mm-processor-cache-gb 0`, `--no-enable-prefix-caching`, - `--limit-mm-per-prompt '{"image": 1}'`). vLLM 0.30.0, the version LightOn tests. -- Prompt modes: plain sends the image alone; grounding adds the text "grounding". The card - says other instructions are out of distribution. -- Sampling: the model card's vLLM example (temperature 0.2, top_p 0.9, max_tokens 4096). -- Pages: downscaled to 2048 px on the longest edge with LightOn's own resize (never - upscaled), sent as PNG, as the official client does. The PNG uses a fast compression - level; PNG is lossless, so the server decodes the same pixels. -- Escaped dollar delimiters are repaired (`\\$x\\$` -> `$x$`) as the client does; `raw` - keeps the model's text. - -Speed settings: pages are prepared in `--prepare-workers` threads (default: the CPU_CORES -that HF Jobs sets), and saturate's adaptive window sets how many pages are in flight, up to -a cap that fits the Job's memory (window_cap below). `--window N` pins it instead. The -server also gets `--max-num-batched-tokens 16384`, and 4 API server processes on flavors -with 12 or more CPU cores (see SERVING). Pass --serve-args "--api-server-count N" to choose. - -Measured speed, LightOnOCR-3-0.8B (2026-11-05, vLLM 0.30.0). 600 pages: 350 book pages from -finebooks/bhl-impact-gt and 250 pages of typed industry documents, all fitted to 2048 px. -Steady state, excluding the server start (about 4 min, also paid by lighton-ocr3.py): - - flavor pages/s $ per 1,000 pages lighton-ocr3.py (offline batches) - a10g-small 2.2 0.12 0.90 pages/s, $0.31 - l4x1 1.6 0.14 - a10g-large 2.7 0.15 - a100-large 7.2 0.10 1.27 pages/s, $0.55 - rtx-pro-6000 10.0 0.08 - -The 4B on a100-large (one API server): 2.7 pages/s, $0.26 per 1,000 pages; on these book -pages its character error rate was higher than the 0.8B's (0.10 mean, 0.023 median, one -run), so check a sample before paying for it. The header's a10g-small is a good default -for small and medium runs; for large runs add --flavor rtx-pro-6000 (or a100-large). In -every run the outputs differed from lighton-ocr3.py's no more than two runs of this recipe -differ from each other (sampling at temperature 0.2). The character error rate on the 282 -book pages with at least 20 characters of ground truth was 0.077 to 0.083 mean and 0.020 -median in every 0.8B run. - -Truncation and repair: 9 to 12 of the 600 pages stopped at max_tokens 4096 in each run, -most of them typed tables. With --repair-max-tokens 12000, 8 of 12 such pages finished: -3 in fewer than 4,096 tokens on the second try, and 5 long pages that needed 4,900 to -6,100 tokens. The other 4 hit the cap again. The pass added 22% to the run's output -tokens. With --repair-max-tokens 8192 (suggested), 5 of 9 such pages finished, the same 4 -hit the cap again, and the pass added 16%. Pages that hit the cap on both tries keep -their first output in data/. - -The SERVING dict below is the per-model tuning prior. Agents can `ast.literal_eval` it -without running the script; the script itself consumes it. -""" - -import argparse -import base64 -import hashlib -import io -import json -import os -import shlex -import sys -import tempfile - -# Serving starting values for LightOnOCR-3 (0.8B and 4B). Per-value provenance: -# - image: vLLM 0.30.0, the version LightOn's client pins and tests (0.27.1 makes the -# models loop, per the LightOnOCR README). -# - context 18000 and serve_args: the LightOnOCR README "Models" table for the 0.8B and 4B, -# plus its `--limit-mm-per-prompt '{"image": 1}'`. -# - max_tokens/temperature/top_p: the model card's vLLM example, verbatim. -# - longest_edge 2048: the card's rendering tip and the client's page size for these models. -# - patch 32: 16 px patches with a 2x2 merge, so a 2048x2048 page is at most 64x64 = 4,096 -# image tokens (used for the context check). -# - --max-num-batched-tokens 16384: speed only. vLLM 0.30 serves with 2048 on A10G, L4 and -# A100 (8192 on other GPUs of 70 GB or more), less than one page's image tokens. Measured on a100-large: -# 6.20 and 6.30 pages/s against 5.83 without it, outputs within the run-to-run noise. -# - pages_per_gib: see window_cap(). -# - api_servers 4 when CPU_CORES >= 12: speed only. With one vLLM API server, a100-large and -# rtx-pro-6000 had 128-256 pages in flight but only 36-60 running in the engine and none -# waiting: the rest queued for image preprocessing in the API process. Measured, 4 API -# servers against one: a100-large 7.29 and 7.18 against 6.20 and 6.30 pages/s, -# rtx-pro-6000 10.0 against 9.15, a10g-large 2.74 against 2.49; outputs within the -# run-to-run noise. Small flavors (a10g-small 3 cores, l4x1 8) keep one, to leave CPU -# for page preparation. -SERVING = { - "models": ["lightonai/LightOnOCR-3-0.8B", "lightonai/LightOnOCR-3-4B"], - "image": "vllm/vllm-openai:v0.30.0", - "context": 18000, - "serve_args": [ - "--default-chat-template-kwargs", '{"enable_thinking": false}', - "--limit-mm-per-prompt", '{"image": 1}', - "--mm-processor-cache-gb", "0", - "--no-enable-prefix-caching", - "--max-num-batched-tokens", "16384", - ], - "pages_per_gib": 6, - "api_servers": 4, - "api_servers_min_cores": 12, - "max_tokens": 4096, - "temperature": 0.2, - "top_p": 0.9, - "repair_temperature": 0.1, - "longest_edge": 2048, - "patch": 32, -} - - -def window_cap() -> int: - """Most pages in flight that this machine's memory allows. - - Every page in flight holds about 0.1 GiB of image data on the host (the client's copy and - the server's preprocessed image), on top of 7 to 9 GiB for the engine itself. On - a10g-small (14.9 GiB limit), 64 pages in flight reached the limit and the Job stopped - making progress; 32 peaked at 12.0 GiB, and up to 39 peaked at 13.0 and 14.8 GiB on two - runs. So the window may grow by SERVING "pages_per_gib" pages per GiB above 10 GiB: 29 on - a10g-small (which is GPU-bound from about 20 pages in flight), about 100 on l4x1, the full - 512 on a100-large. The limit is read from the container (cgroup v2), then from the MEMORY - variable that HF Jobs sets. - """ - limit_gib = None - try: - with open("/sys/fs/cgroup/memory.max") as handle: - value = handle.read().strip() - if value != "max": - limit_gib = int(value) / 2**30 - except (OSError, ValueError): - pass - if limit_gib is None and os.environ.get("MEMORY"): - try: # e.g. "16.0G" (decimal gigabytes) - limit_gib = float(os.environ["MEMORY"].upper().rstrip("GIB ")) * 1e9 / 2**30 - except ValueError: - pass - if limit_gib is None: - return 512 - return max(8, min(512, int((limit_gib - 10) * SERVING["pages_per_gib"]))) - - -def flag_value(tokens: list[str], name: str): - """Last value given for `name` in a `vllm serve` argument list (`--x v` or `--x=v`), else None.""" - value = None - for index, token in enumerate(tokens): - if token == name and index + 1 < len(tokens): - value = tokens[index + 1] - elif token.startswith(name + "="): - value = token.split("=", 1)[1] - return value - - -def saved_truncations(output_dataset: str) -> set: - """Ids whose saved result in data/ stopped at max_tokens and that have no saved repair. - - A restarted run skips rows already in data/, so without this the pages truncated - before the restart would never reach the repair pass. Reads only three columns. - """ - import fsspec - import pyarrow.parquet as pq - - def records(subdir, columns): - fs, root = fsspec.core.url_to_fs(f"hf://datasets/{output_dataset}/{subdir}") - if not fs.exists(root): - return - for path in fs.glob(f"{root}/part-*.parquet"): - with fs.open(path, "rb") as handle: - yield from pq.read_table(handle, columns=columns).to_pylist() - - finish = {} - for record in records("data", ["id", "error", "finish_reason"]): - if record["error"] is None: - finish[record["id"]] = record["finish_reason"] - repaired = {r["id"] for r in records("repair", ["id", "error"]) if r["error"] is None} - return {row_id for row_id, reason in finish.items() if reason == "length" and row_id not in repaired} - - -def max_image_tokens(longest_edge: int) -> int: - """Upper bound on the image tokens of a page fitted to longest_edge (square page).""" - side = -(-longest_edge // SERVING["patch"]) - return side * side - - -def to_pil(value): - from PIL import Image - - if isinstance(value, Image.Image): - return value - if isinstance(value, dict) and value.get("bytes"): - return Image.open(io.BytesIO(value["bytes"])) - if isinstance(value, dict) and value.get("path"): - return Image.open(value["path"]) - if isinstance(value, (bytes, bytearray)): - return Image.open(io.BytesIO(value)) - raise ValueError(f"unsupported image value: {type(value)}") - - -def page_png(value, longest_edge: int) -> bytes: - """RGB page fitted to longest_edge with LightOn's resize, as PNG bytes. - - compress_level=1 instead of Pillow's default 6: PNG is lossless at every level, so the - pixels are identical, and level 1 encodes several times faster (CPU is the limit on - small flavors). - """ - from lightonocr import fit - - image = fit(to_pil(value).convert("RGB"), longest_edge) - buffer = io.BytesIO() - image.save(buffer, format="PNG", compress_level=1) - return buffer.getvalue() - - -def chat_request(model: str, png: bytes, mode: str, max_tokens: int, temperature: float, top_p: float) -> dict: - """One page as the client sends it: the image, plus the word "grounding" in grounding mode.""" - from lightonocr import GROUNDING_PROMPT - - url = "data:image/png;base64," + base64.b64encode(png).decode() - content = [{"type": "image_url", "image_url": {"url": url}}] - if mode == "grounding": - content.append({"type": "text", "text": GROUNDING_PROMPT}) - return { - "model": model, - "messages": [{"role": "user", "content": content}], - "max_tokens": max_tokens, - "temperature": temperature, - "top_p": top_p, - "chat_template_kwargs": {"enable_thinking": False}, - } - - -def postprocess(raw: str, mode: str, fix_dollars: bool): - """Return (markdown, layout_blocks JSON or None) for one model output, as lighton-ocr3.py.""" - from lightonocr import fix_escaped_dollars, parse_blocks, to_markdown - - text = fix_escaped_dollars(raw) if fix_dollars else raw - if mode != "grounding": - return text, None - blocks = parse_blocks(text) - if not blocks: - return text, json.dumps([]) # no markers parsed: keep the text so nothing is lost - return to_markdown(blocks), json.dumps([b.to_dict() for b in blocks], ensure_ascii=False) - - -def main(): - ap = argparse.ArgumentParser(description="LightOnOCR-3 batch OCR via saturate") - ap.add_argument("input_dataset", help="Input dataset repo id (rows with an image column)") - ap.add_argument("output_dataset", help="Output dataset repo id (created private if missing)") - ap.add_argument("--model", default=SERVING["models"][0], choices=SERVING["models"]) - ap.add_argument("--mode", default="plain", choices=["plain", "grounding"], - help="plain = markdown; grounding = labelled layout blocks with 0-1000 boxes") - ap.add_argument("--image-column", default="image") - ap.add_argument("--config", default=None, help="Dataset config name") - ap.add_argument("--split", default="train") - ap.add_argument("--id-column", default=None, - help="Column to use as row id (default: split-index ids)") - ap.add_argument("--max-samples", "--limit", dest="limit", type=int, default=None, - help="Process only the first N rows (smoke test)") - ap.add_argument("--max-tokens", type=int, default=SERVING["max_tokens"], - help="Output cap per page (default 4096, the model card's)") - ap.add_argument("--temperature", type=float, default=SERVING["temperature"]) - ap.add_argument("--top-p", type=float, default=SERVING["top_p"], - help="Default 0.9, the model card's; LightOn's client uses 1.0") - ap.add_argument("--longest-edge", type=int, default=SERVING["longest_edge"], - help="Downscale pages to at most this many pixels on the longest edge") - ap.add_argument("--no-fix-dollars", action="store_true", - help="Keep the model's text in `markdown` without repairing escaped dollars") - ap.add_argument("--repair-max-tokens", type=int, default=0, - help="Re-send pages that hit --max-tokens once, with this cap and " - "temperature 0.1, into repair/ (default 0: off; 8192 suggested)") - ap.add_argument("--window", default="auto", - help="Pages in flight: 'auto' (saturate adapts it) or a fixed number") - ap.add_argument("--prepare-workers", type=int, default=None, - help="Threads that decode, resize and encode pages (default: CPU_CORES)") - ap.add_argument("--serve-args", default="", - help="Extra `vllm serve` flags, one quoted string, e.g. " - "\"--max-num-batched-tokens 16384\"") - ap.add_argument("--retry-errors", action="store_true", - help="Re-admit rows whose only record is an error row") - args = ap.parse_args() - - user_serve_args = shlex.split(args.serve_args) - if args.longest_edge < 1: - ap.error("--longest-edge must be at least 1") - try: # --serve-args may set its own --max-model-len; vLLM uses the last one given - context = int(flag_value(user_serve_args, "--max-model-len") or SERVING["context"]) - except ValueError: - ap.error("--max-model-len in --serve-args must be a whole number of tokens") - room = context - max_image_tokens(args.longest_edge) - 64 - for flag, value in (("--max-tokens", args.max_tokens), ("--repair-max-tokens", args.repair_max_tokens)): - if value > room: - ap.error(f"{flag} {value} can overflow the {context}-token context with a " - f"{args.longest_edge} px page; use at most {room}") - if args.max_tokens < 1: - ap.error("--max-tokens must be at least 1") - if args.repair_max_tokens and args.repair_max_tokens <= args.max_tokens: - ap.error("--repair-max-tokens must be larger than --max-tokens") - if args.window != "auto" and not (args.window.isdigit() and int(args.window) >= 1): - ap.error("--window must be 'auto' or a number of at least 1") - - import pyarrow as pa - from saturate import Auto, Engine, Fixed, dataset_rows, pump - - if args.id_column is None: - ids = "index" - elif args.id_column in ("index", "content"): - # saturate reads these two names as id strategies, so a column with one of them - # needs a callable. It returns the raw value, so saturate still refuses a null id. - def ids(example): - return example[args.id_column] - else: - ids = args.id_column - - rows = dataset_rows( - args.input_dataset, config=args.config, split=args.split, - columns=[args.image_column], ids=ids, limit=args.limit, - ) - - # Declared, so a part holding only error rows has the same columns as the rest - # (datasets.load_dataset reads every part with one schema). - schema = pa.schema([ - ("id", pa.string()), ("error", pa.string()), ("markdown", pa.string()), ("raw", pa.string()), - ("finish_reason", pa.string()), ("layout_blocks", pa.string()), ("model", pa.string()), - ("prompt_tokens", pa.int64()), ("completion_tokens", pa.int64()), - ]) # fmt: skip - - # Pages that hit --max-tokens, kept on local disk for the repair pass: those truncated - # in this run (stashed in parse) and those saved as truncated by an earlier, interrupted - # run (stashed as the stream passes them; the main pass skips them). - repair_dir = tempfile.mkdtemp(prefix="lighton-ocr3-repair-") if args.repair_max_tokens else None - earlier = saved_truncations(args.output_dataset) if repair_dir else set() - truncated = [] - - def stash(row_id, image): - path = os.path.join(repair_dir, hashlib.sha1(row_id.encode()).hexdigest() + ".png") - with open(path, "wb") as handle: - handle.write(page_png(image, args.longest_edge)) - truncated.append((row_id, path)) - - def to_request(row): - png = page_png(row[args.image_column], args.longest_edge) - return chat_request(args.model, png, args.mode, args.max_tokens, args.temperature, args.top_p) - - def make_parse(stash_truncated: bool): - def parse(row, body): - choice = body["choices"][0] - raw = (choice["message"].get("content") or "").strip() - markdown, blocks = postprocess(raw, args.mode, fix_dollars=not args.no_fix_dollars) - usage = body.get("usage") or {} - if stash_truncated and choice.get("finish_reason") == "length": - stash(row["__id"], row[args.image_column]) - return { - "markdown": markdown, - "raw": raw, - "finish_reason": choice.get("finish_reason"), - "layout_blocks": blocks, - "model": args.model, - "prompt_tokens": usage.get("prompt_tokens"), - "completion_tokens": usage.get("completion_tokens"), - } - return parse - - def with_ids(source): - # Keep each row's id on the row, so parse can name the page it stashes for repair. - for row_id, row in source: - if row_id in earlier: - stash(row_id, row[args.image_column]) - yield row_id, {**row, "__id": row_id} - - cap = window_cap() - if args.window == "auto": - window = Auto(initial=min(64, cap), max_limit=cap) - print(f"window: auto, at most {cap} pages in flight (host memory)", file=sys.stderr) - else: - window = Fixed(int(args.window)) - if int(args.window) > cap: - print(f"warning: --window {args.window} is above the {cap} pages this machine's " - "memory allows; the Job may run out of memory", file=sys.stderr) - cores = max(1, int(float(os.environ.get("CPU_CORES") or "4"))) - workers = args.prepare_workers if args.prepare_workers is not None else cores - extra = [ - "--max-model-len", str(SERVING["context"]), - *SERVING["serve_args"], - *user_serve_args, - ] - # Several API server processes share the image decoding and preprocessing, which one - # process cannot keep up with on a fast GPU. Only where there are cores to spare. - if cores >= SERVING["api_servers_min_cores"] and flag_value(extra, "--api-server-count") is None: - extra += ["--api-server-count", str(SERVING["api_servers"])] - print(f"server: --api-server-count {SERVING['api_servers']} ({cores} CPU cores)", file=sys.stderr) - - output = f"hf://datasets/{args.output_dataset}/data" - with Engine(args.model, engine="vllm", extra_args=extra) as endpoint: - stats = pump(with_ids(rows) if repair_dir else rows, to_request, make_parse(bool(repair_dir)), - endpoint, output, window=window, prepare_workers=workers, - retry_errors=args.retry_errors, schema=schema) - print("LIGHTON_OCR3_SATURATE " + stats.to_json(), flush=True) - - if repair_dir and truncated: - print(f"repair: re-sending {len(truncated)} pages that hit --max-tokens " - f"with a cap of {args.repair_max_tokens}", file=sys.stderr, flush=True) - - def repair_rows(): - for row_id, path in truncated: - with open(path, "rb") as handle: - yield row_id, {"png": handle.read()} - - def repair_request(row): - return chat_request(args.model, row["png"], args.mode, args.repair_max_tokens, - SERVING["repair_temperature"], args.top_p) - - repair_stats = pump(repair_rows(), repair_request, make_parse(False), endpoint, - f"hf://datasets/{args.output_dataset}/repair", window=window, - retry_errors=args.retry_errors, schema=schema) - print("LIGHTON_OCR3_SATURATE_REPAIR " + repair_stats.to_json(), flush=True) - - print(f"https://huggingface.co/datasets/{args.output_dataset} " - f"({stats.rows_processed} ok, {stats.rows_failed} error rows, " - f"{len(truncated) if repair_dir else 'n/a'} truncated pages re-sent to repair/)", file=sys.stderr) - - -if __name__ == "__main__": - main() diff --git a/lighton-ocr3.py b/lighton-ocr3.py deleted file mode 100644 index deaee0148f54d308c7f1efe6d0738a9dc8c5d8e2..0000000000000000000000000000000000000000 --- a/lighton-ocr3.py +++ /dev/null @@ -1,810 +0,0 @@ -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "datasets>=4.0.0", -# "huggingface-hub", -# "pillow", -# "toolz", -# # LightOn's official client, pinned to a commit (not on PyPI). Used for its -# # parser, page resize and dollar-delimiter repair so outputs match upstream. -# "lightonocr @ https://github.com/lightonai/LightOnOCR/archive/36755d461be079737860a5f03ae0c803501269e9.tar.gz", -# ] -# -# [tool.hf-jobs] -# image = "vllm/vllm-openai:v0.30.0" -# python = "/usr/bin/python3" -# env = { PYTHONPATH = "/usr/local/lib/python3.12/dist-packages" } -# flavor = "a10g-small" -# secrets = ["HF_TOKEN"] -# /// - -""" -Convert document images to markdown (or layout blocks) using LightOnOCR-3 with vLLM. - -LightOnOCR-3 is LightOn's third generation of end-to-end OCR models. The 4B and 0.8B -variants use the stock Qwen3.5 vision-language architecture. Besides plain -transcription, they have a grounding mode: every block of the page comes back with a -label (title, text, table, chart, image, ...) and a bounding box. Images get a short -description and charts become an HTML table of their data points. - -Models (Apache-2.0): - lightonai/LightOnOCR-3-4B (default) 86.3 olmOCR-Bench, 75.1 ParseBench - lightonai/LightOnOCR-3-0.8B 85.5 olmOCR-Bench, 74.6 ParseBench -LightOnOCR-3-1B is not supported here: it keeps the LightOnOCR-2 (Pixtral) -architecture and needs a different vLLM/transformers pin. - -Run on HF Jobs (needs `hf` CLI 1.32+; the [tool.hf-jobs] header above sets the -vllm/vllm-openai:v0.30.0 image, a10g-small flavor and HF_TOKEN secret): - - hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3.py \\ - input-dataset output-dataset --max-samples 10 - - # Layout blocks with labels and boxes, smaller model - hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3.py \\ - input-dataset output-dataset --mode grounding --model lightonai/LightOnOCR-3-0.8B - -Run on your own GPU (vLLM and torch come from the image on Jobs, so add them here): - - uv run --with vllm==0.30.0 lighton-ocr3.py input-dataset output-dataset - -For large scans with very small type, try a higher --longest-edge and --max-tokens. - -For large runs use lighton-ocr3-saturate.py: same model, prompts and sampling, served by -vLLM with many pages in flight (measured 2.4x the pages per second on a10g-small, 5.7x on -a100-large), with resumable output. - -The image is pinned to vLLM 0.30.0 because LightOn's client reports that vLLM 0.27.1 -makes the models loop and 0.30.0 is the version they test. Loosen the pin once a newer -vLLM is checked against the same outputs. - -Modes: -- plain (default): the image alone -> markdown transcription. Same as LightOnOCR-2. -- grounding: the image + the text "grounding" -> one `![label](x1,y1,x2,y2)` block per - region, coordinates normalised to 0-1000. The output column gets the block texts - joined as markdown; the --blocks-column gets the parsed blocks as JSON - ([{label, bbox, text, continues}, ...]). Grounding adds about 25% output tokens. -The card says other instructions are out of distribution, so there is no custom prompt. - -Sampling matches the model card's vLLM example: temperature 0.2, top_p 0.9, -max_tokens 4096, thinking disabled. (LightOn's client defaults to top_p 1.0 for -LightOnOCR-3; pass --top-p 1.0 to match it.) Pre- and post-processing follow the -official client (lightonocr/render.py, client.py): pages are downscaled to 2048 px on -the longest edge (the card's rendering tip; the processor does no further resizing), -and escaped dollar delimiters are repaired (`\\$x\\$` -> `$x$`) on every output. -""" - -import argparse -import io -import json -import logging -import os -import sys -import time -from datetime import datetime -from typing import Any, Dict, Union - -import torch -from datasets import load_dataset -from huggingface_hub import DatasetCard, hf_hub_download, login -from lightonocr import ( - DEFAULT_LONGEST_EDGE, - GROUNDING_PROMPT, - fit, - fix_escaped_dollars, - parse_blocks, - to_markdown, -) -from PIL import Image -from toolz import partition_all - -# Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the -# default uv-script image lacks (engine init then crashes). On the vllm/vllm-openai image it's -# a harmless no-op. -os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0") -# DeepGEMM's init asserts on a missing nvcc (non-fatal traceback); OCR doesn't need it. -os.environ.setdefault("VLLM_USE_DEEP_GEMM", "0") -from vllm import LLM, SamplingParams - -logging.basicConfig(level=logging.INFO) -logger = logging.getLogger(__name__) - -MODELS = ["lightonai/LightOnOCR-3-4B", "lightonai/LightOnOCR-3-0.8B"] -DEFAULT_MODEL = MODELS[0] - -# Sampling from the model card's vLLM example (temperature 0.2, top_p 0.9, max_tokens 4096). -DEFAULT_TEMPERATURE = 0.2 -DEFAULT_TOP_P = 0.9 -DEFAULT_MAX_TOKENS = 4096 - - -def check_cuda_availability(): - """Check if CUDA is available and exit if not.""" - if not torch.cuda.is_available(): - logger.error("CUDA is not available. This script requires a GPU.") - logger.error("Please run on a machine with a CUDA-capable GPU.") - sys.exit(1) - else: - logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}") - - -def ensure_output_columns_free(dataset, columns, overwrite=False): - """Fail fast if an output column would collide with an existing input column. - - Adding a column that already exists silently overwrites it (e.g. a ground-truth - `text`/`markdown` column) or crashes on push with a duplicate-column error only - *after* inference has run. Catch it up front. With overwrite=True, drop the clashing - column(s) here instead (logged) so the later add_column is clean. - """ - clash = [c for c in columns if c in dataset.column_names] - if not clash: - return dataset - if overwrite: - logger.warning(f"--overwrite: replacing existing column(s) {clash}") - return dataset.remove_columns(clash) - logger.error( - f"Output column(s) {clash} already exist in the input dataset " - f"(columns: {dataset.column_names})." - ) - logger.error("Choose a different --output-column, or pass --overwrite to replace them.") - sys.exit(1) - - -def to_pil_image(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image: - """Convert a dataset image cell (PIL image, bytes dict, or path) to RGB PIL.""" - if isinstance(image, Image.Image): - pil_img = image - elif isinstance(image, dict) and "bytes" in image: - pil_img = Image.open(io.BytesIO(image["bytes"])) - elif isinstance(image, str): - pil_img = Image.open(image) - else: - raise ValueError(f"Unsupported image type: {type(image)}") - return pil_img.convert("RGB") - - -def build_prompt(llm: LLM, mode: str) -> str: - """Chat-template prompt for one page, with thinking disabled. - - plain sends the image alone; grounding adds the text "grounding" after it - (client.py). The 0.8B and 4B were trained without thinking, so the template is - rendered with enable_thinking=False, as the card and client do. - """ - content = [{"type": "image"}] - if mode == "grounding": - content.append({"type": "text", "text": GROUNDING_PROMPT}) - return llm.get_tokenizer().apply_chat_template( - [{"role": "user", "content": content}], - tokenize=False, - add_generation_prompt=True, - enable_thinking=False, - ) - - -def postprocess_output(text: str, mode: str, fix_dollars: bool): - """Return (markdown, blocks_json or None) for one raw model output.""" - text = text.strip() - if fix_dollars: - text = fix_escaped_dollars(text) - if mode != "grounding": - return text, None - blocks = parse_blocks(text) - if not blocks: - # No markers parsed: keep the raw text so nothing is lost. - return text, json.dumps([]) - markdown = to_markdown(blocks) - return markdown, json.dumps([b.to_dict() for b in blocks], ensure_ascii=False) - - -def jobs_flavor() -> str: - """Return the HF Jobs hardware flavor this run is on, or "" when it cannot be told. - - HF Jobs sets ACCELERATOR to "cpu" or "gpu", not the flavor name, so the flavor is looked up - in the public Jobs hardware list: first by GPU model and count, then by the CPU_CORES and - MEMORY values that Jobs sets in the container (to tell a10g-small from a10g-large, or - cpu-basic from cpu-upgrade). Any failure (no network, older huggingface_hub) returns "". - """ - hardware = os.environ.get("ACCELERATOR") or "" - if "-" in hardware or any(character.isdigit() for character in hardware): - return hardware # already a flavor name - try: - from huggingface_hub import HfApi - - gpu_name, gpu_count = "", 0 - try: - import torch - - if torch.cuda.is_available(): - gpu_name = torch.cuda.get_device_name(0) - gpu_count = torch.cuda.device_count() - except ImportError: - # Torch-free drivers (e.g. the -server recipes): ask nvidia-smi instead. - import subprocess - - try: - listed = subprocess.run( - ["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"], - capture_output=True, text=True, timeout=10, check=True, - ).stdout - names = [line.strip() for line in listed.splitlines() if line.strip()] - if names: - gpu_name, gpu_count = names[0], len(names) - except (OSError, subprocess.SubprocessError): - pass - if gpu_count == 0 and hardware == "gpu": - return "" # a GPU run whose GPU cannot be identified: do not guess a CPU flavor - - # Whole-word match, so "L4" does not match "NVIDIA L40S" ("NVIDIA A100-SXM4-80GB" -> A100). - gpu_words = gpu_name.upper().replace("-", " ").split() - candidates = [] - for flavor in HfApi(token=False).list_jobs_hardware(): - accelerator = flavor.accelerator - if gpu_count == 0 and accelerator is None: - candidates.append(flavor) - elif ( - gpu_count > 0 - and accelerator is not None - and accelerator.model.upper() in gpu_words - and int(accelerator.quantity) == gpu_count - ): - candidates.append(flavor) - if not candidates: - return "" - - cores = float(os.environ.get("CPU_CORES") or 0) - memory_gb = float((os.environ.get("MEMORY") or "0").upper().rstrip("GIB ") or 0) - - def distance(flavor) -> float: - # Relative gap to the listed vCPUs and RAM; Jobs reports slightly different numbers. - listed_cores = float(flavor.cpu.split()[0]) - listed_memory = float(flavor.ram.split()[0]) - return abs(listed_cores - cores) / listed_cores + abs(listed_memory - memory_gb) / listed_memory - - return min(candidates, key=distance).name - except Exception: - return "" - - -def create_dataset_card( - source_dataset: str, - model: str, - mode: str, - num_samples: int, - processing_time: str, - batch_size: int, - max_model_len: int, - max_tokens: int, - temperature: float, - top_p: float, - longest_edge: int, - gpu_memory_utilization: float, - output_column: str, - blocks_column: str, - image_column: str = "image", - split: str = "train", -) -> str: - """Create a dataset card documenting the OCR process.""" - model_name = model.split("/")[-1] - - # Canonical provenance stamp (see AGENTS.md): Jobs claim gated on JOB_ID, set by HF Jobs in-container. - on_jobs = os.environ.get("JOB_ID") is not None - hw = jobs_flavor() # flavor name, e.g. "a10g-small"; "" when it cannot be told - origin = ( - "Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)" - + (f" (`{hw}`)" if hw else "") - ) if on_jobs else "Generated" - jobs_tag = "\n- hf-jobs" if on_jobs else "" - - model_arg = f" \\\n --model {model}" if model != DEFAULT_MODEL else "" - mode_arg = " \\\n --mode grounding" if mode == "grounding" else "" - blocks_line = ( - f"- `{blocks_column}`: JSON list of layout blocks " - "(`label`, `bbox` as x1,y1,x2,y2 normalised to 0-1000, `text`, `continues`)\n" - if mode == "grounding" - else "" - ) - - return f"""--- -tags: -- ocr -- document-processing -- lighton-ocr-3 -- markdown -- uv-script -- generated{jobs_tag} ---- - -# Document OCR using {model_name} - -This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using [{model_name}](https://huggingface.co/{model}) in **{mode}** mode. - -## Processing Details - -- **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) -- **Model**: [{model}](https://huggingface.co/{model}) -- **Mode**: `{mode}` -- **Number of Samples**: {num_samples:,} -- **Processing Time**: {processing_time} -- **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")} - -### Configuration - -- **Image Column**: `{image_column}` -- **Dataset Split**: `{split}` -- **Batch Size**: {batch_size} -- **Longest Image Edge**: {longest_edge}px -- **Max Model Length**: {max_model_len:,} tokens -- **Max Output Tokens**: {max_tokens:,} -- **Temperature**: {temperature} -- **Top P**: {top_p} -- **GPU Memory Utilization**: {gpu_memory_utilization:.1%} - -## Dataset Structure - -The dataset contains all original columns plus: -- `{output_column}`: The extracted text in markdown format -{blocks_line}- `inference_info`: JSON list tracking all OCR models applied to this dataset - -## Reproduction - -{origin} with the [`lighton-ocr3.py`](https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3.py) recipe from [uv-scripts](https://huggingface.co/uv-scripts). Run it yourself: - -```bash -hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3.py \\ - {source_dataset} \\ - \\ - --image-column {image_column} \\ - --batch-size {batch_size}{model_arg}{mode_arg} -``` -""" - - -def main( - input_dataset: str, - output_dataset: str, - model: str = DEFAULT_MODEL, - mode: str = "plain", - image_column: str = "image", - batch_size: int = 16, - max_model_len: int = 16384, - max_tokens: int = DEFAULT_MAX_TOKENS, - temperature: float = DEFAULT_TEMPERATURE, - top_p: float = DEFAULT_TOP_P, - longest_edge: int = DEFAULT_LONGEST_EDGE, - no_fix_dollars: bool = False, - gpu_memory_utilization: float = 0.8, - hf_token: str = None, - split: str = "train", - max_samples: int = None, - private: bool = False, - shuffle: bool = False, - seed: int = 42, - output_column: str = "markdown", - blocks_column: str = "layout_blocks", - overwrite: bool = False, - verbose: bool = False, - config: str = None, - create_pr: bool = False, -): - """Process images from HF dataset through LightOnOCR-3.""" - - check_cuda_availability() - - start_time = datetime.now() - - HF_TOKEN = hf_token or os.environ.get("HF_TOKEN") - if HF_TOKEN: - login(token=HF_TOKEN) - - logger.info(f"Using model: {model} ({mode} mode)") - - # Load dataset - logger.info(f"Loading dataset: {input_dataset}") - dataset = load_dataset(input_dataset, split=split) - - if image_column not in dataset.column_names: - raise ValueError( - f"Column '{image_column}' not found. Available: {dataset.column_names}" - ) - - # Fail fast if an output column would collide with an existing input column - output_columns = [output_column] + ([blocks_column] if mode == "grounding" else []) - dataset = ensure_output_columns_free(dataset, output_columns, overwrite=overwrite) - - if shuffle: - logger.info(f"Shuffling dataset with seed {seed}") - dataset = dataset.shuffle(seed=seed) - - if max_samples: - dataset = dataset.select(range(min(max_samples, len(dataset)))) - logger.info(f"Limited to {len(dataset)} samples") - - # Initialize vLLM - logger.info(f"Initializing vLLM with {model}") - logger.info("This may take a few minutes on first run...") - # Stock Qwen3_5ForConditionalGeneration arch, so no trust_remote_code. A 2048px page - # is at most 64x64 = 4,096 image tokens (16px patches, 2x2 merge), so 16384 leaves - # room for the card's 4096 output tokens. gdn_prefill_backend="triton" avoids the - # Qwen3.5 gated-delta-net prefill path that needs a CUDA JIT toolchain (as ovis-ocr2.py). - llm = LLM( - model=model, - max_model_len=max_model_len, - gpu_memory_utilization=gpu_memory_utilization, - limit_mm_per_prompt={"image": 1}, - gdn_prefill_backend="triton", - ) - - prompt = build_prompt(llm, mode) - sampling_params = SamplingParams( - temperature=temperature, top_p=top_p, max_tokens=max_tokens - ) - - logger.info(f"Processing {len(dataset)} images in batches of {batch_size}") - logger.info(f"Output will be written to column: {output_column}") - if mode == "grounding": - logger.info(f"Layout blocks will be written to column: {blocks_column}") - - all_markdown = [] - all_blocks = [] - total_batches = (len(dataset) + batch_size - 1) // batch_size - processed = 0 - - for batch_num, batch_indices in enumerate( - partition_all(batch_size, range(len(dataset))), 1 - ): - batch_indices = list(batch_indices) - batch_images = [dataset[i][image_column] for i in batch_indices] - - logger.info( - f"Batch {batch_num}/{total_batches} " - f"({processed}/{len(dataset)} images done)" - ) - - try: - # Downscale to the training render size (never upscale), as the client does. - vllm_inputs = [ - { - "prompt": prompt, - "multi_modal_data": {"image": fit(to_pil_image(img), longest_edge)}, - } - for img in batch_images - ] - - outputs = llm.generate(vllm_inputs, sampling_params) - - for output in outputs: - markdown, blocks = postprocess_output( - output.outputs[0].text, mode, fix_dollars=not no_fix_dollars - ) - all_markdown.append(markdown) - all_blocks.append(blocks) - - processed += len(batch_images) - - except Exception as e: - logger.error(f"Error processing batch: {e}") - all_markdown.extend(["[OCR ERROR]"] * len(batch_images)) - all_blocks.extend([json.dumps([])] * len(batch_images)) - processed += len(batch_images) - - processing_duration = datetime.now() - start_time - processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min" - - logger.info(f"Adding '{output_column}' column to dataset") - dataset = dataset.add_column(output_column, all_markdown) - if mode == "grounding": - logger.info(f"Adding '{blocks_column}' column to dataset") - dataset = dataset.add_column(blocks_column, all_blocks) - - # Inference info tracking - inference_entry = { - "model_id": model, - "model_name": model.split("/")[-1], - "mode": mode, - "column_name": output_column, - "blocks_column": blocks_column if mode == "grounding" else None, - "timestamp": datetime.now().isoformat(), - "temperature": temperature, - "top_p": top_p, - "max_tokens": max_tokens, - "longest_edge": longest_edge, - "fix_dollars": not no_fix_dollars, - } - - if "inference_info" in dataset.column_names: - logger.info("Updating existing inference_info column") - - def update_inference_info(example): - try: - existing_info = ( - json.loads(example["inference_info"]) - if example["inference_info"] - else [] - ) - except (json.JSONDecodeError, TypeError): - existing_info = [] - existing_info.append(inference_entry) - return {"inference_info": json.dumps(existing_info)} - - dataset = dataset.map(update_inference_info) - else: - logger.info("Creating new inference_info column") - inference_list = [json.dumps([inference_entry])] * len(dataset) - dataset = dataset.add_column("inference_info", inference_list) - - # Push to hub with retry and XET fallback - logger.info(f"Pushing to {output_dataset}") - max_retries = 3 - for attempt in range(1, max_retries + 1): - try: - if attempt > 1: - logger.warning("Disabling XET (fallback to HTTP upload)") - os.environ["HF_HUB_DISABLE_XET"] = "1" - commit_info = dataset.push_to_hub( - output_dataset, - private=private, - token=HF_TOKEN, - max_shard_size="500MB", - **({"config_name": config} if config else {}), - create_pr=create_pr, - commit_message=f"Add {model} OCR results ({len(dataset)} samples)" - + (f" [{config}]" if config else ""), - ) - break - except Exception as e: - logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}") - if attempt < max_retries: - delay = 30 * (2 ** (attempt - 1)) - logger.info(f"Retrying in {delay}s...") - time.sleep(delay) - else: - logger.error("All upload attempts failed. OCR results are lost.") - sys.exit(1) - - # Create and push dataset card - logger.info("Creating dataset card") - card_content = create_dataset_card( - source_dataset=input_dataset, - model=model, - mode=mode, - num_samples=len(dataset), - processing_time=processing_time_str, - batch_size=batch_size, - max_model_len=max_model_len, - max_tokens=max_tokens, - temperature=temperature, - top_p=top_p, - longest_edge=longest_edge, - gpu_memory_utilization=gpu_memory_utilization, - output_column=output_column, - blocks_column=blocks_column, - image_column=image_column, - split=split, - ) - - # With --create-pr the data went to a PR branch; the card goes to the same branch. - revision = commit_info.pr_revision if create_pr else None - card = DatasetCard(card_content) - # Keep the configs/dataset_info metadata push_to_hub just wrote, or named configs - # (--config) stop loading. - pushed = DatasetCard.load( - hf_hub_download(output_dataset, "README.md", repo_type="dataset", - revision=revision, token=HF_TOKEN) - ) - for key in ("configs", "dataset_info"): - if pushed.data.get(key) is not None: - card.data[key] = pushed.data[key] - card.push_to_hub(output_dataset, token=HF_TOKEN, revision=revision) - - logger.info("Done! LightOnOCR-3 processing complete.") - logger.info( - f"Dataset available at: https://huggingface.co/datasets/{output_dataset}" - ) - logger.info(f"Processing time: {processing_time_str}") - logger.info( - f"Processing speed: {len(dataset) / processing_duration.total_seconds():.2f} images/sec" - ) - - if verbose: - import importlib.metadata - - logger.info("--- Resolved package versions ---") - for pkg in ["vllm", "transformers", "torch", "datasets", "pyarrow", "pillow", "lightonocr"]: - try: - logger.info(f" {pkg}=={importlib.metadata.version(pkg)}") - except importlib.metadata.PackageNotFoundError: - logger.info(f" {pkg}: not installed") - logger.info("--- End versions ---") - - -if __name__ == "__main__": - if len(sys.argv) == 1: - print("=" * 70) - print("LightOnOCR-3 Document Processing") - print("=" * 70) - print("\n4B (default) or 0.8B end-to-end OCR, Qwen3.5 architecture") - print("\nModes:") - print(" plain markdown transcription (default)") - print(" grounding labelled layout blocks with 0-1000 boxes") - print("\nExamples:") - print("\n1. Basic OCR (own GPU):") - print(" uv run --with vllm==0.30.0 lighton-ocr3.py input-dataset output-dataset") - print("\n2. Layout blocks with the 0.8B model:") - print(" uv run --with vllm==0.30.0 lighton-ocr3.py docs results \\") - print(" --mode grounding --model lightonai/LightOnOCR-3-0.8B") - print("\n3. Running on HF Jobs (hf CLI 1.32+; image/flavor/secrets from the script header):") - print(" hf jobs uv run \\") - print( - " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/lighton-ocr3.py \\" - ) - print(" input-dataset output-dataset --max-samples 10") - print("\nFor full help: uv run --with vllm==0.30.0 lighton-ocr3.py --help") - sys.exit(0) - - parser = argparse.ArgumentParser( - description="Document OCR using LightOnOCR-3 (4B or 0.8B, plain or grounding mode)", - formatter_class=argparse.RawDescriptionHelpFormatter, - epilog=""" -Examples: - uv run --with vllm==0.30.0 lighton-ocr3.py my-docs analyzed-docs - uv run --with vllm==0.30.0 lighton-ocr3.py docs results --mode grounding - uv run --with vllm==0.30.0 lighton-ocr3.py docs results --model lightonai/LightOnOCR-3-0.8B - """, - ) - - parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub") - parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub") - parser.add_argument( - "--model", - default=DEFAULT_MODEL, - choices=MODELS, - help=f"Model checkpoint (default: {DEFAULT_MODEL})", - ) - parser.add_argument( - "--mode", - default="plain", - choices=["plain", "grounding"], - help="plain = markdown transcription; grounding = labelled layout blocks " - "with boxes, parsed into --blocks-column (default: plain)", - ) - parser.add_argument( - "--image-column", - default="image", - help="Column containing images (default: image)", - ) - parser.add_argument( - "--batch-size", - type=int, - default=16, - help="Batch size for processing (default: 16)", - ) - parser.add_argument( - "--max-model-len", - type=int, - default=16384, - help="Maximum model context length (default: 16384; model supports 262144). " - "A 2048px page is at most 4,096 image tokens.", - ) - parser.add_argument( - "--max-tokens", - type=int, - default=DEFAULT_MAX_TOKENS, - help=f"Maximum tokens to generate (default: {DEFAULT_MAX_TOKENS}, the card's " - "vLLM example). Raise it for very dense pages in grounding mode.", - ) - parser.add_argument( - "--temperature", - type=float, - default=DEFAULT_TEMPERATURE, - help=f"Sampling temperature (default: {DEFAULT_TEMPERATURE}, model card)", - ) - parser.add_argument( - "--top-p", - type=float, - default=DEFAULT_TOP_P, - help=f"Top-p (default: {DEFAULT_TOP_P}, model card; LightOn's client uses 1.0)", - ) - parser.add_argument( - "--longest-edge", - type=int, - default=DEFAULT_LONGEST_EDGE, - help=f"Downscale pages so the longest edge is at most this many pixels " - f"(default: {DEFAULT_LONGEST_EDGE}, the training render size)", - ) - parser.add_argument( - "--no-fix-dollars", - action="store_true", - help="Keep the raw model output instead of repairing escaped dollar " - "delimiters (the official client repairs them by default)", - ) - parser.add_argument( - "--gpu-memory-utilization", - type=float, - default=0.8, - help="GPU memory utilization (default: 0.8)", - ) - parser.add_argument("--hf-token", help="Hugging Face API token") - parser.add_argument( - "--split", default="train", help="Dataset split to use (default: train)" - ) - parser.add_argument( - "--max-samples", - type=int, - help="Maximum number of samples to process (for testing)", - ) - parser.add_argument( - "--private", action="store_true", help="Make output dataset private" - ) - parser.add_argument( - "--config", - help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)", - ) - parser.add_argument( - "--create-pr", - action="store_true", - help="Create a pull request instead of pushing directly (for parallel benchmarking)", - ) - parser.add_argument( - "--shuffle", action="store_true", help="Shuffle dataset before processing" - ) - parser.add_argument( - "--seed", - type=int, - default=42, - help="Random seed for shuffling (default: 42)", - ) - parser.add_argument( - "--output-column", - default="markdown", - help="Column name for output text (default: markdown)", - ) - parser.add_argument( - "--blocks-column", - default="layout_blocks", - help="Column name for parsed layout blocks in grounding mode (default: layout_blocks)", - ) - parser.add_argument( - "--overwrite", - action="store_true", - help="Replace the output column(s) if they already exist in the input dataset " - "(default: error out to avoid clobbering an existing column).", - ) - parser.add_argument( - "--verbose", - action="store_true", - help="Log resolved package versions after processing (useful for pinning deps)", - ) - - args = parser.parse_args() - - if args.max_tokens > args.max_model_len: - parser.error( - f"--max-tokens ({args.max_tokens}) must be <= --max-model-len ({args.max_model_len})" - ) - - main( - input_dataset=args.input_dataset, - output_dataset=args.output_dataset, - model=args.model, - mode=args.mode, - image_column=args.image_column, - batch_size=args.batch_size, - max_model_len=args.max_model_len, - max_tokens=args.max_tokens, - temperature=args.temperature, - top_p=args.top_p, - longest_edge=args.longest_edge, - no_fix_dollars=args.no_fix_dollars, - gpu_memory_utilization=args.gpu_memory_utilization, - hf_token=args.hf_token, - split=args.split, - max_samples=args.max_samples, - private=args.private, - shuffle=args.shuffle, - seed=args.seed, - output_column=args.output_column, - blocks_column=args.blocks_column, - overwrite=args.overwrite, - verbose=args.verbose, - config=args.config, - create_pr=args.create_pr, - ) diff --git a/minicpm-ocr.py b/minicpm-ocr.py deleted file mode 100644 index b378bc4a127ff1c0a569680087f9700c86710dfa..0000000000000000000000000000000000000000 --- a/minicpm-ocr.py +++ /dev/null @@ -1,644 +0,0 @@ -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "datasets>=3.1.0", -# "huggingface-hub>=1.0", -# "pillow", -# "bucketbag @ https://github.com/davanstrien/bucketbag/archive/refs/tags/v0.3.1.tar.gz", -# ] -# -# [tool.hf-jobs] -# image = "cr.hf.co/davanstrien/minicpm-ocr:1.0-vllm-5d35ce3" -# flavor = "a10g-large" -# timeout = "2h" -# secrets = ["HF_TOKEN"] -# /// - -""" -Convert document images to markdown with OpenBMB's MiniCPM-OCR 1.0 pipeline. - -MiniCPM-OCR 1.0 (1.3B, Apache-2.0) is a region reader: the official SDK finds layout regions -with PP-DocLayoutV3, crops them, sends each crop to the model with the prompt for its type -(`Text Recognition:`, `Table Recognition:`, `Formula Recognition:`, ...) and assembles the page -as Markdown (tables as HTML, formulas as LaTeX). This script runs that pipeline unchanged. - -Two ways in and out: - - # Hub dataset -> Hub dataset (adds `markdown` and `markdown_status` columns) - hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/minicpm-ocr.py \\ - input-dataset output-dataset --max-samples 20 - - # Bucket (or folder) of page images -> one .md per image in a Bucket (or folder) - hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/minicpm-ocr.py \\ - hf://buckets///pages hf://buckets///minicpm-ocr - -Bucket input is listed and downloaded in batches with bucketbag (no mount); `x/y.jp2` becomes -`x/y.md` under the output prefix. A page whose regions all read cleanly is written; a page with -failed regions is not, and is listed at the end, so re-running the same command retries it (pages -with a `.md` already are skipped). In dataset mode every row gets a `markdown_status`: `ok`, -`partial_failed` (some regions failed; the text is kept), `failed` or `error: ...` (no text). - -Runtime image (from the [tool.hf-jobs] header): cr.hf.co/davanstrien/minicpm-ocr, built from -images/minicpm-ocr/Dockerfile. It holds: -- vLLM nightly 5d35ce3. MiniCPMOcrForConditionalGeneration landed in vLLM main on 23 Oct 2026 - and is not in a release yet. Drop the custom image for a stock vllm/vllm-openai tag once a - release has the architecture. -- transformers at OpenBMB's pin (549e5b4). -- The minicpm-ocr SDK 1.0.1 in its own venv (/opt/sdk) with PaddlePaddle GPU, as OpenBMB's docs - require (SDK and inference service in separate environments), and the PP-DocLayoutV3 layout - model baked in at /opt/minicpm-ocr-assets. - -Server settings follow OpenBMB's SDK tutorial (docs/minicpmvocr_tutorial_en.md): max-model-len -40960, 32 sequences, image limit 36, `downsample_mode` 4x, thinking off, DSpark speculative -decoding with the matching draft model (`--no-dspark` for plain decoding). The SDK's bundled -config sets sampling and per-region prompts; nothing here overrides them. The SDK reads page -numbers, headers, footers, footnotes and side notes but leaves them out of the Markdown; -`--keep-labels footnote aside_text` puts those region types back. - -Model: https://huggingface.co/openbmb/MiniCPM-OCR-1.0 -SDK: https://github.com/OpenBMB/MiniCPM-OCR -Image: https://huggingface.co/containers/davanstrien/minicpm-ocr -""" - -import argparse -import contextlib -import json -import logging -import os -import shlex -import shutil -import signal -import subprocess -import sys -import tempfile -import time -import urllib.request -from datetime import datetime -from pathlib import Path - -logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") -logger = logging.getLogger(__name__) - -SCRIPT_URL = "https://huggingface.co/datasets/uv-scripts/ocr/raw/main/minicpm-ocr.py" -MODEL = "openbmb/MiniCPM-OCR-1.0" -MODEL_REVISION = "a59a4acf215e34c6d73149e9eafdb88ed2086e39" -DRAFT_MODEL = "openbmb/MiniCPM-OCR-1.0-DSpark" # must come from the same release as MODEL -DRAFT_REVISION = "31e3feaf80e0061cd6aa73db23480d2d691d6452" -SERVED_NAME = "minicpm-ocr" -PORT = 18499 -SDK_PYTHON = "/opt/sdk/bin/python" -LAYOUT_MODEL_DIR = "/opt/minicpm-ocr-assets/models/PP-DocLayoutV3_infer" -# minicpm-ocr SDK 1.0.1 markdown_assembly.ignore_labels: read by the model, left out of the Markdown -SDK_IGNORED_LABELS = ["number", "footnote", "header", "footer", "aside_text"] -IMAGE_TAG = "cr.hf.co/davanstrien/minicpm-ocr:1.0-vllm-5d35ce3" -BUCKET_SCHEME = "hf://buckets/" -IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".tif", ".tiff", ".bmp", ".webp", ".jp2"} - -# Runs inside the SDK venv: the SDK's documented Python API (docs/minicpmvocr_api_en.md), -# with the bundled config and only the input, server and layout path filled in. -SDK_RUNNER = """ -import json, sys -from importlib.resources import files -from pathlib import Path -from minicpmvocr import load_config, pipelined_run -from minicpmvocr.prompts import DEFAULT_PROMPT_MAP -args = json.loads(sys.argv[1]) -prompt = {} -if args["keep_labels"]: - # A prompt-map file replaces whole top-level sections, so write the full assembly section. - assembly = dict(DEFAULT_PROMPT_MAP["markdown_assembly"]) - assembly["ignore_labels"] = [l for l in assembly["ignore_labels"] if l not in args["keep_labels"]] - prompt_map = Path(args["run_root"]) / "prompt_map.json" - prompt_map.parent.mkdir(parents=True, exist_ok=True) - prompt_map.write_text(json.dumps({"markdown_assembly": assembly})) - prompt = {"prompt_map": str(prompt_map)} -cfg = load_config(str(files("minicpmvocr").joinpath("configs/minicpmvocr.yaml")), overrides={ - "input": {"image_dir": args["image_dir"]}, - "run": {"run_root": args["run_root"], "run_tag": args["run_tag"]}, - "engine": {"server_url": args["server_url"], "model_name": args["model_name"], "max_model_len": 40960}, - "layout": {"model_dir": args["layout_dir"], "device": "cuda:0"}, - "pipeline": {"overlap_layout": True}, - "prompt": prompt, -}) -pipelined_run(cfg) -print(json.dumps({"run_dir": cfg["_meta"]["run_dir"]})) -""" - - -def image_python() -> str | None: - """The image's own python3 (the one with vLLM and torch), looking past this script's venv.""" - own_bin = os.path.realpath(os.path.join(sys.prefix, "bin")) - path = os.pathsep.join(p for p in os.environ.get("PATH", "").split(os.pathsep) - if os.path.realpath(p) != own_bin) - return shutil.which("python3", path=path) - - -def check_runtime(): - """Fail fast, naming the fix, when not on the MiniCPM-OCR image or without a CUDA GPU.""" - py = image_python() - if not (py and shutil.which("vllm") and Path(SDK_PYTHON).exists() and Path(LAYOUT_MODEL_DIR).exists()): - logger.error("This script needs the %s image (vLLM with MiniCPM-OCR support, the " - "minicpm-ocr SDK and the layout model).", IMAGE_TAG) - logger.error("Run it with `hf jobs uv run`, which reads the image from the script header, " - "or pass --image %s.", IMAGE_TAG) - sys.exit(1) - probe = subprocess.run([py, "-c", "import torch; print(torch.cuda.is_available())"], - capture_output=True, text=True) - if probe.stdout.strip() != "True": - logger.error("CUDA is not available to the image's torch. This script needs a GPU " - "(e.g. --flavor a10g-large). %s", probe.stderr.strip()[-300:]) - sys.exit(1) - - -@contextlib.contextmanager -def vllm_server(dspark: bool): - """Run vLLM with OpenBMB's tutorial settings for the duration of the block. - - The server gets its own process group, and is terminated, then killed, then reaped, on every - exit path, including a failed or interrupted startup. - """ - from huggingface_hub import snapshot_download - - model_dir = snapshot_download(MODEL, revision=MODEL_REVISION) - cmd = [ - "vllm", "serve", model_dir, "--served-model-name", SERVED_NAME, - "--host", "127.0.0.1", "--port", str(PORT), - "--max-model-len", "40960", "--max-num-batched-tokens", "40960", "--max-num-seqs", "32", - "--limit-mm-per-prompt", '{"image":36,"video":0}', - "--mm-processor-kwargs", '{"downsample_mode":"4x"}', - "--gpu-memory-utilization", "0.85", "--trust-request-mm-kwargs", - "--default-chat-template-kwargs", '{"enable_thinking":false}', - ] - if dspark: - draft_dir = snapshot_download(DRAFT_MODEL, revision=DRAFT_REVISION) - cmd += ["--speculative-config", json.dumps({ - "method": "dspark", "model": draft_dir, "num_speculative_tokens": 15, - "enable_adaptive_verification": False})] - # This script's VIRTUAL_ENV must not leak into the image's vLLM. - env = {k: v for k, v in os.environ.items() if k != "VIRTUAL_ENV"} - logger.info("Starting vLLM: %s", shlex.join(cmd)) - proc = subprocess.Popen(cmd, env=env, start_new_session=True) - try: - deadline = time.time() + 1800 - while True: - if proc.poll() is not None: - sys.exit(f"vLLM exited during startup (code {proc.returncode})") - try: - with urllib.request.urlopen(f"http://127.0.0.1:{PORT}/v1/models", timeout=5) as r: - if SERVED_NAME in r.read().decode(): - break - except OSError: - pass - if time.time() > deadline: - sys.exit("vLLM did not become ready within 30 minutes") - time.sleep(5) - logger.info("vLLM ready") - yield - finally: - stop_process_group(proc) - - -def group_alive(pgid: int) -> bool: - try: - os.killpg(pgid, 0) - return True - except (ProcessLookupError, PermissionError): - return False - - -def stop_process_group(proc: subprocess.Popen): - """SIGTERM the whole group, wait up to 60 s for it to empty, then SIGKILL; always reap the - parent. Checks the group, not just the parent, since vLLM's workers can outlive it.""" - pgid = proc.pid # start_new_session=True: the server leads its own group - for sig, wait in ((signal.SIGTERM, 60), (signal.SIGKILL, 30)): - if not group_alive(pgid): - break - with contextlib.suppress(ProcessLookupError): - os.killpg(pgid, sig) - deadline = time.time() + wait - while group_alive(pgid) and time.time() < deadline: - with contextlib.suppress(subprocess.TimeoutExpired): - proc.wait(timeout=1) - with contextlib.suppress(subprocess.TimeoutExpired): - proc.wait(timeout=5) - - -def parse_batch(images: dict, work: Path, tag: str, keep_labels: list[str]) -> dict: - """OCR one batch of pages with the SDK. - - `images` maps a key to a PIL image, a path, or an undecoded datasets image dict. Returns - key -> (status, markdown or None). A page that cannot be read gets an `error: ...` status and - does not stop the batch; if the SDK run itself fails, every page in the batch gets one. - """ - from datasets import Image as ImageFeature - from PIL import Image, ImageOps - - decoder = ImageFeature() - image_dir = work / tag / "images" - image_dir.mkdir(parents=True) - results, ids = {}, {} - for i, (key, source) in enumerate(images.items()): - try: - if isinstance(source, dict): - # datasets Image(decode=False): {"bytes", "path"}. The datasets decoder handles - # remote paths and auth, and turns EXIF-rotated photos upright. - img = decoder.decode_example(source) - else: - img = source if isinstance(source, Image.Image) else Image.open(source) - img = ImageOps.exif_transpose(img) - img.convert("RGB").save(image_dir / f"{i:06d}.png") - ids[f"{i:06d}"] = key - except Exception as e: # one unreadable page must not lose the batch - logger.warning("Cannot read %s: %s", key, e) - results[key] = (f"error: unreadable image ({type(e).__name__})", None) - if ids: - args = {"image_dir": str(image_dir), "run_root": str(work / tag / "runs"), "run_tag": tag, - "server_url": f"http://127.0.0.1:{PORT}", "model_name": SERVED_NAME, - "layout_dir": LAYOUT_MODEL_DIR, "keep_labels": keep_labels} - run = subprocess.run([SDK_PYTHON, "-c", SDK_RUNNER, json.dumps(args)], - capture_output=True, text=True) - if run.returncode != 0: - logger.error("SDK run failed for %s (exit %d):\n%s", tag, run.returncode, run.stderr[-3000:]) - results.update({key: (f"error: SDK exit {run.returncode}", None) for key in ids.values()}) - else: - run_dir = Path(json.loads(run.stdout.strip().splitlines()[-1])["run_dir"]) - status = {} - metrics = run_dir / "per_page_metrics.jsonl" - if metrics.exists(): - for line in metrics.read_text(encoding="utf-8").splitlines(): - row = json.loads(line) - status[row["image_id"]] = row.get("status") or "unknown" - for image_id, key in ids.items(): - md = run_dir / "output" / f"{image_id}.md" - page_status = status.get(image_id, "failed" if not md.exists() else "unknown") - text = md.read_text(encoding="utf-8").strip() if md.exists() else None - results[key] = (page_status, text if page_status in ("ok", "partial_failed") else None) - shutil.rmtree(work / tag, ignore_errors=True) - return results - - -# --- Bucket / folder mode ------------------------------------------------------------------ - - -def is_bucket(location: str) -> bool: - return location.startswith(BUCKET_SCHEME) - - -def as_bucket_dir(url: str) -> tuple[str, str]: - """Split a bucket URL into (bucket root URL, directory key prefix ending in "/"). - - The prefix goes to bucketbag explicitly: it matches prefixes as strings, so `.../vol` - would also list `.../vol2/...`. - """ - parts = url[len(BUCKET_SCHEME):].strip("/").split("/", 2) - if len(parts) < 2: - raise ValueError(f"Not a bucket URL: {url} (expected hf://buckets//[/])") - prefix = parts[2] + "/" if len(parts) == 3 else "" - return BUCKET_SCHEME + "/".join(parts[:2]), prefix - - -def md_rel(rel: str) -> str: - return str(Path(rel).with_suffix(".md")) - - -def list_rels(location: str) -> list[str]: - """Relative paths of every file under a bucket prefix or folder, sorted.""" - if is_bucket(location): - from bucketbag import iter_keys - - url, prefix = as_bucket_dir(location) - return sorted(k[len(prefix):] for k in iter_keys(url, prefix=prefix)) - root = Path(location) - return sorted(str(p.relative_to(root)) for p in root.rglob("*") if p.is_file()) if root.is_dir() else [] - - -def iter_local_batches(source: str, rels: list[str], n: int): - """Yield batches of (rel, local path): from disk, or downloaded by bucketbag to scratch.""" - if not is_bucket(source): - for i in range(0, len(rels), n): - yield [(rel, Path(source) / rel) for rel in rels[i: i + n]] - return - from bucketbag import batched_files - - url, prefix = as_bucket_dir(source) - for batch in batched_files(url, keys=[prefix + rel for rel in rels], n=n, prefetch=2): - yield [(item.key[len(prefix):], item.path) for item in batch] - - -def write_outputs(dest: str, pairs: list[tuple[str, str]]): - if not pairs: - return - if is_bucket(dest): - from bucketbag import put_files - - url, prefix = as_bucket_dir(dest) - put_files([(prefix + rel, content) for rel, content in pairs], url) - return - for rel, content in pairs: - # Temp file + rename: a stopped job never leaves a partial .md that a re-run counts as done. - path = Path(dest) / rel - path.parent.mkdir(parents=True, exist_ok=True) - tmp = path.with_name(f".{path.name}.tmp") - tmp.write_text(content, encoding="utf-8") - os.replace(tmp, path) - - -def run_files(args): - inputs = [r for r in list_rels(args.input) if Path(r).suffix.lower() in IMAGE_EXTENSIONS] - owners: dict[str, list[str]] = {} - for rel in inputs: - owners.setdefault(md_rel(rel), []).append(rel) - clashes = [" + ".join(group) for group in owners.values() if len(group) > 1] - if clashes: - sys.exit("These inputs would write the same .md file; rename or move them first:\n " - + "\n ".join(clashes)) - if args.max_samples: - inputs = inputs[: args.max_samples] # the same pages on every run, so a re-run resumes them - done = {r for r in list_rels(args.output) if r.endswith(".md")} - todo = [r for r in inputs if args.overwrite or md_rel(r) not in done] - already = sum(md_rel(r) in done for r in inputs) - logger.info("%d images under %s, %d already have a .md, %d to OCR", len(inputs), args.input, - already, len(todo)) - if not todo: - return - failed = [] - with vllm_server(dspark=not args.no_dspark), tempfile.TemporaryDirectory() as work: - for b, batch in enumerate(iter_local_batches(args.input, todo, args.batch_size)): - results = parse_batch(dict(batch), Path(work), f"batch{b:06d}", args.keep_labels) - write_outputs(args.output, [(md_rel(rel), text) for rel, (status, text) in results.items() - if status == "ok"]) - failed += [f"{rel} ({status})" for rel, (status, _) in results.items() if status != "ok"] - logger.info("%d/%d images", min((b + 1) * args.batch_size, len(todo)), len(todo)) - if failed: - logger.warning("%d pages not written (re-run the same command to retry them):\n %s", - len(failed), "\n ".join(failed)) - stale = [f for f in failed if md_rel(f.rsplit(" (", 1)[0]) in done] - if args.overwrite and stale: - logger.warning("%d of them still have a .md from an earlier run, which a re-run without " - "--overwrite will skip; delete those files to retry them:\n %s", - len(stale), "\n ".join(stale)) - - -# --- Dataset mode ---------------------------------------------------------------------------- - - -def jobs_flavor() -> str: - """Return the HF Jobs hardware flavor this run is on, or "" when it cannot be told. - - HF Jobs sets ACCELERATOR to "cpu" or "gpu", not the flavor name, so the flavor is looked up - in the public Jobs hardware list: first by GPU model and count, then by the CPU_CORES and - MEMORY values that Jobs sets in the container (to tell a10g-small from a10g-large, or - cpu-basic from cpu-upgrade). Any failure (no network, older huggingface_hub) returns "". - """ - hardware = os.environ.get("ACCELERATOR") or "" - if "-" in hardware or any(character.isdigit() for character in hardware): - return hardware # already a flavor name - try: - from huggingface_hub import HfApi - - gpu_name, gpu_count = "", 0 - try: - import torch - - if torch.cuda.is_available(): - gpu_name = torch.cuda.get_device_name(0) - gpu_count = torch.cuda.device_count() - except ImportError: - # Torch-free drivers (e.g. the -server recipes): ask nvidia-smi instead. - import subprocess - - try: - listed = subprocess.run( - ["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"], - capture_output=True, text=True, timeout=10, check=True, - ).stdout - names = [line.strip() for line in listed.splitlines() if line.strip()] - if names: - gpu_name, gpu_count = names[0], len(names) - except (OSError, subprocess.SubprocessError): - pass - if gpu_count == 0 and hardware == "gpu": - return "" # a GPU run whose GPU cannot be identified: do not guess a CPU flavor - - # Whole-word match, so "L4" does not match "NVIDIA L40S" ("NVIDIA A100-SXM4-80GB" -> A100). - gpu_words = gpu_name.upper().replace("-", " ").split() - candidates = [] - for flavor in HfApi(token=False).list_jobs_hardware(): - accelerator = flavor.accelerator - if gpu_count == 0 and accelerator is None: - candidates.append(flavor) - elif ( - gpu_count > 0 - and accelerator is not None - and accelerator.model.upper() in gpu_words - and int(accelerator.quantity) == gpu_count - ): - candidates.append(flavor) - if not candidates: - return "" - - cores = float(os.environ.get("CPU_CORES") or 0) - memory_gb = float((os.environ.get("MEMORY") or "0").upper().rstrip("GIB ") or 0) - - def distance(flavor) -> float: - # Relative gap to the listed vCPUs and RAM; Jobs reports slightly different numbers. - listed_cores = float(flavor.cpu.split()[0]) - listed_memory = float(flavor.ram.split()[0]) - return abs(listed_cores - cores) / listed_cores + abs(listed_memory - memory_gb) / listed_memory - - return min(candidates, key=distance).name - except Exception: - return "" - - -def create_dataset_card(args, num_samples: int, counts: dict, processing_time: str) -> str: - # Canonical provenance stamp (see AGENTS.md): Jobs claim gated on JOB_ID, set by HF Jobs in-container. - on_jobs = os.environ.get("JOB_ID") is not None - hw = jobs_flavor() - origin = ( - "Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)" - + (f" (`{hw}`)" if hw else "") - ) if on_jobs else "Generated" - jobs_tag = "\n- hf-jobs" if on_jobs else "" - status_col = f"{args.output_column}_status" - flags = [f"--flavor {hw or 'a10g-large'}"] - for flag, value, default in (("--split", args.split, "train"), ("--image-column", args.image_column, "image"), - ("--output-column", args.output_column, "markdown"), - ("--batch-size", args.batch_size, 64)): - if value != default: - flags.append(f"{flag} {shlex.quote(str(value))}") - if args.max_samples: - flags.append(f"--max-samples {args.max_samples}") - if args.shuffle: - flags.append(f"--shuffle --seed {args.seed}") - if args.no_dspark: - flags.append("--no-dspark") - if args.keep_labels: - flags.append("--keep-labels " + " ".join(args.keep_labels)) - if args.overwrite: - flags.append("--overwrite") - command = f"hf jobs uv run {' '.join(flags[:1])} \\\n {SCRIPT_URL} \\\n {args.input} " - if flags[1:]: - command += " \\\n " + " ".join(flags[1:]) - counts_line = ", ".join(f"`{k}` {v:,}" for k, v in sorted(counts.items())) - return f"""--- -tags: -- ocr -- document-processing -- minicpm-ocr -- markdown -- uv-script -- generated{jobs_tag} ---- - -# Document OCR using MiniCPM-OCR 1.0 - -OCR of [{args.input}](https://huggingface.co/datasets/{args.input}) with OpenBMB's -[MiniCPM-OCR 1.0](https://huggingface.co/{MODEL}) pipeline: PP-DocLayoutV3 layout regions, each -region read by the model, assembled into Markdown by the official SDK. - -## Processing Details - -- **Source Dataset**: [{args.input}](https://huggingface.co/datasets/{args.input}) (split `{args.split}`, column `{args.image_column}`) -- **Model**: [{MODEL}](https://huggingface.co/{MODEL}) @ `{MODEL_REVISION[:7]}` -- **Decoding**: {"standard" if args.no_dspark else "DSpark speculative decoding"} -- **Region types left out of the Markdown**: {", ".join(f"`{l}`" for l in SDK_IGNORED_LABELS if l not in args.keep_labels) or "none"} -- **Number of Samples**: {num_samples:,} -- **Page status**: {counts_line} -- **Processing Time**: {processing_time} -- **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")} - -## Columns - -- `{args.output_column}`: the SDK's Markdown for each page (tables as HTML, formulas as LaTeX); empty when - the page failed -- `{status_col}`: `ok`, `partial_failed` (some regions failed; text kept), `failed` or `error: ...` -- `inference_info`: JSON list tracking all OCR models applied to this dataset - -## Reproduction - -{origin} with the [`minicpm-ocr.py`]({SCRIPT_URL}) recipe from [uv-scripts](https://huggingface.co/uv-scripts). Run it yourself: - -```bash -{command} -``` -""" - - -def run_dataset(args): - from datasets import load_dataset - from huggingface_hub import DatasetCard - - status_col = f"{args.output_column}_status" - reserved = {"inference_info", args.image_column} - if args.output_column in reserved or status_col in reserved: - sys.exit(f"--output-column {args.output_column!r} clashes with {sorted(reserved)}; pick another name") - - dataset = load_dataset(args.input, split=args.split) - if args.shuffle: - dataset = dataset.shuffle(seed=args.seed) - if args.max_samples: - dataset = dataset.select(range(min(args.max_samples, len(dataset)))) - # Undecoded: a corrupt image then fails inside parse_batch's per-page guard, not in the slice. - from datasets import Image as ImageFeature - - dataset = dataset.cast_column(args.image_column, ImageFeature(decode=False)) - clash = [c for c in (args.output_column, status_col) if c in dataset.column_names] - if clash and not args.overwrite: - sys.exit(f"Output column(s) {clash} already exist; choose another --output-column or pass --overwrite") - if clash: - logger.warning("--overwrite: replacing existing column(s) %s", clash) - dataset = dataset.remove_columns(clash) - logger.info("%d pages from %s", len(dataset), args.input) - - # Slice only the image column: slicing the full dataset would decode every other image - # column too, outside the per-page guard. - image_only = dataset.select_columns([args.image_column]) - start = datetime.now() - texts, statuses = [], [] - with vllm_server(dspark=not args.no_dspark), tempfile.TemporaryDirectory() as work: - for b in range(0, len(dataset), args.batch_size): - images = image_only[b: b + args.batch_size][args.image_column] - results = parse_batch(dict(enumerate(images)), Path(work), f"batch{b:08d}", args.keep_labels) - for i in range(len(images)): - status, text = results[i] - statuses.append(status) - texts.append(text or "") - logger.info("%d/%d pages", len(texts), len(dataset)) - elapsed = datetime.now() - start - - counts = {} - for s in statuses: - key = "error" if s.startswith("error") else s - counts[key] = counts.get(key, 0) + 1 - logger.info("Page status: %s", counts) - - dataset = dataset.cast_column(args.image_column, ImageFeature()) - dataset = dataset.add_column(args.output_column, texts).add_column(status_col, statuses) - entry = {"model_id": MODEL, "model_name": "MiniCPM-OCR-1.0", "column_name": args.output_column, - "timestamp": datetime.now().isoformat(), "model_revision": MODEL_REVISION, - "pipeline": "minicpm-ocr SDK 1.0.1 (PP-DocLayoutV3)", "dspark": not args.no_dspark, - "keep_labels": args.keep_labels} - if "inference_info" in dataset.column_names: - def update(example): - try: - info = json.loads(example["inference_info"]) if example["inference_info"] else [] - except (json.JSONDecodeError, TypeError): - info = [] - return {"inference_info": json.dumps(info + [entry])} - dataset = dataset.map(update) - else: - dataset = dataset.add_column("inference_info", [json.dumps([entry])] * len(dataset)) - - dataset.push_to_hub(args.output, private=args.private) - card = create_dataset_card(args, len(dataset), counts, f"{elapsed.total_seconds() / 60:.1f} min") - DatasetCard(card).push_to_hub(args.output) - logger.info("Done: https://huggingface.co/datasets/%s (%.2f pages/s including startup)", - args.output, len(dataset) / elapsed.total_seconds()) - - -def main(): - parser = argparse.ArgumentParser( - description="Document OCR with the MiniCPM-OCR 1.0 pipeline", - formatter_class=argparse.RawDescriptionHelpFormatter, - epilog="Input/output: Hub dataset IDs (dataset mode), or hf://buckets//[/] " - "URLs / folders (one .md per image).") - parser.add_argument("input", help="Hub dataset ID, or hf://buckets/... URL or folder of page images") - parser.add_argument("output", help="Hub dataset ID (dataset input), or hf://buckets/... URL or folder") - parser.add_argument("--image-column", default="image", help="Dataset mode: image column") - parser.add_argument("--output-column", default="markdown", help="Dataset mode: output column") - parser.add_argument("--split", default="train", help="Dataset mode: split") - parser.add_argument("--max-samples", type=int, help="Process only the first N pages (for testing)") - parser.add_argument("--shuffle", action="store_true", help="Dataset mode: shuffle before --max-samples") - parser.add_argument("--seed", type=int, default=42) - parser.add_argument("--batch-size", type=int, default=64, - help="Pages handed to the SDK per run (it parallelises regions inside a run)") - parser.add_argument("--no-dspark", action="store_true", help="Standard decoding, no draft model") - parser.add_argument("--keep-labels", nargs="+", default=[], choices=SDK_IGNORED_LABELS, - help="Region types to keep in the Markdown that the SDK leaves out by default") - parser.add_argument("--private", action="store_true", help="Dataset mode: private output dataset") - parser.add_argument("--overwrite", action="store_true", - help="Replace an existing output column / re-OCR images that already have a .md") - parser.add_argument("--hf-token", help="Hugging Face token (default: HF_TOKEN env var)") - args = parser.parse_args() - - if args.hf_token: - os.environ["HF_TOKEN"] = args.hf_token - if args.max_samples is not None and args.max_samples < 1: - sys.exit("--max-samples must be at least 1") - if args.batch_size < 1: - sys.exit("--batch-size must be at least 1") - # The input decides the mode: a Bucket or an existing folder means files, anything else is a - # Hub dataset ID. In file mode the output is a Bucket URL or a folder (created if new). - file_in = is_bucket(args.input) or Path(args.input).is_dir() - if not file_in and (is_bucket(args.output) or Path(args.output).is_dir()): - sys.exit("Dataset input writes a Hub dataset; for Bucket output, give a Bucket or folder as input.") - check_runtime() - if file_in: - run_files(args) - else: - run_dataset(args) - - -if __name__ == "__main__": - main() diff --git a/models.json b/models.json deleted file mode 100644 index f8d40f862c6468812fa3eb475fb693a776086ec9..0000000000000000000000000000000000000000 --- a/models.json +++ /dev/null @@ -1,1140 +0,0 @@ -{ - "_meta": { - "description": "Machine-readable catalog of the OCR recipes in this directory: script -> model, params, backend, support level, the tested Jobs launch config (the script's [tool.hf-jobs] header), and what the model's own card claims about language coverage. Human-readable language notes: LANGUAGES.md. Language evidence levels, strongest first: per-language-benchmark | count-claim | named-list | multilingual-unspecified | english-only | not-stated | not-applicable. Claims come from model cards (compiled 2026-07-15) - treat as claims, not guarantees.", - "updated": "2026-11-06", - "run_pattern": "hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/""" - - -class LiveView: - """The last pages read, served as a web page from inside the Job (`--live-port`).""" - - def __init__(self, port: int, pages_total: int, names: dict, keep: int = 300, stale_s: float = 3600): - self.pages = collections.deque(maxlen=keep) - self.images: dict[str, bytes] = {} # key -> JPEG, for in-flight and kept pages - self.in_flight: dict[str, tuple[str, float]] = {} # page path -> (image key, time loaded) - self.stale_s = stale_s # a window not back after this long was given up on - self.lock = threading.Lock() - self.seq = 0 - self.pages_total, self.pages_done, self.pages_failed, self.words = pages_total, 0, 0, 0 - self.booted = time.time() - self.started = None # first page loaded: the rate and elapsed time leave out server start-up - self.phases = [] - self.recent = collections.deque() # (time, pages) of finished windows, for the rolling rate - self.spark = collections.deque(maxlen=30) # pages per minute in 60 s buckets - self.gpu = None - self.names = names # page path -> (document, page number) - self.offered = None # (path, base64 JPEG) of the newest prepared page - self.stream = None # the page being read live, token by token - live = self - - class Handler(BaseHTTPRequestHandler): - def do_GET(self): - try: - if self.path.startswith("/stream.json"): - with live.lock: - body = json.dumps(live.stream) - self.reply(body.encode(), "application/json") - elif self.path.startswith("/feed.json"): - try: - since = int(self.path.partition("since=")[2] or 0) - except ValueError: - since = 0 - self.reply(json.dumps(live.feed(since)).encode(), "application/json") - elif self.path.startswith("/img/"): - with live.lock: - jpeg = live.images.get(self.path[len("/img/"):]) - if jpeg is None: - self.send_error(404) - else: - self.reply(jpeg, "image/jpeg", cache="max-age=86400") - else: - self.reply(LIVE_PAGE.encode(), "text/html; charset=utf-8") - except (BrokenPipeError, ConnectionResetError): - pass # the viewer closed the tab mid-reply - - def reply(self, body: bytes, ctype: str, cache: str = "no-store"): - self.send_response(200) - self.send_header("Content-Type", ctype) - self.send_header("Cache-Control", cache) - self.end_headers() - self.wfile.write(body) - - def log_message(self, *args): # keep the Job log for the OCR run - pass - - server = ThreadingHTTPServer(("0.0.0.0", port), Handler) - threading.Thread(target=server.serve_forever, daemon=True).start() - threading.Thread(target=self.tick, daemon=True).start() - # An exposed Job port is served at https://--.hf.jobs. - where = (f"https://{os.environ['JOB_ID']}--{port}.hf.jobs (needs --expose-public {port})" - if os.environ.get("JOB_ID") else f"http://localhost:{port}") - print(f"Live view: {where}", file=sys.stderr, flush=True) - - def offer(self, path: str, b64: str): - with self.lock: - self.offered = (path, b64) - - def start_streaming(self, url: str): - """Read one page at a time with streaming on, so the page can show the model's text as it is produced. - - This is one extra single-page request beside the batch (a few percent of the GPU); its - output is only shown, never written. - """ - threading.Thread(target=self._stream_loop, args=(url,), daemon=True).start() - - def _stream_loop(self, url: str): - import urllib.request - - while True: - with self.lock: - offered, self.offered = self.offered, None - key = self.in_flight.get(offered[0], ("",))[0] if offered else "" - if not offered: - time.sleep(0.5) - continue - path, b64 = offered - doc, page = self.names.get(path, ("", 0)) - raw, tokens, t0 = "", 0, time.time() - with self.lock: - self.stream = {"img": key, "doc": doc, "page": page, "text": "", "tok_s": 0, "done": False} - try: - req = urllib.request.Request(f"{url}/v1/chat/completions", - data=json.dumps(page_request([b64], stream=True)).encode(), - headers={"Content-Type": "application/json"}) - with urllib.request.urlopen(req, timeout=600) as resp: - for line in resp: - line = line.decode("utf-8", "replace").strip() - if not line.startswith("data: ") or line == "data: [DONE]": - continue - delta = (json.loads(line[6:])["choices"][0].get("delta") or {}).get("content") or "" - raw += delta - tokens += 1 - text = clean_page(raw.split("")[-1], keep_furniture=False) - with self.lock: - self.stream.update(text=text[-1500:], tok_s=round(tokens / max(0.1, time.time() - t0))) - except (OSError, ValueError, KeyError, IndexError) as e: # the live view must never affect the run - print(f"Live view stream: {type(e).__name__}: {e}", file=sys.stderr) - time.sleep(5) - with self.lock: - self.stream["done"] = True - time.sleep(3) # leave the finished page on screen for a moment - - def phase(self, name: str): - with self.lock: - self.phases.append({"name": name, "at_s": round(time.time() - self.booted)}) - - def tick(self): - """Every few seconds: GPU memory and load (so start-up visibly moves), and the sparkline.""" - last_bucket, done_then = time.time(), 0 - while True: - try: - out = subprocess.run(["nvidia-smi", "--query-gpu=utilization.gpu,memory.used,memory.total", - "--format=csv,noheader,nounits"], capture_output=True, text=True, - timeout=10, check=True).stdout.splitlines()[0] - util, used, total = (float(x) for x in out.split(",")) - gpu = {"util": round(util), "mem_used_gb": used / 1024, "mem_total_gb": total / 1024} - except (OSError, subprocess.SubprocessError, ValueError, IndexError): - gpu = None - with self.lock: - self.gpu = gpu - if self.started and time.time() - last_bucket >= 60: - self.spark.append(round((self.pages_done - done_then) * 60 / (time.time() - last_bucket), 1)) - last_bucket, done_then = time.time(), self.pages_done - time.sleep(3) - - def add_thumbnail(self, path: str, img): - thumb = img.copy() - thumb.thumbnail((600, 600)) - buf = io.BytesIO() - thumb.save(buf, format="JPEG", quality=80) - with self.lock: - if self.started is None: - self.started = time.time() - self.phases.append({"name": "Reading pages", "at_s": round(self.started - self.booted)}) - self.seq += 1 - key = f"{self.seq}.jpg" - self.images[key] = buf.getvalue() - old = self.in_flight.get(path) - if old: # prepared again for a retry: drop the earlier copy - self.images.pop(old[0], None) - self.in_flight[path] = (key, time.time()) - - def add_window(self, row: dict, status: str, texts): - now = time.time() - with self.lock: - self.pages_done += len(row["paths"]) - self.recent.append((now, len(row["paths"]))) - for i, (path, rid) in enumerate(zip(row["paths"], row["page_files"], strict=True)): - text = texts[i] if texts and i < len(texts) else "" - self.words += len(text.split()) - self.pages_failed += status != "ok" - if len(self.pages) == self.pages.maxlen: # the oldest kept page leaves: drop its image - self.images.pop(self.pages[0]["img"], None) - self.seq += 1 - key, _ = self.in_flight.pop(path, ("", now)) - self.pages.append({"seq": self.seq, "doc": row["doc_id"].rsplit("/", 1)[-1], - "page": row["first_page"] + i + 1, "file": rid, "status": status, - "text": text[:4000], "img": key}) - - def feed(self, since: int) -> dict: - now = time.time() - with self.lock: - for path, (key, t) in list(self.in_flight.items()): - if now - t > self.stale_s: # never came back: stop showing it as being read - del self.in_flight[path] - self.images.pop(key, None) - while self.recent and now - self.recent[0][0] > 300: - self.recent.popleft() - span = min(300, now - self.started) if self.started else 0 - rate = sum(n for _, n in self.recent) * 60 / span if span >= 20 else 0 - return {"stats": {"phase": self.phases[-1]["name"] if self.phases else "Starting", - "phases": self.phases, - "uptime_s": round(now - self.booted), - "reading_s": round(now - self.started) if self.started else 0, - "pages_total": self.pages_total, "pages_done": self.pages_done, - "pages_failed": self.pages_failed, "words": self.words, - "in_flight": len(self.in_flight), "rate_ppm": round(rate, 1), - "spark": list(self.spark), "gpu": self.gpu}, - "in_flight": [key for key, _ in self.in_flight.values()][-24:], - "pages": [p for p in self.pages if p["seq"] > since]} - - -def clean_page(raw_page: str, keep_furniture: bool) -> str: - """One page of model output -> plain markdown. - - Drops block tags and boxes, turns titles into `#` headings, drops page - numbers and running heads, and joins ``d blocks (e.g. verse lines). - """ - blocks: list[str] = [] - merge_next = False - matches = list(BLOCK_RE.finditer(raw_page)) - for i, m in enumerate(matches): - end = matches[i + 1].start() if i + 1 < len(matches) else len(raw_page) - body = raw_page[m.end(): end].strip() - merge_prev, merge_next = merge_next, body.endswith("") - body = body.removesuffix("").strip() - kind = m.group("type") - if not body or (kind in FURNITURE and not keep_furniture): - continue - if kind == "title" and m.group("level"): - body = "#" * int(m.group("level")) + " " + body - if merge_prev and blocks: - blocks[-1] += "\n" + body - else: - blocks.append(body) - return "\n\n".join(blocks) - - -def prepare_workers() -> int: - """Threads that decode and encode pages: enough to keep ~40 requests fed, within the Job's CPU quota. - - os.cpu_count() reports the host's cores (190 on a Jobs node), not the quota; that many - threads starve the loop that sends requests. Jobs sets CPU_CORES to the quota. - """ - cores = int(os.environ.get("CPU_CORES") or len(os.sched_getaffinity(0))) - return max(4, min(16, cores - 6)) # leave cores for SGLang's tokenizer and scheduler - - -def start_server_cmd() -> list[str]: - """Install Baidu's wheel into the image's sglang Python and return the server command.""" - # The SGLang image keeps sglang in its own venv (/opt/sglang/bin), first on PATH; - # `uv run` puts this script's venv in front, so look past it. - own_bin = os.path.realpath(os.path.join(sys.prefix, "bin")) - path = os.pathsep.join(p for p in os.environ.get("PATH", "").split(os.pathsep) - if os.path.realpath(p) != own_bin) - py = shutil.which("python3", path=path) - if not py or subprocess.run([py, "-c", "import sglang"], check=False, - capture_output=True).returncode != 0: - sys.exit("No Python with sglang found: run this on the lmsysorg/sglang image " - "(`hf jobs uv run` picks it up from the script's [tool.hf-jobs] table).") - env = {k: v for k, v in os.environ.items() if k != "VIRTUAL_ENV"} - pip = ["uv", "pip", "install", "-q", "--python", py] - subprocess.run([*pip, "--no-deps", SERVING["wheel"]], check=True, env=env) - subprocess.run([*pip, *SERVING["extra_pip"]], check=True, env=env) - os.environ.update(SERVING["env"]) # inherited by the server process - return [py, "-m", "sglang.launch_server", "--model-path", SERVING["model"], - "--served-model-name", SERVING["served_name"], *SERVING["serve_args"], - "--enable-metrics", "--host", "127.0.0.1", "--port", "8000"] - - -def main(): - ap = argparse.ArgumentParser(description="Unlimited-OCR-2 document OCR on HF Jobs") - ap.add_argument("input", help="Glob or folder of page images: hf://buckets/..., a mounted dir, ...") - ap.add_argument("output", help="Output dataset id (org/name) or fsspec URI (hf://buckets/...)") - ap.add_argument("--pages-per-request", type=int, default=16, - help="Consecutive pages per request (default 16)") - ap.add_argument("--max-pages", type=int, default=None, help="Stop after N pages (for a test run)") - ap.add_argument("--max-side", type=int, default=1280, - help="Long side (px) pages are sent at. The model resizes each page to a " - "1024 px view, so more pixels only make the requests bigger") - ap.add_argument("--keep-furniture", action="store_true", - help="Keep page numbers and running heads in page_markdown") - ap.add_argument("--retry-errors", action="store_true", help="Retry windows recorded as errors") - ap.add_argument("--live-port", type=int, default=None, - help="Serve a live view of pages as they are read on this port " - "(on Jobs, also pass --expose-public with the same port)") - args = ap.parse_args() - - import fsspec - from saturate import Auto, Engine, pump - - rows = list(list_windows(args.input, args.pages_per_request, args.max_pages)) - print(f"{len({r['doc_id'] for _, r in rows})} documents, " - f"{sum(len(r['paths']) for _, r in rows)} pages, {len(rows)} requests", file=sys.stderr) - fs = fsspec.core.url_to_fs(args.input.split("*")[0] or ".")[0] - live = None - if args.live_port: - names = {p: (r["doc_id"].rsplit("/", 1)[-1], r["first_page"] + i + 1) - for _, r in rows for i, p in enumerate(r["paths"])} - live = LiveView(args.live_port, sum(len(r["paths"]) for _, r in rows), names) - - def to_request(row): - return page_request([load_page(fs, p, args.max_side, live) for p in row["paths"]]) - - def parse(row, body): - choice = body["choices"][0] - raw = choice["message"]["content"] - raw_pages = raw.split("")[1:] - if choice.get("finish_reason") == "length": - status = "truncated" - elif len(raw_pages) != len(row["paths"]): - status = "page_mismatch" - else: - status = "ok" - usage = body.get("usage") or {} - page_markdown = [clean_page(p, args.keep_furniture) for p in raw_pages] if status == "ok" else None - if live is not None: - live.add_window(row, status, page_markdown) - return { - "doc_id": row["doc_id"], - "first_page": row["first_page"], - "page_files": row["page_files"], - "status": status, - "page_markdown": page_markdown, - "raw": raw, - "model": SERVING["model"], - "prompt_tokens": usage.get("prompt_tokens"), - "completion_tokens": usage.get("completion_tokens"), - } - - is_repo_id = re.fullmatch(r"[\w-][\w.-]*/[\w.-]*[\w-]", args.output) and not os.path.exists(args.output) - output = f"hf://datasets/{args.output}/data" if is_repo_id else args.output - - # One request is minutes of decoding: read_timeout=3600 below, and a row's retries get - # 2 x read_timeout in total (saturate's default retry budget). - if live is not None: - live.phase("Installing Baidu's SGLang build") - cmd = start_server_cmd() - if live is not None: - live.phase("Loading the model") - with Engine(SERVING["model"], engine="sglang", cmd=cmd) as endpoint: - if live is not None: - live.start_streaming("http://127.0.0.1:8000") - stats = pump(rows, to_request, parse, endpoint, output, - window=Auto(initial=32, max_limit=64), # long requests: start wide - flush_every=4, # each row is minutes of GPU time; write often - read_timeout=3600, prepare_workers=prepare_workers(), retry_errors=args.retry_errors) - print(f"{output}: {stats.rows_processed} windows written, {stats.rows_failed} errors", file=sys.stderr) - if live is not None: - live.phase("Finished") - time.sleep(60) # keep the final numbers on screen for a minute before the Job exits - print("UNLIMITED_OCR2 " + stats.to_json(), flush=True) - - -if __name__ == "__main__": - main() diff --git a/unlimited-ocr2-saturate.py b/unlimited-ocr2-saturate.py deleted file mode 100644 index ddfc01450d2687c7687c77d33b5362400aea3c91..0000000000000000000000000000000000000000 --- a/unlimited-ocr2-saturate.py +++ /dev/null @@ -1,907 +0,0 @@ -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "saturate[hf]==0.3.0", -# "pillow>=10", -# "pymupdf>=1.24", -# ] -# -# [tool.hf-jobs] -# image = "lmsysorg/sglang:v0.5.20-cu130" -# flavor = "rtx-pro-6000" -# timeout = "4h" -# secrets = ["HF_TOKEN"] -# /// -""" -OCR whole documents (book volumes, PDFs) with Baidu Unlimited-OCR-2 via saturate. - -Tuned version of `unlimited-ocr2.py`, and experimental: it adds a repair pass for -pages the model loops on, faster JPEG 2000 decoding, PDF input, Baidu's own -Markdown post-processing and speed flags. It changes more often; start with -`unlimited-ocr2.py` and use this one when you need the extras. Window ids and the -main output layout are the same, so `--repair-only` works on a minimal run too. - -Unlimited-OCR-2 reads many pages in ONE request and keeps context across page -breaks: a paragraph that runs onto the next page comes back tagged as a -continuation, not as two fragments. So the unit of work here is a document, not -a page. Input is a folder (bucket, mounted dir or local) of page images and/or -PDFs; pages are grouped into documents, each document is cut into windows of ---pages-per-request consecutive pages, and each window is one request. - -Run on HF Jobs (the [tool.hf-jobs] table above supplies image, flavor, timeout -and HF_TOKEN; flags you pass on the command line win): - - hf jobs uv run --detach \\ - https://huggingface.co/datasets/uv-scripts/ocr/raw/main/unlimited-ocr2-saturate.py \\ - "hf://buckets/biglam/britannica/source/pages/1771EncyclopediaBritannicaNLS/*.jp2" \\ - /britannica-1771-uocr2 - -Grouping pages into documents: -- Page files: the document is the parent folder plus the file name with its - trailing page number removed (`Volume 1, A-B_0007.jp2` -> `Volume 1, A-B`), - so an Internet Archive item holding several volumes splits into volumes. - Pages are ordered by that number (natural sort). -- PDFs: one document per file, pages rendered at --pdf-dpi. - -Output: `data/part-*.parquet` in the output dataset (or any fsspec URI, e.g. -hf://buckets/...), one row per window: -`{id, doc_id, first_page, page_files, num_pages, status, finish_reason, -page_markdown, markdown, raw, prompt_tokens, completion_tokens, error}`. `page_markdown` is aligned with -`page_files`; `raw` keeps the model's grounded output (block types + boxes). -`markdown` is the whole window through Baidu's own post-processor (vendored -below at a pinned commit): cross-page paragraph/table chains merged, figures as -image links, page furniture kept. `page_markdown` is a lighter per-page cleanup -that stays aligned with page files (page numbers and running heads dropped -unless --keep-furniture). A window whose output is truncated or has the wrong -number of blocks keeps its text with `status` = truncated / page_mismatch -(greedy decoding repeats it on retry); `page_markdown` is set only when status = ok. -Re-running the same command resumes; --retry-errors re-admits failed windows. - -Repair pass (on by default; --no-repair skips it, --repair-only runs just it): -about 2% of 1771 Britannica pages, mostly dense mathematics, sent the model -into a loop inside a window; the forced page break then shifted the next -page's text by one. After the main pass, looping pages, their empty neighbours -and every page of a failed window are re-OCR'd one at a time in gundam mode -into `repairs/` (one row per page: `{page_file, page, doc_id, window, status, -markdown, raw}`). That fixed 28 of 33 flagged pages in testing; the rest keep -their text with status = degenerate. To assemble final per-page text, take the -`repairs/` row for a page when it exists, else `page_markdown` from its window. - -Why this is a saturate recipe, not an offline one: the multi-page engine lives -in Baidu's own SGLang build (no vLLM support for v2). The script installs that -wheel into the image's Python, boots `sglang.launch_server`, and lets saturate -drive it (adaptive concurrency from SGLang's /metrics, resumable parquet output). - -Model: baidu/Unlimited-OCR-2 (3.3B, MIT). https://huggingface.co/baidu/Unlimited-OCR-2 -""" - -import argparse -import base64 -import io -import json -import os -import pickle -import re -import shutil -import subprocess -import sys -import threading -import types -import zlib - -# Per-value provenance: -# - image lmsysorg/sglang:v0.5.20-cu130: the SGLang release whose pins match -# Baidu's wheel exactly (torch 2.13.0, transformers 5.12.1, flashinfer 0.6.18 -# cu13). The wheel is installed --no-deps on top. Move the pin only together -# with the wheel; drop both once upstream SGLang ships the architecture. -# - env + serve_args: the model card's launch command, verbatim (tuned for an -# 80 GB A800; validated 2026-10-27 on a100-large and rtx-pro-6000, boot ~3.5 min). -# - flavor rtx-pro-6000: on the same 512 1771 Britannica pages it finished 32/32 -# windows in 805 s (1,571 tok/s end to end) vs a100-large 1,267 s (866 tok/s): -# ~30% cheaper per page. The n-gram guard makes decode scheduler-CPU-bound, so -# CPU matters as much as the GPU. 24 GB cards (a10g, l4) thrash the KV cache on -# 16-page windows (~31k tokens each); use >= 48 GB. -# - tokens_per_page 8000, ngram 35, window 1024 multi / 128 single, page guard -# 20000, temperature 0: the card's client example. -# - crop_mode False (base, one global view per page): the card's multi-page -# default (infer_multi). On a 32-page 1861 scan gundam (crop) mode read the -# same text with 6.7x the image tokens (58k vs 8.7k). -# - wheel: the URL names a model-repo commit, because Baidu replaces the wheel on -# main (dev10 was removed 2026-10-29). -SERVING = { - "model": "baidu/Unlimited-OCR-2", - "served_name": "Unlimited-OCR-2", - "image": "lmsysorg/sglang:v0.5.20-cu130", - "wheel": "https://huggingface.co/baidu/Unlimited-OCR-2/resolve/91da6546d8ed91e02525f59c012a1d243266d7dd/wheel/" - "sglang-0.5.20.dev10%2Bg8d62f5fb9c-py3-none-any.whl", - "extra_pip": ["fastokens==0.3.2"], - "env": { - "SGLANG_UOCR_EANABLE_DOC_LIMIT": "1", # (sic) upstream spelling - "SGLANG_UOCR_DOC_GUNDAM_PAGE_WINDOW": "10", - "SGLANG_UOCR_DOC_BASE_PAGE_WINDOW": "10", - "SGLANG_UOCR_MAX_PAGE_TOKENS": "20000", - "SGLANG_OPT_UOCR_SAM_REL_POS_BIAS_MB": "64", - "SGLANG_UOCR_SHM_WRAP_MODEL_DATA": "1", - "SGLANG_UOCR_SHM_WRAP_MIN_MB": "1", - "SGLANG_VLM_CACHE_SIZE_MB": "0", - "PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True", - }, - "serve_args": [ - "--chat-template", "unlimited-ocr", - "--tokenizer-backend", "fastokens", "--tokenizer-worker-num", "8", - "--mem-fraction-static", "0.7", - "--max-running-requests", "64", - "--max-prefill-tokens", "2048", - "--enable-custom-logit-processor", "--enable-streaming-session", - "--allow-auto-truncate", "--disable-radix-cache", - "--mm-preprocess-cache-size-mb", "0", - "--cuda-graph-backend-decode", "full", "--cuda-graph-max-bs-decode", "64", - "--cuda-graph-backend-prefill", "full", - "--cuda-graph-max-bs-prefill", "16384", - "--cuda-graph-bs-prefill", "1024", "2048", - "--cuda-graph-config", '{"prefill": {"backend": "full", "full_prefill_max_req": 64}}', - ], - "tokens_per_page": 8000, - "temperature": 0.0, - "crop_mode": False, - "ngram_size": 35, - "page_token_id": 128827, # , = sparse_attention_config.page_token_id - "eos_token_id": 1, - "max_page_tokens": 20000, -} - -PDF_LOCK = threading.Lock() -PAGE_EXTS = (".jp2", ".jpg", ".jpeg", ".png", ".tif", ".tiff", ".webp") -FURNITURE = {"page_number", "header", "footer"} -PAGE_BLOCK_RE = re.compile(r"(?P[a-z_]+)(?:\d)>)?\[[\d, ]*\]") - - -def ngram_processor() -> str: - """The card's DeepseekOCRNoRepeatNGramLogitProcessor.to_str(), built without sglang. - - to_str() is json({"callable": dill.dumps(cls).hex()}) and dill pickles an - importable class by reference, so the payload is just a pickled global - (module + name). Building it here keeps sglang/torch/dill out of the driver. - """ - mod, name = "sglang.srt.sampling.custom_logit_processor", "DeepseekOCRNoRepeatNGramLogitProcessor" - saved = {k: sys.modules.get(k) for k in ("sglang", "sglang.srt", "sglang.srt.sampling", mod)} - try: - parts = mod.split(".") - for i in range(len(parts)): - sys.modules[".".join(parts[: i + 1])] = types.ModuleType(parts[i]) - cls = type(name, (), {"__module__": mod}) - setattr(sys.modules[mod], name, cls) - return json.dumps({"callable": pickle.dumps(cls).hex()}) - finally: - for k, v in saved.items(): - if v is None: - sys.modules.pop(k, None) - else: - sys.modules[k] = v - - -def natural_key(s: str): - return [int(t) if t.isdigit() else t for t in re.split(r"(\d+)", s)] - - -def doc_key(rel_path: str) -> str: - """`item/Volume 1, A-B_0007.jp2` -> `item/Volume 1, A-B`; a PDF is its own doc.""" - if rel_path.lower().endswith(".pdf"): - return rel_path - stem = rel_path.rsplit(".", 1)[0] - doc = re.sub(r"[_\-. ]?\d+$", "", stem) - return doc if doc and not doc.endswith("/") else (doc or ".") - - -def list_windows(pattern: str, pages_per_request: int, limit_docs, max_pages, pdf_dpi): - """List page files, group into documents, cut each into windows -> (id, row).""" - import fsspec - from saturate import bucket_rows - - if not re.search(r"[*?\[]", pattern) and not pattern.lower().endswith(".pdf"): - pattern = pattern.rstrip("/") + "/**" - files = [(rid, row["path"]) for rid, row in bucket_rows(pattern, read=False) - if rid.lower().endswith(PAGE_EXTS + (".pdf",))] - if not files: - sys.exit(f"no page images or PDFs matched {pattern!r}") - - docs: dict[str, list[tuple[str, str]]] = {} - for rid, path in files: - docs.setdefault(doc_key(rid), []).append((rid, path)) - doc_ids = sorted(docs, key=natural_key)[:limit_docs] - - fs = fsspec.core.url_to_fs(pattern)[0] - n_pages = 0 - for d in doc_ids: - pages = sorted(docs[d], key=lambda p: natural_key(p[0])) - if d.lower().endswith(".pdf"): # explode a PDF into (page-index) entries - import fitz - - with fs.open(pages[0][1], "rb") as f: - count = fitz.open(stream=f.read(), filetype="pdf").page_count - pages = [(f"{d}#{i + 1}", f"{pages[0][1]}#{i}") for i in range(count)] - for start in range(0, len(pages), pages_per_request): - if max_pages is not None and n_pages >= max_pages: - return - window = pages[start: start + pages_per_request] - if max_pages is not None: - window = window[: max_pages - n_pages] - n_pages += len(window) - # The id encodes the page range: a --max-pages-truncated window must - # not mark the full window done on a later resume. - yield f"{d}@{start:06d}-{start + len(window):06d}", { - "doc_id": d, "first_page": start, - "page_files": [rid for rid, _ in window], - "paths": [p for _, p in window], - } - - -def load_page(fs, path: str, max_side: int, pdf_dpi: int) -> str: - """Read one page (image file or `file.pdf#i`), downscale, return base64 JPEG.""" - from PIL import Image - - if "#" in path and path.split("#")[0].lower().endswith(".pdf"): - import fitz - - pdf_path, idx = path.rsplit("#", 1) - with fs.open(pdf_path, "rb") as f: - data = f.read() - with PDF_LOCK: # PyMuPDF is not thread-safe; pages are prepared in threads - png = fitz.open(stream=data, filetype="pdf")[int(idx)].get_pixmap(dpi=pdf_dpi).tobytes("png") - img = Image.open(io.BytesIO(png)) - else: - with fs.open(path, "rb") as f: - data = f.read() - img = Image.open(io.BytesIO(data)) - if img.format == "JPEG2000": - # Decode straight at a lower wavelet level when the page stays >= max_side: - # same pixels the model would see after downscaling, ~2.5x less CPU - # (measured: 406 -> 160 ms/page at 8 threads on 1771 Britannica scans). - # Some codestreams fail at a reduced level ("broken data stream"), so step - # back towards a full decode until one works. - reduce = 0 - while max(img.size) >> (reduce + 1) >= max_side: - reduce += 1 - while True: - try: - img = Image.open(io.BytesIO(data)) - img.reduce = reduce - img.load() - break - except OSError: - if reduce == 0: - raise - reduce -= 1 - else: - img.load() - img = img.convert("RGB") - img.thumbnail((max_side, max_side), Image.LANCZOS) - buf = io.BytesIO() - img.save(buf, format="JPEG", quality=90) - return base64.b64encode(buf.getvalue()).decode() - - -def clean_page(raw_page: str, keep_furniture: bool) -> tuple[str, bool]: - """Grounded page -> (markdown, continues_previous_page). - - Tags and boxes dropped, titles -> #, furniture dropped. A block preceded by - belongs to the block before it (joined with a newline, e.g. verse - lines); an `append_*` first block continues the previous page's last block. - """ - blocks: list[str] = [] - continues = False - merge_next = False - matches = list(PAGE_BLOCK_RE.finditer(raw_page)) - for i, m in enumerate(matches): - body = raw_page[m.end(): matches[i + 1].start() if i + 1 < len(matches) else len(raw_page)].strip() - merge_prev, merge_next = merge_next, body.endswith("") - body = body.removesuffix("").strip() - kind = m.group("type") - if not body or (kind in FURNITURE and not keep_furniture): - continue - if kind == "title" and m.group("level"): - body = "#" * int(m.group("level")) + " " + body - if not blocks and kind.startswith("append_"): - continues = True - if merge_prev and blocks: - blocks[-1] += "\n" + body - else: - blocks.append(body) - return "\n\n".join(blocks), continues - - -def degenerate(raw_page: str) -> bool: - """A looping page: far longer than any real page, or highly repetitive. - - Thresholds from 1771 Britannica (median raw page ~6.5k chars, densest real - page ~10k; loops ran 14k-109k chars at zlib ratio 0.005-0.19, real text ~0.35). - """ - if len(raw_page) > 15000: - return True - return len(raw_page) > 2000 and len(zlib.compress(raw_page.encode())) / len(raw_page) < 0.2 - - -def repair_rows(windows, output: str): - """Pages to re-OCR one at a time, from the windows and what the main pass wrote. - - A window with no usable record (error row, or truncated / page_mismatch) has all - its pages repaired. In an ok window, a looping page is repaired together with - an empty neighbour: the loop's forced page break shifts the next page's text. - """ - from saturate import read_output - - done = dict(read_output(output)) - for wid, row in windows: - n = len(row["paths"]) - rec = done.get(wid) - raw_pages = (rec or {}).get("raw", "").split("")[1:] - texts = (rec or {}).get("page_markdown") or [] - # Anything we cannot line up page-for-page is repaired whole (also covers - # records written before the status column existed). - if rec is None or rec.get("status", "ok") != "ok" or len(raw_pages) != n or len(texts) != n: - bad = set(range(n)) - else: - bad = {i for i, p in enumerate(raw_pages) if degenerate(p)} - for i in list(bad): - bad |= {j for j in (i - 1, i + 1) if 0 <= j < n and not (texts[j] or "").strip()} - for i in sorted(bad): - yield row["page_files"][i], { - "doc_id": row["doc_id"], "page": row["first_page"] + i, "window": wid, - "page_file": row["page_files"][i], "paths": [row["paths"][i]], - # alone and tiled: fixed 8 of 10 looping 1771 pages in testing - "crop": True, "max_side": 2048, - } - - -def find_server_python(candidates) -> str: - """The image's Python (the one that has sglang), not this script's uv venv. - - The SGLang image keeps sglang in its own venv (/opt/sglang/bin), first on PATH; - `uv run` puts this script's venv in front, so search PATH without it. - """ - own_bin = os.path.join(sys.prefix, "bin") - path = os.pathsep.join(p for p in os.environ.get("PATH", "").split(os.pathsep) - if os.path.realpath(p) != os.path.realpath(own_bin)) - on_path = [shutil.which(name, path=path) for name in ("python3", "python")] - for py in [p for p in on_path if p] + list(candidates): - if os.path.exists(py) and subprocess.run( - [py, "-c", "import sglang"], check=False, capture_output=True - ).returncode == 0: - return py - sys.exit( - "No Python with sglang found. Run on the SGLang image, e.g.\n" - f" hf jobs uv run --image {SERVING['image']} --flavor a100-large -s HF_TOKEN ...\n" - "(the script's [tool.hf-jobs] table sets this when launched with `hf jobs uv run`)." - ) - - -def main(): - ap = argparse.ArgumentParser(description="Unlimited-OCR-2 document OCR via saturate") - ap.add_argument("input", help="Folder/glob of page images or PDFs: hf://buckets/..., a mounted dir, ...") - ap.add_argument("output", help="Output dataset id (org/name) or fsspec URI (hf://buckets/...)") - ap.add_argument("--pages-per-request", type=int, default=16, - help="Window size: consecutive pages sent in one request (default 16). " - "Each request decodes as one serial stream, so smaller windows finish " - "sooner and leave throughput to concurrency; the server itself works " - "in 10-page chunks with KV reuse across them.") - ap.add_argument("--limit-docs", type=int, default=None, help="Only the first N documents") - ap.add_argument("--max-pages", type=int, default=None, help="Stop after N pages in total (smoke tests)") - ap.add_argument("--crop-mode", action="store_true", - help="Gundam mode: tile each page (more image tokens; for small print)") - ap.add_argument("--max-side", type=int, default=None, - help="Long side (px) pages are sent at. Default 1280 in base mode (the model " - "resizes every page to one 1024 px view, so more pixels are discarded) and " - "2048 with --crop-mode (tiles use the detail)") - ap.add_argument("--pdf-dpi", type=int, default=150) - ap.add_argument("--keep-furniture", action="store_true", - help="Keep page numbers, running heads and footers in `markdown`") - ap.add_argument("--ngram-window", type=int, default=1024, - help="Look-back (tokens) of the card's no-repeat n-gram guard for multi-page " - "windows (single pages use 128). It runs in Python on every decode step " - "for every request, so it bounds throughput; 0 disables the guard " - "(and its per-page length cap)") - ap.add_argument("--retry-errors", action="store_true", help="Re-admit windows recorded as errors") - ap.add_argument("--no-repair", action="store_true", - help="Skip the repair pass (re-OCR of looping pages one at a time, in gundam mode)") - ap.add_argument("--repair-only", action="store_true", - help="Run only the repair pass over an existing output (same input/output args)") - ap.add_argument("--prepare-workers", type=int, default=8, - help="Threads decoding/encoding pages ahead of the engine") - ap.add_argument("--dp-size", type=int, default=1, - help="SGLang data-parallel replicas (one per GPU on multi-GPU flavors). The n-gram " - "guard makes each scheduler CPU-bound, so replicas multiply throughput") - ap.add_argument("--endpoint", default=None, - help="Use a running server (e.g. a Jobs --expose URL + /v1) instead of booting one") - ap.add_argument("--server-python", nargs="+", default=["/opt/sglang/bin/python3", "/usr/bin/python3"], - help="Fallback Pythons to try after PATH (the one with sglang wins)") - args = ap.parse_args() - if args.max_side is None: - # Payload matters as much as pixels: 32 concurrent 16-page bodies at 1600 px - # (~14 MB of base64 each) stalled SGLang's HTTP front end past saturate's fixed - # 30 s connect/write timeouts. - args.max_side = 2048 if args.crop_mode else 1280 - - import fsspec - from saturate import Auto, Engine, pump - - rows = list(list_windows(args.input, args.pages_per_request, args.limit_docs, - args.max_pages, args.pdf_dpi)) - n_pages = sum(len(r["paths"]) for _, r in rows) - print(f"{len({r['doc_id'] for _, r in rows})} documents, {n_pages} pages, " - f"{len(rows)} windows of <= {args.pages_per_request} pages", file=sys.stderr) - fs = fsspec.core.url_to_fs(args.input.split("*")[0] or ".")[0] - processor = ngram_processor() - - def to_request(row): - max_side = row.get("max_side", args.max_side) - images = [load_page(fs, p, max_side, args.pdf_dpi) for p in row["paths"]] - n = len(images) - content = [{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b}"}} - for b in images] - content.append({"type": "text", "text": "" * n + "Multi page parsing."}) - body = { - "model": SERVING["served_name"], - "messages": [{"role": "user", "content": content}], - "max_tokens": SERVING["tokens_per_page"] * n, # global budget for the window - "temperature": SERVING["temperature"], - "skip_special_tokens": False, # / markers are the structure - "images_config": {"crop_mode": row.get("crop", args.crop_mode or SERVING["crop_mode"])}, - } - if args.ngram_window > 0: - body["custom_logit_processor"] = processor - body["custom_params"] = { - "ngram_size": SERVING["ngram_size"], - "window_size": args.ngram_window if n > 1 else 128, - "page_token_id": SERVING["page_token_id"], - "eos_token_id": SERVING["eos_token_id"], - "max_page_tokens": SERVING["max_page_tokens"], - } - return body - - def parse(row, body): - raw = body["choices"][0]["message"]["content"] - raw_pages = raw.split("")[1:] if "" in raw else [raw] - finish = body["choices"][0].get("finish_reason") - # Decoding is greedy, so a truncated or page-misaligned window comes back the same - # on retry: keep its text and flag it (`status`) instead of an error row. - # Only transport failures become error rows (--retry-errors). - if finish == "length": - status = "truncated" - elif len(raw_pages) != len(row["paths"]): - status = "page_mismatch" - else: - status = "ok" - cleaned = [clean_page(p, args.keep_furniture) for p in raw_pages] - pages = [text for text, _ in cleaned] - usage = body.get("usage") or {} - return { - "doc_id": row["doc_id"], - "first_page": row["first_page"], - "page_files": row["page_files"], - "num_pages": len(row["paths"]), - "status": status, - "finish_reason": finish, - # aligned with page_files only when status == "ok" - "page_markdown": pages if status == "ok" else None, - "markdown": convert(raw), - "raw": raw, - "model": SERVING["model"], - "prompt_tokens": usage.get("prompt_tokens"), - "completion_tokens": usage.get("completion_tokens"), - } - - def parse_repair(row, body): - raw = body["choices"][0]["message"]["content"] - finish = body["choices"][0].get("finish_reason") - pages = raw.split("")[1:] - page_raw = pages[0] if pages else raw - if len(pages) != 1: - status = "page_mismatch" # never substitute a malformed reading for the page - elif finish == "length" or degenerate(page_raw): - status = "degenerate" # still looping alone: keep the text, flagged - else: - status = "ok" - usage = body.get("usage") or {} - return { - "doc_id": row["doc_id"], - "page": row["page"], - "page_file": row["page_file"], - "window": row["window"], - "status": status, - "finish_reason": finish, - "markdown": clean_page(page_raw, args.keep_furniture)[0], - "raw": raw, - "mode": "gundam", - "model": SERVING["model"], - "completion_tokens": usage.get("completion_tokens"), - } - - is_repo_id = re.fullmatch(r"[\w-][\w.-]*/[\w.-]*[\w-]", args.output) and not os.path.exists(args.output) - output = f"hf://datasets/{args.output}/data" if is_repo_id else args.output - # Sibling of data/, or a subfolder of the output (saturate only reads /part-*.parquet, - # so it never mixes the two); never a path outside the output repo or bucket. - repairs_out = re.sub(r"/data/?$", "/repairs", output) if re.search(r"/data/?$", output) \ - else output.rstrip("/") + "/repairs" - # One window is minutes of decode, and Auto widens only on completed-request - # evidence, so it ramps slowly from a small start. Start near the measured - # headroom (a100-large: 8 x 32-page windows used ~25% of KV) and flush often, - # since each row is expensive to redo. - window = Auto(initial=32, max_limit=64) - # read_timeout=3600: one window is minutes of decode. A row's retries then get - # 2 x read_timeout in total (saturate's default retry budget). - def run_passes(endpoint, headers=None): - common = {"retry_errors": args.retry_errors, "headers": headers, - "prepare_workers": args.prepare_workers, "read_timeout": 3600} - if not args.repair_only: - stats = pump(rows, to_request, parse, endpoint, output, window=window, flush_every=4, **common) - print(f"{output} ({stats.rows_processed} ok, {stats.rows_failed} error rows)", file=sys.stderr) - print("UNLIMITED_OCR2_SATURATE " + stats.to_json(), flush=True) - if args.no_repair: - return - targets = list(repair_rows(rows, output)) - print(f"repair pass: {len(targets)} pages to re-OCR alone (gundam) -> {repairs_out}", file=sys.stderr) - if targets: - rstats = pump(targets, to_request, parse_repair, endpoint, repairs_out, - window=Auto(initial=32, max_limit=64), flush_every=16, **common) - print("UNLIMITED_OCR2_REPAIR " + rstats.to_json(), flush=True) - - if args.endpoint: - run_passes(args.endpoint, {"Authorization": f"Bearer {os.environ['HF_TOKEN']}"} - if os.environ.get("HF_TOKEN") else None) - else: - py = find_server_python(args.server_python) - print(f"server python: {py}", file=sys.stderr) - # The image's venv may have no pip (uv-built); uv is always present under `uv run`. - has_pip = subprocess.run([py, "-m", "pip", "--version"], check=False, - capture_output=True).returncode == 0 - pip = [py, "-m", "pip", "install", "-q"] if has_pip else ["uv", "pip", "install", "-q", "--python", py] - pip_env = {**os.environ, "PIP_BREAK_SYSTEM_PACKAGES": "1"} - pip_env.pop("VIRTUAL_ENV", None) # never install into this script's venv - subprocess.run([*pip, "--no-deps", SERVING["wheel"]], check=True, env=pip_env) - subprocess.run([*pip, *SERVING["extra_pip"]], check=True, env=pip_env) - os.environ.update(SERVING["env"]) # inherited by the server process - cmd = [py, "-m", "sglang.launch_server", "--model-path", SERVING["model"], - "--served-model-name", SERVING["served_name"], *SERVING["serve_args"], - "--enable-metrics", "--host", "127.0.0.1", "--port", "8000"] - if args.dp_size > 1: - cmd += ["--dp-size", str(args.dp_size)] - with Engine(SERVING["model"], engine="sglang", cmd=cmd) as endpoint: - run_passes(endpoint) - - -# --------------------------------------------------------------------------- -# Vendored verbatim from Baidu's Unlimited-OCR repo (MIT License, Copyright (c) 2026 Baidu): -# https://github.com/baidu/Unlimited-OCR/blob/0cdd7877868bd0e17715d742911b9ce937c53d3f/utils/process_unlimitedOCR2.py -# Lines 30-353 (constants, helpers, convert()); only the file's CLI main() is left out. -# To update: re-copy those lines from a newer commit and bump the hash above. -# Kept byte-for-byte, so its two style-rule hits are waived file-wide: -# ruff: noqa: FURB167, SIM114 -# --------------------------------------------------------------------------- - -# ── block / token patterns ─────────────────────────────────────────────────── -PAGE_SPLIT_RE = re.compile(r'<\s*/?\s*PAGE\s*\d*\s*>', re.I) -MERGE_RE = re.compile(r'<\s*/?\s*MERGE\s*>', re.I) -STRAY_TOKEN_RE = re.compile( - r'<[||]/?[a-zA-Z_]+[||]>|' - r'|<\s*/?\s*PAGE\s*\d*\s*>|<\s*/?\s*BLOCK\s*>|<\s*/?\s*FORK\s*>' - r'|<\s*/?\s*LEVEL\s*\d*\s*[>}]?|<\s*/?\s*MERGE\s*>', re.I) -# label [|[bbox]] [|[bbox]] [] ; LEVEL-first or bbox-first. -BLOCK_RE = re.compile( - r'<\s*BLOCK\s*>\s*([a-zA-Z_]+)' - r'(?:' - r'\s*<\s*/?\s*LEVEL\s*(\d*)\s*[>}]?(?:\s*\[\s*(-?\d+)\s*[,,]\s*(-?\d+)\s*[,,]\s*(-?\d+)\s*[,,]\s*(-?\d+)' - r'(?:\s*[,,]\s*-?\d+)*\s*\])?' - r'|' - r'\s*\[\s*(-?\d+)\s*[,,]\s*(-?\d+)\s*[,,]\s*(-?\d+)\s*[,,]\s*(-?\d+)' - r'(?:\s*[,,]\s*-?\d+)*\s*\](?:\s*<\s*/?\s*LEVEL\s*(\d*)\s*[>}]?)?' - r')?' - r'\s*(?:<\s*FORK\s*>)?', re.I) -TR_RE = re.compile(r']*>.*?', re.I | re.S) -TABLE_OPEN_RE = re.compile(r']*>', re.I) -SPAN_ATTR_RE = re.compile(r'\b(colspan|rowspan)\s*=\s*"([^"]*)"', re.I) - -DROP_LABELS = set() # header/footer/page_number kept (canonical default) -IMAGE_LABELS = {'image', 'figure', 'picture', 'chart', 'img', 'seal'} -NOISE_CONTENT = {'[non-text]', '[unreadable]', '[image]', '[figure]'} -CHAIN_TYPES = {'text', 'table'} -MAX_HEADER_ROWS = 5 - -_BASE_LABELS = { - 'text', 'title', 'header', 'footer', 'page_number', 'image', 'figure', - 'chart', 'seal', 'table', 'image_caption', 'image_footnote', - 'page_footnote', 'equation', 'ref_text', 'aside_text', 'algorithm', -} -_BARE_LABELS = _BASE_LABELS | { - f'{p}{l}' for p in ('cross_', 'append_') for l in _BASE_LABELS} -BARE_BLOCK_RE = re.compile( - r'(?:(?<=)|(?<=)|(?<=\n)|^)' - r'(?:<[||]\s*det\s*[||]>)?' - r'((?:[a-zA-Z_][a-zA-Z_0-9]*)(?:\s*<\s*/?\s*LEVEL\s*\d*\s*[>}]?)?\s*' - r'\[\s*-?\d+(?:\s*[,,]\s*-?\d+){3,}[^\]]*\])', re.I) - - -def _scale(v): - return max(0, min(1000, int(v))) - - -def _fix_span_attrs(text): - def repl(m): - name, val = m.group(1), m.group(2) - try: - int(val) - return m.group(0) - except ValueError: - num = re.search(r'\d+', val) - return f'{name}="{num.group() if num else 1}"' - return SPAN_ATTR_RE.sub(repl, text) - - -def _fix_bare_blocks(text): - """Add the missing prefix to bare block declarations (known labels only).""" - def _repl(m): - label = re.match(r'[a-zA-Z_][a-zA-Z_0-9]*', m.group(1)).group(0) - if label.lower() not in _BARE_LABELS: - return m.group(0) - return f'{m.group(1)}' - text = BARE_BLOCK_RE.sub(_repl, text) - return re.sub(r'\n\s*\s*(?=)', '\n', text, flags=re.I) - - -def _base_type(label): - """cross_text/append_text -> text; append_table/cross_table -> table.""" - for p in ('append_', 'cross_'): - if label.startswith(p): - return label[len(p):] - return label - - -def _parse_blocks(text, page_base=1): - """Split on ; return blocks [{label,bbox,level,content,page,merge_prev}].""" - text = _fix_bare_blocks(text) - segments = PAGE_SPLIT_RE.split(text) - if segments and not segments[0].strip(): - segments = segments[1:] - blocks = [] - for i, seg in enumerate(segments): - page_no = page_base + i - if not seg.strip(): - continue - matches = list(BLOCK_RE.finditer(seg)) - if not matches: - blocks.append({'label': '__raw__', 'bbox': None, 'level': None, - 'content': MERGE_RE.sub('', seg).strip(), - 'page': page_no, 'merge_prev': False}) - continue - for j, m in enumerate(matches): - gap = seg[:m.start()] if j == 0 else seg[matches[j - 1].end():m.start()] - merge_prev = bool(MERGE_RE.search(gap)) - if j == 0: - pre = STRAY_TOKEN_RE.sub('', MERGE_RE.sub('', gap)).strip() - if pre: - blocks.append({'label': '__raw__', 'bbox': None, 'level': None, - 'content': pre, 'page': page_no, 'merge_prev': False}) - end = matches[j + 1].start() if j + 1 < len(matches) else len(seg) - content = MERGE_RE.sub('', seg[m.end():end]).strip() - if m.group(2) is not None: # LEVEL-first - level = int(m.group(2)) if m.group(2) else None - bbox = (tuple(int(m.group(k)) for k in range(3, 7)) - if m.group(3) is not None else None) - else: # bbox-first (or none) - bbox = (tuple(int(m.group(k)) for k in range(7, 11)) - if m.group(7) is not None else None) - level = int(m.group(11)) if m.group(11) else None - blocks.append({'label': m.group(1).lower(), 'bbox': bbox, 'level': level, - 'content': content, 'page': page_no, 'merge_prev': merge_prev}) - return blocks - -def _merge_adjacent_titles(blocks): - """Merge strictly-adjacent, same-page, same- title blocks into one.""" - if not blocks: - return blocks - out = [blocks[0]] - for blk in blocks[1:]: - prev = out[-1] - if (blk['label'] == 'title' and prev['label'] == 'title' - and blk['page'] == prev['page'] - and blk['level'] is not None and prev['level'] is not None - and blk['level'] == prev['level']): - prev['content'] = '\n'.join(x for x in (prev['content'], blk['content']) if x) - continue - out.append(blk) - return out - - -def _build_groups(blocks): - """Union-find grouping of append/cross chains and same-page columns.""" - n = len(blocks) - parent = list(range(n)) - - def find(x): - while parent[x] != x: - parent[x] = parent[parent[x]] - x = parent[x] - return x - - def union(a, b): - ra, rb = find(a), find(b) - if ra != rb: - parent[max(ra, rb)] = min(ra, rb) - - pages_with = {} - for blk in blocks: - b = _base_type(blk['label']) - if blk['label'] != '__raw__' and b in CHAIN_TYPES: - pages_with.setdefault(b, set()).add(blk['page']) - - def _table_adjacent(tail_page, cur_page): - if cur_page - tail_page <= 1: - return True - return all(p not in pages_with.get('table', ()) - for p in range(tail_page + 1, cur_page)) - - open_chain = {} # base type -> current chain-tail index - for i, blk in enumerate(blocks): - label, base = blk['label'], _base_type(blk['label']) - if label == '__raw__' or base not in CHAIN_TYPES: - continue - if label.startswith('append_'): - tail = open_chain.get(base) - if tail is None: - continue - if base == 'table' and not _table_adjacent(blocks[tail]['page'], blk['page']): - open_chain.pop(base, None) - continue - union(tail, i) - open_chain[base] = i - elif label.startswith('cross_'): - open_chain[base] = i - elif base == 'table': - open_chain[base] = i - - for i, blk in enumerate(blocks): # same-page column edges - if not blk.get('merge_prev') or i == 0: - continue - pblk = blocks[i - 1] - if pblk['page'] != blk['page']: - continue - if (blk['label'] == 'title' or _base_type(blk['label']) == 'text') \ - and (pblk['label'] == 'title' or _base_type(pblk['label']) == 'text'): - union(i - 1, i) - - groups = {} - for i in range(n): - groups.setdefault(find(i), []).append(i) - return [groups[r] for r in sorted(groups, key=lambda r: groups[r][0])] - - -def _row_key(tr_html): - txt = re.sub(r'<[^>]+>', ' ', tr_html) - txt = ''.join(chr(ord(c) - 0xFEE0) if 0xFF01 <= ord(c) <= 0xFF5E else c for c in txt) - ncells = len(re.findall(r'') + ''.join(out_rows) + '' - return merged + ('\n\n' + '\n\n'.join(extra) if extra else '') - -def _render_blocks(blocks, groups): - """Render each group to a Markdown item (figure/table/heading/text).""" - items = [] - for members in groups: - head = blocks[members[0]] - base = head['label'] if head['label'] == '__raw__' else _base_type(head['label']) - contents = [blocks[k]['content'] for k in members - if blocks[k]['content'] and blocks[k]['content'].lower() not in NOISE_CONTENT] - if base == '__raw__': - if contents: - items.append(contents[0]) - continue - if base in IMAGE_LABELS: - if head['bbox'] is not None: - x1, y1, x2, y2 = (_scale(v) for v in head['bbox']) - items.append(f'![](page{head["page"]}_{x1}_{y1}_{x2}_{y2}.jpg)') - if contents: - items.append(contents[0]) - continue - if not contents or base in DROP_LABELS: - continue - if base == 'title': - lv = max(1, head['level'] or 1) - joined = ''.join(contents) - if not STRAY_TOKEN_RE.sub('', joined).strip(): - continue - items.append(f'{"#" * lv} {joined}') - continue - if base == 'table': - items.append(_merge_table_fragments(contents) if len(contents) > 1 else contents[0]) - continue - items.append(''.join(contents)) # text family: concatenate, no separator - return items - - -def _head_level(item): - s = item.lstrip() - return len(s) - len(s.lstrip('#')) - - -def _single_root_titles(items): - """Collapse multiple top-level headings under the first one (single root).""" - idxs = [i for i, it in enumerate(items) if it.lstrip().startswith('#')] - if len(idxs) <= 1: - return items - levels = [_head_level(items[i]) for i in idxs] - min_lv = min(levels) - if sum(1 for lv in levels if lv == min_lv) <= 1: - return items - first_lv, out = levels[0], list(items) - for k, i in enumerate(idxs): - body = items[i].lstrip()[levels[k]:].lstrip(' ') - new_lv = 1 if k == 0 else max(2, levels[k] - first_lv + 2) - out[i] = '#' * new_lv + ' ' + body - return out - - -def _fold_head_ws(items): - out = [] - for it in items: - s = it.lstrip() - if s.startswith('#'): - n = len(s) - len(s.lstrip('#')) - it = '#' * n + ' ' + re.sub(r'\s+', ' ', s[n:]).strip() - out.append(it) - return out - - -def _drop_empty_heads(items): - return [it for it in items - if not (it.lstrip().startswith('#') and not it.lstrip().lstrip('#').strip())] - - -def convert(result): - """Unlimited-OCR 2 raw document string -> MarathonDocBench evaluation Markdown.""" - text = (result or '').strip() - if text.startswith('```markdown'): - text = text[len('```markdown'):].strip() - if text.endswith('```'): - text = text[:-3].strip() - - blocks = _parse_blocks(text, page_base=1) - blocks = _merge_adjacent_titles(blocks) - groups = _build_groups(blocks) - items = _drop_empty_heads(_render_blocks(blocks, groups)) - items = _fold_head_ws(items) - text = '\n\n'.join(items) - - text = text.replace('\\coloneqq', ':=').replace('\\eqqcolon', '=:') - text = STRAY_TOKEN_RE.sub('', text) - text = _fix_span_attrs(text) - text = re.sub(r'(?m)^\s*\[\s*-?\d+\s*,\s*-?\d+\s*,\s*-?\d+\s*,\s*-?\d+\s*\]\s*$', '', text) - text = re.sub(r'[ \t]+\n', '\n', text) - text = re.sub(r'\n{3,}', '\n\n', text).strip() - return '\n\n'.join(_single_root_titles(text.split('\n\n'))) - - -if __name__ == "__main__": - main() diff --git a/unlimited-ocr2.py b/unlimited-ocr2.py deleted file mode 100644 index ebf709dc0257f87d6a18a3b93068880ba1cba420..0000000000000000000000000000000000000000 --- a/unlimited-ocr2.py +++ /dev/null @@ -1,349 +0,0 @@ -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "saturate[hf]==0.3.0", -# "pillow>=10", -# ] -# -# [tool.hf-jobs] -# image = "lmsysorg/sglang:v0.5.20-cu130" -# flavor = "rtx-pro-6000" -# timeout = "4h" -# secrets = ["HF_TOKEN"] -# /// -""" -OCR whole documents (book volumes, folders of scans) with Baidu Unlimited-OCR-2. - -Unlimited-OCR-2 reads many pages in ONE request and keeps context across page -breaks: a paragraph that runs onto the next page comes back tagged as a -continuation, not as two fragments. This script groups page images into -documents and sends 16 consecutive pages per request. - - hf jobs uv run --detach \\ - https://huggingface.co/datasets/uv-scripts/ocr/raw/main/unlimited-ocr2.py \\ - "hf://buckets/biglam/britannica/source/pages/1771EncyclopediaBritannicaNLS/*.jp2" \\ - /britannica-1771 - -The [tool.hf-jobs] table above sets the image, GPU, timeout and HF_TOKEN. -The GPU needs >= 48 GB: on 24 GB cards a 16-page request (~31k tokens of KV) -thrashes the cache. rtx-pro-6000 was the fastest per dollar in our tests. - -Input: a glob or folder of page images (a Bucket, a mounted dir, a local dir). -A document is the parent folder plus the file name without its trailing page -number (`Volume 1, A-B_0007.jp2` -> `Volume 1, A-B`); pages sort by that number. - -Output: `data/part-*.parquet`, one row per 16-page window: -`{id, doc_id, first_page, page_files, status, page_markdown, raw, ...}`. -`page_markdown` lines up with `page_files`; `raw` is the model's output with its -layout blocks and boxes. `status` is `truncated` or `page_mismatch` when the model -ran out of budget or lost a page boundary (then `page_markdown` is empty and only -`raw` is kept). Re-running the same command resumes where it stopped. - -About 2% of dense 18th-century pages (mostly mathematics) send the model into a -loop; a page stops at `--max-page-tokens` (8000). `unlimited-ocr2-saturate.py` is the -tuned version of this script: it re-reads those pages one at a time, reads PDFs and adds -Baidu's own Markdown post-processing. It may change more often. - -How it runs: Unlimited-OCR-2 needs Baidu's own SGLang build (no vLLM support). -The script installs that wheel into the image's Python, starts the server in the -Job, and sends requests with saturate (adaptive concurrency, resumable output). - -Model: https://huggingface.co/baidu/Unlimited-OCR-2 (3.3B, MIT) -""" - -import argparse -import base64 -import io -import json -import os -import re -import shutil -import subprocess -import sys - -# The model card's launch settings. The image is the SGLang release whose pins -# match Baidu's wheel (torch 2.13.0, transformers 5.12.1); move both together. The wheel URL -# names a model-repo commit: Baidu replaces the wheel on main (dev10 was removed 2026-10-29). -SERVING = { - "model": "baidu/Unlimited-OCR-2", - "served_name": "Unlimited-OCR-2", - "wheel": "https://huggingface.co/baidu/Unlimited-OCR-2/resolve/91da6546d8ed91e02525f59c012a1d243266d7dd/wheel/" - "sglang-0.5.20.dev10%2Bg8d62f5fb9c-py3-none-any.whl", - "extra_pip": ["fastokens==0.3.2"], - "env": { - "SGLANG_UOCR_EANABLE_DOC_LIMIT": "1", # (sic) upstream spelling - "SGLANG_UOCR_DOC_GUNDAM_PAGE_WINDOW": "10", - "SGLANG_UOCR_DOC_BASE_PAGE_WINDOW": "10", - # Per-page output cap; --max-page-tokens sets it (default 8000). - "SGLANG_UOCR_MAX_PAGE_TOKENS": "8000", - "SGLANG_OPT_UOCR_SAM_REL_POS_BIAS_MB": "64", - "SGLANG_UOCR_SHM_WRAP_MODEL_DATA": "1", - "SGLANG_UOCR_SHM_WRAP_MIN_MB": "1", - "SGLANG_VLM_CACHE_SIZE_MB": "0", - "PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True", - }, - "serve_args": [ - "--chat-template", "unlimited-ocr", - "--tokenizer-backend", "fastokens", "--tokenizer-worker-num", "8", - "--mem-fraction-static", "0.7", - "--max-running-requests", "64", - "--max-prefill-tokens", "2048", - "--enable-custom-logit-processor", "--enable-streaming-session", - "--allow-auto-truncate", "--disable-radix-cache", - "--mm-preprocess-cache-size-mb", "0", - "--cuda-graph-backend-decode", "full", "--cuda-graph-max-bs-decode", "64", - "--cuda-graph-backend-prefill", "full", - "--cuda-graph-max-bs-prefill", "16384", - "--cuda-graph-bs-prefill", "1024", "2048", - "--cuda-graph-config", '{"prefill": {"backend": "full", "full_prefill_max_req": 64}}', - ], -} - -# The card's no-repeat n-gram guard: DeepseekOCRNoRepeatNGramLogitProcessor.to_str(), -# i.e. json({"callable": dill.dumps(cls).hex()}). dill pickles an importable class -# by reference (module + name), so this is a fixed string and needs no sglang here. -NGRAM_PROCESSOR = json.dumps({"callable": ( - "80059559000000000000008c2a73676c616e672e7372742e73616d706c696e672e637573746f6d5f6c6f6769" - "745f70726f636573736f72948c26446565707365656b4f43524e6f5265706561744e4772616d4c6f67697450" - "726f636573736f729493942e")}) - -PAGE_EXTS = (".jp2", ".jpg", ".jpeg", ".png", ".tif", ".tiff", ".webp") -FURNITURE = {"page_number", "header", "footer"} -BLOCK_RE = re.compile(r"(?P[a-z_]+)(?:\d)>)?\[[\d, ]*\]") - - -def natural_key(s: str): - return [int(t) if t.isdigit() else t for t in re.split(r"(\d+)", s)] - - -def doc_key(rel_path: str) -> str: - """`item/Volume 1, A-B_0007.jp2` -> `item/Volume 1, A-B`; bare `0007.jp2` -> `.`.""" - stem = rel_path.rsplit(".", 1)[0] - doc = re.sub(r"[_\-. ]?\d+$", "", stem) - return doc if doc and not doc.endswith("/") else (doc or ".") - - -def list_windows(pattern: str, pages_per_request: int, max_pages): - """List page files, group them into documents, cut each into windows -> (id, row).""" - from saturate import bucket_rows - - if not re.search(r"[*?\[]", pattern): - pattern = pattern.rstrip("/") + "/**" - docs: dict[str, list[tuple[str, str]]] = {} - for rid, row in bucket_rows(pattern, read=False): - if rid.lower().endswith(PAGE_EXTS): - docs.setdefault(doc_key(rid), []).append((rid, row["path"])) - if not docs: - sys.exit(f"no page images matched {pattern!r}") - - n_pages = 0 - for doc in sorted(docs, key=natural_key): - pages = sorted(docs[doc], key=lambda p: natural_key(p[0])) - for start in range(0, len(pages), pages_per_request): - if max_pages is not None and n_pages >= max_pages: - return - window = pages[start: start + pages_per_request] - if max_pages is not None: - window = window[: max_pages - n_pages] - n_pages += len(window) - # The id encodes the page range, so a --max-pages-truncated window is not - # mistaken for the full window when a later run resumes. - yield f"{doc}@{start:06d}-{start + len(window):06d}", { - "doc_id": doc, "first_page": start, - "page_files": [rid for rid, _ in window], - "paths": [p for _, p in window], - } - - -def load_page(fs, path: str, max_side: int) -> str: - """Read one page image, downscale it, return base64 JPEG.""" - from PIL import Image - - with fs.open(path, "rb") as f: - data = f.read() - img = Image.open(io.BytesIO(data)) - if img.format == "JPEG2000": - # Decode straight at a lower wavelet level while the page stays >= max_side: close - # to the full decode after downscaling, for a fraction of the CPU. Some codestreams fail - # at a reduced level, so step back towards a full decode until one works. - reduce = 0 - while max(img.size) >> (reduce + 1) >= max_side: - reduce += 1 - while True: - try: - img = Image.open(io.BytesIO(data)) - img.reduce = reduce - img.load() - break - except OSError: - if reduce == 0: - raise - reduce -= 1 - else: - img.load() - img = img.convert("RGB") - img.thumbnail((max_side, max_side), Image.LANCZOS) - buf = io.BytesIO() - img.save(buf, format="JPEG", quality=90) - return base64.b64encode(buf.getvalue()).decode() - - -def clean_page(raw_page: str, keep_furniture: bool) -> str: - """One page of model output -> plain markdown. - - Drops block tags and boxes, turns titles into `#` headings, drops page - numbers and running heads, and joins ``d blocks (e.g. verse lines). - """ - blocks: list[str] = [] - merge_next = False - matches = list(BLOCK_RE.finditer(raw_page)) - for i, m in enumerate(matches): - end = matches[i + 1].start() if i + 1 < len(matches) else len(raw_page) - body = raw_page[m.end(): end].strip() - merge_prev, merge_next = merge_next, body.endswith("") - body = body.removesuffix("").strip() - kind = m.group("type") - if not body or (kind in FURNITURE and not keep_furniture): - continue - if kind == "title" and m.group("level"): - body = "#" * int(m.group("level")) + " " + body - if merge_prev and blocks: - blocks[-1] += "\n" + body - else: - blocks.append(body) - return "\n\n".join(blocks) - - -def prepare_workers() -> int: - """Threads that decode and encode pages: enough to keep ~40 requests fed, within the Job's CPU quota. - - os.cpu_count() reports the host's cores (190 on a Jobs node), not the quota; that many - threads starve the loop that sends requests. Jobs sets CPU_CORES to the quota. - """ - try: - cores = int(os.environ.get("CPU_CORES", "")) - except ValueError: - cores = 0 - if cores <= 0: - try: - cores = len(os.sched_getaffinity(0)) - except AttributeError: # not Linux - cores = os.cpu_count() or 1 - return max(4, min(16, cores - 6)) # leave cores for SGLang's tokenizer and scheduler - - -def start_server_cmd() -> list[str]: - """Install Baidu's wheel into the image's sglang Python and return the server command.""" - # The SGLang image keeps sglang in its own venv (/opt/sglang/bin), first on PATH; - # `uv run` puts this script's venv in front, so look past it. - own_bin = os.path.realpath(os.path.join(sys.prefix, "bin")) - path = os.pathsep.join(p for p in os.environ.get("PATH", "").split(os.pathsep) - if os.path.realpath(p) != own_bin) - py = shutil.which("python3", path=path) - if not py or subprocess.run([py, "-c", "import sglang"], check=False, - capture_output=True).returncode != 0: - sys.exit("No Python with sglang found: run this on the lmsysorg/sglang image " - "(`hf jobs uv run` picks it up from the script's [tool.hf-jobs] table).") - env = {k: v for k, v in os.environ.items() if k != "VIRTUAL_ENV"} - pip = ["uv", "pip", "install", "-q", "--python", py] - subprocess.run([*pip, "--no-deps", SERVING["wheel"]], check=True, env=env) - subprocess.run([*pip, *SERVING["extra_pip"]], check=True, env=env) - os.environ.update(SERVING["env"]) # inherited by the server process - return [py, "-m", "sglang.launch_server", "--model-path", SERVING["model"], - "--served-model-name", SERVING["served_name"], *SERVING["serve_args"], - "--enable-metrics", "--host", "127.0.0.1", "--port", "8000"] - - -def main(): - ap = argparse.ArgumentParser(description="Unlimited-OCR-2 document OCR on HF Jobs") - ap.add_argument("input", help="Glob or folder of page images: hf://buckets/..., a mounted dir, ...") - ap.add_argument("output", help="Output dataset id (org/name) or fsspec URI (hf://buckets/...)") - ap.add_argument("--pages-per-request", type=int, default=16, - help="Consecutive pages per request (default 16)") - ap.add_argument("--max-pages", type=int, default=None, help="Stop after N pages (for a test run)") - ap.add_argument("--max-side", type=int, default=1280, - help="Long side (px) pages are sent at. The model resizes each page to a " - "1024 px view, so more pixels only make the requests bigger") - ap.add_argument("--keep-furniture", action="store_true", - help="Keep page numbers and running heads in page_markdown") - ap.add_argument("--max-page-tokens", type=int, default=8000, - help="Output cap per page (default 8000). A book page is ~2,000 characters; " - "past 8000 tokens it is almost always a repetition loop. Raise it (up to " - "20000) for very dense pages: large tables, mathematics") - ap.add_argument("--retry-errors", action="store_true", help="Retry windows recorded as errors") - args = ap.parse_args() - if args.max_side <= 0: - ap.error("--max-side must be a positive number of pixels") - if not 0 < args.max_page_tokens <= 20000: - ap.error("--max-page-tokens must be between 1 and 20000") - SERVING["env"]["SGLANG_UOCR_MAX_PAGE_TOKENS"] = str(args.max_page_tokens) - - import fsspec - from saturate import Auto, Engine, pump - - rows = list(list_windows(args.input, args.pages_per_request, args.max_pages)) - print(f"{len({r['doc_id'] for _, r in rows})} documents, " - f"{sum(len(r['paths']) for _, r in rows)} pages, {len(rows)} requests", file=sys.stderr) - fs = fsspec.core.url_to_fs(args.input.split("*")[0] or ".")[0] - - def to_request(row): - n = len(row["paths"]) - content = [{"type": "image_url", - "image_url": {"url": f"data:image/jpeg;base64,{load_page(fs, p, args.max_side)}"}} - for p in row["paths"]] - content.append({"type": "text", "text": "" * n + "Multi page parsing."}) - # Sampling and guard settings from the model card's client example. - return { - "model": SERVING["served_name"], - "messages": [{"role": "user", "content": content}], - "max_tokens": max(8000, args.max_page_tokens) * n, # output budget for the whole window - "temperature": 0, - "skip_special_tokens": False, # / markers are the structure - "images_config": {"crop_mode": False}, # base mode: one 1024 px view per page - "custom_logit_processor": NGRAM_PROCESSOR, - "custom_params": { - "ngram_size": 35, "window_size": 1024 if n > 1 else 128, - "page_token_id": 128827, "eos_token_id": 1, "max_page_tokens": args.max_page_tokens, - }, - } - - def parse(row, body): - choice = body["choices"][0] - raw = choice["message"]["content"] - raw_pages = raw.split("")[1:] - if choice.get("finish_reason") == "length": - status = "truncated" - elif len(raw_pages) != len(row["paths"]): - status = "page_mismatch" - else: - status = "ok" - usage = body.get("usage") or {} - return { - "doc_id": row["doc_id"], - "first_page": row["first_page"], - "page_files": row["page_files"], - "status": status, - "page_markdown": [clean_page(p, args.keep_furniture) for p in raw_pages] - if status == "ok" else None, - "raw": raw, - "model": SERVING["model"], - "prompt_tokens": usage.get("prompt_tokens"), - "completion_tokens": usage.get("completion_tokens"), - } - - is_repo_id = re.fullmatch(r"[\w-][\w.-]*/[\w.-]*[\w-]", args.output) and not os.path.exists(args.output) - output = f"hf://datasets/{args.output}/data" if is_repo_id else args.output - - # One request is minutes of decoding: read_timeout=3600 below, and a row's retries get - # 2 x read_timeout in total (saturate's default retry budget). - with Engine(SERVING["model"], engine="sglang", cmd=start_server_cmd()) as endpoint: - stats = pump(rows, to_request, parse, endpoint, output, - window=Auto(initial=32, max_limit=64), # long requests: start wide - flush_every=4, # each row is minutes of GPU time; write often - read_timeout=3600, prepare_workers=prepare_workers(), retry_errors=args.retry_errors) - print(f"{output}: {stats.rows_processed} windows written, {stats.rows_failed} errors", file=sys.stderr) - print("UNLIMITED_OCR2 " + stats.to_json(), flush=True) - - -if __name__ == "__main__": - main() diff --git a/xiaomi-ocr-0-saturate.py b/xiaomi-ocr-0-saturate.py deleted file mode 100644 index 0da9db5b50009d9ee6ef540c0e95c2d272368991..0000000000000000000000000000000000000000 --- a/xiaomi-ocr-0-saturate.py +++ /dev/null @@ -1,595 +0,0 @@ -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "saturate[hf]==0.3.1", -# "pillow>=10", -# ] -# -# [tool.hf-jobs] -# image = "vllm/vllm-openai:v0.29.0" -# flavor = "a10g-small" -# timeout = "4h" -# secrets = ["HF_TOKEN"] -# /// -""" -Convert document images to markdown using Xiaomi-OCR-0 via saturate. - -Whole-page parsing on an in-job vLLM or SGLang server, driven by the `saturate` -library: adaptive concurrency, resumable parquet output and durable error rows. - -Run on HF Jobs. The script starts the server itself; its [tool.hf-jobs] header -declares the image that provides `vllm`, the hardware and the HF_TOKEN secret -(`hf` CLI 1.32+). Flags on the command line override the header: - - hf jobs uv run --detach \\ - https://huggingface.co/datasets/uv-scripts/ocr/raw/main/xiaomi-ocr-0-saturate.py \\ - - -SGLang instead of vLLM, on the matching image: - - hf jobs uv run --detach --image lmsysorg/sglang:v0.5.20-cu130 \\ - https://huggingface.co/datasets/uv-scripts/ocr/raw/main/xiaomi-ocr-0-saturate.py \\ - --engine sglang - -Smoke test first with --max-samples 3. For speed at the same cost per page, add ---flavor rtx-pro-6000. - -Output: the output repo holds `data/part-*.parquet` with rows -`{id, markdown, raw, finish_reason, model, prompt_tokens, completion_tokens, error}` -keyed by the input row id (`--id-column`, or `:::<000000000>` by -default). Read it with `saturate.read_output`, which keeps one row per id (a success over -an earlier error). `datasets.load_dataset(, data_dir="data")` returns every -record, so after a --retry-errors run it also holds the old error rows: drop rows with an -`error` before you join back to the input on id. Re-running the same command skips -finished rows; --retry-errors re-admits failed ones. A corrupt image stops the run when -it is read (images are decoded as the dataset streams); remove that row and run again. -`finish_reason` = "length" marks a page that hit --max-tokens. Empty `markdown` with no `error` means the model returned no text, -which is the correct result for a blank page; greedy decoding would repeat it on retry. - -Model: xiaomi-research/Xiaomi-OCR-0 (0.8B, Apache-2.0) -- Card scores (OmniDocBench v1.6 96.83, Real5 95.24, Wild 87.94) come from Xiaomi's - TWO-STAGE pipeline (PP-DocLayoutV3 layout, then per-region prompts). This recipe - runs the model's single-stage whole-page mode, so do not quote those scores for it. -- The card's document prompt, image before text, `enable_thinking=False`, greedy - decoding, and images fitted to 2048 px on the long edge and sent as PNG - (skills/xiaomi-ocr/mcp_ocr_server.py `_chat`, evaluation_pipeline/cropping.py). -- Post-processing as upstream's `finalize_document`: repeated-tail cleanup, math - delimiters to `$`/`$$`, OTSL tables to HTML. The model's text is kept in `raw`. -- Deliberate deviation: the card and MCP server use max_tokens 4096, which truncates - dense pages. Upstream's whole-page evaluation (evaluation_pipeline/e2e_img2md.py) uses - 16384 on the model's full context. This recipe serves the 16384 context from the repo - README, to keep KV memory small, so the default is 12000: the most that context leaves - after a worst-case 2048x2048 page (about 4200 image tokens). Lower it with --max-tokens. -- Deliberate deviation: upstream's evaluation re-requests pages that its repetition - guard flags (--retry-repetitive, presence penalty 1.5). This recipe does not. It only - trims a repeated tail, so a page where the model loops keeps the looped text. -- Upstream behaviour kept: a paragraph (text between blank lines) that holds an OTSL - table tag is replaced by the converted table, so text in the same paragraph is lost. - `raw` keeps the model's full output. -- Limits seen in testing: on small-print historical newspapers the model can loop or - insert Chinese characters, and `finish_reason` stays "stop". Tables can lose an item - or the separators between items in a cell. Check a sample of your own pages. - -The SERVING dict below is the per-model tuning prior. Agents can `ast.literal_eval` -it without running the script; the script itself consumes it. -""" - -import argparse -import base64 -import io -import os -import re -import sys -from dataclasses import dataclass - -# Serving starting values for xiaomi-research/Xiaomi-OCR-0. Per-value provenance: -# - context 16384: the repo README's `vllm serve --max-model-len` and SGLang -# `--context-length` value, verbatim. -# - vllm_args cache/mm flags: house OCR defaults (see SERVING.md). -# - max_tokens 12000: house choice, see the docstring. Upstream sends 4096 (card, MCP) -# and 16384 in its whole-page evaluation, on the full model context. -# - temperature, top_p, presence_penalty, repetition_penalty: mcp_ocr_server.py `_chat`. -# - max_edge 2048: evaluation_pipeline/cropping.py MAX_IMAGE_EDGE. -# - window: saturate's default Auto(). Receipts below; a fixed cap only slowed large GPUs. -# - prepare_workers: threads for PNG encoding, sized from CPU_CORES (set by HF Jobs). -# Throughput receipts on UFO scans, vLLM, excluding boot (2026-10-30): -# a10g-small 3.4 pages/s, rtx-pro-6000 9.7 pages/s, both about $0.08 per 1,000 pages. -# - images: vLLM pin matches ovis-ocr2.py (same Qwen3_5 arch); SGLang pin matches -# unlimited-ocr2.py. Move them forward once a newer image passes a smoke test. -SERVING = { - "model": "xiaomi-research/Xiaomi-OCR-0", - "images": {"vllm": "vllm/vllm-openai:v0.29.0", "sglang": "lmsysorg/sglang:v0.5.20-cu130"}, - "context": 16384, - "vllm_args": [ - "--limit-mm-per-prompt", '{"image": 1}', - "--mm-processor-cache-gb", "0", - "--no-enable-prefix-caching", - ], - "max_tokens": 12000, - "temperature": 0.0, - "top_p": 0.8, - "presence_penalty": 0.0, - "repetition_penalty": 1.0, - "max_edge": 2048, -} - -# Card "Task prompts" table, Document row, verbatim. -OCR_PROMPT = ( - "Extract all information from the main body of the document image and represent it " - "in markdown format, ignoring headers and footers. Tables should be expressed in OTSL " - "format, formulas in the document should be represented using LATEX format, and the " - "parsing should be organized according to the reading order." -) - - -def to_pil(value): - from PIL import Image - - if isinstance(value, Image.Image): - return value - if isinstance(value, dict) and value.get("bytes"): - return Image.open(io.BytesIO(value["bytes"])) - if isinstance(value, (bytes, bytearray)): - return Image.open(io.BytesIO(value)) - raise ValueError(f"unsupported image value: {type(value)}") - - -def encode_image(value, max_edge: int) -> str: - """RGB-convert, fit within max_edge keeping aspect ratio, return base64 PNG.""" - from PIL import Image - - img = to_pil(value).convert("RGB") - img.thumbnail((max_edge, max_edge), Image.Resampling.LANCZOS) - buf = io.BytesIO() - img.save(buf, format="PNG") - return base64.b64encode(buf.getvalue()).decode() - - -# Vendored from github.com/xiaomi-research/Xiaomi-OCR-0 at b1a9bb4 (Apache-2.0, -# Copyright 2026 Xiaomi Corporation): postprocess/otsl.py and postprocess/document.py. - - -ROW_BREAK = "" -CELL = "" -EMPTY = "" -LEFT = "" -UP = "" -BOTH = "" - -ALL_TAGS = (CELL, EMPTY, LEFT, UP, BOTH, ROW_BREAK) -TAG_RE = re.compile("(" + "|".join(re.escape(tag) for tag in ALL_TAGS) + ")") - -ORIGIN_TAGS = frozenset({CELL, EMPTY}) -RIGHT_CONTINUATION = frozenset({LEFT, BOTH}) -DOWN_CONTINUATION = frozenset({UP, BOTH}) - - -@dataclass -class Cell: - """A resolved cell placed on the rectangular grid.""" - - text: str - row: int - column: int - rowspan: int = 1 - colspan: int = 1 - - -def _tag_of(chunk: str) -> str: - match = TAG_RE.match(chunk) - return match.group(0) if match else "" - - -def _split_chunks(line: str) -> list[str]: - """Split a row into chunks, each holding one tag plus the text after it.""" - starts = [match.start() for match in TAG_RE.finditer(line)] - ends = starts[1:] + [len(line)] - return [line[start:end] for start, end in zip(starts, ends)] - - -def _required_width(chunks: list[str]) -> int: - """Number of leading cells a row must keep to preserve its last content.""" - width = 0 - for position, chunk in enumerate(chunks, start=1): - if _tag_of(chunk) == CELL: - width = position - return width - - -def _target_width(rows: list[list[str]]) -> int: - """Pick one cell count every row is padded or truncated to. - - Every row must keep at least the cells it declared content for, and the - cheapest width balances the total amount of truncation and padding. - """ - lower = max(_required_width(row) for row in rows) - upper = max(len(row) for row in rows) - best_width = upper - best_cost = None - for width in range(lower, upper + 1): - cost = sum(abs(len(row) - width) for row in rows) - if best_cost is None or cost < best_cost: - best_width = width - best_cost = cost - return best_width - - -def pad_rows(otsl: str) -> str: - """Give every row the same cell count so the grid can be indexed.""" - text = otsl.strip() - if ROW_BREAK not in text: - return text + ROW_BREAK - - rows = [] - for line in text.split(ROW_BREAK): - chunks = _split_chunks(line) - if chunks: - rows.append(chunks) - if not rows: - return ROW_BREAK - - width = _target_width(rows) - padded = [] - for chunks in rows: - fixed = chunks[:width] - fixed += [EMPTY] * (width - len(fixed)) - padded.append("".join(fixed)) - return ROW_BREAK.join(padded) + ROW_BREAK - - -def parse_grid(otsl: str) -> tuple[list[list[str]], list[list[str]]]: - """Return the padded table as parallel tag and text grids.""" - tag_rows: list[list[str]] = [] - text_rows: list[list[str]] = [] - - for line in otsl.split(ROW_BREAK): - chunks = _split_chunks(line) - if not chunks: - continue - tags = [] - texts = [] - for chunk in chunks: - tag = _tag_of(chunk) - tags.append(tag) - texts.append(chunk[len(tag):] if tag == CELL else "") - tag_rows.append(tags) - text_rows.append(texts) - - width = max((len(row) for row in tag_rows), default=0) - for tags, texts in zip(tag_rows, text_rows): - tags += [EMPTY] * (width - len(tags)) - texts += [""] * (width - len(texts)) - return tag_rows, text_rows - - -def resolve_cells( - tag_rows: list[list[str]], text_rows: list[list[str]] -) -> list[Cell]: - """Turn origin tags into cells, measuring spans from the continuation tags.""" - height = len(tag_rows) - cells: list[Cell] = [] - - for row_index, tags in enumerate(tag_rows): - for column, tag in enumerate(tags): - if tag not in ORIGIN_TAGS: - continue - - colspan = 1 - while ( - column + colspan < len(tags) - and tags[column + colspan] in RIGHT_CONTINUATION - ): - colspan += 1 - - rowspan = 1 - while ( - row_index + rowspan < height - and column < len(tag_rows[row_index + rowspan]) - and tag_rows[row_index + rowspan][column] in DOWN_CONTINUATION - ): - rowspan += 1 - - text = text_rows[row_index][column] if tag == CELL else "" - cells.append( - Cell( - text=text.strip(), - row=row_index, - column=column, - rowspan=rowspan, - colspan=colspan, - ) - ) - return cells - - -def render_html(cells: list[Cell], num_rows: int, num_cols: int) -> str: - """Render resolved cells as an HTML table element. - - Layout is walked column by column, so every row emits exactly one cell per - grid column and the result stays a well-formed table even when the input - OTSL contradicts itself. Spans are measured against the ownership grid, so - a span never claims a position owned by another cell. - """ - if not cells: - return "" - - grid: list[list[Cell | None]] = [ - [None] * num_cols for _ in range(num_rows) - ] - for cell in cells: - for row in range(cell.row, min(cell.row + cell.rowspan, num_rows)): - for column in range(cell.column, min(cell.column + cell.colspan, num_cols)): - if row >= 0 and column >= 0: - grid[row][column] = cell - - covered_until: dict[int, int] = {} - parts = [] - for row in range(num_rows): - parts.append("") - column = 0 - while column < num_cols: - if covered_until.get(column, 0) > row: - column += 1 - continue - - cell = grid[row][column] - if cell is None or cell.row != row or cell.column != column: - # A continuation tag with no origin of its own: keep the column - # so the row still spans the full grid width. - parts.append("") - column += 1 - continue - - colspan = 1 - while ( - column + colspan < num_cols - and grid[row][column + colspan] is cell - ): - colspan += 1 - - rowspan = 1 - while row + rowspan < num_rows and all( - grid[row + rowspan][offset] is cell - for offset in range(column, column + colspan) - ): - rowspan += 1 - - attributes = "" - if rowspan > 1: - attributes += f' rowspan="{rowspan}"' - if colspan > 1: - attributes += f' colspan="{colspan}"' - parts.append(f"{cell.text}") - - for offset in range(column, column + colspan): - covered_until[offset] = max( - covered_until.get(offset, 0), row + rowspan - ) - column += colspan - parts.append("") - return "" + "".join(parts) + "
" - - -def convert_otsl_to_html(otsl_content: str) -> str: - """Convert an OTSL table into an HTML ```` element.""" - if not isinstance(otsl_content, str): - raise TypeError("otsl_content must be a string") - - tag_rows, text_rows = parse_grid(pad_rows(otsl_content)) - cells = resolve_cells(tag_rows, text_rows) - num_rows = len(tag_rows) - num_cols = max((len(row) for row in tag_rows), default=0) - return render_html(cells, num_rows, num_cols) - - -OTSL_TAG_RE = re.compile(r"<(?:fcel|ecel|nl|lcel|ucel|xcel)>") - - -def postprocess_math_delimiters(markdown: str) -> str: - """Convert LaTeX delimiters in whole-page markdown to markdown math delimiters.""" - if not markdown: - return markdown - markdown = markdown.replace("\\[\\[", "\\[").replace("\\]\\]", "\\]") - markdown = re.sub( - r"\$\$?\s*\\\[\s*(.*?)\s*\\\]\s*\$\$?", - r" $$ \1 $$ ", - markdown, - flags=re.DOTALL, - ) - markdown = re.sub( - r"\$\s*\\\(\s*(.*?)\s*\\\)\s*\$", - r" $ \1 $", - markdown, - flags=re.DOTALL, - ) - markdown = re.sub( - r"\\\[\s*(.*?)\s*\\\]", - r" $$ \1 $$ ", - markdown, - flags=re.DOTALL, - ) - markdown = re.sub( - r"\\\(\s*(.*?)\s*\\\)", - r" $ \1 $", - markdown, - flags=re.DOTALL, - ) - return markdown - - -def _split_markdown_blocks(markdown: str): - parts = re.split(r"(\n\s*\n)", markdown) - blocks = [] - for i in range(0, len(parts), 2): - text = parts[i] - sep = parts[i + 1] if i + 1 < len(parts) else "" - blocks.append([text, sep]) - return blocks - - -def postprocess_otsl_tables(markdown: str) -> str: - """Convert OTSL-looking markdown blocks to HTML tables; keep original on failure.""" - if not markdown or not OTSL_TAG_RE.search(markdown): - return markdown - - blocks = _split_markdown_blocks(markdown) - in_fence = False - converted = [] - for text, sep in blocks: - stripped = text.strip() - fence_count = stripped.count("```") - should_skip = in_fence - if fence_count % 2 == 1: - in_fence = not in_fence - should_skip = True - - if not should_skip and OTSL_TAG_RE.search(stripped): - try: - html = convert_otsl_to_html(stripped) - if html: - text = html - except Exception: - pass - converted.append(text + sep) - return "".join(converted) - - -def _clean_truncated_repeats( - text: str, - min_text_len: int = 8000, - max_period: int = 200, - min_period: int = 1, - min_repeat_chars: int = 100, - min_repeat_times: int = 5, -) -> str: - """Trim a degenerate repeated tail, keeping one period plus the remainder.""" - n = len(text) - if n < min_text_len: - return text - - max_period = min(max_period, n - 1) - for unit_len in range(min_period, max_period + 1): - if text[n - 1] != text[n - 1 - unit_len]: - continue - - match_len = 1 - idx = n - 2 - while idx >= unit_len and text[idx] == text[idx - unit_len]: - match_len += 1 - idx -= 1 - - total_len = match_len + unit_len - repeat_times = total_len // unit_len - tail_len = total_len % unit_len - - if repeat_times >= min_repeat_times and total_len >= min_repeat_chars: - return text[: n - total_len + unit_len] + text[n - tail_len:] - - return text - - -def finalize_document(text: str) -> str: - """Upstream's whole-page post-processing order (postprocess/document.py).""" - return postprocess_otsl_tables(postprocess_math_delimiters(_clean_truncated_repeats(text))) - - -def main(): - ap = argparse.ArgumentParser(description="Xiaomi-OCR-0 batch OCR via saturate") - ap.add_argument("input_dataset", help="Input dataset repo id (rows with an image column)") - ap.add_argument("output_dataset", help="Output dataset repo id (created if missing)") - ap.add_argument("--engine", choices=["vllm", "sglang"], default="vllm", - help="Serving engine; sglang also needs the SGLang --image (see docstring)") - ap.add_argument("--image-column", default="image") - ap.add_argument("--config", default=None, help="Dataset config name") - ap.add_argument("--split", default="train") - ap.add_argument("--id-column", default=None, - help="Column to use as row id (default: split-index ids)") - ap.add_argument("--max-samples", "--limit", dest="limit", type=int, default=None, - help="Process only the first N rows (smoke test)") - ap.add_argument("--max-tokens", type=int, default=SERVING["max_tokens"], - help="Output cap; must leave room for the image in the 16384 context") - ap.add_argument("--retry-errors", action="store_true", - help="Re-admit rows whose only record is an error row") - args = ap.parse_args() - - if args.max_tokens < 1: - ap.error("--max-tokens must be at least 1") - if args.max_tokens > SERVING["max_tokens"]: - ap.error(f"--max-tokens above {SERVING['max_tokens']} can overflow the {SERVING['context']} context") - - import pyarrow as pa - from saturate import Engine, dataset_rows, pump - - if args.id_column is None: - ids = "index" - elif args.id_column in ("index", "content"): - # saturate reads these two names as id strategies, so a column with one of them - # needs a callable. It returns the raw value, so saturate still refuses a null id. - ids = lambda example: example[args.id_column] - else: - ids = args.id_column - - rows = dataset_rows( - args.input_dataset, config=args.config, split=args.split, - columns=[args.image_column], ids=ids, limit=args.limit, - ) - - def to_request(row): - b64 = encode_image(row[args.image_column], SERVING["max_edge"]) - return { - "model": SERVING["model"], - "messages": [{"role": "user", "content": [ - {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}}, - {"type": "text", "text": OCR_PROMPT}, - ]}], - "max_tokens": args.max_tokens, - "temperature": SERVING["temperature"], - "top_p": SERVING["top_p"], - "presence_penalty": SERVING["presence_penalty"], - "repetition_penalty": SERVING["repetition_penalty"], - "chat_template_kwargs": {"enable_thinking": False}, - } - - # Declared, so a part holding only error rows has the same columns as the rest - # (datasets.load_dataset reads every part with one schema). - schema = pa.schema([ - ("id", pa.string()), ("error", pa.string()), ("markdown", pa.string()), ("raw", pa.string()), - ("finish_reason", pa.string()), ("model", pa.string()), - ("prompt_tokens", pa.int64()), ("completion_tokens", pa.int64()), - ]) # fmt: skip - - def parse(row, body): - choice = body["choices"][0] - raw = choice["message"]["content"].strip() - usage = body.get("usage") or {} - return { - "markdown": finalize_document(raw), - "raw": raw, - "finish_reason": choice.get("finish_reason"), - "model": SERVING["model"], - "prompt_tokens": usage.get("prompt_tokens"), - "completion_tokens": usage.get("completion_tokens"), - } - - if args.engine == "sglang": - # saturate starts SGLang with the image's Python (the one that has sglang), not this - # script's venv; without the SGLang --image the server fails with "No module named sglang". - extra = ["--context-length", str(SERVING["context"]), "--host", "127.0.0.1"] - engine = Engine(SERVING["model"], engine="sglang", extra_args=extra) - else: - extra = ["--max-model-len", str(SERVING["context"]), *SERVING["vllm_args"]] - engine = Engine(SERVING["model"], engine="vllm", extra_args=extra) - - output = f"hf://datasets/{args.output_dataset}/data" - with engine as endpoint: - stats = pump(rows, to_request, parse, endpoint, output, - prepare_workers=int(float(os.environ.get("CPU_CORES") or "4")), - retry_errors=args.retry_errors, schema=schema) - - print(f"https://huggingface.co/datasets/{args.output_dataset} " - f"({stats.rows_processed} ok, {stats.rows_failed} error rows)", file=sys.stderr) - print("XIAOMI_OCR_0_SATURATE " + stats.to_json(), flush=True) - - -if __name__ == "__main__": - main()