PhilipL commited on
Commit
a578f9e
·
verified ·
1 Parent(s): da3cb03

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +405 -0
app.py ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from openai import OpenAI
3
+ from huggingface_hub import InferenceClient
4
+ import os
5
+ import sys
6
+ import subprocess
7
+ import time
8
+ import requests
9
+ import urllib.parse
10
+ import pandas as pd
11
+ from langchain_huggingface import HuggingFaceEmbeddings
12
+ from langchain_community.vectorstores import FAISS
13
+ from PIL import Image
14
+ from dotenv import load_dotenv
15
+
16
+ # ==========================================
17
+ # Step 0: 環境安裝檢查 (僅保留 Playwright)
18
+ # ==========================================
19
+ def install_playwright():
20
+ """確保 Playwright 瀏覽器核心有安裝"""
21
+ try:
22
+ import playwright
23
+ except ImportError:
24
+ print("⚠️ 偵測到缺少 playwright,正在強制安裝...")
25
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "playwright"])
26
+
27
+ # 設定瀏覽器路徑
28
+ os.environ["PLAYWRIGHT_BROWSERS_PATH"] = os.path.join(os.getcwd(), "playwright_browsers")
29
+
30
+ print("🔄 檢查 Chromium 瀏覽器...")
31
+ try:
32
+ # 檢查是否已安裝,若無則安裝
33
+ if not os.path.exists(os.environ["PLAYWRIGHT_BROWSERS_PATH"]):
34
+ subprocess.run([sys.executable, "-m", "playwright", "install", "chromium"], check=True)
35
+ except Exception as e:
36
+ print(f"⚠️ 瀏覽器安裝警告: {e}")
37
+
38
+ # 執行安裝
39
+ install_playwright()
40
+
41
+ # 延遲匯入
42
+ from playwright.sync_api import sync_playwright
43
+
44
+ load_dotenv()
45
+
46
+ # ==========================================
47
+ # 模組載入 (emotion 模組)
48
+ # ==========================================
49
+ import emotion
50
+
51
+ # ==========================================
52
+ # 0. 環境變數 & 1. 資料初始化
53
+ # ==========================================
54
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
55
+ HF_TOKEN = os.getenv("HF_TOKEN")
56
+
57
+ global_df = None
58
+ global_mood_df = None
59
+ global_retriever = None
60
+ rag_initialized = False
61
+
62
+ def init_static_data():
63
+ """初始化靜態的心情資料:讀取外部 CSV"""
64
+ global global_mood_df
65
+ if global_mood_df is None:
66
+ csv_path = 'mood_food_guide.csv'
67
+ if os.path.exists(csv_path):
68
+ try:
69
+ # 讀取 CSV,確保欄位正確
70
+ global_mood_df = pd.read_csv(csv_path)
71
+ print(f"✅ 成功載入心情指南:{csv_path}")
72
+ except Exception as e:
73
+ print(f"❌ 讀取 CSV 失敗: {e}")
74
+ global_mood_df = pd.DataFrame() # 建立空表防止後續報錯
75
+ else:
76
+ print(f"⚠️ 警告:找不到 {csv_path},請確認檔案已上傳至 Space。")
77
+ global_mood_df = pd.DataFrame()
78
+
79
+ # ==========================================
80
+ # API 金鑰檢查工具函式
81
+ # ==========================================
82
+ def check_api_key_status(name, key):
83
+ """檢查 API Key 是否存在,並回傳部分內容以供辨識"""
84
+ if not key:
85
+ return "❌ 未設定 (Not Set)"
86
+
87
+ # 遮罩處理,只顯示前後幾碼
88
+ if len(key) > 8:
89
+ masked = f"{key[:4]}...{key[-4:]}"
90
+ else:
91
+ masked = "******"
92
+ return f"✅ 已設定 ({masked})"
93
+
94
+ # ==========================================
95
+ # 2. Google Maps 爬蟲功能
96
+ # ==========================================
97
+ def sync_google_maps(url):
98
+ global global_df, global_retriever, rag_initialized
99
+ clean_url = url.strip() if url else ""
100
+ if not clean_url or "http" not in clean_url.lower():
101
+ yield "❌ 請輸入有效的 Google Maps 分享連結。"
102
+ return
103
+
104
+ try:
105
+ yield "🚀 [1/4] 啟動瀏覽器..."
106
+ with sync_playwright() as p:
107
+ browser = p.chromium.launch(headless=True)
108
+ page = browser.new_page()
109
+ yield "🌐 [2/4] 連線中..."
110
+ page.goto(clean_url, wait_until="domcontentloaded", timeout=60000)
111
+ yield "⏳ [3/4] 等待列表加載 (約 10 秒)..."
112
+ time.sleep(10)
113
+ yield "📄 [4/4] 解析餐廳資訊..."
114
+
115
+ titles = page.locator('div.fontHeadlineSmall').all_inner_texts()
116
+ details = page.locator('div.fontBodyMedium').all_inner_texts()
117
+
118
+ restaurant_list = []
119
+ for i, name in enumerate(titles):
120
+ name = name.strip()
121
+ if name:
122
+ addr = details[i].strip() if i < len(details) else ""
123
+ search_query = f"{name} {addr}"
124
+ restaurant_list.append({
125
+ "Name": name,
126
+ "Address": addr,
127
+ "Category": "未分類",
128
+ "RAG_Content": f"餐廳:{name},資訊:{addr}",
129
+ "URL": f"https://www.google.com/maps/search/?api=1&query={urllib.parse.quote(search_query)}"
130
+ })
131
+ browser.close()
132
+
133
+ if not restaurant_list:
134
+ yield "⚠️ 找不到餐廳。請確認連結格式正確且已公開。"
135
+ return
136
+
137
+ global_df = pd.DataFrame(restaurant_list)
138
+
139
+ try:
140
+ embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
141
+ vectorstore = FAISS.from_texts(global_df['RAG_Content'].tolist(), embeddings, metadatas=global_df.to_dict('records'))
142
+ global_retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
143
+ except Exception as e:
144
+ print(f"RAG 初始化警告: {e}")
145
+
146
+ rag_initialized = True
147
+ yield f"✅ 同步成功!已載入 {len(restaurant_list)} 間餐廳。"
148
+ except Exception as e:
149
+ yield f"❌ 系統錯誤:{str(e)}"
150
+
151
+ # ==========================================
152
+ # 3. 核心功能 (AI Agent)
153
+ # ==========================================
154
+ def get_restaurant_data(mood_score_str, food_choice):
155
+ init_static_data() # 確保心情指南已載入
156
+
157
+ if global_df is None or global_df.empty:
158
+ return None, True, "", "資料庫未載入,無建議"
159
+
160
+ # 解析分數 (例如 "3 (普通)" -> 3)
161
+ try: score = int(str(mood_score_str).split(' ')[0])
162
+ except: score = 3
163
+
164
+ # 從 CSV 資料中查找對應的推薦類別與原因
165
+ rec_categories = ""
166
+ mood_reason = "隨意探索"
167
+
168
+ if global_mood_df is not None and not global_mood_df.empty:
169
+ mood_info = global_mood_df[global_mood_df['分數'] == score]
170
+ if not mood_info.empty:
171
+ rec_categories = mood_info.iloc[0]['推薦料理類別']
172
+ mood_reason = mood_info.iloc[0]['原因']
173
+
174
+ candidates = global_df.copy()
175
+ food_keyword = "飯" if food_choice == "吃飯" else "麵" if food_choice == "吃麵" else ""
176
+
177
+ is_random = False
178
+ if food_keyword:
179
+ filtered = candidates[candidates['Name'].str.contains(food_keyword, case=False, na=False) | candidates['RAG_Content'].str.contains(food_keyword, case=False, na=False)]
180
+ if not filtered.empty:
181
+ candidates = filtered
182
+ else:
183
+ is_random = True
184
+
185
+ if candidates.empty:
186
+ result = global_df.sample(1).iloc[0]; is_random = True
187
+ else:
188
+ result = candidates.sample(1).iloc[0]
189
+
190
+ return result, is_random, rec_categories, mood_reason
191
+
192
+ def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, mood_score, mood_guide_reason, debug_mode=False):
193
+ if not GROQ_API_KEY: return "⚠️ 請設定 GROQ_API_KEY", ""
194
+
195
+ client = OpenAI(api_key=GROQ_API_KEY, base_url="https://api.groq.com/openai/v1")
196
+
197
+ system_prompt = "你是一個幽默、懂吃且善解人意的 AI 朋友。請根據使用者的日記、心情以及「心情美食指南」來推薦餐廳。"
198
+ user_msg = f"""
199
+ 【狀態】心情分數:{mood_score},日記:{user_diary}
200
+ 【心情美食指南建議】
201
+ 因為分數是 {mood_score},建議吃這類食物的原因是:「{mood_guide_reason}」。
202
+
203
+ 【推薦餐廳】
204
+ 名稱:{restaurant_name}
205
+ 資料:{restaurant_detail}
206
+
207
+ 任務:
208
+ 請用繁體中文寫一段溫暖有趣的回覆:
209
+ 1. 先回應他的日記與測驗人設。
210
+ 2. 引用「心情美食指南」的原因,告訴他為什麼現在適合吃這家餐廳。
211
+ 3. 介紹這家餐廳的特色。
212
+ """
213
+
214
+ debug_log = ""
215
+ if debug_mode:
216
+ debug_log = f"### 🔧 Groq Prompt Debug\n**System:** {system_prompt}\n**User:** {user_msg}"
217
+
218
+ try:
219
+ response = client.chat.completions.create(model="llama-3.3-70b-versatile", messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_msg}])
220
+ return response.choices[0].message.content, debug_log
221
+ except Exception as e:
222
+ return f"Groq Error: {str(e)}", debug_log
223
+
224
+ def generate_image_huggingface(prompt):
225
+ if not HF_TOKEN:
226
+ return None, "HF_TOKEN 未設定"
227
+
228
+ try:
229
+ hf_client = InferenceClient(token=HF_TOKEN)
230
+ image = hf_client.text_to_image(
231
+ prompt=prompt,
232
+ negative_prompt="blurry, low quality, distortion, text, watermark",
233
+ model="stabilityai/stable-diffusion-xl-base-1.0"
234
+ )
235
+ return image, None # 成功時,錯誤訊息為 None
236
+ except Exception as e:
237
+ # 回傳具體錯誤訊息
238
+ return None, str(e)
239
+
240
+ def mood_agent_logic(score_input, food_input, diary_input, debug_mode):
241
+ if not rag_initialized:
242
+ yield "⚠️ 請先同步地圖清單!", None, "", gr.update()
243
+ return
244
+
245
+ restaurant, is_random, rec_categories, mood_reason = get_restaurant_data(score_input, food_input)
246
+ if restaurant is None:
247
+ yield "資料庫讀取錯誤", None, "", gr.update()
248
+ return
249
+
250
+ name = restaurant['Name']; url = restaurant['URL']
251
+ info = restaurant.get('RAG_Content', '')
252
+ rag_info = str(restaurant.get('RAG_Content', ''))
253
+
254
+ img_prompt = f"Delicious food photography of {name}, {info}. high quality, photorealistic, 8k, cinematic lighting, appetizing, restaurant atmosphere, 50mm lens"
255
+
256
+ ai_text, groq_debug_log = generate_content_with_groq(name, rag_info, diary_input, score_input, mood_reason, debug_mode)
257
+
258
+ prefix = ""
259
+ if is_random and food_input != "隨便":
260
+ prefix = f"> 💡 **溫馨提示**:清單中暫無『{food_input}』,已從現有名單挑選最適合的店!\n\n"
261
+
262
+ # 組合完整的除錯資訊,包含 API Key 狀態與錯誤訊息
263
+ full_debug_log = ""
264
+ if debug_mode:
265
+ # 1. 檢查 Key 狀態
266
+ groq_status = check_api_key_status("GROQ_API_KEY", GROQ_API_KEY)
267
+ hf_status = check_api_key_status("HF_TOKEN", HF_TOKEN)
268
+
269
+ api_debug_block = f"""
270
+ ### 🔑 API 金鑰與系統狀態
271
+ - **GROQ_API_KEY**: {groq_status}
272
+ - **HF_TOKEN**: {hf_status}
273
+ - **RAG 狀態**: {"✅ 已初始化" if rag_initialized else "❌ 未初始化"}
274
+ """
275
+ full_debug_log = api_debug_block + "\n" + groq_debug_log + f"\n\n### 🎨 Image Prompt Debug\n{img_prompt}"
276
+
277
+ debug_output_update = gr.update(value=full_debug_log, visible=debug_mode)
278
+
279
+ final_response = f"{prefix}### 🍽️ 推薦:{name}\n\n{ai_text}"
280
+ 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>'
281
+
282
+ # 先回傳文字
283
+ yield final_response, None, map_html, debug_output_update
284
+
285
+ # 呼叫圖片生成並捕捉錯誤
286
+ image_output, img_error = generate_image_huggingface(img_prompt)
287
+
288
+ # 如果有圖片錯誤且在除錯模式,追加錯誤訊息到 log
289
+ if img_error and debug_mode:
290
+ full_debug_log += f"\n\n⚠️ **Hugging Face 圖片生成失敗:**\n{img_error}"
291
+ debug_output_update = gr.update(value=full_debug_log)
292
+
293
+ yield final_response, image_output, map_html, debug_output_update
294
+
295
+ # ==========================================
296
+ # 4. 橋接邏輯
297
+ # ==========================================
298
+ def _score_to_radio_value(score):
299
+ mapping = {1: "1 (心情差)", 2: "2 (不太好)", 3: "3 (普通)", 4: "4 (不錯)", 5: "5 (超棒)"}
300
+ try: score = int(score)
301
+ except: score = 3
302
+ return mapping.get(score, "3 (普通)")
303
+
304
+ def bridge_start_click(st):
305
+ try:
306
+ res = emotion.on_restart(st)
307
+ return res[1], res[0], gr.update(visible=True), res[5], res[4], gr.update(visible=False)
308
+ except: return gr.update(), gr.update(), gr.update(), gr.update(), st, gr.update()
309
+
310
+ def bridge_stop_click(st):
311
+ try:
312
+ res = emotion.on_stop(st)
313
+ return res[1], res[0], gr.update(visible=False), res[5], res[4]
314
+ except: return gr.update(), gr.update(), gr.update(), gr.update(), st
315
+
316
+ def bridge_predict_frame(frame, st):
317
+ try:
318
+ res = emotion.on_stream(frame, st)
319
+ out_cam = res[0]; out_result = res[1]; out_st = res[4]; out_btn_start = res[5]
320
+ score_update = gr.update(); btn_go_visible = gr.update(visible=False)
321
+ out_btn_stop = gr.update()
322
+
323
+ if hasattr(out_st, 'finished') and out_st.finished and hasattr(out_st, 'final_score'):
324
+ new_val = _score_to_radio_value(out_st.final_score)
325
+ score_update = gr.update(value=new_val)
326
+ out_btn_stop = gr.update(visible=False)
327
+ btn_go_visible = gr.update(visible=True)
328
+
329
+ return out_cam, out_result, out_st, out_btn_stop, out_btn_start, score_update, btn_go_visible
330
+ except Exception as e:
331
+ return frame, gr.update(), st, gr.update(), gr.update(), gr.update(), gr.update()
332
+
333
+ def bridge_predict_upload(img, st):
334
+ try:
335
+ res = emotion.on_upload(img, st)
336
+ out_result, out_st = res[0], res[2]
337
+ score_update = gr.update()
338
+ if hasattr(out_st, 'finished') and out_st.finished and hasattr(out_st, 'final_score'):
339
+ new_val = _score_to_radio_value(out_st.final_score)
340
+ score_update = gr.update(value=new_val)
341
+ return out_result, score_update, gr.Tabs(selected=1), out_st
342
+ except: return gr.update(), gr.update(), gr.Tabs(), st
343
+
344
+ # ==========================================
345
+ # 5. Gradio 介面
346
+ # ==========================================
347
+ css_ = "#app_container { max-width: 960px; margin: 0 auto; }"
348
+ if hasattr(emotion, 'css'): css_ += "\n" + emotion.css
349
+
350
+ with gr.Blocks(title="AI 心情食堂", css=css_) as demo:
351
+ st_state = gr.State(emotion.AppState())
352
+
353
+ with gr.Tabs() as tabs:
354
+ # Tab 1
355
+ with gr.TabItem("😊 情緒辨識 (Step 1)", id=0):
356
+ with gr.Column(elem_id="app_container"):
357
+ gr.Markdown("### 第一步:測測你的心情能量\n讓 AI 看看你的表情,自動幫你決定心情分數!")
358
+ with gr.Row():
359
+ btn_start = gr.Button("📸 開啟攝影機辨識", variant="primary")
360
+ btn_stop = gr.Button("⏹️ 停止", variant="secondary", visible=False)
361
+ cam = gr.Image(sources=["webcam"], streaming=True, type="numpy", label="攝影機畫面", visible=False)
362
+ result_markdown = gr.Markdown(emotion._hint_html("請按「開啟攝影機辨識」並允許瀏覽器使用相機。"))
363
+ btn_go_dining = gr.Button("🚀 確定心情,來找餐廳!", variant="primary", visible=False, size="lg")
364
+
365
+ # Tab 2
366
+ with gr.TabItem("🍽️ AI 心情食堂 (Step 2)", id=1):
367
+ with gr.Column():
368
+ gr.Markdown(f"## 🔗 載入你的口袋名單")
369
+ with gr.Row():
370
+ map_url = gr.Textbox(label="Google Maps Saved Lists 連結", placeholder="請貼上清單的分享連結...", scale=3)
371
+ sync_btn = gr.Button("🔄 同步清單", variant="secondary", scale=1)
372
+ sync_msg = gr.Markdown("ℹ️ 尚未同步資料庫")
373
+ gr.Markdown("---")
374
+ gr.Markdown(f"## 🍱 今天想吃點什麼?")
375
+ with gr.Row():
376
+ with gr.Column(scale=1):
377
+ score_input = gr.Radio(["1 (心情差)", "2 (不太好)", "3 (普通)", "4 (不錯)", "5 (超棒)"], label="1. 心情分數 (由 Tab 1 自動填入)", value="3 (普通)")
378
+ food_input = gr.Radio(["吃飯", "吃麵", "隨便"], label="2. 想吃什麼", value="隨便")
379
+ diary_input = gr.Textbox(lines=4, label="3. 心情日記", placeholder="寫下今天發生的事...")
380
+
381
+ debug_mode_btn = gr.Checkbox(label="🔧 開啟除錯模式", value=False)
382
+ submit_btn = gr.Button("🍱 送出給 Agent", variant="primary")
383
+ debug_output = gr.Markdown(label="除錯資訊 (Debug Log)", visible=False)
384
+
385
+ with gr.Column(scale=1):
386
+ agent_output = gr.Markdown(label="AI 回應")
387
+ image_output = gr.Image(label="AI 推薦美食圖", type="pil", width=400)
388
+ map_output = gr.HTML(label="地圖導航")
389
+
390
+ # 事件
391
+ sync_btn.click(fn=sync_google_maps, inputs=[map_url], outputs=[sync_msg])
392
+ btn_start.click(fn=bridge_start_click, inputs=[st_state], outputs=[result_markdown, cam, btn_stop, btn_start, st_state, btn_go_dining])
393
+ btn_stop.click(fn=bridge_stop_click, inputs=[st_state], outputs=[result_markdown, cam, btn_stop, btn_start, st_state])
394
+ cam.stream(fn=bridge_predict_frame, inputs=[cam, st_state], outputs=[cam, result_markdown, st_state, btn_stop, btn_start, score_input, btn_go_dining])
395
+ btn_go_dining.click(fn=lambda: gr.Tabs(selected=1), inputs=None, outputs=tabs)
396
+
397
+ # debug_mode
398
+ submit_btn.click(
399
+ fn=mood_agent_logic,
400
+ inputs=[score_input, food_input, diary_input, debug_mode_btn],
401
+ outputs=[agent_output, image_output, map_output, debug_output]
402
+ )
403
+
404
+ if __name__ == "__main__":
405
+ demo.launch(ssr_mode=False)