from transformers import TrOCRProcessor, VisionEncoderDecoderModel from PIL import Image, ImageEnhance import re # Load TrOCR 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: Preprocess 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 Hugging Face 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] print("OCR Output:", full_text) # Step 3: Extract numeric weight cleaned = full_text.lower().replace(" ", "") match = re.search(r"(\d+(\.\d+)?)", cleaned) weight = match.group(1) if match else None # Step 4: Decide unit if any(u in cleaned for u in ["kg", "kgs", "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"