YuAnTsai commited on
Commit
fff66be
·
verified ·
1 Parent(s): 590a359

Update emotion.py

Browse files
Files changed (1) hide show
  1. emotion.py +82 -134
emotion.py CHANGED
@@ -1,175 +1,123 @@
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
  # =========================
13
  ANALYZE_EVERY_SEC = 0.8
14
  DOWNSAMPLE_W = 720
15
  EMA_ALPHA = 0.45
16
  CONF_TH = 40.0
17
  SWITCH_CONFIRM_SEC = 2.5
18
- ZOOM_FACTOR = 1.3
 
 
 
 
 
19
 
20
  # =========================
21
- # 狀態與映射
22
  # =========================
23
- EMO_ZH = {"angry": "生氣", "disgust": "厭惡", "fear": "害怕", "happy": "開心", "sad": "難過", "surprise": "驚訝", "neutral": "平靜", "unknown": "未知"}
24
- EMO_TO_SCORE = {"angry": 1, "disgust": 1, "fear": 1, "sad": 2, "neutral": 3, "surprise": 4, "happy": 5, "unknown": 3}
25
- SCORE_LABELS = {i: f"{i}({desc})" for i, desc in zip(range(1,6), ["心情差","不太好","普通","不錯","超棒"])}
26
- SCORE_CHOICES = [SCORE_LABELS[i] for i in range(1,6)]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
 
 
 
28
  @dataclass
29
  class AppState:
 
 
30
  running: bool = True
31
  finished: bool = False
32
  last_analyze_t: float = 0.0
33
- last_check_t: float = 0.0
34
- is_aligned: bool = False
 
 
 
35
  ema_scores: Optional[np.ndarray] = None
36
  emo_keys: List[str] = field(default_factory=list)
 
 
37
  stable_emo: str = "unknown"
38
  candidate_emo: Optional[str] = None
39
  candidate_since: Optional[float] = None
 
 
40
  final_emo: Optional[str] = None
41
  final_conf: Optional[float] = None
42
 
 
 
 
43
  # =========================
44
- # UI 介面
45
  # =========================
46
  def _hint_html(msg: str) -> str:
47
- return f'<div style="border-radius:14px;padding:14px;border:1px dashed #DADADA;background:#FAFAFA;color:#000000;text-align:center;">{msg}</div>'
48
-
49
- def _result_card_html(emo_key: str, conf: Optional[float]) -> str:
50
- zh = EMO_ZH.get(emo_key, emo_key)
51
- score = EMO_TO_SCORE.get(emo_key, 3)
52
- conf_txt = f"{conf:.1f}%" if conf else "--%"
53
  return f"""
54
- <div style="border-radius:16px;padding:30px;border:2px solid #4CAF50;background:#FFFFFF;color:#000000;text-align:center;box-shadow: 0 4px 10px rgba(0,0,0,0.1);">
55
- <div style="font-size:18px;margin-bottom:10px;color:#666;">✨ 辨識完成 ✨</div>
56
- <div style="font-size:56px;font-weight:800;color:#2E7D32;margin-bottom:15px;">{zh}</div>
57
- <div style="font-size:20px;margin-bottom:10px;">心情分數:<strong>{score}</strong></div>
58
- <div style="font-size:16px;color:#888;">系統信心值:{conf_txt}</div>
59
  </div>
60
  """
61
 
62
- def _draw_ui_overlay(frame: np.ndarray, is_aligned: bool):
63
- canvas = frame.copy()
64
- h, w = canvas.shape[:2]
65
- bw, bh = int(w * 0.45), int(h * 0.55)
66
- x1, y1 = (w - bw) // 2, (h - bh) // 2
67
- x2, y2 = x1 + bw, y1 + bh
68
- color = (0, 255, 0) if is_aligned else (255, 0, 0)
69
- text = "SCANNING..." if is_aligned else "PLACE FACE HERE"
70
- cv2.rectangle(canvas, (x1, y1), (x2, y2), color, 2)
71
- l = 40
72
- cv2.line(canvas, (x1, y1), (x1+l, y1), color, 5); cv2.line(canvas, (x1, y1), (x1, y1+l), color, 5)
73
- cv2.line(canvas, (x2, y2), (x2-l, y2), color, 5); cv2.line(canvas, (x2, y2), (x2, y2-l), color, 5)
74
- cv2.putText(canvas, text, (x1, y1 - 15), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2)
75
- return canvas
76
 
77
- # =========================
78
- # 核心串流邏輯
79
- # =========================
80
- def on_stream(frame_rgb: np.ndarray, st: AppState):
81
- if frame_rgb is None or st.finished or not st.running:
82
- # 當 finished 為 True 時,這裡會被觸發,返回關閉攝影機的指令
83
- return (gr.update(visible=False), gr.update(), gr.update(), gr.update(), st)
84
-
85
- now = time.time()
86
- # 數位變焦
87
- h, w = frame_rgb.shape[:2]
88
- nw, nh = int(w / ZOOM_FACTOR), int(h / ZOOM_FACTOR)
89
- sx, sy = (w - nw) // 2, (h - nh) // 2
90
- frame_rgb = frame_rgb[sy:sy+nh, sx:sx+nw]
91
-
92
- # 每 0.3 秒檢查一次臉部位置
93
- if now - st.last_check_t > 0.3:
94
- st.last_check_t = now
95
- try:
96
- small = np.array(Image.fromarray(frame_rgb).resize((200, 200)))
97
- faces = DeepFace.extract_faces(img_path=small, detector_backend="opencv", enforce_detection=False)
98
- if faces and faces[0]['face'] is not None:
99
- fa = faces[0]['facial_area']
100
- fx, fy = fa['x'] * (frame_rgb.shape[1]/200), fa['y'] * (frame_rgb.shape[0]/200)
101
- fw, fh = fa['w'] * (frame_rgb.shape[1]/200), fa['h'] * (frame_rgb.shape[0]/200)
102
- gx1, gy1 = (frame_rgb.shape[1] - int(frame_rgb.shape[1]*0.45))//2, (frame_rgb.shape[0] - int(frame_rgb.shape[0]*0.55))//2
103
- gx2, gy2 = gx1 + int(frame_rgb.shape[1]*0.45), gy1 + int(frame_rgb.shape[0]*0.55)
104
- st.is_aligned = (gx1 < fx + fw/2 < gx2) and (gy1 < fy + fh/2 < gy2)
105
- else:
106
- st.is_aligned = False
107
- except:
108
- st.is_aligned = False
109
-
110
- frame_with_ui = _draw_ui_overlay(frame_rgb, st.is_aligned)
111
-
112
- # 分析邏輯
113
- if st.is_aligned and (now - st.last_analyze_t >= ANALYZE_EVERY_SEC):
114
- st.last_analyze_t = now
115
- try:
116
- res = DeepFace.analyze(img_path=frame_rgb, actions=["emotion"], enforce_detection=False, detector_backend="opencv")
117
- emo_dict = res[0].get("emotion") if isinstance(res, list) else res.get("emotion")
118
- if emo_dict:
119
- keys = list(emo_dict.keys())
120
- vec = np.array([float(emo_dict[k]) for k in keys])
121
- if st.ema_scores is None: st.ema_scores, st.emo_keys = vec, keys
122
- else: st.ema_scores = EMA_ALPHA * vec + (1.0 - EMA_ALPHA) * st.ema_scores
123
-
124
- stable_key = st.emo_keys[np.argmax(st.ema_scores)]
125
- st.stable_emo = stable_key
126
-
127
- if st.candidate_emo != stable_key:
128
- st.candidate_emo, st.candidate_since = stable_key, now
129
- elif st.candidate_since and (now - st.candidate_since >= SWITCH_CONFIRM_SEC):
130
- # 【關鍵點】辨識成功,設定 finished 並關閉攝像頭
131
- st.final_emo, st.final_conf, st.running, st.finished = stable_key, float(emo_dict[stable_key]), False, True
132
- return (
133
- gr.update(visible=False), # 隱藏攝像頭
134
- _result_card_html(stable_key, st.final_conf), # 跳出大卡片
135
- SCORE_LABELS[EMO_TO_SCORE.get(stable_key, 3)], # 更新分數按鈕
136
- _hint_html("辨識完成!"), # 更新提示文字
137
- st
138
- )
139
- except:
140
- pass
141
-
142
- return (frame_with_ui, gr.update(value=_result_card_html(st.stable_emo, None)), gr.update(), gr.update(), st)
143
 
144
- # =========================
145
- # 按鈕動作
146
- # =========================
147
- def on_restart(st: AppState):
148
- st.running, st.finished, st.ema_scores, st.stable_emo = True, False, None, "unknown"
149
- return (gr.update(visible=True), _hint_html("請將臉部對準方框"), SCORE_LABELS[3], st)
150
 
151
- # =========================
152
- # UI 配置
153
- # =========================
154
- with gr.Blocks(title="Emotion Detector") as demo:
155
- state = gr.State(AppState())
156
- gr.Markdown("## 情緒辨識系統")
157
-
158
- hint = gr.HTML(_hint_html("請點擊下方錄製按鈕開始辨識"))
159
-
160
- with gr.Column(elem_id="main-container"):
161
- cam = gr.Image(sources=["webcam"], streaming=True, type="numpy", label="攝影機預覽")
162
- result_area = gr.HTML(_hint_html("辨識結果將在此顯示"))
163
-
164
- with gr.Row():
165
- btn_restart = gr.Button("重新辨識 / 開啟攝影機", variant="primary")
166
- btn_stop = gr.Button("停止", variant="secondary")
167
-
168
- mood = gr.Radio(choices=SCORE_CHOICES, value=SCORE_LABELS[3], label="判定心情", interactive=False)
169
-
170
- cam.stream(on_stream, [cam, state], [cam, result_area, mood, hint, state], show_progress="minimal")
171
- btn_restart.click(on_restart, [state], [cam, hint, mood, state])
172
- btn_stop.click(lambda st: (gr.update(visible=False), _hint_html("已停止"), st), [state], [cam, hint, state])
173
-
174
- if __name__ == "__main__":
175
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
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, ImageDraw
8
+
9
  from deepface import DeepFace
10
 
11
+
12
  # =========================
13
+ # 參數(可微調)
14
  # =========================
15
  ANALYZE_EVERY_SEC = 0.8
16
  DOWNSAMPLE_W = 720
17
  EMA_ALPHA = 0.45
18
  CONF_TH = 40.0
19
  SWITCH_CONFIRM_SEC = 2.5
20
+ IOU_TH = 0.25
21
+ ZOOM_FACTOR = 1.5
22
+
23
+ DETECTOR_BACKEND = "mtcnn" # 想快一點可改 "opencv"
24
+ ALIGN_FACE = True
25
+
26
 
27
  # =========================
28
+ # 情緒中文 + 分數映射(7 -> 5)
29
  # =========================
30
+ EMO_ZH = {
31
+ "angry": "生氣",
32
+ "disgust": "厭惡",
33
+ "fear": "害怕",
34
+ "happy": "開心",
35
+ "sad": "難過",
36
+ "surprise": "驚訝",
37
+ "neutral": "平靜",
38
+ "unknown": "未知",
39
+ }
40
+
41
+ # 你要的:把 7 種情緒塞進 5 分心情分數
42
+ EMO_TO_SCORE = {
43
+ "angry": 1,
44
+ "disgust": 1,
45
+ "fear": 1,
46
+ "sad": 2,
47
+ "neutral": 3,
48
+ "surprise": 4,
49
+ "happy": 5,
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(不太好)",
59
+ 3: "3(普通)",
60
+ 4: "4(不錯)",
61
+ 5: "5(超棒)",
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
+ # UI HTML (強制黑色文字)
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])