Final: clean working app - all errors fixed
Browse files
app.py
CHANGED
|
@@ -1,47 +1,58 @@
|
|
| 1 |
-
#
|
| 2 |
-
#
|
| 3 |
-
#
|
| 4 |
-
#
|
| 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 |
-
|
| 10 |
-
|
| 11 |
-
def _safe_getattr_static(obj, attr, default=None):
|
| 12 |
try:
|
| 13 |
-
return
|
| 14 |
except TypeError:
|
| 15 |
return default
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
#
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
tf.config.threading.set_intra_op_parallelism_threads(2)
|
| 31 |
tf.config.threading.set_inter_op_parallelism_threads(2)
|
| 32 |
|
| 33 |
-
#
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
| 37 |
model.predict(np.zeros((1, 48, 48, 1), dtype=np.float32), verbose=0)
|
| 38 |
|
| 39 |
-
#
|
| 40 |
# CONSTANTS
|
| 41 |
-
#
|
| 42 |
-
|
| 43 |
|
| 44 |
-
|
| 45 |
"Angry": "π ",
|
| 46 |
"Happy": "π",
|
| 47 |
"Neutral": "π",
|
|
@@ -49,7 +60,7 @@ EMOTION_EMOJIS = {
|
|
| 49 |
"Surprised": "π²"
|
| 50 |
}
|
| 51 |
|
| 52 |
-
|
| 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
|
| 61 |
-
THICKNESS = 2
|
| 62 |
|
| 63 |
-
#
|
| 64 |
# FACE DETECTOR
|
| 65 |
-
#
|
| 66 |
-
|
| 67 |
cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
|
| 68 |
)
|
| 69 |
|
| 70 |
-
#
|
| 71 |
_cache = {"frame": None}
|
| 72 |
|
| 73 |
-
|
| 74 |
-
#
|
| 75 |
-
#
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 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 =
|
| 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),
|
| 101 |
else:
|
| 102 |
-
#
|
| 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 |
-
|
| 109 |
-
np.array(rois),
|
| 110 |
)
|
| 111 |
|
| 112 |
for i, (x, y, w, h) in enumerate(faces):
|
| 113 |
-
idx
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
color
|
|
|
|
| 117 |
|
| 118 |
# Bounding box
|
| 119 |
cv2.rectangle(img, (x, y), (x+w, y+h), color, 3)
|
| 120 |
|
| 121 |
-
#
|
| 122 |
-
|
| 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,
|
| 133 |
-
FONT, 0.9, (255, 255, 255),
|
| 134 |
|
| 135 |
-
out
|
| 136 |
_cache["frame"] = out
|
| 137 |
return out
|
| 138 |
|
| 139 |
-
|
| 140 |
-
#
|
| 141 |
-
#
|
| 142 |
-
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 143 |
def live_detect(frame):
|
| 144 |
"""
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
"""
|
| 150 |
if frame is None:
|
| 151 |
return None, None
|
| 152 |
-
return frame, _process(frame,
|
| 153 |
|
| 154 |
|
| 155 |
-
def image_detect(
|
| 156 |
-
"""
|
| 157 |
-
if
|
| 158 |
return None
|
| 159 |
-
return _process(
|
| 160 |
|
| 161 |
|
| 162 |
-
def
|
| 163 |
-
"""Saves latest annotated frame as PNG
|
| 164 |
frame = _cache.get("frame")
|
| 165 |
if frame is None:
|
| 166 |
return None
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
cv2.imwrite(
|
| 170 |
-
return
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
#
|
| 174 |
-
#
|
| 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(
|
| 184 |
-
|
| 185 |
-
|
|
|
|
|
|
|
| 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** =
|
| 194 |
-
"**Right** = live detection output
|
| 195 |
-
"Both
|
| 196 |
)
|
|
|
|
| 197 |
with gr.Row():
|
| 198 |
-
|
| 199 |
-
sources=["webcam"],
|
| 200 |
-
|
|
|
|
|
|
|
| 201 |
)
|
| 202 |
-
|
| 203 |
-
label="π― Live Detection Output",
|
|
|
|
| 204 |
)
|
| 205 |
|
| 206 |
gr.Markdown(
|
| 207 |
-
"π Angry Β· π Happy Β· "
|
| 208 |
-
"π Neutral Β· π’ Sad Β· π² Surprised"
|
| 209 |
)
|
| 210 |
|
| 211 |
with gr.Row():
|
| 212 |
-
|
| 213 |
-
|
| 214 |
)
|
| 215 |
|
| 216 |
-
|
| 217 |
-
input_image.stream(
|
| 218 |
fn=live_detect,
|
| 219 |
-
inputs=
|
| 220 |
-
outputs=[
|
| 221 |
stream_every=0.1,
|
| 222 |
time_limit=600
|
| 223 |
)
|
| 224 |
-
|
| 225 |
|
| 226 |
# ββ TAB 2 : IMAGE UPLOAD βββββββββββββββββββββββββββββββββ
|
| 227 |
with gr.TabItem("πΌοΈ Image Upload"):
|
|
|
|
| 228 |
gr.Markdown(
|
| 229 |
-
"Upload
|
| 230 |
-
"
|
| 231 |
)
|
|
|
|
| 232 |
with gr.Row():
|
| 233 |
-
|
| 234 |
-
sources=["upload"],
|
| 235 |
-
|
|
|
|
|
|
|
| 236 |
)
|
| 237 |
-
|
| 238 |
-
label="π― Detection Result",
|
|
|
|
| 239 |
)
|
| 240 |
|
| 241 |
gr.Markdown(
|
| 242 |
-
"π Angry Β· π Happy Β· "
|
| 243 |
-
"π Neutral Β· π’ Sad Β· π² Surprised"
|
| 244 |
)
|
| 245 |
|
| 246 |
with gr.Row():
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
)
|
| 251 |
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
)
|
| 255 |
-
dl_upload.click(fn=save_snapshot, inputs=None, outputs=dl_upload)
|
| 256 |
|
| 257 |
-
gr.Markdown(
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
|
|
|
|
|
|
| 262 |
|
| 263 |
-
|
| 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 Β· "
|
| 189 |
+
"**Left** = raw live feed Β· "
|
| 190 |
+
"**Right** = live detection output Β· "
|
| 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 Β· π Happy Β· "
|
| 208 |
+
"π Neutral Β· π’ Sad Β· π² 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 Β· π Happy Β· "
|
| 247 |
+
"π Neutral Β· π’ Sad Β· π² 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) | "
|
| 262 |
+
"<b>Input:</b> 48Γ48 grayscale | "
|
| 263 |
+
"<b>Detector:</b> OpenCV Haar Cascade"
|
| 264 |
+
"</center>"
|
| 265 |
+
)
|
| 266 |
|
| 267 |
+
demo.launch(ssr_mode=False)
|
|
|