Spaces:
Sleeping
Sleeping
Update app.py
Browse files7 unmodified lines891011121378 unmodified lines92939495969798991001011021031041051061071081091101111121131141151163 unmodified lines1201211221231241251261271281291301311321331341351361371381391401412 unmodified lines14414514614714814915015115215315415515615714 unmodified lines1721731741751761775 unmodified lines18318418518618718818947 unmodified lines2372382392402412422432442452462472482492505 unmodified lines2562572582592602612622637 unmodified lines27127227327427527692 unmodified lines36937037137237337413 unmodified lines3883893903913923933943953963973983994004014024037 unmodified linesimport requestsimport urllib.parseimport pandas as pdfrom langchain_huggingface import HuggingFaceEmbeddingsfrom langchain_community.vectorstores import FAISSfrom PIL import Image78 unmodified linesreturn f"✅ 已設定 ({masked})"# ==========================================# 2. Google Maps 爬蟲功能# ==========================================def sync_google_maps(url):global global_df, global_retriever, rag_initializedclean_url = url.strip() if url else ""if not clean_url or "http" not in clean_url.lower():yield "❌ 請輸入有效的 Google Maps 分享連結。"returntry:yield "🚀 [1/4] 啟動瀏覽器..."with sync_playwright() as p:browser = p.chromium.launch(headless=True)page = browser.new_page()yield "🌐 [2/4] 連線中..."page.goto(clean_url, wait_until="domcontentloaded", timeout=60000)yield "⏳ [3/4] 等待列表加載 (約 10 秒)..."time.sleep(10)yield "📄 [4/4] 解析餐廳資訊..."titles = page.locator('div.fontHeadlineSmall').all_inner_texts()details = page.locator('div.fontBodyMedium').all_inner_texts()3 unmodified linesname = name.strip()if name:addr = details[i].strip() if i < len(details) else ""search_query = f"{name} {addr}"restaurant_list.append({"Name": name,"Address": addr,"Category": "未分類","RAG_Content": f"餐廳:{name},資訊:{addr}","URL": f"https://www.google.com/maps/search/?api=1&query={urllib.parse.quote(search_query)}"})browser.close()if not restaurant_list:yield "⚠️ 找不到餐廳。請確認連結格式正確且已公開。"returnglobal_df = pd.DataFrame(restaurant_list)try:embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")vectorstore = FAISS.from_texts(global_df['RAG_Content'].tolist(), embeddings, metadatas=global_df.to_dict('records'))2 unmodified linesprint(f"RAG 初始化警告: {e}")rag_initialized = Trueyield f"✅ 同步成功!已載入 {len(restaurant_list)} 間餐廳。"except Exception as e:yield f"❌ 系統錯誤:{str(e)}"# ==========================================# 3. 核心功能 (AI Agent)# ==========================================def get_restaurant_data(mood_score_str, food_choice):init_static_data() # 確保心情指南已載入if global_df is None or global_df.empty:14 unmodified linesmood_reason = mood_info.iloc[0]['原因']candidates = global_df.copy()food_keyword = "飯" if food_choice == "吃飯" else "麵" if food_choice == "吃麵" else ""is_random = False5 unmodified linesis_random = Trueif candidates.empty:result = global_df.sample(1).iloc[0]; is_random = Trueelse:result = candidates.sample(1).iloc[0]47 unmodified lines# 回傳具體錯誤訊息return None, str(e)def mood_agent_logic(score_input, food_input, diary_input, debug_mode):if not rag_initialized:yield "⚠️ 請先同步地圖清單!", None, "", gr.update()returnrestaurant, is_random, rec_categories, mood_reason = get_restaurant_data(score_input, food_input)if restaurant is None:yield "資料庫讀取錯誤", None, "", gr.update()returnname = restaurant['Name']; url = restaurant['URL']5 unmodified linesai_text, groq_debug_log = generate_content_with_groq(name, rag_info, diary_input, score_input, mood_reason, debug_mode)prefix = ""if is_random and food_input != "隨便":prefix = f"> 💡 **溫馨提示**:清單中暫無『{food_input}』,已從現有名單挑選最適合的店!\n\n"# 組合完整的除錯資訊,包含 API Key 狀態與錯誤訊息full_debug_log = ""7 unmodified lines- **GROQ_API_KEY**: {groq_status}- **HF_TOKEN**: {hf_status}- **RAG 狀態**: {"✅ 已初始化" if rag_initialized else "❌ 未初始化"}"""full_debug_log = api_debug_block + "\n" + groq_debug_log + f"\n\n### 🎨 Image Prompt Debug\n{img_prompt}"92 unmodified lineswith gr.Row():map_url = gr.Textbox(label="Google Maps Saved Lists 連結", placeholder="請貼上清單的分享連結...", scale=3)sync_btn = gr.Button("🔄 同步清單", variant="secondary", scale=1)sync_msg = gr.Markdown("ℹ️ 尚未同步資料庫")gr.Markdown("---")gr.Markdown(f"## 🍱 今天想吃點什麼?")13 unmodified linesmap_output = gr.HTML(label="地圖導航")# 事件sync_btn.click(fn=sync_google_maps, inputs=[map_url], outputs=[sync_msg])btn_start.click(fn=bridge_start_click, inputs=[st_state], outputs=[result_markdown, cam, btn_stop, btn_start, st_state, btn_go_dining])btn_stop.click(fn=bridge_stop_click, inputs=[st_state], outputs=[result_markdown, cam, btn_stop, btn_start, st_state])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])btn_go_dining.click(fn=lambda: gr.Tabs(selected=1), inputs=None, outputs=tabs)# debug_modesubmit_btn.click(fn=mood_agent_logic,inputs=[score_input, food_input, diary_input, debug_mode_btn],outputs=[agent_output, image_output, map_output, debug_output])7 unmodified lines89101112131478 unmodified lines939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441453 unmodified lines1491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831842 unmodified lines18718818919019119219319419519619719819920020120220320420520614 unmodified lines2212222232242252262272282292302312322332342355 unmodified lines24124224324424524624724824925025147 unmodified lines2993003013023033043053063073083093103113123133143153165 unmodified lines3223233243253263273283293303313327 unmodified lines34034134234334434534692 unmodified lines43944044144244344444544644744813 unmodified lines4624634644654664674684694704714724734744754764774784797 unmodified linesimport requestsimport urllib.parseimport pandas as pdimport re # 新增 re 模組用於解析地址from langchain_huggingface import HuggingFaceEmbeddingsfrom langchain_community.vectorstores import FAISSfrom PIL import Image78 unmodified linesreturn f"✅ 已設定 ({masked})"# ==========================================# 2. Google Maps 爬蟲與資料處理功能# ==========================================def extract_city(address):"""從地址中解析縣市名稱"""if not isinstance(address, str) or not address:return "未知地區"# 常見的台灣縣市列表cities = ["台北市", "新北市", "基隆市", "桃園市", "新竹市", "新竹縣", "苗栗縣","台中市", "彰化縣", "南投縣", "雲林縣", "嘉義市", "嘉義縣", "台南市","高雄市", "屏東縣", "宜蘭縣", "花蓮縣", "台東縣", "澎湖縣", "金門縣", "連江縣"]# 1. 直接比對for city in cities:if city in address:return city# 2. 正則表達式備案 (抓取 'XX市' 或 'XX縣')match = re.search(r'(\w{2,3}[縣市])', address)if match:return match.group(1)return "其他地區"def sync_google_maps(url):global global_df, global_retriever, rag_initializedclean_url = url.strip() if url else ""# 初始狀態:不更新下拉選單no_update = gr.update()if not clean_url or "http" not in clean_url.lower():yield "❌ 請輸入有效的 Google Maps 分享連結。", no_updatereturntry:yield "🚀 [1/4] 啟動瀏覽器...", no_updatewith sync_playwright() as p:browser = p.chromium.launch(headless=True)page = browser.new_page()yield "🌐 [2/4] 連線中...", no_updatepage.goto(clean_url, wait_until="domcontentloaded", timeout=60000)yield "⏳ [3/4] 等待列表加載 (約 10 秒)...", no_updatetime.sleep(10)yield "📄 [4/4] 解析餐廳資訊...", no_updatetitles = page.locator('div.fontHeadlineSmall').all_inner_texts()details = page.locator('div.fontBodyMedium').all_inner_texts()3 unmodified linesname = name.strip()if name:addr = details[i].strip() if i < len(details) else ""# 解析縣市city = extract_city(addr)search_query = f"{name} {addr}"restaurant_list.append({"Name": name,"Address": addr,"City": city, # 新增欄位"Category": "未分類","RAG_Content": f"餐廳:{name},地區:{city},資訊:{addr}","URL": f"https://www.google.com/maps/search/?api=1&query={urllib.parse.quote(search_query)}"})browser.close()if not restaurant_list:yield "⚠️ 找不到餐廳。請確認連結格式正確且已公開。", no_updatereturnglobal_df = pd.DataFrame(restaurant_list)# 準備下拉選單的選項unique_cities = sorted(global_df['City'].unique().tolist())# 將 '未知地區' 或 '其他地區' 移到最後if "其他地區" in unique_cities:unique_cities.remove("其他地區")unique_cities.append("其他地區")# 插入「全區」選項dropdown_choices = ["全區"] + unique_citiestry:embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")vectorstore = FAISS.from_texts(global_df['RAG_Content'].tolist(), embeddings, metadatas=global_df.to_dict('records'))2 unmodified linesprint(f"RAG 初始化警告: {e}")rag_initialized = True# 回傳成功訊息以及下拉選單的更新 (設為預設選第一項 '全區')yield f"✅ 同步成功!已載入 {len(restaurant_list)} 間餐廳。", gr.update(choices=dropdown_choices, value="全區", visible=True)except Exception as e:yield f"❌ 系統錯誤:{str(e)}", no_update# ==========================================# 3. 核心功能 (AI Agent)# ==========================================def get_restaurant_data(mood_score_str, food_choice, location_filter="全區"):"""依據心情、食物類別與「地區」篩選餐廳"""init_static_data() # 確保心情指南已載入if global_df is None or global_df.empty:14 unmodified linesmood_reason = mood_info.iloc[0]['原因']candidates = global_df.copy()# --- 新增:地區篩選邏輯 ---if location_filter and location_filter != "全區":candidates = candidates[candidates['City'] == location_filter]# 如果篩選後沒資料,則退回全部資料並標記 Random (或者回傳空值讓前端顯示警告)if candidates.empty:return None, True, "", f"在【{location_filter}】找不到餐廳,請嘗試切換地區。"# ------------------------food_keyword = "飯" if food_choice == "吃飯" else "麵" if food_choice == "吃麵" else ""is_random = False5 unmodified linesis_random = Trueif candidates.empty:# 如果經過兩層篩選都沒東西,就從 global_df 隨便抓 (但盡量遵守地區)backup_pool = global_df[global_df['City'] == location_filter] if location_filter != "全區" else global_dfif backup_pool.empty: backup_pool = global_dfresult = backup_pool.sample(1).iloc[0]; is_random = Trueelse:result = candidates.sample(1).iloc[0]47 unmodified lines# 回傳具體錯誤訊息return None, str(e)def mood_agent_logic(score_input, food_input, location_input, diary_input, debug_mode):if not rag_initialized:yield "⚠️ 請先同步地圖清單!", None, "", gr.update()return# 傳入 location_input 進行篩選restaurant, is_random, rec_categories, mood_reason = get_restaurant_data(score_input, food_input, location_input)# 錯誤處理:如果 restaurant 是 None,通常是因為該地區沒餐廳if restaurant is None:error_msg = mood_reason # 這裡借用 mood_reason 回傳錯誤訊息yield f"❌ {error_msg}", None, "", gr.update()returnname = restaurant['Name']; url = restaurant['URL']5 unmodified linesai_text, groq_debug_log = generate_content_with_groq(name, rag_info, diary_input, score_input, mood_reason, debug_mode)prefix = ""if is_random:if food_input != "隨便":prefix = f"> 💡 **溫馨提示**:在 {location_input} 的清單中暫無『{food_input}』,已為您挑選其他類型的美味!\n\n"else:prefix = f"> 💡 **探索模式**:在 {location_input} 為您精選了一家餐廳!\n\n"# 組合完整的除錯資訊,包含 API Key 狀態與錯誤訊息full_debug_log = ""7 unmodified lines- **GROQ_API_KEY**: {groq_status}- **HF_TOKEN**: {hf_status}- **RAG 狀態**: {"✅ 已初始化" if rag_initialized else "❌ 未初始化"}- **目前篩選地區**: {location_input}"""full_debug_log = api_debug_block + "\n" + groq_debug_log + f"\n\n### 🎨 Image Prompt Debug\n{img_prompt}"92 unmodified lineswith gr.Row():map_url = gr.Textbox(label="Google Maps Saved Lists 連結", placeholder="請貼上清單的分享連結...", scale=3)sync_btn = gr.Button("🔄 同步清單", variant="secondary", scale=1)# 新增:動態下拉選單location_dropdown = gr.Dropdown(label="📍 選擇餐廳地區 (同步後自動更新)", choices=["請先同步清單"], value="請先同步清單", interactive=True)sync_msg = gr.Markdown("ℹ️ 尚未同步資料庫")gr.Markdown("---")gr.Markdown(f"## 🍱 今天想吃點什麼?")13 unmodified linesmap_output = gr.HTML(label="地圖導航")# 事件# 修改:sync_btn 現在會同時更新 sync_msg 和 location_dropdownsync_btn.click(fn=sync_google_maps, inputs=[map_url], outputs=[sync_msg, location_dropdown])btn_start.click(fn=bridge_start_click, inputs=[st_state], outputs=[result_markdown, cam, btn_stop, btn_start, st_state, btn_go_dining])btn_stop.click(fn=bridge_stop_click, inputs=[st_state], outputs=[result_markdown, cam, btn_stop, btn_start, st_state])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])btn_go_dining.click(fn=lambda: gr.Tabs(selected=1), inputs=None, outputs=tabs)# 修改:submit_btn 加入 location_dropdown 作為輸入submit_btn.click(fn=mood_agent_logic,inputs=[score_input, food_input, location_dropdown, diary_input, debug_mode_btn],outputs=[agent_output, image_output, map_output, debug_output])
app.py+97-21