nirnit-13 commited on
Commit
53f483f
Β·
1 Parent(s): cbd5fd8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -235
app.py CHANGED
@@ -1,252 +1,116 @@
 
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
- # ═══════════════════════════════════════════════════════════════════
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,
76
- minSize=(40, 40),
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)
167
- tmp.close()
168
- cv2.imwrite(tmp.name, cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
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__":
252
  demo.launch()
 
1
+ import gradio as gr
2
  import cv2
3
  import numpy as np
 
 
 
4
  from tensorflow import keras
5
 
6
+ # Load model
7
+ model = keras.models.load_model('model/emotion_detection_model.h5')
 
 
 
 
 
 
 
 
 
 
 
8
 
9
+ # Load face detector
10
+ face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
11
 
12
+ # Emotion labels
13
+ EMOTION_LABELS = ["Angry", "Happy", "Neutral", "Sad", "Surprised"]
 
 
14
 
15
+ EMOTION_EMOJIS = {
16
+ "Angry": "😠",
17
+ "Happy": "😊",
18
+ "Neutral": "😐",
19
+ "Sad": "😒",
20
+ "Surprised": "😲"
 
21
  }
22
 
23
+ EMOTION_COLORS = {
24
+ "Angry": (0, 0, 255),
25
+ "Happy": (0, 200, 0),
26
+ "Neutral": (200, 200, 200),
27
+ "Sad": (255, 100, 0),
28
+ "Surprised": (0, 165, 255)
29
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ def predict_emotion(frame):
32
+ """Detect and predict emotion from webcam frame"""
33
+
34
  if frame is None:
35
  return None
36
+
37
+ # Convert RGB to BGR for OpenCV
38
+ img = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
39
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
40
+
41
+ # Detect faces
42
+ faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)
43
+
44
+ # Process each detected face
45
+ for (x, y, w, h) in faces:
46
+ # Extract face region
47
+ face = gray[y:y+h, x:x+w]
48
+
49
+ # Preprocess for model
50
+ face = cv2.resize(face, (48, 48))
51
+ face = face / 255.0
52
+ face = face.reshape(1, 48, 48, 1)
53
+
54
+ # Predict emotion
55
+ prediction = model.predict(face, verbose=0)
56
+ emotion_index = np.argmax(prediction)
57
+ emotion = EMOTION_LABELS[emotion_index]
58
+ confidence = prediction[0][emotion_index] * 100
59
+
60
+ # Draw bounding box
61
+ color = EMOTION_COLORS[emotion]
62
+ cv2.rectangle(img, (x, y), (x+w, y+h), color, 3)
63
+
64
+ # Create label
65
+ label = f"{emotion} {EMOTION_EMOJIS[emotion]} ({confidence:.1f}%)"
66
+
67
+ # Draw text background
68
+ (text_width, text_height), _ = cv2.getTextSize(
69
+ label, cv2.FONT_HERSHEY_SIMPLEX, 0.9, 2
70
+ )
71
+ cv2.rectangle(
72
+ img,
73
+ (x, y - text_height - 10),
74
+ (x + text_width + 10, y),
75
+ color,
76
+ -1
77
+ )
78
+
79
+ # Draw text
80
+ cv2.putText(
81
+ img, label,
82
+ (x + 5, y - 5),
83
+ cv2.FONT_HERSHEY_SIMPLEX,
84
+ 0.9,
85
+ (255, 255, 255),
86
+ 2
87
+ )
88
+
89
+ # Convert back to RGB for Gradio
90
+ return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
91
+
92
+
93
+ # Create Gradio interface
94
+ with gr.Blocks(title="Emotion Detection") as demo:
95
+ gr.Markdown("# 😊 Real-Time Emotion Detection 🎭")
96
+ gr.Markdown("**Powered by Deep Learning & Computer Vision**")
97
+
98
+ with gr.Row():
99
+ with gr.Column():
100
+ input_image = gr.Image(sources=["webcam"], streaming=True, label="Webcam Input", height=480)
101
+ with gr.Column():
102
+ output_image = gr.Image(label="Emotion Detection Output", height=480)
103
+
 
 
 
 
 
 
 
 
 
 
 
104
  gr.Markdown("""
105
+ **Detects 5 emotions:**
106
+ - 😠 Angry
107
+ - 😊 Happy
108
+ - 😐 Neutral
109
+ - 😒 Sad
110
+ - 😲 Surprised
111
  """)
112
+
113
+ input_image.stream(predict_emotion, inputs=input_image, outputs=output_image)
114
 
115
  if __name__ == "__main__":
116
  demo.launch()