logger2 / ocr_engine.py
Sanjayraju30's picture
Update ocr_engine.py
5217dbe verified
raw
history blame
1.16 kB
from PIL import Image
from transformers import AutoProcessor, VisionEncoderDecoderModel
import re
# Load model fine-tuned for 7-segment displays
processor = AutoProcessor.from_pretrained("roboflow/ocr-7segment")
model = VisionEncoderDecoderModel.from_pretrained("roboflow/ocr-7segment")
def extract_weight(image: Image.Image) -> str:
image = image.convert("RGB")
pixel_values = processor(images=image, return_tensors="pt").pixel_values
generated_ids = model.generate(pixel_values)
full_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
print("OCR Text:", full_text) # optional debug
# Extract number (weight)
match = re.search(r"(\d+(\.\d+)?)", full_text)
weight = match.group(1) if match else None
# Detect unit
text_lower = full_text.lower().replace(" ", "")
if any(u in text_lower for u in ["kg", "kgs", "kilogram", "kilo"]):
unit = "kg"
elif any(u in text_lower for u in ["g", "gram", "grams"]):
unit = "grams"
else:
unit = "kg" if weight and float(weight) >= 5 else "grams"
return f"{weight} {unit}" if weight else "No valid weight detected"