Fix: both input and output panels now show live video simultaneously
Browse files
app.py
CHANGED
|
@@ -14,12 +14,11 @@ tf.config.threading.set_inter_op_parallelism_threads(2)
|
|
| 14 |
|
| 15 |
model = keras.models.load_model("emotion_detection_model.h5")
|
| 16 |
|
| 17 |
-
# Compile to concrete TF function β no re-tracing, instant inference
|
| 18 |
@tf.function(input_signature=[tf.TensorSpec(shape=[None, 48, 48, 1], dtype=tf.float32)])
|
| 19 |
def fast_predict(x):
|
| 20 |
return model(x, training=False)
|
| 21 |
|
| 22 |
-
# Warm-up
|
| 23 |
fast_predict(tf.zeros([1, 48, 48, 1], dtype=tf.float32))
|
| 24 |
|
| 25 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
@@ -35,7 +34,6 @@ EMOTION_EMOJIS = {
|
|
| 35 |
"Surprised": "π²"
|
| 36 |
}
|
| 37 |
|
| 38 |
-
# BGR colors per emotion
|
| 39 |
EMOTION_COLORS = {
|
| 40 |
"Angry": (0, 0, 255),
|
| 41 |
"Happy": (0, 200, 0),
|
|
@@ -54,138 +52,120 @@ face_cascade = cv2.CascadeClassifier(
|
|
| 54 |
cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
|
| 55 |
)
|
| 56 |
|
| 57 |
-
# Cache
|
| 58 |
_cache = {"frame": None}
|
| 59 |
|
| 60 |
|
| 61 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 62 |
# CORE PIPELINE
|
| 63 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 64 |
-
def
|
| 65 |
-
"""Downscale if needed, convert to equalised grayscale."""
|
| 66 |
-
h, w = bgr.shape[:2]
|
| 67 |
-
if w > max_width:
|
| 68 |
-
bgr = cv2.resize(
|
| 69 |
-
bgr, (max_width, int(h * max_width / w)),
|
| 70 |
-
interpolation=cv2.INTER_AREA
|
| 71 |
-
)
|
| 72 |
-
gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
|
| 73 |
-
gray = cv2.equalizeHist(gray)
|
| 74 |
-
return bgr, gray
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
def _batch_predict(gray, faces):
|
| 78 |
-
"""
|
| 79 |
-
Crop all face ROIs β batch β single fast_predict() call.
|
| 80 |
-
Returns list of (emotion_str, confidence_float).
|
| 81 |
-
"""
|
| 82 |
-
rois = []
|
| 83 |
-
for (x, y, w, h) in faces:
|
| 84 |
-
roi = cv2.resize(gray[y:y+h, x:x+w], (48, 48))
|
| 85 |
-
rois.append(roi.astype(np.float32) / 255.0)
|
| 86 |
-
|
| 87 |
-
batch = tf.constant(
|
| 88 |
-
np.array(rois).reshape(-1, 48, 48, 1), dtype=tf.float32
|
| 89 |
-
)
|
| 90 |
-
preds = fast_predict(batch).numpy()
|
| 91 |
-
|
| 92 |
-
out = []
|
| 93 |
-
for p in preds:
|
| 94 |
-
idx = int(np.argmax(p))
|
| 95 |
-
out.append((EMOTION_LABELS[idx], float(p[idx]) * 100))
|
| 96 |
-
return out
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
def _draw_annotations(bgr, faces, results):
|
| 100 |
"""
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
"""
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
label = f"{emotion} {EMOTION_EMOJIS[emotion]} ({conf:.1f}%)"
|
| 113 |
-
|
| 114 |
-
# Measure text for background rect
|
| 115 |
-
(tw, th), _ = cv2.getTextSize(label, FONT, 0.9, THICKNESS)
|
| 116 |
-
|
| 117 |
-
# Filled background above box (matches reference)
|
| 118 |
-
cv2.rectangle(
|
| 119 |
-
bgr,
|
| 120 |
-
(x, y - th - 10),
|
| 121 |
-
(x + tw + 10, y),
|
| 122 |
-
color, -1
|
| 123 |
-
)
|
| 124 |
-
|
| 125 |
-
# White text on colored background (matches reference)
|
| 126 |
-
cv2.putText(
|
| 127 |
-
bgr, label,
|
| 128 |
-
(x + 5, y - 5),
|
| 129 |
-
FONT, 0.9,
|
| 130 |
-
(255, 255, 255),
|
| 131 |
-
THICKNESS
|
| 132 |
)
|
| 133 |
-
return bgr
|
| 134 |
|
|
|
|
|
|
|
| 135 |
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
β annotate β cache β RGB out.
|
| 140 |
-
"""
|
| 141 |
-
bgr = cv2.cvtColor(rgb_frame, cv2.COLOR_RGB2BGR)
|
| 142 |
-
bgr, gray = _preprocess(bgr, max_width)
|
| 143 |
|
|
|
|
| 144 |
faces = face_cascade.detectMultiScale(
|
| 145 |
-
gray,
|
| 146 |
-
scaleFactor=1.3,
|
| 147 |
-
minNeighbors=5,
|
| 148 |
-
minSize=(40, 40),
|
| 149 |
-
flags=cv2.CASCADE_SCALE_IMAGE
|
| 150 |
)
|
| 151 |
|
| 152 |
if len(faces) == 0:
|
| 153 |
-
cv2.putText(
|
| 154 |
-
|
| 155 |
-
FONT, 0.9, (0, 0, 255), THICKNESS, cv2.LINE_AA
|
| 156 |
-
)
|
| 157 |
else:
|
| 158 |
-
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
|
| 161 |
-
|
|
|
|
| 162 |
_cache["frame"] = out
|
| 163 |
return out
|
| 164 |
|
| 165 |
|
| 166 |
-
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 167 |
-
# GRADIO HANDLERS
|
| 168 |
-
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 169 |
def live_detect(frame):
|
| 170 |
"""
|
| 171 |
-
Streaming handler
|
| 172 |
-
Returns
|
| 173 |
-
|
|
|
|
|
|
|
| 174 |
"""
|
| 175 |
if frame is None:
|
| 176 |
-
return None
|
| 177 |
-
|
|
|
|
| 178 |
|
| 179 |
|
| 180 |
def image_detect(image):
|
| 181 |
-
"""Static upload
|
| 182 |
if image is None:
|
| 183 |
return None
|
| 184 |
-
return
|
| 185 |
|
| 186 |
|
| 187 |
def save_snapshot():
|
| 188 |
-
"""Saves latest
|
| 189 |
frame = _cache.get("frame")
|
| 190 |
if frame is None:
|
| 191 |
return None
|
|
@@ -213,40 +193,43 @@ with gr.Blocks(title="Real-Time Emotion Detection", css=CSS) as demo:
|
|
| 213 |
# ββ TAB 1 : LIVE WEBCAM ββββββββββββββββββββββββββββββββββ
|
| 214 |
with gr.TabItem("π· Live Detection"):
|
| 215 |
gr.Markdown(
|
| 216 |
-
"Click **βΆ Start** on the webcam
|
| 217 |
-
"
|
| 218 |
-
"
|
|
|
|
| 219 |
)
|
|
|
|
| 220 |
with gr.Row():
|
| 221 |
-
#
|
| 222 |
input_image = gr.Image(
|
| 223 |
sources=["webcam"],
|
| 224 |
streaming=True,
|
| 225 |
-
label="π·
|
| 226 |
height=480
|
| 227 |
)
|
| 228 |
-
#
|
| 229 |
output_image = gr.Image(
|
| 230 |
-
label="π―
|
| 231 |
height=480
|
| 232 |
)
|
| 233 |
|
| 234 |
-
gr.Markdown(
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
|
| 239 |
with gr.Row():
|
| 240 |
dl_live = gr.DownloadButton(
|
| 241 |
label="π₯ Download Snapshot", variant="primary"
|
| 242 |
)
|
| 243 |
|
| 244 |
-
# stream
|
| 245 |
-
#
|
|
|
|
| 246 |
input_image.stream(
|
| 247 |
fn=live_detect,
|
| 248 |
inputs=input_image,
|
| 249 |
-
outputs=output_image,
|
| 250 |
stream_every=0.1,
|
| 251 |
time_limit=600
|
| 252 |
)
|
|
@@ -256,8 +239,9 @@ with gr.Blocks(title="Real-Time Emotion Detection", css=CSS) as demo:
|
|
| 256 |
with gr.TabItem("πΌοΈ Image Upload"):
|
| 257 |
gr.Markdown(
|
| 258 |
"Upload any photo and click **π Detect Emotions**. "
|
| 259 |
-
"
|
| 260 |
)
|
|
|
|
| 261 |
with gr.Row():
|
| 262 |
upload_in = gr.Image(
|
| 263 |
sources=["upload"], type="numpy",
|
|
@@ -269,10 +253,10 @@ with gr.Blocks(title="Real-Time Emotion Detection", css=CSS) as demo:
|
|
| 269 |
height=480
|
| 270 |
)
|
| 271 |
|
| 272 |
-
gr.Markdown(
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
|
| 277 |
with gr.Row():
|
| 278 |
detect_btn = gr.Button("π Detect Emotions", variant="primary")
|
|
|
|
| 14 |
|
| 15 |
model = keras.models.load_model("emotion_detection_model.h5")
|
| 16 |
|
|
|
|
| 17 |
@tf.function(input_signature=[tf.TensorSpec(shape=[None, 48, 48, 1], dtype=tf.float32)])
|
| 18 |
def fast_predict(x):
|
| 19 |
return model(x, training=False)
|
| 20 |
|
| 21 |
+
# Warm-up β compile graph before first frame hits
|
| 22 |
fast_predict(tf.zeros([1, 48, 48, 1], dtype=tf.float32))
|
| 23 |
|
| 24 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 34 |
"Surprised": "π²"
|
| 35 |
}
|
| 36 |
|
|
|
|
| 37 |
EMOTION_COLORS = {
|
| 38 |
"Angry": (0, 0, 255),
|
| 39 |
"Happy": (0, 200, 0),
|
|
|
|
| 52 |
cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
|
| 53 |
)
|
| 54 |
|
| 55 |
+
# Cache for download
|
| 56 |
_cache = {"frame": None}
|
| 57 |
|
| 58 |
|
| 59 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 60 |
# CORE PIPELINE
|
| 61 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 62 |
+
def _process(rgb_frame, max_width):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
"""
|
| 64 |
+
Mirrors the Detection.ipynb loop exactly:
|
| 65 |
+
1. Read frame (rgb_frame from Gradio)
|
| 66 |
+
2. Convert to gray
|
| 67 |
+
3. detectMultiScale
|
| 68 |
+
4. For each face: resize β normalize β predict β draw on frame
|
| 69 |
+
5. Return annotated frame
|
| 70 |
+
|
| 71 |
+
Both the raw frame (input panel) and annotated frame (output panel)
|
| 72 |
+
come from the same live stream β just like cv2.imshow() in the notebook.
|
| 73 |
"""
|
| 74 |
+
# Resize large frames for speed
|
| 75 |
+
h, w = rgb_frame.shape[:2]
|
| 76 |
+
if w > max_width:
|
| 77 |
+
rgb_frame = cv2.resize(
|
| 78 |
+
rgb_frame,
|
| 79 |
+
(max_width, int(h * max_width / w)),
|
| 80 |
+
interpolation=cv2.INTER_AREA
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
)
|
|
|
|
| 82 |
|
| 83 |
+
# Work on a copy so input panel stays clean
|
| 84 |
+
annotated = rgb_frame.copy()
|
| 85 |
|
| 86 |
+
# RGB β BGR for OpenCV (same as cv2.VideoCapture gives BGR)
|
| 87 |
+
img = cv2.cvtColor(annotated, cv2.COLOR_RGB2BGR)
|
| 88 |
+
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
+
# detectMultiScale β same params as Detection.ipynb
|
| 91 |
faces = face_cascade.detectMultiScale(
|
| 92 |
+
gray, scaleFactor=1.3, minNeighbors=5
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
)
|
| 94 |
|
| 95 |
if len(faces) == 0:
|
| 96 |
+
cv2.putText(img, "No face detected", (16, 40),
|
| 97 |
+
FONT, 0.9, (0, 0, 255), THICKNESS, cv2.LINE_AA)
|
|
|
|
|
|
|
| 98 |
else:
|
| 99 |
+
# Batch all faces β single predict call
|
| 100 |
+
rois = []
|
| 101 |
+
for (x, y, w, h) in faces:
|
| 102 |
+
face = gray[y:y+h, x:x+w]
|
| 103 |
+
face = cv2.resize(face, (48, 48))
|
| 104 |
+
face = face / 255.0
|
| 105 |
+
rois.append(face.reshape(48, 48, 1).astype(np.float32))
|
| 106 |
+
|
| 107 |
+
batch = tf.constant(np.array(rois), dtype=tf.float32)
|
| 108 |
+
predictions = fast_predict(batch).numpy()
|
| 109 |
+
|
| 110 |
+
for i, (x, y, w, h) in enumerate(faces):
|
| 111 |
+
emotion_index = int(np.argmax(predictions[i]))
|
| 112 |
+
emotion = EMOTION_LABELS[emotion_index]
|
| 113 |
+
confidence = float(predictions[i][emotion_index]) * 100
|
| 114 |
+
color = EMOTION_COLORS[emotion]
|
| 115 |
+
|
| 116 |
+
# Draw rectangle β same as Detection.ipynb
|
| 117 |
+
cv2.rectangle(img, (x, y), (x+w, y+h), color, 3)
|
| 118 |
+
|
| 119 |
+
# Label with emoji + confidence
|
| 120 |
+
label = f"{emotion} {EMOTION_EMOJIS[emotion]} ({confidence:.1f}%)"
|
| 121 |
+
|
| 122 |
+
# Filled label background above box
|
| 123 |
+
(tw, th), _ = cv2.getTextSize(label, FONT, 0.9, THICKNESS)
|
| 124 |
+
cv2.rectangle(
|
| 125 |
+
img,
|
| 126 |
+
(x, y - th - 10),
|
| 127 |
+
(x + tw + 10, y),
|
| 128 |
+
color, -1
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
# White text
|
| 132 |
+
cv2.putText(
|
| 133 |
+
img, label,
|
| 134 |
+
(x + 5, y - 5),
|
| 135 |
+
FONT, 0.9,
|
| 136 |
+
(255, 255, 255),
|
| 137 |
+
THICKNESS
|
| 138 |
+
)
|
| 139 |
|
| 140 |
+
# BGR β RGB for Gradio output
|
| 141 |
+
out = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 142 |
_cache["frame"] = out
|
| 143 |
return out
|
| 144 |
|
| 145 |
|
|
|
|
|
|
|
|
|
|
| 146 |
def live_detect(frame):
|
| 147 |
"""
|
| 148 |
+
Streaming handler.
|
| 149 |
+
Returns TWO values:
|
| 150 |
+
- raw frame β input_image (keeps input panel live)
|
| 151 |
+
- annotated β output_image (detection drawn on same frame)
|
| 152 |
+
This makes BOTH panels show live video simultaneously.
|
| 153 |
"""
|
| 154 |
if frame is None:
|
| 155 |
+
return None, None
|
| 156 |
+
annotated = _process(frame, max_width=480)
|
| 157 |
+
return frame, annotated # β raw + annotated returned together
|
| 158 |
|
| 159 |
|
| 160 |
def image_detect(image):
|
| 161 |
+
"""Static upload β runs same pipeline at full resolution."""
|
| 162 |
if image is None:
|
| 163 |
return None
|
| 164 |
+
return _process(image, max_width=1280)
|
| 165 |
|
| 166 |
|
| 167 |
def save_snapshot():
|
| 168 |
+
"""Saves latest annotated frame as PNG for download."""
|
| 169 |
frame = _cache.get("frame")
|
| 170 |
if frame is None:
|
| 171 |
return None
|
|
|
|
| 193 |
# ββ TAB 1 : LIVE WEBCAM ββββββββββββββββββββββββββββββββββ
|
| 194 |
with gr.TabItem("π· Live Detection"):
|
| 195 |
gr.Markdown(
|
| 196 |
+
"Click **βΆ Start** on the webcam. "
|
| 197 |
+
"**Left panel** = live raw feed Β· "
|
| 198 |
+
"**Right panel** = live detection output. "
|
| 199 |
+
"Both windows update in real time."
|
| 200 |
)
|
| 201 |
+
|
| 202 |
with gr.Row():
|
| 203 |
+
# Left β raw live feed (updated every frame from stream return)
|
| 204 |
input_image = gr.Image(
|
| 205 |
sources=["webcam"],
|
| 206 |
streaming=True,
|
| 207 |
+
label="π· Live Input",
|
| 208 |
height=480
|
| 209 |
)
|
| 210 |
+
# Right β annotated live output (detection drawn on same frame)
|
| 211 |
output_image = gr.Image(
|
| 212 |
+
label="π― Live Detection Output",
|
| 213 |
height=480
|
| 214 |
)
|
| 215 |
|
| 216 |
+
gr.Markdown(
|
| 217 |
+
"π Angry Β· π Happy Β· "
|
| 218 |
+
"π Neutral Β· π’ Sad Β· π² Surprised"
|
| 219 |
+
)
|
| 220 |
|
| 221 |
with gr.Row():
|
| 222 |
dl_live = gr.DownloadButton(
|
| 223 |
label="π₯ Download Snapshot", variant="primary"
|
| 224 |
)
|
| 225 |
|
| 226 |
+
# stream returns (raw_frame, annotated_frame)
|
| 227 |
+
# β input_image gets raw (live video stays moving)
|
| 228 |
+
# β output_image gets annotated (detections drawn on same live frame)
|
| 229 |
input_image.stream(
|
| 230 |
fn=live_detect,
|
| 231 |
inputs=input_image,
|
| 232 |
+
outputs=[input_image, output_image],
|
| 233 |
stream_every=0.1,
|
| 234 |
time_limit=600
|
| 235 |
)
|
|
|
|
| 239 |
with gr.TabItem("πΌοΈ Image Upload"):
|
| 240 |
gr.Markdown(
|
| 241 |
"Upload any photo and click **π Detect Emotions**. "
|
| 242 |
+
"Download the annotated result with **π₯ Download Result**."
|
| 243 |
)
|
| 244 |
+
|
| 245 |
with gr.Row():
|
| 246 |
upload_in = gr.Image(
|
| 247 |
sources=["upload"], type="numpy",
|
|
|
|
| 253 |
height=480
|
| 254 |
)
|
| 255 |
|
| 256 |
+
gr.Markdown(
|
| 257 |
+
"π Angry Β· π Happy Β· "
|
| 258 |
+
"π Neutral Β· π’ Sad Β· π² Surprised"
|
| 259 |
+
)
|
| 260 |
|
| 261 |
with gr.Row():
|
| 262 |
detect_btn = gr.Button("π Detect Emotions", variant="primary")
|