nirnit-13 commited on
Commit
8438cdf
Β·
1 Parent(s): 8a69ca5

Fix: non-blocking threaded inference, 25fps stream, download button

Browse files
Files changed (1) hide show
  1. app.py +145 -97
app.py CHANGED
@@ -1,9 +1,10 @@
1
  import cv2
2
  import numpy as np
3
  import gradio as gr
 
4
  from keras.models import load_model
5
 
6
- # Load model
7
  model = load_model("emotion_detection_model.h5")
8
 
9
  # Emotion labels
@@ -15,134 +16,181 @@ emotion_labels = {
15
  4: "Surprised"
16
  }
17
 
18
- # Emotion colors (BGR) β€” each emotion gets a distinct color
19
  emotion_colors = {
20
- "Angry": (0, 0, 255), # Red
21
- "Happy": (0, 200, 0), # Green
22
- "Neutral": (200, 200, 0), # Cyan
23
- "Sad": (255, 100, 0), # Blue
24
- "Surprised": (0, 140, 255) # Orange
25
  }
26
 
27
- # Load face detector via OpenCV built-in path
28
  face_cascade = cv2.CascadeClassifier(
29
  cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
30
  )
31
 
32
- def detect_emotion(frame):
33
- """
34
- Called on each throttled webcam frame.
35
- Detects faces, predicts emotion, draws annotations.
36
- Returns the annotated frame (RGB) to replace the webcam feed.
37
- """
38
- if frame is None:
39
- return frame
40
 
41
- # Gradio streams RGB β€” convert to BGR for OpenCV processing
42
- frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
43
- gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY)
44
 
45
- # Equalize histogram for better detection in varied lighting
46
- gray = cv2.equalizeHist(gray)
 
 
 
 
47
 
48
  faces = face_cascade.detectMultiScale(
49
- gray,
50
  scaleFactor=1.2,
51
  minNeighbors=6,
52
  minSize=(60, 60)
53
  )
54
 
55
- if len(faces) == 0:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  cv2.putText(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  frame_bgr,
58
- "No face detected",
59
- (20, 40),
60
- cv2.FONT_HERSHEY_SIMPLEX,
61
- 0.9,
62
- (0, 0, 255),
63
- 2,
64
- cv2.LINE_AA
65
  )
66
- else:
67
- for (x, y, w, h) in faces:
68
- # Crop and preprocess face for model
69
- face_roi = gray[y:y+h, x:x+w]
70
- face_roi = cv2.resize(face_roi, (48, 48))
71
- face_roi = face_roi / 255.0
72
- face_roi = face_roi.reshape(1, 48, 48, 1)
73
-
74
- # Predict emotion
75
- prediction = model.predict(face_roi, verbose=0)
76
- emotion = emotion_labels[np.argmax(prediction)]
77
- confidence = float(np.max(prediction)) * 100
78
- color = emotion_colors[emotion]
79
-
80
- # Draw bounding box
81
- cv2.rectangle(frame_bgr, (x, y), (x+w, y+h), color, 2)
82
-
83
- # Build label
84
- label = f"{emotion} {confidence:.1f}%"
85
- font = cv2.FONT_HERSHEY_SIMPLEX
86
- font_scale = 0.75
87
- thickness = 2
88
- (tw, th), baseline = cv2.getTextSize(label, font, font_scale, thickness)
89
-
90
- # Filled label background above the box
91
- label_y = max(y - 10, th + 10)
92
- cv2.rectangle(
93
- frame_bgr,
94
- (x, label_y - th - baseline - 4),
95
- (x + tw + 6, label_y + baseline - 4),
96
- color,
97
- -1
98
- )
99
-
100
- # Label text in black for contrast
101
- cv2.putText(
102
- frame_bgr,
103
- label,
104
- (x + 3, label_y - baseline),
105
- font,
106
- font_scale,
107
- (0, 0, 0),
108
- thickness,
109
- cv2.LINE_AA
110
- )
111
-
112
- # Return RGB for Gradio
113
- return cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
114
-
115
-
116
- # ── Gradio Interface ──────────────────────────────────────────────
 
 
117
  with gr.Blocks(title="Real-Time Emotion Detection") as demo:
118
 
119
  gr.Markdown("""
120
  # 😊 Real-Time Emotion Detection
121
- Click **β–Ά Start** on the webcam below to begin.
122
- Detectable emotions: 😠 Angry  |  πŸ˜„ Happy  |  😐 Neutral  |  😒 Sad  |  😲 Surprised
 
123
  """)
124
 
125
- # Single webcam component β€” output feeds back into the same stream
126
- # stream_every=0.1 β†’ process ~10 frames/sec (smooth without blinking)
127
- webcam = gr.Image(
128
- sources=["webcam"],
129
- streaming=True,
130
- label="Live Feed",
131
- )
 
 
 
 
 
132
 
 
 
133
  webcam.stream(
134
- fn=detect_emotion,
135
  inputs=webcam,
136
- outputs=webcam,
137
- stream_every=0.1, # throttle: run inference every 100ms (~10 fps)
138
- time_limit=300 # auto-stop stream after 5 minutes
139
  )
140
 
141
  gr.Markdown("""
142
  ---
143
- **Model:** Custom CNN β€” 3 Conv layers β†’ Dense(256) β†’ Softmax(5)
144
- **Input:** 48Γ—48 grayscale face patch
145
- **Face Detection:** OpenCV Haar Cascade
146
  """)
147
 
148
 
 
1
  import cv2
2
  import numpy as np
3
  import gradio as gr
4
+ import threading
5
  from keras.models import load_model
6
 
7
+ # ── Load model ────────────────────────────────────────────────────
8
  model = load_model("emotion_detection_model.h5")
9
 
10
  # Emotion labels
 
16
  4: "Surprised"
17
  }
18
 
19
+ # Emotion colors (BGR)
20
  emotion_colors = {
21
+ "Angry": (0, 0, 255),
22
+ "Happy": (0, 200, 0),
23
+ "Neutral": (200, 200, 0),
24
+ "Sad": (255, 100, 0),
25
+ "Surprised": (0, 140, 255)
26
  }
27
 
28
+ # Load face detector
29
  face_cascade = cv2.CascadeClassifier(
30
  cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
31
  )
32
 
33
+ # ── Shared state for background inference ─────────────────────────
34
+ # Stores the latest annotation result so the webcam never waits for inference
35
+ _lock = threading.Lock()
36
+ _latest_result = {"faces": [], "emotions": []} # filled by bg thread
37
+ _inference_busy = False # prevent overlapping calls
 
 
 
38
 
 
 
 
39
 
40
+ def _run_inference(gray_frame):
41
+ """
42
+ Runs face detection + emotion prediction in a background thread.
43
+ Writes results into _latest_result so the main stream can read them.
44
+ """
45
+ global _inference_busy, _latest_result
46
 
47
  faces = face_cascade.detectMultiScale(
48
+ gray_frame,
49
  scaleFactor=1.2,
50
  minNeighbors=6,
51
  minSize=(60, 60)
52
  )
53
 
54
+ results = []
55
+ for (x, y, w, h) in faces:
56
+ face_roi = gray_frame[y:y+h, x:x+w]
57
+ face_roi = cv2.resize(face_roi, (48, 48))
58
+ face_roi = face_roi / 255.0
59
+ face_roi = face_roi.reshape(1, 48, 48, 1)
60
+
61
+ prediction = model.predict(face_roi, verbose=0)
62
+ emotion = emotion_labels[np.argmax(prediction)]
63
+ confidence = float(np.max(prediction)) * 100
64
+ results.append((x, y, w, h, emotion, confidence))
65
+
66
+ with _lock:
67
+ _latest_result = {"faces": results}
68
+ _inference_busy = False
69
+
70
+
71
+ def _annotate_frame(frame_bgr, results):
72
+ """
73
+ Draws bounding boxes and emotion labels onto the frame
74
+ using the latest inference results.
75
+ """
76
+ if not results["faces"]:
77
  cv2.putText(
78
+ frame_bgr, "No face detected", (20, 40),
79
+ cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2, cv2.LINE_AA
80
+ )
81
+ return frame_bgr
82
+
83
+ font = cv2.FONT_HERSHEY_SIMPLEX
84
+ font_scale = 0.75
85
+ thickness = 2
86
+
87
+ for (x, y, w, h, emotion, confidence) in results["faces"]:
88
+ color = emotion_colors[emotion]
89
+
90
+ # Bounding box
91
+ cv2.rectangle(frame_bgr, (x, y), (x+w, y+h), color, 2)
92
+
93
+ # Label
94
+ label = f"{emotion} {confidence:.1f}%"
95
+ (tw, th), baseline = cv2.getTextSize(label, font, font_scale, thickness)
96
+ label_y = max(y - 10, th + 10)
97
+
98
+ # Filled background
99
+ cv2.rectangle(
100
  frame_bgr,
101
+ (x, label_y - th - baseline - 4),
102
+ (x + tw + 6, label_y + baseline - 4),
103
+ color, -1
 
 
 
 
104
  )
105
+ # Text
106
+ cv2.putText(
107
+ frame_bgr, label, (x + 3, label_y - baseline),
108
+ font, font_scale, (0, 0, 0), thickness, cv2.LINE_AA
109
+ )
110
+
111
+ return frame_bgr
112
+
113
+
114
+ def process_frame(frame):
115
+ """
116
+ Main streaming function called by Gradio on every frame.
117
+
118
+ - Instantly returns the annotated frame using the LAST known inference
119
+ result β†’ webcam feed NEVER freezes or waits.
120
+ - Fires a new background inference thread only when the previous one
121
+ has finished β†’ no overlapping predictions.
122
+
123
+ Returns: (annotated_live_frame, snapshot_for_download)
124
+ """
125
+ global _inference_busy
126
+
127
+ if frame is None:
128
+ return None, None
129
+
130
+ # Convert RGB (Gradio) β†’ BGR (OpenCV)
131
+ frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
132
+ gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY)
133
+ gray = cv2.equalizeHist(gray)
134
+
135
+ # Fire inference in background only if not already running
136
+ with _lock:
137
+ busy = _inference_busy
138
+ if not busy:
139
+ with _lock:
140
+ _inference_busy = True
141
+ t = threading.Thread(target=_run_inference, args=(gray.copy(),), daemon=True)
142
+ t.start()
143
+
144
+ # Annotate current frame with LATEST available result (non-blocking)
145
+ with _lock:
146
+ results = dict(_latest_result)
147
+
148
+ annotated_bgr = _annotate_frame(frame_bgr.copy(), results)
149
+ annotated_rgb = cv2.cvtColor(annotated_bgr, cv2.COLOR_BGR2RGB)
150
+
151
+ # Snapshot = same annotated frame, returned as a downloadable image
152
+ snapshot = annotated_rgb.copy()
153
+
154
+ return annotated_rgb, snapshot
155
+
156
+
157
+ # ── Gradio UI ─────────────────────────────────────────────────────
158
  with gr.Blocks(title="Real-Time Emotion Detection") as demo:
159
 
160
  gr.Markdown("""
161
  # 😊 Real-Time Emotion Detection
162
+ Click **β–Ά Start** on the webcam to begin live detection.
163
+ Use the **πŸ“₯ Download** button below the output to save the current detection as an image.
164
+ Emotions detected: 😠 Angry  |  πŸ˜„ Happy  |  😐 Neutral  |  😒 Sad  |  😲 Surprised
165
  """)
166
 
167
+ with gr.Row():
168
+ # Left β€” live webcam input (never frozen, always streaming)
169
+ webcam = gr.Image(
170
+ sources=["webcam"],
171
+ streaming=True,
172
+ label="πŸ“· Live Webcam"
173
+ )
174
+ # Right β€” annotated output (updated every frame via bg inference)
175
+ output_img = gr.Image(
176
+ label="🎯 Detected Emotion",
177
+ show_download_button=True # ← built-in download button
178
+ )
179
 
180
+ # stream_every=0.04 β†’ ~25 fps capture rate
181
+ # inference runs in background so capture is never blocked
182
  webcam.stream(
183
+ fn=process_frame,
184
  inputs=webcam,
185
+ outputs=[output_img, output_img],
186
+ stream_every=0.04,
187
+ time_limit=600
188
  )
189
 
190
  gr.Markdown("""
191
  ---
192
+ **Model:** Custom CNN β€” Conv2D(45) β†’ Conv2D(64) β†’ Conv2D(128) β†’ Dense(256) β†’ Softmax(5)
193
+ **Input:** 48Γ—48 grayscale face patch  |  **Face Detector:** OpenCV Haar Cascade
 
194
  """)
195
 
196