Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -6,42 +6,46 @@ from datetime import datetime
|
|
6 |
import re
|
7 |
from PIL import Image
|
8 |
|
9 |
-
# Initialize PaddleOCR
|
10 |
-
ocr = PaddleOCR(use_angle_cls=True, lang='en') #
|
11 |
|
12 |
def detect_weight(image):
|
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 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
|
|
|
|
|
|
|
|
45 |
|
46 |
# Gradio UI
|
47 |
gr.Interface(
|
|
|
6 |
import re
|
7 |
from PIL import Image
|
8 |
|
9 |
+
# Initialize PaddleOCR once
|
10 |
+
ocr = PaddleOCR(use_angle_cls=True, lang='en') # English OCR model
|
11 |
|
12 |
def detect_weight(image):
|
13 |
+
try:
|
14 |
+
if image is None:
|
15 |
+
return "No image uploaded", "N/A", None
|
16 |
+
|
17 |
+
# Convert PIL image to RGB numpy array
|
18 |
+
image = image.convert("RGB")
|
19 |
+
image_np = np.array(image)
|
20 |
+
|
21 |
+
# Convert to grayscale and enhance contrast
|
22 |
+
gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
|
23 |
+
enhanced = cv2.equalizeHist(gray)
|
24 |
+
rgb_image = cv2.cvtColor(enhanced, cv2.COLOR_GRAY2RGB)
|
25 |
+
|
26 |
+
# Perform OCR
|
27 |
+
result = ocr.ocr(rgb_image, cls=True)
|
28 |
+
|
29 |
+
best_match = None
|
30 |
+
best_conf = 0
|
31 |
+
|
32 |
+
for line in result:
|
33 |
+
for box in line:
|
34 |
+
text, conf = box[1]
|
35 |
+
match = re.search(r"\d+\.\d+", text)
|
36 |
+
if match and conf > best_conf:
|
37 |
+
best_match = match.group()
|
38 |
+
best_conf = conf
|
39 |
+
|
40 |
+
if best_match:
|
41 |
+
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
42 |
+
return f"Weight: {best_match} kg (Confidence: {round(best_conf * 100, 2)}%)", now, image
|
43 |
+
else:
|
44 |
+
return "No weight detected kg (Confidence: 0.0%)", "N/A", image
|
45 |
+
|
46 |
+
except Exception as e:
|
47 |
+
# Show error in output instead of crashing
|
48 |
+
return f"Error: {str(e)}", "Error", None
|
49 |
|
50 |
# Gradio UI
|
51 |
gr.Interface(
|