Spaces:
Running
Running
Update ocr_engine.py
Browse files- ocr_engine.py +5 -2
ocr_engine.py
CHANGED
@@ -2,26 +2,29 @@ from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
|
2 |
from PIL import Image, ImageEnhance
|
3 |
import re
|
4 |
|
5 |
-
# Load model
|
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 |
image = image.convert("L") # grayscale
|
11 |
image = ImageEnhance.Contrast(image).enhance(2.0)
|
12 |
image = ImageEnhance.Sharpness(image).enhance(2.5)
|
13 |
image = image.convert("RGB")
|
14 |
|
|
|
15 |
pixel_values = processor(images=image, return_tensors="pt").pixel_values
|
16 |
generated_ids = model.generate(pixel_values, max_length=32)
|
17 |
full_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
18 |
-
|
19 |
print("OCR Output:", full_text)
|
20 |
|
|
|
21 |
cleaned = full_text.lower().replace(" ", "")
|
22 |
match = re.search(r"(\d+(\.\d+)?)", cleaned)
|
23 |
weight = match.group(1) if match else None
|
24 |
|
|
|
25 |
if any(u in cleaned for u in ["kg", "kgs", "kilo"]):
|
26 |
unit = "kg"
|
27 |
elif any(u in cleaned for u in ["g", "gram", "grams"]):
|
|
|
2 |
from PIL import Image, ImageEnhance
|
3 |
import re
|
4 |
|
5 |
+
# ✅ Load model optimized for printed text (NOT handwritten)
|
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 |
+
# Step 1: Preprocess image to enhance readability
|
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 |
+
# Step 2: Run TrOCR
|
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 |
print("OCR Output:", full_text)
|
21 |
|
22 |
+
# Step 3: Extract numeric value
|
23 |
cleaned = full_text.lower().replace(" ", "")
|
24 |
match = re.search(r"(\d+(\.\d+)?)", cleaned)
|
25 |
weight = match.group(1) if match else None
|
26 |
|
27 |
+
# Step 4: Determine unit
|
28 |
if any(u in cleaned for u in ["kg", "kgs", "kilo"]):
|
29 |
unit = "kg"
|
30 |
elif any(u in cleaned for u in ["g", "gram", "grams"]):
|