AutoWeightLogger / ocr_engine.py
Sanjayraju30's picture
Update ocr_engine.py
477d4fe verified
raw
history blame
1.14 kB
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"