⚠️ 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:
- Abkhaz Cyrillic OCR (Tesseract) — Best for historical documents with both orthographic periods
- 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:
- Explore whether general-purpose vision-language models can be effectively fine-tuned for low-resource OCR tasks.
- Provide a baseline for future research on applying VLMs to Caucasian languages.
- 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
- Abkhaz Cyrillic Dataset for PaddleOCR — 37,514 image+transcription pairs used to train this model
- Abkhaz Cyrillic OCR Dataset (Tesseract) — 9,497 TIFF+BOX pairs for Tesseract training
- Abkhaz Mkhedruli OCR Dataset (Tesseract) — 4,221 TIFF+BOX pairs for historical Mkhedruli script
- Abkhaz Mkhedruli Dataset for PaddleOCR — 7,065 image+transcription pairs
🤖 OCR Models (Recommended for Production)
- Abkhaz Cyrillic OCR (Tesseract) — ⭐ Best for historical documents
- Abkhaz Cyrillic OCR (PaddleOCR) — ⭐ Best for modern documents
- Abkhaz Mkhedruli OCR (Tesseract) — Tesseract LSTM for Mkhedruli
- Abkhaz Mkhedruli OCR (PaddleOCR) — PaddleOCR for Mkhedruli
🏷️ NLP Pipeline
- Abkhaz POS Tagger (XLM-RoBERTa) — Part-of-speech tagging
- Abkhaz Lemmatizer (ByT5) — Byte-level lemmatization
🎙️ Speech
- OmniVoice Abkhazian Finetuned — Text-to-speech for Abkhaz
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).