Nanonets-OCR2 by Nanonets is a family of powerful, state-of-the-art image-to-markdown OCR models that go far beyond traditional text extraction. It transforms documents into structured markdown with intelligent content recognition and semantic tagging, making it ideal for downstream processing by Large Language Models (LLMs).
Nanonets-OCR2 is packed with features designed to handle complex documents with ease:
LaTeX Equation Recognition: Automatically converts mathematical equations and formulas into properly formatted LaTeX syntax. It distinguishes between inline ($...$) and display ($$...$$) equations.
Intelligent Image Description: Describes images within documents using structured <img> tags, making them digestible for LLM processing. It can describe various image types, including logos, charts, graphs and so on, detailing their content, style, and context.
Signature Detection & Isolation: Identifies and isolates signatures from other text, outputting them within a <signature> tag. This is crucial for processing legal and business documents.
Watermark Extraction: Detects and extracts watermark text from documents, placing it within a <watermark> tag.
Smart Checkbox Handling: Converts form checkboxes and radio buttons into standardized Unicode symbols (☐, ☑, ☒) for consistent and reliable processing.
Complex Table Extraction: Accurately extracts complex tables from documents and converts them into both markdown and HTML table formats.
Flow charts & Organisational charts: Extracts flow charts and organisational as mermaid code.
Handwritten Documents: The model is trained on handwritten documents across multiple languages.
Multilingual: Model is trained on documents of multiple languages, including English, Chinese, French, Spanish, Portuguese, German, Italian, Russian, Japanese, Korean, Arabic, and many more.
Visual Question Answering (VQA): The model is designed to provide the answer directly if it is present in the document; otherwise, it responds with "Not mentioned."
1from PIL import Image
2from transformers import AutoTokenizer, AutoProcessor, AutoModelForImageTextToText
34model_path ="nanonets/Nanonets-OCR2-3B"56model = AutoModelForImageTextToText.from_pretrained(7 model_path,8 torch_dtype="auto",9 device_map="auto",10 attn_implementation="flash_attention_2"11)12model.eval()1314tokenizer = AutoTokenizer.from_pretrained(model_path)15processor = AutoProcessor.from_pretrained(model_path)161718defocr_page_with_nanonets_s(image_path, model, processor, max_new_tokens=4096):19 prompt ="""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."""20 image = Image.open(image_path)21 messages =[22{"role":"system","content":"You are a helpful assistant."},23{"role":"user","content":[24{"type":"image","image":f"file://{image_path}"},25{"type":"text","text": prompt},26]},27]28 text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)29 inputs = processor(text=[text], images=[image], padding=True, return_tensors="pt")30 inputs = inputs.to(model.device)3132 output_ids = model.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False)33 generated_ids =[output_ids[len(input_ids):]for input_ids, output_ids inzip(inputs.input_ids, output_ids)]3435 output_text = processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)36return output_text[0]3738image_path ="/path/to/your/document.jpg"39result = ocr_page_with_nanonets_s(image_path, model, processor, max_new_tokens=15000)40print(result)
Using vLLM
Start the vLLM server.
vllm serve nanonets/Nanonets-OCR2-3B
Predict with the model
python
1from openai import OpenAI
2import base64
34client = OpenAI(api_key="123", base_url="http://localhost:8000/v1")56model ="nanonets/Nanonets-OCR2-3B"78defencode_image(image_path):9withopen(image_path,"rb")as image_file:10return base64.b64encode(image_file.read()).decode("utf-8")1112defocr_page_with_nanonets_s(img_base64):13 response = client.chat.completions.create(14 model=model,15 messages=[16{17"role":"user",18"content":[19{20"type":"image_url",21"image_url":{"url":f"data:image/png;base64,{img_base64}"},22},23{24"type":"text",25"text":"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.",26},27],28}29],30 temperature=0.0,31 max_tokens=1500032)33return response.choices[0].message.content
3435test_img_path ="/path/to/your/document.jpg"36img_base64 = encode_image(test_img_path)37print(ocr_page_with_nanonets_s(img_base64))
Increasing the image resolution will improve model's performance.
For complex tables (eg. Financial documents) using repetition_penalty=1 gives better results. You can try this prompt also, which generally works better for finantial documents.
user_prompt = """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. Only return HTML table within <table></table>."""
This is already implemented in Docstrange, please use the Markdown (Financial Docs) option for processing table heavy financial documents.
Model might work best on certain resolution for specific document types. Please check the cookbooks for details.
BibTex
@misc{Nanonets-OCR2,
title={Nanonets-OCR2: A model for transforming documents into structured markdown with intelligent content recognition and semantic tagging},
author={Souvik Mandal and Ashish Talewar and Siddhant Thakuria and Paras Ahuja and Prathamesh Juvatkar},
year={2025},
}