Update app/utils.py
Browse files- app/utils.py +9 -6
app/utils.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
from transformers import AutoModel, AutoTokenizer
|
| 2 |
import os
|
| 3 |
import torch
|
|
|
|
| 4 |
|
| 5 |
class OCRModel:
|
| 6 |
_instance = None
|
|
@@ -12,30 +13,32 @@ class OCRModel:
|
|
| 12 |
return cls._instance
|
| 13 |
|
| 14 |
def initialize(self):
|
| 15 |
-
# تحميل النموذج مرة واحدة وتخزينه محلياً
|
| 16 |
model_path = os.getenv('MODEL_PATH', 'RufusRubin777/GOT-OCR2_0_CPU')
|
| 17 |
|
| 18 |
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 19 |
model_path,
|
| 20 |
trust_remote_code=True,
|
| 21 |
-
local_files_only=False
|
| 22 |
)
|
| 23 |
|
| 24 |
self.model = AutoModel.from_pretrained(
|
| 25 |
model_path,
|
| 26 |
trust_remote_code=True,
|
| 27 |
low_cpu_mem_usage=True,
|
| 28 |
-
device_map='cpu',
|
| 29 |
use_safetensors=True,
|
| 30 |
pad_token_id=self.tokenizer.eos_token_id
|
| 31 |
)
|
| 32 |
|
| 33 |
self.model = self.model.eval()
|
| 34 |
|
| 35 |
-
def process_image(self,
|
| 36 |
try:
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
| 39 |
return result
|
| 40 |
except Exception as e:
|
| 41 |
return f"Error processing image: {str(e)}"
|
|
|
|
| 1 |
from transformers import AutoModel, AutoTokenizer
|
| 2 |
import os
|
| 3 |
import torch
|
| 4 |
+
from PIL import Image
|
| 5 |
|
| 6 |
class OCRModel:
|
| 7 |
_instance = None
|
|
|
|
| 13 |
return cls._instance
|
| 14 |
|
| 15 |
def initialize(self):
|
|
|
|
| 16 |
model_path = os.getenv('MODEL_PATH', 'RufusRubin777/GOT-OCR2_0_CPU')
|
| 17 |
|
| 18 |
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 19 |
model_path,
|
| 20 |
trust_remote_code=True,
|
| 21 |
+
local_files_only=False
|
| 22 |
)
|
| 23 |
|
| 24 |
self.model = AutoModel.from_pretrained(
|
| 25 |
model_path,
|
| 26 |
trust_remote_code=True,
|
| 27 |
low_cpu_mem_usage=True,
|
| 28 |
+
device_map='cpu',
|
| 29 |
use_safetensors=True,
|
| 30 |
pad_token_id=self.tokenizer.eos_token_id
|
| 31 |
)
|
| 32 |
|
| 33 |
self.model = self.model.eval()
|
| 34 |
|
| 35 |
+
def process_image(self, image_stream):
|
| 36 |
try:
|
| 37 |
+
# فتح الصورة من الذاكرة
|
| 38 |
+
image = Image.open(image_stream)
|
| 39 |
+
|
| 40 |
+
with torch.no_grad():
|
| 41 |
+
result = self.model.chat(self.tokenizer, image, ocr_type='format')
|
| 42 |
return result
|
| 43 |
except Exception as e:
|
| 44 |
return f"Error processing image: {str(e)}"
|