Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,6 +7,8 @@ import streamlit as st
|
|
| 7 |
from PIL import Image
|
| 8 |
import numpy as np
|
| 9 |
import time
|
|
|
|
|
|
|
| 10 |
|
| 11 |
# Définition du modèle CNN
|
| 12 |
class EmotionCNN(nn.Module):
|
|
@@ -127,7 +129,7 @@ st.title("🎭 Détecteur d'Émotions en Temps Réel")
|
|
| 127 |
def load_model():
|
| 128 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 129 |
model = EmotionCNN().to(device)
|
| 130 |
-
model.load_state_dict(torch.load("cnn_emotion_model.pth", map_location=device))
|
| 131 |
model.eval()
|
| 132 |
return model, device
|
| 133 |
|
|
@@ -150,85 +152,78 @@ def detect_faces(frame):
|
|
| 150 |
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
|
| 151 |
return faces
|
| 152 |
|
| 153 |
-
# Configuration
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
col1, col2 = st.columns([2, 1])
|
| 155 |
|
| 156 |
with col1:
|
| 157 |
st.markdown("### 📹 Flux Vidéo")
|
| 158 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
with col2:
|
| 161 |
st.markdown("### 😊 Émotion Détectée")
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
if start_button:
|
| 169 |
-
cap = cv2.VideoCapture(0)
|
| 170 |
-
|
| 171 |
-
if not cap.isOpened():
|
| 172 |
-
st.error("❌ Impossible d'accéder à la webcam. Veuillez vérifier vos permissions.")
|
| 173 |
-
st.stop()
|
| 174 |
-
|
| 175 |
-
try:
|
| 176 |
-
while True:
|
| 177 |
-
ret, frame = cap.read()
|
| 178 |
-
if not ret:
|
| 179 |
-
st.error("❌ Erreur lors de la capture vidéo.")
|
| 180 |
-
break
|
| 181 |
-
|
| 182 |
-
# Détection des visages
|
| 183 |
-
faces = detect_faces(frame)
|
| 184 |
-
|
| 185 |
-
# Traitement de chaque visage détecté
|
| 186 |
-
for (x, y, w, h) in faces:
|
| 187 |
-
# Dessiner la bounding box
|
| 188 |
-
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
|
| 189 |
-
|
| 190 |
-
# Extraire et prétraiter le visage
|
| 191 |
-
face_img = frame[y:y+h, x:x+w]
|
| 192 |
-
pil_img = Image.fromarray(cv2.cvtColor(face_img, cv2.COLOR_BGR2RGB))
|
| 193 |
-
|
| 194 |
-
# Prédiction de l'émotion
|
| 195 |
-
img_tensor = transform(pil_img).unsqueeze(0).to(device)
|
| 196 |
-
with torch.no_grad():
|
| 197 |
-
output = model(img_tensor)
|
| 198 |
-
_, predicted = torch.max(output, 1)
|
| 199 |
-
emotion_idx = predicted.item()
|
| 200 |
-
|
| 201 |
-
# Afficher l'émotion sur l'image
|
| 202 |
-
emotion_name = emotion_dict[emotion_idx]["name"]
|
| 203 |
-
cv2.putText(frame, emotion_name, (x, y-10),
|
| 204 |
-
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
|
| 205 |
-
|
| 206 |
-
# Mettre à jour l'affichage de l'émotion et du message
|
| 207 |
-
with emotion_placeholder:
|
| 208 |
-
st.markdown(f"""
|
| 209 |
-
<div class="emotion-box">
|
| 210 |
-
<div class="emotion-title">{emotion_name}</div>
|
| 211 |
-
</div>
|
| 212 |
-
""", unsafe_allow_html=True)
|
| 213 |
-
|
| 214 |
-
with message_placeholder:
|
| 215 |
-
st.markdown(f"""
|
| 216 |
-
<div class="emotion-box">
|
| 217 |
-
<div class="emotion-message">{emotion_dict[emotion_idx]["message"]}</div>
|
| 218 |
-
</div>
|
| 219 |
-
""", unsafe_allow_html=True)
|
| 220 |
-
|
| 221 |
-
# Afficher le flux vidéo
|
| 222 |
-
frame_placeholder.image(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
|
| 223 |
-
|
| 224 |
-
# Petite pause pour éviter une surcharge
|
| 225 |
-
time.sleep(0.1)
|
| 226 |
-
|
| 227 |
-
except Exception as e:
|
| 228 |
-
st.error(f"Une erreur s'est produite : {str(e)}")
|
| 229 |
|
| 230 |
-
|
| 231 |
-
|
| 232 |
|
| 233 |
-
|
| 234 |
-
st.info("👆 Cliquez sur le bouton pour démarrer la détection d'émotions.")
|
|
|
|
| 7 |
from PIL import Image
|
| 8 |
import numpy as np
|
| 9 |
import time
|
| 10 |
+
from streamlit_webrtc import webrtc_streamer, VideoProcessorBase, RTCConfiguration
|
| 11 |
+
import av
|
| 12 |
|
| 13 |
# Définition du modèle CNN
|
| 14 |
class EmotionCNN(nn.Module):
|
|
|
|
| 129 |
def load_model():
|
| 130 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 131 |
model = EmotionCNN().to(device)
|
| 132 |
+
model.load_state_dict(torch.load("modele/cnn_emotion_model.pth", map_location=device))
|
| 133 |
model.eval()
|
| 134 |
return model, device
|
| 135 |
|
|
|
|
| 152 |
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
|
| 153 |
return faces
|
| 154 |
|
| 155 |
+
# Configuration RTC pour WebRTC (utile pour Hugging Face Spaces)
|
| 156 |
+
RTC_CONFIGURATION = RTCConfiguration({
|
| 157 |
+
"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]
|
| 158 |
+
})
|
| 159 |
+
|
| 160 |
+
# Classe pour traiter les frames vidéo
|
| 161 |
+
class VideoProcessor(VideoProcessorBase):
|
| 162 |
+
def __init__(self):
|
| 163 |
+
self.model = model
|
| 164 |
+
self.device = device
|
| 165 |
+
self.transform = transform
|
| 166 |
+
self.face_cascade = face_cascade
|
| 167 |
+
self.emotion_dict = emotion_dict
|
| 168 |
+
self.emotion_placeholder = st.session_state.get('emotion_placeholder')
|
| 169 |
+
self.message_placeholder = st.session_state.get('message_placeholder')
|
| 170 |
+
|
| 171 |
+
def recv(self, frame):
|
| 172 |
+
img = frame.to_ndarray(format="bgr24")
|
| 173 |
+
faces = detect_faces(img)
|
| 174 |
+
|
| 175 |
+
for (x, y, w, h) in faces:
|
| 176 |
+
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
|
| 177 |
+
face_img = img[y:y+h, x:x+w]
|
| 178 |
+
pil_img = Image.fromarray(cv2.cvtColor(face_img, cv2.COLOR_BGR2RGB))
|
| 179 |
+
img_tensor = self.transform(pil_img).unsqueeze(0).to(self.device)
|
| 180 |
+
with torch.no_grad():
|
| 181 |
+
output = self.model(img_tensor)
|
| 182 |
+
_, predicted = torch.max(output, 1)
|
| 183 |
+
emotion_idx = predicted.item()
|
| 184 |
+
emotion_name = self.emotion_dict[emotion_idx]["name"]
|
| 185 |
+
cv2.putText(img, emotion_name, (x, y-10),
|
| 186 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
|
| 187 |
+
|
| 188 |
+
# Mettre à jour les placeholders (utiliser st.session_state pour partager)
|
| 189 |
+
if self.emotion_placeholder:
|
| 190 |
+
self.emotion_placeholder.markdown(f"""
|
| 191 |
+
<div class="emotion-box">
|
| 192 |
+
<div class="emotion-title">{emotion_name}</div>
|
| 193 |
+
</div>
|
| 194 |
+
""", unsafe_allow_html=True)
|
| 195 |
+
|
| 196 |
+
if self.message_placeholder:
|
| 197 |
+
self.message_placeholder.markdown(f"""
|
| 198 |
+
<div class="emotion-box">
|
| 199 |
+
<div class="emotion-message">{self.emotion_dict[emotion_idx]["message"]}</div>
|
| 200 |
+
</div>
|
| 201 |
+
""", unsafe_allow_html=True)
|
| 202 |
+
|
| 203 |
+
return av.VideoFrame.from_ndarray(img, format="bgr24")
|
| 204 |
+
|
| 205 |
+
# Configuration de la webcam avec streamlit-webrtc
|
| 206 |
col1, col2 = st.columns([2, 1])
|
| 207 |
|
| 208 |
with col1:
|
| 209 |
st.markdown("### 📹 Flux Vidéo")
|
| 210 |
+
# Lancer le flux webcam
|
| 211 |
+
webrtc_ctx = webrtc_streamer(
|
| 212 |
+
key="emotion-detection",
|
| 213 |
+
rtc_configuration=RTC_CONFIGURATION,
|
| 214 |
+
video_processor_factory=VideoProcessor,
|
| 215 |
+
media_stream_constraints={"video": True, "audio": False},
|
| 216 |
+
)
|
| 217 |
|
| 218 |
with col2:
|
| 219 |
st.markdown("### 😊 Émotion Détectée")
|
| 220 |
+
# Utiliser session_state pour partager les placeholders avec VideoProcessor
|
| 221 |
+
if 'emotion_placeholder' not in st.session_state:
|
| 222 |
+
st.session_state.emotion_placeholder = st.empty()
|
| 223 |
+
if 'message_placeholder' not in st.session_state:
|
| 224 |
+
st.session_state.message_placeholder = st.empty()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
|
| 226 |
+
emotion_placeholder = st.session_state.emotion_placeholder
|
| 227 |
+
message_placeholder = st.session_state.message_placeholder
|
| 228 |
|
| 229 |
+
st.info("👆 Autorisez l'accès à la webcam dans votre navigateur pour démarrer la détection d'émotions.")
|
|
|