Spaces:
Build error
Build error
Update app.py
Browse files
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
def load_model(model_path, num_classes=7):
|
| 25 |
"""Load the CLIP-based emotion recognition model."""
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
def preprocess_image(image):
|
| 33 |
"""Preprocess image for the model."""
|
| 34 |
-
|
| 35 |
-
transforms.
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 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
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 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")
|