Downloads · 30 days
2
2% of all-time downloads
MohamedQiqa/legal-documents-ocr-parser-1.0
legal-documents-ocr-parser-1.0 is a machine learning model from MohamedQiqa. Use it for the machine learning task on the model card, and read the license before you ship it in a product.
Downloads · 30 days
2
2% of all-time downloads
All-time downloads
85
Public
Parameters
4.3B
23.7 GB on disk
Likes
0
Public
Click a slice to open those files.
.safetensors13.6 GB · 57%
From the Hugging Face model README
A multimodal vision-language model specialized in extracting structured metadata from scanned Arabic legal documents, including government regulations, official correspondence, and institutional records.
</div>Arabic Legal Documents OCR Parser is a multimodal vision-language model fine-tuned from Google's Gemma-3-4B-IT for the task of structured metadata extraction from scanned Arabic legal documents. Given an image of a legal document page, the model outputs a comprehensive JSON object containing classified document metadata — including document type, issuing authority, physical properties, official seals/stamps, signatures, routing information, and quality assessments.
The model was fine-tuned using LoRA (Low-Rank Adaptation) via LLaMA-Factory. After training, the LoRA adapter was merged back into the base model — this repository contains the full-precision merged weights, ready for direct inference without any adapter loading or quantization.
| Attribute | Details |
|---|---|
| Developed by | MohamedSamyAI |
| Model type | Multimodal Vision-Language Model (Image-to-Text) |
| Language(s) | Arabic (primary), English (secondary) |
| License | Apache 2.0 |
| Fine-tuned from | google/gemma-3-4b-it |
| Fine-tuning method | LoRA (adapter merged into base model) |
| Model format | Full-precision merged weights (no quantization) |
| Fine-tuning framework | LLaMA-Factory |
This model is designed for automated extraction of structured metadata from scanned images of Arabic legal documents. It is suitable for:
The model can be integrated into larger systems:
This model is NOT intended for:
from transformers import AutoProcessor, AutoModelForImageTextToText
from PIL import Image
import torch
import json
# Load the merged model directly — no adapter loading needed
model_id = "MohamedSamyAI/arabic-legal-documents-ocr-parser-1.0"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForImageTextToText.from_pretrained(
model_id,
torch_dtype=torch.float16,
device_map="auto",
)
# Load your document image
image = Image.open("path/to/legal_document.jpg")
# Prepare the prompt
prompt = """<image>You are a professional OCR Details Extractor.
Your rule to extract the: document_classification, source, physical_properties, official_marks, signatures_authorization, routing_distribution, attachments_references, condition_notes and confidence_quality of the document.
Extract the final output into a json format.
Do not generate any introduction or conclusion."""
messages = [
{"role": "user", "content": [
{"type": "image"},
{"type": "text", "text": prompt}
]}
]
# Generate
inputs = processor.apply_chat_template(messages, return_tensors="pt").to(model.device)
outputs = model.generate(**inputs, max_new_tokens=2048)
result = processor.decode(outputs[0], skip_special_tokens=True)
# Parse the JSON output
parsed = json.loads(result)
print(json.dumps(parsed, indent=2, ensure_ascii=False))
💡 Note: This is a fully merged model — you load it directly like any other model. No adapter paths or LoRA configuration required.
llamafactory-cli chat \
--model_name_or_path MohamedSamyAI/arabic-legal-documents-ocr-parser-1.0 \
--template gemma3
The model was fine-tuned on a custom dataset of Arabic legal documents, including:
human → image + instruction, gpt → structured JSON output).| Split | Description |
|---|---|
| Train | Primary training set with diverse legal document types |
| Validation | Held-out set for monitoring overfitting during training |
The model was fine-tuned using Supervised Fine-Tuning (SFT) with QLoRA (4-bit quantized LoRA). After training, the LoRA adapter was merged back into the base model to produce the full merged weights published in this repository.
762b480)lora_target: all)bitsandbytes (used during training for memory efficiency)paged_adamw_8bit)| Parameter | Value |
|---|---|
| LoRA rank | 16 |
| LoRA target | All linear layers |
| Quantization (training) | 4-bit NF4 (bitsandbytes) — training only, merged model is unquantized |
| Batch size | 1 (per device) |
| Gradient accumulation | 8 steps |
| Effective batch size | 8 |
| Learning rate | 1e-4 |
| LR scheduler | Cosine |
| Warmup ratio | 0.1 |
| Epochs | 3 |
| Max sequence length | 2048 tokens |
| Precision | FP16 |
| Gradient checkpointing | ✅ Enabled |
| Vision tower | 🧊 Frozen |
gemma3 chat template via LLaMA-Factory.ensure_ascii=False).Evaluation was performed on the held-out validation set during training, with metrics logged via Weights & Biases.
| Metric | Details |
|---|---|
| Eval strategy | Every 50 training steps |
| Eval batch size | 1 |
| Tracking | WandB (yt-ocr-finetune-llamafactory) |
The model produces structured JSON with the following extraction categories:
├── document_classification → type, subtype, category, languages
├── source → issuing authority, department, dates, references
├── physical_properties → page info, scan quality, orientation, watermarks
├── official_marks → seals, stamps, barcodes/QR codes
├── signatures_authorization → signatories, approval chains
├── routing_distribution → addressees, CC, forwarding info
├── attachments_references → mentioned attachments, referenced documents
├── condition_notes → completeness, legibility, damage, annotations
└── confidence_quality → overall confidence, uncertain elements, review flags
| Component | Specification |
|---|---|
| Platform | Kaggle Notebooks |
| GPU | NVIDIA P100 / T4 (16 GB VRAM) |
| Precision | FP16 mixed-precision |
| Memory optimization (training) | 4-bit QLoRA + gradient checkpointing + paged optimizer |
| Runtime | Python 3.12, PyTorch 2.8.0, Transformers 4.57.6 |
confidence_quality field in model outputs to flag uncertain extractions.requires_manual_review flag to route low-confidence documents to human reviewers.Carbon emissions were estimated using the ML CO2 Impact Calculator.
| Factor | Estimate |
|---|---|
| Hardware type | NVIDIA P100 (16 GB) |
| Hours used | ~3–4 hours |
| Cloud provider | Kaggle (Google Cloud) |
| Compute region | US |
| Carbon emitted | ~0.5 kg CO₂ eq. (estimated) |
If you use this model in your research or applications, please cite:
@misc{mohamedsamyai2026arabiclegaldocparser,
title = {Arabic Legal Documents OCR Parser},
author = {Mohamed Samy},
year = {2026},
publisher = {Hugging Face},
howpublished = {\url{https://huggingface.co/MohamedSamyAI/arabic-legal-documents-ocr-parser-1.0}},
note = {Fine-tuned from google/gemma-3-4b-it using QLoRA via LLaMA-Factory, adapter merged into base}
}
Mohamed Samy. (2026). Arabic Legal Documents OCR Parser [Multimodal Language Model]. Hugging Face. https://huggingface.co/MohamedSamyAI/arabic-legal-documents-ocr-parser-1.0
For questions, suggestions, or issues with this model card, please open a discussion on the model repository or contact the author via Hugging Face.
Built with ❤️ using Gemma 3 and LLaMA-Factory
</div>