nirnit-13 commited on
Commit
3ab193f
Β·
1 Parent(s): c44362f

Final: clean working app - all errors fixed

Browse files
Files changed (1) hide show
  1. app.py +147 -144
app.py CHANGED
@@ -1,47 +1,58 @@
1
- # ── Patch inspect.getattr_static FIRST β€” before any other import ──
2
- # HF Spaces reloader (codefind) calls getattr_static() on every
3
- # Python object. Keras/TF objects have a C-backed _DictWrapper as
4
- # their __dict__, which Python 3.13's stricter inspect crashes on.
5
- # This monkey-patch wraps the crash in a try/except so it silently
6
- # continues instead of killing the reloader thread.
7
  import inspect as _inspect
8
-
9
- _orig_getattr_static = _inspect.getattr_static
10
-
11
- def _safe_getattr_static(obj, attr, default=None):
12
  try:
13
- return _orig_getattr_static(obj, attr, default)
14
  except TypeError:
15
  return default
16
-
17
- _inspect.getattr_static = _safe_getattr_static
18
-
19
- # ── Now safe to import everything else ────────────────────────────
20
- import os
 
 
 
 
 
 
 
 
21
  import cv2
22
  import numpy as np
23
  import gradio as gr
24
  import tempfile
25
-
26
- os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" # suppress TF boot logs
27
-
28
  import tensorflow as tf
29
- tf.config.set_visible_devices(tf.config.list_physical_devices("CPU"), "CPU")
 
 
 
 
 
 
 
30
  tf.config.threading.set_intra_op_parallelism_threads(2)
31
  tf.config.threading.set_inter_op_parallelism_threads(2)
32
 
33
- # Load model with compile=False to avoid _DictWrapper optimiser objects
34
- model = tf.keras.models.load_model("emotion_detection_model.h5", compile=False)
35
-
36
- # Warm-up: run one dummy inference so TF builds its compute graph now
 
 
 
37
  model.predict(np.zeros((1, 48, 48, 1), dtype=np.float32), verbose=0)
38
 
39
- # ═══════════════════════════════════════════════════════════════════
40
  # CONSTANTS
41
- # ═══════════════════════════════════════════════════════════════════
42
- EMOTION_LABELS = ["Angry", "Happy", "Neutral", "Sad", "Surprised"]
43
 
44
- EMOTION_EMOJIS = {
45
  "Angry": "😠",
46
  "Happy": "😊",
47
  "Neutral": "😐",
@@ -49,7 +60,7 @@ EMOTION_EMOJIS = {
49
  "Surprised": "😲"
50
  }
51
 
52
- EMOTION_COLORS = {
53
  "Angry": (0, 0, 255),
54
  "Happy": (0, 200, 0),
55
  "Neutral": (200, 200, 200),
@@ -57,208 +68,200 @@ EMOTION_COLORS = {
57
  "Surprised": (0, 165, 255)
58
  }
59
 
60
- FONT = cv2.FONT_HERSHEY_SIMPLEX
61
- THICKNESS = 2
62
 
63
- # ═══════════════════════════════════════════════════════════════════
64
  # FACE DETECTOR
65
- # ═══════════════════════════════════════════════════════════════════
66
- face_cascade = cv2.CascadeClassifier(
67
  cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
68
  )
69
 
70
- # Cache latest annotated frame for download
71
  _cache = {"frame": None}
72
 
73
-
74
- # ══════════════════════��════════════════════════════════════════════
75
- # CORE PIPELINE
76
- # ═══════════════════════════════════════════════════════════════════
77
- def _process(rgb_frame, max_width):
78
- """
79
- Mirrors Detection.ipynb loop:
80
- read frame β†’ gray β†’ detectMultiScale β†’
81
- per-face: resize / normalise / predict β†’ draw β†’ return annotated
82
- """
83
- h, w = rgb_frame.shape[:2]
84
- if w > max_width:
85
- rgb_frame = cv2.resize(
86
- rgb_frame,
87
- (max_width, int(h * max_width / w)),
88
- interpolation=cv2.INTER_AREA
89
- )
90
-
91
- img = cv2.cvtColor(rgb_frame, cv2.COLOR_RGB2BGR)
92
  gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
93
 
94
- faces = face_cascade.detectMultiScale(
95
  gray, scaleFactor=1.3, minNeighbors=5
96
  )
97
 
98
  if len(faces) == 0:
99
  cv2.putText(img, "No face detected", (16, 40),
100
- FONT, 0.9, (0, 0, 255), THICKNESS, cv2.LINE_AA)
101
  else:
102
- # Batch all faces β†’ single model.predict() call
103
  rois = []
104
  for (x, y, w, h) in faces:
105
  face = cv2.resize(gray[y:y+h, x:x+w], (48, 48))
106
  rois.append((face / 255.0).reshape(48, 48, 1).astype(np.float32))
107
 
108
- predictions = model.predict(
109
- np.array(rois), verbose=0, batch_size=len(rois)
110
  )
111
 
112
  for i, (x, y, w, h) in enumerate(faces):
113
- idx = int(np.argmax(predictions[i]))
114
- emotion = EMOTION_LABELS[idx]
115
- confidence = float(predictions[i][idx]) * 100
116
- color = EMOTION_COLORS[emotion]
 
117
 
118
  # Bounding box
119
  cv2.rectangle(img, (x, y), (x+w, y+h), color, 3)
120
 
121
- # Label: "Happy 😊 (97.2%)"
122
- label = f"{emotion} {EMOTION_EMOJIS[emotion]} ({confidence:.1f}%)"
123
- (tw, th), _ = cv2.getTextSize(label, FONT, 0.9, THICKNESS)
124
-
125
- # Filled background
126
  cv2.rectangle(img,
127
  (x, y - th - 10),
128
  (x + tw + 10, y),
129
  color, -1)
130
 
131
  # White text
132
- cv2.putText(img, label, (x + 5, y - 5),
133
- FONT, 0.9, (255, 255, 255), THICKNESS)
134
 
135
- out = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
136
  _cache["frame"] = out
137
  return out
138
 
139
-
140
- # ═══════════════════════════════════════════════════════════════════
141
- # GRADIO HANDLERS
142
- # ═══════════════════════════════════════════════════════════════════
143
  def live_detect(frame):
144
  """
145
- Returns (raw_frame, annotated_frame):
146
- β€’ input panel ← raw frame (live webcam keeps moving)
147
- β€’ output panel ← annotated (detections drawn on same frame)
148
- Both panels are fully live β€” mirrors cv2.imshow() from notebook.
149
  """
150
  if frame is None:
151
  return None, None
152
- return frame, _process(frame, max_width=480)
153
 
154
 
155
- def image_detect(image):
156
- """Static upload β€” full resolution."""
157
- if image is None:
158
  return None
159
- return _process(image, max_width=1280)
160
 
161
 
162
- def save_snapshot():
163
- """Saves latest annotated frame as PNG, returns path for download."""
164
  frame = _cache.get("frame")
165
  if frame is None:
166
  return None
167
- tmp = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
168
- tmp.close()
169
- cv2.imwrite(tmp.name, cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
170
- return tmp.name
171
-
172
-
173
- # ═══════════════════════════════════════════════════════════════════
174
- # GRADIO UI
175
- # ═══════════════════════════════════════════════════════════════════
176
- CSS = """
177
- #title { text-align: center; }
178
- #tagline { text-align: center; color: #888; margin-top: -10px; }
179
- """
180
-
181
  with gr.Blocks(title="Real-Time Emotion Detection") as demo:
182
 
183
- gr.Markdown("# 😊 Real-Time Emotion Detection 🎭", elem_id="title")
184
- gr.Markdown("**Powered by Deep Learning & Computer Vision**",
185
- elem_id="tagline")
 
 
186
 
187
  with gr.Tabs():
188
 
189
  # ── TAB 1 : LIVE WEBCAM ──────────────────────────────────
190
  with gr.TabItem("πŸ“· Live Detection"):
 
191
  gr.Markdown(
192
- "Click **β–Ά Start** on the webcam. "
193
- "**Left** = live raw feed  Β·  "
194
- "**Right** = live detection output. "
195
- "Both panels update in real time."
196
  )
 
197
  with gr.Row():
198
- input_image = gr.Image(
199
- sources=["webcam"], streaming=True,
200
- label="πŸ“· Live Input", height=480
 
 
201
  )
202
- output_image = gr.Image(
203
- label="🎯 Live Detection Output", height=480
 
204
  )
205
 
206
  gr.Markdown(
207
- "😠 Angry  Β·  😊 Happy  Β·  "
208
- "😐 Neutral  Β·  😒 Sad  Β·  😲 Surprised"
209
  )
210
 
211
  with gr.Row():
212
- dl_live = gr.DownloadButton(
213
- label="πŸ“₯ Download Snapshot", variant="primary"
214
  )
215
 
216
- # Both panels fed from same stream tick
217
- input_image.stream(
218
  fn=live_detect,
219
- inputs=input_image,
220
- outputs=[input_image, output_image],
221
  stream_every=0.1,
222
  time_limit=600
223
  )
224
- dl_live.click(fn=save_snapshot, inputs=None, outputs=dl_live)
225
 
226
  # ── TAB 2 : IMAGE UPLOAD ─────────────────────────────────
227
  with gr.TabItem("πŸ–ΌοΈ Image Upload"):
 
228
  gr.Markdown(
229
- "Upload any photo and click **πŸ” Detect Emotions**. "
230
- "Use **πŸ“₯ Download Result** to save the annotated image."
231
  )
 
232
  with gr.Row():
233
- upload_in = gr.Image(
234
- sources=["upload"], type="numpy",
235
- label="πŸ“‚ Upload Image", height=480
 
 
236
  )
237
- upload_out = gr.Image(
238
- label="🎯 Detection Result", height=480
 
239
  )
240
 
241
  gr.Markdown(
242
- "😠 Angry  Β·  😊 Happy  Β·  "
243
- "😐 Neutral  Β·  😒 Sad  Β·  😲 Surprised"
244
  )
245
 
246
  with gr.Row():
247
- detect_btn = gr.Button("πŸ” Detect Emotions", variant="primary")
248
- dl_upload = gr.DownloadButton(
249
- label="πŸ“₯ Download Result", variant="secondary"
250
  )
251
 
252
- detect_btn.click(
253
- fn=image_detect, inputs=upload_in, outputs=upload_out
254
- )
255
- dl_upload.click(fn=save_snapshot, inputs=None, outputs=dl_upload)
256
 
257
- gr.Markdown("""
258
- ---
259
- **Model:** CNN β€” Conv2D(45) β†’ Conv2D(64) β†’ Conv2D(128) β†’ Dense(256) β†’ Softmax(5)  | 
260
- **Input:** 48Γ—48 grayscale  |  **Detector:** OpenCV Haar Cascade
261
- """)
 
 
262
 
263
- if __name__ == "__main__":
264
- demo.launch(css=CSS, ssr_mode=False)
 
1
+ # ================================================================
2
+ # PATCH inspect BEFORE EVERYTHING β€” fixes HF Spaces reloader crash
3
+ # caused by TF/Keras _DictWrapper objects on Python 3.13
4
+ # ================================================================
 
 
5
  import inspect as _inspect
6
+ _orig = _inspect.getattr_static
7
+ def _safe(obj, attr, default=None):
 
 
8
  try:
9
+ return _orig(obj, attr, default)
10
  except TypeError:
11
  return default
12
+ _inspect.getattr_static = _safe
13
+
14
+ # ================================================================
15
+ # SUPPRESS ALL NOISY LOGS
16
+ # ================================================================
17
+ import os, warnings
18
+ os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
19
+ os.environ["PYTHONWARNINGS"] = "ignore"
20
+ warnings.filterwarnings("ignore")
21
+
22
+ # ================================================================
23
+ # IMPORTS
24
+ # ================================================================
25
  import cv2
26
  import numpy as np
27
  import gradio as gr
28
  import tempfile
 
 
 
29
  import tensorflow as tf
30
+
31
+ # ================================================================
32
+ # TF CONFIGURATION
33
+ # ================================================================
34
+ tf.get_logger().setLevel("ERROR")
35
+ tf.config.set_visible_devices(
36
+ tf.config.list_physical_devices("CPU"), "CPU"
37
+ )
38
  tf.config.threading.set_intra_op_parallelism_threads(2)
39
  tf.config.threading.set_inter_op_parallelism_threads(2)
40
 
41
+ # ================================================================
42
+ # MODEL β€” compile=False avoids _DictWrapper optimizer objects
43
+ # ================================================================
44
+ model = tf.keras.models.load_model(
45
+ "emotion_detection_model.h5", compile=False
46
+ )
47
+ # Warm-up: forces TF to build compute graph NOW, not on first frame
48
  model.predict(np.zeros((1, 48, 48, 1), dtype=np.float32), verbose=0)
49
 
50
+ # ================================================================
51
  # CONSTANTS
52
+ # ================================================================
53
+ LABELS = ["Angry", "Happy", "Neutral", "Sad", "Surprised"]
54
 
55
+ EMOJIS = {
56
  "Angry": "😠",
57
  "Happy": "😊",
58
  "Neutral": "😐",
 
60
  "Surprised": "😲"
61
  }
62
 
63
+ COLORS = { # BGR
64
  "Angry": (0, 0, 255),
65
  "Happy": (0, 200, 0),
66
  "Neutral": (200, 200, 200),
 
68
  "Surprised": (0, 165, 255)
69
  }
70
 
71
+ FONT = cv2.FONT_HERSHEY_SIMPLEX
 
72
 
73
+ # ================================================================
74
  # FACE DETECTOR
75
+ # ================================================================
76
+ cascade = cv2.CascadeClassifier(
77
  cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
78
  )
79
 
80
+ # Shared cache for download button
81
  _cache = {"frame": None}
82
 
83
+ # ================================================================
84
+ # CORE DETECTION PIPELINE
85
+ # ================================================================
86
+ def _process(rgb, max_w):
87
+ # Resize for speed if needed
88
+ h, w = rgb.shape[:2]
89
+ if w > max_w:
90
+ rgb = cv2.resize(rgb, (max_w, int(h * max_w / w)),
91
+ interpolation=cv2.INTER_AREA)
92
+
93
+ img = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)
 
 
 
 
 
 
 
 
94
  gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
95
 
96
+ faces = cascade.detectMultiScale(
97
  gray, scaleFactor=1.3, minNeighbors=5
98
  )
99
 
100
  if len(faces) == 0:
101
  cv2.putText(img, "No face detected", (16, 40),
102
+ FONT, 0.9, (0, 0, 255), 2, cv2.LINE_AA)
103
  else:
104
+ # Build batch from all faces β†’ single predict call
105
  rois = []
106
  for (x, y, w, h) in faces:
107
  face = cv2.resize(gray[y:y+h, x:x+w], (48, 48))
108
  rois.append((face / 255.0).reshape(48, 48, 1).astype(np.float32))
109
 
110
+ preds = model.predict(
111
+ np.array(rois), batch_size=len(rois), verbose=0
112
  )
113
 
114
  for i, (x, y, w, h) in enumerate(faces):
115
+ idx = int(np.argmax(preds[i]))
116
+ label = LABELS[idx]
117
+ conf = float(preds[i][idx]) * 100
118
+ color = COLORS[label]
119
+ text = f"{label} {EMOJIS[label]} ({conf:.1f}%)"
120
 
121
  # Bounding box
122
  cv2.rectangle(img, (x, y), (x+w, y+h), color, 3)
123
 
124
+ # Filled label background
125
+ (tw, th), _ = cv2.getTextSize(text, FONT, 0.9, 2)
 
 
 
126
  cv2.rectangle(img,
127
  (x, y - th - 10),
128
  (x + tw + 10, y),
129
  color, -1)
130
 
131
  # White text
132
+ cv2.putText(img, text, (x + 5, y - 5),
133
+ FONT, 0.9, (255, 255, 255), 2)
134
 
135
+ out = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
136
  _cache["frame"] = out
137
  return out
138
 
139
+ # ================================================================
140
+ # GRADIO HANDLER FUNCTIONS
141
+ # ================================================================
 
142
  def live_detect(frame):
143
  """
144
+ Called on every stream tick.
145
+ Returns (raw, annotated) so BOTH panels update live:
146
+ left panel ← raw frame (always moving, never frozen)
147
+ right panel ← annotated frame (detections drawn on same frame)
148
  """
149
  if frame is None:
150
  return None, None
151
+ return frame, _process(frame, max_w=480)
152
 
153
 
154
+ def image_detect(img):
155
+ """Called when user uploads a static image."""
156
+ if img is None:
157
  return None
158
+ return _process(img, max_w=1280)
159
 
160
 
161
+ def download_snapshot():
162
+ """Saves latest annotated frame as PNG and returns file path."""
163
  frame = _cache.get("frame")
164
  if frame is None:
165
  return None
166
+ f = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
167
+ f.close()
168
+ cv2.imwrite(f.name, cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
169
+ return f.name
170
+
171
+ # ================================================================
172
+ # UI
173
+ # ================================================================
 
 
 
 
 
 
174
  with gr.Blocks(title="Real-Time Emotion Detection") as demo:
175
 
176
+ gr.Markdown(
177
+ "<h1 style='text-align:center'>😊 Real-Time Emotion Detection 🎭</h1>"
178
+ "<p style='text-align:center;color:gray;margin-top:-10px'>"
179
+ "<b>Powered by Deep Learning & Computer Vision</b></p>"
180
+ )
181
 
182
  with gr.Tabs():
183
 
184
  # ── TAB 1 : LIVE WEBCAM ──────────────────────────────────
185
  with gr.TabItem("πŸ“· Live Detection"):
186
+
187
  gr.Markdown(
188
+ "Click **β–Ά Start** on the webcam &nbsp;Β·&nbsp; "
189
+ "**Left** = raw live feed &nbsp;Β·&nbsp; "
190
+ "**Right** = live detection output &nbsp;Β·&nbsp; "
191
+ "Both update in real time"
192
  )
193
+
194
  with gr.Row():
195
+ inp = gr.Image(
196
+ sources=["webcam"],
197
+ streaming=True,
198
+ label="πŸ“· Live Input",
199
+ height=480
200
  )
201
+ out = gr.Image(
202
+ label="🎯 Live Detection Output",
203
+ height=480
204
  )
205
 
206
  gr.Markdown(
207
+ "<center>😠 Angry &nbsp;·&nbsp; 😊 Happy &nbsp;·&nbsp; "
208
+ "😐 Neutral &nbsp;·&nbsp; 😒 Sad &nbsp;·&nbsp; 😲 Surprised</center>"
209
  )
210
 
211
  with gr.Row():
212
+ dl_btn = gr.DownloadButton(
213
+ "πŸ“₯ Download Snapshot", variant="primary"
214
  )
215
 
216
+ inp.stream(
 
217
  fn=live_detect,
218
+ inputs=inp,
219
+ outputs=[inp, out],
220
  stream_every=0.1,
221
  time_limit=600
222
  )
223
+ dl_btn.click(fn=download_snapshot, inputs=None, outputs=dl_btn)
224
 
225
  # ── TAB 2 : IMAGE UPLOAD ─────────────────────────────────
226
  with gr.TabItem("πŸ–ΌοΈ Image Upload"):
227
+
228
  gr.Markdown(
229
+ "Upload a photo β†’ click **πŸ” Detect Emotions** β†’ "
230
+ "save with **πŸ“₯ Download Result**"
231
  )
232
+
233
  with gr.Row():
234
+ up_in = gr.Image(
235
+ sources=["upload"],
236
+ type="numpy",
237
+ label="πŸ“‚ Upload Image",
238
+ height=480
239
  )
240
+ up_out = gr.Image(
241
+ label="🎯 Detection Result",
242
+ height=480
243
  )
244
 
245
  gr.Markdown(
246
+ "<center>😠 Angry &nbsp;·&nbsp; 😊 Happy &nbsp;·&nbsp; "
247
+ "😐 Neutral &nbsp;·&nbsp; 😒 Sad &nbsp;·&nbsp; 😲 Surprised</center>"
248
  )
249
 
250
  with gr.Row():
251
+ det_btn = gr.Button("πŸ” Detect Emotions", variant="primary")
252
+ dl_up = gr.DownloadButton(
253
+ "πŸ“₯ Download Result", variant="secondary"
254
  )
255
 
256
+ det_btn.click(fn=image_detect, inputs=up_in, outputs=up_out)
257
+ dl_up.click(fn=download_snapshot, inputs=None, outputs=dl_up)
 
 
258
 
259
+ gr.Markdown(
260
+ "<hr><center>"
261
+ "<b>Model:</b> CNN β€” Conv2D(45)β†’Conv2D(64)β†’Conv2D(128)β†’Dense(256)β†’Softmax(5) &nbsp;|&nbsp; "
262
+ "<b>Input:</b> 48Γ—48 grayscale &nbsp;|&nbsp; "
263
+ "<b>Detector:</b> OpenCV Haar Cascade"
264
+ "</center>"
265
+ )
266
 
267
+ demo.launch(ssr_mode=False)