PhilipL commited on
Commit
b11c346
·
verified ·
1 Parent(s): 63038eb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +160 -193
app.py CHANGED
@@ -6,7 +6,6 @@ import time
6
  import requests
7
  import urllib.parse
8
  import pandas as pd
9
- import random # [新增] 用於隨機抽選
10
  from langchain_huggingface import HuggingFaceEmbeddings
11
  from langchain_community.vectorstores import FAISS
12
  from PIL import Image
@@ -26,33 +25,46 @@ global_retriever = None
26
  rag_initialized = False
27
 
28
  # ==========================================
29
- # 1. 系統初始化 (維持不變)
30
  # ==========================================
31
  def init_rag_system():
32
  global global_df, global_mood_df, global_retriever, rag_initialized
 
33
  if rag_initialized: return
 
34
  print("⏳ 正在初始化系統...")
 
 
35
  try:
36
  global_df = pd.read_csv('restaurants.csv')
37
  global_df['RAG_Content'] = global_df['RAG_Content'].fillna("")
38
  global_df['Category'] = global_df['Category'].fillna("其他")
 
39
  global_mood_df = pd.read_csv('mood_food_guide.csv')
40
  print(f"✅ CSV 資料讀取成功 (餐廳: {len(global_df)} 筆)")
41
  except Exception as e:
42
  print(f"❌ CSV 讀取失敗: {e}")
43
  return
44
 
 
45
  if os.path.exists("faiss_index"):
46
  try:
47
  print("⏳ 正在載入 FAISS 向量資料庫...")
48
  embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
49
- vectorstore = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
 
 
 
 
 
50
  global_retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
51
  print("✅ FAISS 資料庫載入完成!")
52
  except Exception as e:
53
  print(f"❌ FAISS 載入失敗: {e}")
54
  else:
55
  print("⚠️ 警告:找不到 'faiss_index' 資料夾,RAG 功能將無法使用。")
 
 
56
  rag_initialized = True
57
 
58
  # ==========================================
@@ -66,78 +78,54 @@ custom_css = """
66
  """
67
 
68
  # 設定圖片路徑
69
- img_paths = {
70
- "q1": "images/image_0.png",
71
- "q2": "images/image_1.png",
72
- "q3": "images/image_2.png",
73
- "q4": "images/image_3.png",
74
- "q5": "images/image_4.png"
75
- }
76
  if not os.path.exists("images"): os.makedirs("images")
77
- for p in img_paths.values():
78
  if not os.path.exists(p):
79
  Image.new('RGB', (400, 300), color='lightgray').save(p)
80
 
81
- # --- 選項設定 (放入同一個字典方便管理) ---
82
- OPTIONS_MAP = {
83
- "q1": {
84
- "title": "直覺測試",
85
- "question": "請觀察圖片,如果是你,你會怎麼做?",
86
- "options": {
87
- "不​要​再​問白癡​問題​了​我​只​想​吃飯​": "現實主義者 (只想吃飯)",
88
- "去​過隱​居​生活": "隱士 (嚮往平靜)",
89
- "加入​禁衛軍,​保衛​這個​世界": "守護者 (充滿正義感)",
90
- "神​羅​天​征,毀滅這個​世界​": "破壞神 (心情可能很差或很中二)"
91
- }
92
- },
93
- "q2": {
94
- "title": "魔法適性",
95
- "question": "身為魔導士的你,會選擇哪一個法術?",
96
- "options": {
97
- "不​要​再​問白癡​問題​了​我​只​想​吃飯​": "無魔法 (飢餓度MAX)",
98
- "麵​包形狀​的​魔法​炸彈": "爆炸魔法 (喜歡刺激/重口味)",
99
- "毒氣​的​生化​魔法": "毒氣魔法 (可能想吃臭豆腐或特殊風味)",
100
- "領域​展開:​無量​空處​": "領域展開 (思緒混亂或想放空)"
101
- }
102
- },
103
- "q3": {
104
- "title": "旅遊直覺",
105
- "question": "不考慮其他因素,假你在桃機你最想去哪裡玩?",
106
- "options": {
107
- "不​要​在​問白癡​問題​了​我​只​想​吃飯​": "現實主義者 (只想吃飯)",
108
- "歐洲": "嚮往歐洲 (浪漫/西式)",
109
- "日本": "嚮往日本 (精緻/日式)",
110
- "泰國": "嚮往泰國 (熱情/酸辣)",
111
- "轉身搭機捷回家": "戀家 (只想回家)"
112
- }
113
- },
114
- "q4": {
115
- "title": "社交場合",
116
- "question": "你是小大一,班上還不熟,現在你正參加你們班上的認識彼此的活動,下列哪一個人是你會選擇搭話的人?",
117
- "options": {
118
- "轉頭​回家​睡覺​": "獨行俠 (想睡覺)",
119
- "看​起來​很​會玩​的​帥潮​": "外向 (找帥潮)",
120
- "感覺​是​動漫宅​的​同好​": "御宅族 (找同好)",
121
- "有​興趣​的​異性​": "大膽 (找異性)"
122
- }
123
- },
124
- "q5": {
125
- "title": "追劇時光",
126
- "question": "假設失憶了忘記以下所列的劇的劇情,而你現在閒了下來剛好想看劇,你會想看哪一部?",
127
- "options": {
128
- "甚麼​都​不​想​​": "放空 (什麼都不想)",
129
- "來​自​星星​的​你​": "韓劇迷 (浪漫愛情)",
130
- "進擊​的​巨人​": "動漫迷 (熱血戰鬥)",
131
- "洛基": "美劇迷 (懸疑燒腦)"
132
- }
133
- }
134
  }
135
 
136
  # ==========================================
137
  # 3. 核心功能
138
  # ==========================================
139
 
140
- # ... get_restaurant_data 維持不變 ...
141
  def get_restaurant_data(mood_score_str, food_choice):
142
  init_rag_system()
143
  if global_df is None or global_df.empty: return None, True, "資料庫未載入", "無建議"
@@ -176,7 +164,7 @@ def get_restaurant_data(mood_score_str, food_choice):
176
 
177
  return result, is_random, rec_categories, mood_reason
178
 
179
- # [修改] Prompt 生成邏輯:動態讀取 quiz_result
180
  def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, mood_score, quiz_result, mood_guide_reason, debug_mode=False):
181
  if not GROQ_API_KEY: return "⚠️ 請設定 GROQ_API_KEY"
182
 
@@ -184,21 +172,15 @@ def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, m
184
 
185
  system_prompt = "你是一個幽默、懂吃且善解人意的 AI 朋友。請根據使用者的日記、心情以及「心情美食指南」來推薦餐廳。"
186
 
187
- # [新增] 格式化測驗結果字串
188
- quiz_summary = ""
189
- if quiz_result:
190
- for q_key, answer_text in quiz_result.items():
191
- # 取得題目的標題 (例如: 追劇時光)
192
- title = OPTIONS_MAP.get(q_key, {}).get("title", q_key)
193
- quiz_summary += f"- {title}:{answer_text}\n"
194
- else:
195
- quiz_summary = "(使用者未進行測驗或無資料)"
196
-
197
  user_msg = f"""
198
  【狀態】心情分數:{mood_score},日記:{user_diary}
199
 
200
- 【隨機測驗結果】
201
- {quiz_summary}
 
 
 
 
202
 
203
  【心情美食指南建議】
204
  因為分數是 {mood_score},建議吃這類食物的原因是:「{mood_guide_reason}」。
@@ -209,7 +191,7 @@ def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, m
209
 
210
  任務:
211
  請用繁體中文寫一段溫暖有趣的回覆:
212
- 1. 綜合回應他的日記與上述測驗結果(請針對他有回答的部分做連結即可)。
213
  2. 引用「心情美食指南」的原因。
214
  3. 介紹這家餐廳的特色。
215
  (只需要回覆文字內容)
@@ -221,6 +203,7 @@ def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, m
221
  )
222
  content = response.choices[0].message.content
223
 
 
224
  if debug_mode:
225
  debug_info = f"""
226
  \n\n--- 🛠️ [DEBUG] LLM Prompt 檢查 ---
@@ -234,10 +217,10 @@ def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, m
234
  except Exception as e:
235
  return f"Groq Error: {str(e)}"
236
 
237
- # ... generate_image_huggingface 維持不變 ...
238
  def generate_image_huggingface(prompt):
239
  if not HF_TOKEN: return None
240
  if not prompt or pd.isna(prompt): prompt = "Delicious gourmet food, photorealistic, 8k"
 
241
  try:
242
  hf_client = InferenceClient(token=HF_TOKEN)
243
  return hf_client.text_to_image(prompt=prompt, model="stabilityai/stable-diffusion-xl-base-1.0")
@@ -245,182 +228,166 @@ def generate_image_huggingface(prompt):
245
  print(f"❌ 生圖失敗: {e}")
246
  return None
247
 
248
- # ... mood_agent_logic 維持不變 ...
249
  def mood_agent_logic(score_input, food_input, diary_input, quiz_state, debug_mode):
250
  restaurant, is_random, rec_categories, mood_reason = get_restaurant_data(score_input, food_input)
 
251
  if restaurant is None:
252
  yield "資料庫讀取錯誤", None, ""
253
  return
 
254
  name = restaurant['Name']
255
  address = restaurant['Address']
256
  url = restaurant['URL']
257
  img_prompt = restaurant.get('Visual_prompt')
258
  note = "(隨機推薦)" if is_random else ""
 
 
259
  rag_info = str(restaurant.get('RAG_Content', ''))
260
  if global_retriever:
261
  docs = global_retriever.invoke(name)
262
- if docs: rag_info = "\n".join([d.page_content for d in docs])
 
263
 
 
264
  ai_text = generate_content_with_groq(name, rag_info, diary_input, score_input, quiz_state, mood_reason, debug_mode)
265
 
 
266
  if debug_mode:
267
  img_debug_info = f"""
268
  \n\n--- 🛠️ [DEBUG] 圖片生成檢查 ---
269
  \n**使用的 Visual Prompt:**\n{img_prompt}
 
270
  \n-----------------------------------
271
  """
272
  ai_text += img_debug_info
273
 
274
  final_response = f"### 🍽️ 推薦:{name} {note}\n\n{ai_text}"
275
  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>'
 
276
  yield final_response, None, map_html
277
  image_output = generate_image_huggingface(img_prompt)
278
  yield final_response, image_output, map_html
279
 
280
  # ==========================================
281
- # 4. 隨機與導航邏輯 (重點修改區)
282
  # ==========================================
 
 
 
 
283
 
284
- # 開始測驗:隨機選 2 題
285
- def start_quiz_logic(current_state):
286
- # 從 0 到 4 (對應 q1~q5) 中隨機取 2 個不重複的數字
287
- selected_indices = random.sample(range(5), 2)
288
- # 儲存題目順序,例如 [2, 0] 代表先做 Q3 再做 Q1
289
- current_state["flow"] = selected_indices
290
- current_state["current_step_index"] = 0 # 目前在 flow 中的第幾個
291
- current_state["answers"] = {} # 重置答案
292
-
293
- first_q_index = selected_indices[0]
294
- print(f"🎲 隨機抽選題目索引: {selected_indices}")
295
-
296
- # 回傳:更新後的 State, 跳轉到第一個題目的 Tab ID
297
- return current_state, gr.Tabs(selected=first_q_index)
298
-
299
- # 處理導航:決定去下一題還是去 Main
300
- def navigate_logic(q_key, selected_option, current_state):
301
- if not selected_option:
302
- return current_state, gr.Tabs() # 沒選答案就不動
303
-
304
- # 1. 儲存答案
305
- options_dict = OPTIONS_MAP[q_key]["options"]
306
- answer_value = options_dict.get(selected_option, selected_option)
307
- current_state["answers"][q_key] = answer_value
308
-
309
- # 2. 判斷下一步
310
- flow = current_state.get("flow", [])
311
- current_step = current_state.get("current_step_index", 0)
312
-
313
- # 如果還有下一題
314
- if current_step < len(flow) - 1:
315
- next_step = current_step + 1
316
- current_state["current_step_index"] = next_step
317
- next_q_index = flow[next_step]
318
- print(f"➡️ 前往下一題: Index {next_q_index}")
319
- return current_state, gr.Tabs(selected=next_q_index)
320
- else:
321
- # 已經是最後一題,前往 Main (ID: 5)
322
- print("🏁 測驗結束,前往結果頁")
323
- return current_state, gr.Tabs(selected=5)
324
 
325
- # 為了讓按鈕啟用/禁用正常運作的輔助函式
326
- def on_radio_select(val):
327
- return gr.Button(interactive=True, variant="primary")
 
328
 
329
  # ==========================================
330
  # 5. Gradio 介面建構
331
  # ==========================================
332
  with gr.Blocks(title="AI 心情食堂") as demo:
333
  gr.HTML(f"<style>{custom_css}</style>")
334
-
335
- # 狀態變數:存放 flow(題目順序), answers(答案), current_step_index
336
- quiz_state = gr.State(value={"flow": [], "answers": {}, "current_step_index": 0})
337
 
338
  with gr.Tabs(elem_id="hidden_tabs") as tabs:
339
-
340
- # [新增] Tab -1: 開始頁面 (作為預設頁)
341
- with gr.TabItem("Start", id=-1):
342
- with gr.Column(elem_classes="start-page"):
343
- gr.Markdown("# 🔮 AI 心情食堂 - 命運測驗")
344
- gr.Markdown("在為您推薦美食之前,請回答 **2 個隨機問題**,讓我們更了解您現在的狀態。")
345
- start_btn = gr.Button("開始隨機測驗 ➔", variant="primary", size="lg")
346
-
347
- # 動態生成 Q1 ~ Q5 的頁面 (ID 0 ~ 4)
348
- # 我們可以用迴圈來建立,讓程式碼更乾淨
349
- radios = {}
350
- buttons = {}
351
-
352
- # 依序建立 Q1(0), Q2(1), Q3(2), Q4(3), Q5(4)
353
- keys = ["q1", "q2", "q3", "q4", "q5"]
354
- for idx, key in enumerate(keys):
355
- cfg = OPTIONS_MAP[key]
356
- with gr.TabItem(key.upper(), id=idx):
357
- with gr.Column():
358
- gr.Markdown(f"### 🔮 {cfg['title']}")
359
- gr.Image(value=img_paths[key], type="filepath", label="請觀察圖片", height=300)
360
- gr.Markdown(f"**問題:{cfg['question']}**")
361
-
362
- # 建立 Radio
363
- r = gr.Radio(choices=list(cfg["options"].keys()), label="請選擇", elem_classes="vertical-radio")
364
- radios[key] = r
365
-
366
- # 建立按鈕 (預設禁用)
367
- b = gr.Button("下一頁 ➔", interactive=False)
368
- buttons[key] = b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
369
 
370
  # Tab 5: Main
371
  with gr.TabItem("Main", id=5):
372
  with gr.Column():
373
  gr.Markdown(f"## 🍱 呷飽沒??!")
374
- gr.Markdown("測驗結束!請填寫最後的需求:")
375
  with gr.Row():
376
  with gr.Column(scale=1):
377
  score_input = gr.Radio(["1 (心情差)", "2 (不太好)", "3 (普通)", "4 (不錯)", "5 (超棒)"], label="1. 心情分數", value="3 (普通)")
378
  food_input = gr.Radio(["吃飯", "吃麵", "隨便"], label="2. 想吃什麼", value="隨便")
379
  diary_input = gr.Textbox(lines=4, label="3. 心情日記", placeholder="寫下今天發生的事...")
 
 
380
  debug_mode_btn = gr.Checkbox(label="🔧 開啟除錯模式 (顯示 Prompt 與圖片資訊)", value=False)
 
381
  submit_btn = gr.Button("送出給 Agent", variant="primary")
382
  with gr.Column(scale=1):
383
  agent_output = gr.Markdown(label="AI 回應")
384
  image_output = gr.Image(label="AI 推薦美食圖", type="pil", width=400)
385
  map_output = gr.HTML(label="地圖導航")
386
 
387
- # --- 事件綁定 ---
 
 
 
 
 
388
 
389
- # 1. 開始按鈕:觸發隨機邏輯 -> 跳到第一題
390
- start_btn.click(
391
- fn=start_quiz_logic,
392
- inputs=[quiz_state],
393
- outputs=[quiz_state, tabs]
394
- )
395
 
396
- # 2. 綁定每一題的 Radio 與 Button
397
- # 使用閉包 (Closure) 來確保 loop 中的 key 是正確的
398
- for key in keys:
399
- # 當選擇 Radio 時,啟用按鈕
400
- radios[key].change(fn=on_radio_select, inputs=[radios[key]], outputs=[buttons[key]])
401
-
402
- # 當按下按鈕時,執行導航邏輯
403
- # 注意:我們需要傳入固定的 key (如 "q1") 給 navigate_logic
404
- # 這裡用 partial 或 default arg trick
405
- buttons[key].click(
406
- fn=lambda k=key, opt=None, state=None: navigate_logic(k, opt, state), # Wrapper for safely passing key
407
- inputs=[gr.State(key), radios[key], quiz_state], # gr.State(key) is a trick, or just use partial
408
- outputs=[quiz_state, tabs]
409
- )
410
- # 更正:上面的 lambda 寫法在 inputs 混用有點怪,改用更有保證的寫法:
411
- def make_handler(k):
412
- return lambda opt, state: navigate_logic(k, opt, state)
413
-
414
- buttons[key].click(
415
- fn=make_handler(key),
416
- inputs=[radios[key], quiz_state],
417
- outputs=[quiz_state, tabs]
418
- )
419
 
420
- # 3. 送出給 Agent
421
- # 注意:我們要傳入 quiz_state["answers"] 給後端
422
  submit_btn.click(
423
- fn=lambda s, f, d, st, db: mood_agent_logic(s, f, d, st["answers"], db),
424
  inputs=[score_input, food_input, diary_input, quiz_state, debug_mode_btn],
425
  outputs=[agent_output, image_output, map_output]
426
  )
 
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
 
25
  rag_initialized = False
26
 
27
  # ==========================================
28
+ # 1. 系統初始化 (讀取 CSV + 讀取 FAISS)
29
  # ==========================================
30
  def init_rag_system():
31
  global global_df, global_mood_df, global_retriever, rag_initialized
32
+
33
  if rag_initialized: return
34
+
35
  print("⏳ 正在初始化系統...")
36
+
37
+ # --- A. 讀取 CSV (用於篩選與對照) ---
38
  try:
39
  global_df = pd.read_csv('restaurants.csv')
40
  global_df['RAG_Content'] = global_df['RAG_Content'].fillna("")
41
  global_df['Category'] = global_df['Category'].fillna("其他")
42
+
43
  global_mood_df = pd.read_csv('mood_food_guide.csv')
44
  print(f"✅ CSV 資料讀取成功 (餐廳: {len(global_df)} 筆)")
45
  except Exception as e:
46
  print(f"❌ CSV 讀取失敗: {e}")
47
  return
48
 
49
+ # --- B. 讀取預先建立好的 FAISS 索引 ---
50
  if os.path.exists("faiss_index"):
51
  try:
52
  print("⏳ 正在載入 FAISS 向量資料庫...")
53
  embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
54
+
55
+ vectorstore = FAISS.load_local(
56
+ "faiss_index",
57
+ embeddings,
58
+ allow_dangerous_deserialization=True
59
+ )
60
  global_retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
61
  print("✅ FAISS 資料庫載入完成!")
62
  except Exception as e:
63
  print(f"❌ FAISS 載入失敗: {e}")
64
  else:
65
  print("⚠️ 警告:找不到 'faiss_index' 資料夾,RAG 功能將無法使用。")
66
+ print("請先執行 build_index.py 並上傳資料夾。")
67
+
68
  rag_initialized = True
69
 
70
  # ==========================================
 
78
  """
79
 
80
  # 設定圖片路徑
81
+ img_path_1 = "images/image_0.png"
82
+ img_path_2 = "images/image_1.png"
83
+ img_path_3 = "images/image_2.png" # Q3
84
+ img_path_4 = "images/image_3.png" # Q4
85
+ img_path_5 = "images/image_4.png" # Q5
86
+
 
87
  if not os.path.exists("images"): os.makedirs("images")
88
+ for p in [img_path_1, img_path_2, img_path_3, img_path_4, img_path_5]:
89
  if not os.path.exists(p):
90
  Image.new('RGB', (400, 300), color='lightgray').save(p)
91
 
92
+ # --- 選項設定 ---
93
+ q1_options_map = {
94
+ "不​要​再​問白癡​問題​了​我​只​想​吃飯​": "現實主義者 (只想吃飯)",
95
+ "去​過隱​居​生活": "隱士 (嚮往平靜)",
96
+ "加入​禁衛軍,​保衛​這個​世界": "守護者 (充滿正義感)",
97
+ "神​羅​天​征,毀滅這個​世界​": "破壞神 (心情可能很差或很中二)"
98
+ }
99
+ q2_options_map = {
100
+ "不​要​再​問白癡​問題​了​我​只​想​吃飯​": "無魔法 (飢餓度MAX)",
101
+ "麵​包形狀​的​魔法​炸彈": "爆炸魔法 (喜歡刺激/重口味)",
102
+ "毒氣​的​生化​魔法": "毒氣魔法 (可能想吃臭豆腐或特殊風味)",
103
+ "領域​展開:​無量​空處​": "領域展開 (思緒混亂或想放空)"
104
+ }
105
+ q3_options_map = {
106
+ "不​要​在​問白癡​問題​了​我​只​想​吃飯​": "現實主義者 (只想吃飯)",
107
+ "歐洲": "嚮往歐洲 (浪漫/西式)",
108
+ "日本": "嚮往日本 (精緻/日式)",
109
+ "泰國": "嚮往泰國 (熱情/酸辣)",
110
+ "轉身搭機捷回家": "戀家 (只想回家)"
111
+ }
112
+ q4_options_map = {
113
+ "轉頭​回家​睡覺​": "獨行俠 (想睡覺)",
114
+ "看​起來​很​會玩​的​帥潮​": "外向 (找帥潮)",
115
+ "感覺​是​動漫宅​的​同好​": "御宅族 (找同好)",
116
+ "有​興趣​的​異性​": "大膽 (找異性)"
117
+ }
118
+ q5_options_map = {
119
+ "甚麼​都​不​想​​": "放空 (什麼都不想)",
120
+ "來​自​星星​的​你​": "韓劇迷 (浪漫愛情)",
121
+ "進擊​的​巨人​": "動漫迷 (熱血戰鬥)",
122
+ "洛基": "美劇迷 (懸疑燒腦)"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  }
124
 
125
  # ==========================================
126
  # 3. 核心功能
127
  # ==========================================
128
 
 
129
  def get_restaurant_data(mood_score_str, food_choice):
130
  init_rag_system()
131
  if global_df is None or global_df.empty: return None, True, "資料庫未載入", "無建議"
 
164
 
165
  return result, is_random, rec_categories, mood_reason
166
 
167
+ # [修改] 增加 debug_mode 參數
168
  def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, mood_score, quiz_result, mood_guide_reason, debug_mode=False):
169
  if not GROQ_API_KEY: return "⚠️ 請設定 GROQ_API_KEY"
170
 
 
172
 
173
  system_prompt = "你是一個幽默、懂吃且善解人意的 AI 朋友。請根據使用者的日記、心情以及「心情美食指南」來推薦餐廳。"
174
 
 
 
 
 
 
 
 
 
 
 
175
  user_msg = f"""
176
  【狀態】心情分數:{mood_score},日記:{user_diary}
177
 
178
+ 【五題測驗結果】
179
+ 1. 人設直覺:{quiz_result.get('q1', '未知')}
180
+ 2. 魔法適性:{quiz_result.get('q2', '未知')}
181
+ 3. 旅遊偏好:{quiz_result.get('q3', '未知')}
182
+ 4. 社交選擇:{quiz_result.get('q4', '未知')}
183
+ 5. 追劇偏好:{quiz_result.get('q5', '未知')}
184
 
185
  【心情美食指南建議】
186
  因為分數是 {mood_score},建議吃這類食物的原因是:「{mood_guide_reason}」。
 
191
 
192
  任務:
193
  請用繁體中文寫一段溫暖有趣的回覆:
194
+ 1. 綜合回應他的日記與上述 5 個測驗結果。
195
  2. 引用「心情美食指南」的原因。
196
  3. 介紹這家餐廳的特色。
197
  (只需要回覆文字內容)
 
203
  )
204
  content = response.choices[0].message.content
205
 
206
+ # [修改] 如果開啟除錯模���,附加 Prompt 資訊
207
  if debug_mode:
208
  debug_info = f"""
209
  \n\n--- 🛠️ [DEBUG] LLM Prompt 檢查 ---
 
217
  except Exception as e:
218
  return f"Groq Error: {str(e)}"
219
 
 
220
  def generate_image_huggingface(prompt):
221
  if not HF_TOKEN: return None
222
  if not prompt or pd.isna(prompt): prompt = "Delicious gourmet food, photorealistic, 8k"
223
+
224
  try:
225
  hf_client = InferenceClient(token=HF_TOKEN)
226
  return hf_client.text_to_image(prompt=prompt, model="stabilityai/stable-diffusion-xl-base-1.0")
 
228
  print(f"❌ 生圖失敗: {e}")
229
  return None
230
 
231
+ # [修改] 增加 debug_mode 參數
232
  def mood_agent_logic(score_input, food_input, diary_input, quiz_state, debug_mode):
233
  restaurant, is_random, rec_categories, mood_reason = get_restaurant_data(score_input, food_input)
234
+
235
  if restaurant is None:
236
  yield "資料庫讀取錯誤", None, ""
237
  return
238
+
239
  name = restaurant['Name']
240
  address = restaurant['Address']
241
  url = restaurant['URL']
242
  img_prompt = restaurant.get('Visual_prompt')
243
  note = "(隨機推薦)" if is_random else ""
244
+
245
+ # RAG 檢索
246
  rag_info = str(restaurant.get('RAG_Content', ''))
247
  if global_retriever:
248
  docs = global_retriever.invoke(name)
249
+ if docs:
250
+ rag_info = "\n".join([d.page_content for d in docs])
251
 
252
+ # [修改] 傳入 debug_mode
253
  ai_text = generate_content_with_groq(name, rag_info, diary_input, score_input, quiz_state, mood_reason, debug_mode)
254
 
255
+ # [修改] 如果開啟除錯模式,附加圖片 Prompt 資訊
256
  if debug_mode:
257
  img_debug_info = f"""
258
  \n\n--- 🛠️ [DEBUG] 圖片生成檢查 ---
259
  \n**使用的 Visual Prompt:**\n{img_prompt}
260
+ \n(如果上方圖片為空白,可能是 HF API 忙碌或 Prompt 無效)
261
  \n-----------------------------------
262
  """
263
  ai_text += img_debug_info
264
 
265
  final_response = f"### 🍽️ 推薦:{name} {note}\n\n{ai_text}"
266
  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>'
267
+
268
  yield final_response, None, map_html
269
  image_output = generate_image_huggingface(img_prompt)
270
  yield final_response, image_output, map_html
271
 
272
  # ==========================================
273
+ # 4. 介面互動邏輯
274
  # ==========================================
275
+ def handle_q1_change(selected_label, current_state):
276
+ if not selected_label: return current_state, gr.Button(interactive=False)
277
+ current_state["q1"] = q1_options_map[selected_label]
278
+ return current_state, gr.Button(interactive=True, variant="primary")
279
 
280
+ def handle_q2_change(selected_label, current_state):
281
+ if not selected_label: return current_state, gr.Button(interactive=False)
282
+ current_state["q2"] = q2_options_map[selected_label]
283
+ return current_state, gr.Button(interactive=True, variant="primary")
284
+
285
+ def handle_q3_change(selected_label, current_state):
286
+ if not selected_label: return current_state, gr.Button(interactive=False)
287
+ current_state["q3"] = q3_options_map[selected_label]
288
+ return current_state, gr.Button(interactive=True, variant="primary")
289
+
290
+ def handle_q4_change(selected_label, current_state):
291
+ if not selected_label: return current_state, gr.Button(interactive=False)
292
+ current_state["q4"] = q4_options_map[selected_label]
293
+ return current_state, gr.Button(interactive=True, variant="primary")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
 
295
+ def handle_q5_change(selected_label, current_state):
296
+ if not selected_label: return current_state, gr.Button(interactive=False)
297
+ current_state["q5"] = q5_options_map[selected_label]
298
+ return current_state, gr.Button(interactive=True, variant="primary", value="完成測驗 (前往點餐) ➔")
299
 
300
  # ==========================================
301
  # 5. Gradio 介面建構
302
  # ==========================================
303
  with gr.Blocks(title="AI 心情食堂") as demo:
304
  gr.HTML(f"<style>{custom_css}</style>")
305
+ quiz_state = gr.State(value={})
 
 
306
 
307
  with gr.Tabs(elem_id="hidden_tabs") as tabs:
308
+ # Tab 0: Q1
309
+ with gr.TabItem("Q1", id=0):
310
+ with gr.Column():
311
+ gr.Markdown("### 🔮 第一題:直覺測試")
312
+ gr.Image(value=img_path_1, type="filepath", label="請觀察圖片", height=300)
313
+ gr.Markdown("**問題:請觀察上方圖片,如果是你,你會怎麼做?**")
314
+ radio_q1 = gr.Radio(choices=list(q1_options_map.keys()), label="請選擇", elem_classes="vertical-radio")
315
+ btn_q1_next = gr.Button("下一頁 ➔", interactive=False)
316
+
317
+ # Tab 1: Q2
318
+ with gr.TabItem("Q2", id=1):
319
+ with gr.Column():
320
+ gr.Markdown("### 🔮 第二題:魔法適性")
321
+ gr.Image(value=img_path_2, type="filepath", label="請觀察圖片", height=300)
322
+ gr.Markdown("**問題:身為魔導士的你,會選擇哪一個法術?**")
323
+ radio_q2 = gr.Radio(choices=list(q2_options_map.keys()), label="請選擇", elem_classes="vertical-radio")
324
+ btn_q2_next = gr.Button("下一頁 ➔", interactive=False)
325
+
326
+ # Tab 2: Q3
327
+ with gr.TabItem("Q3", id=2):
328
+ with gr.Column():
329
+ gr.Markdown("### 🔮 第三題:旅遊直覺")
330
+ gr.Image(value=img_path_3, type="filepath", label="請觀察圖片", height=300)
331
+ gr.Markdown("**問題三:不考慮其他因素,假你在桃機你最想去哪裡玩?**")
332
+ radio_q3 = gr.Radio(choices=list(q3_options_map.keys()), label="請選擇", elem_classes="vertical-radio")
333
+ btn_q3_next = gr.Button("下一頁 ➔", interactive=False)
334
+
335
+ # Tab 3: Q4
336
+ with gr.TabItem("Q4", id=3):
337
+ with gr.Column():
338
+ gr.Markdown("### 🔮 第四題:社交場合")
339
+ gr.Image(value=img_path_4, type="filepath", label="請觀察圖片", height=300)
340
+ gr.Markdown("**問題四:你是小大一,班上還不熟,現在你正參加你們班上的認識彼此的活動,下列哪一個人是你會選擇搭話的人?**")
341
+ radio_q4 = gr.Radio(choices=list(q4_options_map.keys()), label="請選擇", elem_classes="vertical-radio")
342
+ btn_q4_next = gr.Button("下一頁 ➔", interactive=False)
343
+
344
+ # Tab 4: Q5
345
+ with gr.TabItem("Q5", id=4):
346
+ with gr.Column():
347
+ gr.Markdown("### 🔮 第五題:追劇時光")
348
+ gr.Image(value=img_path_5, type="filepath", label="請觀察圖片", height=300)
349
+ gr.Markdown("**問題五:假設失憶了忘記以下所列的劇的劇情,而你現在閒了下來剛好想看劇,你會想看哪一部?**")
350
+ radio_q5 = gr.Radio(choices=list(q5_options_map.keys()), label="請選擇", elem_classes="vertical-radio")
351
+ btn_q5_finish = gr.Button("完成測驗 ➔", interactive=False)
352
 
353
  # Tab 5: Main
354
  with gr.TabItem("Main", id=5):
355
  with gr.Column():
356
  gr.Markdown(f"## 🍱 呷飽沒??!")
 
357
  with gr.Row():
358
  with gr.Column(scale=1):
359
  score_input = gr.Radio(["1 (心情差)", "2 (不太好)", "3 (普通)", "4 (不錯)", "5 (超棒)"], label="1. 心情分數", value="3 (普通)")
360
  food_input = gr.Radio(["吃飯", "吃麵", "隨便"], label="2. 想吃什麼", value="隨便")
361
  diary_input = gr.Textbox(lines=4, label="3. 心情日記", placeholder="寫下今天發生的事...")
362
+
363
+ # [新增] 除錯模式開關
364
  debug_mode_btn = gr.Checkbox(label="🔧 開啟除錯模式 (顯示 Prompt 與圖片資訊)", value=False)
365
+
366
  submit_btn = gr.Button("送出給 Agent", variant="primary")
367
  with gr.Column(scale=1):
368
  agent_output = gr.Markdown(label="AI 回應")
369
  image_output = gr.Image(label="AI 推薦美食圖", type="pil", width=400)
370
  map_output = gr.HTML(label="地圖導航")
371
 
372
+ # 事件綁定 (Events)
373
+ radio_q1.change(fn=handle_q1_change, inputs=[radio_q1, quiz_state], outputs=[quiz_state, btn_q1_next])
374
+ btn_q1_next.click(fn=lambda: gr.Tabs(selected=1), outputs=tabs)
375
+
376
+ radio_q2.change(fn=handle_q2_change, inputs=[radio_q2, quiz_state], outputs=[quiz_state, btn_q2_next])
377
+ btn_q2_next.click(fn=lambda: gr.Tabs(selected=2), outputs=tabs)
378
 
379
+ radio_q3.change(fn=handle_q3_change, inputs=[radio_q3, quiz_state], outputs=[quiz_state, btn_q3_next])
380
+ btn_q3_next.click(fn=lambda: gr.Tabs(selected=3), outputs=tabs)
 
 
 
 
381
 
382
+ radio_q4.change(fn=handle_q4_change, inputs=[radio_q4, quiz_state], outputs=[quiz_state, btn_q4_next])
383
+ btn_q4_next.click(fn=lambda: gr.Tabs(selected=4), outputs=tabs)
384
+
385
+ radio_q5.change(fn=handle_q5_change, inputs=[radio_q5, quiz_state], outputs=[quiz_state, btn_q5_finish])
386
+ btn_q5_finish.click(fn=lambda: gr.Tabs(selected=5), outputs=tabs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
387
 
388
+ # [修改] 加入 debug_mode_btn 到輸入
 
389
  submit_btn.click(
390
+ fn=mood_agent_logic,
391
  inputs=[score_input, food_input, diary_input, quiz_state, debug_mode_btn],
392
  outputs=[agent_output, image_output, map_output]
393
  )