YuAnTsai commited on
Commit
07c0b27
·
verified ·
1 Parent(s): 10ce868

Update emotion.py

Browse files
Files changed (1) hide show
  1. emotion.py +136 -250
emotion.py CHANGED
@@ -1,73 +1,35 @@
1
  import time
2
- import threading
3
  from dataclasses import dataclass, field
4
  from typing import Optional, Dict, Tuple, List
5
 
6
  import gradio as gr
7
  import numpy as np
8
- from PIL import Image, ImageDraw
9
 
10
  from deepface import DeepFace
11
 
12
 
 
 
 
 
13
  # =========================
14
- # 參數(優先順:快)
15
  # =========================
16
- ANALYZE_EVERY_SEC = 1.2 # ✅ 降頻率(原 0.8)
17
- DOWNSAMPLE_W = 480 # ✅ 降解析(原 720)
18
  EMA_ALPHA = 0.45
19
  CONF_TH = 40.0
20
  SWITCH_CONFIRM_SEC = 2.5
21
  IOU_TH = 0.25
22
- ZOOM_FACTOR = 1.25 # ✅ 稍微降 zoom(減少失真與負擔)
23
 
24
- DETECTOR_BACKEND = "opencv" # ✅ 改快(原 mtcnn)
25
  ALIGN_FACE = True
26
 
27
- # 防誤判(保留)
28
- MIN_FACE_AREA_RATIO = 0.05
29
- MIN_DET_CONF = 0.90
30
-
31
 
32
  # =========================
33
- # Warm-up(優先順:按 Record 不要等)
34
- # =========================
35
- _WARMED = False
36
-
37
- def _warmup_models():
38
- global _WARMED
39
- if _WARMED:
40
- return
41
- _WARMED = True
42
- try:
43
- dummy = np.zeros((224, 224, 3), dtype=np.uint8)
44
- # detector warmup
45
- try:
46
- DeepFace.extract_faces(
47
- img_path=dummy,
48
- detector_backend=DETECTOR_BACKEND,
49
- enforce_detection=False,
50
- align=ALIGN_FACE,
51
- )
52
- except Exception:
53
- pass
54
- # emotion model warmup
55
- try:
56
- DeepFace.analyze(
57
- img_path=dummy,
58
- actions=["emotion"],
59
- enforce_detection=False,
60
- )
61
- except Exception:
62
- pass
63
- except Exception:
64
- pass
65
-
66
- threading.Thread(target=_warmup_models, daemon=True).start()
67
-
68
-
69
- # =========================
70
- # 情緒中文 + 分數映射
71
  # =========================
72
  EMO_ZH = {
73
  "angry": "生氣",
@@ -80,6 +42,7 @@ EMO_ZH = {
80
  "unknown": "未知",
81
  }
82
 
 
83
  EMO_TO_SCORE = {
84
  "angry": 1,
85
  "disgust": 1,
@@ -91,6 +54,9 @@ EMO_TO_SCORE = {
91
  "unknown": 3,
92
  }
93
 
 
 
 
94
  SCORE_LABELS = {
95
  1: "1(心情差)",
96
  2: "2(不太好)",
@@ -106,72 +72,101 @@ SCORE_CHOICES = [SCORE_LABELS[i] for i in [1, 2, 3, 4, 5]]
106
  # =========================
107
  @dataclass
108
  class AppState:
 
 
109
  running: bool = True
110
  finished: bool = False
111
  last_analyze_t: float = 0.0
112
 
 
113
  track_bbox: Optional[Tuple[int, int, int, int]] = None
114
 
 
115
  ema_scores: Optional[np.ndarray] = None
116
  emo_keys: List[str] = field(default_factory=list)
117
 
 
118
  stable_emo: str = "unknown"
119
  candidate_emo: Optional[str] = None
120
  candidate_since: Optional[float] = None
121
 
 
122
  final_emo: Optional[str] = None
123
  final_conf: Optional[float] = None
124
- final_score: int = 3
125
 
126
- last_face_t: float = 0.0
127
- face_in_box: bool = False
128
 
129
 
130
  # =========================
131
- # UI HTML
132
  # =========================
133
  def _hint_html(msg: str) -> str:
 
134
  return f"""
135
  <div style="border-radius:14px;padding:14px;border:1px dashed #DADADA;background:#FAFAFA;color:#000000;">
136
  {msg}
137
  </div>
138
  """
139
 
 
140
  def _camera_hint_before_start() -> str:
141
  return _hint_html(
142
  "請先按「Click to access webcam / 允許」開啟攝影機;"
143
  "接著,請按「錄製(Record)」開始。"
144
  )
145
 
 
146
  def _camera_hint_done() -> str:
147
  return _hint_html("已完成辨識,可按「重新攝影機辨識」再次進行辨識。")
148
 
 
149
  def _camera_hint_stopped() -> str:
150
  return _hint_html("已停止辨識。可按「重新攝影機辨識」再試一次。")
151
 
 
152
  def _result_card_html(emo_key: str, conf: Optional[float]) -> str:
153
  zh = EMO_ZH.get(emo_key, emo_key)
154
  score = EMO_TO_SCORE.get(emo_key, 3)
155
  conf_txt = "" if conf is None else f"{conf:.1f}%"
156
  score_desc = SCORE_LABELS[score].split("(")[1].rstrip(")")
 
 
157
  return f"""
158
- <div style="border-radius:16px;padding:20px;border:1px solid #E6E6E6;background:#FFFFFF;color:#000000;">
159
- <div style="font-size:14px;color:#000000;margin-bottom:8px;">辨識結果</div>
160
- <div style="font-size:42px;font-weight:800;line-height:1.1;margin-bottom:14px;color:#000000;">{zh}</div>
161
- <div style="font-size:16px;color:#000000;margin-bottom:6px;">心情分數:{score}({score_desc})</div>
162
- <div style="font-size:14px;color:#000000;">信心值:{conf_txt}</div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  </div>
164
  """
165
 
 
166
  def _score_radio_value(score: int) -> str:
167
  score = int(score)
168
  score = min(5, max(1, score))
169
  return SCORE_LABELS[score]
170
 
171
 
172
- # =========================
173
- # 影像工具
174
- # =========================
175
  def _downsample_rgb(frame: np.ndarray, target_w: int) -> np.ndarray:
176
  if frame is None:
177
  return None
@@ -185,66 +180,28 @@ def _downsample_rgb(frame: np.ndarray, target_w: int) -> np.ndarray:
185
  return np.array(img)
186
 
187
  def _zoom_center(frame: np.ndarray, zoom: float) -> np.ndarray:
 
 
 
 
188
  if frame is None or zoom <= 1.0:
189
  return frame
 
190
  h, w = frame.shape[:2]
 
 
191
  new_w = int(w / zoom)
192
  new_h = int(h / zoom)
 
 
193
  start_x = (w - new_w) // 2
194
  start_y = (h - new_h) // 2
195
- return frame[start_y:start_y + new_h, start_x:start_x + new_w]
196
-
197
-
198
- # =========================
199
- # 引導框(永遠畫)
200
- # =========================
201
- GUIDE_W_RATIO = 0.55
202
- GUIDE_H_RATIO = 0.70
203
- GUIDE_Y_OFFSET = 0.00
204
-
205
- def _guide_box(frame: np.ndarray) -> Tuple[int, int, int, int]:
206
- h, w = frame.shape[:2]
207
- gw = int(w * GUIDE_W_RATIO)
208
- gh = int(h * GUIDE_H_RATIO)
209
- cx = w // 2
210
- cy = int(h * (0.5 + GUIDE_Y_OFFSET))
211
- x1 = max(0, cx - gw // 2)
212
- y1 = max(0, cy - gh // 2)
213
- x2 = min(w - 1, cx + gw // 2)
214
- y2 = min(h - 1, cy + gh // 2)
215
- return x1, y1, x2, y2
216
-
217
- def _bbox_center_in_box(bbox_xywh: Tuple[float, float, float, float], box_xyxy: Tuple[int, int, int, int]) -> bool:
218
- x, y, w, h = bbox_xywh
219
- cx = x + w / 2.0
220
- cy = y + h / 2.0
221
- x1, y1, x2, y2 = box_xyxy
222
- return (x1 <= cx <= x2) and (y1 <= cy <= y2)
223
-
224
- def _draw_guide_overlay(frame_rgb: np.ndarray, detected_in_box: bool) -> np.ndarray:
225
- img = Image.fromarray(frame_rgb)
226
- draw = ImageDraw.Draw(img)
227
-
228
- x1, y1, x2, y2 = _guide_box(frame_rgb)
229
- color = (0, 200, 0) if detected_in_box else (220, 0, 0)
230
-
231
- h, w = frame_rgb.shape[:2]
232
- thickness = max(3, int(min(w, h) * 0.008))
233
- for t in range(thickness):
234
- draw.rectangle([x1 - t, y1 - t, x2 + t, y2 + t], outline=color)
235
-
236
- msg = "已偵測到人臉,開始辨識情緒中…" if detected_in_box else "未偵測到人臉,請把臉放進框內"
237
- tx = x1
238
- ty = max(0, y1 - int(thickness * 6))
239
- draw.rectangle([tx, ty, tx + 360, ty + 32], fill=(255, 255, 255))
240
- draw.text((tx + 6, ty + 6), msg, fill=(0, 0, 0))
241
-
242
- return np.array(img)
243
 
244
 
245
- # =========================
246
- # Tracking / IoU
247
- # =========================
248
  def _iou(a: Tuple[int, int, int, int], b: Tuple[int, int, int, int]) -> float:
249
  ax, ay, aw, ah = a
250
  bx, by, bw, bh = b
@@ -260,9 +217,14 @@ def _iou(a: Tuple[int, int, int, int], b: Tuple[int, int, int, int]) -> float:
260
  union = aw * ah + bw * bh - inter
261
  return inter / max(1e-6, union)
262
 
263
- def _pick_face_by_tracking(faces: List[Dict], prev_bbox: Optional[Tuple[int, int, int, int]]):
 
 
 
 
264
  if not faces:
265
  return None, None
 
266
  cand = []
267
  for f in faces:
268
  fa = f.get("facial_area", {}) or {}
@@ -304,47 +266,30 @@ def _reset_state_for_camera(st: AppState) -> AppState:
304
  st.final_emo = None
305
  st.final_conf = None
306
  st.final_score = 3
307
- st.last_face_t = 0.0
308
- st.face_in_box = False
309
  return st
310
 
311
 
312
- def _is_real_face(pick: Dict, bbox_full_xywh: Tuple[float, float, float, float], frame_hw: Tuple[int, int]) -> bool:
313
- fh, fw = frame_hw
314
- x, y, w, h = bbox_full_xywh
315
- area_ratio = (w * h) / max(1.0, float(fw * fh))
316
- if area_ratio < MIN_FACE_AREA_RATIO:
317
- return False
318
- det_conf = pick.get("confidence", None)
319
- if det_conf is not None:
320
- try:
321
- if float(det_conf) < MIN_DET_CONF:
322
- return False
323
- except Exception:
324
- pass
325
- return True
326
-
327
-
328
  # =========================
329
- # Stream(優先順)
330
  # =========================
331
  def on_stream(frame_rgb: np.ndarray, st: AppState):
332
  if st.finished or (not st.running):
333
  cam_visible = False
 
334
  if st.final_emo:
335
- return (
336
- gr.update(visible=cam_visible),
337
- gr.update(value=_result_card_html(st.final_emo, st.final_conf)),
338
- gr.update(value=_score_radio_value(EMO_TO_SCORE.get(st.final_emo, 3))),
339
- gr.update(value=_camera_hint_done()),
340
- st,
341
- gr.update(value="重新攝影機辨識"),
342
- )
343
  return (
344
  gr.update(visible=cam_visible),
345
- gr.update(value=_hint_html("尚未完成辨識。")),
346
- gr.update(value=_score_radio_value(3)),
347
- gr.update(value=_camera_hint_stopped()),
348
  st,
349
  gr.update(value="重新攝影機辨識"),
350
  )
@@ -358,128 +303,65 @@ def on_stream(frame_rgb: np.ndarray, st: AppState):
358
  st,
359
  gr.update(value="重新攝影機辨識"),
360
  )
361
-
362
  frame_rgb = _zoom_center(frame_rgb, ZOOM_FACTOR)
363
- now = time.time()
364
 
365
- # ✅ 先畫框(永遠立即有框),不等 detector
366
- detected_recent = st.face_in_box and (now - st.last_face_t) < 1.0
367
- annotated_fast = _draw_guide_overlay(frame_rgb, detected_recent)
368
-
369
- # ✅ 如果還沒到分析時間,直接回傳畫框(超順)
370
  if now - st.last_analyze_t < ANALYZE_EVERY_SEC:
 
371
  return (
372
- gr.update(visible=True, value=annotated_fast),
373
- gr.update(value=_hint_html("已偵測到人臉,開始辨識情緒中…" if detected_recent else "未偵測到人臉,請把臉放進框內")),
374
- gr.update(value=_score_radio_value(3)),
375
  gr.update(value=_camera_hint_before_start()),
376
  st,
377
  gr.update(value="重新攝影機辨識"),
378
  )
379
 
380
- # 到時間才做一次重工作(低頻)
381
  st.last_analyze_t = now
382
- small = _downsample_rgb(frame_rgb, DOWNSAMPLE_W)
383
 
384
- try:
385
- faces = DeepFace.extract_faces(
386
- img_path=small,
387
- detector_backend=DETECTOR_BACKEND,
388
- enforce_detection=True,
389
- align=ALIGN_FACE,
390
- )
391
- except Exception:
392
- faces = []
393
 
 
 
 
 
 
 
 
394
  pick, bbox = _pick_face_by_tracking(faces, st.track_bbox)
395
-
396
  if pick is None or bbox is None or pick.get("face") is None:
397
- st.track_bbox = None
398
- st.face_in_box = False
399
- st.last_face_t = now
400
- st.stable_emo = "unknown"
401
- annotated = _draw_guide_overlay(frame_rgb, False)
402
- return (
403
- gr.update(visible=True, value=annotated),
404
- gr.update(value=_hint_html("未偵測到人臉,請把臉放進框內")),
405
- gr.update(value=_score_radio_value(3)),
406
- gr.update(value=_camera_hint_before_start()),
407
- st,
408
- gr.update(value="重新攝影機辨識"),
409
- )
410
-
411
- sh, sw = small.shape[:2]
412
- fh, fw = frame_rgb.shape[:2]
413
- sx = fw / max(1, sw)
414
- sy = fh / max(1, sh)
415
- x, y, w, h = bbox
416
- bbox_full = (x * sx, y * sy, w * sx, h * sy)
417
-
418
- if not _is_real_face(pick, bbox_full, (fh, fw)):
419
- st.track_bbox = None
420
- st.face_in_box = False
421
- st.last_face_t = now
422
- annotated = _draw_guide_overlay(frame_rgb, False)
423
  return (
424
- gr.update(visible=True, value=annotated),
425
- gr.update(value=_hint_html("未偵測到人臉,請把臉放進框內")),
426
- gr.update(value=_score_radio_value(3)),
427
  gr.update(value=_camera_hint_before_start()),
428
  st,
429
  gr.update(value="重新攝影機辨識"),
430
  )
431
 
432
- guide = _guide_box(frame_rgb)
433
- in_box = _bbox_center_in_box(bbox_full, guide)
434
-
435
- st.last_face_t = now
436
- st.face_in_box = in_box
437
  st.track_bbox = bbox
438
-
439
- if not in_box:
440
- annotated = _draw_guide_overlay(frame_rgb, False)
441
- return (
442
- gr.update(visible=True, value=annotated),
443
- gr.update(value=_hint_html("已偵測到人臉,但請把臉放進框內")),
444
- gr.update(value=_score_radio_value(3)),
445
- gr.update(value=_camera_hint_before_start()),
446
- st,
447
- gr.update(value="重新攝影機辨識"),
448
- )
449
-
450
- # 只有臉在框內才分析情緒
451
  face = pick["face"]
452
  if face.dtype != np.uint8:
453
  face = np.clip(face * 255.0, 0, 255).astype(np.uint8)
454
 
455
- try:
456
- result = DeepFace.analyze(
457
- img_path=face,
458
- actions=["emotion"],
459
- enforce_detection=True,
460
- )
461
- except Exception:
462
- annotated = _draw_guide_overlay(frame_rgb, False)
463
- st.face_in_box = False
464
- st.last_face_t = now
465
- return (
466
- gr.update(visible=True, value=annotated),
467
- gr.update(value=_hint_html("未偵測到人臉,請把臉放進框內")),
468
- gr.update(value=_score_radio_value(3)),
469
- gr.update(value=_camera_hint_before_start()),
470
- st,
471
- gr.update(value="重新攝影機辨識"),
472
- )
473
-
474
  if isinstance(result, list):
475
  result = result[0]
476
  emo_dict = result.get("emotion", None)
 
477
  if not isinstance(emo_dict, dict) or len(emo_dict) == 0:
478
- annotated = _draw_guide_overlay(frame_rgb, True)
479
  return (
480
- gr.update(visible=True, value=annotated),
481
- gr.update(value=_hint_html("已偵測到人臉,開始辨識情緒中…")),
482
- gr.update(value=_score_radio_value(3)),
483
  gr.update(value=_camera_hint_before_start()),
484
  st,
485
  gr.update(value="重新攝影機辨識"),
@@ -489,11 +371,11 @@ def on_stream(frame_rgb: np.ndarray, st: AppState):
489
  top_conf = float(emo_dict[top_key])
490
 
491
  if top_conf < CONF_TH:
492
- annotated = _draw_guide_overlay(frame_rgb, True)
493
  return (
494
- gr.update(visible=True, value=annotated),
495
- gr.update(value=_hint_html("已偵測到人臉,開始辨識情緒中…")),
496
- gr.update(value=_score_radio_value(3)),
497
  gr.update(value=_camera_hint_before_start()),
498
  st,
499
  gr.update(value="重新攝影機辨識"),
@@ -512,6 +394,7 @@ def on_stream(frame_rgb: np.ndarray, st: AppState):
512
  stable_key = st.emo_keys[stable_idx]
513
  st.stable_emo = stable_key
514
 
 
515
  if st.candidate_emo != stable_key:
516
  st.candidate_emo = stable_key
517
  st.candidate_since = now
@@ -528,8 +411,10 @@ def on_stream(frame_rgb: np.ndarray, st: AppState):
528
  st.final_emo = stable_key
529
  st.final_conf = top_conf
530
  st.final_score = EMO_TO_SCORE.get(stable_key, 3)
 
531
  st.running = False
532
  st.finished = True
 
533
  return (
534
  gr.update(visible=False),
535
  gr.update(value=_result_card_html(stable_key, top_conf)),
@@ -539,9 +424,8 @@ def on_stream(frame_rgb: np.ndarray, st: AppState):
539
  gr.update(value="重新攝影機辨識"),
540
  )
541
 
542
- annotated = _draw_guide_overlay(frame_rgb, True)
543
  return (
544
- gr.update(visible=True, value=annotated),
545
  gr.update(value=_result_card_html(stable_key, top_conf)),
546
  gr.update(value=_score_radio_value(EMO_TO_SCORE.get(stable_key, 3))),
547
  gr.update(value=_camera_hint_before_start()),
@@ -551,33 +435,35 @@ def on_stream(frame_rgb: np.ndarray, st: AppState):
551
 
552
 
553
  # =========================
554
- # Buttons
555
  # =========================
556
  def on_restart(st: AppState):
557
  st = _reset_state_for_camera(st)
558
  return (
559
- gr.update(visible=True, value=None), # ✅ 清掉上一張畫面
560
- gr.update(value=_hint_html("等待影像…(尚未開始串流)")),
561
- gr.update(value=_score_radio_value(3)),
562
- gr.update(value=_camera_hint_before_start()),
563
  st,
564
- gr.update(value="重新攝影機辨識"),
565
  )
566
 
 
567
  def on_stop(st: AppState):
568
  st.running = False
569
  st.finished = True
570
  if st.final_emo is None:
571
  return (
572
- gr.update(visible=False, value=None),
573
  gr.update(value=_hint_html("已停止辨識。")),
574
  gr.update(value=_score_radio_value(3)),
575
  gr.update(value=_camera_hint_stopped()),
576
  st,
577
  gr.update(value="重新攝影機辨識"),
578
  )
 
579
  return (
580
- gr.update(visible=False, value=None),
581
  gr.update(value=_result_card_html(st.final_emo, st.final_conf)),
582
  gr.update(value=_score_radio_value(EMO_TO_SCORE.get(st.final_emo, 3))),
583
  gr.update(value=_camera_hint_done()),
@@ -594,7 +480,7 @@ if __name__ == "__main__":
594
  st = gr.State(AppState())
595
 
596
  gr.Markdown("## 情緒辨識")
597
-
598
  hint = gr.HTML(_camera_hint_before_start())
599
 
600
  cam = gr.Image(
 
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
+ # ✅ 避免 css 未定義造成 NameError(不影響功能)
13
+ css = ""
14
+
15
+
16
  # =========================
17
+ # 參數(可微調)
18
  # =========================
19
+ ANALYZE_EVERY_SEC = 0.8
20
+ DOWNSAMPLE_W = 720
21
  EMA_ALPHA = 0.45
22
  CONF_TH = 40.0
23
  SWITCH_CONFIRM_SEC = 2.5
24
  IOU_TH = 0.25
25
+ ZOOM_FACTOR = 1.5
26
 
27
+ DETECTOR_BACKEND = "mtcnn" # 想快一點可改 "opencv"
28
  ALIGN_FACE = True
29
 
 
 
 
 
30
 
31
  # =========================
32
+ # 情緒中文 + 分數映射(7 -> 5)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  # =========================
34
  EMO_ZH = {
35
  "angry": "生氣",
 
42
  "unknown": "未知",
43
  }
44
 
45
+ # 你要的:把 7 種情緒塞進 5 分心情分數
46
  EMO_TO_SCORE = {
47
  "angry": 1,
48
  "disgust": 1,
 
54
  "unknown": 3,
55
  }
56
 
57
+ def get_emotion_score(emo: str) -> int:
58
+ return EMO_TO_SCORE.get(emo, 3)
59
+
60
  SCORE_LABELS = {
61
  1: "1(心情差)",
62
  2: "2(不太好)",
 
72
  # =========================
73
  @dataclass
74
  class AppState:
75
+ mode: str = "攝影機辨識"
76
+
77
  running: bool = True
78
  finished: bool = False
79
  last_analyze_t: float = 0.0
80
 
81
+ # tracking
82
  track_bbox: Optional[Tuple[int, int, int, int]] = None
83
 
84
+ # smoothing
85
  ema_scores: Optional[np.ndarray] = None
86
  emo_keys: List[str] = field(default_factory=list)
87
 
88
+ # stable/candidate
89
  stable_emo: str = "unknown"
90
  candidate_emo: Optional[str] = None
91
  candidate_since: Optional[float] = None
92
 
93
+ # final
94
  final_emo: Optional[str] = None
95
  final_conf: Optional[float] = None
 
96
 
97
+ final_score: int = 3
 
98
 
99
 
100
  # =========================
101
+ # UI HTML (強制黑色文字)
102
  # =========================
103
  def _hint_html(msg: str) -> str:
104
+ # 加入 color:#000000 強制黑色
105
  return f"""
106
  <div style="border-radius:14px;padding:14px;border:1px dashed #DADADA;background:#FAFAFA;color:#000000;">
107
  {msg}
108
  </div>
109
  """
110
 
111
+
112
  def _camera_hint_before_start() -> str:
113
  return _hint_html(
114
  "請先按「Click to access webcam / 允許」開啟攝影機;"
115
  "接著,請按「錄製(Record)」開始。"
116
  )
117
 
118
+
119
  def _camera_hint_done() -> str:
120
  return _hint_html("已完成辨識,可按「重新攝影機辨識」再次進行辨識。")
121
 
122
+
123
  def _camera_hint_stopped() -> str:
124
  return _hint_html("已停止辨識。可按「重新攝影機辨識」再試一次。")
125
 
126
+
127
  def _result_card_html(emo_key: str, conf: Optional[float]) -> str:
128
  zh = EMO_ZH.get(emo_key, emo_key)
129
  score = EMO_TO_SCORE.get(emo_key, 3)
130
  conf_txt = "" if conf is None else f"{conf:.1f}%"
131
  score_desc = SCORE_LABELS[score].split("(")[1].rstrip(")")
132
+
133
+ # ✅ 強制設定 color: #000000
134
  return f"""
135
+ <div style="
136
+ border-radius:16px;
137
+ padding:20px;
138
+ border:1px solid #E6E6E6;
139
+ background:#FFFFFF;
140
+ color:#000000;
141
+ ">
142
+ <div style="font-size:14px;color:#000000;margin-bottom:8px;">
143
+ 辨識結果
144
+ </div>
145
+ <div style="
146
+ font-size:42px;
147
+ font-weight:800;
148
+ line-height:1.1;
149
+ margin-bottom:14px;
150
+ color:#000000;
151
+ ">
152
+ {zh}
153
+ </div>
154
+ <div style="font-size:16px;color:#000000;margin-bottom:6px;">
155
+ 心情分數:{score}({score_desc})
156
+ </div>
157
+ <div style="font-size:14px;color:#000000;">
158
+ 信心值:{conf_txt}
159
+ </div>
160
  </div>
161
  """
162
 
163
+
164
  def _score_radio_value(score: int) -> str:
165
  score = int(score)
166
  score = min(5, max(1, score))
167
  return SCORE_LABELS[score]
168
 
169
 
 
 
 
170
  def _downsample_rgb(frame: np.ndarray, target_w: int) -> np.ndarray:
171
  if frame is None:
172
  return None
 
180
  return np.array(img)
181
 
182
  def _zoom_center(frame: np.ndarray, zoom: float) -> np.ndarray:
183
+ """
184
+ 裁切畫面中心以模擬數位變焦。
185
+ zoom: 放大倍率 (例如 1.5)
186
+ """
187
  if frame is None or zoom <= 1.0:
188
  return frame
189
+
190
  h, w = frame.shape[:2]
191
+
192
+ # 計算新的寬高
193
  new_w = int(w / zoom)
194
  new_h = int(h / zoom)
195
+
196
+ # 計算起始點 (讓裁切框置中)
197
  start_x = (w - new_w) // 2
198
  start_y = (h - new_h) // 2
199
+
200
+ # 進行裁切
201
+ cropped = frame[start_y : start_y + new_h, start_x : start_x + new_w]
202
+ return cropped
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
 
204
 
 
 
 
205
  def _iou(a: Tuple[int, int, int, int], b: Tuple[int, int, int, int]) -> float:
206
  ax, ay, aw, ah = a
207
  bx, by, bw, bh = b
 
217
  union = aw * ah + bw * bh - inter
218
  return inter / max(1e-6, union)
219
 
220
+
221
+ def _pick_face_by_tracking(
222
+ faces: List[Dict],
223
+ prev_bbox: Optional[Tuple[int, int, int, int]]
224
+ ) -> Tuple[Optional[Dict], Optional[Tuple[int, int, int, int]]]:
225
  if not faces:
226
  return None, None
227
+
228
  cand = []
229
  for f in faces:
230
  fa = f.get("facial_area", {}) or {}
 
266
  st.final_emo = None
267
  st.final_conf = None
268
  st.final_score = 3
 
 
269
  return st
270
 
271
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
272
  # =========================
273
+ # Camera streaming
274
  # =========================
275
  def on_stream(frame_rgb: np.ndarray, st: AppState):
276
  if st.finished or (not st.running):
277
  cam_visible = False
278
+
279
  if st.final_emo:
280
+ result_html = _result_card_html(st.final_emo, st.final_conf)
281
+ mood_val = _score_radio_value(EMO_TO_SCORE.get(st.final_emo, 3))
282
+ hint_html = _camera_hint_done()
283
+ else:
284
+ result_html = _hint_html("尚未完成辨識。")
285
+ mood_val = _score_radio_value(3)
286
+ hint_html = _camera_hint_stopped()
287
+
288
  return (
289
  gr.update(visible=cam_visible),
290
+ gr.update(value=result_html),
291
+ gr.update(value=mood_val),
292
+ gr.update(value=hint_html),
293
  st,
294
  gr.update(value="重新攝影機辨識"),
295
  )
 
303
  st,
304
  gr.update(value="重新攝影機辨識"),
305
  )
306
+
307
  frame_rgb = _zoom_center(frame_rgb, ZOOM_FACTOR)
 
308
 
309
+ now = time.time()
 
 
 
 
310
  if now - st.last_analyze_t < ANALYZE_EVERY_SEC:
311
+ show = st.stable_emo or "unknown"
312
  return (
313
+ gr.update(visible=True),
314
+ gr.update(value=_result_card_html(show, st.final_conf)),
315
+ gr.update(value=_score_radio_value(EMO_TO_SCORE.get(show, 3))),
316
  gr.update(value=_camera_hint_before_start()),
317
  st,
318
  gr.update(value="重新攝影機辨識"),
319
  )
320
 
 
321
  st.last_analyze_t = now
 
322
 
323
+ small = _downsample_rgb(frame_rgb, DOWNSAMPLE_W)
 
 
 
 
 
 
 
 
324
 
325
+ # ✅ 這裡固定 enforce_detection=False(避免沒臉就丟例外,造成卡頓/誤判)
326
+ faces = DeepFace.extract_faces(
327
+ img_path=small,
328
+ detector_backend=DETECTOR_BACKEND,
329
+ enforce_detection=False,
330
+ align=ALIGN_FACE,
331
+ )
332
  pick, bbox = _pick_face_by_tracking(faces, st.track_bbox)
 
333
  if pick is None or bbox is None or pick.get("face") is None:
334
+ show = st.stable_emo or "unknown"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
335
  return (
336
+ gr.update(visible=True),
337
+ gr.update(value=_result_card_html(show, st.final_conf)),
338
+ gr.update(value=_score_radio_value(EMO_TO_SCORE.get(show, 3))),
339
  gr.update(value=_camera_hint_before_start()),
340
  st,
341
  gr.update(value="重新攝影機辨識"),
342
  )
343
 
 
 
 
 
 
344
  st.track_bbox = bbox
 
 
 
 
 
 
 
 
 
 
 
 
 
345
  face = pick["face"]
346
  if face.dtype != np.uint8:
347
  face = np.clip(face * 255.0, 0, 255).astype(np.uint8)
348
 
349
+ # ✅ 這裡也固定 enforce_detection=False(避免偶發抓不到臉時丟例外)
350
+ result = DeepFace.analyze(
351
+ img_path=face,
352
+ actions=["emotion"],
353
+ enforce_detection=False,
354
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
355
  if isinstance(result, list):
356
  result = result[0]
357
  emo_dict = result.get("emotion", None)
358
+
359
  if not isinstance(emo_dict, dict) or len(emo_dict) == 0:
360
+ show = st.stable_emo or "unknown"
361
  return (
362
+ gr.update(visible=True),
363
+ gr.update(value=_result_card_html(show, st.final_conf)),
364
+ gr.update(value=_score_radio_value(EMO_TO_SCORE.get(show, 3))),
365
  gr.update(value=_camera_hint_before_start()),
366
  st,
367
  gr.update(value="重新攝影機辨識"),
 
371
  top_conf = float(emo_dict[top_key])
372
 
373
  if top_conf < CONF_TH:
374
+ show = st.stable_emo or "unknown"
375
  return (
376
+ gr.update(visible=True),
377
+ gr.update(value=_result_card_html(show, st.final_conf)),
378
+ gr.update(value=_score_radio_value(EMO_TO_SCORE.get(show, 3))),
379
  gr.update(value=_camera_hint_before_start()),
380
  st,
381
  gr.update(value="重新攝影機辨識"),
 
394
  stable_key = st.emo_keys[stable_idx]
395
  st.stable_emo = stable_key
396
 
397
+ # 延遲確認
398
  if st.candidate_emo != stable_key:
399
  st.candidate_emo = stable_key
400
  st.candidate_since = now
 
411
  st.final_emo = stable_key
412
  st.final_conf = top_conf
413
  st.final_score = EMO_TO_SCORE.get(stable_key, 3)
414
+
415
  st.running = False
416
  st.finished = True
417
+
418
  return (
419
  gr.update(visible=False),
420
  gr.update(value=_result_card_html(stable_key, top_conf)),
 
424
  gr.update(value="重新攝影機辨識"),
425
  )
426
 
 
427
  return (
428
+ gr.update(visible=True),
429
  gr.update(value=_result_card_html(stable_key, top_conf)),
430
  gr.update(value=_score_radio_value(EMO_TO_SCORE.get(stable_key, 3))),
431
  gr.update(value=_camera_hint_before_start()),
 
435
 
436
 
437
  # =========================
438
+ # Mode / Buttons
439
  # =========================
440
  def on_restart(st: AppState):
441
  st = _reset_state_for_camera(st)
442
  return (
443
+ gr.update(visible=True),
444
+ gr.update(value=_hint_html("等待影像…(尚未開始串流)")),
445
+ gr.update(value=_score_radio_value(3)),
446
+ gr.update(value=_camera_hint_before_start()),
447
  st,
448
+ gr.update(value="重新攝影機辨識"),
449
  )
450
 
451
+
452
  def on_stop(st: AppState):
453
  st.running = False
454
  st.finished = True
455
  if st.final_emo is None:
456
  return (
457
+ gr.update(visible=False),
458
  gr.update(value=_hint_html("已停止辨識。")),
459
  gr.update(value=_score_radio_value(3)),
460
  gr.update(value=_camera_hint_stopped()),
461
  st,
462
  gr.update(value="重新攝影機辨識"),
463
  )
464
+
465
  return (
466
+ gr.update(visible=False),
467
  gr.update(value=_result_card_html(st.final_emo, st.final_conf)),
468
  gr.update(value=_score_radio_value(EMO_TO_SCORE.get(st.final_emo, 3))),
469
  gr.update(value=_camera_hint_done()),
 
480
  st = gr.State(AppState())
481
 
482
  gr.Markdown("## 情緒辨識")
483
+
484
  hint = gr.HTML(_camera_hint_before_start())
485
 
486
  cam = gr.Image(