Sanjayraju30 commited on
Commit
0263481
·
verified ·
1 Parent(s): 9b5d129

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -34
app.py CHANGED
@@ -6,42 +6,46 @@ from datetime import datetime
6
  import re
7
  from PIL import Image
8
 
9
- # Initialize PaddleOCR (only once)
10
- ocr = PaddleOCR(use_angle_cls=True, lang='en') # Use English OCR model
11
 
12
  def detect_weight(image):
13
- if image is None:
14
- return "No image uploaded", "N/A", None
15
-
16
- # Convert PIL Image to OpenCV format (NumPy array)
17
- image = image.convert("RGB")
18
- image_np = np.array(image)
19
-
20
- # Preprocess: Grayscale + contrast enhancement (optional)
21
- gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
22
- gray_eq = cv2.equalizeHist(gray)
23
- processed_image = cv2.cvtColor(gray_eq, cv2.COLOR_GRAY2RGB) # convert back to RGB for PaddleOCR
24
-
25
- # Run OCR
26
- result = ocr.ocr(processed_image, cls=True)
27
-
28
- best_match = None
29
- best_conf = 0
30
-
31
- # Search for a decimal number like 25.52
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
  # 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(