DhominickJ commited on
Commit
53b904a
·
1 Parent(s): 6b65f03

Initial implementation of MosqScope

Browse files
Files changed (1) hide show
  1. app.py +96 -75
app.py CHANGED
@@ -1,117 +1,138 @@
1
  import torch
2
  import torchvision.transforms as transforms
3
- from torchvision.models.detection import ssd300_vgg16
4
  import av
5
  import numpy as np
6
  import cv2
7
  import streamlit as st
8
  from streamlit_webrtc import webrtc_streamer, VideoProcessorBase, WebRtcMode, RTCConfiguration
9
  from huggingface_hub import hf_hub_download
 
10
  import logging
 
11
 
12
- # Set up logging
13
- logging.basicConfig(level=logging.DEBUG)
 
 
 
14
 
15
  # Define dataset classes
16
  classes = ['dengue-regions', 'wet_surface']
17
- num_classes = len(classes) + 1 # Including background
18
 
19
  # Load the SSD Model
20
  @st.cache_resource
21
  def load_model():
22
  try:
23
  model_path = hf_hub_download(repo_id="DhominickJ/MosqScope", filename="mosquito_model.pth")
24
- model = ssd300_vgg16(pretrained=False) # Don't load ImageNet weights
25
-
26
- # SSD models have a different structure - no need to modify the head like in Faster R-CNN
27
  model.load_state_dict(torch.load(model_path, map_location=torch.device("cpu")))
28
  model.eval()
29
  return model
30
  except Exception as e:
31
  st.error(f"Error loading model: {str(e)}")
 
32
  return None
33
 
34
- try:
35
- model = load_model()
36
- except Exception as e:
37
- st.error(f"Error loading model: {e}")
38
- model = None
39
-
40
- # Define Video Processor for WebRTC
41
- class SSDVideoProcessor(VideoProcessorBase):
42
- def __init__(self):
43
- self.model = model
44
- # SSD models expect input in [0,1] range and resized to 300x300
45
- self.transform = transforms.Compose([
46
- transforms.ToPILImage(),
47
- transforms.Resize((300, 300)),
48
- transforms.ToTensor(),
49
- ])
50
-
51
  def recv(self, frame):
52
- if self.model is None:
53
- # Just return the frame if model isn't loaded
54
- return frame
55
-
56
  img = frame.to_ndarray(format="bgr24")
57
- # Make a copy for drawing
58
- display_img = img.copy()
59
-
60
- try:
61
- # Transform for model
62
- image_tensor = self.transform(img).unsqueeze(0)
63
-
64
- with torch.no_grad():
65
- detections = self.model(image_tensor)
66
-
67
- # Get the detection results
68
- boxes = detections[0]['boxes'].cpu().numpy()
69
- scores = detections[0]['scores'].cpu().numpy()
70
- labels = detections[0]['labels'].cpu().numpy()
71
-
72
- # Scale coordinates to original image dimensions
73
- h, w = img.shape[:2]
74
- scale_x, scale_y = w / 300, h / 300
75
-
76
- # Draw detections
77
- for box, label, score in zip(boxes, labels, scores):
78
- if score > 0.5: # Only show confident detections
79
- x_min, y_min, x_max, y_max = box
80
- # Scale coordinates back to original image
81
- x_min, x_max = int(x_min * scale_x), int(x_max * scale_x)
82
- y_min, y_max = int(y_min * scale_y), int(y_max * scale_y)
83
-
84
- cv2.rectangle(display_img, (x_min, y_min), (x_max, y_max), (0, 255, 0), 2)
85
- label_name = classes[label - 1] # Adjust for background class
86
- cv2.putText(display_img, f"{label_name} {score:.2f}",
87
- (x_min, y_min - 5), cv2.FONT_HERSHEY_SIMPLEX,
88
- 0.5, (0, 0, 255), 2)
89
- except Exception as e:
90
- logging.error(f"Error in inference: {e}")
91
- # Add error message to frame
92
- cv2.putText(display_img, f"Error: {str(e)}", (10, 30),
93
- cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
94
-
95
- return av.VideoFrame.from_ndarray(display_img, format="bgr24")
96
 
97
  # Streamlit UI
98
  st.title("Mosquito Detection with WebRTC")
99
  st.write("This app uses a SSD model to detect mosquito breeding sites in real-time.")
100
 
101
- # Configure WebRTC with proper STUN/TURN servers
102
- rtc_config = RTCConfiguration(
103
- {"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]},
 
 
 
 
 
 
 
104
  )
105
 
106
- # Start WebRTC Streaming with proper error handling
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  try:
 
108
  webrtc_ctx = webrtc_streamer(
109
- key="ssd-detection",
110
  mode=WebRtcMode.SENDRECV,
111
- rtc_configuration=rtc_config,
112
- video_processor_factory=SSDVideoProcessor,
113
  media_stream_constraints={"video": True, "audio": False},
114
- async_processing=True,
115
  )
116
  except Exception as e:
117
  st.error(f"WebRTC Error: {e}")
 
1
  import torch
2
  import torchvision.transforms as transforms
3
+ from torchvision.models.detection.ssd import ssd300_vgg16
4
  import av
5
  import numpy as np
6
  import cv2
7
  import streamlit as st
8
  from streamlit_webrtc import webrtc_streamer, VideoProcessorBase, WebRtcMode, RTCConfiguration
9
  from huggingface_hub import hf_hub_download
10
+ import asyncio
11
  import logging
12
+ import os
13
 
14
+ # Configure logging
15
+ logging.basicConfig(level=logging.INFO)
16
+
17
+ # Fix for asyncio loop issues in some environments
18
+ os.environ["STREAMLIT_SERVER_ENABLE_STATIC_SERVING"] = "true"
19
 
20
  # Define dataset classes
21
  classes = ['dengue-regions', 'wet_surface']
 
22
 
23
  # Load the SSD Model
24
  @st.cache_resource
25
  def load_model():
26
  try:
27
  model_path = hf_hub_download(repo_id="DhominickJ/MosqScope", filename="mosquito_model.pth")
28
+ model = ssd300_vgg16(pretrained=False)
 
 
29
  model.load_state_dict(torch.load(model_path, map_location=torch.device("cpu")))
30
  model.eval()
31
  return model
32
  except Exception as e:
33
  st.error(f"Error loading model: {str(e)}")
34
+ logging.error(f"Model loading error: {e}")
35
  return None
36
 
37
+ # Simple fallback class if model loading fails
38
+ class VideoProcessor(VideoProcessorBase):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  def recv(self, frame):
 
 
 
 
40
  img = frame.to_ndarray(format="bgr24")
41
+ # Just add a text overlay indicating the model isn't loaded
42
+ cv2.putText(img, "Model not loaded", (10, 30),
43
+ cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
44
+ return av.VideoFrame.from_ndarray(img, format="bgr24")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  # Streamlit UI
47
  st.title("Mosquito Detection with WebRTC")
48
  st.write("This app uses a SSD model to detect mosquito breeding sites in real-time.")
49
 
50
+ # Use a more reliable WebRTC configuration
51
+ rtc_configuration = RTCConfiguration(
52
+ {"iceServers": [
53
+ {"urls": ["stun:stun.l.google.com:19302"]},
54
+ {
55
+ "urls": ["turn:openrelay.metered.ca:80"],
56
+ "username": "openrelayproject",
57
+ "credential": "openrelayproject",
58
+ }
59
+ ]}
60
  )
61
 
62
+ # Load model conditionally - separate from the WebRTC setup
63
+ try:
64
+ model = load_model()
65
+
66
+ if model is not None:
67
+ # Define Video Processor with the loaded model
68
+ class SSDVideoProcessor(VideoProcessorBase):
69
+ def __init__(self):
70
+ self.model = model
71
+ self.transform = transforms.Compose([
72
+ transforms.ToPILImage(),
73
+ transforms.Resize((300, 300)),
74
+ transforms.ToTensor(),
75
+ ])
76
+
77
+ def recv(self, frame):
78
+ img = frame.to_ndarray(format="bgr24")
79
+ display_img = img.copy()
80
+
81
+ try:
82
+ # Transform for model
83
+ image_tensor = self.transform(img).unsqueeze(0)
84
+
85
+ with torch.no_grad():
86
+ detections = self.model(image_tensor)
87
+
88
+ # Get the detection results
89
+ boxes = detections[0]['boxes'].cpu().numpy()
90
+ scores = detections[0]['scores'].cpu().numpy()
91
+ labels = detections[0]['labels'].cpu().numpy()
92
+
93
+ # Scale coordinates to original image dimensions
94
+ h, w = img.shape[:2]
95
+ scale_x, scale_y = w / 300, h / 300
96
+
97
+ # Draw detections
98
+ for box, label, score in zip(boxes, labels, scores):
99
+ if score > 0.5: # Only show confident detections
100
+ x_min, y_min, x_max, y_max = box
101
+ # Scale coordinates back to original image
102
+ x_min, x_max = int(x_min * scale_x), int(x_max * scale_x)
103
+ y_min, y_max = int(y_min * scale_y), int(y_max * scale_y)
104
+
105
+ cv2.rectangle(display_img, (x_min, y_min), (x_max, y_max), (0, 255, 0), 2)
106
+ label_name = classes[label - 1] # Adjust for background class
107
+ cv2.putText(display_img, f"{label_name} {score:.2f}",
108
+ (x_min, y_min - 5), cv2.FONT_HERSHEY_SIMPLEX,
109
+ 0.5, (0, 0, 255), 2)
110
+ except Exception as e:
111
+ logging.error(f"Error in inference: {e}")
112
+ cv2.putText(display_img, f"Error: {str(e)}", (10, 30),
113
+ cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
114
+
115
+ return av.VideoFrame.from_ndarray(display_img, format="bgr24")
116
+
117
+ processor_factory = SSDVideoProcessor
118
+ else:
119
+ st.warning("Model couldn't be loaded. Running in fallback mode.")
120
+ processor_factory = VideoProcessor
121
+
122
+ except Exception as e:
123
+ st.error(f"Error setting up model: {e}")
124
+ processor_factory = VideoProcessor
125
+
126
+ # Start WebRTC streaming in a try-except block
127
  try:
128
+ # Use simpler configuration with fewer options to reduce chances of error
129
  webrtc_ctx = webrtc_streamer(
130
+ key="mosquito-detection",
131
  mode=WebRtcMode.SENDRECV,
132
+ rtc_configuration=rtc_configuration,
133
+ video_processor_factory=processor_factory,
134
  media_stream_constraints={"video": True, "audio": False},
135
+ async_processing=False, # Try with sync processing first
136
  )
137
  except Exception as e:
138
  st.error(f"WebRTC Error: {e}")