Sync from GitHub via hub-sync
Browse files- 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 -0
CLAUDE.md
CHANGED
|
@@ -1,5 +1,101 @@
|
|
| 1 |
# OCR Scripts - Development Notes
|
| 2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
## Active Scripts
|
| 4 |
|
| 5 |
### DeepSeek-OCR v1 (`deepseek-ocr-vllm.py`)
|
|
@@ -290,7 +386,33 @@ need **+** the h200/`fa3` infra fix (for exact R-SWA quality). Single-image vLLM
|
|
| 290 |
the batch default.
|
| 291 |
|
| 292 |
### Nanonets OCR (`nanonets-ocr.py`, `nanonets-ocr2.py`)
|
| 293 |
-
✅
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
|
| 295 |
### PaddleOCR-VL (`paddleocr-vl.py`)
|
| 296 |
✅ Working
|
|
|
|
| 1 |
# OCR Scripts - Development Notes
|
| 2 |
|
| 3 |
+
## Large full-page scan fixes (2026-07-01)
|
| 4 |
+
|
| 5 |
+
A batch of scripts run over a **large**-page historical book-scan corpus (WebP, ~2000–4000px /
|
| 6 |
+
7–9 MP) exposed 5 failures. Root-caused + fixed + verified on Jobs (l4x1, `--max-samples 4–16` on
|
| 7 |
+
that corpus). `deepseek-ocr-vllm.py` / `paddleocr-vl-1.6.py` were unaffected.
|
| 8 |
+
|
| 9 |
+
> ⚠️ **Gotcha for testing on such corpora:** some eval sets already ship `text`, `markdown`,
|
| 10 |
+
> `docling`, `xml` columns, so **every** default `--output-column` collides — pass a distinct one
|
| 11 |
+
> (e.g. `--output-column ocr_md`) on *all* the markdown-default scripts, not just pp-ocrv6.
|
| 12 |
+
|
| 13 |
+
- **`surya-ocr.py` — silent per-row `[SURYA GENERATE ERROR]`, log `No module named 'vllm'`.**
|
| 14 |
+
Working as designed (deps omit `vllm`; needs `--image vllm/vllm-openai:v0.20.1` — see its own section
|
| 15 |
+
below); the batch run just dropped the image flags. **Fix:** added a `check_vllm_available()` preflight
|
| 16 |
+
that `sys.exit(1)`s with the exact required flags **before** processing, instead of writing 400 silent
|
| 17 |
+
sentinels. `--max-model-len` was already 18000. Verified: bare-image run now fails fast.
|
| 18 |
+
- **`dots-ocr.py` — `[OCR ERROR]` on large pages (small pages OK).** No image resize; a 7–9 MP page →
|
| 19 |
+
up to ~14k image tokens (model's 11.29M-px processor cap) > the old `--max-model-len 8192` → vLLM
|
| 20 |
+
rejects → sentinel. **Fix:** default `--max-model-len` 8192→**32768** + new optional `--max-pixels`
|
| 21 |
+
(mm_processor cap). Verified 4/4 real OCR (matches GT; v1 works with the auto-detected `openai` chat
|
| 22 |
+
format — the dots-1.5 `content_format="string"` fix does **not** apply to v1).
|
| 23 |
+
- **`lighton-ocr2.py` — `[OCR ERROR]` on large pages.** Its 1540px resize is correct, but ~6k image
|
| 24 |
+
tokens **+ `--max-tokens 4096`** > `--max-model-len 8192` at admission. **Fix:** default
|
| 25 |
+
`--max-model-len` 8192→**16384**. Verified 4/4 real OCR on l4x1.
|
| 26 |
+
- **`glm-ocr.py` — whole JOB ERROR.** The *current* blocker was **not** OOM: glm pinned
|
| 27 |
+
`pyarrow>=17.0.0,<18.0.0`, but `datasets>=5.0.0` (which understands this dataset's `Json` feature
|
| 28 |
+
type) needs `pyarrow>=21`, so uv resolved `datasets 4.0.0` and `load_dataset` threw
|
| 29 |
+
`ValueError: Feature type 'Json' not found` (this is the 3-second startup ERROR seen in job history;
|
| 30 |
+
dots/lighton don't pin pyarrow, so they loaded fine). **Fix:** dropped the pyarrow pin. Also added
|
| 31 |
+
`VLLM_USE_DEEP_GEMM=0` (silences the non-fatal deep_gemm assertion on the nvcc-less nightly image) and
|
| 32 |
+
an **optional** `--max-pixels` cap. Verified: loads + completes 16/16 large pages, and **did NOT OOM
|
| 33 |
+
at defaults** (batch 16, no cap) — so `--max-pixels` stays an opt-in memory safety-valve, not a
|
| 34 |
+
default (the original "30-min OOM" didn't reproduce on 16 pages; it likely needed a specific
|
| 35 |
+
page/batch deep in a 400-row run). glm is chatty on blank pages / can emit degenerate repeats, but
|
| 36 |
+
that's model quality, not the crash.
|
| 37 |
+
- **`pp-ocrv6.py` — crash on SAVE: duplicated column `['text']`.** Hardcoded output to `text` with **no**
|
| 38 |
+
`--output-column` flag; the corpus already has a `text` column. **Fix:** added `--output-column`
|
| 39 |
+
(default `markdown`, matching siblings) threaded through the sink + card + inference_info, plus a
|
| 40 |
+
**fast-fail startup guard** (`sys.exit(1)` before inference) if the chosen output column — or
|
| 41 |
+
`pp_ocr_blocks` — already exists in the input, so it never silently overwrites ground truth. Verified:
|
| 42 |
+
guard fires on the colliding default; `--output-column ocr_md` pushes cleanly.
|
| 43 |
+
|
| 44 |
+
### Cross-cutting notes
|
| 45 |
+
- **Output-column collision guard (rolled out to ALL ~31 output-writing scripts, 2026-07-01):**
|
| 46 |
+
generalises the pp-ocrv6 fix. A shared `ensure_output_columns_free(dataset, columns, overwrite=False)`
|
| 47 |
+
helper (copied into each standalone script — no shared lib in this repo) fails fast at startup if an
|
| 48 |
+
output column already exists in the input, instead of silently building a duplicate that crashes on
|
| 49 |
+
push *after* inference (or clobbering a ground-truth column). New `--overwrite` flag opts in to
|
| 50 |
+
replacing it. surya guards both `output_column` + `blocks_column`; the sink scripts (pp-ocrv6,
|
| 51 |
+
pp-doclayout) carry the equivalent guard inline. The 5 scripts that hardcoded `"markdown"`
|
| 52 |
+
(nanonets-ocr/-ocr2, abot-ocr, deepseek-ocr/-ocr-vllm) also gained a configurable `--output-column`.
|
| 53 |
+
Static-verified (ruff + AST + wiring) on all; the pattern is Jobs-proven via pp-ocrv6.
|
| 54 |
+
- **Error signalling (#6 — documented, NOT implemented this pass):** ~39 sentinel-string sites
|
| 55 |
+
(`[OCR ERROR]`, `[SURYA GENERATE ERROR]`, …) across ~20 scripts write the sentinel *into* the OCR
|
| 56 |
+
column, so partial failures are silent and pollute downstream metrics. **Proposed follow-up:** leave
|
| 57 |
+
the OCR cell null/empty on failure and record the truncated exception in a companion `ocr_error`
|
| 58 |
+
column, so "model read nothing" is distinguishable from "the run errored." Deferred — would touch all
|
| 59 |
+
~20 standalone scripts (no shared lib).
|
| 60 |
+
- **`--max-model-len` policy:** the durable fix is to **bound the input** (image cap) and size context
|
| 61 |
+
to that bound + output — what the working `paddleocr-vl-1.6.py` (~1M-px smart resize) and `surya-ocr.py`
|
| 62 |
+
(max_pixels + 18000) already do. The per-script default bumps above are the minimal version. Don't
|
| 63 |
+
auto-size `max_model_len` from images (it's fixed at engine init, before images are seen).
|
| 64 |
+
- **Context-length invariant (must hold for every vLLM recipe):**
|
| 65 |
+
`--max-tokens` ≤ `--max-model-len` ≤ the model's real max context. The real max is the language
|
| 66 |
+
model's `max_position_embeddings` in `config.json` (VLMs: usually under `text_config`/`language_config`,
|
| 67 |
+
adjusted by any `rope_scaling`). If `max_model_len` > that, vLLM refuses to start (we don't set
|
| 68 |
+
`VLLM_ALLOW_LONG_MAX_MODEL_LEN`); if `max_tokens` > `max_model_len`, the output alone can't fit.
|
| 69 |
+
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'))"`.
|
| 70 |
+
Audited 2026-07-01 across all vLLM recipes: none exceed their window (dots-ocr 32768/131072 ✓,
|
| 71 |
+
lighton-ocr2 16384/16384 = at cap/zero headroom ✓); fixed `nanonets-ocr.py` (had `max_tokens 15000`
|
| 72 |
+
> `max_model_len 8192` → raised default to 32768).
|
| 73 |
+
|
| 74 |
+
### Future: "self-review a new/changed OCR recipe" skill (spark, 2026-07-01)
|
| 75 |
+
A **dev-only skill** (sibling to `bump-vllm-pins`) that reviews an OCR recipe (a given script or the
|
| 76 |
+
current diff / `--all`) against the invariants this repo keeps re-learning, so a new recipe or a bumped
|
| 77 |
+
default is caught **before** it ships. Mostly a **static** check (fast, no compute); each maps to a
|
| 78 |
+
concrete failure we've hit:
|
| 79 |
+
|
| 80 |
+
1. **Context-length** — `--max-tokens` ≤ `--max-model-len` ≤ model `config.json` `max_position_embeddings`
|
| 81 |
+
(fetch the config; VLMs → `text_config`, mind `rope_scaling`). Catches vLLM-won't-start and
|
| 82 |
+
output-can't-fit (found `nanonets-ocr.py`).
|
| 83 |
+
2. **Output-column collision guard** — has `ensure_output_columns_free` (or the inline sink guard) +
|
| 84 |
+
`--overwrite`, and `--output-column` default isn't a bare hardcoded name that clobbers input.
|
| 85 |
+
3. **vLLM image / preflight** — if the arch isn't in a stable wheel, deps omit `vllm`/`torch` AND there's
|
| 86 |
+
a fail-fast preflight naming the required `--image`/`--python`/`PYTHONPATH` (surya-class).
|
| 87 |
+
4. **Env guards on the bare image** — `VLLM_USE_FLASHINFER_SAMPLER=0` (and `VLLM_USE_DEEP_GEMM=0` for
|
| 88 |
+
nightly vLLM) set before importing vllm.
|
| 89 |
+
5. **Dep sanity** — no stale caps that drag a transitive lib back (e.g. `pyarrow<18` → old `datasets`
|
| 90 |
+
lacking the `Json` feature → `load_dataset` crash, the glm-ocr bug).
|
| 91 |
+
6. **Large-image bounding** — full-page recipes cap input pixels / resize, or size `max_model_len` to fit.
|
| 92 |
+
7. **(optional) Jobs smoke** — only after the static checks pass, run on a tiny hard-input set (the
|
| 93 |
+
smoke-test dataset **+** a large 7–9 MP page) on l4x1, poll to terminal, and classify any failure
|
| 94 |
+
into the catalogued buckets (missing-vllm/wrong-image, collision, context-overflow `[OCR ERROR]`,
|
| 95 |
+
encoder OOM, dep-drift) with remedies.
|
| 96 |
+
|
| 97 |
+
Pairs with the "OCR Smoke Test Dataset" idea below. Build after the current fixes land.
|
| 98 |
+
|
| 99 |
## Active Scripts
|
| 100 |
|
| 101 |
### DeepSeek-OCR v1 (`deepseek-ocr-vllm.py`)
|
|
|
|
| 386 |
the batch default.
|
| 387 |
|
| 388 |
### Nanonets OCR (`nanonets-ocr.py`, `nanonets-ocr2.py`)
|
| 389 |
+
✅ `nanonets-ocr.py` working.
|
| 390 |
+
|
| 391 |
+
**`nanonets-ocr2.py` — ⚠️ requires pinned vLLM image `vllm/vllm-openai:v0.10.2` (fixed 2026-06-30).**
|
| 392 |
+
Nanonets-OCR2-3B is a **Qwen2.5-VL** model. On a floating `vllm` pin (resolved to **0.24.0**) it
|
| 393 |
+
decoded **pure `!` on every page** — the documented vLLM **>=0.11 Qwen2.5-VL regression**
|
| 394 |
+
([vllm#27775](https://github.com/vllm-project/vllm/issues/27775),
|
| 395 |
+
[#14126](https://github.com/vllm-project/vllm/issues/14126); 0.9.2/0.10.1/**0.10.2** are the
|
| 396 |
+
known-good builds). Ruled out along the way: it is **not** context length (still `!` at
|
| 397 |
+
`max_model_len=32768`) and **not** torch.compile (still `!` with `enforce_eager=True`). Pip-pinning
|
| 398 |
+
`vllm==0.10.2` alone fails — its old tokenizer API (`Qwen2Tokenizer.all_special_tokens_extended`)
|
| 399 |
+
clashes with modern `transformers` 5.x. **Fix:** run on the **`vllm/vllm-openai:v0.10.2` image**
|
| 400 |
+
(ships a consistent vLLM 0.10.2 + transformers 4.56.1); `vllm` and `torch` are omitted from the PEP
|
| 401 |
+
723 deps and come from the image via `PYTHONPATH`. Also bumped the `--max-model-len` default
|
| 402 |
+
8192→32768 (the script's `--max-tokens` default is 15000 per the model card, which an 8192 context
|
| 403 |
+
can't hold). Standard `/usr/bin/python3` + `dist-packages` image layout (probed). Re-test the pin
|
| 404 |
+
when a newer vLLM ships a Qwen2.5-VL decode fix → it can move back to the default image.
|
| 405 |
+
|
| 406 |
+
**Smoke test (2026-06-30, `davanstrien/ufo-ColPali`, 5 samples, a10g-small):** 5/5 clean markdown
|
| 407 |
+
(English + Spanish, `<header>`/`<img>` semantic tags), 0 degenerate rows. Output
|
| 408 |
+
`davanstrien/nanonets-ocr2-img0102-test`.
|
| 409 |
+
|
| 410 |
+
```bash
|
| 411 |
+
hf jobs uv run --flavor a10g-small -s HF_TOKEN \
|
| 412 |
+
--image vllm/vllm-openai:v0.10.2 --python /usr/bin/python3 \
|
| 413 |
+
-e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \
|
| 414 |
+
./ocr/nanonets-ocr2.py INPUT_DATASET OUTPUT_DATASET --max-samples 10 --shuffle --seed 42
|
| 415 |
+
```
|
| 416 |
|
| 417 |
### PaddleOCR-VL (`paddleocr-vl.py`)
|
| 418 |
✅ Working
|
dots-ocr.py
CHANGED
|
@@ -93,6 +93,28 @@ def check_cuda_availability():
|
|
| 93 |
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
|
| 94 |
|
| 95 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
def make_ocr_message(
|
| 97 |
image: Union[Image.Image, Dict[str, Any], str],
|
| 98 |
prompt: str = PROMPT_TEMPLATES["ocr"],
|
|
@@ -239,7 +261,8 @@ def main(
|
|
| 239 |
image_column: str = "image",
|
| 240 |
batch_size: int = 16,
|
| 241 |
model: str = "rednote-hilab/dots.ocr",
|
| 242 |
-
max_model_len: int =
|
|
|
|
| 243 |
max_tokens: int = 8192,
|
| 244 |
gpu_memory_utilization: float = 0.8,
|
| 245 |
hf_token: str = None,
|
|
@@ -251,6 +274,7 @@ def main(
|
|
| 251 |
prompt_mode: str = "ocr",
|
| 252 |
custom_prompt: str = None,
|
| 253 |
output_column: str = "markdown",
|
|
|
|
| 254 |
config: str = None,
|
| 255 |
create_pr: bool = False,
|
| 256 |
):
|
|
@@ -285,6 +309,9 @@ def main(
|
|
| 285 |
f"Column '{image_column}' not found. Available: {dataset.column_names}"
|
| 286 |
)
|
| 287 |
|
|
|
|
|
|
|
|
|
|
| 288 |
# Shuffle if requested
|
| 289 |
if shuffle:
|
| 290 |
logger.info(f"Shuffling dataset with seed {seed}")
|
|
@@ -298,13 +325,17 @@ def main(
|
|
| 298 |
# Initialize vLLM model
|
| 299 |
logger.info(f"Initializing vLLM with model: {model}")
|
| 300 |
logger.info("This may take a few minutes on first run...")
|
| 301 |
-
|
| 302 |
model=model,
|
| 303 |
trust_remote_code=True,
|
| 304 |
max_model_len=max_model_len,
|
| 305 |
gpu_memory_utilization=gpu_memory_utilization,
|
| 306 |
limit_mm_per_prompt={"image": 1},
|
| 307 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
|
| 309 |
sampling_params = SamplingParams(
|
| 310 |
temperature=0.0, # Deterministic for OCR
|
|
@@ -509,8 +540,23 @@ Examples:
|
|
| 509 |
parser.add_argument(
|
| 510 |
"--max-model-len",
|
| 511 |
type=int,
|
| 512 |
-
default=
|
| 513 |
-
help=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 514 |
)
|
| 515 |
parser.add_argument(
|
| 516 |
"--max-tokens",
|
|
@@ -560,6 +606,12 @@ Examples:
|
|
| 560 |
default="markdown",
|
| 561 |
help="Column name for output text (default: markdown)",
|
| 562 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 563 |
parser.add_argument(
|
| 564 |
"--config",
|
| 565 |
help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
|
|
@@ -579,6 +631,7 @@ Examples:
|
|
| 579 |
batch_size=args.batch_size,
|
| 580 |
model=args.model,
|
| 581 |
max_model_len=args.max_model_len,
|
|
|
|
| 582 |
max_tokens=args.max_tokens,
|
| 583 |
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 584 |
hf_token=args.hf_token,
|
|
@@ -590,6 +643,7 @@ Examples:
|
|
| 590 |
prompt_mode=args.prompt_mode,
|
| 591 |
custom_prompt=args.custom_prompt,
|
| 592 |
output_column=args.output_column,
|
|
|
|
| 593 |
config=args.config,
|
| 594 |
create_pr=args.create_pr,
|
| 595 |
)
|
|
|
|
| 93 |
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
|
| 94 |
|
| 95 |
|
| 96 |
+
def ensure_output_columns_free(dataset, columns, overwrite=False):
|
| 97 |
+
"""Fail fast if an output column would collide with an existing input column.
|
| 98 |
+
|
| 99 |
+
Adding a column that already exists silently overwrites it (e.g. a ground-truth
|
| 100 |
+
`text`/`markdown` column) or crashes on push with a duplicate-column error only
|
| 101 |
+
*after* inference has run. Catch it up front. With overwrite=True, drop the clashing
|
| 102 |
+
column(s) here instead (logged) so the later add_column is clean.
|
| 103 |
+
"""
|
| 104 |
+
clash = [c for c in columns if c in dataset.column_names]
|
| 105 |
+
if not clash:
|
| 106 |
+
return dataset
|
| 107 |
+
if overwrite:
|
| 108 |
+
logger.warning(f"--overwrite: replacing existing column(s) {clash}")
|
| 109 |
+
return dataset.remove_columns(clash)
|
| 110 |
+
logger.error(
|
| 111 |
+
f"Output column(s) {clash} already exist in the input dataset "
|
| 112 |
+
f"(columns: {dataset.column_names})."
|
| 113 |
+
)
|
| 114 |
+
logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
|
| 115 |
+
sys.exit(1)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
def make_ocr_message(
|
| 119 |
image: Union[Image.Image, Dict[str, Any], str],
|
| 120 |
prompt: str = PROMPT_TEMPLATES["ocr"],
|
|
|
|
| 261 |
image_column: str = "image",
|
| 262 |
batch_size: int = 16,
|
| 263 |
model: str = "rednote-hilab/dots.ocr",
|
| 264 |
+
max_model_len: int = 32768,
|
| 265 |
+
max_pixels: int = None,
|
| 266 |
max_tokens: int = 8192,
|
| 267 |
gpu_memory_utilization: float = 0.8,
|
| 268 |
hf_token: str = None,
|
|
|
|
| 274 |
prompt_mode: str = "ocr",
|
| 275 |
custom_prompt: str = None,
|
| 276 |
output_column: str = "markdown",
|
| 277 |
+
overwrite: bool = False,
|
| 278 |
config: str = None,
|
| 279 |
create_pr: bool = False,
|
| 280 |
):
|
|
|
|
| 309 |
f"Column '{image_column}' not found. Available: {dataset.column_names}"
|
| 310 |
)
|
| 311 |
|
| 312 |
+
# Fail fast if the output column would collide with an existing input column
|
| 313 |
+
dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
|
| 314 |
+
|
| 315 |
# Shuffle if requested
|
| 316 |
if shuffle:
|
| 317 |
logger.info(f"Shuffling dataset with seed {seed}")
|
|
|
|
| 325 |
# Initialize vLLM model
|
| 326 |
logger.info(f"Initializing vLLM with model: {model}")
|
| 327 |
logger.info("This may take a few minutes on first run...")
|
| 328 |
+
llm_kwargs = dict(
|
| 329 |
model=model,
|
| 330 |
trust_remote_code=True,
|
| 331 |
max_model_len=max_model_len,
|
| 332 |
gpu_memory_utilization=gpu_memory_utilization,
|
| 333 |
limit_mm_per_prompt={"image": 1},
|
| 334 |
)
|
| 335 |
+
if max_pixels is not None:
|
| 336 |
+
logger.info(f"Capping input images to max_pixels={max_pixels}")
|
| 337 |
+
llm_kwargs["mm_processor_kwargs"] = {"max_pixels": max_pixels}
|
| 338 |
+
llm = LLM(**llm_kwargs)
|
| 339 |
|
| 340 |
sampling_params = SamplingParams(
|
| 341 |
temperature=0.0, # Deterministic for OCR
|
|
|
|
| 540 |
parser.add_argument(
|
| 541 |
"--max-model-len",
|
| 542 |
type=int,
|
| 543 |
+
default=32768,
|
| 544 |
+
help=(
|
| 545 |
+
"Maximum model context length (default: 32768). dots.ocr does NOT resize "
|
| 546 |
+
"input images, so a full page can reach ~14k image tokens (the model's "
|
| 547 |
+
"11.29M-px processor cap); the old 8192 default rejected such requests and "
|
| 548 |
+
"the row was written as '[OCR ERROR]'. Pair with --max-pixels to cap memory."
|
| 549 |
+
),
|
| 550 |
+
)
|
| 551 |
+
parser.add_argument(
|
| 552 |
+
"--max-pixels",
|
| 553 |
+
type=int,
|
| 554 |
+
default=None,
|
| 555 |
+
help=(
|
| 556 |
+
"Optional cap on input image pixels (width*height) passed to vLLM's "
|
| 557 |
+
"mm_processor. Lower this (e.g. 4000000) to bound image tokens and GPU "
|
| 558 |
+
"memory on very large scans. Default: model's own cap (~11.29M px)."
|
| 559 |
+
),
|
| 560 |
)
|
| 561 |
parser.add_argument(
|
| 562 |
"--max-tokens",
|
|
|
|
| 606 |
default="markdown",
|
| 607 |
help="Column name for output text (default: markdown)",
|
| 608 |
)
|
| 609 |
+
parser.add_argument(
|
| 610 |
+
"--overwrite",
|
| 611 |
+
action="store_true",
|
| 612 |
+
help="Replace the output column if it already exists in the input dataset "
|
| 613 |
+
"(default: error out to avoid clobbering an existing column).",
|
| 614 |
+
)
|
| 615 |
parser.add_argument(
|
| 616 |
"--config",
|
| 617 |
help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
|
|
|
|
| 631 |
batch_size=args.batch_size,
|
| 632 |
model=args.model,
|
| 633 |
max_model_len=args.max_model_len,
|
| 634 |
+
max_pixels=args.max_pixels,
|
| 635 |
max_tokens=args.max_tokens,
|
| 636 |
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 637 |
hf_token=args.hf_token,
|
|
|
|
| 643 |
prompt_mode=args.prompt_mode,
|
| 644 |
custom_prompt=args.custom_prompt,
|
| 645 |
output_column=args.output_column,
|
| 646 |
+
overwrite=args.overwrite,
|
| 647 |
config=args.config,
|
| 648 |
create_pr=args.create_pr,
|
| 649 |
)
|
glm-ocr.py
CHANGED
|
@@ -2,7 +2,6 @@
|
|
| 2 |
# requires-python = ">=3.11"
|
| 3 |
# dependencies = [
|
| 4 |
# "datasets>=3.1.0",
|
| 5 |
-
# "pyarrow>=17.0.0,<18.0.0",
|
| 6 |
# "huggingface-hub",
|
| 7 |
# "pillow",
|
| 8 |
# "vllm",
|
|
@@ -53,7 +52,7 @@ import os
|
|
| 53 |
import sys
|
| 54 |
import time
|
| 55 |
from datetime import datetime
|
| 56 |
-
from typing import Any, Dict, List, Union
|
| 57 |
|
| 58 |
import torch
|
| 59 |
from datasets import load_dataset
|
|
@@ -64,6 +63,10 @@ from toolz import partition_all
|
|
| 64 |
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 65 |
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 66 |
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
from vllm import LLM, SamplingParams
|
| 68 |
|
| 69 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -89,9 +92,49 @@ def check_cuda_availability():
|
|
| 89 |
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
|
| 90 |
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
def make_ocr_message(
|
| 93 |
image: Union[Image.Image, Dict[str, Any], str],
|
| 94 |
task: str = "ocr",
|
|
|
|
| 95 |
) -> List[Dict]:
|
| 96 |
"""
|
| 97 |
Create chat message for OCR processing.
|
|
@@ -112,6 +155,9 @@ def make_ocr_message(
|
|
| 112 |
# Convert to RGB
|
| 113 |
pil_img = pil_img.convert("RGB")
|
| 114 |
|
|
|
|
|
|
|
|
|
|
| 115 |
# Convert to base64 data URI
|
| 116 |
buf = io.BytesIO()
|
| 117 |
pil_img.save(buf, format="PNG")
|
|
@@ -225,6 +271,7 @@ def main(
|
|
| 225 |
image_column: str = "image",
|
| 226 |
batch_size: int = 16,
|
| 227 |
max_model_len: int = 8192,
|
|
|
|
| 228 |
max_tokens: int = 8192,
|
| 229 |
temperature: float = 0.01,
|
| 230 |
top_p: float = 0.00001,
|
|
@@ -238,6 +285,7 @@ def main(
|
|
| 238 |
shuffle: bool = False,
|
| 239 |
seed: int = 42,
|
| 240 |
output_column: str = "markdown",
|
|
|
|
| 241 |
verbose: bool = False,
|
| 242 |
config: str = None,
|
| 243 |
create_pr: bool = False,
|
|
@@ -269,6 +317,9 @@ def main(
|
|
| 269 |
f"Column '{image_column}' not found. Available: {dataset.column_names}"
|
| 270 |
)
|
| 271 |
|
|
|
|
|
|
|
|
|
|
| 272 |
if shuffle:
|
| 273 |
logger.info(f"Shuffling dataset with seed {seed}")
|
| 274 |
dataset = dataset.shuffle(seed=seed)
|
|
@@ -319,7 +370,10 @@ def main(
|
|
| 319 |
)
|
| 320 |
|
| 321 |
try:
|
| 322 |
-
batch_messages = [
|
|
|
|
|
|
|
|
|
|
| 323 |
|
| 324 |
outputs = llm.chat(batch_messages, sampling_params)
|
| 325 |
|
|
@@ -509,6 +563,17 @@ Examples:
|
|
| 509 |
default=8192,
|
| 510 |
help="Maximum model context length (default: 8192)",
|
| 511 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 512 |
parser.add_argument(
|
| 513 |
"--max-tokens",
|
| 514 |
type=int,
|
|
@@ -580,6 +645,12 @@ Examples:
|
|
| 580 |
default="markdown",
|
| 581 |
help="Column name for output text (default: markdown)",
|
| 582 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 583 |
parser.add_argument(
|
| 584 |
"--verbose",
|
| 585 |
action="store_true",
|
|
@@ -594,6 +665,7 @@ Examples:
|
|
| 594 |
image_column=args.image_column,
|
| 595 |
batch_size=args.batch_size,
|
| 596 |
max_model_len=args.max_model_len,
|
|
|
|
| 597 |
max_tokens=args.max_tokens,
|
| 598 |
temperature=args.temperature,
|
| 599 |
top_p=args.top_p,
|
|
@@ -607,6 +679,7 @@ Examples:
|
|
| 607 |
shuffle=args.shuffle,
|
| 608 |
seed=args.seed,
|
| 609 |
output_column=args.output_column,
|
|
|
|
| 610 |
verbose=args.verbose,
|
| 611 |
config=args.config,
|
| 612 |
create_pr=args.create_pr,
|
|
|
|
| 2 |
# requires-python = ">=3.11"
|
| 3 |
# dependencies = [
|
| 4 |
# "datasets>=3.1.0",
|
|
|
|
| 5 |
# "huggingface-hub",
|
| 6 |
# "pillow",
|
| 7 |
# "vllm",
|
|
|
|
| 52 |
import sys
|
| 53 |
import time
|
| 54 |
from datetime import datetime
|
| 55 |
+
from typing import Any, Dict, List, Optional, Union
|
| 56 |
|
| 57 |
import torch
|
| 58 |
from datasets import load_dataset
|
|
|
|
| 63 |
# default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
|
| 64 |
# lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
|
| 65 |
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
|
| 66 |
+
# Same story for DeepGEMM (nightly vLLM): its init calls _find_cuda_home, which asserts on the
|
| 67 |
+
# nvcc-less base image (a non-fatal warning that clutters the log and hides the real traceback).
|
| 68 |
+
# Greedy OCR doesn't need the DeepGEMM JIT path, so disable it explicitly.
|
| 69 |
+
os.environ.setdefault("VLLM_USE_DEEP_GEMM", "0")
|
| 70 |
from vllm import LLM, SamplingParams
|
| 71 |
|
| 72 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 92 |
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
|
| 93 |
|
| 94 |
|
| 95 |
+
def ensure_output_columns_free(dataset, columns, overwrite=False):
|
| 96 |
+
"""Fail fast if an output column would collide with an existing input column.
|
| 97 |
+
|
| 98 |
+
Adding a column that already exists silently overwrites it (e.g. a ground-truth
|
| 99 |
+
`text`/`markdown` column) or crashes on push with a duplicate-column error only
|
| 100 |
+
*after* inference has run. Catch it up front. With overwrite=True, drop the clashing
|
| 101 |
+
column(s) here instead (logged) so the later add_column is clean.
|
| 102 |
+
"""
|
| 103 |
+
clash = [c for c in columns if c in dataset.column_names]
|
| 104 |
+
if not clash:
|
| 105 |
+
return dataset
|
| 106 |
+
if overwrite:
|
| 107 |
+
logger.warning(f"--overwrite: replacing existing column(s) {clash}")
|
| 108 |
+
return dataset.remove_columns(clash)
|
| 109 |
+
logger.error(
|
| 110 |
+
f"Output column(s) {clash} already exist in the input dataset "
|
| 111 |
+
f"(columns: {dataset.column_names})."
|
| 112 |
+
)
|
| 113 |
+
logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
|
| 114 |
+
sys.exit(1)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def downscale_to_max_pixels(img: Image.Image, max_pixels: Optional[int]) -> Image.Image:
|
| 118 |
+
"""Shrink an image so width*height <= max_pixels, preserving aspect ratio.
|
| 119 |
+
|
| 120 |
+
GLM-OCR does no internal resizing and its card gives no resolution guidance. Capping
|
| 121 |
+
input pixels bounds both image tokens and vision-encoder memory, a safety valve for very
|
| 122 |
+
large (multi-MP) scans that can pressure GPU memory at high batch sizes. No-op when
|
| 123 |
+
max_pixels is None or the image is already small enough (never upscales)."""
|
| 124 |
+
if not max_pixels:
|
| 125 |
+
return img
|
| 126 |
+
w, h = img.size
|
| 127 |
+
if w * h <= max_pixels:
|
| 128 |
+
return img
|
| 129 |
+
scale = (max_pixels / (w * h)) ** 0.5
|
| 130 |
+
new_size = (max(1, int(w * scale)), max(1, int(h * scale)))
|
| 131 |
+
return img.resize(new_size, Image.Resampling.LANCZOS)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
def make_ocr_message(
|
| 135 |
image: Union[Image.Image, Dict[str, Any], str],
|
| 136 |
task: str = "ocr",
|
| 137 |
+
max_pixels: Optional[int] = None,
|
| 138 |
) -> List[Dict]:
|
| 139 |
"""
|
| 140 |
Create chat message for OCR processing.
|
|
|
|
| 155 |
# Convert to RGB
|
| 156 |
pil_img = pil_img.convert("RGB")
|
| 157 |
|
| 158 |
+
# Optionally cap resolution to protect the vision encoder from OOM on huge scans
|
| 159 |
+
pil_img = downscale_to_max_pixels(pil_img, max_pixels)
|
| 160 |
+
|
| 161 |
# Convert to base64 data URI
|
| 162 |
buf = io.BytesIO()
|
| 163 |
pil_img.save(buf, format="PNG")
|
|
|
|
| 271 |
image_column: str = "image",
|
| 272 |
batch_size: int = 16,
|
| 273 |
max_model_len: int = 8192,
|
| 274 |
+
max_pixels: Optional[int] = None,
|
| 275 |
max_tokens: int = 8192,
|
| 276 |
temperature: float = 0.01,
|
| 277 |
top_p: float = 0.00001,
|
|
|
|
| 285 |
shuffle: bool = False,
|
| 286 |
seed: int = 42,
|
| 287 |
output_column: str = "markdown",
|
| 288 |
+
overwrite: bool = False,
|
| 289 |
verbose: bool = False,
|
| 290 |
config: str = None,
|
| 291 |
create_pr: bool = False,
|
|
|
|
| 317 |
f"Column '{image_column}' not found. Available: {dataset.column_names}"
|
| 318 |
)
|
| 319 |
|
| 320 |
+
# Fail fast if the output column would collide with an existing input column
|
| 321 |
+
dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
|
| 322 |
+
|
| 323 |
if shuffle:
|
| 324 |
logger.info(f"Shuffling dataset with seed {seed}")
|
| 325 |
dataset = dataset.shuffle(seed=seed)
|
|
|
|
| 370 |
)
|
| 371 |
|
| 372 |
try:
|
| 373 |
+
batch_messages = [
|
| 374 |
+
make_ocr_message(img, task=task, max_pixels=max_pixels)
|
| 375 |
+
for img in batch_images
|
| 376 |
+
]
|
| 377 |
|
| 378 |
outputs = llm.chat(batch_messages, sampling_params)
|
| 379 |
|
|
|
|
| 563 |
default=8192,
|
| 564 |
help="Maximum model context length (default: 8192)",
|
| 565 |
)
|
| 566 |
+
parser.add_argument(
|
| 567 |
+
"--max-pixels",
|
| 568 |
+
type=int,
|
| 569 |
+
default=None,
|
| 570 |
+
help=(
|
| 571 |
+
"Optional cap on input image pixels (width*height); larger scans are "
|
| 572 |
+
"downscaled (aspect preserved) before OCR. GLM-OCR does no internal resizing, "
|
| 573 |
+
"so this bounds vision-encoder memory on very large scans — set e.g. 4000000 "
|
| 574 |
+
"if you hit a GPU OOM at high batch sizes on a big-page corpus. Default: no cap."
|
| 575 |
+
),
|
| 576 |
+
)
|
| 577 |
parser.add_argument(
|
| 578 |
"--max-tokens",
|
| 579 |
type=int,
|
|
|
|
| 645 |
default="markdown",
|
| 646 |
help="Column name for output text (default: markdown)",
|
| 647 |
)
|
| 648 |
+
parser.add_argument(
|
| 649 |
+
"--overwrite",
|
| 650 |
+
action="store_true",
|
| 651 |
+
help="Replace the output column if it already exists in the input dataset "
|
| 652 |
+
"(default: error out to avoid clobbering an existing column).",
|
| 653 |
+
)
|
| 654 |
parser.add_argument(
|
| 655 |
"--verbose",
|
| 656 |
action="store_true",
|
|
|
|
| 665 |
image_column=args.image_column,
|
| 666 |
batch_size=args.batch_size,
|
| 667 |
max_model_len=args.max_model_len,
|
| 668 |
+
max_pixels=args.max_pixels,
|
| 669 |
max_tokens=args.max_tokens,
|
| 670 |
temperature=args.temperature,
|
| 671 |
top_p=args.top_p,
|
|
|
|
| 679 |
shuffle=args.shuffle,
|
| 680 |
seed=args.seed,
|
| 681 |
output_column=args.output_column,
|
| 682 |
+
overwrite=args.overwrite,
|
| 683 |
verbose=args.verbose,
|
| 684 |
config=args.config,
|
| 685 |
create_pr=args.create_pr,
|
lighton-ocr2.py
CHANGED
|
@@ -77,6 +77,28 @@ def check_cuda_availability():
|
|
| 77 |
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
|
| 78 |
|
| 79 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
def resize_image_to_target(image: Image.Image, target_size: int = 1540) -> Image.Image:
|
| 81 |
"""
|
| 82 |
Resize image so longest dimension is target_size while maintaining aspect ratio.
|
|
@@ -286,6 +308,7 @@ def main(
|
|
| 286 |
shuffle: bool = False,
|
| 287 |
seed: int = 42,
|
| 288 |
output_column: str = "markdown",
|
|
|
|
| 289 |
config: str = None,
|
| 290 |
create_pr: bool = False,
|
| 291 |
verbose: bool = False,
|
|
@@ -315,6 +338,9 @@ def main(
|
|
| 315 |
f"Column '{image_column}' not found. Available: {dataset.column_names}"
|
| 316 |
)
|
| 317 |
|
|
|
|
|
|
|
|
|
|
| 318 |
# Shuffle if requested
|
| 319 |
if shuffle:
|
| 320 |
logger.info(f"Shuffling dataset with seed {seed}")
|
|
@@ -558,8 +584,12 @@ Examples:
|
|
| 558 |
parser.add_argument(
|
| 559 |
"--max-model-len",
|
| 560 |
type=int,
|
| 561 |
-
default=
|
| 562 |
-
help=
|
|
|
|
|
|
|
|
|
|
|
|
|
| 563 |
)
|
| 564 |
parser.add_argument(
|
| 565 |
"--max-tokens",
|
|
@@ -631,6 +661,12 @@ Examples:
|
|
| 631 |
default="markdown",
|
| 632 |
help="Column name for output text (default: markdown)",
|
| 633 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 634 |
parser.add_argument(
|
| 635 |
"--verbose",
|
| 636 |
action="store_true",
|
|
@@ -658,6 +694,7 @@ Examples:
|
|
| 658 |
shuffle=args.shuffle,
|
| 659 |
seed=args.seed,
|
| 660 |
output_column=args.output_column,
|
|
|
|
| 661 |
config=args.config,
|
| 662 |
create_pr=args.create_pr,
|
| 663 |
verbose=args.verbose,
|
|
|
|
| 77 |
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
|
| 78 |
|
| 79 |
|
| 80 |
+
def ensure_output_columns_free(dataset, columns, overwrite=False):
|
| 81 |
+
"""Fail fast if an output column would collide with an existing input column.
|
| 82 |
+
|
| 83 |
+
Adding a column that already exists silently overwrites it (e.g. a ground-truth
|
| 84 |
+
`text`/`markdown` column) or crashes on push with a duplicate-column error only
|
| 85 |
+
*after* inference has run. Catch it up front. With overwrite=True, drop the clashing
|
| 86 |
+
column(s) here instead (logged) so the later add_column is clean.
|
| 87 |
+
"""
|
| 88 |
+
clash = [c for c in columns if c in dataset.column_names]
|
| 89 |
+
if not clash:
|
| 90 |
+
return dataset
|
| 91 |
+
if overwrite:
|
| 92 |
+
logger.warning(f"--overwrite: replacing existing column(s) {clash}")
|
| 93 |
+
return dataset.remove_columns(clash)
|
| 94 |
+
logger.error(
|
| 95 |
+
f"Output column(s) {clash} already exist in the input dataset "
|
| 96 |
+
f"(columns: {dataset.column_names})."
|
| 97 |
+
)
|
| 98 |
+
logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
|
| 99 |
+
sys.exit(1)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
def resize_image_to_target(image: Image.Image, target_size: int = 1540) -> Image.Image:
|
| 103 |
"""
|
| 104 |
Resize image so longest dimension is target_size while maintaining aspect ratio.
|
|
|
|
| 308 |
shuffle: bool = False,
|
| 309 |
seed: int = 42,
|
| 310 |
output_column: str = "markdown",
|
| 311 |
+
overwrite: bool = False,
|
| 312 |
config: str = None,
|
| 313 |
create_pr: bool = False,
|
| 314 |
verbose: bool = False,
|
|
|
|
| 338 |
f"Column '{image_column}' not found. Available: {dataset.column_names}"
|
| 339 |
)
|
| 340 |
|
| 341 |
+
# Fail fast if the output column would collide with an existing input column
|
| 342 |
+
dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
|
| 343 |
+
|
| 344 |
# Shuffle if requested
|
| 345 |
if shuffle:
|
| 346 |
logger.info(f"Shuffling dataset with seed {seed}")
|
|
|
|
| 584 |
parser.add_argument(
|
| 585 |
"--max-model-len",
|
| 586 |
type=int,
|
| 587 |
+
default=16384,
|
| 588 |
+
help=(
|
| 589 |
+
"Maximum model context length (default: 16384). A full page resized to "
|
| 590 |
+
"1540px is ~6k image tokens; with --max-tokens 4096 output that overflows "
|
| 591 |
+
"the old 8192 default at admission and vLLM rejects the request."
|
| 592 |
+
),
|
| 593 |
)
|
| 594 |
parser.add_argument(
|
| 595 |
"--max-tokens",
|
|
|
|
| 661 |
default="markdown",
|
| 662 |
help="Column name for output text (default: markdown)",
|
| 663 |
)
|
| 664 |
+
parser.add_argument(
|
| 665 |
+
"--overwrite",
|
| 666 |
+
action="store_true",
|
| 667 |
+
help="Replace the output column if it already exists in the input dataset "
|
| 668 |
+
"(default: error out to avoid clobbering an existing column).",
|
| 669 |
+
)
|
| 670 |
parser.add_argument(
|
| 671 |
"--verbose",
|
| 672 |
action="store_true",
|
|
|
|
| 694 |
shuffle=args.shuffle,
|
| 695 |
seed=args.seed,
|
| 696 |
output_column=args.output_column,
|
| 697 |
+
overwrite=args.overwrite,
|
| 698 |
config=args.config,
|
| 699 |
create_pr=args.create_pr,
|
| 700 |
verbose=args.verbose,
|
pp-ocrv6.py
CHANGED
|
@@ -69,6 +69,7 @@ import io
|
|
| 69 |
import json
|
| 70 |
import logging
|
| 71 |
import os
|
|
|
|
| 72 |
import time
|
| 73 |
from dataclasses import dataclass
|
| 74 |
from datetime import datetime, timezone
|
|
@@ -404,6 +405,8 @@ class DatasetRepoSink:
|
|
| 404 |
create_pr: bool,
|
| 405 |
source_id: str,
|
| 406 |
original_dataset=None,
|
|
|
|
|
|
|
| 407 |
):
|
| 408 |
self.repo_id = repo_id
|
| 409 |
self.hf_token = hf_token
|
|
@@ -412,6 +415,8 @@ class DatasetRepoSink:
|
|
| 412 |
self.create_pr = create_pr
|
| 413 |
self.source_id = source_id
|
| 414 |
self.original_dataset = original_dataset
|
|
|
|
|
|
|
| 415 |
self._texts: List[str] = []
|
| 416 |
self._blocks: List[str] = []
|
| 417 |
|
|
@@ -438,14 +443,25 @@ class DatasetRepoSink:
|
|
| 438 |
while len(self._texts) < len(self.original_dataset):
|
| 439 |
self._texts.append("")
|
| 440 |
self._blocks.append("[]")
|
| 441 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 442 |
ds = ds.add_column("pp_ocr_blocks", self._blocks)
|
| 443 |
else:
|
| 444 |
if not self._texts:
|
| 445 |
logger.warning("No rows produced; nothing to push.")
|
| 446 |
return
|
| 447 |
ds = Dataset.from_list([
|
| 448 |
-
{"source_path": None,
|
| 449 |
for t, b in zip(self._texts, self._blocks)
|
| 450 |
])
|
| 451 |
|
|
@@ -511,6 +527,7 @@ class DatasetRepoSink:
|
|
| 511 |
processing_time=args_dict["processing_time"],
|
| 512 |
engine=args_dict.get("engine", "paddle_static"),
|
| 513 |
output_id=self.repo_id,
|
|
|
|
| 514 |
)
|
| 515 |
)
|
| 516 |
card.push_to_hub(self.repo_id, token=self.hf_token)
|
|
@@ -684,7 +701,7 @@ def build_inference_entry(tier: str, det_model: str, rec_model: str, args_dict:
|
|
| 684 |
"rec_accuracy_pct": TIER_REC.get(tier),
|
| 685 |
"languages": TIER_LANGUAGES.get(tier, ""),
|
| 686 |
"engine": "paddle_static",
|
| 687 |
-
"output_column": "
|
| 688 |
"blocks_column": "pp_ocr_blocks",
|
| 689 |
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 690 |
}
|
|
@@ -699,6 +716,7 @@ def create_dataset_card(
|
|
| 699 |
processing_time: str,
|
| 700 |
engine: str,
|
| 701 |
output_id: str,
|
|
|
|
| 702 |
) -> str:
|
| 703 |
tier_display = tier.upper() if tier == "tiny" else tier.capitalize()
|
| 704 |
if is_bucket_url(source):
|
|
@@ -739,7 +757,7 @@ PaddlePaddle's [PP-OCRv6](https://huggingface.co/collections/PaddlePaddle/pp-ocr
|
|
| 739 |
|
| 740 |
Each row contains the original columns plus:
|
| 741 |
|
| 742 |
-
- `
|
| 743 |
detected text lines, newline-separated).
|
| 744 |
- `pp_ocr_blocks`: JSON list, one dict per detected text line:
|
| 745 |
```json
|
|
@@ -766,7 +784,7 @@ import json
|
|
| 766 |
from datasets import load_dataset
|
| 767 |
|
| 768 |
ds = load_dataset("{output_id}", split="train")
|
| 769 |
-
print(ds[0]["
|
| 770 |
for block in json.loads(ds[0]["pp_ocr_blocks"]):
|
| 771 |
print(block["text"], block["score"])
|
| 772 |
```
|
|
@@ -824,6 +842,27 @@ def main(args: argparse.Namespace) -> None:
|
|
| 824 |
seed=args.seed,
|
| 825 |
max_samples=args.max_samples,
|
| 826 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 827 |
|
| 828 |
# ---------- sink ----------
|
| 829 |
if is_bucket_url(args.output_target):
|
|
@@ -843,6 +882,8 @@ def main(args: argparse.Namespace) -> None:
|
|
| 843 |
create_pr=args.create_pr,
|
| 844 |
source_id=args.input_source,
|
| 845 |
original_dataset=original_dataset,
|
|
|
|
|
|
|
| 846 |
)
|
| 847 |
|
| 848 |
completed = sink.already_done()
|
|
@@ -931,6 +972,7 @@ def main(args: argparse.Namespace) -> None:
|
|
| 931 |
"engine": "paddle_static",
|
| 932 |
"shard_size": args.shard_size,
|
| 933 |
"processing_time": processing_time_str,
|
|
|
|
| 934 |
}
|
| 935 |
sink.finalize(
|
| 936 |
tier=tier,
|
|
@@ -1015,6 +1057,22 @@ def build_parser() -> argparse.ArgumentParser:
|
|
| 1015 |
action="store_true",
|
| 1016 |
help="Create PR instead of direct push (dataset sink only)",
|
| 1017 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1018 |
# Bucket-sink-specific
|
| 1019 |
p.add_argument(
|
| 1020 |
"--shard-size",
|
|
|
|
| 69 |
import json
|
| 70 |
import logging
|
| 71 |
import os
|
| 72 |
+
import sys
|
| 73 |
import time
|
| 74 |
from dataclasses import dataclass
|
| 75 |
from datetime import datetime, timezone
|
|
|
|
| 405 |
create_pr: bool,
|
| 406 |
source_id: str,
|
| 407 |
original_dataset=None,
|
| 408 |
+
output_column: str = "markdown",
|
| 409 |
+
overwrite: bool = False,
|
| 410 |
):
|
| 411 |
self.repo_id = repo_id
|
| 412 |
self.hf_token = hf_token
|
|
|
|
| 415 |
self.create_pr = create_pr
|
| 416 |
self.source_id = source_id
|
| 417 |
self.original_dataset = original_dataset
|
| 418 |
+
self.output_column = output_column
|
| 419 |
+
self.overwrite = overwrite
|
| 420 |
self._texts: List[str] = []
|
| 421 |
self._blocks: List[str] = []
|
| 422 |
|
|
|
|
| 443 |
while len(self._texts) < len(self.original_dataset):
|
| 444 |
self._texts.append("")
|
| 445 |
self._blocks.append("[]")
|
| 446 |
+
# Guard again at save time in case the input column set changed under us.
|
| 447 |
+
base = self.original_dataset
|
| 448 |
+
clash = [c for c in (self.output_column, "pp_ocr_blocks") if c in base.column_names]
|
| 449 |
+
if clash:
|
| 450 |
+
if not self.overwrite:
|
| 451 |
+
raise ValueError(
|
| 452 |
+
f"Output column(s) {clash} already exist in the input dataset; "
|
| 453 |
+
f"pass a different --output-column, or --overwrite to replace them."
|
| 454 |
+
)
|
| 455 |
+
logger.warning(f"--overwrite: replacing existing column(s) {clash}")
|
| 456 |
+
base = base.remove_columns(clash)
|
| 457 |
+
ds = base.add_column(self.output_column, self._texts)
|
| 458 |
ds = ds.add_column("pp_ocr_blocks", self._blocks)
|
| 459 |
else:
|
| 460 |
if not self._texts:
|
| 461 |
logger.warning("No rows produced; nothing to push.")
|
| 462 |
return
|
| 463 |
ds = Dataset.from_list([
|
| 464 |
+
{"source_path": None, self.output_column: t, "pp_ocr_blocks": b}
|
| 465 |
for t, b in zip(self._texts, self._blocks)
|
| 466 |
])
|
| 467 |
|
|
|
|
| 527 |
processing_time=args_dict["processing_time"],
|
| 528 |
engine=args_dict.get("engine", "paddle_static"),
|
| 529 |
output_id=self.repo_id,
|
| 530 |
+
output_column=self.output_column,
|
| 531 |
)
|
| 532 |
)
|
| 533 |
card.push_to_hub(self.repo_id, token=self.hf_token)
|
|
|
|
| 701 |
"rec_accuracy_pct": TIER_REC.get(tier),
|
| 702 |
"languages": TIER_LANGUAGES.get(tier, ""),
|
| 703 |
"engine": "paddle_static",
|
| 704 |
+
"output_column": args_dict.get("output_column", "markdown"),
|
| 705 |
"blocks_column": "pp_ocr_blocks",
|
| 706 |
"timestamp": datetime.now(timezone.utc).isoformat(),
|
| 707 |
}
|
|
|
|
| 716 |
processing_time: str,
|
| 717 |
engine: str,
|
| 718 |
output_id: str,
|
| 719 |
+
output_column: str = "markdown",
|
| 720 |
) -> str:
|
| 721 |
tier_display = tier.upper() if tier == "tiny" else tier.capitalize()
|
| 722 |
if is_bucket_url(source):
|
|
|
|
| 757 |
|
| 758 |
Each row contains the original columns plus:
|
| 759 |
|
| 760 |
+
- `{output_column}`: Plain text extracted from the image (reading-order concatenation of
|
| 761 |
detected text lines, newline-separated).
|
| 762 |
- `pp_ocr_blocks`: JSON list, one dict per detected text line:
|
| 763 |
```json
|
|
|
|
| 784 |
from datasets import load_dataset
|
| 785 |
|
| 786 |
ds = load_dataset("{output_id}", split="train")
|
| 787 |
+
print(ds[0]["{output_column}"])
|
| 788 |
for block in json.loads(ds[0]["pp_ocr_blocks"]):
|
| 789 |
print(block["text"], block["score"])
|
| 790 |
```
|
|
|
|
| 842 |
seed=args.seed,
|
| 843 |
max_samples=args.max_samples,
|
| 844 |
)
|
| 845 |
+
# Fail fast, before minutes of inference, if the output column would collide
|
| 846 |
+
# with an existing input column (e.g. a 'text' ground-truth column). Writing
|
| 847 |
+
# into it would either crash on push or silently overwrite the input data.
|
| 848 |
+
# --overwrite opts in to replacing the existing column(s) instead of erroring.
|
| 849 |
+
if original_dataset is not None:
|
| 850 |
+
clash = [
|
| 851 |
+
col
|
| 852 |
+
for col in (args.output_column, "pp_ocr_blocks")
|
| 853 |
+
if col in original_dataset.column_names
|
| 854 |
+
]
|
| 855 |
+
if clash and not args.overwrite:
|
| 856 |
+
logger.error(
|
| 857 |
+
f"Output column(s) {clash} already exist in the input dataset "
|
| 858 |
+
f"(columns: {original_dataset.column_names})."
|
| 859 |
+
)
|
| 860 |
+
logger.error(
|
| 861 |
+
"Choose a different --output-column, or pass --overwrite to replace them."
|
| 862 |
+
)
|
| 863 |
+
sys.exit(1)
|
| 864 |
+
if clash:
|
| 865 |
+
logger.warning(f"--overwrite: will replace existing column(s) {clash}")
|
| 866 |
|
| 867 |
# ---------- sink ----------
|
| 868 |
if is_bucket_url(args.output_target):
|
|
|
|
| 882 |
create_pr=args.create_pr,
|
| 883 |
source_id=args.input_source,
|
| 884 |
original_dataset=original_dataset,
|
| 885 |
+
output_column=args.output_column,
|
| 886 |
+
overwrite=args.overwrite,
|
| 887 |
)
|
| 888 |
|
| 889 |
completed = sink.already_done()
|
|
|
|
| 972 |
"engine": "paddle_static",
|
| 973 |
"shard_size": args.shard_size,
|
| 974 |
"processing_time": processing_time_str,
|
| 975 |
+
"output_column": args.output_column,
|
| 976 |
}
|
| 977 |
sink.finalize(
|
| 978 |
tier=tier,
|
|
|
|
| 1057 |
action="store_true",
|
| 1058 |
help="Create PR instead of direct push (dataset sink only)",
|
| 1059 |
)
|
| 1060 |
+
p.add_argument(
|
| 1061 |
+
"--output-column",
|
| 1062 |
+
default="markdown",
|
| 1063 |
+
help=(
|
| 1064 |
+
"Column name for the recognized text (dataset sink only, default: markdown). "
|
| 1065 |
+
"Must not collide with an existing input column — many corpora already ship a "
|
| 1066 |
+
"'text' ground-truth column, so 'text' would fail on push. Blocks always go to "
|
| 1067 |
+
"'pp_ocr_blocks'."
|
| 1068 |
+
),
|
| 1069 |
+
)
|
| 1070 |
+
p.add_argument(
|
| 1071 |
+
"--overwrite",
|
| 1072 |
+
action="store_true",
|
| 1073 |
+
help="Replace the output column(s) if they already exist in the input dataset "
|
| 1074 |
+
"(default: error out to avoid clobbering an existing column).",
|
| 1075 |
+
)
|
| 1076 |
# Bucket-sink-specific
|
| 1077 |
p.add_argument(
|
| 1078 |
"--shard-size",
|
surya-ocr.py
CHANGED
|
@@ -104,6 +104,53 @@ def check_cuda_availability() -> None:
|
|
| 104 |
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
|
| 105 |
|
| 106 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
def parse_page_range(spec: Optional[str]) -> Optional[List[int]]:
|
| 108 |
"""Turn '0-3,5' into [0,1,2,3,5]. None/empty -> None (all pages)."""
|
| 109 |
if not spec:
|
|
@@ -444,6 +491,7 @@ def main(
|
|
| 444 |
image_column: str = "image",
|
| 445 |
pdf_column: Optional[str] = None,
|
| 446 |
output_column: str = "markdown",
|
|
|
|
| 447 |
blocks_column: str = "surya_blocks",
|
| 448 |
page_range: Optional[str] = None,
|
| 449 |
split: str = "train",
|
|
@@ -469,6 +517,7 @@ def main(
|
|
| 469 |
os.environ["SURYA_INFERENCE_AUTOSTART"] = "False"
|
| 470 |
|
| 471 |
check_cuda_availability()
|
|
|
|
| 472 |
start_time = datetime.now(timezone.utc)
|
| 473 |
|
| 474 |
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
|
|
@@ -495,6 +544,10 @@ def main(
|
|
| 495 |
f"Column '{source_column}' not found. Available: {dataset.column_names}"
|
| 496 |
)
|
| 497 |
sys.exit(1)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 498 |
if shuffle:
|
| 499 |
dataset = dataset.shuffle(seed=seed)
|
| 500 |
if max_samples:
|
|
@@ -755,6 +808,12 @@ Run on the vllm/vllm-openai:v0.20.1 image:
|
|
| 755 |
default="markdown",
|
| 756 |
help="Text output column (default: markdown)",
|
| 757 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 758 |
parser.add_argument(
|
| 759 |
"--blocks-column",
|
| 760 |
default="surya_blocks",
|
|
@@ -836,6 +895,7 @@ Run on the vllm/vllm-openai:v0.20.1 image:
|
|
| 836 |
image_column=args.image_column,
|
| 837 |
pdf_column=args.pdf_column,
|
| 838 |
output_column=args.output_column,
|
|
|
|
| 839 |
blocks_column=args.blocks_column,
|
| 840 |
page_range=args.page_range,
|
| 841 |
split=args.split,
|
|
|
|
| 104 |
logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
|
| 105 |
|
| 106 |
|
| 107 |
+
def check_vllm_available() -> None:
|
| 108 |
+
"""Fail fast (before loading 400 rows) if vLLM isn't importable.
|
| 109 |
+
|
| 110 |
+
Surya-2 runs its VLM through vLLM's offline engine, but `vllm` is deliberately
|
| 111 |
+
NOT a PEP723 dependency: the recent hybrid `qwen3_5` architecture is only in the
|
| 112 |
+
pinned `vllm/vllm-openai:v0.20.1` image, which also provides torch/transformers via
|
| 113 |
+
PYTHONPATH. Launched on the bare uv image (no `--image`), the import fails per-batch
|
| 114 |
+
and every row silently gets "[SURYA GENERATE ERROR]". Detect that up front instead.
|
| 115 |
+
"""
|
| 116 |
+
import importlib.util
|
| 117 |
+
|
| 118 |
+
if importlib.util.find_spec("vllm") is None:
|
| 119 |
+
logger.error("vLLM is not importable — this recipe cannot run on the bare uv image.")
|
| 120 |
+
logger.error(
|
| 121 |
+
"Surya-2 needs the pinned vLLM build; re-run with the image + interpreter flags:"
|
| 122 |
+
)
|
| 123 |
+
logger.error(
|
| 124 |
+
" hf jobs uv run --flavor l4x1 -s HF_TOKEN \\\n"
|
| 125 |
+
" --image vllm/vllm-openai:v0.20.1 --python /usr/local/bin/python3 \\\n"
|
| 126 |
+
" -e PYTHONPATH=/usr/local/lib/python3.12/site-packages \\\n"
|
| 127 |
+
" <script_url> INPUT_DATASET OUTPUT_DATASET ..."
|
| 128 |
+
)
|
| 129 |
+
sys.exit(1)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def ensure_output_columns_free(dataset, columns, overwrite=False):
|
| 133 |
+
"""Fail fast if an output column would collide with an existing input column.
|
| 134 |
+
|
| 135 |
+
Adding a column that already exists silently overwrites it (e.g. a ground-truth
|
| 136 |
+
`text`/`markdown` column) or crashes on push with a duplicate-column error only
|
| 137 |
+
*after* inference has run. Catch it up front. With overwrite=True, drop the clashing
|
| 138 |
+
column(s) here instead (logged) so the later add_column is clean.
|
| 139 |
+
"""
|
| 140 |
+
clash = [c for c in columns if c in dataset.column_names]
|
| 141 |
+
if not clash:
|
| 142 |
+
return dataset
|
| 143 |
+
if overwrite:
|
| 144 |
+
logger.warning(f"--overwrite: replacing existing column(s) {clash}")
|
| 145 |
+
return dataset.remove_columns(clash)
|
| 146 |
+
logger.error(
|
| 147 |
+
f"Output column(s) {clash} already exist in the input dataset "
|
| 148 |
+
f"(columns: {dataset.column_names})."
|
| 149 |
+
)
|
| 150 |
+
logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
|
| 151 |
+
sys.exit(1)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
def parse_page_range(spec: Optional[str]) -> Optional[List[int]]:
|
| 155 |
"""Turn '0-3,5' into [0,1,2,3,5]. None/empty -> None (all pages)."""
|
| 156 |
if not spec:
|
|
|
|
| 491 |
image_column: str = "image",
|
| 492 |
pdf_column: Optional[str] = None,
|
| 493 |
output_column: str = "markdown",
|
| 494 |
+
overwrite: bool = False,
|
| 495 |
blocks_column: str = "surya_blocks",
|
| 496 |
page_range: Optional[str] = None,
|
| 497 |
split: str = "train",
|
|
|
|
| 517 |
os.environ["SURYA_INFERENCE_AUTOSTART"] = "False"
|
| 518 |
|
| 519 |
check_cuda_availability()
|
| 520 |
+
check_vllm_available()
|
| 521 |
start_time = datetime.now(timezone.utc)
|
| 522 |
|
| 523 |
HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
|
|
|
|
| 544 |
f"Column '{source_column}' not found. Available: {dataset.column_names}"
|
| 545 |
)
|
| 546 |
sys.exit(1)
|
| 547 |
+
# Fail fast if the output column would collide with an existing input column
|
| 548 |
+
dataset = ensure_output_columns_free(
|
| 549 |
+
dataset, [output_column, blocks_column], overwrite=overwrite
|
| 550 |
+
)
|
| 551 |
if shuffle:
|
| 552 |
dataset = dataset.shuffle(seed=seed)
|
| 553 |
if max_samples:
|
|
|
|
| 808 |
default="markdown",
|
| 809 |
help="Text output column (default: markdown)",
|
| 810 |
)
|
| 811 |
+
parser.add_argument(
|
| 812 |
+
"--overwrite",
|
| 813 |
+
action="store_true",
|
| 814 |
+
help="Replace the output column if it already exists in the input dataset "
|
| 815 |
+
"(default: error out to avoid clobbering an existing column).",
|
| 816 |
+
)
|
| 817 |
parser.add_argument(
|
| 818 |
"--blocks-column",
|
| 819 |
default="surya_blocks",
|
|
|
|
| 895 |
image_column=args.image_column,
|
| 896 |
pdf_column=args.pdf_column,
|
| 897 |
output_column=args.output_column,
|
| 898 |
+
overwrite=args.overwrite,
|
| 899 |
blocks_column=args.blocks_column,
|
| 900 |
page_range=args.page_range,
|
| 901 |
split=args.split,
|