Update emotion.py
Browse files- emotion.py +129 -371
emotion.py
CHANGED
|
@@ -1,14 +1,12 @@
|
|
| 1 |
import time
|
|
|
|
| 2 |
from dataclasses import dataclass, field
|
| 3 |
from typing import Optional, Dict, Tuple, List
|
| 4 |
-
|
| 5 |
import gradio as gr
|
| 6 |
import numpy as np
|
| 7 |
from PIL import Image
|
| 8 |
-
|
| 9 |
from deepface import DeepFace
|
| 10 |
|
| 11 |
-
|
| 12 |
# =========================
|
| 13 |
# 參數(可微調)
|
| 14 |
# =========================
|
|
@@ -18,14 +16,12 @@ EMA_ALPHA = 0.45
|
|
| 18 |
CONF_TH = 40.0
|
| 19 |
SWITCH_CONFIRM_SEC = 2.5
|
| 20 |
IOU_TH = 0.25
|
| 21 |
-
ZOOM_FACTOR = 1.
|
| 22 |
-
|
| 23 |
-
DETECTOR_BACKEND = "mtcnn" # 想快一點可改 "opencv"
|
| 24 |
ALIGN_FACE = True
|
| 25 |
|
| 26 |
-
|
| 27 |
# =========================
|
| 28 |
-
# 情緒中文 + 分數映射
|
| 29 |
# =========================
|
| 30 |
EMO_ZH = {
|
| 31 |
"angry": "生氣",
|
|
@@ -38,7 +34,6 @@ EMO_ZH = {
|
|
| 38 |
"unknown": "未知",
|
| 39 |
}
|
| 40 |
|
| 41 |
-
# 你要的:把 7 種情緒塞進 5 分心情分數
|
| 42 |
EMO_TO_SCORE = {
|
| 43 |
"angry": 1,
|
| 44 |
"disgust": 1,
|
|
@@ -50,9 +45,6 @@ EMO_TO_SCORE = {
|
|
| 50 |
"unknown": 3,
|
| 51 |
}
|
| 52 |
|
| 53 |
-
def get_emotion_score(emo: str) -> int:
|
| 54 |
-
return EMO_TO_SCORE.get(emo, 3)
|
| 55 |
-
|
| 56 |
SCORE_LABELS = {
|
| 57 |
1: "1(心情差)",
|
| 58 |
2: "2(不太好)",
|
|
@@ -62,116 +54,65 @@ SCORE_LABELS = {
|
|
| 62 |
}
|
| 63 |
SCORE_CHOICES = [SCORE_LABELS[i] for i in [1, 2, 3, 4, 5]]
|
| 64 |
|
| 65 |
-
|
| 66 |
# =========================
|
| 67 |
# 狀態
|
| 68 |
# =========================
|
| 69 |
@dataclass
|
| 70 |
class AppState:
|
| 71 |
-
mode: str = "攝影機辨識"
|
| 72 |
-
|
| 73 |
running: bool = True
|
| 74 |
finished: bool = False
|
| 75 |
last_analyze_t: float = 0.0
|
| 76 |
-
|
| 77 |
-
# tracking
|
| 78 |
track_bbox: Optional[Tuple[int, int, int, int]] = None
|
| 79 |
-
|
| 80 |
-
# smoothing
|
| 81 |
ema_scores: Optional[np.ndarray] = None
|
| 82 |
emo_keys: List[str] = field(default_factory=list)
|
| 83 |
-
|
| 84 |
-
# stable/candidate
|
| 85 |
stable_emo: str = "unknown"
|
| 86 |
candidate_emo: Optional[str] = None
|
| 87 |
candidate_since: Optional[float] = None
|
| 88 |
-
|
| 89 |
-
# final
|
| 90 |
final_emo: Optional[str] = None
|
| 91 |
final_conf: Optional[float] = None
|
| 92 |
-
|
| 93 |
-
final_score: int = 3
|
| 94 |
-
|
| 95 |
|
| 96 |
# =========================
|
| 97 |
-
#
|
| 98 |
# =========================
|
| 99 |
def _hint_html(msg: str) -> str:
|
| 100 |
-
# 加入 color:#000000 強制黑色
|
| 101 |
return f"""
|
| 102 |
<div style="border-radius:14px;padding:14px;border:1px dashed #DADADA;background:#FAFAFA;color:#000000;">
|
| 103 |
{msg}
|
| 104 |
</div>
|
| 105 |
"""
|
| 106 |
|
| 107 |
-
|
| 108 |
def _camera_hint_before_start() -> str:
|
| 109 |
-
return _hint_html(
|
| 110 |
-
"請先按「Click to access webcam / 允許」開啟攝影機;"
|
| 111 |
-
"接著,請按「錄製(Record)」開始。"
|
| 112 |
-
)
|
| 113 |
-
|
| 114 |
|
| 115 |
def _camera_hint_done() -> str:
|
| 116 |
-
return _hint_html("已完成辨識,可按「重新攝影機辨識」再次進行
|
| 117 |
-
|
| 118 |
|
| 119 |
def _camera_hint_stopped() -> str:
|
| 120 |
-
return _hint_html("已停止辨識。
|
| 121 |
-
|
| 122 |
|
| 123 |
def _result_card_html(emo_key: str, conf: Optional[float]) -> str:
|
| 124 |
zh = EMO_ZH.get(emo_key, emo_key)
|
| 125 |
score = EMO_TO_SCORE.get(emo_key, 3)
|
| 126 |
conf_txt = "" if conf is None else f"{conf:.1f}%"
|
| 127 |
score_desc = SCORE_LABELS[score].split("(")[1].rstrip(")")
|
| 128 |
-
|
| 129 |
-
# ✅ 強制設定 color: #000000
|
| 130 |
return f"""
|
| 131 |
-
<div style="
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
color:#000000;
|
| 137 |
-
">
|
| 138 |
-
<div style="font-size:14px;color:#000000;margin-bottom:8px;">
|
| 139 |
-
辨識結果
|
| 140 |
-
</div>
|
| 141 |
-
|
| 142 |
-
<div style="
|
| 143 |
-
font-size:42px;
|
| 144 |
-
font-weight:800;
|
| 145 |
-
line-height:1.1;
|
| 146 |
-
margin-bottom:14px;
|
| 147 |
-
color:#000000;
|
| 148 |
-
">
|
| 149 |
-
{zh}
|
| 150 |
-
</div>
|
| 151 |
-
|
| 152 |
-
<div style="font-size:16px;color:#000000;margin-bottom:6px;">
|
| 153 |
-
心情分數:{score}({score_desc})
|
| 154 |
-
</div>
|
| 155 |
-
|
| 156 |
-
<div style="font-size:14px;color:#000000;">
|
| 157 |
-
信心值:{conf_txt}
|
| 158 |
-
</div>
|
| 159 |
</div>
|
| 160 |
"""
|
| 161 |
|
| 162 |
-
|
| 163 |
def _score_radio_value(score: int) -> str:
|
| 164 |
-
|
| 165 |
-
score = min(5, max(1, score))
|
| 166 |
-
return SCORE_LABELS[score]
|
| 167 |
-
|
| 168 |
|
| 169 |
def _downsample_rgb(frame: np.ndarray, target_w: int) -> np.ndarray:
|
| 170 |
-
if frame is None:
|
| 171 |
-
return None
|
| 172 |
h, w = frame.shape[:2]
|
| 173 |
-
if w <= target_w:
|
| 174 |
-
return frame
|
| 175 |
scale = target_w / w
|
| 176 |
new_h = max(1, int(h * scale))
|
| 177 |
img = Image.fromarray(frame)
|
|
@@ -179,351 +120,168 @@ def _downsample_rgb(frame: np.ndarray, target_w: int) -> np.ndarray:
|
|
| 179 |
return np.array(img)
|
| 180 |
|
| 181 |
def _zoom_center(frame: np.ndarray, zoom: float) -> np.ndarray:
|
| 182 |
-
|
| 183 |
-
裁切畫面中心以模擬數位變焦。
|
| 184 |
-
zoom: 放大倍率 (例如 1.5)
|
| 185 |
-
"""
|
| 186 |
-
if frame is None or zoom <= 1.0:
|
| 187 |
-
return frame
|
| 188 |
-
|
| 189 |
h, w = frame.shape[:2]
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
new_h = int(h / zoom)
|
| 194 |
-
|
| 195 |
-
# 計算起始點 (讓裁切框置中)
|
| 196 |
-
start_x = (w - new_w) // 2
|
| 197 |
-
start_y = (h - new_h) // 2
|
| 198 |
-
|
| 199 |
-
# 進行裁切
|
| 200 |
-
cropped = frame[start_y : start_y + new_h, start_x : start_x + new_w]
|
| 201 |
-
return cropped
|
| 202 |
-
|
| 203 |
|
| 204 |
def _iou(a: Tuple[int, int, int, int], b: Tuple[int, int, int, int]) -> float:
|
| 205 |
ax, ay, aw, ah = a
|
| 206 |
bx, by, bw, bh = b
|
| 207 |
-
ax2, ay2 = ax
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
ix1, iy1 = max(ax, bx), max(ay, by)
|
| 211 |
-
ix2, iy2 = min(ax2, bx2), min(ay2, by2)
|
| 212 |
iw, ih = max(0, ix2 - ix1), max(0, iy2 - iy1)
|
| 213 |
inter = iw * ih
|
| 214 |
-
if inter <= 0:
|
| 215 |
-
|
| 216 |
-
union = aw * ah + bw * bh - inter
|
| 217 |
-
return inter / max(1e-6, union)
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
def _pick_face_by_tracking(
|
| 221 |
-
faces: List[Dict],
|
| 222 |
-
prev_bbox: Optional[Tuple[int, int, int, int]]
|
| 223 |
-
) -> Tuple[Optional[Dict], Optional[Tuple[int, int, int, int]]]:
|
| 224 |
-
if not faces:
|
| 225 |
-
return None, None
|
| 226 |
|
|
|
|
|
|
|
| 227 |
cand = []
|
| 228 |
for f in faces:
|
| 229 |
-
fa = f.get("facial_area", {})
|
| 230 |
-
x =
|
| 231 |
-
y = int(fa.get("y", 0) or 0)
|
| 232 |
-
w = int(fa.get("w", 0) or 0)
|
| 233 |
-
h = int(fa.get("h", 0) or 0)
|
| 234 |
if w > 0 and h > 0 and f.get("face") is not None:
|
| 235 |
cand.append((f, (x, y, w, h), w * h))
|
| 236 |
-
|
| 237 |
-
if
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
if prev_bbox is not None:
|
| 241 |
-
best = None
|
| 242 |
-
best_i = 0.0
|
| 243 |
for f, bb, area in cand:
|
| 244 |
i = _iou(prev_bbox, bb)
|
| 245 |
-
if i > best_i:
|
| 246 |
-
|
| 247 |
-
best = (f, bb)
|
| 248 |
-
if best is not None and best_i >= IOU_TH:
|
| 249 |
-
return best[0], best[1]
|
| 250 |
-
|
| 251 |
cand.sort(key=lambda x: x[2], reverse=True)
|
| 252 |
return cand[0][0], cand[0][1]
|
| 253 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
|
| 255 |
def _reset_state_for_camera(st: AppState) -> AppState:
|
| 256 |
-
st.running = True
|
| 257 |
-
st.
|
| 258 |
-
st.
|
| 259 |
-
st.
|
| 260 |
-
st.ema_scores = None
|
| 261 |
-
st.emo_keys = []
|
| 262 |
-
st.stable_emo = "unknown"
|
| 263 |
-
st.candidate_emo = None
|
| 264 |
-
st.candidate_since = None
|
| 265 |
-
st.final_emo = None
|
| 266 |
-
st.final_conf = None
|
| 267 |
-
st.final_score = 3
|
| 268 |
return st
|
| 269 |
|
| 270 |
-
|
| 271 |
# =========================
|
| 272 |
# Camera streaming
|
| 273 |
# =========================
|
| 274 |
def on_stream(frame_rgb: np.ndarray, st: AppState):
|
| 275 |
-
if st.finished or (not st.running):
|
| 276 |
-
cam_visible = False
|
| 277 |
-
|
| 278 |
-
if st.final_emo:
|
| 279 |
-
result_html = _result_card_html(st.final_emo, st.final_conf)
|
| 280 |
-
mood_val = _score_radio_value(EMO_TO_SCORE.get(st.final_emo, 3))
|
| 281 |
-
hint_html = _camera_hint_done()
|
| 282 |
-
else:
|
| 283 |
-
result_html = _hint_html("尚未完成辨識。")
|
| 284 |
-
mood_val = _score_radio_value(3)
|
| 285 |
-
hint_html = _camera_hint_stopped()
|
| 286 |
-
|
| 287 |
-
return (
|
| 288 |
-
gr.update(visible=cam_visible),
|
| 289 |
-
gr.update(value=result_html),
|
| 290 |
-
gr.update(value=mood_val),
|
| 291 |
-
gr.update(value=hint_html),
|
| 292 |
-
st,
|
| 293 |
-
gr.update(value="重新攝影機辨識"),
|
| 294 |
-
)
|
| 295 |
-
|
| 296 |
if frame_rgb is None:
|
| 297 |
-
return (
|
| 298 |
-
gr.update(visible=True),
|
| 299 |
-
gr.update(value=_hint_html("等待影像…(尚未開始串流)")),
|
| 300 |
-
gr.update(value=_score_radio_value(3)),
|
| 301 |
-
gr.update(value=_camera_hint_before_start()),
|
| 302 |
-
st,
|
| 303 |
-
gr.update(value="重新攝影機辨識"),
|
| 304 |
-
)
|
| 305 |
-
|
| 306 |
-
frame_rgb = _zoom_center(frame_rgb, ZOOM_FACTOR)
|
| 307 |
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
gr.update(value=_result_card_html(show, st.final_conf)),
|
| 314 |
-
gr.update(value=_score_radio_value(EMO_TO_SCORE.get(show, 3))),
|
| 315 |
-
gr.update(value=_camera_hint_before_start()),
|
| 316 |
-
st,
|
| 317 |
-
gr.update(value="重新攝影機辨識"),
|
| 318 |
-
)
|
| 319 |
-
|
| 320 |
-
st.last_analyze_t = now
|
| 321 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
small = _downsample_rgb(frame_rgb, DOWNSAMPLE_W)
|
| 323 |
-
|
| 324 |
-
faces = DeepFace.extract_faces(
|
| 325 |
-
img_path=small,
|
| 326 |
-
detector_backend=DETECTOR_BACKEND,
|
| 327 |
-
enforce_detection=False,
|
| 328 |
-
align=ALIGN_FACE,
|
| 329 |
-
)
|
| 330 |
pick, bbox = _pick_face_by_tracking(faces, st.track_bbox)
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
gr.update(value=_score_radio_value(EMO_TO_SCORE.get(show, 3))),
|
| 337 |
-
gr.update(value=_camera_hint_before_start()),
|
| 338 |
-
st,
|
| 339 |
-
gr.update(value="重新攝影機辨識"),
|
| 340 |
-
)
|
| 341 |
-
|
| 342 |
-
st.track_bbox = bbox
|
| 343 |
-
face = pick["face"]
|
| 344 |
-
if face.dtype != np.uint8:
|
| 345 |
-
face = np.clip(face * 255.0, 0, 255).astype(np.uint8)
|
| 346 |
-
|
| 347 |
-
result = DeepFace.analyze(
|
| 348 |
-
img_path=face,
|
| 349 |
-
actions=["emotion"],
|
| 350 |
-
enforce_detection=False,
|
| 351 |
-
)
|
| 352 |
-
if isinstance(result, list):
|
| 353 |
-
result = result[0]
|
| 354 |
-
emo_dict = result.get("emotion", None)
|
| 355 |
-
|
| 356 |
-
if not isinstance(emo_dict, dict) or len(emo_dict) == 0:
|
| 357 |
-
show = st.stable_emo or "unknown"
|
| 358 |
-
return (
|
| 359 |
-
gr.update(visible=True),
|
| 360 |
-
gr.update(value=_result_card_html(show, st.final_conf)),
|
| 361 |
-
gr.update(value=_score_radio_value(EMO_TO_SCORE.get(show, 3))),
|
| 362 |
-
gr.update(value=_camera_hint_before_start()),
|
| 363 |
-
st,
|
| 364 |
-
gr.update(value="重新攝影機辨識"),
|
| 365 |
-
)
|
| 366 |
-
|
| 367 |
-
top_key = max(emo_dict, key=lambda k: float(emo_dict[k]))
|
| 368 |
-
top_conf = float(emo_dict[top_key])
|
| 369 |
-
|
| 370 |
-
if top_conf < CONF_TH:
|
| 371 |
-
show = st.stable_emo or "unknown"
|
| 372 |
-
return (
|
| 373 |
-
gr.update(visible=True),
|
| 374 |
-
gr.update(value=_result_card_html(show, st.final_conf)),
|
| 375 |
-
gr.update(value=_score_radio_value(EMO_TO_SCORE.get(show, 3))),
|
| 376 |
-
gr.update(value=_camera_hint_before_start()),
|
| 377 |
-
st,
|
| 378 |
-
gr.update(value="重新攝影機辨識"),
|
| 379 |
-
)
|
| 380 |
-
|
| 381 |
-
keys = list(emo_dict.keys())
|
| 382 |
-
vec = np.array([float(emo_dict[k]) for k in keys], dtype=np.float32)
|
| 383 |
-
|
| 384 |
-
if st.ema_scores is None or st.emo_keys != keys:
|
| 385 |
-
st.ema_scores = vec
|
| 386 |
-
st.emo_keys = keys
|
| 387 |
-
else:
|
| 388 |
-
st.ema_scores = EMA_ALPHA * vec + (1.0 - EMA_ALPHA) * st.ema_scores
|
| 389 |
-
|
| 390 |
-
stable_idx = int(np.argmax(st.ema_scores))
|
| 391 |
-
stable_key = st.emo_keys[stable_idx]
|
| 392 |
-
st.stable_emo = stable_key
|
| 393 |
-
|
| 394 |
-
# 延遲確認
|
| 395 |
-
if st.candidate_emo != stable_key:
|
| 396 |
-
st.candidate_emo = stable_key
|
| 397 |
-
st.candidate_since = now
|
| 398 |
-
else:
|
| 399 |
-
if st.candidate_since is None:
|
| 400 |
-
st.candidate_since = now
|
| 401 |
-
|
| 402 |
-
confirmed = (
|
| 403 |
-
st.candidate_since is not None
|
| 404 |
-
and (now - st.candidate_since) >= SWITCH_CONFIRM_SEC
|
| 405 |
-
)
|
| 406 |
-
|
| 407 |
-
if confirmed and st.final_emo is None:
|
| 408 |
-
st.final_emo = stable_key
|
| 409 |
-
st.final_conf = top_conf
|
| 410 |
-
st.final_score = EMO_TO_SCORE.get(stable_key, 3)
|
| 411 |
-
|
| 412 |
-
st.running = False
|
| 413 |
-
st.finished = True
|
| 414 |
-
|
| 415 |
-
return (
|
| 416 |
-
gr.update(visible=False),
|
| 417 |
-
gr.update(value=_result_card_html(stable_key, top_conf)),
|
| 418 |
-
gr.update(value=_score_radio_value(EMO_TO_SCORE.get(stable_key, 3))),
|
| 419 |
-
gr.update(value=_camera_hint_done()),
|
| 420 |
-
st,
|
| 421 |
-
gr.update(value="重新攝影機辨識"),
|
| 422 |
-
)
|
| 423 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 424 |
return (
|
| 425 |
-
|
| 426 |
-
gr.update(value=_result_card_html(
|
| 427 |
-
gr.update(value=_score_radio_value(EMO_TO_SCORE.get(
|
| 428 |
gr.update(value=_camera_hint_before_start()),
|
| 429 |
st,
|
| 430 |
-
gr.update(
|
| 431 |
)
|
| 432 |
|
| 433 |
-
|
| 434 |
-
# =========================
|
| 435 |
-
# Mode / Buttons
|
| 436 |
-
# =========================
|
| 437 |
-
|
| 438 |
def on_restart(st: AppState):
|
| 439 |
st = _reset_state_for_camera(st)
|
| 440 |
-
return (
|
| 441 |
-
gr.update(visible=True),
|
| 442 |
-
gr.update(value=_hint_html("等待影像…(尚未開始串流)")),
|
| 443 |
-
gr.update(value=_score_radio_value(3)),
|
| 444 |
-
gr.update(value=_camera_hint_before_start()),
|
| 445 |
-
st,
|
| 446 |
-
gr.update(value="重新攝影機辨識"),
|
| 447 |
-
)
|
| 448 |
-
|
| 449 |
|
| 450 |
def on_stop(st: AppState):
|
| 451 |
-
st.running = False
|
| 452 |
-
|
| 453 |
-
if st.final_emo is None:
|
| 454 |
-
return (
|
| 455 |
-
gr.update(visible=False),
|
| 456 |
-
gr.update(value=_hint_html("已停止辨識。")),
|
| 457 |
-
gr.update(value=_score_radio_value(3)),
|
| 458 |
-
gr.update(value=_camera_hint_stopped()),
|
| 459 |
-
st,
|
| 460 |
-
gr.update(value="重新攝影機辨識"),
|
| 461 |
-
)
|
| 462 |
-
|
| 463 |
-
return (
|
| 464 |
-
gr.update(visible=False),
|
| 465 |
-
gr.update(value=_result_card_html(st.final_emo, st.final_conf)),
|
| 466 |
-
gr.update(value=_score_radio_value(EMO_TO_SCORE.get(st.final_emo, 3))),
|
| 467 |
-
gr.update(value=_camera_hint_done()),
|
| 468 |
-
st,
|
| 469 |
-
gr.update(value="重新攝影機辨識"),
|
| 470 |
-
)
|
| 471 |
-
|
| 472 |
|
| 473 |
# =========================
|
| 474 |
# Gradio UI
|
| 475 |
# =========================
|
| 476 |
-
|
| 477 |
if __name__ == "__main__":
|
| 478 |
-
with gr.Blocks(title="Emotion Detector"
|
| 479 |
st = gr.State(AppState())
|
| 480 |
-
|
| 481 |
gr.Markdown("## 情緒辨識")
|
| 482 |
-
|
| 483 |
hint = gr.HTML(_camera_hint_before_start())
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
sources=["webcam"],
|
| 487 |
-
streaming=True,
|
| 488 |
-
type="numpy",
|
| 489 |
-
label="攝影機",
|
| 490 |
-
visible=True,
|
| 491 |
-
)
|
| 492 |
-
|
| 493 |
with gr.Row():
|
| 494 |
btn_restart = gr.Button("重新攝影機辨識", variant="primary")
|
| 495 |
btn_stop = gr.Button("停止", variant="secondary")
|
| 496 |
-
|
| 497 |
gr.Markdown("### 辨識結果")
|
| 498 |
-
result = gr.HTML(_hint_html("等待影像…
|
| 499 |
-
|
| 500 |
gr.Markdown("### 心情分數(系統判定)")
|
| 501 |
-
mood = gr.Radio(
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
cam.stream(
|
| 509 |
-
fn=on_stream,
|
| 510 |
-
inputs=[cam, st],
|
| 511 |
-
outputs=[cam, result, mood, hint, st, btn_restart],
|
| 512 |
-
show_progress="minimal",
|
| 513 |
-
)
|
| 514 |
-
|
| 515 |
-
btn_restart.click(
|
| 516 |
-
fn=on_restart,
|
| 517 |
-
inputs=[st],
|
| 518 |
-
outputs=[cam, result, mood, hint, st, btn_restart],
|
| 519 |
-
show_progress="minimal",
|
| 520 |
-
)
|
| 521 |
-
|
| 522 |
-
btn_stop.click(
|
| 523 |
-
fn=on_stop,
|
| 524 |
-
inputs=[st],
|
| 525 |
-
outputs=[cam, result, mood, hint, st, btn_restart],
|
| 526 |
-
show_progress="minimal",
|
| 527 |
-
)
|
| 528 |
-
|
| 529 |
demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
|
|
|
|
| 1 |
import time
|
| 2 |
+
import cv2 # 新增:用於繪圖
|
| 3 |
from dataclasses import dataclass, field
|
| 4 |
from typing import Optional, Dict, Tuple, List
|
|
|
|
| 5 |
import gradio as gr
|
| 6 |
import numpy as np
|
| 7 |
from PIL import Image
|
|
|
|
| 8 |
from deepface import DeepFace
|
| 9 |
|
|
|
|
| 10 |
# =========================
|
| 11 |
# 參數(可微調)
|
| 12 |
# =========================
|
|
|
|
| 16 |
CONF_TH = 40.0
|
| 17 |
SWITCH_CONFIRM_SEC = 2.5
|
| 18 |
IOU_TH = 0.25
|
| 19 |
+
ZOOM_FACTOR = 1.3 # 微調縮放倍率
|
| 20 |
+
DETECTOR_BACKEND = "mtcnn"
|
|
|
|
| 21 |
ALIGN_FACE = True
|
| 22 |
|
|
|
|
| 23 |
# =========================
|
| 24 |
+
# 情緒中文 + 分數映射
|
| 25 |
# =========================
|
| 26 |
EMO_ZH = {
|
| 27 |
"angry": "生氣",
|
|
|
|
| 34 |
"unknown": "未知",
|
| 35 |
}
|
| 36 |
|
|
|
|
| 37 |
EMO_TO_SCORE = {
|
| 38 |
"angry": 1,
|
| 39 |
"disgust": 1,
|
|
|
|
| 45 |
"unknown": 3,
|
| 46 |
}
|
| 47 |
|
|
|
|
|
|
|
|
|
|
| 48 |
SCORE_LABELS = {
|
| 49 |
1: "1(心情差)",
|
| 50 |
2: "2(不太好)",
|
|
|
|
| 54 |
}
|
| 55 |
SCORE_CHOICES = [SCORE_LABELS[i] for i in [1, 2, 3, 4, 5]]
|
| 56 |
|
|
|
|
| 57 |
# =========================
|
| 58 |
# 狀態
|
| 59 |
# =========================
|
| 60 |
@dataclass
|
| 61 |
class AppState:
|
| 62 |
+
mode: str = "攝影機辨識"
|
|
|
|
| 63 |
running: bool = True
|
| 64 |
finished: bool = False
|
| 65 |
last_analyze_t: float = 0.0
|
|
|
|
|
|
|
| 66 |
track_bbox: Optional[Tuple[int, int, int, int]] = None
|
|
|
|
|
|
|
| 67 |
ema_scores: Optional[np.ndarray] = None
|
| 68 |
emo_keys: List[str] = field(default_factory=list)
|
|
|
|
|
|
|
| 69 |
stable_emo: str = "unknown"
|
| 70 |
candidate_emo: Optional[str] = None
|
| 71 |
candidate_since: Optional[float] = None
|
|
|
|
|
|
|
| 72 |
final_emo: Optional[str] = None
|
| 73 |
final_conf: Optional[float] = None
|
| 74 |
+
final_score: int = 3
|
|
|
|
|
|
|
| 75 |
|
| 76 |
# =========================
|
| 77 |
+
# 輔助函式
|
| 78 |
# =========================
|
| 79 |
def _hint_html(msg: str) -> str:
|
|
|
|
| 80 |
return f"""
|
| 81 |
<div style="border-radius:14px;padding:14px;border:1px dashed #DADADA;background:#FAFAFA;color:#000000;">
|
| 82 |
{msg}
|
| 83 |
</div>
|
| 84 |
"""
|
| 85 |
|
|
|
|
| 86 |
def _camera_hint_before_start() -> str:
|
| 87 |
+
return _hint_html("請先按「Click to access webcam」開啟攝影機;接著,按「錄製 (Record)」開始。")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
def _camera_hint_done() -> str:
|
| 90 |
+
return _hint_html("已完成辨識,可按「重新攝影機辨識」再次進行。")
|
|
|
|
| 91 |
|
| 92 |
def _camera_hint_stopped() -> str:
|
| 93 |
+
return _hint_html("已停止辨識。")
|
|
|
|
| 94 |
|
| 95 |
def _result_card_html(emo_key: str, conf: Optional[float]) -> str:
|
| 96 |
zh = EMO_ZH.get(emo_key, emo_key)
|
| 97 |
score = EMO_TO_SCORE.get(emo_key, 3)
|
| 98 |
conf_txt = "" if conf is None else f"{conf:.1f}%"
|
| 99 |
score_desc = SCORE_LABELS[score].split("(")[1].rstrip(")")
|
|
|
|
|
|
|
| 100 |
return f"""
|
| 101 |
+
<div style="border-radius:16px;padding:20px;border:1px solid #E6E6E6;background:#FFFFFF;color:#000000;">
|
| 102 |
+
<div style="font-size:14px;margin-bottom:8px;">辨識結果</div>
|
| 103 |
+
<div style="font-size:42px;font-weight:800;line-height:1.1;margin-bottom:14px;">{zh}</div>
|
| 104 |
+
<div style="font-size:16px;margin-bottom:6px;">心情分數:{score}({score_desc})</div>
|
| 105 |
+
<div style="font-size:14px;">信心值:{conf_txt}</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
</div>
|
| 107 |
"""
|
| 108 |
|
|
|
|
| 109 |
def _score_radio_value(score: int) -> str:
|
| 110 |
+
return SCORE_LABELS[min(5, max(1, int(score)))]
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
def _downsample_rgb(frame: np.ndarray, target_w: int) -> np.ndarray:
|
| 113 |
+
if frame is None: return None
|
|
|
|
| 114 |
h, w = frame.shape[:2]
|
| 115 |
+
if w <= target_w: return frame
|
|
|
|
| 116 |
scale = target_w / w
|
| 117 |
new_h = max(1, int(h * scale))
|
| 118 |
img = Image.fromarray(frame)
|
|
|
|
| 120 |
return np.array(img)
|
| 121 |
|
| 122 |
def _zoom_center(frame: np.ndarray, zoom: float) -> np.ndarray:
|
| 123 |
+
if frame is None or zoom <= 1.0: return frame
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
h, w = frame.shape[:2]
|
| 125 |
+
new_w, new_h = int(w / zoom), int(h / zoom)
|
| 126 |
+
start_x, start_y = (w - new_w) // 2, (h - new_h) // 2
|
| 127 |
+
return frame[start_y : start_y + new_h, start_x : start_x + new_w]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
def _iou(a: Tuple[int, int, int, int], b: Tuple[int, int, int, int]) -> float:
|
| 130 |
ax, ay, aw, ah = a
|
| 131 |
bx, by, bw, bh = b
|
| 132 |
+
ax2, ay2, bx2, by2 = ax+aw, ay+ah, bx+bw, by+bh
|
| 133 |
+
ix1, iy1, ix2, iy2 = max(ax, bx), max(ay, by), min(ax2, bx2), min(ay2, by2)
|
|
|
|
|
|
|
|
|
|
| 134 |
iw, ih = max(0, ix2 - ix1), max(0, iy2 - iy1)
|
| 135 |
inter = iw * ih
|
| 136 |
+
if inter <= 0: return 0.0
|
| 137 |
+
return inter / (aw * ah + bw * bh - inter)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
+
def _pick_face_by_tracking(faces: List[Dict], prev_bbox: Optional[Tuple[int, int, int, int]]):
|
| 140 |
+
if not faces: return None, None
|
| 141 |
cand = []
|
| 142 |
for f in faces:
|
| 143 |
+
fa = f.get("facial_area", {})
|
| 144 |
+
x, y, w, h = fa.get("x",0), fa.get("y",0), fa.get("w",0), fa.get("h",0)
|
|
|
|
|
|
|
|
|
|
| 145 |
if w > 0 and h > 0 and f.get("face") is not None:
|
| 146 |
cand.append((f, (x, y, w, h), w * h))
|
| 147 |
+
if not cand: return None, None
|
| 148 |
+
if prev_bbox:
|
| 149 |
+
best, best_i = None, 0.0
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
for f, bb, area in cand:
|
| 151 |
i = _iou(prev_bbox, bb)
|
| 152 |
+
if i > best_i: best_i, best = i, (f, bb)
|
| 153 |
+
if best and best_i >= IOU_TH: return best
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
cand.sort(key=lambda x: x[2], reverse=True)
|
| 155 |
return cand[0][0], cand[0][1]
|
| 156 |
|
| 157 |
+
def _draw_guide_box(frame: np.ndarray, is_detected: bool):
|
| 158 |
+
""" 在影像上繪製導引框(紅框/綠框) """
|
| 159 |
+
h, w = frame.shape[:2]
|
| 160 |
+
# 建立一個佔畫面中間 50% 的框
|
| 161 |
+
bw, bh = int(w * 0.5), int(h * 0.6)
|
| 162 |
+
x1, y1 = (w - bw) // 2, (h - bh) // 2
|
| 163 |
+
x2, y2 = x1 + bw, y1 + bh
|
| 164 |
+
|
| 165 |
+
# 顏色 (RGB): 綠色表示偵測中,紅色表示未對準
|
| 166 |
+
color = (0, 255, 0) if is_detected else (255, 0, 0)
|
| 167 |
+
label = "Scanning..." if is_detected else "Please align your face"
|
| 168 |
+
|
| 169 |
+
# 繪製矩形與文字
|
| 170 |
+
cv2.rectangle(frame, (x1, y1), (x2, y2), color, 3)
|
| 171 |
+
cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2)
|
| 172 |
+
return frame
|
| 173 |
|
| 174 |
def _reset_state_for_camera(st: AppState) -> AppState:
|
| 175 |
+
st.running, st.finished, st.last_analyze_t = True, False, 0.0
|
| 176 |
+
st.track_bbox, st.ema_scores, st.emo_keys = None, None, []
|
| 177 |
+
st.stable_emo, st.candidate_emo, st.candidate_since = "unknown", None, None
|
| 178 |
+
st.final_emo, st.final_conf, st.final_score = None, None, 3
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
return st
|
| 180 |
|
|
|
|
| 181 |
# =========================
|
| 182 |
# Camera streaming
|
| 183 |
# =========================
|
| 184 |
def on_stream(frame_rgb: np.ndarray, st: AppState):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
if frame_rgb is None:
|
| 186 |
+
return (None, gr.update(), gr.update(), gr.update(), st, gr.update())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
|
| 188 |
+
if st.finished or (not st.running):
|
| 189 |
+
# 結束時顯示結果,隱藏攝像頭
|
| 190 |
+
result_html = _result_card_html(st.final_emo, st.final_conf) if st.final_emo else _hint_html("已停止")
|
| 191 |
+
mood_val = _score_radio_value(EMO_TO_SCORE.get(st.final_emo, 3)) if st.final_emo else _score_radio_value(3)
|
| 192 |
+
return (None, gr.update(value=result_html), gr.update(value=mood_val), gr.update(value=_camera_hint_done()), st, gr.update(value="重新攝影機辨識"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
|
| 194 |
+
# 1. 數位變焦
|
| 195 |
+
frame_rgb = _zoom_center(frame_rgb, ZOOM_FACTOR)
|
| 196 |
+
|
| 197 |
+
# 2. 為了畫框,進行快速人臉檢查
|
| 198 |
small = _downsample_rgb(frame_rgb, DOWNSAMPLE_W)
|
| 199 |
+
faces = DeepFace.extract_faces(img_path=small, detector_backend="opencv", enforce_detection=False, align=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
pick, bbox = _pick_face_by_tracking(faces, st.track_bbox)
|
| 201 |
+
is_detected = pick is not None and pick.get("face") is not None
|
| 202 |
+
|
| 203 |
+
# 3. 繪製導引框
|
| 204 |
+
frame_with_box = _draw_guide_box(frame_rgb.copy(), is_detected)
|
| 205 |
+
now = time.time()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
|
| 207 |
+
# 4. 核心辨識邏輯 (每隔一段時間分析)
|
| 208 |
+
if is_detected and (now - st.last_analyze_t >= ANALYZE_EVERY_SEC):
|
| 209 |
+
st.last_analyze_t = now
|
| 210 |
+
st.track_bbox = bbox
|
| 211 |
+
|
| 212 |
+
face = pick["face"]
|
| 213 |
+
if face.dtype != np.uint8:
|
| 214 |
+
face = np.clip(face * 255.0, 0, 255).astype(np.uint8)
|
| 215 |
+
|
| 216 |
+
result = DeepFace.analyze(img_path=face, actions=["emotion"], enforce_detection=False)
|
| 217 |
+
if isinstance(result, list): result = result[0]
|
| 218 |
+
emo_dict = result.get("emotion", {})
|
| 219 |
+
|
| 220 |
+
if emo_dict:
|
| 221 |
+
top_key = max(emo_dict, key=lambda k: float(emo_dict[k]))
|
| 222 |
+
top_conf = float(emo_dict[top_key])
|
| 223 |
+
|
| 224 |
+
# EMA 平滑
|
| 225 |
+
keys = list(emo_dict.keys())
|
| 226 |
+
vec = np.array([float(emo_dict[k]) for k in keys], dtype=np.float32)
|
| 227 |
+
if st.ema_scores is None or st.emo_keys != keys:
|
| 228 |
+
st.ema_scores, st.emo_keys = vec, keys
|
| 229 |
+
else:
|
| 230 |
+
st.ema_scores = EMA_ALPHA * vec + (1.0 - EMA_ALPHA) * st.ema_scores
|
| 231 |
+
|
| 232 |
+
stable_key = st.emo_keys[int(np.argmax(st.ema_scores))]
|
| 233 |
+
st.stable_emo = stable_key
|
| 234 |
+
|
| 235 |
+
# 延遲確認邏輯
|
| 236 |
+
if st.candidate_emo != stable_key:
|
| 237 |
+
st.candidate_emo, st.candidate_since = stable_key, now
|
| 238 |
+
|
| 239 |
+
if st.candidate_since and (now - st.candidate_since >= SWITCH_CONFIRM_SEC):
|
| 240 |
+
st.final_emo, st.final_conf, st.running, st.finished = stable_key, top_conf, False, True
|
| 241 |
+
return (frame_with_box, gr.update(value=_result_card_html(stable_key, top_conf)), gr.update(value=_score_radio_value(EMO_TO_SCORE.get(stable_key, 3))), gr.update(value=_camera_hint_done()), st, gr.update(value="重新攝影機辨識"))
|
| 242 |
+
|
| 243 |
+
# 持續回傳帶有導引框的影像
|
| 244 |
+
show_emo = st.stable_emo or "unknown"
|
| 245 |
return (
|
| 246 |
+
frame_with_box,
|
| 247 |
+
gr.update(value=_result_card_html(show_emo, st.final_conf)),
|
| 248 |
+
gr.update(value=_score_radio_value(EMO_TO_SCORE.get(show_emo, 3))),
|
| 249 |
gr.update(value=_camera_hint_before_start()),
|
| 250 |
st,
|
| 251 |
+
gr.update()
|
| 252 |
)
|
| 253 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
def on_restart(st: AppState):
|
| 255 |
st = _reset_state_for_camera(st)
|
| 256 |
+
return (gr.update(visible=True), gr.update(value=_hint_html("等待影像…")), gr.update(value=_score_radio_value(3)), gr.update(value=_camera_hint_before_start()), st, gr.update(value="重新攝影機辨識"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
|
| 258 |
def on_stop(st: AppState):
|
| 259 |
+
st.running, st.finished = False, True
|
| 260 |
+
return (gr.update(visible=False), gr.update(value=_hint_html("已停止")), gr.update(value=_score_radio_value(3)), gr.update(value=_camera_hint_stopped()), st, gr.update(value="重新攝影機辨識"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 261 |
|
| 262 |
# =========================
|
| 263 |
# Gradio UI
|
| 264 |
# =========================
|
|
|
|
| 265 |
if __name__ == "__main__":
|
| 266 |
+
with gr.Blocks(title="Emotion Detector") as demo:
|
| 267 |
st = gr.State(AppState())
|
|
|
|
| 268 |
gr.Markdown("## 情緒辨識")
|
| 269 |
+
|
| 270 |
hint = gr.HTML(_camera_hint_before_start())
|
| 271 |
+
cam = gr.Image(sources=["webcam"], streaming=True, type="numpy", label="攝影機", visible=True)
|
| 272 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
with gr.Row():
|
| 274 |
btn_restart = gr.Button("重新攝影機辨識", variant="primary")
|
| 275 |
btn_stop = gr.Button("停止", variant="secondary")
|
| 276 |
+
|
| 277 |
gr.Markdown("### 辨識結果")
|
| 278 |
+
result = gr.HTML(_hint_html("等待影像…"))
|
| 279 |
+
|
| 280 |
gr.Markdown("### 心情分數(系統判定)")
|
| 281 |
+
mood = gr.Radio(choices=SCORE_CHOICES, value=_score_radio_value(3), label="心情分數", interactive=False)
|
| 282 |
+
|
| 283 |
+
cam.stream(fn=on_stream, inputs=[cam, st], outputs=[cam, result, mood, hint, st, btn_restart], show_progress="minimal")
|
| 284 |
+
btn_restart.click(fn=on_restart, inputs=[st], outputs=[cam, result, mood, hint, st, btn_restart])
|
| 285 |
+
btn_stop.click(fn=on_stop, inputs=[st], outputs=[cam, result, mood, hint, st, btn_restart])
|
| 286 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
|