Fix: non-blocking threaded inference, 25fps stream, download button
Browse files
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)
|
| 19 |
emotion_colors = {
|
| 20 |
-
"Angry": (0, 0, 255),
|
| 21 |
-
"Happy": (0, 200, 0),
|
| 22 |
-
"Neutral": (200, 200, 0),
|
| 23 |
-
"Sad": (255, 100, 0),
|
| 24 |
-
"Surprised": (0, 140, 255)
|
| 25 |
}
|
| 26 |
|
| 27 |
-
# Load face detector
|
| 28 |
face_cascade = cv2.CascadeClassifier(
|
| 29 |
cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
|
| 30 |
)
|
| 31 |
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 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 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
faces = face_cascade.detectMultiScale(
|
| 49 |
-
|
| 50 |
scaleFactor=1.2,
|
| 51 |
minNeighbors=6,
|
| 52 |
minSize=(60, 60)
|
| 53 |
)
|
| 54 |
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
cv2.putText(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
frame_bgr,
|
| 58 |
-
|
| 59 |
-
(
|
| 60 |
-
|
| 61 |
-
0.9,
|
| 62 |
-
(0, 0, 255),
|
| 63 |
-
2,
|
| 64 |
-
cv2.LINE_AA
|
| 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 |
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
|
| 122 |
-
|
|
|
|
| 123 |
""")
|
| 124 |
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
|
|
|
|
|
|
| 133 |
webcam.stream(
|
| 134 |
-
fn=
|
| 135 |
inputs=webcam,
|
| 136 |
-
outputs=
|
| 137 |
-
stream_every=0.
|
| 138 |
-
time_limit=
|
| 139 |
)
|
| 140 |
|
| 141 |
gr.Markdown("""
|
| 142 |
---
|
| 143 |
-
**Model:** Custom CNN β
|
| 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 |
|