Views
No views yet
| Feature | Value |
|---|---|
| Base Model | Qwen/Qwen2.5-VL-3B-Instruct |
| Parameters | 3 Billion |
| Quantization | 4-bit |
| Supported Languages | Arabic, English |
| Model Type | Multimodal (Image + Text) |
| License | Apache-2.0 |
1from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
2import torch
3from PIL import Image
4from typing import List, Dict
5
6def process_vision_info(messages: List[dict]):
7 image_inputs = []
8 video_inputs = []
9 for message in messages:
10 if isinstance(message["content"], list):
11 for item in message["content"]:
12 if item["type"] == "image":
13 image = item["image"]
14 if isinstance(image, str):
15 image = Image.open(image).convert("RGB")
16 elif isinstance(image, Image.Image):
17 pass
18 else:
19 raise ValueError(f"Unsupported image type: {type(image)}")
20 image_inputs.append(image)
21 elif item["type"] == "video":
22 video_inputs.append(item["video"])
23 return image_inputs if image_inputs else None, video_inputs if video_inputs else None
24
25# Load model and processor
26model_name = "sherif1313/Arabic-handwritten-OCR-4bit-Qwen2.5-VL-3B-v1"
27model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
28 model_name,
29 torch_dtype=torch.float16,
30 device_map="auto"
31)
32
33# Setup processor
34min_pixels = 512 * 28 * 28
35max_pixels = 2048 * 28 * 28
36processor = AutoProcessor.from_pretrained(
37 model_name,
38 min_pixels=min_pixels,
39 max_pixels=max_pixels
40)
41
42def extract_text_from_image(image_path):
43 try:
44 messages = [
45 {
46 "role": "user",
47 "content": [
48 {"type": "image", "image": image_path},
49 {"type": "text", "text": "Read all texts in this image and extract them as they are. Don't miss any word."},
50 ],
51 }
52 ]
53
54 text = processor.apply_chat_template(
55 messages, tokenize=False, add_generation_prompt=True
56 )
57 image_inputs, video_inputs = process_vision_info(messages)
58
59 inputs = processor(
60 text=[text],
61 images=image_inputs,
62 videos=video_inputs,
63 padding=True,
64 return_tensors="pt",
65 ).to(model.device)
66
67 generated_ids = model.generate(
68 **inputs,
69 max_new_tokens=1000,
70 do_sample=False,
71 pad_token_id=processor.tokenizer.pad_token_id
72 )
73
74 input_len = inputs.input_ids.shape[1]
75 output_text = processor.batch_decode(
76 generated_ids[:, input_len:],
77 skip_special_tokens=True,
78 clean_up_tokenization_spaces=False
79 )[0]
80
81 return output_text.strip()
82
83 except Exception as e:
84 return f"Error processing image: {e}"
85
86# Usage example
87if __name__ == "__main__":
88 image_path = "path/to/your/image.jpg" # Replace with your image path
89 extracted_text = extract_text_from_image(image_path)
90 print("Extracted Text:")
91 print(extracted_text)
92
93
94
95
96
97
98
99🏋️ Training Data
100Data Sources:
101
102 Muharaf Public Dataset https://huggingface.co/datasets/aamijar/muharaf-public
103
104 Arabic OCR Images https://huggingface.co/datasets/saleh-c4/arabic-ocr-images
105
106 KHATT Arabic Dataset https://gts.ai/dataset-download/khatt-arabic-dataset/
107
108
109
110 Additional historical manuscripts and documents
111
112Training Statistics:
113Item Value
114Training Samples 60,880+
115Epochs 3
116Learning Rate 2e-5
117Batch Size 40
118📊 Performance
119Test Results on Various Documents:
120Task Accuracy Description
121Text Extraction from Documents 77.63% Arabic texts from historical documents
122Best Performance 96.88% On clear and simple texts
123Worst Performance 56.00% On complex texts or difficult fonts
124🚀 We Launched the Beta Version!
125What We Offer:
126
127 First open-source Arabic OCR model for historical documents
128
129 Average accuracy 77.63% - suitable for archiving and exploration
130
131 Completely free to use
132
133 4-bit quantized model for high efficiency
134
135How You Can Help:
136
137 Use the model and give us feedback
138
139 Send us challenging examples you encounter
140
141 Help improve training data
142
143Coming Soon:
144
145 Version 2.0 with target accuracy 85%+
146
147 Support for more Arabic fonts
148
149 User-friendly web interface
150
151⚠️ Limitations & Warnings
152
153 📷 Image Quality: Performance depends on input image quality and clarity
154
155 🖋️ Handwriting: May struggle with irregular handwriting
156
157 🔞 Content: Must be used for legal and ethical purposes only
158
159 🌐 Dialects: Primarily trained on Standard Arabic
160
161🛡️ Ethical Responsibility
162
163This model should be used responsibly considering:
164
165 Respect for privacy and copyright
166
167 Avoidance of fraudulent purposes
168
169 Compliance with local and international laws
170
171 Verification of results in sensitive applications
172
173📄 Citation
174
175If you use this model in your research, please cite as follows:
176
177
178
179@misc{qwen25vlarabicocr,
180 title={Arabic-handwritten-OCR-4bit-Qwen2.5-VL-3B-v1: Arabic Text Extraction Model},
181 author={Sherif1313},
182 year={2025},
183 publisher={Hugging Face},
184 howpublished={\url{https://huggingface.co/sherif1313/Arabic-handwritten-OCR-4bit-Qwen2.5-VL-3B-v1}}
185}