Spaces:
Runtime error
Runtime error
File size: 1,142 Bytes
477d4fe da9f292 477d4fe da9f292 363a646 65ed4c1 363a646 477d4fe da9f292 477d4fe ee1d691 da9f292 477d4fe 103f82b ee1d691 477d4fe 103f82b ee1d691 477d4fe 8fe1b94 65ed4c1 2132698 |
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 |
from paddleocr import PaddleOCR
import numpy as np
import re
ocr = PaddleOCR(use_angle_cls=True, lang='en', use_gpu=False)
def extract_weight_from_image(pil_img):
try:
img = np.array(pil_img)
result = ocr.ocr(img, cls=True)
all_text = []
weight_candidates = []
for line in result:
for box, (text, confidence) in line:
all_text.append(text)
cleaned = text.lower()
cleaned = cleaned.replace("kg", "").replace("kgs", "")
cleaned = cleaned.replace("o", "0").replace("s", "5").replace("g", "9")
cleaned = re.sub(r"[^\d\.]", "", cleaned)
if re.fullmatch(r"\d{2,4}(\.\d{1,2})?", cleaned):
weight_candidates.append((cleaned, confidence))
if not weight_candidates:
return "Not detected", 0.0, "\n".join(all_text)
best_weight, best_conf = sorted(weight_candidates, key=lambda x: -x[1])[0]
return best_weight, round(best_conf * 100, 2), "\n".join(all_text)
except Exception as e:
return f"Error: {str(e)}", 0.0, "OCR failed"
|