Update app.py
Browse files
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 |
-
|
| 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 |
-
#
|
| 23 |
-
|
| 24 |
|
| 25 |
-
#
|
| 26 |
-
|
| 27 |
-
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 28 |
-
LABELS = {0: "Angry", 1: "Happy", 2: "Neutral", 3: "Sad", 4: "Surprised"}
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
"
|
| 33 |
-
"
|
| 34 |
-
"
|
| 35 |
-
"
|
| 36 |
-
"Surprised": (0, 140, 255),
|
| 37 |
}
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 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
|
| 162 |
-
"""
|
| 163 |
-
|
| 164 |
if frame is None:
|
| 165 |
return None
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
#
|
| 175 |
-
|
| 176 |
-
#
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 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 |
-
|
| 248 |
-
|
|
|
|
|
|
|
|
|
|
| 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()
|