/ Модель

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

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

KarantaOCR

Генерация текстаТекст → текст8 профессий

KarantaOCR — дообученная мультимодальная модель для извлечения текста, таблиц и структуры документов, особенно на африканских языках.

28скачиваний за 30 дней7лайковвеса обновлены25 янв 2026

Бенчмарки

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

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

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

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

    Вместе с другими моделями категории «Текст» — сравнение идёт внутри одной категории.

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

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

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

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

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

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

В подключённых источниках результатов для этой модели пока нет.

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

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

KarantaOCR — мультимодальная модель распознавания и обработки документов, созданная разработчиками проекта KarantaOCR на основе Qwen/Qwen2.5-VL-3B-Instruct. Модель содержит 3,1 млрд параметров и дообучена по двухэтапной схеме: сначала на общих OCR-данных, затем на PDF-документах на африканских языках.

Модель извлекает текст из PDF, включая таблицы и документы со сложной вёрсткой, несколькими колонками, колонтитулами и сочетанием сканируемого и цифрового текста. Её ключевой акцент — точная передача диакритики и специальных символов в африканских языках; также заявлена поддержка английского и других распространённых языков. Для распознавания страницы PDF её нужно представить модели как изображение и использовать структурированный запрос.

Модель использует архитектуру Qwen2.5-VL и поддерживает контекст до 128 000 токенов. README приводит результаты на OCR-бенчмарках, но они зависят от типа документа и не гарантируют точность на конкретных данных. Репозиторий распространяется по лицензии Apache-2.0.

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

  • извлечение текста из PDF на африканских языках
  • распознавание диакритики и специальных символов в документах
  • извлечение таблиц из PDF
  • распознавание текста в многостраничных и многоколоночных документах
  • обработка смешанных сканированных и цифровых PDF

Ограничения

Для распознавания страниц PDF требуется предварительно преобразовать их в изображения и сформировать структурированный запрос. Приведённые оценки относятся к указанным бенчмаркам и могут не отражать качество на других документах.

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

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

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

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

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

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

Открыть на Hugging Face

KarantaOCR: Efficient Document Processing for African Languages

Table of Contents


Model Description

Paper

KarantaOCR is an open-source document OCR and processing model designed for high-accuracy text extraction in African languages. The model focuses on preserving language-specific characters and diacritics that are often lost, normalized, or mis-transcribed by existing OCR systems.

KarantaOCR is fine-tuned from Qwen/Qwen2.5-VL-3B-Instruct, a vision-language model that combines a strong vision encoder with a large language model. Through targeted curriculum fine-tuning, KarantaOCR extends these capabilities to robust document understanding across diverse PDF formats and multilingual settings.

Training Data

KarantaOCR was trained using a two-stage curriculum fine-tuning strategy.

Stage 1: General OCR Training

  • 100,000 documents sampled from Allenai OCRMix
  • Purpose: learn general OCR skills across layouts, fonts, tables, and document structures

Stage 2: African Language Fine-Tuning

  • 50,000 PDFs containing text in 10 African languages, crawled from the web

  • Domains include:

    • Religious texts
    • Legal documents
    • Dictionaries
    • Novels
    • Other long-form and structured documents

This stage emphasizes accurate transcription of diacritics, special characters, and region-specific typography.

Training Plots


Capabilities

KarantaOCR supports:

  • High-accuracy text extraction from PDFs

  • Table extraction and structured document understanding

  • Robust handling of:

    • Multi-column layouts
    • Headers and footers
    • Mixed scanned and digital PDFs

While improved performance on African languages was our priority, KarantaOCR maintains strong performance on English and other high-resource languages, making it suitable for mixed-language document collections.

Evaluation

KarantaOCR is evaluated on the OLMOocr benchmark using pass-rate accuracy. Scores are reported as averages across JSONL files with 95% confidence intervals. In addition to OLMOocr benchmark, we also create a KarantaOCR-Bench, which focuses specifically on testing OCR extraction on special characters and diacritics.

Results -- KarantaOCR-Bench

JSONL FileKarantaOCR (3B)RoLMOCR (7B)NanoNetsOCR-2 (3B)OLMOCR-2 (7B)
Diacritics & Special Characters61.653.655.155.5

Results -- OlmoOCR-Bench

JSONL FileKarantaOCR (3B)RoLMOCR (7B)NanoNetsOCR-2 (3B)OLMOCR-1 (7B)OLMOCR-2 (7B)Mistral OCR APIDeepSeek-OCR (3B)
arxiv_math74.276.873.763.383.077.277.2
baseline99.497.999.597.999.799.499.8
headers_footers95.394.132.893.496.193.696.1
long_tiny_text72.261.392.154.881.977.179.4
multi_column75.670.082.567.683.771.366.4
old_scans41.342.441.438.647.729.333.3
old_scans_math70.380.144.167.582.367.573.6
table_tests64.372.284.262.384.960.680.2
Average74.1%74.4%68.8%68.2%82.4%72.075.7

How to Use

KarantaOCR processes PDF documents by rendering pages into images and combining them with structured prompts for inference.

Load the Model and Processor

import torch
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor

def load_model(model_path: str, device_map: str = "auto", dtype: str = "auto"):
    model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
        model_path,
        torch_dtype=getattr(torch, dtype) if dtype != "auto" else "auto",
        device_map=device_map,
    )
    return model

def load_processor(processor_name: str, min_pixels=None, max_pixels=None):
    if min_pixels and max_pixels:
        return AutoProcessor.from_pretrained(
            processor_name, min_pixels=min_pixels, max_pixels=max_pixels
        )
    return AutoProcessor.from_pretrained(processor_name)

Prepare a PDF Page for Inference

from jinja2 import Template

def render_pdf_to_base64png(
    local_pdf_path: str, page_num: int, target_longest_image_dim: int = 2048
) -> str:
    longest_dim = max(get_pdf_media_box_width_height(local_pdf_path, page_num))

    # Convert PDF page to PNG using pdftoppm
    pdftoppm_result = subprocess.run(
        [
            "pdftoppm",
            "-png",
            "-f",
            str(page_num),
            "-l",
            str(page_num),
            "-r",
            str(
                target_longest_image_dim * 72 / longest_dim
            ),  # 72 pixels per point is the conversion factor
            local_pdf_path,
        ],
        timeout=120,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )
    assert pdftoppm_result.returncode == 0, pdftoppm_result.stderr
    return base64.b64encode(pdftoppm_result.stdout).decode("utf-8")

def build_message(image_url: str, system_prompt: str, page: int = 0):
    image_base64 = render_pdf_to_base64png(image_url, page, TARGET_IMAGE_DIM)

    prompt = [
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": system_prompt
                },
                {
                    "type": "image",
                    "image": f"data:image/png;base64,{image_base64}",
                },
            ],
        }
    ]
    return prompt

Run OCR Inference

from qwen_vl_utils import process_vision_info

def run_inference(model, processor, messages, max_new_tokens=128, device="cuda"):
    text = processor.apply_chat_template(
        messages, tokenize=False, add_generation_prompt=True
    )

    image_inputs, _ = process_vision_info(messages)
    inputs = processor(
        text=[text],
        images=image_inputs,
        padding=False,
        return_tensors="pt",
    ).to(device)

    generated_ids = model.generate(**inputs, max_new_tokens=max_new_tokens)
    trimmed_ids = [
        out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
    ]

    outputs = processor.batch_decode(
        trimmed_ids,
        skip_special_tokens=True,
        clean_up_tokenization_spaces=False,
    )
    return outputs[0]

End-to-End Example

model = load_model("taresco/KarantaOCR")
processor = load_processor("taresco/KarantaOCR")

prompt = """Below is the image of one page of a PDF document.
Just return the plain text representation of this document as if you were reading it naturally.
Turn equations into a LaTeX representation, and tables into markdown format. Remove the headers and footers, but keep references and footnotes.
Read any natural handwriting.
This is likely one page out of several in the document, so be sure to preserve any sentences that come from the previous page, or continue onto the next page, exactly as they are.
If there is no text at all that you think you should read, you can output null.
if the document contains diacritics, please include them in the output.
Do not hallucinate.
"""

messages = build_message(
    image_url="example.pdf",
    system_prompt=prompt,
    page=0
)

output_text = run_inference(model, processor, messages)
print(output_text)

Citation Information

Coming soon ...

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

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

GPU в ailist

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

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

Подбираем GPU…

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

0 моделей