Spaces:
Runtime error
Runtime error
| from transformers import TrOCRProcessor, VisionEncoderDecoderModel | |
| from PIL import Image, ImageEnhance | |
| import re | |
| # β Load model optimized for printed text (NOT handwritten) | |
| processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-printed") | |
| model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-printed") | |
| def extract_weight(image: Image.Image) -> str: | |
| # Step 1: Preprocess image to enhance readability | |
| 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 TrOCR | |
| 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 value | |
| cleaned = full_text.lower().replace(" ", "") | |
| match = re.search(r"(\d+(\.\d+)?)", cleaned) | |
| weight = match.group(1) if match else None | |
| # Step 4: Determine 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" | |