PhilipL commited on
Commit
037cd0a
·
verified ·
1 Parent(s): 521d319

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -143
app.py CHANGED
@@ -12,25 +12,21 @@ from dotenv import load_dotenv
12
  # ==========================================
13
  def install_dependencies():
14
  """確保必要套件與瀏覽器核心都有安裝"""
15
- # 1. 檢查並安裝 playwright 套件
16
  try:
17
  import playwright
18
  except ImportError:
19
  print("⚠️ 偵測到缺少 playwright,正在強制安裝...")
20
  subprocess.check_call([sys.executable, "-m", "pip", "install", "playwright"])
21
 
22
- # 2. 設定瀏覽器路徑 (針對 Hugging Face 環境優化)
23
  os.environ["PLAYWRIGHT_BROWSERS_PATH"] = os.path.join(os.getcwd(), "playwright_browsers")
24
 
25
- # 3. 檢查並安裝 Chromium 瀏覽器核心
26
  print("正在檢查 Chromium 瀏覽器...")
27
  try:
28
- # 嘗試執行安裝指令
29
  subprocess.run([sys.executable, "-m", "playwright", "install", "chromium"], check=True)
30
  except Exception as e:
31
  print(f"瀏覽器安裝警告: {e}")
32
 
33
- # 執行依賴檢查
34
  install_dependencies()
35
 
36
  # ==========================================
@@ -44,11 +40,44 @@ from langchain_huggingface import HuggingFaceEmbeddings
44
  from langchain_community.vectorstores import FAISS
45
  from PIL import Image
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  # 嘗試匯入組員的模組
48
  try:
49
- import emotion # 情緒辨識
50
- except ImportError:
51
- print("警告:找不到 emotion 模組,請確保同級目錄下有 emotion.py。")
 
 
52
 
53
  load_dotenv()
54
 
@@ -64,13 +93,11 @@ global_retriever = None
64
  rag_initialized = False
65
 
66
  def init_static_data():
67
- """初始化靜態的心情資料 (心情指南)"""
68
  global global_mood_df
69
  if global_mood_df is None:
70
  try:
71
  global_mood_df = pd.read_csv('mood_food_guide.csv')
72
  except:
73
- # 如果沒有 csv,使用預設資料
74
  global_mood_df = pd.DataFrame({
75
  '分數': [1, 2, 3, 4, 5],
76
  '推薦料理類別': ["療癒系", "暖胃", "隨意", "豐富", "大餐"],
@@ -78,7 +105,7 @@ def init_static_data():
78
  })
79
 
80
  # ==========================================
81
- # 2. Google Maps 爬蟲功能 (取代原本的靜態 CSV)
82
  # ==========================================
83
  def sync_google_maps(url):
84
  global global_df, global_retriever, rag_initialized
@@ -109,7 +136,7 @@ def sync_google_maps(url):
109
  restaurant_list.append({
110
  "Name": name,
111
  "Address": addr,
112
- "Category": "未分類", # 爬蟲暫時無法精確抓取類別,設為預設
113
  "RAG_Content": f"餐廳:{name},資訊:{addr}",
114
  "URL": f"https://www.google.com/search?q={urllib.parse.quote(name)}"
115
  })
@@ -121,7 +148,6 @@ def sync_google_maps(url):
121
 
122
  global_df = pd.DataFrame(restaurant_list)
123
 
124
- # 建立簡易 RAG 索引
125
  try:
126
  embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
127
  vectorstore = FAISS.from_texts(global_df['RAG_Content'].tolist(), embeddings, metadatas=global_df.to_dict('records'))
@@ -138,26 +164,18 @@ def sync_google_maps(url):
138
  # 3. 核心功能 (推薦與生成)
139
  # ==========================================
140
  def get_restaurant_data(mood_score_str, food_choice):
141
- init_static_data() # 確保心情指南已載入
142
-
143
  if global_df is None or global_df.empty:
144
  return None, True, "資料庫未載入", "尚未同步地圖資料", ""
145
 
146
- # 取得所有餐廳名稱供 fallback 參考
147
  all_names = "、".join(global_df['Name'].tolist())
148
-
149
  try: score = int(str(mood_score_str).split(' ')[0])
150
  except: score = 3
151
 
152
  mood_info = global_mood_df[global_mood_df['分數'] == score]
153
- if not mood_info.empty:
154
- mood_reason = mood_info.iloc[0]['原因']
155
- else:
156
- mood_reason = "隨意探索"
157
 
158
  candidates = global_df.copy()
159
-
160
- # 關鍵字篩選
161
  food_keyword = "飯" if food_choice == "吃飯" else "麵" if food_choice == "吃麵" else ""
162
  is_match = True
163
 
@@ -166,47 +184,31 @@ def get_restaurant_data(mood_score_str, food_choice):
166
  if not filtered.empty:
167
  candidates = filtered
168
  else:
169
- is_match = False # 沒找到符合的,但還是會回傳隨機的
170
 
171
  result = candidates.sample(1).iloc[0]
172
  return result, is_match, "個人清單", mood_reason, all_names
173
 
174
  def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, mood_score, mood_guide_reason):
175
  if not GROQ_API_KEY: return "⚠️ 請設定 GROQ_API_KEY"
176
-
177
  client = OpenAI(api_key=GROQ_API_KEY, base_url="https://api.groq.com/openai/v1")
178
 
179
  system_prompt = "你是一個幽默、懂吃且善解人意的 AI 朋友。請根據使用者的日記、心情以及餐廳資訊來推薦。"
180
- user_msg = f"""
181
- 【狀態】心情分數:{mood_score},日記:{user_diary}
182
- 【心情指南建議】原因:「{mood_guide_reason}」。
183
-
184
- 【推薦餐廳】
185
- 名稱:{restaurant_name}
186
- 資料:{restaurant_detail}
187
-
188
- 任務:
189
- 請用繁體中文寫一段溫暖有趣的回覆:
190
- 1. 回應他的日記。
191
- 2. 結合心情指南與這家餐廳的特色進行推薦。
192
- (不需要過長的開頭,直接切入重點)
193
- """
194
  try:
195
  response = client.chat.completions.create(model="llama-3.3-70b-versatile", messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_msg}])
196
- content = response.choices[0].message.content
197
- return content
198
  except Exception as e:
199
  return f"Groq Error: {str(e)}"
200
 
201
  def generate_image_huggingface(prompt):
202
- """使用 Hugging Face 的 SDXL 模型生成圖片"""
203
  if not HF_TOKEN: return None
204
  try:
205
  hf_client = InferenceClient(token=HF_TOKEN)
206
- # 加入負面提示詞以提升品質
207
  return hf_client.text_to_image(
208
  prompt=prompt,
209
- negative_prompt="blurry, low quality, distortion, text, watermark, bad anatomy",
210
  model="stabilityai/stable-diffusion-xl-base-1.0"
211
  )
212
  except Exception as e:
@@ -219,7 +221,6 @@ def mood_agent_logic(score_input, food_input, diary_input, show_prompt):
219
  return
220
 
221
  restaurant, is_match, _, mood_reason, all_names = get_restaurant_data(score_input, food_input)
222
-
223
  if restaurant is None:
224
  yield "資料庫讀取錯誤", None, "", ""
225
  return
@@ -228,88 +229,88 @@ def mood_agent_logic(score_input, food_input, diary_input, show_prompt):
228
  info = restaurant.get('RAG_Content', '')
229
  url = restaurant.get('URL', '#')
230
 
231
- # 處理未命中提示
232
  prefix = ""
233
  if not is_match and food_input != "隨便":
234
  prefix = f"> 💡 **溫馨提示**:清單中暫無『{food_input}』,已從現有名單挑選最適合的店!\n\n"
235
 
236
- # 1. 生成文字
237
  ai_text = generate_content_with_groq(name, info, diary_input, score_input, mood_reason)
238
  final_response = f"{prefix}### 🍽️ 推薦:{name}\n\n{ai_text}"
239
 
240
- # 2. 動態生成圖片 Prompt
241
- prompt = f"Delicious food photography of {name}, {info}. high quality, photorealistic, 8k, cinematic lighting, appetizing, restaurant atmosphere, 50mm lens"
242
-
243
  prompt_output_text = prompt if show_prompt else ""
244
  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>'
245
 
246
- # 先回傳文字
247
  yield final_response, None, map_html, prompt_output_text
248
 
249
- # 3. 生成圖片
250
  image_output = generate_image_huggingface(prompt)
251
  yield final_response, image_output, map_html, prompt_output_text
252
 
253
  # ==========================================
254
- # 4. 橋接邏輯 (Emotion Bridge)
255
  # ==========================================
256
  def _score_to_radio_value(score):
257
  mapping = {1: "1 (心情差)", 2: "2 (不太好)", 3: "3 (普通)", 4: "4 (不錯)", 5: "5 (超棒)"}
258
- try: score = int(score)
259
- except: score = 3
260
- return mapping.get(score, "3 (普通)")
261
 
262
  def bridge_start_click(st):
263
- res = emotion.on_restart(st)
264
- return res[1], res[0], gr.update(visible=True), res[5], res[4], gr.update(visible=False)
 
 
265
 
266
  def bridge_stop_click(st):
267
- res = emotion.on_stop(st)
268
- return res[1], res[0], gr.update(visible=False), res[5], res[4]
 
 
269
 
270
  def bridge_predict_frame(frame, st):
271
- res = emotion.on_stream(frame, st)
272
- out_cam = res[0]; out_result = res[1]; out_st = res[4]; out_btn_start = res[5]
273
- score_update = gr.update(); out_btn_stop = gr.update()
274
- btn_go_visible = gr.update(visible=False)
275
-
276
- if out_st.finished and hasattr(out_st, 'final_score'):
277
- new_val = _score_to_radio_value(out_st.final_score)
278
- score_update = gr.update(value=new_val)
279
- out_btn_stop = gr.update(visible=False)
280
- btn_go_visible = gr.update(visible=True)
281
-
282
- return out_cam, out_result, out_st, out_btn_stop, out_btn_start, score_update, btn_go_visible
 
 
 
 
 
 
 
 
 
283
 
284
  # ==========================================
285
- # 5. Gradio 介面建構
286
  # ==========================================
287
- css_ = "#app_container { max-width: 960px; margin: 0 auto; }"
 
 
288
 
289
- with gr.Blocks(title="AI 心情食堂", css=css_) as demo:
290
-
291
  st_state = gr.State(emotion.AppState())
292
 
293
  with gr.Tabs() as tabs:
294
-
295
- # Tab 1: 情緒辨識
296
  with gr.TabItem("😊 情緒辨識 (Step 1)", id=0):
297
  with gr.Column(elem_id="app_container"):
298
- gr.Markdown("### 第一步:測測你的心情能量\n讓 AI 看看你的表情,自動幫你決定心情分數!(辨識完畢會自動跳轉)")
299
-
300
  with gr.Row():
301
- btn_start = gr.Button("📸 開啟攝影機辨識", variant="primary")
302
  btn_stop = gr.Button("⏹️ 停止", variant="secondary", visible=False)
303
-
304
  cam = gr.Image(sources=["webcam"], streaming=True, type="numpy", label="攝影機畫面", visible=False)
305
- result_markdown = gr.Markdown(emotion._hint_html("請按「開啟攝影機辨識」並允許瀏覽器使用相機。"))
 
306
  btn_go_dining = gr.Button("🚀 確定心情,來找餐廳!", variant="primary", visible=False, size="lg")
307
 
308
- # Tab 2: 主功能區
309
  with gr.TabItem("🍽️ AI 心情食堂 (Step 2)", id=1):
310
  with gr.Column():
311
-
312
- # 新增:爬蟲同步區塊
313
  gr.Markdown("### 🔗 載入你的口袋名單")
314
  with gr.Row():
315
  map_url = gr.Textbox(label="Google Maps 分享連結", placeholder="請貼上清單的分享連結...", scale=3)
@@ -317,73 +318,28 @@ with gr.Blocks(title="AI 心情食堂", css=css_) as demo:
317
  sync_msg = gr.Markdown("ℹ️ 尚未同步資料庫")
318
 
319
  gr.Markdown("---")
320
- gr.Markdown(f"## 🍱 今天想吃點什麼?")
321
 
322
  with gr.Row():
323
  with gr.Column(scale=1):
324
- score_input = gr.Radio(
325
- ["1 (心情差)", "2 (不太好)", "3 (普通)", "4 (不錯)", "5 (超棒)"],
326
- label="1. 心情分數 (由 Tab 1 自動填入)",
327
- value="3 (普通)"
328
- )
329
  food_input = gr.Radio(["吃飯", "吃麵", "隨便"], label="2. 想吃什麼", value="隨便")
330
- diary_input = gr.Textbox(lines=3, label="3. 心情日記", placeholder="寫下今天發生的事...")
331
-
332
- # 新增:Prompt 檢查選項
333
- show_prompt_chk = gr.Checkbox(label="顯示生成圖片的 Prompt (指令)", value=False)
334
-
335
  submit_btn = gr.Button("🍱 推薦美食", variant="primary")
336
 
337
  with gr.Column(scale=1):
338
  agent_output = gr.Markdown(label="AI 回應")
339
- image_output = gr.Image(label="AI 根據餐廳資訊生成的圖片", type="pil", width=400)
340
-
341
- # 新增:Prompt 輸出框 (唯讀)
342
- prompt_output = gr.Textbox(label="圖片生成指令 (Prompt)", visible=True, interactive=False)
343
-
344
  map_output = gr.HTML(label="地圖導航")
345
 
346
- # ==========================================
347
- # 事件綁定
348
- # ==========================================
349
-
350
- # 綁定爬蟲同步按鈕
351
  sync_btn.click(fn=sync_google_maps, inputs=[map_url], outputs=[sync_msg])
352
-
353
- # 情緒辨識按鈕
354
- btn_start.click(
355
- fn=bridge_start_click,
356
- inputs=[st_state],
357
- outputs=[result_markdown, cam, btn_stop, btn_start, st_state, btn_go_dining],
358
- show_progress="minimal"
359
- )
360
-
361
- btn_stop.click(
362
- fn=bridge_stop_click,
363
- inputs=[st_state],
364
- outputs=[result_markdown, cam, btn_stop, btn_start, st_state],
365
- show_progress="minimal"
366
- )
367
-
368
- cam.stream(
369
- fn=bridge_predict_frame,
370
- inputs=[cam, st_state],
371
- outputs=[cam, result_markdown, st_state, btn_stop, btn_start, score_input, btn_go_dining],
372
- show_progress="minimal"
373
- )
374
-
375
- btn_go_dining.click(
376
- fn=lambda: gr.Tabs(selected=1),
377
- inputs=None,
378
- outputs=tabs
379
- )
380
-
381
- # 送出推薦 (加入 show_prompt 邏輯)
382
- submit_btn.click(
383
- fn=mood_agent_logic,
384
- inputs=[score_input, food_input, diary_input, show_prompt_chk],
385
- outputs=[agent_output, image_output, map_output, prompt_output]
386
- )
387
 
388
  if __name__ == "__main__":
389
- demo.launch(ssr_mode=False)
 
12
  # ==========================================
13
  def install_dependencies():
14
  """確保必要套件與瀏覽器核心都有安裝"""
 
15
  try:
16
  import playwright
17
  except ImportError:
18
  print("⚠️ 偵測到缺少 playwright,正在強制安裝...")
19
  subprocess.check_call([sys.executable, "-m", "pip", "install", "playwright"])
20
 
21
+ # 設定瀏覽器路徑
22
  os.environ["PLAYWRIGHT_BROWSERS_PATH"] = os.path.join(os.getcwd(), "playwright_browsers")
23
 
 
24
  print("正在檢查 Chromium 瀏覽器...")
25
  try:
 
26
  subprocess.run([sys.executable, "-m", "playwright", "install", "chromium"], check=True)
27
  except Exception as e:
28
  print(f"瀏覽器安裝警告: {e}")
29
 
 
30
  install_dependencies()
31
 
32
  # ==========================================
 
40
  from langchain_community.vectorstores import FAISS
41
  from PIL import Image
42
 
43
+ # --- 定義 Mock 替身 (防止 emotion.py 壞掉時程式崩潰) ---
44
+ class MockEmotion:
45
+ """當 emotion 模組失效時的替補類別"""
46
+ css = ""
47
+ class AppState: pass
48
+
49
+ @staticmethod
50
+ def _hint_html(s):
51
+ return f"<div style='color:red; border:1px solid red; padding:10px;'>⚠️ 系統警告:情緒辨識模組載入失敗。<br>請檢查 requirements.txt 是否包含 deepface 與 tensorflow-cpu。<br>目前僅提供手動輸入模式。</div><br>{s}"
52
+
53
+ @staticmethod
54
+ def on_restart(st): return [None] * 10
55
+
56
+ @staticmethod
57
+ def on_stop(st): return [None] * 10
58
+
59
+ @staticmethod
60
+ def on_stream(frame, st):
61
+ # 模擬回傳,防止 Gradio 報錯
62
+ class DummyState:
63
+ finished = False
64
+ final_score = 3
65
+ return [None, None, None, None, DummyState(), gr.update(), gr.update()]
66
+
67
+ @staticmethod
68
+ def on_upload(img, st):
69
+ class DummyState:
70
+ finished = True
71
+ final_score = 3
72
+ return [None, None, DummyState(), None]
73
+
74
  # 嘗試匯入組員的模組
75
  try:
76
+ import emotion
77
+ print("✅ 成功載入 emotion 模組")
78
+ except Exception as e:
79
+ print(f"⚠️ 警告:emotion 模組載入失敗 ({e}),正在啟用 Mock 模式以防止崩潰。")
80
+ emotion = MockEmotion() # <--- 關鍵:指派替身,避免 NameError
81
 
82
  load_dotenv()
83
 
 
93
  rag_initialized = False
94
 
95
  def init_static_data():
 
96
  global global_mood_df
97
  if global_mood_df is None:
98
  try:
99
  global_mood_df = pd.read_csv('mood_food_guide.csv')
100
  except:
 
101
  global_mood_df = pd.DataFrame({
102
  '分數': [1, 2, 3, 4, 5],
103
  '推薦料理類別': ["療癒系", "暖胃", "隨意", "豐富", "大餐"],
 
105
  })
106
 
107
  # ==========================================
108
+ # 2. Google Maps 爬蟲功能
109
  # ==========================================
110
  def sync_google_maps(url):
111
  global global_df, global_retriever, rag_initialized
 
136
  restaurant_list.append({
137
  "Name": name,
138
  "Address": addr,
139
+ "Category": "未分類",
140
  "RAG_Content": f"餐廳:{name},資訊:{addr}",
141
  "URL": f"https://www.google.com/search?q={urllib.parse.quote(name)}"
142
  })
 
148
 
149
  global_df = pd.DataFrame(restaurant_list)
150
 
 
151
  try:
152
  embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
153
  vectorstore = FAISS.from_texts(global_df['RAG_Content'].tolist(), embeddings, metadatas=global_df.to_dict('records'))
 
164
  # 3. 核心功能 (推薦與生成)
165
  # ==========================================
166
  def get_restaurant_data(mood_score_str, food_choice):
167
+ init_static_data()
 
168
  if global_df is None or global_df.empty:
169
  return None, True, "資料庫未載入", "尚未同步地圖資料", ""
170
 
 
171
  all_names = "、".join(global_df['Name'].tolist())
 
172
  try: score = int(str(mood_score_str).split(' ')[0])
173
  except: score = 3
174
 
175
  mood_info = global_mood_df[global_mood_df['分數'] == score]
176
+ mood_reason = mood_info.iloc[0]['原因'] if not mood_info.empty else "隨意探索"
 
 
 
177
 
178
  candidates = global_df.copy()
 
 
179
  food_keyword = "飯" if food_choice == "吃飯" else "麵" if food_choice == "吃麵" else ""
180
  is_match = True
181
 
 
184
  if not filtered.empty:
185
  candidates = filtered
186
  else:
187
+ is_match = False
188
 
189
  result = candidates.sample(1).iloc[0]
190
  return result, is_match, "個人清單", mood_reason, all_names
191
 
192
  def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, mood_score, mood_guide_reason):
193
  if not GROQ_API_KEY: return "⚠️ 請設定 GROQ_API_KEY"
 
194
  client = OpenAI(api_key=GROQ_API_KEY, base_url="https://api.groq.com/openai/v1")
195
 
196
  system_prompt = "你是一個幽默、懂吃且善解人意的 AI 朋友。請根據使用者的日記、心情以及餐廳資訊來推薦。"
197
+ user_msg = f"心情分數:{mood_score}\n日記:{user_diary}\n原因:{mood_guide_reason}\n餐廳:{restaurant_name}\n資訊:{restaurant_detail}"
198
+
 
 
 
 
 
 
 
 
 
 
 
 
199
  try:
200
  response = client.chat.completions.create(model="llama-3.3-70b-versatile", messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_msg}])
201
+ return response.choices[0].message.content
 
202
  except Exception as e:
203
  return f"Groq Error: {str(e)}"
204
 
205
  def generate_image_huggingface(prompt):
 
206
  if not HF_TOKEN: return None
207
  try:
208
  hf_client = InferenceClient(token=HF_TOKEN)
 
209
  return hf_client.text_to_image(
210
  prompt=prompt,
211
+ negative_prompt="blurry, low quality, distortion, text, watermark",
212
  model="stabilityai/stable-diffusion-xl-base-1.0"
213
  )
214
  except Exception as e:
 
221
  return
222
 
223
  restaurant, is_match, _, mood_reason, all_names = get_restaurant_data(score_input, food_input)
 
224
  if restaurant is None:
225
  yield "資料庫讀取錯誤", None, "", ""
226
  return
 
229
  info = restaurant.get('RAG_Content', '')
230
  url = restaurant.get('URL', '#')
231
 
 
232
  prefix = ""
233
  if not is_match and food_input != "隨便":
234
  prefix = f"> 💡 **溫馨提示**:清單中暫無『{food_input}』,已從現有名單挑選最適合的店!\n\n"
235
 
 
236
  ai_text = generate_content_with_groq(name, info, diary_input, score_input, mood_reason)
237
  final_response = f"{prefix}### 🍽️ 推薦:{name}\n\n{ai_text}"
238
 
239
+ prompt = f"Delicious food photography of {name}, {info}. high quality, photorealistic, 8k, cinematic lighting, appetizing, restaurant atmosphere"
 
 
240
  prompt_output_text = prompt if show_prompt else ""
241
  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>'
242
 
 
243
  yield final_response, None, map_html, prompt_output_text
244
 
 
245
  image_output = generate_image_huggingface(prompt)
246
  yield final_response, image_output, map_html, prompt_output_text
247
 
248
  # ==========================================
249
+ # 4. 橋接邏輯 (整合 Mock)
250
  # ==========================================
251
  def _score_to_radio_value(score):
252
  mapping = {1: "1 (心情差)", 2: "2 (不太好)", 3: "3 (普通)", 4: "4 (不錯)", 5: "5 (超棒)"}
253
+ return mapping.get(int(score), "3 (普通)")
 
 
254
 
255
  def bridge_start_click(st):
256
+ try:
257
+ res = emotion.on_restart(st)
258
+ return res[1], res[0], gr.update(visible=True), res[5], res[4], gr.update(visible=False)
259
+ except: return gr.update(), gr.update(), gr.update(), gr.update(), st, gr.update()
260
 
261
  def bridge_stop_click(st):
262
+ try:
263
+ res = emotion.on_stop(st)
264
+ return res[1], res[0], gr.update(visible=False), res[5], res[4]
265
+ except: return gr.update(), gr.update(), gr.update(), gr.update(), st
266
 
267
  def bridge_predict_frame(frame, st):
268
+ try:
269
+ res = emotion.on_stream(frame, st)
270
+ out_cam, out_result, out_st, out_btn_start = res[0], res[1], res[4], res[5]
271
+ score_update = gr.update(); btn_go_visible = gr.update(visible=False)
272
+ if hasattr(out_st, 'finished') and out_st.finished and hasattr(out_st, 'final_score'):
273
+ new_val = _score_to_radio_value(out_st.final_score)
274
+ score_update = gr.update(value=new_val)
275
+ btn_go_visible = gr.update(visible=True)
276
+ return out_cam, out_result, out_st, gr.update(visible=False), out_btn_start, score_update, btn_go_visible
277
+ except: return frame, gr.update(), st, gr.update(), gr.update(), gr.update(), gr.update()
278
+
279
+ def bridge_predict_upload(img, st):
280
+ try:
281
+ res = emotion.on_upload(img, st)
282
+ out_result, out_st = res[0], res[2]
283
+ score_update = gr.update()
284
+ if hasattr(out_st, 'finished') and out_st.finished and hasattr(out_st, 'final_score'):
285
+ new_val = _score_to_radio_value(out_st.final_score)
286
+ score_update = gr.update(value=new_val)
287
+ return out_result, score_update, gr.Tabs(selected=1), out_st
288
+ except: return gr.update(), gr.update(), gr.Tabs(), st
289
 
290
  # ==========================================
291
+ # 5. Gradio UI
292
  # ==========================================
293
+ # 修正 CSS 載入:如果 emotion 模組不可用,則忽略 CSS
294
+ css_style = "#app_container { max-width: 960px; margin: 0 auto; }"
295
+ if hasattr(emotion, 'css'): css_style += "\n" + emotion.css
296
 
297
+ with gr.Blocks(title="AI 心情食堂") as demo:
 
298
  st_state = gr.State(emotion.AppState())
299
 
300
  with gr.Tabs() as tabs:
 
 
301
  with gr.TabItem("😊 情緒辨識 (Step 1)", id=0):
302
  with gr.Column(elem_id="app_container"):
303
+ gr.Markdown("### 第一步:測測你的心情能量")
 
304
  with gr.Row():
305
+ btn_start = gr.Button("📸 開啟攝影機", variant="primary")
306
  btn_stop = gr.Button("⏹️ 停止", variant="secondary", visible=False)
 
307
  cam = gr.Image(sources=["webcam"], streaming=True, type="numpy", label="攝影機畫面", visible=False)
308
+ result_markdown = gr.Markdown(emotion._hint_html("請按上方按鈕開始"))
309
+ upload_img = gr.Image(sources=["upload"], type="numpy", label="上傳照片")
310
  btn_go_dining = gr.Button("🚀 確定心情,來找餐廳!", variant="primary", visible=False, size="lg")
311
 
 
312
  with gr.TabItem("🍽️ AI 心情食堂 (Step 2)", id=1):
313
  with gr.Column():
 
 
314
  gr.Markdown("### 🔗 載入你的口袋名單")
315
  with gr.Row():
316
  map_url = gr.Textbox(label="Google Maps 分享連結", placeholder="請貼上清單的分享連結...", scale=3)
 
318
  sync_msg = gr.Markdown("ℹ️ 尚未同步資料庫")
319
 
320
  gr.Markdown("---")
 
321
 
322
  with gr.Row():
323
  with gr.Column(scale=1):
324
+ score_input = gr.Radio(["1 (心情差)", "2 (不太好)", "3 (普通)", "4 (不錯)", "5 (超棒)"], label="1. 心情分數", value="3 (普通)")
 
 
 
 
325
  food_input = gr.Radio(["吃飯", "吃麵", "隨便"], label="2. 想吃什麼", value="隨便")
326
+ diary_input = gr.Textbox(lines=3, label="3. 心情日記", placeholder="寫下今天的心情...")
327
+ show_prompt_chk = gr.Checkbox(label="顯示 Prompt", value=False)
 
 
 
328
  submit_btn = gr.Button("🍱 推薦美食", variant="primary")
329
 
330
  with gr.Column(scale=1):
331
  agent_output = gr.Markdown(label="AI 回應")
332
+ image_output = gr.Image(label="AI 推薦美食圖", type="pil", width=400)
333
+ prompt_output = gr.Textbox(label="Prompt", visible=True, interactive=False)
 
 
 
334
  map_output = gr.HTML(label="地圖導航")
335
 
 
 
 
 
 
336
  sync_btn.click(fn=sync_google_maps, inputs=[map_url], outputs=[sync_msg])
337
+ btn_start.click(fn=bridge_start_click, inputs=[st_state], outputs=[result_markdown, cam, btn_stop, btn_start, st_state, btn_go_dining])
338
+ btn_stop.click(fn=bridge_stop_click, inputs=[st_state], outputs=[result_markdown, cam, btn_stop, btn_start, st_state])
339
+ cam.stream(fn=bridge_predict_frame, inputs=[cam, st_state], outputs=[cam, result_markdown, st_state, btn_stop, btn_start, score_input, btn_go_visible=btn_go_dining])
340
+ upload_img.change(fn=bridge_predict_upload, inputs=[upload_img, st_state], outputs=[result_markdown, score_input, tabs, st_state])
341
+ btn_go_dining.click(fn=lambda: gr.Tabs(selected=1), inputs=None, outputs=tabs)
342
+ submit_btn.click(fn=mood_agent_logic, inputs=[score_input, food_input, diary_input, show_prompt_chk], outputs=[agent_output, image_output, map_output, prompt_output])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
343
 
344
  if __name__ == "__main__":
345
+ demo.launch(ssr_mode=False, css=css_style)