nusaibah0110 commited on
Commit
0406f85
Β·
1 Parent(s): 4742baa

Fix ultralytics model loading with CPU device and error handling

Browse files
Files changed (1) hide show
  1. backend/inference.py +108 -46
backend/inference.py CHANGED
@@ -8,9 +8,13 @@ from ultralytics import YOLO
8
 
9
  # MODEL LOAD (Safe Backend Path)
10
  AW_MODEL_PATH = os.path.join(os.path.dirname(__file__), "models", "AW_yolo.pt")
11
- aw_model = YOLO(AW_MODEL_PATH)
12
-
13
- print("Acetowhite model loaded from:", AW_MODEL_PATH)
 
 
 
 
14
 
15
  # CONFIGURABLE PARAMETERS
16
  MIN_AREA = 150 # minimum contour area (px)
@@ -30,54 +34,87 @@ def infer_aw_contour(frame, conf_threshold=DEFAULT_CONF):
30
  "frame_height": 0
31
  }
32
 
33
- results = aw_model.predict(
34
- frame,
35
- conf=conf_threshold,
36
- imgsz=IMG_SIZE,
37
- verbose=False
38
- )[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  overlay = frame.copy()
41
  contours_list = []
42
  detection_count = 0
43
 
44
- if results.masks is not None and len(results.masks.xy) > 0:
 
 
45
 
46
- for idx, polygon in enumerate(results.masks.xy):
47
 
48
- confidence = float(results.boxes.conf[idx])
49
 
50
- # Skip low-confidence masks (extra safety layer)
51
- if confidence < conf_threshold:
52
- continue
53
 
54
- contour = polygon.astype(np.int32)
55
 
56
- area = cv2.contourArea(contour)
57
 
58
- if area < MIN_AREA:
59
- continue
60
 
61
- # Optional smoothing
62
- epsilon = SMOOTHING_EPSILON * cv2.arcLength(contour, True)
63
- contour = cv2.approxPolyDP(contour, epsilon, True)
64
 
65
- # Draw clean contour
66
- cv2.polylines(
67
- overlay,
68
- [contour],
69
- isClosed=True,
70
- color=(0, 255, 0),
71
- thickness=2
72
- )
73
 
74
- contours_list.append({
75
- "points": contour.tolist(),
76
- "area": float(area),
77
- "confidence": round(confidence, 3)
78
- })
79
 
80
- detection_count += 1
 
 
 
 
 
 
81
 
82
  return {
83
  "overlay": overlay,
@@ -96,10 +133,14 @@ from ultralytics import YOLO
96
  from collections import deque
97
 
98
  cervix_MODEL_PATH = os.path.join(os.path.dirname(__file__), "models", "cervix_yolo.pt")
99
- cervix_model = YOLO(cervix_MODEL_PATH)
100
-
101
- print("Cervix model loaded from:", cervix_MODEL_PATH)
102
- print("Classes:", cervix_model.model.names)
 
 
 
 
103
 
104
  # Stability buffer for video
105
  detect_history = deque(maxlen=10)
@@ -142,14 +183,35 @@ def analyze_frame(frame, conf_threshold=0.3):
142
  "quality_percent": 0
143
  }
144
 
 
 
 
 
 
 
 
 
 
145
  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
146
 
147
- results = cervix_model.predict(
148
- frame,
149
- conf=conf_threshold,
150
- imgsz=640,
151
- verbose=False
152
- )
 
 
 
 
 
 
 
 
 
 
 
 
153
 
154
  r = results[0]
155
 
 
8
 
9
  # MODEL LOAD (Safe Backend Path)
10
  AW_MODEL_PATH = os.path.join(os.path.dirname(__file__), "models", "AW_yolo.pt")
11
+ try:
12
+ aw_model = YOLO(AW_MODEL_PATH)
13
+ aw_model.to('cpu') # Force CPU device
14
+ print("βœ… Acetowhite model loaded from:", AW_MODEL_PATH)
15
+ except Exception as e:
16
+ print(f"❌ Error loading Acetowhite model: {e}")
17
+ aw_model = None
18
 
19
  # CONFIGURABLE PARAMETERS
20
  MIN_AREA = 150 # minimum contour area (px)
 
34
  "frame_height": 0
35
  }
36
 
37
+ if aw_model is None:
38
+ print("❌ Acetowhite model not loaded")
39
+ return {
40
+ "overlay": None,
41
+ "contours": [],
42
+ "detections": 0,
43
+ "frame_width": frame.shape[1],
44
+ "frame_height": frame.shape[0]
45
+ }
46
+
47
+ try:
48
+ print(f"πŸ”„ Running YOLO prediction on frame shape: {frame.shape}")
49
+ results = aw_model.predict(
50
+ frame,
51
+ conf=conf_threshold,
52
+ imgsz=IMG_SIZE,
53
+ verbose=False,
54
+ device='cpu'
55
+ )[0]
56
+ print(f"βœ… YOLO prediction complete")
57
+ except Exception as e:
58
+ print(f"❌ YOLO prediction error: {e}")
59
+ import traceback
60
+ traceback.print_exc()
61
+ return {
62
+ "overlay": None,
63
+ "contours": [],
64
+ "detections": 0,
65
+ "frame_width": frame.shape[1],
66
+ "frame_height": frame.shape[0]
67
+ }
68
 
69
  overlay = frame.copy()
70
  contours_list = []
71
  detection_count = 0
72
 
73
+ try:
74
+ if results.masks is not None and len(results.masks.xy) > 0:
75
+ print(f"βœ… Found masks: {len(results.masks.xy)}")
76
 
77
+ for idx, polygon in enumerate(results.masks.xy):
78
 
79
+ confidence = float(results.boxes.conf[idx])
80
 
81
+ # Skip low-confidence masks (extra safety layer)
82
+ if confidence < conf_threshold:
83
+ continue
84
 
85
+ contour = polygon.astype(np.int32)
86
 
87
+ area = cv2.contourArea(contour)
88
 
89
+ if area < MIN_AREA:
90
+ continue
91
 
92
+ # Optional smoothing
93
+ epsilon = SMOOTHING_EPSILON * cv2.arcLength(contour, True)
94
+ contour = cv2.approxPolyDP(contour, epsilon, True)
95
 
96
+ # Draw clean contour
97
+ cv2.polylines(
98
+ overlay,
99
+ [contour],
100
+ isClosed=True,
101
+ color=(0, 255, 0),
102
+ thickness=2
103
+ )
104
 
105
+ contours_list.append({
106
+ "points": contour.tolist(),
107
+ "area": float(area),
108
+ "confidence": round(confidence, 3)
109
+ })
110
 
111
+ detection_count += 1
112
+ else:
113
+ print("ℹ️ No masks found in results")
114
+ except Exception as e:
115
+ print(f"❌ Error processing masks: {e}")
116
+ import traceback
117
+ traceback.print_exc()
118
 
119
  return {
120
  "overlay": overlay,
 
133
  from collections import deque
134
 
135
  cervix_MODEL_PATH = os.path.join(os.path.dirname(__file__), "models", "cervix_yolo.pt")
136
+ try:
137
+ cervix_model = YOLO(cervix_MODEL_PATH)
138
+ cervix_model.to('cpu') # Force CPU device
139
+ print(f"βœ… Cervix model loaded from: {cervix_MODEL_PATH}")
140
+ print(f"βœ… Classes: {cervix_model.model.names}")
141
+ except Exception as e:
142
+ print(f"❌ Error loading Cervix model: {e}")
143
+ cervix_model = None
144
 
145
  # Stability buffer for video
146
  detect_history = deque(maxlen=10)
 
183
  "quality_percent": 0
184
  }
185
 
186
+ if cervix_model is None:
187
+ print("❌ Cervix model not loaded")
188
+ return {
189
+ "detected": False,
190
+ "detection_confidence": 0.0,
191
+ "quality_score": 0.0,
192
+ "quality_percent": 0
193
+ }
194
+
195
  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
196
 
197
+ try:
198
+ results = cervix_model.predict(
199
+ frame,
200
+ conf=conf_threshold,
201
+ imgsz=640,
202
+ verbose=False,
203
+ device='cpu'
204
+ )
205
+ except Exception as e:
206
+ print(f"❌ Cervix model prediction error: {e}")
207
+ import traceback
208
+ traceback.print_exc()
209
+ return {
210
+ "detected": False,
211
+ "detection_confidence": 0.0,
212
+ "quality_score": 0.0,
213
+ "quality_percent": 0
214
+ }
215
 
216
  r = results[0]
217