davanstrien HF Staff commited on
Commit
c009b2c
·
verified ·
1 Parent(s): b5beaf6

Sync from GitHub via hub-sync

Browse files
Files changed (2) hide show
  1. README.md +1 -1
  2. nanonets-ocr2.py +81 -12
README.md CHANGED
@@ -65,7 +65,7 @@ _Sorted by model size:_
65
  | `abot-ocr.py` | [ABot-OCR](https://huggingface.co/acvlab/ABot-OCR) | 2B | vLLM | Qwen3-VL based, doc→Markdown (text/LaTeX/HTML tables). Needs `vllm/vllm-openai` image. [paper](https://arxiv.org/abs/2605.27978) |
66
  | `nanonets-ocr.py` | [Nanonets-OCR-s](https://huggingface.co/nanonets/Nanonets-OCR-s) | 2B | vLLM | LaTeX, tables, forms |
67
  | `dots-mocr.py` | [dots.mocr](https://huggingface.co/rednote-hilab/dots.mocr) | 3B | vLLM | 8 prompt modes incl. SVG generation, layout + bbox, 100+ languages |
68
- | `nanonets-ocr2.py` | [Nanonets-OCR2-3B](https://huggingface.co/nanonets/Nanonets-OCR2-s) | 3B | vLLM | Next-gen, Qwen2.5-VL base |
69
  | `deepseek-ocr-vllm.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | vLLM | 5 resolution + 5 prompt modes |
70
  | `deepseek-ocr.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | Transformers | Same model, Transformers backend |
71
  | `deepseek-ocr2-vllm.py` | [DeepSeek-OCR-2](https://huggingface.co/deepseek-ai/DeepSeek-OCR-2) | 3B | vLLM | Newer; needs nightly vLLM **+ the `vllm/vllm-openai` image** ([why](#if-a-vllm-script-crashes-at-startup-the-nvcc--nvrtc-error)) |
 
65
  | `abot-ocr.py` | [ABot-OCR](https://huggingface.co/acvlab/ABot-OCR) | 2B | vLLM | Qwen3-VL based, doc→Markdown (text/LaTeX/HTML tables). Needs `vllm/vllm-openai` image. [paper](https://arxiv.org/abs/2605.27978) |
66
  | `nanonets-ocr.py` | [Nanonets-OCR-s](https://huggingface.co/nanonets/Nanonets-OCR-s) | 2B | vLLM | LaTeX, tables, forms |
67
  | `dots-mocr.py` | [dots.mocr](https://huggingface.co/rednote-hilab/dots.mocr) | 3B | vLLM | 8 prompt modes incl. SVG generation, layout + bbox, 100+ languages |
68
+ | `nanonets-ocr2.py` | [Nanonets-OCR2-3B](https://huggingface.co/nanonets/Nanonets-OCR2-3B) | 3B | vLLM | Next-gen, Qwen2.5-VL base. **Pin `--image vllm/vllm-openai:v0.10.2`** (vLLM ≥0.11 breaks Qwen2.5-VL → all `!`) |
69
  | `deepseek-ocr-vllm.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | vLLM | 5 resolution + 5 prompt modes |
70
  | `deepseek-ocr.py` | [DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) | 4B | Transformers | Same model, Transformers backend |
71
  | `deepseek-ocr2-vllm.py` | [DeepSeek-OCR-2](https://huggingface.co/deepseek-ai/DeepSeek-OCR-2) | 3B | vLLM | Newer; needs nightly vLLM **+ the `vllm/vllm-openai` image** ([why](#if-a-vllm-script-crashes-at-startup-the-nvcc--nvrtc-error)) |
nanonets-ocr2.py CHANGED
@@ -4,10 +4,8 @@
4
  # "datasets>=4.0.0",
5
  # "huggingface-hub",
6
  # "pillow",
7
- # "vllm>=0.15.1",
8
  # "tqdm",
9
  # "toolz",
10
- # "torch",
11
  # ]
12
  #
13
  # ///
@@ -26,6 +24,20 @@ Features:
26
  - Signature and watermark detection
27
  - Checkbox recognition
28
  - Multilingual support
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  """
30
 
31
  import argparse
@@ -38,15 +50,32 @@ import sys
38
  from typing import Any, Dict, List, Union
39
  from datetime import datetime
40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  import torch
42
  from datasets import load_dataset
43
  from huggingface_hub import DatasetCard, login
44
  from PIL import Image
45
  from toolz import partition_all
46
  from tqdm.auto import tqdm
47
- # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
48
- # default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
49
- # lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
50
  os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
51
  from vllm import LLM, SamplingParams
52
 
@@ -64,6 +93,28 @@ def check_cuda_availability():
64
  logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
65
 
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  def make_ocr_message(
68
  image: Union[Image.Image, Dict[str, Any], str],
69
  prompt: str = "Extract the text from the above document as if you were reading it naturally. Return the tables in html format. Return the equations in LaTeX representation. If there is an image in the document and image caption is not present, add a small description of the image inside the <img></img> tag; otherwise, add the image caption inside <img></img>. Watermarks should be wrapped in brackets. Ex: <watermark>OFFICIAL COPY</watermark>. Page numbers should be wrapped in brackets. Ex: <page_number>14</page_number> or <page_number>9/22</page_number>. Prefer using ☐ and ☑ for check boxes.",
@@ -214,7 +265,7 @@ def main(
214
  image_column: str = "image",
215
  batch_size: int = 16,
216
  model: str = "nanonets/Nanonets-OCR2-3B",
217
- max_model_len: int = 8192,
218
  max_tokens: int = 15000,
219
  gpu_memory_utilization: float = 0.8,
220
  hf_token: str = None,
@@ -223,6 +274,8 @@ def main(
223
  private: bool = False,
224
  shuffle: bool = False,
225
  seed: int = 42,
 
 
226
  verbose: bool = False,
227
  ):
228
  """Process images from HF dataset through Nanonets-OCR2-3B model."""
@@ -251,6 +304,9 @@ def main(
251
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
252
  )
253
 
 
 
 
254
  # Shuffle if requested
255
  if shuffle:
256
  logger.info(f"Shuffling dataset with seed {seed}")
@@ -307,9 +363,9 @@ def main(
307
  # Add error placeholders for failed batch
308
  all_markdown.extend(["[OCR FAILED]"] * len(batch_images))
309
 
310
- # Add markdown column to dataset
311
- logger.info("Adding markdown column to dataset")
312
- dataset = dataset.add_column("markdown", all_markdown)
313
 
314
  # Handle inference_info tracking
315
  logger.info("Updating inference_info...")
@@ -317,7 +373,7 @@ def main(
317
  inference_entry = {
318
  "model_id": model,
319
  "model_name": "Nanonets-OCR2-3B",
320
- "column_name": "markdown",
321
  "timestamp": datetime.now().isoformat(),
322
  "batch_size": batch_size,
323
  "max_tokens": max_tokens,
@@ -476,8 +532,8 @@ Examples:
476
  parser.add_argument(
477
  "--max-model-len",
478
  type=int,
479
- default=8192,
480
- help="Maximum model context length (default: 8192)",
481
  )
482
  parser.add_argument(
483
  "--max-tokens",
@@ -514,6 +570,17 @@ Examples:
514
  default=42,
515
  help="Random seed for shuffling (default: 42)",
516
  )
 
 
 
 
 
 
 
 
 
 
 
517
  parser.add_argument(
518
  "--verbose",
519
  action="store_true",
@@ -537,5 +604,7 @@ Examples:
537
  private=args.private,
538
  shuffle=args.shuffle,
539
  seed=args.seed,
 
 
540
  verbose=args.verbose,
541
  )
 
4
  # "datasets>=4.0.0",
5
  # "huggingface-hub",
6
  # "pillow",
 
7
  # "tqdm",
8
  # "toolz",
 
9
  # ]
10
  #
11
  # ///
 
24
  - Signature and watermark detection
25
  - Checkbox recognition
26
  - Multilingual support
27
+
28
+ ⚠️ Pinned vLLM image required. Nanonets-OCR2-3B is a Qwen2.5-VL model, and vLLM
29
+ >=0.11 regressed Qwen2.5-VL decoding to a stream of "!" (vllm-project/vllm#27775,
30
+ #14126); 0.10.2 is the last known-good. So `vllm` and `torch` are intentionally
31
+ omitted from the deps above and come from the `vllm/vllm-openai:v0.10.2` image at
32
+ runtime via PYTHONPATH. Run it like:
33
+
34
+ hf jobs uv run --flavor a10g-small -s HF_TOKEN \
35
+ --image vllm/vllm-openai:v0.10.2 --python /usr/bin/python3 \
36
+ -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \
37
+ nanonets-ocr2.py INPUT_DATASET OUTPUT_DATASET --max-samples 10 --shuffle
38
+
39
+ Re-test the pin when a newer vLLM ships a Qwen2.5-VL decode fix; it can then move
40
+ back to a plain `vllm>=...` dep on the default image.
41
  """
42
 
43
  import argparse
 
50
  from typing import Any, Dict, List, Union
51
  from datetime import datetime
52
 
53
+ # Preflight: torch/vllm are deliberately NOT PEP 723 deps (see docstring) — they come from
54
+ # the pinned vllm/vllm-openai:v0.10.2 image. On the bare uv image the imports below would
55
+ # die with a raw ModuleNotFoundError; fail fast naming the exact flags instead.
56
+ import importlib.util
57
+
58
+ if importlib.util.find_spec("vllm") is None or importlib.util.find_spec("torch") is None:
59
+ sys.stderr.write(
60
+ "ERROR: vllm/torch not importable — this recipe cannot run on the bare uv image.\n"
61
+ "Nanonets-OCR2-3B needs vLLM 0.10.2 (>=0.11 regresses Qwen2.5-VL decoding to '!').\n"
62
+ "Re-run with the pinned image + interpreter flags:\n"
63
+ " hf jobs uv run --flavor a10g-small -s HF_TOKEN \\\n"
64
+ " --image vllm/vllm-openai:v0.10.2 --python /usr/bin/python3 \\\n"
65
+ " -e PYTHONPATH=/usr/local/lib/python3.12/dist-packages \\\n"
66
+ " nanonets-ocr2.py INPUT_DATASET OUTPUT_DATASET ...\n"
67
+ )
68
+ sys.exit(1)
69
+
70
  import torch
71
  from datasets import load_dataset
72
  from huggingface_hub import DatasetCard, login
73
  from PIL import Image
74
  from toolz import partition_all
75
  from tqdm.auto import tqdm
76
+ # Disable vLLM's FlashInfer sampler (JIT-compiles a CUDA kernel; greedy OCR doesn't use it).
77
+ # Harmless no-op on the pinned vllm/vllm-openai image; kept in case the pin is ever relaxed
78
+ # back to an environment without nvcc.
79
  os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
80
  from vllm import LLM, SamplingParams
81
 
 
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 = "Extract the text from the above document as if you were reading it naturally. Return the tables in html format. Return the equations in LaTeX representation. If there is an image in the document and image caption is not present, add a small description of the image inside the <img></img> tag; otherwise, add the image caption inside <img></img>. Watermarks should be wrapped in brackets. Ex: <watermark>OFFICIAL COPY</watermark>. Page numbers should be wrapped in brackets. Ex: <page_number>14</page_number> or <page_number>9/22</page_number>. Prefer using ☐ and ☑ for check boxes.",
 
265
  image_column: str = "image",
266
  batch_size: int = 16,
267
  model: str = "nanonets/Nanonets-OCR2-3B",
268
+ max_model_len: int = 32768,
269
  max_tokens: int = 15000,
270
  gpu_memory_utilization: float = 0.8,
271
  hf_token: str = None,
 
274
  private: bool = False,
275
  shuffle: bool = False,
276
  seed: int = 42,
277
+ output_column: str = "markdown",
278
+ overwrite: bool = False,
279
  verbose: bool = False,
280
  ):
281
  """Process images from HF dataset through Nanonets-OCR2-3B model."""
 
304
  f"Column '{image_column}' not found. Available: {dataset.column_names}"
305
  )
306
 
307
+ # Fail fast if the output column would collide with an existing input column
308
+ dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
309
+
310
  # Shuffle if requested
311
  if shuffle:
312
  logger.info(f"Shuffling dataset with seed {seed}")
 
363
  # Add error placeholders for failed batch
364
  all_markdown.extend(["[OCR FAILED]"] * len(batch_images))
365
 
366
+ # Add output column to dataset
367
+ logger.info(f"Adding '{output_column}' column to dataset")
368
+ dataset = dataset.add_column(output_column, all_markdown)
369
 
370
  # Handle inference_info tracking
371
  logger.info("Updating inference_info...")
 
373
  inference_entry = {
374
  "model_id": model,
375
  "model_name": "Nanonets-OCR2-3B",
376
+ "column_name": output_column,
377
  "timestamp": datetime.now().isoformat(),
378
  "batch_size": batch_size,
379
  "max_tokens": max_tokens,
 
532
  parser.add_argument(
533
  "--max-model-len",
534
  type=int,
535
+ default=32768,
536
+ help="Maximum model context length (default: 32768)",
537
  )
538
  parser.add_argument(
539
  "--max-tokens",
 
570
  default=42,
571
  help="Random seed for shuffling (default: 42)",
572
  )
573
+ parser.add_argument(
574
+ "--output-column",
575
+ default="markdown",
576
+ help="Column name for the OCR output text (default: markdown)",
577
+ )
578
+ parser.add_argument(
579
+ "--overwrite",
580
+ action="store_true",
581
+ help="Replace the output column if it already exists in the input dataset "
582
+ "(default: error out to avoid clobbering an existing column).",
583
+ )
584
  parser.add_argument(
585
  "--verbose",
586
  action="store_true",
 
604
  private=args.private,
605
  shuffle=args.shuffle,
606
  seed=args.seed,
607
+ output_column=args.output_column,
608
+ overwrite=args.overwrite,
609
  verbose=args.verbose,
610
  )