Old app.py
Browse files
app.py
CHANGED
|
@@ -1,267 +1,174 @@
|
|
| 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 |
-
#
|
| 33 |
-
#
|
| 34 |
-
|
| 35 |
-
tf.config.
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
#
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
# ================================================================
|
| 53 |
-
LABELS = ["Angry", "Happy", "Neutral", "Sad", "Surprised"]
|
| 54 |
-
|
| 55 |
-
EMOJIS = {
|
| 56 |
-
"Angry": "π ",
|
| 57 |
-
"Happy": "π",
|
| 58 |
-
"Neutral": "π",
|
| 59 |
-
"Sad": "π’",
|
| 60 |
-
"Surprised": "π²"
|
| 61 |
}
|
| 62 |
|
| 63 |
-
|
|
|
|
| 64 |
"Angry": (0, 0, 255),
|
| 65 |
-
"Happy": (0, 200,
|
| 66 |
-
"Neutral": (200, 200,
|
| 67 |
-
"Sad": (255, 100,
|
| 68 |
-
"Surprised": (0,
|
| 69 |
}
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
# ================================================================
|
| 74 |
-
# FACE DETECTOR
|
| 75 |
-
# ================================================================
|
| 76 |
-
cascade = cv2.CascadeClassifier(
|
| 77 |
cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
|
| 78 |
)
|
| 79 |
|
| 80 |
-
#
|
| 81 |
-
|
| 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 |
-
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
-
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
)
|
| 99 |
|
| 100 |
if len(faces) == 0:
|
| 101 |
-
cv2.putText(
|
| 102 |
-
|
| 103 |
else:
|
| 104 |
-
#
|
| 105 |
-
|
|
|
|
| 106 |
for (x, y, w, h) in faces:
|
| 107 |
-
|
| 108 |
-
|
|
|
|
|
|
|
| 109 |
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
)
|
| 113 |
|
| 114 |
-
for i, (x, y, w, h) in enumerate(
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
color = COLORS[label]
|
| 119 |
-
text = f"{label} {EMOJIS[label]} ({conf:.1f}%)"
|
| 120 |
|
| 121 |
# Bounding box
|
| 122 |
-
cv2.rectangle(
|
| 123 |
-
|
| 124 |
-
#
|
| 125 |
-
|
| 126 |
-
cv2.
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
| 129 |
color, -1)
|
|
|
|
|
|
|
| 130 |
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
FONT, 0.9, (255, 255, 255), 2)
|
| 134 |
|
| 135 |
-
|
| 136 |
-
|
| 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
|
| 155 |
-
"""
|
| 156 |
-
|
|
|
|
| 157 |
return None
|
| 158 |
-
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
|
| 161 |
-
|
| 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 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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",
|
| 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,
|
| 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()
|