Nanonets-OCR2
Collection
2 items • Updated • 25
How to use nanonets/Nanonets-OCR2-3B with Transformers:
# Use a pipeline as a high-level helper
from transformers import pipeline
pipe = pipeline("image-text-to-text", model="nanonets/Nanonets-OCR2-3B")
messages = [
{
"role": "user",
"content": [
{"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"},
{"type": "text", "text": "What animal is on the candy?"}
]
},
]
pipe(text=messages) # Load model directly
from transformers import AutoProcessor, AutoModelForImageTextToText
processor = AutoProcessor.from_pretrained("nanonets/Nanonets-OCR2-3B")
model = AutoModelForImageTextToText.from_pretrained("nanonets/Nanonets-OCR2-3B")
messages = [
{
"role": "user",
"content": [
{"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"},
{"type": "text", "text": "What animal is on the candy?"}
]
},
]
inputs = processor.apply_chat_template(
messages,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
return_tensors="pt",
).to(model.device)
outputs = model.generate(**inputs, max_new_tokens=40)
print(processor.decode(outputs[0][inputs["input_ids"].shape[-1]:]))How to use nanonets/Nanonets-OCR2-3B with vLLM:
# Install vLLM from pip:
pip install vllm
# Start the vLLM server:
vllm serve "nanonets/Nanonets-OCR2-3B"
# Call the server using curl (OpenAI-compatible API):
curl -X POST "http://localhost:8000/v1/chat/completions" \
-H "Content-Type: application/json" \
--data '{
"model": "nanonets/Nanonets-OCR2-3B",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Describe this image in one sentence."
},
{
"type": "image_url",
"image_url": {
"url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
}
}
]
}
]
}'docker model run hf.co/nanonets/Nanonets-OCR2-3B
How to use nanonets/Nanonets-OCR2-3B with SGLang:
# Install SGLang from pip:
pip install sglang
# Start the SGLang server:
python3 -m sglang.launch_server \
--model-path "nanonets/Nanonets-OCR2-3B" \
--host 0.0.0.0 \
--port 30000
# Call the server using curl (OpenAI-compatible API):
curl -X POST "http://localhost:30000/v1/chat/completions" \
-H "Content-Type: application/json" \
--data '{
"model": "nanonets/Nanonets-OCR2-3B",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Describe this image in one sentence."
},
{
"type": "image_url",
"image_url": {
"url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
}
}
]
}
]
}'docker run --gpus all \
--shm-size 32g \
-p 30000:30000 \
-v ~/.cache/huggingface:/root/.cache/huggingface \
--env "HF_TOKEN=<secret>" \
--ipc=host \
lmsysorg/sglang:latest \
python3 -m sglang.launch_server \
--model-path "nanonets/Nanonets-OCR2-3B" \
--host 0.0.0.0 \
--port 30000
# Call the server using curl (OpenAI-compatible API):
curl -X POST "http://localhost:30000/v1/chat/completions" \
-H "Content-Type: application/json" \
--data '{
"model": "nanonets/Nanonets-OCR2-3B",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Describe this image in one sentence."
},
{
"type": "image_url",
"image_url": {
"url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
}
}
]
}
]
}'How to use nanonets/Nanonets-OCR2-3B with Docker Model Runner:
docker model run hf.co/nanonets/Nanonets-OCR2-3B
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:
$...$) and display ($$...$$) equations.<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> tag. This is crucial for processing legal and business documents.<watermark> tag.☐, ☑, ☒) for consistent and reliable processing.| Model | Access Link |
|---|---|
| Nanonets-OCR2-Plus | Docstrange link |
| Nanonets-OCR2-3B | 🤗 link |
| Nanonets-OCR2-1.5B-exp | 🤗 link |
from PIL import Image
from transformers import AutoTokenizer, AutoProcessor, AutoModelForImageTextToText
model_path = "nanonets/Nanonets-OCR2-3B"
model = AutoModelForImageTextToText.from_pretrained(
model_path,
torch_dtype="auto",
device_map="auto",
attn_implementation="flash_attention_2"
)
model.eval()
tokenizer = AutoTokenizer.from_pretrained(model_path)
processor = AutoProcessor.from_pretrained(model_path)
def ocr_page_with_nanonets_s(image_path, model, processor, max_new_tokens=4096):
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."""
image = Image.open(image_path)
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": [
{"type": "image", "image": f"file://{image_path}"},
{"type": "text", "text": prompt},
]},
]
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = processor(text=[text], images=[image], padding=True, return_tensors="pt")
inputs = inputs.to(model.device)
output_ids = model.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False)
generated_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(inputs.input_ids, output_ids)]
output_text = processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)
return output_text[0]
image_path = "/path/to/your/document.jpg"
result = ocr_page_with_nanonets_s(image_path, model, processor, max_new_tokens=15000)
print(result)
vllm serve nanonets/Nanonets-OCR2-3B
from openai import OpenAI
import base64
client = OpenAI(api_key="123", base_url="http://localhost:8000/v1")
model = "nanonets/Nanonets-OCR2-3B"
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
def ocr_page_with_nanonets_s(img_base64):
response = client.chat.completions.create(
model=model,
messages=[
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {"url": f"data:image/png;base64,{img_base64}"},
},
{
"type": "text",
"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.",
},
],
}
],
temperature=0.0,
max_tokens=15000
)
return response.choices[0].message.content
test_img_path = "/path/to/your/document.jpg"
img_base64 = encode_image(test_img_path)
print(ocr_page_with_nanonets_s(img_base64))
import requests
url = "https://extraction-api.nanonets.com/extract"
headers = {"Authorization": <API KEY>}
files = {"file": open("/path/to/your/file", "rb")}
data = {"output_type": "markdown"}
data["model"] = "nanonets"
response = requests.post(url, headers=headers, files=files, data=data)
print(response.json())
Check out Docstrange for more details.
| Model | Win Rate vs Nanonets OCR2 Plus (%) | Lose Rate vs Nanonets OCR2 Plus (%) | Both Correct (%) |
|---|---|---|---|
| Gemini 2.5 flash (No Thinking) | 34.35 | 57.60 | 8.06 |
| Nanonets OCR2 3B | 29.37 | 54.58 | 16.04 |
| Nanonets-OCR-s | 24.86 | 66.12 | 9.02 |
| Nanonets OCR2 1.5B exp | 13.00 | 81.20 | 5.79 |
| GPT-5 (Thinking: low) | 23.53 | 74.86 | 1.60 |
| Model | Win Rate vs Nanonets OCR2 3B (%) | Lose Rate vs Nanonets OCR2 3B (%) | Both Correct (%) |
|---|---|---|---|
| Gemini 2.5 flash (No Thinking) | 39.98 | 52.43 | 7.58 |
| Nanonets-OCR-s | 30.61 | 58.28 | 11.12 |
| Nanonets OCR2 1.5B exp | 14.78 | 79.18 | 6.04 |
| GPT-5 | 25.00 | 72.87 | 2.13 |
| Dataset | Nanonets OCR2 Plus | Nanonets OCR2 3B | Qwen2.5-VL-72B-Instruct | Gemini 2.5 Flash |
|---|---|---|---|---|
| ChartQA (IDP-Leaderboard) | 79.20 | 78.56 | 76.20 | 84.82 |
| DocVQA (IDP-Leaderboard) | 85.15 | 89.43 | 84.00 | 85.51 |
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>."""
Markdown (Financial Docs) option for processing table heavy financial documents.import requests
url = "https://extraction-api.nanonets.com/extract"
headers = {"Authorization": <API KEY>}
files = {"file": open("/path/to/your/file", "rb")}
data = {"output_type": "markdown-financial-docs"}
response = requests.post(url, headers=headers, files=files, data=data)
print(response.json())
@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},
}
Base model
Qwen/Qwen2.5-VL-3B-Instruct