Spaces:
Running
Running
Update ocr_engine.py
Browse files- ocr_engine.py +7 -7
ocr_engine.py
CHANGED
@@ -2,30 +2,30 @@ from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
|
2 |
from PIL import Image, ImageEnhance
|
3 |
import re
|
4 |
|
5 |
-
# Load
|
6 |
-
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-
|
7 |
-
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-
|
8 |
|
9 |
def extract_weight(image: Image.Image) -> str:
|
10 |
-
#
|
11 |
image = image.convert("L") # grayscale
|
12 |
image = ImageEnhance.Contrast(image).enhance(2.0)
|
13 |
image = ImageEnhance.Sharpness(image).enhance(2.5)
|
14 |
image = image.convert("RGB")
|
15 |
|
16 |
-
#
|
17 |
pixel_values = processor(images=image, return_tensors="pt").pixel_values
|
18 |
generated_ids = model.generate(pixel_values, max_length=32)
|
19 |
full_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
20 |
|
21 |
print("OCR Output:", full_text)
|
22 |
|
23 |
-
#
|
24 |
cleaned = full_text.lower().replace(" ", "")
|
25 |
match = re.search(r"(\d+(\.\d+)?)", cleaned)
|
26 |
weight = match.group(1) if match else None
|
27 |
|
28 |
-
#
|
29 |
if any(u in cleaned for u in ["kg", "kgs", "kilo"]):
|
30 |
unit = "kg"
|
31 |
elif any(u in cleaned for u in ["g", "gram", "grams"]):
|
|
|
2 |
from PIL import Image, ImageEnhance
|
3 |
import re
|
4 |
|
5 |
+
# ✅ Load printed text model (more accurate for digital fonts)
|
6 |
+
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-printed")
|
7 |
+
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-printed")
|
8 |
|
9 |
def extract_weight(image: Image.Image) -> str:
|
10 |
+
# Preprocess: convert to grayscale and enhance contrast
|
11 |
image = image.convert("L") # grayscale
|
12 |
image = ImageEnhance.Contrast(image).enhance(2.0)
|
13 |
image = ImageEnhance.Sharpness(image).enhance(2.5)
|
14 |
image = image.convert("RGB")
|
15 |
|
16 |
+
# Run OCR
|
17 |
pixel_values = processor(images=image, return_tensors="pt").pixel_values
|
18 |
generated_ids = model.generate(pixel_values, max_length=32)
|
19 |
full_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
20 |
|
21 |
print("OCR Output:", full_text)
|
22 |
|
23 |
+
# Extract number
|
24 |
cleaned = full_text.lower().replace(" ", "")
|
25 |
match = re.search(r"(\d+(\.\d+)?)", cleaned)
|
26 |
weight = match.group(1) if match else None
|
27 |
|
28 |
+
# Determine unit
|
29 |
if any(u in cleaned for u in ["kg", "kgs", "kilo"]):
|
30 |
unit = "kg"
|
31 |
elif any(u in cleaned for u in ["g", "gram", "grams"]):
|