Spaces:
Sleeping
Sleeping
Update ocr_engine.py
Browse files- ocr_engine.py +9 -12
ocr_engine.py
CHANGED
|
@@ -1,33 +1,30 @@
|
|
| 1 |
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
| 2 |
from PIL import Image
|
|
|
|
| 3 |
|
| 4 |
-
# Load
|
| 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 |
-
# Ensure image is in RGB
|
| 10 |
image = image.convert("RGB")
|
| 11 |
-
|
| 12 |
-
# Process with Hugging Face OCR
|
| 13 |
pixel_values = processor(images=image, return_tensors="pt").pixel_values
|
| 14 |
generated_ids = model.generate(pixel_values)
|
| 15 |
full_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 16 |
|
| 17 |
-
#
|
| 18 |
-
|
| 19 |
|
| 20 |
# Detect unit
|
| 21 |
-
if "kg" in
|
| 22 |
unit = "kg"
|
| 23 |
-
elif "g" in
|
| 24 |
unit = "grams"
|
| 25 |
else:
|
| 26 |
-
unit = "grams" # default
|
| 27 |
|
| 28 |
-
# Extract number
|
| 29 |
-
|
| 30 |
-
match = re.search(r"(\d+(\.\d+)?)", full_text_cleaned)
|
| 31 |
if match:
|
| 32 |
weight = match.group(1)
|
| 33 |
return f"{weight} {unit}"
|
|
|
|
| 1 |
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
| 2 |
from PIL import Image
|
| 3 |
+
import re
|
| 4 |
|
| 5 |
+
# Load model + processor
|
| 6 |
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-stage1")
|
| 7 |
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-stage1")
|
| 8 |
|
| 9 |
def extract_weight(image: Image.Image) -> str:
|
|
|
|
| 10 |
image = image.convert("RGB")
|
|
|
|
|
|
|
| 11 |
pixel_values = processor(images=image, return_tensors="pt").pixel_values
|
| 12 |
generated_ids = model.generate(pixel_values)
|
| 13 |
full_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 14 |
|
| 15 |
+
# Lowercase text but don't strip spacing before kg detection
|
| 16 |
+
full_text_lower = full_text.lower()
|
| 17 |
|
| 18 |
# Detect unit
|
| 19 |
+
if "kg" in full_text_lower.replace(" ", ""):
|
| 20 |
unit = "kg"
|
| 21 |
+
elif "g" in full_text_lower.replace(" ", "") or "gram" in full_text_lower:
|
| 22 |
unit = "grams"
|
| 23 |
else:
|
| 24 |
+
unit = "grams" # default
|
| 25 |
|
| 26 |
+
# Extract number using regex
|
| 27 |
+
match = re.search(r"(\d+(\.\d+)?)", full_text)
|
|
|
|
| 28 |
if match:
|
| 29 |
weight = match.group(1)
|
| 30 |
return f"{weight} {unit}"
|