nirnit-13 commited on
Commit
9944c34
·
1 Parent(s): 88abe6a

Rewrite: fresh app.py — fix TF freeze, warm-up predict, batch inference, no threading

Browse files
Files changed (1) hide show
  1. app.py +102 -150
app.py CHANGED
@@ -1,16 +1,25 @@
1
  import cv2
2
  import numpy as np
3
  import gradio as gr
4
- import threading
5
  import tempfile
6
- import os
7
- from keras.models import load_model
8
 
9
- # ── Load model ────────────────────────────────────────────────────
10
- model = load_model("emotion_detection_model.h5")
 
 
 
11
 
12
- # Emotion labels
13
- emotion_labels = {
 
 
 
 
 
 
 
14
  0: "Angry",
15
  1: "Happy",
16
  2: "Neutral",
@@ -18,8 +27,8 @@ emotion_labels = {
18
  4: "Surprised"
19
  }
20
 
21
- # Emotion colors (BGR)
22
- emotion_colors = {
23
  "Angry": (0, 0, 255),
24
  "Happy": (0, 200, 0),
25
  "Neutral": (200, 200, 0),
@@ -32,191 +41,134 @@ face_cascade = cv2.CascadeClassifier(
32
  cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
33
  )
34
 
35
- # ── Shared state for background inference ─────────────────────────
36
- _lock = threading.Lock()
37
- _latest_result = {"faces": [], "emotions": []}
38
- _inference_busy = False
39
- _latest_snapshot = {"frame": None} # holds latest annotated frame for download
40
 
41
 
42
- def _run_inference(gray_frame):
 
43
  """
44
- Runs face detection + emotion prediction in a background thread.
45
- Writes results into _latest_result so the main stream can read them.
 
46
  """
47
- global _inference_busy, _latest_result
48
-
49
- faces = face_cascade.detectMultiScale(
50
- gray_frame,
51
- scaleFactor=1.2,
52
- minNeighbors=6,
53
- minSize=(60, 60)
54
- )
55
-
56
- results = []
57
- for (x, y, w, h) in faces:
58
- face_roi = gray_frame[y:y+h, x:x+w]
59
- face_roi = cv2.resize(face_roi, (48, 48))
60
- face_roi = face_roi / 255.0
61
- face_roi = face_roi.reshape(1, 48, 48, 1)
62
-
63
- prediction = model.predict(face_roi, verbose=0)
64
- emotion = emotion_labels[np.argmax(prediction)]
65
- confidence = float(np.max(prediction)) * 100
66
- results.append((x, y, w, h, emotion, confidence))
67
-
68
- with _lock:
69
- _latest_result = {"faces": results}
70
- _inference_busy = False
71
-
72
-
73
- def _annotate_frame(frame_bgr, results):
74
- """
75
- Draws bounding boxes and emotion labels onto the frame
76
- using the latest inference results.
77
- """
78
- if not results["faces"]:
79
- cv2.putText(
80
- frame_bgr, "No face detected", (20, 40),
81
- cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2, cv2.LINE_AA
82
- )
83
- return frame_bgr
84
-
85
- font = cv2.FONT_HERSHEY_SIMPLEX
86
- font_scale = 0.75
87
- thickness = 2
88
-
89
- for (x, y, w, h, emotion, confidence) in results["faces"]:
90
- color = emotion_colors[emotion]
91
-
92
- # Bounding box
93
- cv2.rectangle(frame_bgr, (x, y), (x+w, y+h), color, 2)
94
-
95
- # Label
96
- label = f"{emotion} {confidence:.1f}%"
97
- (tw, th), baseline = cv2.getTextSize(label, font, font_scale, thickness)
98
- label_y = max(y - 10, th + 10)
99
-
100
- # Filled background
101
- cv2.rectangle(
102
- frame_bgr,
103
- (x, label_y - th - baseline - 4),
104
- (x + tw + 6, label_y + baseline - 4),
105
- color, -1
106
- )
107
- # Text
108
- cv2.putText(
109
- frame_bgr, label, (x + 3, label_y - baseline),
110
- font, font_scale, (0, 0, 0), thickness, cv2.LINE_AA
111
- )
112
-
113
- return frame_bgr
114
-
115
-
116
- def process_frame(frame):
117
- """
118
- Main streaming function called by Gradio on every frame.
119
-
120
- - Instantly returns the annotated frame using the LAST known inference
121
- result → webcam feed NEVER freezes or waits.
122
- - Fires a new background inference thread only when the previous one
123
- has finished → no overlapping predictions.
124
-
125
- Returns: (annotated_live_frame, snapshot_for_download)
126
- """
127
- global _inference_busy
128
-
129
  if frame is None:
130
- return None, None
131
-
132
- # Convert RGB (Gradio) → BGR (OpenCV)
133
- frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
134
- gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY)
135
- gray = cv2.equalizeHist(gray)
136
 
137
- # Fire inference in background only if not already running
138
- with _lock:
139
- busy = _inference_busy
140
- if not busy:
141
- with _lock:
142
- _inference_busy = True
143
- t = threading.Thread(target=_run_inference, args=(gray.copy(),), daemon=True)
144
- t.start()
145
 
146
- # Annotate current frame with LATEST available result (non-blocking)
147
- with _lock:
148
- results = dict(_latest_result)
 
 
149
 
150
- annotated_bgr = _annotate_frame(frame_bgr.copy(), results)
151
- annotated_rgb = cv2.cvtColor(annotated_bgr, cv2.COLOR_BGR2RGB)
152
 
153
- # Store latest annotated frame so download button can access it
154
- with _lock:
155
- _latest_snapshot["frame"] = annotated_rgb.copy()
 
 
 
 
 
156
 
157
- return annotated_rgb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
 
159
 
160
- # ── Gradio UI ─────────────────────────────────────────────────────
161
  def save_snapshot():
162
- """Saves the latest annotated frame to a temp file and returns the path."""
163
- with _lock:
164
- frame = _latest_snapshot["frame"]
165
  if frame is None:
166
  return None
167
- # Save as PNG to a named temp file
168
  tmp = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
169
  tmp.close()
170
  cv2.imwrite(tmp.name, cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
171
  return tmp.name
172
 
173
 
 
174
  with gr.Blocks(title="Real-Time Emotion Detection") as demo:
175
 
176
  gr.Markdown("""
177
  # 😊 Real-Time Emotion Detection
178
- Click **▶ Start** on the webcam to begin live detection.
179
- Click **📥 Download Snapshot** to save the current detection as an image.
180
- Emotions detected: 😠 Angry  |  😄 Happy  |  😐 Neutral  |  😢 Sad  |  😲 Surprised
181
  """)
182
 
183
  with gr.Row():
184
- # Left — live webcam input (never frozen, always streaming)
185
- webcam = gr.Image(
186
- sources=["webcam"],
187
- streaming=True,
188
- label="📷 Live Webcam"
189
- )
190
- # Right — annotated output (updated every frame via bg inference)
191
- output_img = gr.Image(
192
- label="🎯 Detected Emotion"
193
- )
194
 
195
- # Download button — saves latest annotated frame as PNG
196
  with gr.Row():
197
  download_btn = gr.DownloadButton(
198
- label="📥 Download Snapshot",
199
- variant="primary"
200
  )
201
 
202
- # stream_every=0.04 → ~25 fps | inference in background → no freeze
203
  webcam.stream(
204
- fn=process_frame,
205
  inputs=webcam,
206
  outputs=output_img,
207
- stream_every=0.04,
208
  time_limit=600
209
  )
210
 
211
- # On click → save frame to temp file → trigger browser download
212
  download_btn.click(fn=save_snapshot, inputs=None, outputs=download_btn)
213
 
214
  gr.Markdown("""
215
  ---
216
- **Model:** Custom CNN — Conv2D(45) → Conv2D(64) → Conv2D(128) → Dense(256) → Softmax(5)
217
- **Input:** 48×48 grayscale face patch  |  **Face Detector:** OpenCV Haar Cascade
218
  """)
219
 
220
-
221
  if __name__ == "__main__":
222
  demo.launch()
 
1
  import cv2
2
  import numpy as np
3
  import gradio as gr
 
4
  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",
 
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),
 
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,
75
+ minSize=(40, 40),
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)
131
  tmp.close()
132
  cv2.imwrite(tmp.name, cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
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__":
174
  demo.launch()