Fix: patch inspect.getattr_static to handle TF _DictWrapper crash in HF reloader
Browse files
app.py
CHANGED
|
@@ -1,35 +1,40 @@
|
|
| 1 |
-
import
|
| 2 |
-
#
|
| 3 |
-
#
|
| 4 |
-
#
|
| 5 |
-
#
|
| 6 |
-
#
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
import cv2
|
| 11 |
import numpy as np
|
| 12 |
import gradio as gr
|
| 13 |
import tempfile
|
| 14 |
-
import numpy as np
|
| 15 |
|
| 16 |
-
|
|
|
|
| 17 |
import tensorflow as tf
|
| 18 |
tf.config.set_visible_devices(tf.config.list_physical_devices("CPU"), "CPU")
|
| 19 |
tf.config.threading.set_intra_op_parallelism_threads(2)
|
| 20 |
tf.config.threading.set_inter_op_parallelism_threads(2)
|
| 21 |
|
| 22 |
-
# Load with compile=False
|
| 23 |
-
|
| 24 |
-
model = tf.keras.models.load_model(
|
| 25 |
-
"emotion_detection_model.h5",
|
| 26 |
-
compile=False
|
| 27 |
-
)
|
| 28 |
-
model.compile() # re-compile cleanly with default settings
|
| 29 |
|
| 30 |
-
# Warm-up
|
| 31 |
-
|
| 32 |
-
model.predict(_dummy, verbose=0)
|
| 33 |
|
| 34 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 35 |
# CONSTANTS
|
|
@@ -73,7 +78,7 @@ def _process(rgb_frame, max_width):
|
|
| 73 |
"""
|
| 74 |
Mirrors Detection.ipynb loop:
|
| 75 |
read frame β gray β detectMultiScale β
|
| 76 |
-
per-face: resize/
|
| 77 |
"""
|
| 78 |
h, w = rgb_frame.shape[:2]
|
| 79 |
if w > max_width:
|
|
@@ -94,7 +99,7 @@ def _process(rgb_frame, max_width):
|
|
| 94 |
cv2.putText(img, "No face detected", (16, 40),
|
| 95 |
FONT, 0.9, (0, 0, 255), THICKNESS, cv2.LINE_AA)
|
| 96 |
else:
|
| 97 |
-
# Batch all faces
|
| 98 |
rois = []
|
| 99 |
for (x, y, w, h) in faces:
|
| 100 |
face = cv2.resize(gray[y:y+h, x:x+w], (48, 48))
|
|
@@ -110,13 +115,20 @@ def _process(rgb_frame, max_width):
|
|
| 110 |
confidence = float(predictions[i][idx]) * 100
|
| 111 |
color = EMOTION_COLORS[emotion]
|
| 112 |
|
|
|
|
| 113 |
cv2.rectangle(img, (x, y), (x+w, y+h), color, 3)
|
| 114 |
|
|
|
|
| 115 |
label = f"{emotion} {EMOTION_EMOJIS[emotion]} ({confidence:.1f}%)"
|
| 116 |
(tw, th), _ = cv2.getTextSize(label, FONT, 0.9, THICKNESS)
|
|
|
|
|
|
|
| 117 |
cv2.rectangle(img,
|
| 118 |
-
(x, y - th - 10),
|
|
|
|
| 119 |
color, -1)
|
|
|
|
|
|
|
| 120 |
cv2.putText(img, label, (x + 5, y - 5),
|
| 121 |
FONT, 0.9, (255, 255, 255), THICKNESS)
|
| 122 |
|
|
@@ -130,10 +142,10 @@ def _process(rgb_frame, max_width):
|
|
| 130 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 131 |
def live_detect(frame):
|
| 132 |
"""
|
| 133 |
-
Returns (raw_frame, annotated_frame)
|
| 134 |
-
β’ input
|
| 135 |
-
β’ output panel
|
| 136 |
-
Both panels
|
| 137 |
"""
|
| 138 |
if frame is None:
|
| 139 |
return None, None
|
|
@@ -141,14 +153,14 @@ def live_detect(frame):
|
|
| 141 |
|
| 142 |
|
| 143 |
def image_detect(image):
|
| 144 |
-
"""Static upload β full resolution
|
| 145 |
if image is None:
|
| 146 |
return None
|
| 147 |
return _process(image, max_width=1280)
|
| 148 |
|
| 149 |
|
| 150 |
def save_snapshot():
|
| 151 |
-
"""
|
| 152 |
frame = _cache.get("frame")
|
| 153 |
if frame is None:
|
| 154 |
return None
|
|
@@ -180,7 +192,7 @@ with gr.Blocks(title="Real-Time Emotion Detection", css=CSS) as demo:
|
|
| 180 |
"Click **βΆ Start** on the webcam. "
|
| 181 |
"**Left** = live raw feed Β· "
|
| 182 |
"**Right** = live detection output. "
|
| 183 |
-
"Both update in real time."
|
| 184 |
)
|
| 185 |
with gr.Row():
|
| 186 |
input_image = gr.Image(
|
|
@@ -201,6 +213,7 @@ with gr.Blocks(title="Real-Time Emotion Detection", css=CSS) as demo:
|
|
| 201 |
label="π₯ Download Snapshot", variant="primary"
|
| 202 |
)
|
| 203 |
|
|
|
|
| 204 |
input_image.stream(
|
| 205 |
fn=live_detect,
|
| 206 |
inputs=input_image,
|
|
@@ -214,7 +227,7 @@ with gr.Blocks(title="Real-Time Emotion Detection", css=CSS) as demo:
|
|
| 214 |
with gr.TabItem("πΌοΈ Image Upload"):
|
| 215 |
gr.Markdown(
|
| 216 |
"Upload any photo and click **π Detect Emotions**. "
|
| 217 |
-
"Use **π₯ Download Result** to save."
|
| 218 |
)
|
| 219 |
with gr.Row():
|
| 220 |
upload_in = gr.Image(
|
|
|
|
| 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
|
|
|
|
| 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:
|
|
|
|
| 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))
|
|
|
|
| 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 |
|
|
|
|
| 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
|
|
|
|
| 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
|
|
|
|
| 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(
|
|
|
|
| 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,
|
|
|
|
| 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(
|