Update app/utils.py
Browse files- app/utils.py +83 -28
app/utils.py
CHANGED
@@ -1,8 +1,12 @@
|
|
|
|
1 |
import os
|
2 |
-
from transformers import
|
3 |
-
from PIL import Image
|
4 |
import torch
|
5 |
-
|
|
|
|
|
|
|
6 |
class OCRModel:
|
7 |
_instance = None
|
8 |
|
@@ -13,34 +17,85 @@ class OCRModel:
|
|
13 |
return cls._instance
|
14 |
|
15 |
def initialize(self):
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
def process_image(self, image_stream):
|
38 |
try:
|
39 |
-
|
40 |
-
image = Image.open(image_stream)
|
41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
with torch.no_grad():
|
43 |
-
|
44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
except Exception as e:
|
|
|
46 |
return f"Error processing image: {str(e)}"
|
|
|
1 |
+
# utils.py
|
2 |
import os
|
3 |
+
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
4 |
+
from PIL import Image, ImageEnhance, ImageFilter
|
5 |
import torch
|
6 |
+
import logging
|
7 |
+
|
8 |
+
logger = logging.getLogger(__name__)
|
9 |
+
|
10 |
class OCRModel:
|
11 |
_instance = None
|
12 |
|
|
|
17 |
return cls._instance
|
18 |
|
19 |
def initialize(self):
|
20 |
+
try:
|
21 |
+
logger.info("Initializing OCR model...")
|
22 |
+
|
23 |
+
# تهيئة النموذج والمعالج
|
24 |
+
self.processor = TrOCRProcessor.from_pretrained('microsoft/trocr-base-handwritten')
|
25 |
+
self.model = VisionEncoderDecoderModel.from_pretrained('microsoft/trocr-base-handwritten')
|
26 |
+
|
27 |
+
# تحديد الجهاز
|
28 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
29 |
+
logger.info(f"Using device: {self.device}")
|
30 |
+
|
31 |
+
self.model.to(self.device)
|
32 |
+
self.model.eval()
|
33 |
+
|
34 |
+
logger.info("Model initialization completed successfully")
|
35 |
+
|
36 |
+
except Exception as e:
|
37 |
+
logger.error(f"Error initializing model: {str(e)}", exc_info=True)
|
38 |
+
raise
|
39 |
+
|
40 |
+
def preprocess_image(self, image):
|
41 |
+
"""معالجة مسبقة للصورة لتحسين جودة التعرف على النص"""
|
42 |
+
try:
|
43 |
+
# تحويل الصورة إلى RGB إذا لم تكن كذلك
|
44 |
+
if image.mode != 'RGB':
|
45 |
+
image = image.convert('RGB')
|
46 |
+
|
47 |
+
# تحسين التباين
|
48 |
+
enhancer = ImageEnhance.Contrast(image)
|
49 |
+
image = enhancer.enhance(1.5)
|
50 |
+
|
51 |
+
# تحسين الحدة
|
52 |
+
enhancer = ImageEnhance.Sharpness(image)
|
53 |
+
image = enhancer.enhance(1.5)
|
54 |
+
|
55 |
+
# تحسين السطوع
|
56 |
+
enhancer = ImageEnhance.Brightness(image)
|
57 |
+
image = enhancer.enhance(1.2)
|
58 |
+
|
59 |
+
# تطبيق فلتر لتنعيم الصورة قليلاً
|
60 |
+
image = image.filter(ImageFilter.SMOOTH)
|
61 |
+
|
62 |
+
return image
|
63 |
+
except Exception as e:
|
64 |
+
logger.error(f"Error in image preprocessing: {str(e)}", exc_info=True)
|
65 |
+
raise
|
66 |
+
|
67 |
def process_image(self, image_stream):
|
68 |
try:
|
69 |
+
logger.info("Starting image processing")
|
|
|
70 |
|
71 |
+
# إعادة تعيين مؤشر البداية للـ BytesIO
|
72 |
+
image_stream.seek(0)
|
73 |
+
|
74 |
+
# فتح الصورة
|
75 |
+
image = Image.open(image_stream).convert('RGB')
|
76 |
+
|
77 |
+
# تطبيق المعالجة المسبقة
|
78 |
+
processed_image = self.preprocess_image(image)
|
79 |
+
|
80 |
+
# معالجة الصورة للنموذج
|
81 |
+
pixel_values = self.processor(processed_image, return_tensors="pt").pixel_values.to(self.device)
|
82 |
+
|
83 |
+
# التعرف على النص
|
84 |
with torch.no_grad():
|
85 |
+
generated_ids = self.model.generate(
|
86 |
+
pixel_values,
|
87 |
+
max_length=128,
|
88 |
+
num_beams=4,
|
89 |
+
length_penalty=2.0,
|
90 |
+
early_stopping=True
|
91 |
+
)
|
92 |
+
|
93 |
+
# تحويل النتيجة إلى نص
|
94 |
+
generated_text = self.processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
95 |
+
|
96 |
+
logger.info(f"Successfully extracted text: {generated_text[:100]}...")
|
97 |
+
return generated_text.strip()
|
98 |
+
|
99 |
except Exception as e:
|
100 |
+
logger.error(f"Error in image processing: {str(e)}", exc_info=True)
|
101 |
return f"Error processing image: {str(e)}"
|