from transformers import TrOCRProcessor, VisionEncoderDecoderModel from PIL import Image import torch import re # Load model and processor processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten") model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten") def clean_ocr_text(text): print("[RAW OCR]", text) text = text.replace(",", ".").replace("s", "5").replace("o", "0").lower() text = re.sub(r"[^\d\.kg]", "", text) print("[CLEANED OCR]", text) return text def extract_weight(image): try: pixel_values = processor(images=image, return_tensors="pt").pixel_values generated_ids = model.generate(pixel_values) raw_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip() cleaned = clean_ocr_text(raw_text) # First try with unit match = re.search(r'(\d{1,5}(?:\.\d{1,3})?)\s*(kg|g)', cleaned) if match: return f"{match.group(1)} {match.group(2)}" # Fallback: only number, assume grams fallback = re.search(r'(\d{1,5}(?:\.\d{1,3})?)', cleaned) if fallback: return f"{fallback.group(1)} g" return f"No valid weight found | OCR: {cleaned}" except Exception as e: return f"Error: {str(e)}"