imran-nawar commited on
Commit
8ce0f55
·
verified ·
1 Parent(s): a4d037c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +137 -72
app.py CHANGED
@@ -12,6 +12,13 @@ from PIL import Image
12
  import numpy as np
13
  from model_architecture import CLIPClassifier
14
  from streamlit_webrtc import webrtc_streamer, VideoTransformerBase, RTCConfiguration, WebRtcMode
 
 
 
 
 
 
 
15
 
16
  # Page configuration
17
  st.set_page_config(page_title="Facial Emotion Recognition", layout="wide")
@@ -19,81 +26,123 @@ st.set_page_config(page_title="Facial Emotion Recognition", layout="wide")
19
  # Constants
20
  EMOTIONS = ['angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral']
21
  PRETRAINED_MODEL = 'clip_fer.pth'
22
- RTC_CONFIGURATION = RTCConfiguration({"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]})
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
  def load_model(model_path, num_classes=7):
25
  """Load the CLIP-based emotion recognition model."""
26
- model = CLIPClassifier(num_classes)
27
- state_dict = torch.load(model_path, map_location=torch.device('cpu'))
28
- model.load_state_dict(state_dict)
29
- model.eval()
30
- return model
 
 
 
 
31
 
32
  def preprocess_image(image):
33
  """Preprocess image for the model."""
34
- transform = transforms.Compose([
35
- transforms.Resize((224, 224)),
36
- transforms.Grayscale(num_output_channels=3),
37
- transforms.ToTensor(),
38
- transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
39
- ])
40
- image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
41
- return transform(image).unsqueeze(0)
42
-
43
- # Load model and cascade classifier globally
44
- try:
45
- model = load_model(PRETRAINED_MODEL)
46
- face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
47
- except Exception as e:
48
- st.error(f"Error loading models: {str(e)}")
49
 
50
  class EmotionDetector(VideoTransformerBase):
51
- def transform(self, frame):
52
- img = frame.to_ndarray(format="bgr24")
53
- gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
54
-
55
- # Detect faces
56
- faces = face_cascade.detectMultiScale(
57
- image=gray,
58
- scaleFactor=1.1,
59
- minNeighbors=5,
60
- minSize=(30, 30)
61
- )
62
-
63
- # Process each detected face
64
- for (x, y, w, h) in faces:
65
- # Extract face region
66
- face = img[y:y+h, x:x+w]
67
 
68
- try:
69
- # Preprocess face for model
70
- face_tensor = preprocess_image(face)
71
-
72
- # Get prediction
73
- with torch.no_grad():
74
- output = model(face_tensor)
75
- _, predicted = torch.max(output, 1)
76
- emotion = EMOTIONS[predicted.item()]
77
-
78
- # Draw rectangle and emotion label
79
- cv2.rectangle(img, (x, y), (x+w, y+h), (210, 140, 70), 2)
80
- cv2.putText(
81
- img,
82
- emotion,
83
- (x, y-10),
84
- cv2.FONT_HERSHEY_SIMPLEX,
85
- 0.9,
86
- (50, 200, 0),
87
- 2
88
- )
89
- except Exception as e:
90
- print(f"Error processing face: {str(e)}")
91
- continue
92
-
93
- return img
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
  def main():
96
- # Sidebar
97
  st.sidebar.header("Facial Emotion Recognition System")
98
  activities = ["Home", "Live Detection", "About"]
99
  choice = st.sidebar.selectbox("Select Activity", activities)
@@ -116,14 +165,30 @@ def main():
116
  st.title("Live Emotion Detection")
117
  st.write("Click 'START' below to begin webcam emotion detection")
118
 
119
- webrtc_streamer(
120
- key="emotion_detection",
121
- mode=WebRtcMode.SENDRECV,
122
- rtc_configuration=RTC_CONFIGURATION,
123
- video_processor_factory=EmotionDetector,
124
- media_stream_constraints={"video": True, "audio": False},
125
- async_processing=True
126
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
 
128
  elif choice == "About":
129
  st.title("About")
 
12
  import numpy as np
13
  from model_architecture import CLIPClassifier
14
  from streamlit_webrtc import webrtc_streamer, VideoTransformerBase, RTCConfiguration, WebRtcMode
15
+ import av
16
+ import logging
17
+ import threading
18
+
19
+ # Configure logging
20
+ logging.basicConfig(level=logging.DEBUG)
21
+ logger = logging.getLogger(__name__)
22
 
23
  # Page configuration
24
  st.set_page_config(page_title="Facial Emotion Recognition", layout="wide")
 
26
  # Constants
27
  EMOTIONS = ['angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral']
28
  PRETRAINED_MODEL = 'clip_fer.pth'
29
+
30
+ # WebRTC configuration with additional STUN/TURN servers for better connectivity
31
+ RTC_CONFIGURATION = RTCConfiguration(
32
+ {"iceServers": [
33
+ {"urls": ["stun:stun.l.google.com:19302"]},
34
+ {"urls": ["stun:stun1.l.google.com:19302"]},
35
+ {"urls": ["stun:stun2.l.google.com:19302"]},
36
+ ]}
37
+ )
38
+
39
+ # Global state for model and face detector
40
+ model = None
41
+ face_cascade = None
42
+ model_lock = threading.Lock()
43
 
44
  def load_model(model_path, num_classes=7):
45
  """Load the CLIP-based emotion recognition model."""
46
+ try:
47
+ model = CLIPClassifier(num_classes)
48
+ state_dict = torch.load(model_path, map_location=torch.device('cpu'))
49
+ model.load_state_dict(state_dict)
50
+ model.eval()
51
+ return model
52
+ except Exception as e:
53
+ logger.error(f"Error loading model: {str(e)}")
54
+ raise
55
 
56
  def preprocess_image(image):
57
  """Preprocess image for the model."""
58
+ try:
59
+ transform = transforms.Compose([
60
+ transforms.Resize((224, 224)),
61
+ transforms.Grayscale(num_output_channels=3),
62
+ transforms.ToTensor(),
63
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
64
+ ])
65
+ image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
66
+ return transform(image).unsqueeze(0)
67
+ except Exception as e:
68
+ logger.error(f"Error preprocessing image: {str(e)}")
69
+ return None
 
 
 
70
 
71
  class EmotionDetector(VideoTransformerBase):
72
+ def __init__(self):
73
+ global model, face_cascade
74
+ # Initialize the model and face detector if not already done
75
+ if model is None:
76
+ with model_lock:
77
+ model = load_model(PRETRAINED_MODEL)
78
+ if face_cascade is None:
79
+ with model_lock:
80
+ face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
81
+ self.model = model
82
+ self.face_cascade = face_cascade
83
+ logger.info("EmotionDetector initialized successfully")
84
+
85
+ def recv(self, frame):
86
+ try:
87
+ img = frame.to_ndarray(format="bgr24")
88
 
89
+ # Check if image is valid
90
+ if img is None or img.size == 0:
91
+ logger.warning("Received empty frame")
92
+ return frame
93
+
94
+ # Convert to grayscale
95
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
96
+
97
+ # Detect faces
98
+ faces = self.face_cascade.detectMultiScale(
99
+ image=gray,
100
+ scaleFactor=1.1,
101
+ minNeighbors=5,
102
+ minSize=(30, 30)
103
+ )
104
+
105
+ # Process each detected face
106
+ for (x, y, w, h) in faces:
107
+ try:
108
+ # Extract and process face region
109
+ face = img[y:y+h, x:x+w]
110
+ if face.size == 0:
111
+ continue
112
+
113
+ face_tensor = preprocess_image(face)
114
+ if face_tensor is None:
115
+ continue
116
+
117
+ # Get prediction
118
+ with torch.no_grad():
119
+ output = self.model(face_tensor)
120
+ _, predicted = torch.max(output, 1)
121
+ emotion = EMOTIONS[predicted.item()]
122
+
123
+ # Draw rectangle and emotion label
124
+ cv2.rectangle(img, (x, y), (x+w, y+h), (210, 140, 70), 2)
125
+ cv2.putText(
126
+ img,
127
+ emotion,
128
+ (x, y-10),
129
+ cv2.FONT_HERSHEY_SIMPLEX,
130
+ 0.9,
131
+ (50, 200, 0),
132
+ 2
133
+ )
134
+ except Exception as e:
135
+ logger.error(f"Error processing individual face: {str(e)}")
136
+ continue
137
+
138
+ # Return the processed frame
139
+ return av.VideoFrame.from_ndarray(img, format="bgr24")
140
+
141
+ except Exception as e:
142
+ logger.error(f"Error in frame processing: {str(e)}")
143
+ return frame
144
 
145
  def main():
 
146
  st.sidebar.header("Facial Emotion Recognition System")
147
  activities = ["Home", "Live Detection", "About"]
148
  choice = st.sidebar.selectbox("Select Activity", activities)
 
165
  st.title("Live Emotion Detection")
166
  st.write("Click 'START' below to begin webcam emotion detection")
167
 
168
+ # Status placeholder for debugging
169
+ status_place = st.empty()
170
+
171
+ try:
172
+ webrtc_ctx = webrtc_streamer(
173
+ key="emotion_detection",
174
+ mode=WebRtcMode.SENDRECV,
175
+ rtc_configuration=RTC_CONFIGURATION,
176
+ video_processor_factory=EmotionDetector,
177
+ media_stream_constraints={
178
+ "video": {"width": 640, "height": 480, "frameRate": {"ideal": 30}},
179
+ "audio": False
180
+ },
181
+ async_processing=True
182
+ )
183
+
184
+ if webrtc_ctx.state.playing:
185
+ status_place.success("Stream started successfully!")
186
+ else:
187
+ status_place.warning("Stream not started. Please check your camera permissions.")
188
+
189
+ except Exception as e:
190
+ st.error(f"Error initializing video stream: {str(e)}")
191
+ logger.error(f"Stream error: {str(e)}")
192
 
193
  elif choice == "About":
194
  st.title("About")