Spaces:
Running
Running
File size: 1,384 Bytes
c2e79e4 65ef5f8 c2e79e4 65ef5f8 c2e79e4 5d38db5 c2e79e4 65ef5f8 c2e79e4 |
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 37 |
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
from PIL import Image, ImageEnhance
import re
# Load TrOCR model (works without apt.txt)
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 for OCR
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]
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: Infer 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"
|