nirnit-13 commited on
Commit
6dcd49f
Β·
1 Parent(s): 50d1309

Fix: both input and output panels now show live video simultaneously

Browse files
Files changed (1) hide show
  1. app.py +104 -120
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: compile graph before first real frame
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 latest annotated frame for download
58
  _cache = {"frame": None}
59
 
60
 
61
  # ═══════════════════════════════════════════════════════════════════
62
  # CORE PIPELINE
63
  # ═══════════════════════════════════════════════════════════════════
64
- def _preprocess(bgr, max_width):
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
- For each face: colored bounding box (thickness=3) +
102
- filled label background + white text with emoji β€” exactly
103
- as in the reference code, but using batch-predicted results.
 
 
 
 
 
 
104
  """
105
- for (x, y, w, h), (emotion, conf) in zip(faces, results):
106
- color = EMOTION_COLORS[emotion]
107
-
108
- # Bounding box (thickness 3 β€” matches reference)
109
- cv2.rectangle(bgr, (x, y), (x+w, y+h), color, 3)
110
-
111
- # Label: "Angry 😠 (94.3%)"
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
- def _run_pipeline(rgb_frame, max_width):
137
- """
138
- Full pipeline: RGB in β†’ preprocess β†’ detect β†’ batch predict
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
- bgr, "No face detected", (16, 40),
155
- FONT, 0.9, (0, 0, 255), THICKNESS, cv2.LINE_AA
156
- )
157
  else:
158
- results = _batch_predict(gray, faces)
159
- _draw_annotations(bgr, faces, results)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
 
161
- out = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
 
162
  _cache["frame"] = out
163
  return out
164
 
165
 
166
- # ═══════════════════════════════════════════════════════════════════
167
- # GRADIO HANDLERS
168
- # ═══════════════════════════════════════════════════════════════════
169
  def live_detect(frame):
170
  """
171
- Streaming handler β€” called on every webcam frame.
172
- Returns annotated frame to the OUTPUT panel only;
173
- the INPUT panel keeps showing the raw live feed.
 
 
174
  """
175
  if frame is None:
176
- return None
177
- return _run_pipeline(frame, max_width=480)
 
178
 
179
 
180
  def image_detect(image):
181
- """Static upload handler."""
182
  if image is None:
183
  return None
184
- return _run_pipeline(image, max_width=1280)
185
 
186
 
187
  def save_snapshot():
188
- """Saves latest cached frame as PNG, returns path for download."""
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 to begin. "
217
- "The left panel shows your **live feed**, the right shows **detections**. "
218
- "Use **πŸ“₯ Download Snapshot** to save."
 
219
  )
 
220
  with gr.Row():
221
- # Input β€” raw live webcam feed (always streaming, never frozen)
222
  input_image = gr.Image(
223
  sources=["webcam"],
224
  streaming=True,
225
- label="πŸ“· Webcam Input",
226
  height=480
227
  )
228
- # Output β€” annotated result updated every frame
229
  output_image = gr.Image(
230
- label="🎯 Emotion Detection Output",
231
  height=480
232
  )
233
 
234
- gr.Markdown("""
235
- **Detects 5 emotions:**
236
-   πŸ˜  Angry  Β·  😊 Happy  Β·  😐 Neutral  Β·  😒 Sad  Β·  😲 Surprised
237
- """)
238
 
239
  with gr.Row():
240
  dl_live = gr.DownloadButton(
241
  label="πŸ“₯ Download Snapshot", variant="primary"
242
  )
243
 
244
- # stream: input panel β†’ live_detect β†’ output panel
245
- # input panel continues streaming raw feed independently
 
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
- "Use **πŸ“₯ Download Result** to save the annotated image."
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
- **Detects 5 emotions:**
274
-   πŸ˜  Angry  Β·  😊 Happy  Β·  😐 Neutral  Β·  😒 Sad  Β·  😲 Surprised
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")