PhilipL commited on
Commit
3b344b0
·
verified ·
1 Parent(s): e246e1d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +250 -356
app.py CHANGED
@@ -1,373 +1,267 @@
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
- # =========================
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
-
22
- # 建議改為 "opencv" 穩定性較高,若想維持原狀可改回 "mtcnn"
23
- DETECTOR_BACKEND = "opencv"
24
- ALIGN_FACE = True
25
-
26
-
27
- # =========================
28
- # 情緒中文 + 分數映射
29
- # =========================
30
- EMO_ZH = {
31
- "angry": "生氣",
32
- "disgust": "厭惡",
33
- "fear": "害怕",
34
- "happy": "開心",
35
- "sad": "難過",
36
- "surprise": "驚訝",
37
- "neutral": "平靜",
38
- "unknown": "未知",
39
- }
40
-
41
- EMO_TO_SCORE = {
42
- "angry": 1,
43
- "disgust": 1,
44
- "fear": 1,
45
- "sad": 2,
46
- "neutral": 3,
47
- "surprise": 4,
48
- "happy": 5,
49
- "unknown": 3,
50
- }
51
-
52
- # ### [整合需求 新增] ###
53
- def get_emotion_score(emo: str) -> int:
54
- return EMO_TO_SCORE.get(emo, 3)
55
- # ######################
56
-
57
- SCORE_LABELS = {
58
- 1: "1(心情差)",
59
- 2: "2(不太好)",
60
- 3: "3(普通)",
61
- 4: "4(不錯)",
62
- 5: "5(超棒)",
63
- }
64
- SCORE_CHOICES = [SCORE_LABELS[i] for i in [1, 2, 3, 4, 5]]
65
-
66
-
67
- # =========================
68
- # 狀態
69
- # =========================
70
- @dataclass
71
- class AppState:
72
- mode: str = "攝影機辨識"
73
-
74
- running: bool = True
75
- finished: bool = False
76
- last_analyze_t: float = 0.0
77
-
78
- # tracking
79
- track_bbox: Optional[Tuple[int, int, int, int]] = None
80
-
81
- # smoothing
82
- ema_scores: Optional[np.ndarray] = None
83
- emo_keys: List[str] = field(default_factory=list)
84
-
85
- # stable/candidate
86
- stable_emo: str = "unknown"
87
- candidate_emo: Optional[str] = None
88
- candidate_since: Optional[float] = None
89
-
90
- # final
91
- final_emo: Optional[str] = None
92
- final_conf: Optional[float] = None
93
-
94
- # ### [整合需求 新增] 用來儲存整數分數 ###
95
- final_score: int = 3
96
- # ######################
97
-
98
-
99
- # =========================
100
- # UI HTML
101
- # =========================
102
- def _hint_html(msg: str) -> str:
103
- return f"""<div style="border-radius:14px;padding:14px;border:1px dashed #DADADA;background:#FAFAFA;color:#111;">{msg}</div>"""
104
-
105
- def _camera_hint_before_start() -> str:
106
- return _hint_html("請先按「Click to access webcam / 允許」開啟攝影機;接著,請按「錄製(Record)」開始。")
107
-
108
- def _camera_hint_done() -> str:
109
- return _hint_html("已完成辨識,可按「重新攝影機辨識」再次進行辨識。")
110
-
111
- def _camera_hint_stopped() -> str:
112
- return _hint_html("已停止辨識。可按「重新攝影機辨識」再試一次。")
113
-
114
- def _upload_hint_before() -> str:
115
- return _hint_html("請上傳一張清楚的臉部照片(臉越大越準)。")
116
-
117
- def _upload_hint_done() -> str:
118
- return _hint_html("已完成圖片辨識,可按「重新上傳圖片辨識」再次辨識。")
119
-
120
- def _upload_hint_stopped() -> str:
121
- return _hint_html("已停止圖片辨識。可按「重新上傳圖片辨識」再試一次。")
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
- return f"""
130
- <div style="border-radius:16px;padding:20px;border:1px solid #E6E6E6;background:#FFFFFF;color:#111;">
131
- <div style="font-size:14px;color:#444;margin-bottom:8px;">辨識結果</div>
132
- <div style="font-size:42px;font-weight:800;line-height:1.1;margin-bottom:14px;color:#000;">{zh}</div>
133
- <div style="font-size:16px;color:#111;margin-bottom:6px;">心情分數:<b>{score}</b>({score_desc})</div>
134
- <div style="font-size:14px;color:#111;">信心值:{conf_txt}</div>
135
- </div>
136
- """
137
-
138
- def _score_radio_value(score: int) -> str:
139
- score = int(score)
140
- score = min(5, max(1, score))
141
- return SCORE_LABELS[score]
142
-
143
- def _downsample_rgb(frame: np.ndarray, target_w: int) -> np.ndarray:
144
- if frame is None: return None
145
- h, w = frame.shape[:2]
146
- if w <= target_w: return frame
147
- scale = target_w / w
148
- new_h = max(1, int(h * scale))
149
- img = Image.fromarray(frame)
150
- img = img.resize((target_w, new_h))
151
- return np.array(img)
152
-
153
- def _iou(a, b) -> float:
154
- ax, ay, aw, ah = a
155
- bx, by, bw, bh = b
156
- ax2, ay2 = ax + aw, ay + ah
157
- bx2, by2 = bx + bw, by + bh
158
- ix1, iy1 = max(ax, bx), max(ay, by)
159
- ix2, iy2 = min(ax2, bx2), min(ay2, by2)
160
- iw, ih = max(0, ix2 - ix1), max(0, iy2 - iy1)
161
- inter = iw * ih
162
- if inter <= 0: return 0.0
163
- union = aw * ah + bw * bh - inter
164
- return inter / max(1e-6, union)
165
-
166
- def _pick_face_by_tracking(faces, prev_bbox):
167
- if not faces: return None, None
168
- cand = []
169
- for f in faces:
170
- fa = f.get("facial_area", {}) or {}
171
- x, y, w, h = int(fa.get("x",0)), int(fa.get("y",0)), int(fa.get("w",0)), int(fa.get("h",0))
172
- if w > 0 and h > 0 and f.get("face") is not None:
173
- cand.append((f, (x, y, w, h), w * h))
174
- if not cand: return None, None
175
- if prev_bbox is not None:
176
- best, best_i = None, 0.0
177
- for f, bb, area in cand:
178
- i = _iou(prev_bbox, bb)
179
- if i > best_i: best_i = i; best = (f, bb)
180
- if best is not None and best_i >= IOU_TH: return best[0], best[1]
181
- cand.sort(key=lambda x: x[2], reverse=True)
182
- return cand[0][0], cand[0][1]
183
-
184
- def _reset_state_for_camera(st: AppState) -> AppState:
185
- st.running = True; st.finished = False; st.last_analyze_t = 0.0
186
- st.track_bbox = None; st.ema_scores = None; st.emo_keys = []
187
- st.stable_emo = "unknown"; st.candidate_emo = None; st.candidate_since = None
188
- st.final_emo = None; st.final_conf = None
189
- # ### [整合需求] 重置分數
190
- st.final_score = 3
191
- return st
192
-
193
- def _reset_state_for_upload(st: AppState) -> AppState:
194
- st.running = False; st.finished = False; st.last_analyze_t = 0.0
195
- st.track_bbox = None; st.ema_scores = None; st.emo_keys = []
196
- st.stable_emo = "unknown"; st.candidate_emo = None; st.candidate_since = None
197
- st.final_emo = None; st.final_conf = None
198
- # ### [整合需求] 重置分數
199
- st.final_score = 3
200
- return st
201
-
202
-
203
- # =========================
204
- # Camera streaming
205
- # =========================
206
- def on_stream(frame_rgb: np.ndarray, st: AppState):
207
- if st.mode != "攝影機辨識":
208
- return gr.update(), gr.update(), gr.update(), gr.update(value=_upload_hint_before()), st, gr.update(value="重新上傳圖片辨識")
209
-
210
- if st.finished or (not st.running):
211
- cam_visible = False
212
- if st.final_emo:
213
- result_html = _result_card_html(st.final_emo, st.final_conf)
214
- mood_val = _score_radio_value(EMO_TO_SCORE.get(st.final_emo, 3))
215
- hint_html = _camera_hint_done()
216
- else:
217
- result_html = _hint_html("尚未完成辨識。")
218
- mood_val = _score_radio_value(3)
219
- hint_html = _camera_hint_stopped()
220
- return gr.update(visible=cam_visible), gr.update(value=result_html), gr.update(value=mood_val), gr.update(value=hint_html), st, gr.update(value="重新攝影機辨識")
221
-
222
- if frame_rgb is None:
223
- 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="重新攝影機辨識")
224
-
225
- now = time.time()
226
- if now - st.last_analyze_t < ANALYZE_EVERY_SEC:
227
- show = st.stable_emo or "unknown"
228
- return gr.update(visible=True), gr.update(value=_result_card_html(show, st.final_conf)), gr.update(value=_score_radio_value(EMO_TO_SCORE.get(show, 3))), gr.update(value=_camera_hint_before_start()), st, gr.update(value="重新攝影機辨識")
229
-
230
- st.last_analyze_t = now
231
- small = _downsample_rgb(frame_rgb, DOWNSAMPLE_W)
232
- faces = DeepFace.extract_faces(img_path=small, detector_backend=DETECTOR_BACKEND, enforce_detection=False, align=ALIGN_FACE)
233
- pick, bbox = _pick_face_by_tracking(faces, st.track_bbox)
234
-
235
- if pick is None or bbox is None or pick.get("face") is None:
236
- show = st.stable_emo or "unknown"
237
- return gr.update(visible=True), gr.update(value=_result_card_html(show, st.final_conf)), gr.update(value=_score_radio_value(EMO_TO_SCORE.get(show, 3))), gr.update(value=_camera_hint_before_start()), st, gr.update(value="重新攝影機辨識")
238
-
239
- st.track_bbox = bbox
240
- face = pick["face"]
241
- if face.dtype != np.uint8: face = np.clip(face * 255.0, 0, 255).astype(np.uint8)
242
-
243
- result = DeepFace.analyze(img_path=face, actions=["emotion"], enforce_detection=False)
244
- if isinstance(result, list): result = result[0]
245
- emo_dict = result.get("emotion", None)
246
-
247
- if not isinstance(emo_dict, dict) or len(emo_dict) == 0:
248
- show = st.stable_emo or "unknown"
249
- return gr.update(visible=True), gr.update(value=_result_card_html(show, st.final_conf)), gr.update(value=_score_radio_value(EMO_TO_SCORE.get(show, 3))), gr.update(value=_camera_hint_before_start()), st, gr.update(value="重新攝影機辨識")
250
-
251
- top_key = max(emo_dict, key=lambda k: float(emo_dict[k]))
252
- top_conf = float(emo_dict[top_key])
253
-
254
- if top_conf < CONF_TH:
255
- show = st.stable_emo or "unknown"
256
- return gr.update(visible=True), gr.update(value=_result_card_html(show, st.final_conf)), gr.update(value=_score_radio_value(EMO_TO_SCORE.get(show, 3))), gr.update(value=_camera_hint_before_start()), st, gr.update(value="重新攝影機辨識")
257
-
258
- keys = list(emo_dict.keys())
259
- vec = np.array([float(emo_dict[k]) for k in keys], dtype=np.float32)
260
-
261
- if st.ema_scores is None or st.emo_keys != keys:
262
- st.ema_scores = vec; st.emo_keys = keys
263
  else:
264
- st.ema_scores = EMA_ALPHA * vec + (1.0 - EMA_ALPHA) * st.ema_scores
265
-
266
- stable_idx = int(np.argmax(st.ema_scores))
267
- stable_key = st.emo_keys[stable_idx]
268
- st.stable_emo = stable_key
269
-
270
- if st.candidate_emo != stable_key:
271
- st.candidate_emo = stable_key; st.candidate_since = now
 
 
272
  else:
273
- if st.candidate_since is None: st.candidate_since = now
274
-
275
- confirmed = (st.candidate_since is not None and (now - st.candidate_since) >= SWITCH_CONFIRM_SEC)
276
-
277
- if confirmed and st.final_emo is None:
278
- st.final_emo = stable_key; st.final_conf = top_conf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
279
 
280
- # ### [整合需求] 存入分數 ###
281
- st.final_score = EMO_TO_SCORE.get(stable_key, 3)
282
- # #######################
283
 
284
- st.running = False; st.finished = True
285
- return gr.update(visible=False), 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="重新攝影機辨識")
286
-
287
- return gr.update(visible=True), 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_before_start()), st, gr.update(value="重新攝影機辨識")
288
-
289
 
290
- # =========================
291
- # Upload image
292
- # =========================
293
- def on_upload(img: np.ndarray, st: AppState):
294
- if st.mode != "上傳圖片辨識":
295
- return gr.update(), gr.update(), st, gr.update(value=_camera_hint_before_start()), gr.update(value="重新攝影機辨識")
296
-
297
- st = _reset_state_for_upload(st)
298
- if img is None:
299
- return gr.update(value=_upload_hint_before()), gr.update(value=_score_radio_value(3)), st, gr.update(value=_upload_hint_before()), gr.update(value="重新上傳圖片辨識")
300
-
301
- # ### [修正] 圖片格式處理 (解決 PNG/灰階 問題) ###
302
- if img.ndim == 2:
303
- img = np.stack([img, img, img], axis=-1)
304
- if img.shape[-1] == 4:
305
- img = img[:, :, :3]
306
- # ###########################################
307
 
308
- small = _downsample_rgb(img, DOWNSAMPLE_W)
309
- faces = DeepFace.extract_faces(img_path=small, detector_backend=DETECTOR_BACKEND, enforce_detection=False, align=ALIGN_FACE)
310
- pick, bbox = _pick_face_by_tracking(faces, None)
 
 
 
311
 
312
- if pick is None or pick.get("face") is None:
313
- return gr.update(value=_hint_html("沒有偵測到人臉,請換一張更清楚、臉更大的照片。")), gr.update(value=_score_radio_value(3)), st, gr.update(value=_upload_hint_before()), gr.update(value="重新上傳圖片辨識")
314
 
315
- face = pick["face"]
316
- if face.dtype != np.uint8: face = np.clip(face * 255.0, 0, 255).astype(np.uint8)
317
 
318
- result = DeepFace.analyze(img_path=face, actions=["emotion"], enforce_detection=False)
319
- if isinstance(result, list): result = result[0]
320
- emo_dict = result.get("emotion", None)
321
- if not isinstance(emo_dict, dict) or len(emo_dict) == 0:
322
- return gr.update(value=_hint_html("辨識失敗,請換一張照片再試一次。")), gr.update(value=_score_radio_value(3)), st, gr.update(value=_upload_hint_before()), gr.update(value="重新上傳圖片辨識")
323
 
324
- top_key = max(emo_dict, key=lambda k: float(emo_dict[k]))
325
- top_conf = float(emo_dict[top_key])
326
 
327
- st.final_emo = top_key; st.final_conf = top_conf
328
-
329
- # ### [整合需求] 存入分數 ###
330
- st.final_score = EMO_TO_SCORE.get(top_key, 3)
331
- # #######################
332
 
333
- st.finished = True
334
- return gr.update(value=_result_card_html(top_key, top_conf)), gr.update(value=_score_radio_value(EMO_TO_SCORE.get(top_key, 3))), st, gr.update(value=_upload_hint_done()), gr.update(value="重新上傳圖片辨識")
335
-
336
-
337
- # =========================
338
- # Mode / Buttons
339
- # =========================
340
- def on_mode_change(mode: str, st: AppState):
341
- st.mode = mode
342
- if mode == "攝影機辨識":
343
- st = _reset_state_for_camera(st)
344
- return gr.update(visible=True), gr.update(visible=False, value=None), gr.update(value=_hint_html("等待影像…(尚未開始串流)")), gr.update(value=_score_radio_value(3)), gr.update(value=_camera_hint_before_start()), st, gr.update(value="重新攝影機辨識")
345
- else:
346
- st = _reset_state_for_upload(st)
347
- return gr.update(visible=False), gr.update(visible=True, value=None), gr.update(value=_upload_hint_before()), gr.update(value=_score_radio_value(3)), gr.update(value=_upload_hint_before()), st, gr.update(value="重新上傳圖片辨識")
348
 
349
- def on_restart(st: AppState):
350
- if st.mode == "攝影機辨識":
351
- st = _reset_state_for_camera(st)
352
- 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="重新攝影機辨識"), gr.update()
353
- else:
354
- st = _reset_state_for_upload(st)
355
- return gr.update(), gr.update(value=_upload_hint_before()), gr.update(value=_score_radio_value(3)), gr.update(value=_upload_hint_before()), st, gr.update(value="重新上傳圖片辨識"), gr.update(value=None)
356
-
357
- def on_stop(st: AppState):
358
- if st.mode == "攝影機辨識":
359
- st.running = False; st.finished = True
360
- if st.final_emo is None:
361
- 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="重新攝影機辨識"), gr.update()
362
- return gr.update(visible=False), gr.update(value=_result_card_html(st.final_emo, st.final_conf)), gr.update(value=_score_radio_value(EMO_TO_SCORE.get(st.final_emo, 3))), gr.update(value=_camera_hint_done()), st, gr.update(value="重新攝影機辨識"), gr.update()
363
-
364
- st = _reset_state_for_upload(st)
365
- return gr.update(), gr.update(value=_hint_html("已停止圖片辨識。")), gr.update(value=_score_radio_value(3)), gr.update(value=_upload_hint_stopped()), st, gr.update(value="重新上傳圖片辨識"), gr.update(value=None)
366
-
367
- css = """#app_container { max-width: 960px; margin: 0 auto; } .gradio-container { background: #f1f5f9 !important; }"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
368
 
369
  if __name__ == "__main__":
370
- with gr.Blocks(title="Emotion Detector", css=css) as demo:
371
- # 隊友的單獨測試介面 (略)
372
- pass
373
- # demo.launch()
 
 
 
 
 
1
  import gradio as gr
2
+ from openai import OpenAI
3
+ from huggingface_hub import InferenceClient
4
+ import os
5
+ import time
6
+ import requests
7
+ import urllib.parse
8
+ import pandas as pd
9
+ from langchain_huggingface import HuggingFaceEmbeddings
10
+ from langchain_community.vectorstores import FAISS
11
  from PIL import Image
12
+ from dotenv import load_dotenv
13
+
14
+ # --- 匯入組員的模組 ---
15
+ import emotion
16
+ # ---------------------------
17
+
18
+ load_dotenv()
19
+
20
+ # ==========================================
21
+ # 0. 環境變數 & 1. 系統初始化 (保持不變)
22
+ # ==========================================
23
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
24
+ HF_TOKEN = os.getenv("HF_TOKEN")
25
+
26
+ global_df = None
27
+ global_mood_df = None
28
+ global_retriever = None
29
+ rag_initialized = False
30
+
31
+ def init_rag_system():
32
+ global global_df, global_mood_df, global_retriever, rag_initialized
33
+ if rag_initialized: return
34
+ try:
35
+ global_df = pd.read_csv('restaurants.csv')
36
+ global_df['RAG_Content'] = global_df['RAG_Content'].fillna("")
37
+ global_df['Category'] = global_df['Category'].fillna("其他")
38
+ global_mood_df = pd.read_csv('mood_food_guide.csv')
39
+ except Exception: pass
40
+ if os.path.exists("faiss_index"):
41
+ try:
42
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
43
+ vectorstore = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
44
+ global_retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
45
+ except Exception: pass
46
+ rag_initialized = True
47
+
48
+ # ==========================================
49
+ # 2. 核心功能 (保持不變)
50
+ # ==========================================
51
+ def get_restaurant_data(mood_score_str, food_choice):
52
+ init_rag_system()
53
+ if global_df is None or global_df.empty: return None, True, "資料庫未載入", "無建議"
54
+ try: score = int(str(mood_score_str).split(' ')[0])
55
+ except: score = 3
56
+ mood_info = global_mood_df[global_mood_df['分數'] == score]
57
+ if not mood_info.empty:
58
+ rec_categories = mood_info.iloc[0]['推薦料理類別']
59
+ mood_reason = mood_info.iloc[0]['原因']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  else:
61
+ rec_categories = ""
62
+ mood_reason = "隨意探索"
63
+ candidates = global_df.copy()
64
+ if rec_categories:
65
+ candidates = candidates[candidates['Category'].apply(lambda x: str(x) in str(rec_categories) or str(rec_categories) in str(x))]
66
+ food_keyword = "飯" if food_choice == "吃飯" else "麵" if food_choice == "吃麵" else ""
67
+ if food_keyword:
68
+ candidates = candidates[candidates['Name'].str.contains(food_keyword, case=False, na=False) | candidates['RAG_Content'].str.contains(food_keyword, case=False, na=False)]
69
+ if candidates.empty:
70
+ result = global_df.sample(1).iloc[0]; is_random = True
71
  else:
72
+ result = candidates.sample(1).iloc[0]; is_random = False
73
+ return result, is_random, rec_categories, mood_reason
74
+
75
+ def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, mood_score, mood_guide_reason, debug_mode=False):
76
+ if not GROQ_API_KEY: return "⚠️ 請設定 GROQ_API_KEY"
77
+ client = OpenAI(api_key=GROQ_API_KEY, base_url="https://api.groq.com/openai/v1")
78
+ system_prompt = "你是一個幽默、懂吃且善解人意的 AI 朋友..."
79
+ user_msg = f"【狀態】心情分數:{mood_score}\n【日記】{user_diary}\n【建議原因】{mood_guide_reason}\n【餐廳】{restaurant_name}\n資料:{restaurant_detail}"
80
+ try:
81
+ response = client.chat.completions.create(model="llama-3.3-70b-versatile", messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_msg}])
82
+ return response.choices[0].message.content
83
+ except Exception as e: return f"Groq Error: {str(e)}"
84
+
85
+ def generate_image_huggingface(prompt):
86
+ if not HF_TOKEN: return None
87
+ try:
88
+ hf_client = InferenceClient(token=HF_TOKEN)
89
+ return hf_client.text_to_image(prompt=prompt, model="stabilityai/stable-diffusion-xl-base-1.0")
90
+ except: return None
91
+
92
+ def mood_agent_logic(score_input, food_input, diary_input, debug_mode):
93
+ restaurant, is_random, rec_categories, mood_reason = get_restaurant_data(score_input, food_input)
94
+ if restaurant is None: yield "資料庫讀取錯誤", None, ""; return
95
+ name = restaurant['Name']; address = restaurant['Address']; url = restaurant['URL']; img_prompt = restaurant.get('Visual_prompt')
96
+ rag_info = str(restaurant.get('RAG_Content', ''))
97
+ if global_retriever:
98
+ docs = global_retriever.invoke(name)
99
+ if docs: rag_info = "\n".join([d.page_content for d in docs])
100
+ ai_text = generate_content_with_groq(name, rag_info, diary_input, score_input, mood_reason, debug_mode)
101
+ final_response = f"### 🍽️ 推薦:{name}\n\n{ai_text}"
102
+ map_html = f'<div style="text-align:center"><a href="{url}" target="_blank" style="background:#4CAF50;color:white;padding:8px 16px;border-radius:20px;text-decoration:none">🗺️ Google Map 導航</a></div>'
103
+ yield final_response, None, map_html
104
+ image_output = generate_image_huggingface(img_prompt)
105
+ yield final_response, image_output, map_html
106
+
107
+
108
+ # ==========================================
109
+ # 3. [修正版] 橋接邏輯 (Bridge Functions)
110
+ # ==========================================
111
+
112
+ # 這是 app.py 自己的格式 (注意:這裡是半形括號)
113
+ def _score_to_radio_value(score):
114
+ mapping = {1: "1 (心情差)", 2: "2 (不太好)", 3: "3 (普通)", 4: "4 (不錯)", 5: "5 (超棒)"}
115
+ # 預防萬一 score 是 None 或其他怪怪的值
116
+ try:
117
+ score = int(score)
118
+ except:
119
+ score = 3
120
+ return mapping.get(score, "3 (普通)")
121
+
122
+ # 橋接 1:開始
123
+ def bridge_start_click(st):
124
+ res = emotion.on_restart(st)
125
+ return res[1], res[0], gr.update(visible=True), res[5], res[4]
126
+
127
+ # 橋接 2:停止
128
+ def bridge_stop_click(st):
129
+ res = emotion.on_stop(st)
130
+ return res[1], res[0], gr.update(visible=False), res[5], res[4]
131
+
132
+ # 橋接 3:Webcam 串流 (修正分數填入問題)
133
+ def bridge_predict_frame(frame, st):
134
+ res = emotion.on_stream(frame, st)
135
+
136
+ out_cam = res[0]
137
+ out_result = res[1]
138
+ # out_mood = res[2] # ❌ 我們不使用隊友回傳的 UI 更新,因為括號格式不同
139
+ out_st = res[4]
140
+ out_btn_start = res[5]
141
+
142
+ score_update = gr.update()
143
+ tabs_update = gr.update()
144
+ out_btn_stop = gr.update()
145
+
146
+ # 如果辨識完成,我們自己產生一個符合 app.py 格式的 UI 更新
147
+ if out_st.finished and hasattr(out_st, 'final_score'):
148
+ # ✅ 使用 _score_to_radio_value 將整數轉換為半形括號字串
149
+ new_val = _score_to_radio_value(out_st.final_score)
150
+ score_update = gr.update(value=new_val)
151
 
152
+ tabs_update = gr.Tabs(selected=1)
153
+ out_btn_stop = gr.update(visible=False)
 
154
 
155
+ return out_cam, out_result, out_st, out_btn_stop, out_btn_start, score_update, tabs_update
 
 
 
 
156
 
157
+ # 橋接 4:圖片上傳 (修正分數填入問題)
158
+ def bridge_predict_upload(img, st):
159
+ res = emotion.on_upload(img, st)
160
+
161
+ out_result = res[0]
162
+ # out_mood = res[1] # ❌ 同樣忽略隊友的格式
163
+ out_st = res[2]
164
+
165
+ score_update = gr.update()
166
+ tabs_update = gr.update()
 
 
 
 
 
 
 
167
 
168
+ if out_st.finished and hasattr(out_st, 'final_score'):
169
+ # ✅ 使用 _score_to_radio_value 將整數轉換為半形括號字串
170
+ new_val = _score_to_radio_value(out_st.final_score)
171
+ score_update = gr.update(value=new_val)
172
+
173
+ tabs_update = gr.Tabs(selected=1)
174
 
175
+ return out_result, score_update, tabs_update, out_st
 
176
 
 
 
177
 
178
+ # ==========================================
179
+ # 4. Gradio 介面建構
180
+ # ==========================================
 
 
181
 
182
+ combined_css = emotion.css
 
183
 
184
+ with gr.Blocks(title="AI 心情食堂", css=combined_css) as demo:
 
 
 
 
185
 
186
+ st_state = gr.State(emotion.AppState())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
 
188
+ with gr.Tabs() as tabs:
189
+
190
+ # Tab 1: 情緒辨識
191
+ with gr.TabItem("😊 情緒辨識 (Step 1)", id=0):
192
+ with gr.Column(elem_id="app_container"):
193
+ gr.Markdown("### 第一步:測測你的心情能量\n讓 AI 看看你的表情,自動幫你決定心情分數!(辨識完畢會自動跳轉)")
194
+
195
+ with gr.Row():
196
+ btn_start = gr.Button("📸 開啟攝影機辨識", variant="primary")
197
+ btn_stop = gr.Button("⏹️ 停止", variant="secondary", visible=False)
198
+
199
+ cam = gr.Image(sources=["webcam"], streaming=True, type="numpy", label="攝影機畫面", visible=False)
200
+ result_markdown = gr.Markdown(emotion._hint_html("請按「開啟攝影機辨識」或下方上傳照片。"))
201
+
202
+ gr.Markdown("---")
203
+ gr.Markdown("### 或者:上傳照片")
204
+ upload_img = gr.Image(sources=["upload"], type="numpy", label="上傳照片")
205
+
206
+ # Tab 2: 主功能區
207
+ with gr.TabItem("🍽️ AI 心情食堂 (Step 2)", id=1):
208
+ with gr.Column():
209
+ gr.Markdown(f"## 🍱 今天想吃點什麼?")
210
+ with gr.Row():
211
+ with gr.Column(scale=1):
212
+ # 这里的 Radio 选项使用的是半形括号
213
+ score_input = gr.Radio(
214
+ ["1 (心情差)", "2 (不太好)", "3 (普通)", "4 (不錯)", "5 (超棒)"],
215
+ label="1. 心情分數 (由 Tab 1 自動填入)",
216
+ value="3 (普通)"
217
+ )
218
+ food_input = gr.Radio(["吃飯", "吃麵", "隨便"], label="2. 想吃什麼", value="隨便")
219
+ diary_input = gr.Textbox(lines=4, label="3. 心情日記", placeholder="寫下今天發生的事...")
220
+ debug_mode_btn = gr.Checkbox(label="🔧 開啟除錯模式", value=False)
221
+ submit_btn = gr.Button("🍱 送出給 Agent", variant="primary")
222
+
223
+ with gr.Column(scale=1):
224
+ agent_output = gr.Markdown(label="AI 回應")
225
+ image_output = gr.Image(label="AI 推薦美食圖", type="pil", width=400)
226
+ map_output = gr.HTML(label="地圖導航")
227
+
228
+ # ==========================================
229
+ # 事件綁定
230
+ # ==========================================
231
+
232
+ btn_start.click(
233
+ fn=bridge_start_click,
234
+ inputs=[st_state],
235
+ outputs=[result_markdown, cam, btn_stop, btn_start, st_state],
236
+ show_progress="minimal"
237
+ )
238
+
239
+ btn_stop.click(
240
+ fn=bridge_stop_click,
241
+ inputs=[st_state],
242
+ outputs=[result_markdown, cam, btn_stop, btn_start, st_state],
243
+ show_progress="minimal"
244
+ )
245
+
246
+ cam.stream(
247
+ fn=bridge_predict_frame,
248
+ inputs=[cam, st_state],
249
+ outputs=[cam, result_markdown, st_state, btn_stop, btn_start, score_input, tabs],
250
+ show_progress="minimal"
251
+ )
252
+
253
+ upload_img.change(
254
+ fn=bridge_predict_upload,
255
+ inputs=[upload_img, st_state],
256
+ outputs=[result_markdown, score_input, tabs, st_state],
257
+ show_progress="minimal"
258
+ )
259
+
260
+ submit_btn.click(
261
+ fn=mood_agent_logic,
262
+ inputs=[score_input, food_input, diary_input, debug_mode_btn],
263
+ outputs=[agent_output, image_output, map_output]
264
+ )
265
 
266
  if __name__ == "__main__":
267
+ demo.launch(ssr_mode=False)