Optical Character Recognition (OCR) has evolved far beyond simple text extraction, and Nanonets-OCR2 is the next-generation proof of that transformation. This state-of-the-art image-to-markdown OCR model doesn’t just pull text from images or PDFs, it converts entire documents into semantically rich, structured markdown ready for immediate downstream processing by Large Language Models (LLMs). From academic papers and business contracts to forms and handwritten notes, Nanonets-OCR2 handles complex layouts and content with remarkable accuracy. It intelligently recognizes LaTeX equations, distinguishing inline math from display formulas, and automatically generates properly formatted LaTeX syntax. The model also provides smart image descriptions via structured <img>
tags, identifies and isolates signatures within <signature>
tags, extracts watermarks, converts checkboxes and radio buttons into standardized Unicode symbols, and faithfully reproduces complex tables in both markdown and HTML formats. Even flow charts and organizational diagrams are transformed into Mermaid code, while multilingual support ensures documents in languages from English and Chinese to Arabic and Korean are fully supported. Additionally, the model is trained for Visual Question Answering (VQA), offering direct answers from the document when present and “Not mentioned” otherwise, making it ideal for AI-driven workflows.
If you’re building automated document pipelines, preparing data for AI models, or just need beautifully structured and machine-friendly OCR output, running Nanonets-OCR2 locally brings full control, speed, and privacy to your workflow. In this guide, we’ll walk you step-by-step through installing and running the model on your own machine, so you can start transforming documents into actionable, structured markdown right away.
Prerequisites
The minimum system requirements for this use case are:
- GPUs: 1x RTX4090 or 1x RTXA6000
- Disk Space: 20 GB
- RAM: At least 16 GB.
- Anaconda set up
Note: The prerequisites for this are highly variable across use cases. A high-end configuration could be used for a large-scale deployment.
Step-by-step process to install and run Nanonets-OCR2
For the purpose of this tutorial, we’ll use a GPU-powered Virtual Machine by NodeShift since it provides high compute Virtual Machines at a very affordable cost on a scale that meets GDPR, SOC2, and ISO27001 requirements. Also, it offers an intuitive and user-friendly interface, making it easier for beginners to get started with Cloud deployments. However, feel free to use any cloud provider of your choice and follow the same steps for the rest of the tutorial.
Step 1: Setting up a NodeShift Account
Visit app.nodeshift.com and create an account by filling in basic details, or continue signing up with your Google/GitHub account.
If you already have an account, login straight to your dashboard.
Step 2: Create a GPU Node
After accessing your account, you should see a dashboard (see image), now:
- Navigate to the menu on the left side.
- Click on the GPU Nodes option.
- Click on Start to start creating your very first GPU node.
These GPU nodes are GPU-powered virtual machines by NodeShift. These nodes are highly customizable and let you control different environmental configurations for GPUs ranging from H100s to A100s, CPUs, RAM, and storage, according to your needs.
Step 3: Selecting configuration for GPU (model, region, storage)
- For this tutorial, we’ll be using 1x RTX A6000 GPU, however, you can choose any GPU as per the prerequisites.
- Similarly, we’ll opt for 200GB storage by sliding the bar. You can also select the region where you want your GPU to reside from the available ones.
Step 4: Choose GPU Configuration and Authentication method
- After selecting your required configuration options, you’ll see the available GPU nodes in your region and according to (or very close to) your configuration. In our case, we’ll choose a 1x RTX A6000 48GB GPU node with 64vCPUs/63GB RAM/200GB SSD.
2. Next, you’ll need to select an authentication method. Two methods are available: Password and SSH Key. We recommend using SSH keys, as they are a more secure option. To create one, head over to our official documentation.
Step 5: Choose an Image
The final step is to choose an image for the VM, which in our case is Nvidia Cuda.
That’s it! You are now ready to deploy the node. Finalize the configuration summary, and if it looks good, click Create to deploy the node.
Step 6: Connect to active Compute Node using SSH
- As soon as you create the node, it will be deployed in a few seconds or a minute. Once deployed, you will see a status Running in green, meaning that our Compute node is ready to use!
- Once your GPU shows this status, navigate to the three dots on the right, click on Connect with SSH, and copy the SSH details that appear.
As you copy the details, follow the below steps to connect to the running GPU VM via SSH:
- Open your terminal, paste the SSH command, and run it.
2. In some cases, your terminal may take your consent before connecting. Enter ‘yes’.
3. A prompt will request a password. Type the SSH password, and you should be connected.
Output:
Next, If you want to check the GPU details, run the following command in the terminal:
!nvidia-smi
Step 7: Set up the project environment with dependencies
- Create a virtual environment using Anaconda.
conda create -n ocr python=3.11 -y && conda activate ocr
Output:
2. Once you’re inside the environment, install necessary dependencies to run the model.
pip install torch torchvision torchaudio einops timm pillow
pip install git+https://github.com/huggingface/transformers
pip install git+https://github.com/huggingface/accelerate
pip install git+https://github.com/huggingface/diffusers
pip install huggingface_hub
pip install sentencepiece bitsandbytes protobuf decord numpy
Output:
3. Install and run jupyter notebook.
conda install -c conda-forge --override-channels notebook -y
conda install -c conda-forge --override-channels ipywidgets -y
jupyter notebook --allow-root
4. If you’re on a remote machine (e.g., NodeShift GPU), you’ll need to do SSH port forwarding in order to access the jupyter notebook session on your local browser.
Run the following command in your local terminal after replacing:
<YOUR_SERVER_PORT>
with the PORT allotted to your remote server (For the NodeShift server – you can find it in the deployed GPU details on the dashboard).
<PATH_TO_SSH_KEY>
with the path to the location where your SSH key is stored.
<YOUR_SERVER_IP>
with the IP address of your remote server.
ssh -L 8888:localhost:8888 -p <YOUR_SERVER_PORT> -i <PATH_TO_SSH_KEY> root@<YOUR_SERVER_IP>
Output:
After this copy the URL you received in your remote server:
And paste this on your local browser to access the Jupyter Notebook session.
Step 8: Download and Run the model
- Open a Python notebook inside Jupyter.
2. Download model checkpoints.
import os
os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "1"
os.environ["TOKENIZERS_PARALLELISM"] = "false"
from huggingface_hub import snapshot_download
model_id = "nanonets/Nanonets-OCR2-3B"
local_dir = snapshot_download(
repo_id=model_id,
local_dir=None,
local_dir_use_symlinks=True,
allow_patterns=None,
tqdm_class=None
)
from transformers import AutoTokenizer, AutoProcessor, AutoModelForImageTextToText
attn_impl = "flash_attention_2"
try:
import flash_attn
except Exception:
attn_impl = "sdpa"
model = AutoModelForImageTextToText.from_pretrained(
local_dir,
torch_dtype="auto",
device_map="auto",
attn_implementation=attn_impl,
)
model.eval()
tokenizer = AutoTokenizer.from_pretrained(local_dir)
processor = AutoProcessor.from_pretrained(local_dir)
3. Run the model for inference.
from PIL import Image
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).convert("RGB")
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").to(model.device)
output_ids = model.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False)
# Slice off the prompt tokens for each batch element
generated = []
for i in range(len(inputs.input_ids)):
start = inputs.input_ids[i].shape[-1]
generated.append(output_ids[i, start:])
output_text = processor.batch_decode(generated, skip_special_tokens=True, clean_up_tokenization_spaces=True)
return output_text[0]
image_path = "doc_00569.png"
print(ocr_page_with_nanonets_s(image_path, model, processor, max_new_tokens=4096))
Here’s the output generated by the model for the given image:
Image:
Output:
Conclusion
In this guide, we saw how Nanonets-OCR2 transforms OCR by converting documents into structured markdown enriched with semantic tagging, handling everything from LaTeX equations and complex tables to signatures, watermarks, and multilingual handwritten text. These intelligent features make it a powerful tool for AI pipelines and LLM-driven workflows, enabling precise, machine-friendly document processing. If you’re running the model locally for full control or leveraging NodeShift Cloud for effortless scaling, deployment, and resource management, combining Nanonets-OCR2 with NodeShift’s cloud infrastructure ensures seamless, efficient, and production-ready document automation at any scale.