File size: 6,602 Bytes
e77ff29
 
 
f622629
18f35e3
e77ff29
 
 
 
 
18f35e3
f622629
 
 
 
 
 
e77ff29
 
 
 
 
 
 
 
 
 
 
 
f622629
 
 
 
 
 
e77ff29
 
 
 
 
 
 
 
f622629
 
e77ff29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f622629
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e77ff29
 
 
 
 
f622629
e77ff29
f622629
e77ff29
 
 
 
 
 
 
 
f622629
e77ff29
 
 
 
 
 
 
 
 
f622629
e77ff29
f622629
e77ff29
 
 
 
f622629
 
e77ff29
 
f622629
e77ff29
 
f622629
e77ff29
 
f622629
e77ff29
f622629
e77ff29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f622629
e77ff29
 
f622629
e77ff29
f622629
 
e77ff29
 
f622629
e77ff29
 
f622629
e77ff29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f622629
 
 
 
 
 
 
e77ff29
 
 
 
 
 
 
 
 
 
f622629
 
e77ff29
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import av
import cv2
import torch
import asyncio
import streamlit as st
from PIL import Image, ImageEnhance
from facenet_pytorch import MTCNN
from transformers import pipeline
from collections import deque, Counter
from streamlit_webrtc import webrtc_streamer, VideoProcessorBase

# Fix for asyncio event loop issues on Hugging Face Spaces
try:
    asyncio.get_event_loop()
except RuntimeError:
    asyncio.set_event_loop(asyncio.new_event_loop())

# =========================
# CONFIG
# =========================
MODEL_NAME = "trpakov/vit-face-expression"

FACE_CONFIDENCE = 0.90
PROCESS_EVERY_N_FRAMES = 2
SMOOTHING_FRAMES = 10

SAD_MIN_SCORE = 0.18
SAD_NEUTRAL_MARGIN = 0.15

EMOTION_COLORS = {
    "happy":   (0, 255, 0),    # Green
    "sad":     (255, 0, 0),    # Blue (BGR)
    "neutral": (255, 255, 0),  # Cyan
}

device = "cuda" if torch.cuda.is_available() else "cpu"


# =========================
# STREAMLIT UI
# =========================
st.set_page_config(page_title="Face Emotion Detection", page_icon="😊", layout="wide")

st.title("😊 Real-Time Face Emotion Detection")
st.write("Detects face emotions in real time: **Happy**, **Sad**, or **Neutral**.")


# =========================
# CACHE MODELS
# =========================
@st.cache_resource
def load_models():
    face_detector = MTCNN(
        keep_all=True,
        device=device,
        min_face_size=60,
        thresholds=[0.6, 0.7, 0.7]
    )

    emotion_model = pipeline(
        "image-classification",
        model=MODEL_NAME,
        top_k=None,
        device=0 if torch.cuda.is_available() else -1
    )

    return face_detector, emotion_model


face_detector, emotion_model = load_models()


# =========================
# HELPERS
# =========================
def get_emotion(preds: list) -> tuple[str, float]:
    """
    Extract happy / sad / neutral from model predictions.
    Applies a soft boost for sad so it isn't drowned out by neutral.
    Always returns one of the three labels β€” no 'uncertain' fallback.
    """
    scores = {p["label"].lower(): float(p["score"]) for p in preds}

    happy   = scores.get("happy",   0.0)
    sad     = scores.get("sad",     0.0)
    neutral = scores.get("neutral", 0.0)

    candidates = {"happy": happy, "sad": sad, "neutral": neutral}

    # Soft boost: prefer sad over neutral when it's close
    if sad >= SAD_MIN_SCORE and sad >= neutral - SAD_NEUTRAL_MARGIN:
        candidates["sad"] = max(sad, neutral - SAD_NEUTRAL_MARGIN + 0.01)

    label = max(candidates, key=candidates.get)
    score = candidates[label]

    return label, score


# =========================
# VIDEO PROCESSOR
# =========================
class EmotionProcessor(VideoProcessorBase):
    def __init__(self):
        self.history    = deque(maxlen=SMOOTHING_FRAMES)
        self.frame_count = 0
        self.last_box   = None
        self.last_label = "No Face"
        self.last_score = 0.0

    def recv(self, frame):
        img = frame.to_ndarray(format="bgr24")
        img = cv2.flip(img, 1)
        display = img.copy()

        h, w = img.shape[:2]
        self.frame_count += 1

        if self.frame_count % PROCESS_EVERY_N_FRAMES == 0:
            rgb_frame = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
            pil_frame = Image.fromarray(rgb_frame)

            boxes, probs = face_detector.detect(pil_frame)

            if boxes is None or probs is None:
                self._reset()
            else:
                # Keep only high-confidence faces; pick the largest one
                valid_faces = []
                for box, prob in zip(boxes, probs):
                    if prob >= FACE_CONFIDENCE:
                        x1, y1, x2, y2 = box.astype(int)
                        x1, y1 = max(0, x1), max(0, y1)
                        x2, y2 = min(w, x2), min(h, y2)
                        area = (x2 - x1) * (y2 - y1)
                        if area > 0:
                            valid_faces.append((area, x1, y1, x2, y2))

                if not valid_faces:
                    self._reset()
                else:
                    valid_faces.sort(reverse=True)
                    _, x1, y1, x2, y2 = valid_faces[0]

                    # Pad the crop for better context
                    pad_x = int((x2 - x1) * 0.20)
                    pad_y = int((y2 - y1) * 0.25)
                    x1p = max(0, x1 - pad_x)
                    y1p = max(0, y1 - pad_y)
                    x2p = min(w, x2 + pad_x)
                    y2p = min(h, y2 + pad_y)

                    face_crop = rgb_frame[y1p:y2p, x1p:x2p]

                    if face_crop.size != 0:
                        face_img = Image.fromarray(face_crop).resize((224, 224))
                        face_img = ImageEnhance.Contrast(face_img).enhance(1.25)
                        face_img = ImageEnhance.Sharpness(face_img).enhance(1.15)

                        preds = emotion_model(face_img)
                        label, score = get_emotion(preds)

                        self.history.append(label)
                        smoothed_label = Counter(self.history).most_common(1)[0][0]

                        self.last_box   = (x1p, y1p, x2p, y2p)
                        self.last_label = smoothed_label
                        self.last_score = score

        # Draw results on frame
        if self.last_box is not None:
            x1, y1, x2, y2 = self.last_box
            color = EMOTION_COLORS.get(self.last_label, (200, 200, 200))

            cv2.rectangle(display, (x1, y1), (x2, y2), color, 2)
            cv2.putText(
                display,
                f"{self.last_label.upper()} ({self.last_score:.2f})",
                (x1, max(30, y1 - 10)),
                cv2.FONT_HERSHEY_SIMPLEX,
                0.75,
                color,
                2
            )
        else:
            cv2.putText(
                display,
                "NO FACE DETECTED",
                (30, 50),
                cv2.FONT_HERSHEY_SIMPLEX,
                0.9,
                (0, 0, 255),
                2
            )

        return av.VideoFrame.from_ndarray(display, format="bgr24")

    def _reset(self):
        """Clear state when no valid face is found."""
        self.last_box   = None
        self.last_label = "No Face"
        self.last_score = 0.0
        self.history.clear()


# =========================
# START CAMERA
# =========================
webrtc_streamer(
    key="emotion-detection",
    video_processor_factory=EmotionProcessor,
    media_stream_constraints={
        "video": True,
        "audio": False
    },
    async_processing=True,
)