Spaces:
Sleeping
Sleeping
Update ocr_engine.py
Browse files- ocr_engine.py +14 -15
ocr_engine.py
CHANGED
@@ -1,23 +1,22 @@
|
|
1 |
-
import
|
2 |
-
import pytesseract
|
3 |
-
import numpy as np
|
4 |
from PIL import Image
|
5 |
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
10 |
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
_, thresh = cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
|
15 |
|
16 |
-
#
|
17 |
-
|
18 |
-
|
19 |
|
20 |
-
#
|
|
|
|
|
|
|
21 |
weight = ''.join(filter(lambda x: x in '0123456789.', text))
|
22 |
|
23 |
return weight.strip() if weight else "No valid weight detected"
|
|
|
1 |
+
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
|
|
|
|
2 |
from PIL import Image
|
3 |
|
4 |
+
# Load model + processor once
|
5 |
+
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-stage1")
|
6 |
+
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-stage1")
|
|
|
7 |
|
8 |
+
def extract_weight(image: Image.Image) -> str:
|
9 |
+
# Convert image to RGB just in case
|
10 |
+
image = image.convert("RGB")
|
|
|
11 |
|
12 |
+
# Preprocess + generate prediction
|
13 |
+
pixel_values = processor(images=image, return_tensors="pt").pixel_values
|
14 |
+
generated_ids = model.generate(pixel_values)
|
15 |
|
16 |
+
# Decode output
|
17 |
+
text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
18 |
+
|
19 |
+
# Keep only numbers + decimal
|
20 |
weight = ''.join(filter(lambda x: x in '0123456789.', text))
|
21 |
|
22 |
return weight.strip() if weight else "No valid weight detected"
|