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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "datasets",
5
+ # "huggingface-hub[hf_transfer]",
6
+ # "pillow",
7
+ # "vllm",
8
+ # "tqdm",
9
+ # "toolz",
10
+ # "torch",
11
+ # ]
12
+ #
13
+ # ///
14
+
15
+ """
16
+ Convert document images to markdown using Nanonets-OCR2-3B with vLLM.
17
+
18
+ This script processes images through the Nanonets-OCR2-3B model (3.75B params)
19
+ to extract text and structure as markdown, ideal for document understanding tasks.
20
+
21
+ Features:
22
+ - LaTeX equation recognition
23
+ - Table extraction and formatting (HTML)
24
+ - Document structure preservation
25
+ - Image descriptions and captions
26
+ - Signature and watermark detection
27
+ - Checkbox recognition
28
+ - Multilingual support
29
+ """
30
+
31
+ import argparse
32
+ import base64
33
+ import io
34
+ import json
35
+ import logging
36
+ import os
37
+ 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
+ from vllm import LLM, SamplingParams
48
+
49
+ logging.basicConfig(level=logging.INFO)
50
+ logger = logging.getLogger(__name__)
51
+
52
+
53
+ def check_cuda_availability():
54
+ """Check if CUDA is available and exit if not."""
55
+ if not torch.cuda.is_available():
56
+ logger.error("CUDA is not available. This script requires a GPU.")
57
+ logger.error("Please run on a machine with a CUDA-capable GPU.")
58
+ sys.exit(1)
59
+ else:
60
+ logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
61
+
62
+
63
+ def make_ocr_message(
64
+ image: Union[Image.Image, Dict[str, Any], str],
65
+ 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.",
66
+ ) -> List[Dict]:
67
+ """Create chat message for OCR processing."""
68
+ # Convert to PIL Image if needed
69
+ if isinstance(image, Image.Image):
70
+ pil_img = image
71
+ elif isinstance(image, dict) and "bytes" in image:
72
+ pil_img = Image.open(io.BytesIO(image["bytes"]))
73
+ elif isinstance(image, str):
74
+ pil_img = Image.open(image)
75
+ else:
76
+ raise ValueError(f"Unsupported image type: {type(image)}")
77
+
78
+ # Convert to base64 data URI
79
+ buf = io.BytesIO()
80
+ pil_img.save(buf, format="PNG")
81
+ data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
82
+
83
+ # Return message in vLLM format
84
+ return [
85
+ {
86
+ "role": "user",
87
+ "content": [
88
+ {"type": "image_url", "image_url": {"url": data_uri}},
89
+ {"type": "text", "text": prompt},
90
+ ],
91
+ }
92
+ ]
93
+
94
+
95
+ def create_dataset_card(
96
+ source_dataset: str,
97
+ model: str,
98
+ num_samples: int,
99
+ processing_time: str,
100
+ batch_size: int,
101
+ max_model_len: int,
102
+ max_tokens: int,
103
+ gpu_memory_utilization: float,
104
+ image_column: str = "image",
105
+ split: str = "train",
106
+ ) -> str:
107
+ """Create a dataset card documenting the OCR process."""
108
+ model_name = model.split("/")[-1]
109
+
110
+ return f"""---
111
+ tags:
112
+ - ocr
113
+ - document-processing
114
+ - nanonets
115
+ - nanonets-ocr2
116
+ - markdown
117
+ - uv-script
118
+ - generated
119
+ ---
120
+
121
+ # Document OCR using {model_name}
122
+
123
+ This dataset contains markdown-formatted OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using Nanonets-OCR2-3B.
124
+
125
+ ## Processing Details
126
+
127
+ - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
128
+ - **Model**: [{model}](https://huggingface.co/{model})
129
+ - **Model Size**: 3.75B parameters
130
+ - **Number of Samples**: {num_samples:,}
131
+ - **Processing Time**: {processing_time}
132
+ - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
133
+
134
+ ### Configuration
135
+
136
+ - **Image Column**: `{image_column}`
137
+ - **Output Column**: `markdown`
138
+ - **Dataset Split**: `{split}`
139
+ - **Batch Size**: {batch_size}
140
+ - **Max Model Length**: {max_model_len:,} tokens
141
+ - **Max Output Tokens**: {max_tokens:,}
142
+ - **GPU Memory Utilization**: {gpu_memory_utilization:.1%}
143
+
144
+ ## Model Information
145
+
146
+ Nanonets-OCR2-3B is a state-of-the-art document OCR model that excels at:
147
+ - 📐 **LaTeX equations** - Mathematical formulas preserved in LaTeX format
148
+ - 📊 **Tables** - Extracted and formatted as HTML
149
+ - 📝 **Document structure** - Headers, lists, and formatting maintained
150
+ - 🖼️ **Images** - Captions and descriptions included in `<img>` tags
151
+ - ☑️ **Forms** - Checkboxes rendered as ☐/☑
152
+ - 🔖 **Watermarks** - Wrapped in `<watermark>` tags
153
+ - 📄 **Page numbers** - Wrapped in `<page_number>` tags
154
+ - 🌍 **Multilingual** - Supports multiple languages
155
+
156
+ ## Dataset Structure
157
+
158
+ The dataset contains all original columns plus:
159
+ - `markdown`: The extracted text in markdown format with preserved structure
160
+ - `inference_info`: JSON list tracking all OCR models applied to this dataset
161
+
162
+ ## Usage
163
+
164
+ ```python
165
+ from datasets import load_dataset
166
+ import json
167
+
168
+ # Load the dataset
169
+ dataset = load_dataset("{{{{output_dataset_id}}}}", split="{split}")
170
+
171
+ # Access the markdown text
172
+ for example in dataset:
173
+ print(example["markdown"])
174
+ break
175
+
176
+ # View all OCR models applied to this dataset
177
+ inference_info = json.loads(dataset[0]["inference_info"])
178
+ for info in inference_info:
179
+ print(f"Column: {{{{info['column_name']}}}} - Model: {{{{info['model_id']}}}}")
180
+ ```
181
+
182
+ ## Reproduction
183
+
184
+ This dataset was generated using the [uv-scripts/ocr](https://huggingface.co/datasets/uv-scripts/ocr) Nanonets OCR2 script:
185
+
186
+ ```bash
187
+ uv run https://huggingface.co/datasets/Alysonhower/scripts/resolve/main/nanonets-ocr2.pyy \\
188
+ {source_dataset} \\
189
+ <output-dataset> \\
190
+ --model {model} \\
191
+ --image-column {image_column} \\
192
+ --batch-size {batch_size} \\
193
+ --max-model-len {max_model_len} \\
194
+ --max-tokens {max_tokens} \\
195
+ --gpu-memory-utilization {gpu_memory_utilization}
196
+ ```
197
+
198
+ ## Performance
199
+
200
+ - **Processing Speed**: ~{num_samples / (float(processing_time.split()[0]) * 60):.1f} images/second
201
+ - **GPU Configuration**: vLLM with {gpu_memory_utilization:.0%} GPU memory utilization
202
+
203
+ Generated with 🤖 [UV Scripts](https://huggingface.co/uv-scripts)
204
+ """
205
+
206
+
207
+ def main(
208
+ input_dataset: str,
209
+ output_dataset: str,
210
+ image_column: str = "image",
211
+ batch_size: int = 16,
212
+ model: str = "nanonets/Nanonets-OCR2-3B",
213
+ max_model_len: int = 15000,
214
+ max_tokens: int = 15000,
215
+ gpu_memory_utilization: float = 0.8,
216
+ hf_token: str = None,
217
+ split: str = "train",
218
+ max_samples: int = None,
219
+ private: bool = False,
220
+ shuffle: bool = False,
221
+ seed: int = 42,
222
+ ):
223
+ """Process images from HF dataset through Nanonets-OCR2-3B model."""
224
+
225
+ # Check CUDA availability first
226
+ check_cuda_availability()
227
+
228
+ # Track processing start time
229
+ start_time = datetime.now()
230
+
231
+ # Enable HF_TRANSFER for faster downloads
232
+ os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
233
+
234
+ # Login to HF if token provided
235
+ HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
236
+ if HF_TOKEN:
237
+ login(token=HF_TOKEN)
238
+
239
+ # Load dataset
240
+ logger.info(f"Loading dataset: {input_dataset}")
241
+ dataset = load_dataset(input_dataset, split=split)
242
+
243
+ # Validate image column
244
+ if image_column not in dataset.column_names:
245
+ raise ValueError(
246
+ f"Column '{image_column}' not found. Available: {dataset.column_names}"
247
+ )
248
+
249
+ # Shuffle if requested
250
+ if shuffle:
251
+ logger.info(f"Shuffling dataset with seed {seed}")
252
+ dataset = dataset.shuffle(seed=seed)
253
+
254
+ # Limit samples if requested
255
+ if max_samples:
256
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
257
+ logger.info(f"Limited to {len(dataset)} samples")
258
+
259
+ # Initialize vLLM
260
+ logger.info(f"Initializing vLLM with model: {model}")
261
+ llm = LLM(
262
+ model=model,
263
+ trust_remote_code=True,
264
+ max_model_len=max_model_len,
265
+ gpu_memory_utilization=gpu_memory_utilization,
266
+ limit_mm_per_prompt={"image": 1},
267
+ )
268
+
269
+ sampling_params = SamplingParams(
270
+ temperature=0.0, # Deterministic for OCR
271
+ max_tokens=max_tokens,
272
+ repetition_penalty=1.0
273
+ )
274
+
275
+ # Process images in batches
276
+ all_markdown = []
277
+
278
+ logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
279
+
280
+ # Process in batches to avoid memory issues
281
+ for batch_indices in tqdm(
282
+ partition_all(batch_size, range(len(dataset))),
283
+ total=(len(dataset) + batch_size - 1) // batch_size,
284
+ desc="OCR processing",
285
+ ):
286
+ batch_indices = list(batch_indices)
287
+ batch_images = [dataset[i][image_column] for i in batch_indices]
288
+
289
+ try:
290
+ # Create messages for batch
291
+ batch_messages = [make_ocr_message(img) for img in batch_images]
292
+
293
+ # Process with vLLM
294
+ outputs = llm.chat(batch_messages, sampling_params)
295
+
296
+ # Extract markdown from outputs
297
+ for output in outputs:
298
+ markdown_text = output.outputs[0].text.strip()
299
+ all_markdown.append(markdown_text)
300
+
301
+ except Exception as e:
302
+ logger.error(f"Error processing batch: {e}")
303
+ # Add error placeholders for failed batch
304
+ all_markdown.extend(["[OCR FAILED]"] * len(batch_images))
305
+
306
+ # Add markdown column to dataset
307
+ logger.info("Adding markdown column to dataset")
308
+ dataset = dataset.add_column("markdown", all_markdown)
309
+
310
+ # Handle inference_info tracking
311
+ logger.info("Updating inference_info...")
312
+
313
+ # Check for existing inference_info
314
+ if "inference_info" in dataset.column_names:
315
+ # Parse existing info from first row (all rows have same info)
316
+ try:
317
+ existing_info = json.loads(dataset[0]["inference_info"])
318
+ if not isinstance(existing_info, list):
319
+ existing_info = [existing_info] # Convert old format to list
320
+ except (json.JSONDecodeError, TypeError):
321
+ existing_info = []
322
+ # Remove old column to update it
323
+ dataset = dataset.remove_columns(["inference_info"])
324
+ else:
325
+ existing_info = []
326
+
327
+ # Add new inference info
328
+ new_info = {
329
+ "column_name": "markdown",
330
+ "model_id": model,
331
+ "processing_date": datetime.now().isoformat(),
332
+ "batch_size": batch_size,
333
+ "max_tokens": max_tokens,
334
+ "gpu_memory_utilization": gpu_memory_utilization,
335
+ "max_model_len": max_model_len,
336
+ "script": "nanonets-ocr2.py",
337
+ "script_version": "1.0.0",
338
+ "script_url": "https://huggingface.co/datasets/Alysonhower/scripts/resolve/main/nanonets-ocr2.pyy"
339
+ }
340
+ existing_info.append(new_info)
341
+
342
+ # Add updated inference_info column
343
+ info_json = json.dumps(existing_info, ensure_ascii=False)
344
+ dataset = dataset.add_column("inference_info", [info_json] * len(dataset))
345
+
346
+ # Push to hub
347
+ logger.info(f"Pushing to {output_dataset}")
348
+ dataset.push_to_hub(output_dataset, private=private, token=HF_TOKEN)
349
+
350
+ # Calculate processing time
351
+ end_time = datetime.now()
352
+ processing_duration = end_time - start_time
353
+ processing_time = f"{processing_duration.total_seconds() / 60:.1f} minutes"
354
+
355
+ # Create and push dataset card
356
+ logger.info("Creating dataset card...")
357
+ card_content = create_dataset_card(
358
+ source_dataset=input_dataset,
359
+ model=model,
360
+ num_samples=len(dataset),
361
+ processing_time=processing_time,
362
+ batch_size=batch_size,
363
+ max_model_len=max_model_len,
364
+ max_tokens=max_tokens,
365
+ gpu_memory_utilization=gpu_memory_utilization,
366
+ image_column=image_column,
367
+ split=split,
368
+ )
369
+
370
+ card = DatasetCard(card_content)
371
+ card.push_to_hub(output_dataset, token=HF_TOKEN)
372
+ logger.info("✅ Dataset card created and pushed!")
373
+
374
+ logger.info("✅ OCR conversion complete!")
375
+ logger.info(
376
+ f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
377
+ )
378
+
379
+
380
+ if __name__ == "__main__":
381
+ # Show example usage if no arguments
382
+ if len(sys.argv) == 1:
383
+ print("=" * 80)
384
+ print("Nanonets OCR2-3B to Markdown Converter")
385
+ print("=" * 80)
386
+ print("\nThis script converts document images to structured markdown using")
387
+ print("the Nanonets-OCR2-3B model (3.75B params) with vLLM acceleration.")
388
+ print("\nFeatures:")
389
+ print("- LaTeX equation recognition")
390
+ print("- Table extraction and formatting (HTML)")
391
+ print("- Document structure preservation")
392
+ print("- Image descriptions and captions")
393
+ print("- Signature and watermark detection")
394
+ print("- Checkbox recognition (☐/☑)")
395
+ print("- Multilingual support")
396
+ print("\nExample usage:")
397
+ print("\n1. Basic OCR conversion:")
398
+ print(" uv run nanonets-ocr2.py document-images markdown-docs")
399
+ print("\n2. With custom settings:")
400
+ print(" uv run nanonets-ocr2.py scanned-pdfs extracted-text \\")
401
+ print(" --image-column page \\")
402
+ print(" --batch-size 32 \\")
403
+ print(" --gpu-memory-utilization 0.8")
404
+ print("\n3. Process a subset for testing:")
405
+ print(" uv run nanonets-ocr2.py large-dataset test-output --max-samples 10")
406
+ print("\n4. Random sample from ordered dataset:")
407
+ print(" uv run nanonets-ocr2.py ordered-dataset random-test \\")
408
+ print(" --max-samples 50 --shuffle")
409
+ print("\n5. Running on HF Jobs:")
410
+ print(" hf jobs uv run --flavor l4x1 \\")
411
+ print(" -e HF_TOKEN=$(python3 -c \"from huggingface_hub import get_token; print(get_token())\") \\")
412
+ print(" https://huggingface.co/datasets/Alysonhower/scripts/resolve/main/nanonets-ocr2.pyy \\")
413
+ print(" your-document-dataset \\")
414
+ print(" your-markdown-output")
415
+ print("\n" + "=" * 80)
416
+ print("\nFor full help, run: uv run nanonets-ocr2.py --help")
417
+ sys.exit(0)
418
+
419
+ parser = argparse.ArgumentParser(
420
+ description="OCR images to markdown using Nanonets-OCR2-3B",
421
+ formatter_class=argparse.RawDescriptionHelpFormatter,
422
+ epilog="""
423
+ Examples:
424
+ # Basic usage
425
+ uv run nanonets-ocr2.py my-images-dataset ocr-results
426
+
427
+ # With specific image column
428
+ uv run nanonets-ocr2.py documents extracted-text --image-column scan
429
+
430
+ # Process subset for testing
431
+ uv run nanonets-ocr2.py large-dataset test-output --max-samples 100
432
+
433
+ # Random sample from ordered dataset
434
+ uv run nanonets-ocr2.py ordered-dataset random-sample --max-samples 50 --shuffle
435
+ """,
436
+ )
437
+
438
+ parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
439
+ parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
440
+ parser.add_argument(
441
+ "--image-column",
442
+ default="image",
443
+ help="Column containing images (default: image)",
444
+ )
445
+ parser.add_argument(
446
+ "--batch-size",
447
+ type=int,
448
+ default=16,
449
+ help="Batch size for processing (default: 16)",
450
+ )
451
+ parser.add_argument(
452
+ "--model",
453
+ default="nanonets/Nanonets-OCR2-3B",
454
+ help="Model to use (default: nanonets/Nanonets-OCR2-3B)",
455
+ )
456
+ parser.add_argument(
457
+ "--max-model-len",
458
+ type=int,
459
+ default=15000,
460
+ help="Maximum model context length (default: 8192)",
461
+ )
462
+ parser.add_argument(
463
+ "--max-tokens",
464
+ type=int,
465
+ default=15000,
466
+ help="Maximum tokens to generate (default: 15000)",
467
+ )
468
+ parser.add_argument(
469
+ "--gpu-memory-utilization",
470
+ type=float,
471
+ default=0.8,
472
+ help="GPU memory utilization (default: 0.8)",
473
+ )
474
+ parser.add_argument("--hf-token", help="Hugging Face API token")
475
+ parser.add_argument(
476
+ "--split", default="train", help="Dataset split to use (default: train)"
477
+ )
478
+ parser.add_argument(
479
+ "--max-samples",
480
+ type=int,
481
+ help="Maximum number of samples to process (for testing)",
482
+ )
483
+ parser.add_argument(
484
+ "--private", action="store_true", help="Make output dataset private"
485
+ )
486
+ parser.add_argument(
487
+ "--shuffle",
488
+ action="store_true",
489
+ help="Shuffle the dataset before processing (useful for random sampling)",
490
+ )
491
+ parser.add_argument(
492
+ "--seed",
493
+ type=int,
494
+ default=42,
495
+ help="Random seed for shuffling (default: 42)",
496
+ )
497
+
498
+ args = parser.parse_args()
499
+
500
+ main(
501
+ input_dataset=args.input_dataset,
502
+ output_dataset=args.output_dataset,
503
+ image_column=args.image_column,
504
+ batch_size=args.batch_size,
505
+ model=args.model,
506
+ max_model_len=args.max_model_len,
507
+ max_tokens=args.max_tokens,
508
+ gpu_memory_utilization=args.gpu_memory_utilization,
509
+ hf_token=args.hf_token,
510
+ split=args.split,
511
+ max_samples=args.max_samples,
512
+ private=args.private,
513
+ shuffle=args.shuffle,
514
+ seed=args.seed,
515
+ )