Sync from GitHub via hub-sync
Browse filesFiles changed (6)
- CLAUDE.md+123-1
- dots-ocr.py+58-4
- glm-ocr.py+76-3
- lighton-ocr2.py+39-2
- pp-ocrv6.py+63-5
- surya-ocr.py+60
12345284 unmodified lines290291292293294295296# OCR Scripts - Development Notes## Active Scripts### DeepSeek-OCR v1 (`deepseek-ocr-vllm.py`)284 unmodified linesthe batch default.### Nanonets OCR (`nanonets-ocr.py`, `nanonets-ocr2.py`)✅ Both versions working### PaddleOCR-VL (`paddleocr-vl.py`)✅ Working123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101284 unmodified lines386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418# OCR Scripts - Development Notes## Large full-page scan fixes (2026-07-01)A batch of scripts run over a **large**-page historical book-scan corpus (WebP, ~2000–4000px /7–9 MP) exposed 5 failures. Root-caused + fixed + verified on Jobs (l4x1, `--max-samples 4–16` onthat corpus). `deepseek-ocr-vllm.py` / `paddleocr-vl-1.6.py` were unaffected.> ⚠️ **Gotcha for testing on such corpora:** some eval sets already ship `text`, `markdown`,> `docling`, `xml` columns, so **every** default `--output-column` collides — pass a distinct one> (e.g. `--output-column ocr_md`) on *all* the markdown-default scripts, not just pp-ocrv6.- **`surya-ocr.py` — silent per-row `[SURYA GENERATE ERROR]`, log `No module named 'vllm'`.**Working as designed (deps omit `vllm`; needs `--image vllm/vllm-openai:v0.20.1` — see its own sectionbelow); the batch run just dropped the image flags. **Fix:** added a `check_vllm_available()` preflightthat `sys.exit(1)`s with the exact required flags **before** processing, instead of writing 400 silentsentinels. `--max-model-len` was already 18000. Verified: bare-image run now fails fast.- **`dots-ocr.py` — `[OCR ERROR]` on large pages (small pages OK).** No image resize; a 7–9 MP page →up to ~14k image tokens (model's 11.29M-px processor cap) > the old `--max-model-len 8192` → vLLMrejects → sentinel. **Fix:** default `--max-model-len` 8192→**32768** + new optional `--max-pixels`(mm_processor cap). Verified 4/4 real OCR (matches GT; v1 works with the auto-detected `openai` chatformat — the dots-1.5 `content_format="string"` fix does **not** apply to v1).- **`lighton-ocr2.py` — `[OCR ERROR]` on large pages.** Its 1540px resize is correct, but ~6k imagetokens **+ `--max-tokens 4096`** > `--max-model-len 8192` at admission. **Fix:** default`--max-model-len` 8192→**16384**. Verified 4/4 real OCR on l4x1.- **`glm-ocr.py` — whole JOB ERROR.** The *current* blocker was **not** OOM: glm pinned`pyarrow>=17.0.0,<18.0.0`, but `datasets>=5.0.0` (which understands this dataset's `Json` featuretype) needs `pyarrow>=21`, so uv resolved `datasets 4.0.0` and `load_dataset` threw`ValueError: Feature type 'Json' not found` (this is the 3-second startup ERROR seen in job history;dots/lighton don't pin pyarrow, so they loaded fine). **Fix:** dropped the pyarrow pin. Also added`VLLM_USE_DEEP_GEMM=0` (silences the non-fatal deep_gemm assertion on the nvcc-less nightly image) andan **optional** `--max-pixels` cap. Verified: loads + completes 16/16 large pages, and **did NOT OOMat defaults** (batch 16, no cap) — so `--max-pixels` stays an opt-in memory safety-valve, not adefault (the original "30-min OOM" didn't reproduce on 16 pages; it likely needed a specificpage/batch deep in a 400-row run). glm is chatty on blank pages / can emit degenerate repeats, butthat's model quality, not the crash.- **`pp-ocrv6.py` — crash on SAVE: duplicated column `['text']`.** Hardcoded output to `text` with **no**`--output-column` flag; the corpus already has a `text` column. **Fix:** added `--output-column`(default `markdown`, matching siblings) threaded through the sink + card + inference_info, plus a**fast-fail startup guard** (`sys.exit(1)` before inference) if the chosen output column — or`pp_ocr_blocks` — already exists in the input, so it never silently overwrites ground truth. Verified:guard fires on the colliding default; `--output-column ocr_md` pushes cleanly.### Cross-cutting notes- **Output-column collision guard (rolled out to ALL ~31 output-writing scripts, 2026-07-01):**generalises the pp-ocrv6 fix. A shared `ensure_output_columns_free(dataset, columns, overwrite=False)`helper (copied into each standalone script — no shared lib in this repo) fails fast at startup if anoutput column already exists in the input, instead of silently building a duplicate that crashes onpush *after* inference (or clobbering a ground-truth column). New `--overwrite` flag opts in toreplacing it. surya guards both `output_column` + `blocks_column`; the sink scripts (pp-ocrv6,pp-doclayout) carry the equivalent guard inline. The 5 scripts that hardcoded `"markdown"`(nanonets-ocr/-ocr2, abot-ocr, deepseek-ocr/-ocr-vllm) also gained a configurable `--output-column`.Static-verified (ruff + AST + wiring) on all; the pattern is Jobs-proven via pp-ocrv6.- **Error signalling (#6 — documented, NOT implemented this pass):** ~39 sentinel-string sites(`[OCR ERROR]`, `[SURYA GENERATE ERROR]`, …) across ~20 scripts write the sentinel *into* the OCRcolumn, so partial failures are silent and pollute downstream metrics. **Proposed follow-up:** leavethe OCR cell null/empty on failure and record the truncated exception in a companion `ocr_error`column, so "model read nothing" is distinguishable from "the run errored." Deferred — would touch all~20 standalone scripts (no shared lib).- **`--max-model-len` policy:** the durable fix is to **bound the input** (image cap) and size contextto that bound + output — what the working `paddleocr-vl-1.6.py` (~1M-px smart resize) and `surya-ocr.py`(max_pixels + 18000) already do. The per-script default bumps above are the minimal version. Don'tauto-size `max_model_len` from images (it's fixed at engine init, before images are seen).- **Context-length invariant (must hold for every vLLM recipe):**`--max-tokens` ≤ `--max-model-len` ≤ the model's real max context. The real max is the languagemodel's `max_position_embeddings` in `config.json` (VLMs: usually under `text_config`/`language_config`,adjusted by any `rope_scaling`). If `max_model_len` > that, vLLM refuses to start (we don't set`VLLM_ALLOW_LONG_MAX_MODEL_LEN`); if `max_tokens` > `max_model_len`, the output alone can't fit.Quick check: `curl -s https://huggingface.co/<model>/raw/main/config.json | python -c "import json,sys;c=json.load(sys.stdin);t=c.get('text_config',c);print(t.get('max_position_embeddings'),t.get('rope_scaling'))"`.Audited 2026-07-01 across all vLLM recipes: none exceed their window (dots-ocr 32768/131072 ✓,lighton-ocr2 16384/16384 = at cap/zero headroom ✓); fixed `nanonets-ocr.py` (had `max_tokens 15000`> `max_model_len 8192` → raised default to 32768).### Future: "self-review a new/changed OCR recipe" skill (spark, 2026-07-01)A **dev-only skill** (sibling to `bump-vllm-pins`) that reviews an OCR recipe (a given script or thecurrent diff / `--all`) against the invariants this repo keeps re-learning, so a new recipe or a bumpeddefault is caught **before** it ships. Mostly a **static** check (fast, no compute); each maps to aconcrete failure we've hit:1. **Context-length** — `--max-tokens` ≤ `--max-model-len` ≤ model `config.json` `max_position_embeddings`(fetch the config; VLMs → `text_config`, mind `rope_scaling`). Catches vLLM-won't-start andoutput-can't-fit (found `nanonets-ocr.py`).2. **Output-column collision guard** — has `ensure_output_columns_free` (or the inline sink guard) +`--overwrite`, and `--output-column` default isn't a bare hardcoded name that clobbers input.3. **vLLM image / preflight** — if the arch isn't in a stable wheel, deps omit `vllm`/`torch` AND there'sa fail-fast preflight naming the required `--image`/`--python`/`PYTHONPATH` (surya-class).4. **Env guards on the bare image** — `VLLM_USE_FLASHINFER_SAMPLER=0` (and `VLLM_USE_DEEP_GEMM=0` fornightly vLLM) set before importing vllm.5. **Dep sanity** — no stale caps that drag a transitive lib back (e.g. `pyarrow<18` → old `datasets`lacking the `Json` feature → `load_dataset` crash, the glm-ocr bug).6. **Large-image bounding** — full-page recipes cap input pixels / resize, or size `max_model_len` to fit.7. **(optional) Jobs smoke** — only after the static checks pass, run on a tiny hard-input set (thesmoke-test dataset **+** a large 7–9 MP page) on l4x1, poll to terminal, and classify any failureinto the catalogued buckets (missing-vllm/wrong-image, collision, context-overflow `[OCR ERROR]`,encoder OOM, dep-drift) with remedies.Pairs with the "OCR Smoke Test Dataset" idea below. Build after the current fixes land.## Active Scripts### DeepSeek-OCR v1 (`deepseek-ocr-vllm.py`)284 unmodified linesthe batch default.### Nanonets OCR (`nanonets-ocr.py`, `nanonets-ocr2.py`)✅ `nanonets-ocr.py` working.**`nanonets-ocr2.py` — ⚠️ requires pinned vLLM image `vllm/vllm-openai:v0.10.2` (fixed 2026-06-30).**Nanonets-OCR2-3B is a **Qwen2.5-VL** model. On a floating `vllm` pin (resolved to **0.24.0**) itdecoded **pure `!` on every page** — the documented vLLM **>=0.11 Qwen2.5-VL regression**([vllm#27775](https://github.com/vllm-project/vllm/issues/27775),[#14126](https://github.com/vllm-project/vllm/issues/14126); 0.9.2/0.10.1/**0.10.2** are theknown-good builds). Ruled out along the way: it is **not** context length (still `!` at`max_model_len=32768`) and **not** torch.compile (still `!` with `enforce_eager=True`). Pip-pinning`vllm==0.10.2` alone fails — its old tokenizer API (`Qwen2Tokenizer.all_special_tokens_extended`)clashes with modern `transformers` 5.x. **Fix:** run on the **`vllm/vllm-openai:v0.10.2` image**(ships a consistent vLLM 0.10.2 + transformers 4.56.1); `vllm` and `torch` are omitted from the PEP723 deps and come from the image via `PYTHONPATH`. Also bumped the `--max-model-len` default8192→32768 (the script's `--max-tokens` default is 15000 per the model card, which an 8192 contextcan't hold). Standard `/usr/bin/python3` + `dist-packages` image layout (probed). Re-test the pinwhen a newer vLLM ships a Qwen2.5-VL decode fix → it can move back to the default image.**Smoke test (2026-06-30, `davanstrien/ufo-ColPali`, 5 samples, a10g-small):** 5/5 clean markdown(English + Spanish, `<header>`/`<img>` semantic tags), 0 degenerate rows. Output`davanstrien/nanonets-ocr2-img0102-test`.```bashhf jobs uv run --flavor a10g-small -s HF_TOKEN \--image vllm/vllm-openai:v0.10.2 --python /usr/bin/python3 \-e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \./ocr/nanonets-ocr2.py INPUT_DATASET OUTPUT_DATASET --max-samples 10 --shuffle --seed 42```### PaddleOCR-VL (`paddleocr-vl.py`)✅ Working
92 unmodified lines939495969798140 unmodified lines2392402412422432442455 unmodified lines25125225325425525628 unmodified lines2852862872882892907 unmodified lines298299300301302303304305306307308309310198 unmodified lines50951051151251351451551643 unmodified lines56056156256356456513 unmodified lines5795805815825835845 unmodified lines59059159259359459592 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def make_ocr_message(image: Union[Image.Image, Dict[str, Any], str],prompt: str = PROMPT_TEMPLATES["ocr"],140 unmodified linesimage_column: str = "image",batch_size: int = 16,model: str = "rednote-hilab/dots.ocr",max_model_len: int = 8192,max_tokens: int = 8192,gpu_memory_utilization: float = 0.8,hf_token: str = None,5 unmodified linesprompt_mode: str = "ocr",custom_prompt: str = None,output_column: str = "markdown",config: str = None,create_pr: bool = False,):28 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")7 unmodified lines# Initialize vLLM modellogger.info(f"Initializing vLLM with model: {model}")logger.info("This may take a few minutes on first run...")llm = LLM(model=model,trust_remote_code=True,max_model_len=max_model_len,gpu_memory_utilization=gpu_memory_utilization,limit_mm_per_prompt={"image": 1},)sampling_params = SamplingParams(temperature=0.0, # Deterministic for OCR198 unmodified linesparser.add_argument("--max-model-len",type=int,default=8192,help="Maximum model context length (default: 8192)",)parser.add_argument("--max-tokens",43 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--config",help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",13 unmodified linesbatch_size=args.batch_size,model=args.model,max_model_len=args.max_model_len,max_tokens=args.max_tokens,gpu_memory_utilization=args.gpu_memory_utilization,hf_token=args.hf_token,5 unmodified linesprompt_mode=args.prompt_mode,custom_prompt=args.custom_prompt,output_column=args.output_column,config=args.config,create_pr=args.create_pr,)92 unmodified lines93949596979899100101102103104105106107108109110111112113114115116117118119120140 unmodified lines2612622632642652662672685 unmodified lines27427527627727827928028 unmodified lines3093103113123133143153163177 unmodified lines325326327328329330331332333334335336337338339340341198 unmodified lines54054154254354454554654754854955055155255355455555655755855956056156243 unmodified lines60660760860961061161261361461561661713 unmodified lines6316326336346356366375 unmodified lines64364464564664764864992 unmodified lineslogger.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 clashingcolumn(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 datasetif 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 make_ocr_message(image: Union[Image.Image, Dict[str, Any], str],prompt: str = PROMPT_TEMPLATES["ocr"],140 unmodified linesimage_column: str = "image",batch_size: int = 16,model: str = "rednote-hilab/dots.ocr",max_model_len: int = 32768,max_pixels: int = None,max_tokens: int = 8192,gpu_memory_utilization: float = 0.8,hf_token: str = None,5 unmodified linesprompt_mode: str = "ocr",custom_prompt: str = None,output_column: str = "markdown",overwrite: bool = False,config: str = None,create_pr: bool = False,):28 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")7 unmodified lines# Initialize vLLM modellogger.info(f"Initializing vLLM with model: {model}")logger.info("This may take a few minutes on first run...")llm_kwargs = dict(model=model,trust_remote_code=True,max_model_len=max_model_len,gpu_memory_utilization=gpu_memory_utilization,limit_mm_per_prompt={"image": 1},)if max_pixels is not None:logger.info(f"Capping input images to max_pixels={max_pixels}")llm_kwargs["mm_processor_kwargs"] = {"max_pixels": max_pixels}llm = LLM(**llm_kwargs)sampling_params = SamplingParams(temperature=0.0, # Deterministic for OCR198 unmodified linesparser.add_argument("--max-model-len",type=int,default=32768,help=("Maximum model context length (default: 32768). dots.ocr does NOT resize ""input images, so a full page can reach ~14k image tokens (the model's ""11.29M-px processor cap); the old 8192 default rejected such requests and ""the row was written as '[OCR ERROR]'. Pair with --max-pixels to cap memory."),)parser.add_argument("--max-pixels",type=int,default=None,help=("Optional cap on input image pixels (width*height) passed to vLLM's ""mm_processor. Lower this (e.g. 4000000) to bound image tokens and GPU ""memory on very large scans. Default: model's own cap (~11.29M px)."),)parser.add_argument("--max-tokens",43 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--config",help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",13 unmodified linesbatch_size=args.batch_size,model=args.model,max_model_len=args.max_model_len,max_pixels=args.max_pixels,max_tokens=args.max_tokens,gpu_memory_utilization=args.gpu_memory_utilization,hf_token=args.hf_token,5 unmodified linesprompt_mode=args.prompt_mode,custom_prompt=args.custom_prompt,output_column=args.output_column,overwrite=args.overwrite,config=args.config,create_pr=args.create_pr,)
1 unmodified line234567844 unmodified lines535455565758594 unmodified lines64656667686919 unmodified lines89909192939495969714 unmodified lines112113114115116117107 unmodified lines2252262272282292307 unmodified lines23823924024124224325 unmodified lines26927027127227327444 unmodified lines319320321322323324325183 unmodified lines50951051151251351465 unmodified lines5805815825835845858 unmodified lines5945955965975985997 unmodified lines6076086096106116121 unmodified line# requires-python = ">=3.11"# dependencies = [# "datasets>=3.1.0",# "pyarrow>=17.0.0,<18.0.0",# "huggingface-hub",# "pillow",# "vllm",44 unmodified linesimport sysimport timefrom datetime import datetimefrom typing import Any, Dict, List, Unionimport torchfrom datasets import load_dataset4 unmodified lines# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")from vllm import LLM, SamplingParamslogging.basicConfig(level=logging.INFO)19 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def make_ocr_message(image: Union[Image.Image, Dict[str, Any], str],task: str = "ocr",) -> List[Dict]:"""Create chat message for OCR processing.14 unmodified lines# Convert to RGBpil_img = pil_img.convert("RGB")# Convert to base64 data URIbuf = io.BytesIO()pil_img.save(buf, format="PNG")107 unmodified linesimage_column: str = "image",batch_size: int = 16,max_model_len: int = 8192,max_tokens: int = 8192,temperature: float = 0.01,top_p: float = 0.00001,7 unmodified linesshuffle: bool = False,seed: int = 42,output_column: str = "markdown",verbose: bool = False,config: str = None,create_pr: bool = False,25 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")if shuffle:logger.info(f"Shuffling dataset with seed {seed}")dataset = dataset.shuffle(seed=seed)44 unmodified lines)try:batch_messages = [make_ocr_message(img, task=task) for img in batch_images]outputs = llm.chat(batch_messages, sampling_params)183 unmodified linesdefault=8192,help="Maximum model context length (default: 8192)",)parser.add_argument("--max-tokens",type=int,65 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--verbose",action="store_true",8 unmodified linesimage_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,7 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,verbose=args.verbose,config=args.config,create_pr=args.create_pr,1 unmodified line23456744 unmodified lines525354555657584 unmodified lines6364656667686970717219 unmodified lines929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014 unmodified lines155156157158159160161162163107 unmodified lines2712722732742752762777 unmodified lines28528628728828929029125 unmodified lines31731831932032132232332432544 unmodified lines370371372373374375376377378379183 unmodified lines56356456556656756856957057157257357457557657757857965 unmodified lines6456466476486496506516526536546556568 unmodified lines6656666676686696706717 unmodified lines6796806816826836846851 unmodified line# requires-python = ">=3.11"# dependencies = [# "datasets>=3.1.0",# "huggingface-hub",# "pillow",# "vllm",44 unmodified linesimport sysimport timefrom datetime import datetimefrom typing import Any, Dict, List, Optional, Unionimport torchfrom datasets import load_dataset4 unmodified lines# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")# Same story for DeepGEMM (nightly vLLM): its init calls _find_cuda_home, which asserts on the# nvcc-less base image (a non-fatal warning that clutters the log and hides the real traceback).# Greedy OCR doesn't need the DeepGEMM JIT path, so disable it explicitly.os.environ.setdefault("VLLM_USE_DEEP_GEMM", "0")from vllm import LLM, SamplingParamslogging.basicConfig(level=logging.INFO)19 unmodified lineslogger.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 clashingcolumn(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 datasetif 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 downscale_to_max_pixels(img: Image.Image, max_pixels: Optional[int]) -> Image.Image:"""Shrink an image so width*height <= max_pixels, preserving aspect ratio.GLM-OCR does no internal resizing and its card gives no resolution guidance. Cappinginput pixels bounds both image tokens and vision-encoder memory, a safety valve for verylarge (multi-MP) scans that can pressure GPU memory at high batch sizes. No-op whenmax_pixels is None or the image is already small enough (never upscales)."""if not max_pixels:return imgw, h = img.sizeif w * h <= max_pixels:return imgscale = (max_pixels / (w * h)) ** 0.5new_size = (max(1, int(w * scale)), max(1, int(h * scale)))return img.resize(new_size, Image.Resampling.LANCZOS)def make_ocr_message(image: Union[Image.Image, Dict[str, Any], str],task: str = "ocr",max_pixels: Optional[int] = None,) -> List[Dict]:"""Create chat message for OCR processing.14 unmodified lines# Convert to RGBpil_img = pil_img.convert("RGB")# Optionally cap resolution to protect the vision encoder from OOM on huge scanspil_img = downscale_to_max_pixels(pil_img, max_pixels)# Convert to base64 data URIbuf = io.BytesIO()pil_img.save(buf, format="PNG")107 unmodified linesimage_column: str = "image",batch_size: int = 16,max_model_len: int = 8192,max_pixels: Optional[int] = None,max_tokens: int = 8192,temperature: float = 0.01,top_p: float = 0.00001,7 unmodified linesshuffle: bool = False,seed: int = 42,output_column: str = "markdown",overwrite: bool = False,verbose: bool = False,config: str = None,create_pr: bool = False,25 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)if shuffle:logger.info(f"Shuffling dataset with seed {seed}")dataset = dataset.shuffle(seed=seed)44 unmodified lines)try:batch_messages = [make_ocr_message(img, task=task, max_pixels=max_pixels)for img in batch_images]outputs = llm.chat(batch_messages, sampling_params)183 unmodified linesdefault=8192,help="Maximum model context length (default: 8192)",)parser.add_argument("--max-pixels",type=int,default=None,help=("Optional cap on input image pixels (width*height); larger scans are ""downscaled (aspect preserved) before OCR. GLM-OCR does no internal resizing, ""so this bounds vision-encoder memory on very large scans — set e.g. 4000000 ""if you hit a GPU OOM at high batch sizes on a big-page corpus. Default: no cap."),)parser.add_argument("--max-tokens",type=int,65 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--verbose",action="store_true",8 unmodified linesimage_column=args.image_column,batch_size=args.batch_size,max_model_len=args.max_model_len,max_pixels=args.max_pixels,max_tokens=args.max_tokens,temperature=args.temperature,top_p=args.top_p,7 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,overwrite=args.overwrite,verbose=args.verbose,config=args.config,create_pr=args.create_pr,
76 unmodified lines777879808182203 unmodified lines28628728828929029123 unmodified lines315316317318319320237 unmodified lines55855956056156256356456565 unmodified lines63163263363463563621 unmodified lines65865966066166266376 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def resize_image_to_target(image: Image.Image, target_size: int = 1540) -> Image.Image:"""Resize image so longest dimension is target_size while maintaining aspect ratio.203 unmodified linesshuffle: bool = False,seed: int = 42,output_column: str = "markdown",config: str = None,create_pr: bool = False,verbose: bool = False,23 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")237 unmodified linesparser.add_argument("--max-model-len",type=int,default=8192,help="Maximum model context length (default: 8192)",)parser.add_argument("--max-tokens",65 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--verbose",action="store_true",21 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,config=args.config,create_pr=args.create_pr,verbose=args.verbose,76 unmodified lines7778798081828384858687888990919293949596979899100101102103104203 unmodified lines30830931031131231331423 unmodified lines338339340341342343344345346237 unmodified lines58458558658758858959059159259359459565 unmodified lines66166266366466566666766866967067167221 unmodified lines69469569669769869970076 unmodified lineslogger.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 clashingcolumn(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 datasetif 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 resize_image_to_target(image: Image.Image, target_size: int = 1540) -> Image.Image:"""Resize image so longest dimension is target_size while maintaining aspect ratio.203 unmodified linesshuffle: bool = False,seed: int = 42,output_column: str = "markdown",overwrite: bool = False,config: str = None,create_pr: bool = False,verbose: bool = False,23 unmodified linesf"Column '{image_column}' not found. Available: {dataset.column_names}")# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)# Shuffle if requestedif shuffle:logger.info(f"Shuffling dataset with seed {seed}")237 unmodified linesparser.add_argument("--max-model-len",type=int,default=16384,help=("Maximum model context length (default: 16384). A full page resized to ""1540px is ~6k image tokens; with --max-tokens 4096 output that overflows ""the old 8192 default at admission and vLLM rejects the request."),)parser.add_argument("--max-tokens",65 unmodified linesdefault="markdown",help="Column name for output text (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--verbose",action="store_true",21 unmodified linesshuffle=args.shuffle,seed=args.seed,output_column=args.output_column,overwrite=args.overwrite,config=args.config,create_pr=args.create_pr,verbose=args.verbose,
68 unmodified lines697071727374329 unmodified lines4044054064074084092 unmodified lines41241341441541641720 unmodified lines43843944044144244344444544644744844945045159 unmodified lines511512513514515516167 unmodified lines6846856866876886896908 unmodified lines69970070170270370434 unmodified lines73974074174274374474520 unmodified lines76676776876977077177251 unmodified lines82482582682782882913 unmodified lines84384484584684784882 unmodified lines93193293393493593678 unmodified lines10151016101710181019102068 unmodified linesimport jsonimport loggingimport osimport timefrom dataclasses import dataclassfrom datetime import datetime, timezone329 unmodified linescreate_pr: bool,source_id: str,original_dataset=None,):self.repo_id = repo_idself.hf_token = hf_token2 unmodified linesself.create_pr = create_prself.source_id = source_idself.original_dataset = original_datasetself._texts: List[str] = []self._blocks: List[str] = []20 unmodified lineswhile len(self._texts) < len(self.original_dataset):self._texts.append("")self._blocks.append("[]")ds = self.original_dataset.add_column("text", self._texts)ds = ds.add_column("pp_ocr_blocks", self._blocks)else:if not self._texts:logger.warning("No rows produced; nothing to push.")returnds = Dataset.from_list([{"source_path": None, "text": t, "pp_ocr_blocks": b}for t, b in zip(self._texts, self._blocks)])59 unmodified linesprocessing_time=args_dict["processing_time"],engine=args_dict.get("engine", "paddle_static"),output_id=self.repo_id,))card.push_to_hub(self.repo_id, token=self.hf_token)167 unmodified lines"rec_accuracy_pct": TIER_REC.get(tier),"languages": TIER_LANGUAGES.get(tier, ""),"engine": "paddle_static","output_column": "text","blocks_column": "pp_ocr_blocks","timestamp": datetime.now(timezone.utc).isoformat(),}8 unmodified linesprocessing_time: str,engine: str,output_id: str,) -> str:tier_display = tier.upper() if tier == "tiny" else tier.capitalize()if is_bucket_url(source):34 unmodified linesEach row contains the original columns plus:- `text`: Plain text extracted from the image (reading-order concatenation ofdetected text lines, newline-separated).- `pp_ocr_blocks`: JSON list, one dict per detected text line:```json20 unmodified linesfrom datasets import load_datasetds = load_dataset("{output_id}", split="train")print(ds[0]["text"])for block in json.loads(ds[0]["pp_ocr_blocks"]):print(block["text"], block["score"])```51 unmodified linesseed=args.seed,max_samples=args.max_samples,)# ---------- sink ----------if is_bucket_url(args.output_target):13 unmodified linescreate_pr=args.create_pr,source_id=args.input_source,original_dataset=original_dataset,)completed = sink.already_done()82 unmodified lines"engine": "paddle_static","shard_size": args.shard_size,"processing_time": processing_time_str,}sink.finalize(tier=tier,78 unmodified linesaction="store_true",help="Create PR instead of direct push (dataset sink only)",)# Bucket-sink-specificp.add_argument("--shard-size",68 unmodified lines69707172737475329 unmodified lines4054064074084094104114122 unmodified lines41541641741841942042142220 unmodified lines44344444544644744844945045145245345445545645745845946046146246346446546646759 unmodified lines527528529530531532533167 unmodified lines7017027037047057067078 unmodified lines71671771871972072172234 unmodified lines75775875976076176276320 unmodified lines78478578678778878979051 unmodified lines84284384484584684784884985085185285385485585685785885986086186286386486586686786813 unmodified lines88288388488588688788888982 unmodified lines97297397497597697797878 unmodified lines105710581059106010611062106310641065106610671068106910701071107210731074107510761077107868 unmodified linesimport jsonimport loggingimport osimport sysimport timefrom dataclasses import dataclassfrom datetime import datetime, timezone329 unmodified linescreate_pr: bool,source_id: str,original_dataset=None,output_column: str = "markdown",overwrite: bool = False,):self.repo_id = repo_idself.hf_token = hf_token2 unmodified linesself.create_pr = create_prself.source_id = source_idself.original_dataset = original_datasetself.output_column = output_columnself.overwrite = overwriteself._texts: List[str] = []self._blocks: List[str] = []20 unmodified lineswhile len(self._texts) < len(self.original_dataset):self._texts.append("")self._blocks.append("[]")# Guard again at save time in case the input column set changed under us.base = self.original_datasetclash = [c for c in (self.output_column, "pp_ocr_blocks") if c in base.column_names]if clash:if not self.overwrite:raise ValueError(f"Output column(s) {clash} already exist in the input dataset; "f"pass a different --output-column, or --overwrite to replace them.")logger.warning(f"--overwrite: replacing existing column(s) {clash}")base = base.remove_columns(clash)ds = base.add_column(self.output_column, self._texts)ds = ds.add_column("pp_ocr_blocks", self._blocks)else:if not self._texts:logger.warning("No rows produced; nothing to push.")returnds = Dataset.from_list([{"source_path": None, self.output_column: t, "pp_ocr_blocks": b}for t, b in zip(self._texts, self._blocks)])59 unmodified linesprocessing_time=args_dict["processing_time"],engine=args_dict.get("engine", "paddle_static"),output_id=self.repo_id,output_column=self.output_column,))card.push_to_hub(self.repo_id, token=self.hf_token)167 unmodified lines"rec_accuracy_pct": TIER_REC.get(tier),"languages": TIER_LANGUAGES.get(tier, ""),"engine": "paddle_static","output_column": args_dict.get("output_column", "markdown"),"blocks_column": "pp_ocr_blocks","timestamp": datetime.now(timezone.utc).isoformat(),}8 unmodified linesprocessing_time: str,engine: str,output_id: str,output_column: str = "markdown",) -> str:tier_display = tier.upper() if tier == "tiny" else tier.capitalize()if is_bucket_url(source):34 unmodified linesEach row contains the original columns plus:- `{output_column}`: Plain text extracted from the image (reading-order concatenation ofdetected text lines, newline-separated).- `pp_ocr_blocks`: JSON list, one dict per detected text line:```json20 unmodified linesfrom datasets import load_datasetds = load_dataset("{output_id}", split="train")print(ds[0]["{output_column}"])for block in json.loads(ds[0]["pp_ocr_blocks"]):print(block["text"], block["score"])```51 unmodified linesseed=args.seed,max_samples=args.max_samples,)# Fail fast, before minutes of inference, if the output column would collide# with an existing input column (e.g. a 'text' ground-truth column). Writing# into it would either crash on push or silently overwrite the input data.# --overwrite opts in to replacing the existing column(s) instead of erroring.if original_dataset is not None:clash = [colfor col in (args.output_column, "pp_ocr_blocks")if col in original_dataset.column_names]if clash and not args.overwrite:logger.error(f"Output column(s) {clash} already exist in the input dataset "f"(columns: {original_dataset.column_names}).")logger.error("Choose a different --output-column, or pass --overwrite to replace them.")sys.exit(1)if clash:logger.warning(f"--overwrite: will replace existing column(s) {clash}")# ---------- sink ----------if is_bucket_url(args.output_target):13 unmodified linescreate_pr=args.create_pr,source_id=args.input_source,original_dataset=original_dataset,output_column=args.output_column,overwrite=args.overwrite,)completed = sink.already_done()82 unmodified lines"engine": "paddle_static","shard_size": args.shard_size,"processing_time": processing_time_str,"output_column": args.output_column,}sink.finalize(tier=tier,78 unmodified linesaction="store_true",help="Create PR instead of direct push (dataset sink only)",)p.add_argument("--output-column",default="markdown",help=("Column name for the recognized text (dataset sink only, default: markdown). ""Must not collide with an existing input column — many corpora already ship a ""'text' ground-truth column, so 'text' would fail on push. Blocks always go to ""'pp_ocr_blocks'."),)p.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).",)# Bucket-sink-specificp.add_argument("--shard-size",
103 unmodified lines104105106107108109334 unmodified lines44444544644744844919 unmodified lines46947047147247347420 unmodified lines495496497498499500254 unmodified lines75575675775875976075 unmodified lines836837838839840841103 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def parse_page_range(spec: Optional[str]) -> Optional[List[int]]:"""Turn '0-3,5' into [0,1,2,3,5]. None/empty -> None (all pages)."""if not spec:334 unmodified linesimage_column: str = "image",pdf_column: Optional[str] = None,output_column: str = "markdown",blocks_column: str = "surya_blocks",page_range: Optional[str] = None,split: str = "train",19 unmodified linesos.environ["SURYA_INFERENCE_AUTOSTART"] = "False"check_cuda_availability()start_time = datetime.now(timezone.utc)HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")20 unmodified linesf"Column '{source_column}' not found. Available: {dataset.column_names}")sys.exit(1)if shuffle:dataset = dataset.shuffle(seed=seed)if max_samples:254 unmodified linesdefault="markdown",help="Text output column (default: markdown)",)parser.add_argument("--blocks-column",default="surya_blocks",75 unmodified linesimage_column=args.image_column,pdf_column=args.pdf_column,output_column=args.output_column,blocks_column=args.blocks_column,page_range=args.page_range,split=args.split,103 unmodified lines104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156334 unmodified lines49149249349449549649719 unmodified lines51751851952052152252320 unmodified lines544545546547548549550551552553254 unmodified lines80880981081181281381481581681781881975 unmodified lines895896897898899900901103 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def check_vllm_available() -> None:"""Fail fast (before loading 400 rows) if vLLM isn't importable.Surya-2 runs its VLM through vLLM's offline engine, but `vllm` is deliberatelyNOT a PEP723 dependency: the recent hybrid `qwen3_5` architecture is only in thepinned `vllm/vllm-openai:v0.20.1` image, which also provides torch/transformers viaPYTHONPATH. Launched on the bare uv image (no `--image`), the import fails per-batchand every row silently gets "[SURYA GENERATE ERROR]". Detect that up front instead."""import importlib.utilif importlib.util.find_spec("vllm") is None:logger.error("vLLM is not importable — this recipe cannot run on the bare uv image.")logger.error("Surya-2 needs the pinned vLLM build; re-run with the image + interpreter flags:")logger.error(" hf jobs uv run --flavor l4x1 -s HF_TOKEN \\\n"" --image vllm/vllm-openai:v0.20.1 --python /usr/local/bin/python3 \\\n"" -e PYTHONPATH=/usr/local/lib/python3.12/site-packages \\\n"" <script_url> INPUT_DATASET OUTPUT_DATASET ...")sys.exit(1)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 clashingcolumn(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 datasetif 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 parse_page_range(spec: Optional[str]) -> Optional[List[int]]:"""Turn '0-3,5' into [0,1,2,3,5]. None/empty -> None (all pages)."""if not spec:334 unmodified linesimage_column: str = "image",pdf_column: Optional[str] = None,output_column: str = "markdown",overwrite: bool = False,blocks_column: str = "surya_blocks",page_range: Optional[str] = None,split: str = "train",19 unmodified linesos.environ["SURYA_INFERENCE_AUTOSTART"] = "False"check_cuda_availability()check_vllm_available()start_time = datetime.now(timezone.utc)HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")20 unmodified linesf"Column '{source_column}' not found. Available: {dataset.column_names}")sys.exit(1)# Fail fast if the output column would collide with an existing input columndataset = ensure_output_columns_free(dataset, [output_column, blocks_column], overwrite=overwrite)if shuffle:dataset = dataset.shuffle(seed=seed)if max_samples:254 unmodified linesdefault="markdown",help="Text output column (default: markdown)",)parser.add_argument("--overwrite",action="store_true",help="Replace the output column if it already exists in the input dataset ""(default: error out to avoid clobbering an existing column).",)parser.add_argument("--blocks-column",default="surya_blocks",75 unmodified linesimage_column=args.image_column,pdf_column=args.pdf_column,output_column=args.output_column,overwrite=args.overwrite,blocks_column=args.blocks_column,page_range=args.page_range,split=args.split,
CLAUDE.md+123-1
dots-ocr.py+58-4
glm-ocr.py+76-3
lighton-ocr2.py+39-2
pp-ocrv6.py+63-5
surya-ocr.py+60