Spaces:
Build error
Build error
Update ocr_engine.py
Browse files- ocr_engine.py +21 -46
ocr_engine.py
CHANGED
@@ -1,54 +1,29 @@
|
|
1 |
-
import re
|
2 |
-
import cv2
|
3 |
-
import numpy as np
|
4 |
-
from PIL import Image
|
5 |
from paddleocr import PaddleOCR
|
|
|
6 |
|
7 |
-
#
|
8 |
-
ocr = PaddleOCR(use_angle_cls=
|
9 |
-
|
10 |
-
def preprocess_image(image):
|
11 |
-
"""
|
12 |
-
Convert to grayscale and enhance contrast to help OCR.
|
13 |
-
"""
|
14 |
-
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
|
15 |
-
processed = cv2.adaptiveThreshold(
|
16 |
-
gray, 255,
|
17 |
-
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
18 |
-
cv2.THRESH_BINARY_INV,
|
19 |
-
11, 2
|
20 |
-
)
|
21 |
-
return processed
|
22 |
-
|
23 |
-
def extract_weight_from_image(pil_image):
|
24 |
-
try:
|
25 |
-
# β
Convert to OpenCV format
|
26 |
-
image = np.array(pil_image.convert("RGB"))
|
27 |
-
|
28 |
-
# β
Preprocess image
|
29 |
-
processed = preprocess_image(image)
|
30 |
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
print(f"[DEBUG] Saved preprocessed image to {debug_path}")
|
35 |
|
36 |
-
|
37 |
-
|
38 |
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
conf = line[1][1]
|
43 |
-
print(f" β’ Text: '{text}' | Confidence: {conf*100:.2f}%")
|
44 |
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
|
|
|
|
49 |
|
50 |
-
|
|
|
|
|
51 |
|
52 |
-
|
53 |
-
print(f"β OCR Error: {e}")
|
54 |
-
return f"Error: {str(e)}", 0.0
|
|
|
|
|
|
|
|
|
|
|
1 |
from paddleocr import PaddleOCR
|
2 |
+
import re
|
3 |
|
4 |
+
# Initialize PaddleOCR once
|
5 |
+
ocr = PaddleOCR(use_angle_cls=True, lang='en')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
|
7 |
+
def extract_weight_from_image(image):
|
8 |
+
result = ocr.ocr(image, cls=True)
|
9 |
+
debug_texts = []
|
|
|
10 |
|
11 |
+
if not result or not result[0]:
|
12 |
+
return ("No weight detected", 0.0)
|
13 |
|
14 |
+
for line in result[0]:
|
15 |
+
text, confidence = line[1][0], line[1][1]
|
16 |
+
debug_texts.append(f"{text} (Conf: {confidence:.2f})")
|
|
|
|
|
17 |
|
18 |
+
# Find number with optional decimal + optional "kg", "g"
|
19 |
+
match = re.search(r'(\d+\.?\d*)\s*(kg|g)?', text.lower())
|
20 |
+
if match:
|
21 |
+
unit = match.group(2) if match.group(2) else "g"
|
22 |
+
weight = match.group(1)
|
23 |
+
return (f"{weight} {unit}", confidence)
|
24 |
|
25 |
+
print("DEBUG OCR OUTPUT:")
|
26 |
+
for d in debug_texts:
|
27 |
+
print(d)
|
28 |
|
29 |
+
return ("No weight detected", 0.0)
|
|
|
|