Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,6 +8,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
|
|
@@ -92,25 +93,53 @@ def check_api_key_status(name, key):
|
|
| 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()
|
|
@@ -120,22 +149,36 @@ def sync_google_maps(url):
|
|
| 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'))
|
|
@@ -144,14 +187,20 @@ def sync_google_maps(url):
|
|
| 144 |
print(f"RAG 初始化警告: {e}")
|
| 145 |
|
| 146 |
rag_initialized = True
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
| 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:
|
|
@@ -172,6 +221,15 @@ def get_restaurant_data(mood_score_str, food_choice):
|
|
| 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
|
|
@@ -183,7 +241,11 @@ def get_restaurant_data(mood_score_str, food_choice):
|
|
| 183 |
is_random = True
|
| 184 |
|
| 185 |
if candidates.empty:
|
| 186 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
else:
|
| 188 |
result = candidates.sample(1).iloc[0]
|
| 189 |
|
|
@@ -237,14 +299,18 @@ def generate_image_huggingface(prompt):
|
|
| 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 |
-
|
| 246 |
-
|
| 247 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 248 |
return
|
| 249 |
|
| 250 |
name = restaurant['Name']; url = restaurant['URL']
|
|
@@ -256,8 +322,11 @@ def mood_agent_logic(score_input, food_input, diary_input, debug_mode):
|
|
| 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
|
| 260 |
-
|
|
|
|
|
|
|
|
|
|
| 261 |
|
| 262 |
# 組合完整的除錯資訊,包含 API Key 狀態與錯誤訊息
|
| 263 |
full_debug_log = ""
|
|
@@ -271,6 +340,7 @@ def mood_agent_logic(score_input, food_input, diary_input, debug_mode):
|
|
| 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 |
|
|
@@ -369,6 +439,10 @@ with gr.Blocks(title="AI 心情食堂", css=css_) as demo:
|
|
| 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"## 🍱 今天想吃點什麼?")
|
|
@@ -388,16 +462,18 @@ with gr.Blocks(title="AI 心情食堂", css=css_) as demo:
|
|
| 388 |
map_output = gr.HTML(label="地圖導航")
|
| 389 |
|
| 390 |
# 事件
|
| 391 |
-
sync_btn
|
|
|
|
|
|
|
| 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 |
-
#
|
| 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 |
|
|
|
|
| 8 |
import requests
|
| 9 |
import urllib.parse
|
| 10 |
import pandas as pd
|
| 11 |
+
import re # 新增 re 模組用於解析地址
|
| 12 |
from langchain_huggingface import HuggingFaceEmbeddings
|
| 13 |
from langchain_community.vectorstores import FAISS
|
| 14 |
from PIL import Image
|
|
|
|
| 93 |
return f"✅ 已設定 ({masked})"
|
| 94 |
|
| 95 |
# ==========================================
|
| 96 |
+
# 2. Google Maps 爬蟲與資料處理功能
|
| 97 |
# ==========================================
|
| 98 |
+
def extract_city(address):
|
| 99 |
+
"""從地址中解析縣市名稱"""
|
| 100 |
+
if not isinstance(address, str) or not address:
|
| 101 |
+
return "未知地區"
|
| 102 |
+
|
| 103 |
+
# 常見的台灣縣市列表
|
| 104 |
+
cities = [
|
| 105 |
+
"台北市", "新北市", "基隆市", "桃園市", "新竹市", "新竹縣", "苗栗縣",
|
| 106 |
+
"台中市", "彰化縣", "南投縣", "雲林縣", "嘉義市", "嘉義縣", "台南市",
|
| 107 |
+
"高雄市", "屏東縣", "宜蘭縣", "花蓮縣", "台東縣", "澎湖縣", "金門縣", "連江縣"
|
| 108 |
+
]
|
| 109 |
+
|
| 110 |
+
# 1. 直接比對
|
| 111 |
+
for city in cities:
|
| 112 |
+
if city in address:
|
| 113 |
+
return city
|
| 114 |
+
|
| 115 |
+
# 2. 正則表達式備案 (抓取 'XX市' 或 'XX縣')
|
| 116 |
+
match = re.search(r'(\w{2,3}[縣市])', address)
|
| 117 |
+
if match:
|
| 118 |
+
return match.group(1)
|
| 119 |
+
|
| 120 |
+
return "其他地區"
|
| 121 |
+
|
| 122 |
def sync_google_maps(url):
|
| 123 |
global global_df, global_retriever, rag_initialized
|
| 124 |
clean_url = url.strip() if url else ""
|
| 125 |
+
|
| 126 |
+
# 初始狀態:不更新下拉選單
|
| 127 |
+
no_update = gr.update()
|
| 128 |
+
|
| 129 |
if not clean_url or "http" not in clean_url.lower():
|
| 130 |
+
yield "❌ 請輸入有效的 Google Maps 分享連結。", no_update
|
| 131 |
return
|
| 132 |
|
| 133 |
try:
|
| 134 |
+
yield "🚀 [1/4] 啟動瀏覽器...", no_update
|
| 135 |
with sync_playwright() as p:
|
| 136 |
browser = p.chromium.launch(headless=True)
|
| 137 |
page = browser.new_page()
|
| 138 |
+
yield "🌐 [2/4] 連線中...", no_update
|
| 139 |
page.goto(clean_url, wait_until="domcontentloaded", timeout=60000)
|
| 140 |
+
yield "⏳ [3/4] 等待列表加載 (約 10 秒)...", no_update
|
| 141 |
time.sleep(10)
|
| 142 |
+
yield "📄 [4/4] 解析餐廳資訊...", no_update
|
| 143 |
|
| 144 |
titles = page.locator('div.fontHeadlineSmall').all_inner_texts()
|
| 145 |
details = page.locator('div.fontBodyMedium').all_inner_texts()
|
|
|
|
| 149 |
name = name.strip()
|
| 150 |
if name:
|
| 151 |
addr = details[i].strip() if i < len(details) else ""
|
| 152 |
+
# 解析縣市
|
| 153 |
+
city = extract_city(addr)
|
| 154 |
+
|
| 155 |
search_query = f"{name} {addr}"
|
| 156 |
restaurant_list.append({
|
| 157 |
"Name": name,
|
| 158 |
"Address": addr,
|
| 159 |
+
"City": city, # 新增欄位
|
| 160 |
"Category": "未分類",
|
| 161 |
+
"RAG_Content": f"餐廳:{name},地區:{city},資訊:{addr}",
|
| 162 |
"URL": f"https://www.google.com/maps/search/?api=1&query={urllib.parse.quote(search_query)}"
|
| 163 |
})
|
| 164 |
browser.close()
|
| 165 |
|
| 166 |
if not restaurant_list:
|
| 167 |
+
yield "⚠️ 找不到餐廳。請確認連結格式正確且已公開。", no_update
|
| 168 |
return
|
| 169 |
|
| 170 |
global_df = pd.DataFrame(restaurant_list)
|
| 171 |
|
| 172 |
+
# 準備下拉選單的選項
|
| 173 |
+
unique_cities = sorted(global_df['City'].unique().tolist())
|
| 174 |
+
# 將 '未知地區' 或 '其他地區' 移到最後
|
| 175 |
+
if "其他地區" in unique_cities:
|
| 176 |
+
unique_cities.remove("其他地區")
|
| 177 |
+
unique_cities.append("其他地區")
|
| 178 |
+
|
| 179 |
+
# 插入「全區」選項
|
| 180 |
+
dropdown_choices = ["全區"] + unique_cities
|
| 181 |
+
|
| 182 |
try:
|
| 183 |
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 184 |
vectorstore = FAISS.from_texts(global_df['RAG_Content'].tolist(), embeddings, metadatas=global_df.to_dict('records'))
|
|
|
|
| 187 |
print(f"RAG 初始化警告: {e}")
|
| 188 |
|
| 189 |
rag_initialized = True
|
| 190 |
+
|
| 191 |
+
# 回傳成功訊息以及下拉選單的更新 (設為預設選第一項 '全區')
|
| 192 |
+
yield f"✅ 同步成功!已載入 {len(restaurant_list)} 間餐廳。", gr.update(choices=dropdown_choices, value="全區", visible=True)
|
| 193 |
+
|
| 194 |
except Exception as e:
|
| 195 |
+
yield f"❌ 系統錯誤:{str(e)}", no_update
|
| 196 |
|
| 197 |
# ==========================================
|
| 198 |
# 3. 核心功能 (AI Agent)
|
| 199 |
# ==========================================
|
| 200 |
+
def get_restaurant_data(mood_score_str, food_choice, location_filter="全區"):
|
| 201 |
+
"""
|
| 202 |
+
依據心情、食物類別與「地區」篩選餐廳
|
| 203 |
+
"""
|
| 204 |
init_static_data() # 確保心情指南已載入
|
| 205 |
|
| 206 |
if global_df is None or global_df.empty:
|
|
|
|
| 221 |
mood_reason = mood_info.iloc[0]['原因']
|
| 222 |
|
| 223 |
candidates = global_df.copy()
|
| 224 |
+
|
| 225 |
+
# --- 新增:地區篩選邏輯 ---
|
| 226 |
+
if location_filter and location_filter != "全區":
|
| 227 |
+
candidates = candidates[candidates['City'] == location_filter]
|
| 228 |
+
# 如果篩選後沒資料,則退回全部資料並標記 Random (或者回傳空值讓前端顯示警告)
|
| 229 |
+
if candidates.empty:
|
| 230 |
+
return None, True, "", f"在【{location_filter}】找不到餐廳,請嘗試切換地區。"
|
| 231 |
+
# ------------------------
|
| 232 |
+
|
| 233 |
food_keyword = "飯" if food_choice == "吃飯" else "麵" if food_choice == "吃麵" else ""
|
| 234 |
|
| 235 |
is_random = False
|
|
|
|
| 241 |
is_random = True
|
| 242 |
|
| 243 |
if candidates.empty:
|
| 244 |
+
# 如果經過兩層篩選都沒東西,就從 global_df 隨便抓 (但盡量遵守地區)
|
| 245 |
+
backup_pool = global_df[global_df['City'] == location_filter] if location_filter != "全區" else global_df
|
| 246 |
+
if backup_pool.empty: backup_pool = global_df
|
| 247 |
+
|
| 248 |
+
result = backup_pool.sample(1).iloc[0]; is_random = True
|
| 249 |
else:
|
| 250 |
result = candidates.sample(1).iloc[0]
|
| 251 |
|
|
|
|
| 299 |
# 回傳具體錯誤訊息
|
| 300 |
return None, str(e)
|
| 301 |
|
| 302 |
+
def mood_agent_logic(score_input, food_input, location_input, diary_input, debug_mode):
|
| 303 |
if not rag_initialized:
|
| 304 |
yield "⚠️ 請先同步地圖清單!", None, "", gr.update()
|
| 305 |
return
|
| 306 |
|
| 307 |
+
# 傳入 location_input 進行篩選
|
| 308 |
+
restaurant, is_random, rec_categories, mood_reason = get_restaurant_data(score_input, food_input, location_input)
|
| 309 |
+
|
| 310 |
+
# 錯誤處理:如果 restaurant 是 None,通常是因為該地區沒餐廳
|
| 311 |
+
if restaurant is None:
|
| 312 |
+
error_msg = mood_reason # 這裡借用 mood_reason 回傳錯誤訊息
|
| 313 |
+
yield f"❌ {error_msg}", None, "", gr.update()
|
| 314 |
return
|
| 315 |
|
| 316 |
name = restaurant['Name']; url = restaurant['URL']
|
|
|
|
| 322 |
ai_text, groq_debug_log = generate_content_with_groq(name, rag_info, diary_input, score_input, mood_reason, debug_mode)
|
| 323 |
|
| 324 |
prefix = ""
|
| 325 |
+
if is_random:
|
| 326 |
+
if food_input != "隨便":
|
| 327 |
+
prefix = f"> 💡 **溫馨提示**:在 {location_input} 的清單中暫無『{food_input}』,已為您挑選其他類型的美味!\n\n"
|
| 328 |
+
else:
|
| 329 |
+
prefix = f"> 💡 **探索模式**:在 {location_input} 為您精選了一家餐廳!\n\n"
|
| 330 |
|
| 331 |
# 組合完整的除錯資訊,包含 API Key 狀態與錯誤訊息
|
| 332 |
full_debug_log = ""
|
|
|
|
| 340 |
- **GROQ_API_KEY**: {groq_status}
|
| 341 |
- **HF_TOKEN**: {hf_status}
|
| 342 |
- **RAG 狀態**: {"✅ 已初始化" if rag_initialized else "❌ 未初始化"}
|
| 343 |
+
- **目前篩選地區**: {location_input}
|
| 344 |
"""
|
| 345 |
full_debug_log = api_debug_block + "\n" + groq_debug_log + f"\n\n### 🎨 Image Prompt Debug\n{img_prompt}"
|
| 346 |
|
|
|
|
| 439 |
with gr.Row():
|
| 440 |
map_url = gr.Textbox(label="Google Maps Saved Lists 連結", placeholder="請貼上清單的分享連結...", scale=3)
|
| 441 |
sync_btn = gr.Button("🔄 同步清單", variant="secondary", scale=1)
|
| 442 |
+
|
| 443 |
+
# 新增:動態下拉選單
|
| 444 |
+
location_dropdown = gr.Dropdown(label="📍 選擇餐廳地區 (同步後自動更新)", choices=["請先同步清單"], value="請先同步清單", interactive=True)
|
| 445 |
+
|
| 446 |
sync_msg = gr.Markdown("ℹ️ 尚未同步資料庫")
|
| 447 |
gr.Markdown("---")
|
| 448 |
gr.Markdown(f"## 🍱 今天想吃點什麼?")
|
|
|
|
| 462 |
map_output = gr.HTML(label="地圖導航")
|
| 463 |
|
| 464 |
# 事件
|
| 465 |
+
# 修改:sync_btn 現在會同時更新 sync_msg 和 location_dropdown
|
| 466 |
+
sync_btn.click(fn=sync_google_maps, inputs=[map_url], outputs=[sync_msg, location_dropdown])
|
| 467 |
+
|
| 468 |
btn_start.click(fn=bridge_start_click, inputs=[st_state], outputs=[result_markdown, cam, btn_stop, btn_start, st_state, btn_go_dining])
|
| 469 |
btn_stop.click(fn=bridge_stop_click, inputs=[st_state], outputs=[result_markdown, cam, btn_stop, btn_start, st_state])
|
| 470 |
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])
|
| 471 |
btn_go_dining.click(fn=lambda: gr.Tabs(selected=1), inputs=None, outputs=tabs)
|
| 472 |
|
| 473 |
+
# 修改:submit_btn 加入 location_dropdown 作為輸入
|
| 474 |
submit_btn.click(
|
| 475 |
fn=mood_agent_logic,
|
| 476 |
+
inputs=[score_input, food_input, location_dropdown, diary_input, debug_mode_btn],
|
| 477 |
outputs=[agent_output, image_output, map_output, debug_output]
|
| 478 |
)
|
| 479 |
|