Create modules/ocr.py
Browse files- modules/ocr.py +42 -0
modules/ocr.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from paddleocr import PaddleOCR
|
| 2 |
+
import cv2
|
| 3 |
+
import numpy as np
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
# تهيئة محرك OCR (يتم تهيئته عند الاستيراد لأداء أفضل)
|
| 7 |
+
ocr_engine = None
|
| 8 |
+
|
| 9 |
+
def get_ocr_engine(lang='en'):
|
| 10 |
+
"""الحصول على أو إنشاء محرك OCR"""
|
| 11 |
+
global ocr_engine
|
| 12 |
+
if ocr_engine is None:
|
| 13 |
+
try:
|
| 14 |
+
ocr_engine = PaddleOCR(use_angle_cls=True, lang=lang, show_log=False)
|
| 15 |
+
print("✅ تم تهيئة محرك PaddleOCR بنجاح")
|
| 16 |
+
except Exception as e:
|
| 17 |
+
print(f"❌ فشل في تهيئة PaddleOCR: {e}")
|
| 18 |
+
raise
|
| 19 |
+
return ocr_engine
|
| 20 |
+
|
| 21 |
+
def extract_texts(image_path: str):
|
| 22 |
+
"""استخراج النصوص والمربعات المحيطة بها من الصورة"""
|
| 23 |
+
try:
|
| 24 |
+
ocr = get_ocr_engine('en')
|
| 25 |
+
results = ocr.ocr(image_path, cls=True)
|
| 26 |
+
|
| 27 |
+
texts = []
|
| 28 |
+
boxes = []
|
| 29 |
+
|
| 30 |
+
if results and results[0] is not None:
|
| 31 |
+
for line in results[0]:
|
| 32 |
+
if line and len(line) >= 2:
|
| 33 |
+
text = line[1][0]
|
| 34 |
+
box = line[0]
|
| 35 |
+
texts.append(text)
|
| 36 |
+
boxes.append(box)
|
| 37 |
+
|
| 38 |
+
return texts, boxes
|
| 39 |
+
|
| 40 |
+
except Exception as e:
|
| 41 |
+
print(f"❌ خطأ في استخراج النصوص: {e}")
|
| 42 |
+
return [], []
|