nirnit-13 commited on
Commit
cbd5fd8
Β·
1 Parent(s): 9944c34

Add image upload tab, optimize with tf.function, batch predict, CPU tuning

Browse files
Files changed (1) hide show
  1. app.py +196 -118
app.py CHANGED
@@ -5,70 +5,71 @@ import tempfile
5
  import tensorflow as tf
6
  from tensorflow import keras
7
 
8
- # ── Fix TensorFlow graph execution for fast inference ─────────────
9
- # Build the model once and compile the predict function into a
10
- # concrete TF graph so every call is instant with no re-tracing
11
- physical_devices = tf.config.list_physical_devices("CPU")
12
- tf.config.set_visible_devices(physical_devices, "CPU")
 
13
 
14
  model = keras.models.load_model("emotion_detection_model.h5")
15
 
16
- # Warm-up: run one dummy prediction so TF compiles the graph now,
17
- # not on the first real frame (which caused the 3-min freeze)
18
- _dummy = np.zeros((1, 48, 48, 1), dtype=np.float32)
19
- model.predict(_dummy, verbose=0)
20
-
21
- # ── Constants ─────────────────────────────────────────────────────
22
- EMOTION_LABELS = {
23
- 0: "Angry",
24
- 1: "Happy",
25
- 2: "Neutral",
26
- 3: "Sad",
27
- 4: "Surprised"
28
- }
29
 
30
- # BGR colors for each emotion
31
  COLORS = {
32
  "Angry": (0, 0, 255),
33
- "Happy": (0, 200, 0),
34
- "Neutral": (200, 200, 0),
35
- "Sad": (255, 100, 0),
36
- "Surprised": (0, 140, 255)
37
  }
38
 
39
- # Load face detector
40
- face_cascade = cv2.CascadeClassifier(
 
 
 
 
 
 
41
  cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
42
  )
43
 
44
- # Holds last saved snapshot path for download
45
- _snapshot_path = {"path": None}
46
-
47
-
48
- # ── Core detection function ────────────────────────────────────────
49
- def detect(frame):
50
- """
51
- Receives one webcam frame (RGB numpy array) from Gradio.
52
- Returns annotated RGB frame immediately β€” no threads, no queues.
53
- TF graph is pre-compiled so predict() takes ~20-50ms on CPU.
54
- """
55
- if frame is None:
56
- return None
57
-
58
- # RGB β†’ BGR for OpenCV
59
- bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
60
 
61
- # Resize to 480p max for faster processing without losing accuracy
62
- h, w = bgr.shape[:2]
63
- if w > 640:
64
- scale = 640 / w
65
- bgr = cv2.resize(bgr, (640, int(h * scale)))
66
 
67
- gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
 
 
 
 
 
 
 
 
 
 
 
68
  gray = cv2.equalizeHist(gray)
 
 
69
 
70
- # Detect faces
71
- faces = face_cascade.detectMultiScale(
 
72
  gray,
73
  scaleFactor=1.3,
74
  minNeighbors=5,
@@ -76,55 +77,90 @@ def detect(frame):
76
  flags=cv2.CASCADE_SCALE_IMAGE
77
  )
78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  if len(faces) == 0:
80
- cv2.putText(bgr, "No face detected", (20, 40),
81
- cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2, cv2.LINE_AA)
82
  else:
83
- # Batch all faces into one predict call for speed
84
- batch = []
85
- regions = []
86
- for (x, y, w, h) in faces:
87
- roi = gray[y:y+h, x:x+w]
88
- roi = cv2.resize(roi, (48, 48)).astype(np.float32) / 255.0
89
- batch.append(roi.reshape(48, 48, 1))
90
- regions.append((x, y, w, h))
91
-
92
- # Single batched prediction β€” much faster than one-by-one
93
- batch = np.array(batch, dtype=np.float32)
94
- predictions = model.predict(batch, verbose=0)
95
-
96
- for i, (x, y, w, h) in enumerate(regions):
97
- emotion = EMOTION_LABELS[np.argmax(predictions[i])]
98
- confidence = float(np.max(predictions[i])) * 100
99
- color = COLORS[emotion]
100
-
101
- # Bounding box
102
- cv2.rectangle(bgr, (x, y), (x+w, y+h), color, 2)
103
-
104
- # Label background + text
105
- label = f"{emotion} {confidence:.1f}%"
106
- font = cv2.FONT_HERSHEY_SIMPLEX
107
- (tw, th), bl = cv2.getTextSize(label, font, 0.7, 2)
108
- ly = max(y - 8, th + 8)
109
- cv2.rectangle(bgr,
110
- (x, ly - th - bl - 4),
111
- (x + tw + 6, ly + bl - 2),
112
- color, -1)
113
- cv2.putText(bgr, label, (x + 3, ly - bl),
114
- font, 0.7, (0, 0, 0), 2, cv2.LINE_AA)
115
-
116
- # BGR β†’ RGB for Gradio output
117
- result = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
118
-
119
- # Cache snapshot for download
120
- _snapshot_path["frame"] = result.copy()
121
 
 
 
122
  return result
123
 
124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  def save_snapshot():
126
- """Saves the latest annotated frame as a PNG and returns path for download."""
127
- frame = _snapshot_path.get("frame")
128
  if frame is None:
129
  return None
130
  tmp = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
@@ -133,41 +169,83 @@ def save_snapshot():
133
  return tmp.name
134
 
135
 
136
- # ── Gradio UI ─────────────────────────────────────────────────────
137
- with gr.Blocks(title="Real-Time Emotion Detection") as demo:
 
 
 
 
 
138
 
139
- gr.Markdown("""
140
- # 😊 Real-Time Emotion Detection
141
- Click **β–Ά Start** on the webcam feed to begin.
142
- Press **πŸ“₯ Download Snapshot** anytime to save the current frame.
143
-    πŸ˜  Angry  |  πŸ˜„ Happy  |  😐 Neutral  |  😒 Sad  |  😲 Surprised
144
- """)
145
-
146
- with gr.Row():
147
- webcam = gr.Image(sources=["webcam"], streaming=True,
148
- label="πŸ“· Live Webcam")
149
- output_img = gr.Image(label="🎯 Detected Emotion")
150
-
151
- with gr.Row():
152
- download_btn = gr.DownloadButton(
153
- label="πŸ“₯ Download Snapshot", variant="primary"
154
- )
155
 
156
- # stream_every=0.1 β†’ 10fps β€” safe for CPU, smooth, no backlog
157
- webcam.stream(
158
- fn=detect,
159
- inputs=webcam,
160
- outputs=output_img,
161
- stream_every=0.1,
162
- time_limit=600
163
  )
164
 
165
- download_btn.click(fn=save_snapshot, inputs=None, outputs=download_btn)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
 
167
  gr.Markdown("""
168
  ---
169
  **Model:** CNN β€” Conv2D(45) β†’ Conv2D(64) β†’ Conv2D(128) β†’ Dense(256) β†’ Softmax(5)  | 
170
- **Input:** 48Γ—48 grayscale  |  **Detector:** Haar Cascade
171
  """)
172
 
173
  if __name__ == "__main__":
 
5
  import tensorflow as tf
6
  from tensorflow import keras
7
 
8
+ # ═══════════════════════════════════════════════════════════════════
9
+ # MODEL SETUP β€” load once, warm up, lock graph for fast inference
10
+ # ═══════════════════════════════════════════════════════════════════
11
+ tf.config.set_visible_devices(tf.config.list_physical_devices("CPU"), "CPU")
12
+ tf.config.threading.set_intra_op_parallelism_threads(2)
13
+ tf.config.threading.set_inter_op_parallelism_threads(2)
14
 
15
  model = keras.models.load_model("emotion_detection_model.h5")
16
 
17
+ # Compile to a concrete TF function β€” eliminates re-tracing on every call
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: force graph compilation before any real frame arrives
23
+ fast_predict(tf.zeros([1, 48, 48, 1], dtype=tf.float32))
24
+
25
+ # ═══════════════════════════════════════════════════════════════════
26
+ # CONSTANTS
27
+ # ═══════════════════════════════════════════════════════════════════
28
+ LABELS = {0: "Angry", 1: "Happy", 2: "Neutral", 3: "Sad", 4: "Surprised"}
 
29
 
30
+ # BGR colors per emotion
31
  COLORS = {
32
  "Angry": (0, 0, 255),
33
+ "Happy": (0, 200, 0),
34
+ "Neutral": (200, 200, 0),
35
+ "Sad": (255, 100, 0),
36
+ "Surprised": (0, 140, 255),
37
  }
38
 
39
+ FONT = cv2.FONT_HERSHEY_SIMPLEX
40
+ FONT_SCALE = 0.65
41
+ THICKNESS = 2
42
+
43
+ # ═══════════════════════════════════════════════════════════════════
44
+ # FACE DETECTOR β€” one instance, reused forever
45
+ # ═══════════════════════════════════════════════════════════════════
46
+ detector = cv2.CascadeClassifier(
47
  cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
48
  )
49
 
50
+ # Latest annotated frame cache for download
51
+ _cache = {"frame": None}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
 
 
 
 
 
53
 
54
+ # ═══════════════════════════════════════════════════════════════════
55
+ # CORE HELPERS
56
+ # ═══════════════════════════════════════════════════════════════════
57
+ def _preprocess(bgr_frame, max_width=640):
58
+ """Resize if too large, convert to grayscale + histogram equalise."""
59
+ h, w = bgr_frame.shape[:2]
60
+ if w > max_width:
61
+ bgr_frame = cv2.resize(
62
+ bgr_frame, (max_width, int(h * max_width / w)),
63
+ interpolation=cv2.INTER_AREA
64
+ )
65
+ gray = cv2.cvtColor(bgr_frame, cv2.COLOR_BGR2GRAY)
66
  gray = cv2.equalizeHist(gray)
67
+ return bgr_frame, gray
68
+
69
 
70
+ def _detect_faces(gray):
71
+ """Run Haar Cascade β€” returns list of (x,y,w,h) or empty."""
72
+ return detector.detectMultiScale(
73
  gray,
74
  scaleFactor=1.3,
75
  minNeighbors=5,
 
77
  flags=cv2.CASCADE_SCALE_IMAGE
78
  )
79
 
80
+
81
+ def _predict_batch(gray, faces):
82
+ """
83
+ Crop every face ROI, stack into one batch, run a single
84
+ fast_predict() call. Returns list of (emotion, confidence).
85
+ """
86
+ rois = []
87
+ for (x, y, w, h) in faces:
88
+ roi = cv2.resize(gray[y:y+h, x:x+w], (48, 48))
89
+ rois.append(roi.astype(np.float32) / 255.0)
90
+
91
+ batch = tf.constant(
92
+ np.array(rois).reshape(-1, 48, 48, 1), dtype=tf.float32
93
+ )
94
+ preds = fast_predict(batch).numpy()
95
+
96
+ results = []
97
+ for p in preds:
98
+ idx = int(np.argmax(p))
99
+ results.append((LABELS[idx], float(p[idx]) * 100))
100
+ return results
101
+
102
+
103
+ def _draw(bgr, faces, predictions):
104
+ """Draw bounding boxes + labels onto bgr in-place."""
105
+ for (x, y, w, h), (emotion, conf) in zip(faces, predictions):
106
+ color = COLORS[emotion]
107
+ cv2.rectangle(bgr, (x, y), (x+w, y+h), color, 2)
108
+
109
+ label = f"{emotion} {conf:.1f}%"
110
+ (tw, th), bl = cv2.getTextSize(label, FONT, FONT_SCALE, THICKNESS)
111
+ ly = max(y - 6, th + 6)
112
+
113
+ # Filled pill background
114
+ cv2.rectangle(bgr,
115
+ (x, ly - th - bl - 4),
116
+ (x + tw + 6, ly + bl - 2),
117
+ color, -1)
118
+ cv2.putText(bgr, label, (x + 3, ly - bl),
119
+ FONT, FONT_SCALE, (0, 0, 0), THICKNESS, cv2.LINE_AA)
120
+ return bgr
121
+
122
+
123
+ def _run_pipeline(rgb_frame, max_width=640):
124
+ """
125
+ Full pipeline: preprocess β†’ detect β†’ predict β†’ draw β†’ cache.
126
+ Input/output: RGB numpy array (Gradio format).
127
+ """
128
+ bgr = cv2.cvtColor(rgb_frame, cv2.COLOR_RGB2BGR)
129
+ bgr, gray = _preprocess(bgr, max_width)
130
+ faces = _detect_faces(gray)
131
+
132
  if len(faces) == 0:
133
+ cv2.putText(bgr, "No face detected", (16, 36),
134
+ FONT, 0.8, (0, 0, 255), 2, cv2.LINE_AA)
135
  else:
136
+ predictions = _predict_batch(gray, faces)
137
+ _draw(bgr, faces, predictions)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
 
139
+ result = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
140
+ _cache["frame"] = result
141
  return result
142
 
143
 
144
+ # ═══════════════════════════════════════════════════════════════════
145
+ # GRADIO HANDLER FUNCTIONS
146
+ # ═══════════════════════════════════════════════════════════════════
147
+ def live_detect(frame):
148
+ """Called on every webcam frame (streaming)."""
149
+ if frame is None:
150
+ return None
151
+ return _run_pipeline(frame, max_width=480) # smaller = faster for live
152
+
153
+
154
+ def image_detect(image):
155
+ """Called when user uploads a static image."""
156
+ if image is None:
157
+ return None
158
+ return _run_pipeline(image, max_width=1280) # larger ok β€” not real-time
159
+
160
+
161
  def save_snapshot():
162
+ """Saves the cached annotated frame as PNG and returns path."""
163
+ frame = _cache.get("frame")
164
  if frame is None:
165
  return None
166
  tmp = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
 
169
  return tmp.name
170
 
171
 
172
+ # ═══════════════════════════════════════════════════════════════════
173
+ # GRADIO UI
174
+ # ═══════════════════════════════════════════════════════════════════
175
+ CSS = """
176
+ #title { text-align: center; }
177
+ #tagline { text-align: center; color: #888; margin-top: -12px; }
178
+ """
179
 
180
+ with gr.Blocks(title="Real-Time Emotion Detection", css=CSS) as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
 
182
+ gr.Markdown("# 😊 Real-Time Emotion Detection", elem_id="title")
183
+ gr.Markdown(
184
+ "😠 Angry  Β·  πŸ˜„ Happy  Β·  😐 Neutral "
185
+ " Β·  😒 Sad  Β·  😲 Surprised",
186
+ elem_id="tagline"
 
 
187
  )
188
 
189
+ with gr.Tabs():
190
+
191
+ # ── TAB 1 : LIVE WEBCAM ──────────────────────────────────
192
+ with gr.TabItem("πŸ“· Live Detection"):
193
+ gr.Markdown(
194
+ "Click **β–Ά Start** on the webcam to begin live detection. "
195
+ "Use **πŸ“₯ Download Snapshot** to save the current frame."
196
+ )
197
+ with gr.Row():
198
+ webcam = gr.Image(
199
+ sources=["webcam"], streaming=True,
200
+ label="πŸ“· Webcam Feed"
201
+ )
202
+ live_out = gr.Image(label="🎯 Live Result")
203
+
204
+ with gr.Row():
205
+ dl_live = gr.DownloadButton(
206
+ label="πŸ“₯ Download Snapshot", variant="primary"
207
+ )
208
+
209
+ # 10 fps β€” reliable on free CPU; no frame backlog
210
+ webcam.stream(
211
+ fn=live_detect,
212
+ inputs=webcam,
213
+ outputs=live_out,
214
+ stream_every=0.1,
215
+ time_limit=600
216
+ )
217
+ dl_live.click(fn=save_snapshot, inputs=None, outputs=dl_live)
218
+
219
+ # ── TAB 2 : IMAGE UPLOAD ─────────────────────────────────
220
+ with gr.TabItem("πŸ–ΌοΈ Image Upload"):
221
+ gr.Markdown(
222
+ "Upload any photo and click **πŸ” Detect Emotions** "
223
+ "to run static detection. Use **πŸ“₯ Download Result** to save."
224
+ )
225
+ with gr.Row():
226
+ upload_in = gr.Image(
227
+ sources=["upload"], type="numpy",
228
+ label="πŸ“‚ Upload Image"
229
+ )
230
+ upload_out = gr.Image(label="🎯 Detection Result")
231
+
232
+ with gr.Row():
233
+ detect_btn = gr.Button("πŸ” Detect Emotions", variant="primary")
234
+ dl_upload = gr.DownloadButton(
235
+ label="πŸ“₯ Download Result", variant="secondary"
236
+ )
237
+
238
+ detect_btn.click(
239
+ fn=image_detect,
240
+ inputs=upload_in,
241
+ outputs=upload_out
242
+ )
243
+ dl_upload.click(fn=save_snapshot, inputs=None, outputs=dl_upload)
244
 
245
  gr.Markdown("""
246
  ---
247
  **Model:** CNN β€” Conv2D(45) β†’ Conv2D(64) β†’ Conv2D(128) β†’ Dense(256) β†’ Softmax(5)  | 
248
+ **Input:** 48Γ—48 grayscale  |  **Detector:** OpenCV Haar Cascade
249
  """)
250
 
251
  if __name__ == "__main__":