logger1 / ocr_engine.py
Sanjayraju30's picture
Update ocr_engine.py
52e7bf6 verified
raw
history blame
1.4 kB
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
from PIL import Image, ImageEnhance
import re
# Load OCR model
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")
def extract_weight(image: Image.Image) -> str:
# Step 1: Enhance image
image = image.convert("L") # grayscale
image = ImageEnhance.Contrast(image).enhance(2.0)
image = ImageEnhance.Sharpness(image).enhance(2.5)
image = image.convert("RGB")
# Step 2: Run OCR
pixel_values = processor(images=image, return_tensors="pt").pixel_values
generated_ids = model.generate(pixel_values, max_length=32)
full_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
# Debug
print("OCR Output:", full_text)
# Step 3: Extract number
cleaned = full_text.lower().replace(" ", "")
match = re.search(r"(\d+(\.\d+)?)", cleaned)
weight = match.group(1) if match else None
# Step 4: Detect unit based on actual OCR text
if any(u in cleaned for u in ["kg", "kgs", "kilogram", "kilo"]):
unit = "kg"
elif any(u in cleaned for u in ["g", "gram", "grams"]):
unit = "grams"
else:
unit = "kg" if weight and float(weight) >= 20 else "grams"
return f"{weight} {unit}" if weight else "No valid weight detected"