/ Модель

Характеристики

Контекст
128 000 токенов
Параметры
3,1 млрд
Размер весов
7,5 ГБ
Архитектура
qwen2_5_vl · dense
Базовая модель
Qwen2.5-VL-3B-Instruct
Библиотека
transformers
Опубликована
13 окт 2025

Nanonets-OCR2-3B

Изображение и текст → текст15 профессий

Мультимодальная модель Nanonets для распознавания многоязычных документов и преобразования текста, таблиц и других элементов в структурированный Markdown.

289 тыс.скачиваний за 30 дней517лайковвеса обновлены16 окт 2025

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Тесты пользователейпока нет

Никто ещё не опубликовал тест этой модели. Соберите бенчмарк из своих задач — результат появится здесь.

  1. Добавьте модель в бенчмарк

    Вместе с другими моделями категории «Изображение → текст» — сравнение идёт внутри одной категории.

  2. Опишите свои задачи

    Напишите запросы, при необходимости приложите файлы и эталонные ответы.

  3. Запустите и опубликуйте

    Модели ответят на каждую задачу, судья оценит ответы. Опубликованный результат появится на этой странице.

Публичные оценки2

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

  • allenai/olmOCR-bench

    score · выше — лучше

    Результат

    69,5

    long_tiny_text 93table_tests 86,8multi_column 81,9
    Hugging Face Leaderboards

    Публичная таблицаревизия не подтверждена

  • Delores-Lin/MDPBench

    score · выше — лучше

    Результат

    64,2

    ru 45,5digital 79,2it 78,5
    Hugging Face Leaderboards

    Публичная таблицаревизия не подтверждена

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

Nanonets-OCR2-3B — мультимодальная модель компании Nanonets для распознавания документов и преобразования их содержимого в структурированный Markdown. Она дообучена на базе Qwen/Qwen2.5-VL-3B-Instruct, использует архитектуру Qwen2.5-VL с 3,1 млрд параметров и принимает изображения вместе с текстовыми запросами. Контекст модели — до 128 000 токенов.

Модель извлекает текст, таблицы, формулы, водяные знаки и подписи, описывает изображения в документах, распознаёт рукописный текст и преобразует блок-схемы и организационные схемы в код Mermaid. Она также отвечает на вопросы по содержимому документа и поддерживает многоязычные документы, в том числе на русском, английском, китайском, французском, испанском, немецком, японском, корейском и арабском языках.

Модель предназначена для подготовки документов к обработке LLM и извлечения из них структурированных данных. Повышение разрешения изображения может улучшить распознавание; для сложных таблиц README рекомендует подбирать параметры генерации и разрешение. Сведения о лицензии в предоставленных данных отсутствуют.

Сценарии применения

  • извлечение текста и разметки из сканов документов
  • преобразование таблиц из финансовых документов в Markdown или HTML
  • распознавание рукописных документов на разных языках
  • извлечение формул в формате LaTeX
  • ответы на вопросы по содержимому документа
  • преобразование блок-схем и оргструктур в Mermaid

Ограничения

Точность может зависеть от разрешения изображения и типа документа; для сложных таблиц могут потребоваться настройки генерации. Лицензия не установлена по предоставленным данным.

Для каких профессий подходит15

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Также подходит для

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

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."

Nanonets-OCR2 Family

ModelAccess Link
Nanonets-OCR2-PlusDocstrange link
Nanonets-OCR2-3B🤗 link
Nanonets-OCR2-1.5B-exp🤗 link

Usage

Using transformers

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)

Using vLLM

  1. Start the vLLM server.
vllm serve nanonets/Nanonets-OCR2-3B
  1. Predict with the model
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))

Using Docstrange

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.

Evaluation

Markdown Evaluations

Nanonets OCR2 Plus

Nanonets OCR2 3B

Visual Question Answering (VQA) Evaluations

Tips to improve accuracy

  1. Increasing the image resolution will improve model's performance.
  2. 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>."""
  1. This is already implemented in Docstrange, please use the 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())
  1. 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},
}

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · transformers

Можно запустить

Подбираем GPU…

Класс архитектуры
Qwen2_5_VLForConditionalGeneration
Ревизия весов
c3886ff

0 моделей