Spaces:
Running
Running
File size: 1,428 Bytes
c43e287 65ef5f8 d9de0dd 35d4bb1 65ef5f8 c43e287 d9de0dd c43e287 5d38db5 d9de0dd c43e287 d9de0dd c43e287 d9de0dd c43e287 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
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"
|