/ Модель

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

Контекст
1 024 токена
Лицензия
CC BY-NC-SA 4.0
Архитектура
florence2 · dense
Библиотека
transformers
Опубликована
4 ноя 2026

abkhaz-cyrillic-ocr-florence2

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

Экспериментальная Florence-2 для распознавания абхазского текста на кириллице в изображениях отдельных строк.

84скачиваний за 30 дней0лайковвеса обновлены4 ноя 2026

Бенчмарки

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

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

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

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

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

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

Экспериментальная модель распознавания абхазского текста на кириллице по изображениям. Её разработал Марат Ионов совместно с Фондом Баграта Шинкуба как часть проекта цифровой инфраструктуры абхазского языка. Модель Florence-2 с архитектурой encoder-decoder дообучена на 37 514 парах изображений и транскрипций из набора Grundik/abkhaz-cyrillic-dataset-paddle; данные представляют собой отдельные строки текста, а не страницы документов.

Модель предназначена для OCR отдельных строк и для экспериментов с применением VLM к распознаванию текста на малоресурсных языках. Она хуже справляется с редкими абхазскими буквами, историческими вариантами орфографии и повреждёнными сканами. Для распознавания страниц и практического использования автор рекомендует специализированные модели Tesseract или PaddleOCR. Лицензия — CC BY-NC-SA 4.0.

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

  • распознавание абхазского текста на изображениях отдельных строк
  • создание базовых транскрипций абхазских текстовых фрагментов
  • эксперименты с OCR для малоресурсных языков
  • исследование применения Florence-2 к абхазским документам

Ограничения

Обучена на изображениях отдельных строк и не оценивалась для распознавания полных страниц и их макета. Качество ниже Tesseract и PaddleOCR; модель испытывает трудности с редкими абхазскими буквами, историческими вариантами орфографии и шумными сканами.

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

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

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

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

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

Открыть на Hugging Face

⚠️ Abkhaz Cyrillic OCR (Florence-2) [EXPERIMENTAL]

This is an experimental model. For production use, please refer to the Tesseract or PaddleOCR models, which demonstrate significantly better quality.

An experimental Florence-2 vision-language model for recognizing the Abkhaz language (ISO 639-1: ab) in Cyrillic script. This model was trained as a proof-of-concept to explore the applicability of general-purpose vision-language models to low-resource OCR tasks.

This model is part of the digital infrastructure project for the Abkhaz language, developed by Marat Ionov in collaboration with the Bagrat Shinkuba Fund (Фонд Баграта Шинкуба).

⚠️ Experimental Status & Performance

Important: This model is provided for research and experimental purposes only.

Training Limitations

  • The model was trained on a line-level dataset (Grundik/abkhaz-cyrillic-dataset-paddle), which contains only individual text lines, not full-page documents.
  • As a result, the model has not been evaluated on page-level OCR tasks (detecting text regions, handling multi-column layouts, etc.).
  • The training data consists of 37,514 image + transcription pairs (.tif + .txt), but these are cropped line segments, not complete pages.

Observed Performance

During inference testing on individual text lines:

  • Quality is lower than both Tesseract and PaddleOCR models.
  • The model struggles with:
    • Rare Abkhaz-specific characters (ә, ҧ, ҳ, қ, ҭ, ҽ, ҿ, ӡ, џ, ҕ, ӷ, ҟ, ҵ, ҩ, ҷ, ԥ)
    • Historical orthographic variants (Ҧ ҧ, Ҕ ҕ from the 1954–1996 period)
    • Noisy or degraded scans

Recommendation

For practical OCR tasks on Abkhaz Cyrillic documents, use the specialized models instead:

  1. Abkhaz Cyrillic OCR (Tesseract) — Best for historical documents with both orthographic periods
  2. Abkhaz Cyrillic OCR (PaddleOCR) — Best for modern documents and batch processing

Model Details

  • Base Model: microsoft/Florence-2-base
  • Model Type: Vision-language model (encoder-decoder architecture)
  • Task: Image-to-text (OCR)
  • Target Script: Abkhaz Cyrillic
  • Training Prompt: <OCR> (Florence-2's standard OCR prompt)

Training Details

  • Training dataset: Grundik/abkhaz-cyrillic-dataset-paddle
  • Training samples: 37,514 image + transcription pairs (.tif + .txt)
  • Training regime: Fine-tuned from Florence-2-base on line-level OCR data
  • Epochs: 2 (experimental, limited due to computational constraints)
  • Data composition: Mix of synthetic data (38 fonts) and real-world scans from apsnyteka.org

Usage

Installation

pip install transformers torch pillow

Quick Start

The included ocr_florence2_kyr.py script provides a simple interface:

python3 ocr_florence2_kyr.py path/to/image.tif
python3 ocr_florence2_kyr.py path/to/image.tif --save output.txt

Using Transformers API Directly

import torch
from PIL import Image
from transformers import AutoModelForCausalLM, AutoProcessor

model_id = "Grundik/abkhaz-cyrillic-ocr-florence2"
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    trust_remote_code=True,
    torch_dtype="auto"
)
processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)

device = "cuda" if torch.cuda.is_available() else "cpu"
model = model.to(device)

image = Image.open("image.tif").convert("RGB")
prompt = "<OCR>"

inputs = processor(text=prompt, images=image, return_tensors="pt").to(device)

with torch.no_grad():
    generated_ids = model.generate(
        input_ids=inputs["input_ids"],
        pixel_values=inputs["pixel_values"],
        max_new_tokens=1024,
        num_beams=1,
        do_sample=False
    )

generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
print(generated_text)

Full Inference Script

Below is the complete ocr_florence2_kyr.py script. Save it and run directly:

#!/usr/bin/env python3
"""
Экспериментальный OCR-скрипт на базе Florence-2 для абхазской кириллицы.
Модель: Grundik/abkhaz-cyrillic-ocr-florence2 (https://huggingface.co/Grundik/abkhaz-cyrillic-ocr-florence2)

ВАЖНО: Эта модель является экспериментальной и показывает качество ниже,
чем специализированные OCR-решения (Tesseract, PaddleOCR).
Используйте её только для исследовательских целей.

Использование:
  python3 ocr_florence2_kyr.py <путь_к_файлу>
  python3 ocr_florence2_kyr.py <файл> --save output.txt
  python3 ocr_florence2_kyr.py <файл> --prompt "<OCR>"
"""
import argparse
import os
import sys
from pathlib import Path
from PIL import Image
import torch
from transformers import AutoModelForCausalLM, AutoProcessor

# ─── Настройки модели ────────────────────────────────────────────────────
HF_REPO_ID = "Grundik/abkhaz-cyrillic-ocr-florence2"
DEFAULT_PROMPT = "<OCR>"


def load_model(model_path: str = None):
    """Загружает модель Florence-2 с HF или локально."""
    if model_path and Path(model_path).exists():
        repo_id = model_path
    else:
        repo_id = HF_REPO_ID
        print(f"Загрузка модели {HF_REPO_ID} с Hugging Face...")
    
    try:
        model = AutoModelForCausalLM.from_pretrained(
            repo_id,
            trust_remote_code=True,
            torch_dtype="auto"
        )
        processor = AutoProcessor.from_pretrained(repo_id, trust_remote_code=True)
        
        device = "cuda" if torch.cuda.is_available() else "cpu"
        model = model.to(device)
        model.eval()
        
        print(f"Модель загружена на {device}")
        return model, processor, device
    except Exception as e:
        print(f"Ошибка загрузки модели: {e}", file=sys.stderr)
        sys.exit(1)


def run_ocr(image_path: Path, model, processor, device: str, prompt: str):
    """Запускает OCR через Florence-2."""
    image = Image.open(image_path).convert("RGB")
    
    inputs = processor(text=prompt, images=image, return_tensors="pt").to(device)
    
    with torch.no_grad():
        generated_ids = model.generate(
            input_ids=inputs["input_ids"],
            pixel_values=inputs["pixel_values"],
            max_new_tokens=1024,
            num_beams=1,
            do_sample=False
        )
    
    generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
    
    # Florence-2 возвращает текст в формате "<OCR>текст"
    # Извлекаем текст после промпта
    if generated_text.startswith(prompt):
        result_text = generated_text[len(prompt):].strip()
    else:
        result_text = generated_text.strip()
    
    return result_text


def main():
    parser = argparse.ArgumentParser(
        description="Экспериментальный OCR через Florence-2 для абхазской кириллицы"
    )
    parser.add_argument("input", help="Путь к файлу изображения")
    parser.add_argument("--model-path", type=str, default=None,
                        help="Локальный путь к модели (по умолчанию загружается с HF)")
    parser.add_argument("--prompt", type=str, default=DEFAULT_PROMPT,
                        help=f"Промпт для Florence-2 (по умолчанию: {DEFAULT_PROMPT})")
    parser.add_argument("--save", type=str, default=None,
                        help="Сохранить результат в файл")
    args = parser.parse_args()

    img_path = Path(args.input)
    if not img_path.exists():
        print(f"Файл не найден: {img_path}", file=sys.stderr)
        sys.exit(1)

    print("⚠️  ВНИМАНИЕ: Это экспериментальная модель.")
    print("   Качество распознавания ниже, чем у Tesseract и PaddleOCR.")
    print("   Используйте для исследовательских целей.\n")

    model, processor, device = load_model(args.model_path)
    result_text = run_ocr(img_path, model, processor, device, args.prompt)

    print("---")
    print(result_text)

    if args.save:
        out = Path(args.save)
        out.write_text(result_text, encoding="utf-8")
        print(f"\nСохранено в: {out}")


if __name__ == "__main__":
    main()

Why This Model Exists

This experimental model was created to:

  1. Explore whether general-purpose vision-language models can be effectively fine-tuned for low-resource OCR tasks.
  2. Provide a baseline for future research on applying VLMs to Caucasian languages.
  3. Document the limitations of using line-level training data for page-level OCR tasks.

The results show that specialized OCR architectures (Tesseract LSTM, PaddleOCR) significantly outperform general-purpose VLMs for this specific task, likely due to:

  • Better handling of rare characters through custom character dictionaries
  • Optimization for document-specific features (line detection, layout analysis)
  • More extensive training on domain-specific data

Related Resources & Cross-References

This model is part of a broader ecosystem for Abkhaz language digitalization:

📊 Training Datasets

🤖 OCR Models (Recommended for Production)

🏷️ NLP Pipeline

🎙️ Speech

Citation

If you use this experimental model in your research, please cite:

@misc{abkhaz_cyrillic_ocr_florence2_2024,
  author = {Ionov, Marat and Bagrat Shinkuba Fund},
  title = {Abkhaz Cyrillic OCR (Florence-2) [Experimental]},
  year = {2024},
  publisher = {Hugging Face},
  url = {https://huggingface.co/Grundik/abkhaz-cyrillic-ocr-florence2},
  note = {Experimental model. For production use, see Tesseract or PaddleOCR variants.}
}

Author & Acknowledgments

Model trained and evaluated by Marat Ionov as part of the digital preservation initiative, supported by the Bagrat Shinkuba Fund.

License

This model is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0).

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

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

GPU в ailist

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

Нельзя запустить

Модели нужен код из репозитория; запуск откроется после проверки совместимости.

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

0 моделей