Spaces:
Sleeping
Sleeping
Update app.py
Browse files12 unmodified lines1314151617182 unmodified lines212223242526272829303122 unmodified lines545556575859606162636465663 unmodified lines7071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231 unmodified line12512612712812913013113213313413513613713813914014114214314414514620 unmodified lines1671681691701711721731741751761771781791801811821831841851861871881891901912 unmodified lines19419519619719819920020120220320420520620720820921021121221321421521661 unmodified lines27827928028128228328412 unmodified linesfrom langchain_community.vectorstores import FAISSfrom PIL import Imagefrom dotenv import load_dotenvfrom openai import OpenAI# --- 匯入組員的模組 ---2 unmodified linesload_dotenv()# 強制設定 Playwright 瀏覽器存放於 user 目錄os.environ["PLAYWRIGHT_BROWSERS_PATH"] = "/home/user/.cache/ms-playwright"try:if not os.path.exists(os.environ["PLAYWRIGHT_BROWSERS_PATH"]):subprocess.run(["python3", "-m", "playwright", "install", "chromium"], check=True)except Exception as e:print(f"Playwright 初始化提示: {e}")22 unmodified lines})# ==========================================# 1. 【核心修正】動態同步功能:強化圖片抓取穩定性# ==========================================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 "❌ 請輸入有效的網址。"returntry:3 unmodified linescontext = browser.new_context(user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")page = context.new_page()yield "🌐 [2/4] 正在開啟網頁..."page.goto(clean_url, wait_until="domcontentloaded", timeout=60000)# 【新增】自動捲動機制:Google Maps 需要捲動才能載入隱藏的圖片yield "⏳ [3/4] 正在觸發圖片載入 (自動捲動與等待)..."for _ in range(3):page.mouse.wheel(0, 1000) # 向下捲動time.sleep(2)yield "📄 [4/4] 正在提取餐廳資料與真實照片..."# 【優化選擇器】改用更穩定的區塊定位# Google Maps 清單中的每一項通常都在 role="article" 的 div 內items = page.locator('div[role="article"]').all()restaurant_list = []for item in items:try:# 1. 抓取店名 (通常在 fontHeadlineSmall 中)name_el = item.locator('div.fontHeadlineSmall').firstif name_el.count() == 0: continuename = name_el.inner_text().strip()# 2. 抓取地址/細節addr_el = item.locator('div.fontBodyMedium').firstaddr = addr_el.inner_text().strip() if addr_el.count() > 0 else "位置見地圖"# 3. 【關鍵修正】多重路徑抓取圖片 URL# 先找直接的 img 標籤,如果沒有,找背景圖片img_url = "https://images.unsplash.com/photo-1555396273-367ea4eb4db5?q=80&w=400" # 預設改為更中性的餐廳圖# 嘗試抓取 srcimg_el = item.locator('img').firstif img_el.count() > 0:src = img_el.get_attribute('src')# 過濾掉 base64 透明佔位圖 (通常以 data: 開頭)if src and not src.startswith('data:'):# 【新增】將縮圖 URL 轉為大圖模式 (Google 的 URL 規則)if "=w" in src:img_url = src.split('=w')[0] + "=w400-h400-p-k-no"else:img_url = srcrestaurant_list.append({"Name": name,"Address": addr,"Image_URL": img_url,"RAG_Content": f"餐廳:{name},細節:{addr}","URL": f"https://www.google.com/search?q={urllib.parse.quote(name)}"})except: continue1 unmodified linebrowser.close()if not restaurant_list:yield "⚠️ 抓取失敗:找不到地點資訊。請確認分享連結是否正確。"return# 更新 RAG 系統global_df = pd.DataFrame(restaurant_list)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'))global_retriever = vectorstore.as_retriever(search_kwargs={"k": 3})rag_initialized = Trueyield f"✅ 同步成功!已載入 {len(restaurant_list)} 間餐廳實景照片。"except Exception as e:yield f"❌ 系統錯誤:{str(e)}"# ==========================================# 2. 【修改】推薦邏輯:支援未匹配告知# ==========================================def get_restaurant_data(mood_score_str, food_choice):init_static_data()20 unmodified linesreturn result, is_match, "口袋名單", mood_reason, all_names# ==========================================# 3. 【修改】Agent 邏輯:整合實景照片輸出# ==========================================def mood_agent_logic(score_input, food_input, diary_input, debug_mode):if not rag_initialized:yield "⚠️ 請先點擊同步按鈕!", None, ""returnrestaurant, is_match, rec_categories, mood_reason, all_names = get_restaurant_data(score_input, food_input)# 組合回報訊息prefix = ""status_hint = ""if not is_match and food_input != "隨便":prefix = f"> 💡 **提醒**:名單中沒找到『{food_input}』,目前有:**{all_names}**。推薦這間試試:\n\n"status_hint = f"\n(注意:清單中無 '{food_input}',請解釋推薦原因。)"name = restaurant['Name']url = restaurant.get('URL', '#')# 【修正】直接使用抓取到的 Image_URLreal_img_url = restaurant.get('Image_URL')rag_info = str(restaurant.get('RAG_Content', '')) + status_hint2 unmodified linesfinal_response = f"{prefix}### 🍽️ 推薦:{name}\n\n{ai_text}"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>'# 回傳圖片yield final_response, real_img_url, map_html# ==========================================# 4. 輔助函數與 Gradio (保持穩定版本)# ==========================================def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, mood_score, mood_guide_reason):if not GROQ_API_KEY: return "⚠️ 請設定 GROQ_API_KEY"client = OpenAI(api_key=GROQ_API_KEY, base_url="https://api.groq.com/openai/v1")system_prompt = "你是一個幽默、懂吃且善解人意的 AI 朋友..."user_msg = f"【餐廳】{restaurant_name}\n【資料】{restaurant_detail}\n【心情分數】{mood_score}\n【日記】{user_diary}"try:response = client.chat.completions.create(model="llama-3.3-70b-versatile", messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_msg}])return response.choices[0].message.contentexcept Exception as e: return f"Groq Error: {str(e)}"# --- 橋接邏輯 ---def _score_to_radio_value(score):mapping = {1: "1 (心情差)", 2: "2 (不太好)", 3: "3 (普通)", 4: "4 (不錯)", 5: "5 (超棒)"}try: score = int(score)61 unmodified linessubmit_btn = gr.Button("🍱 推薦今天的驚喜", variant="primary")with gr.Column(scale=1):agent_output = gr.Markdown(label="AI 回應")image_output = gr.Image(label="餐廳照片", type="filepath", width=400)map_output = gr.HTML(label="地圖導航")# 事件綁定12 unmodified lines131415161718192 unmodified lines2223242526272829303132333422 unmodified lines575859606162636465666768693 unmodified lines7374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371 unmodified line13914014114214314414514614714814915015115215315415515615715815916020 unmodified lines1811821831841851861871881891901911921931941951961971981992002012022032042052 unmodified lines20820921021121221321421521621721821922022122222322422522622722822961 unmodified lines29129229329429529629712 unmodified linesfrom langchain_community.vectorstores import FAISSfrom PIL import Imagefrom dotenv import load_dotenv# 【新增】確保匯入 OpenAI 類別,避免 NameErrorfrom openai import OpenAI# --- 匯入組員的模組 ---2 unmodified linesload_dotenv()# 強制設定 Playwright 瀏覽器路徑os.environ["PLAYWRIGHT_BROWSERS_PATH"] = "/home/user/.cache/ms-playwright"# 【修改】優化環境檢查邏輯try:if not os.path.exists(os.environ["PLAYWRIGHT_BROWSERS_PATH"]):print("正在為環境下載 Chromium...")subprocess.run(["python3", "-m", "playwright", "install", "chromium"], check=True)except Exception as e:print(f"Playwright 初始化提示: {e}")22 unmodified lines})# ==========================================# 1. 【核心優化】動態同步功能:採用錨點定位法抓取圖片# ==========================================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 "❌ 請輸入包含 http 的有效分享連結。"returntry:3 unmodified linescontext = browser.new_context(user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")page = context.new_page()yield "🌐 [2/4] 正在連線至地圖清單頁面..."# 【修改】使用 networkidle 確保大部分內容已下載page.goto(clean_url, wait_until="networkidle", timeout=60000)# 【新增】執行捲動以觸發圖片延遲載入 (Lazy Loading)yield "⏳ [3/4] 正在捲動頁面以讀取餐廳實景圖..."page.mouse.wheel(0, 2000)time.sleep(5)yield "📄 [4/4] 正在解析地點資料與對應照片..."# 【修改】改用店名作為「錨點」來尋找內容# Google Maps 清單店名通常使用這個 classname_selectors = ['div.fontHeadlineSmall', 'div.q09ZMe']titles_found = []for selector in name_selectors:elements = page.locator(selector).all()if elements:titles_found = elementsbreakrestaurant_list = []for i, el in enumerate(titles_found):try:name = el.inner_text().strip()if not name: continue# 【新增】根據店名元素定位其所屬的整塊區塊 (Container)# 這能確保抓到的圖片是「這一間餐廳」的,而不是上一間或下一間的container = page.locator(f"//div[contains(text(), '{name}')]/ancestor::div[img or @role='article']").first# 抓取地址資訊addr = "位置詳見地圖"addr_el = container.locator('div.fontBodyMedium').firstif addr_el.count() > 0:addr = addr_el.inner_text().strip()# 【核心修改】精確抓取該區塊內的圖片 URL# 預設圖 (避免抓不到時空白)img_url = "https://images.unsplash.com/photo-1555396273-367ea4eb4db5?q=80&w=400"# 在該容器內尋找所有圖片,過濾掉圖示或小圖images = container.locator('img').all()for img in images:src = img.get_attribute('src')# 過濾掉 base64 佔位圖與微小的圖示if src and not src.startswith('data:') and ("=w" in src or "googleusercontent" in src):# 將縮圖參數改為較大的尺寸 (例如 400x400)if "=w" in src:img_url = src.split('=w')[0] + "=w400-h400-p-k-no"else:img_url = srcbreak # 抓到第一張有效的就跳出restaurant_list.append({"Name": name,"Address": addr,"Image_URL": img_url,"RAG_Content": f"推薦餐廳:{name},細節:{addr}","URL": f"https://www.google.com/search?q={urllib.parse.quote(name)}"})except: continue1 unmodified linebrowser.close()if not restaurant_list:yield "⚠️ 抓取失敗:在頁面上找不到地點。請確認您的連結是『Send link to view』產生的格式,且清單已設為公開。"return# 更新 RAG 向量資料庫global_df = pd.DataFrame(restaurant_list)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'))global_retriever = vectorstore.as_retriever(search_kwargs={"k": 3})rag_initialized = Trueyield f"✅ 同步成功!已載入 {len(restaurant_list)} 間包含專屬照片的餐廳。"except Exception as e:yield f"❌ 系統錯誤:{str(e)}"# ==========================================# 2. 推薦邏輯 (維持穩定版本)# ==========================================def get_restaurant_data(mood_score_str, food_choice):init_static_data()20 unmodified linesreturn result, is_match, "口袋名單", mood_reason, all_names# ==========================================# 3. Agent 邏輯:整合實景照片輸出# ==========================================def mood_agent_logic(score_input, food_input, diary_input):if not rag_initialized:yield "⚠️ 請先同步地圖清單!", None, ""returnrestaurant, is_match, rec_categories, mood_reason, all_names = get_restaurant_data(score_input, food_input)# 組合回應前綴prefix = ""status_hint = ""if not is_match and food_input != "隨便":prefix = f"> 💡 **小撇步**:沒找到符合「{food_input}」的店,目前清單有:**{all_names}**。推薦這間給你:\n\n"status_hint = f"\n(注意:目前清單中找不到 '{food_input}',請以朋友口吻解釋為何先推薦這間。)"name = restaurant['Name']url = restaurant.get('URL', '#')# 【��改】使用抓取到的實境圖網址real_img_url = restaurant.get('Image_URL')rag_info = str(restaurant.get('RAG_Content', '')) + status_hint2 unmodified linesfinal_response = f"{prefix}### 🍽️ 推薦:{name}\n\n{ai_text}"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>'yield final_response, real_img_url, map_html# ==========================================# 4. 輔助函數與 Gradio (保持穩定)# ==========================================def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, mood_score, mood_guide_reason):if not GROQ_API_KEY: return "⚠️ 未設定 GROQ_API_KEY"client = OpenAI(api_key=GROQ_API_KEY, base_url="https://api.groq.com/openai/v1")system_prompt = "你是一個幽默、懂吃且善解人意的 AI 朋友..."user_msg = f"【餐廳】{restaurant_name}\n【資訊】{restaurant_detail}\n【心情分數】{mood_score}\n【日記】{user_diary}"try:response = client.chat.completions.create(model="llama-3.3-70b-versatile", messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_msg}])return response.choices[0].message.contentexcept Exception as e: return f"Groq Error: {str(e)}"# --- 橋接邏輯 (情緒辨識) ---def _score_to_radio_value(score):mapping = {1: "1 (心情差)", 2: "2 (不太好)", 3: "3 (普通)", 4: "4 (不錯)", 5: "5 (超棒)"}try: score = int(score)61 unmodified linessubmit_btn = gr.Button("🍱 推薦今天的驚喜", variant="primary")with gr.Column(scale=1):agent_output = gr.Markdown(label="AI 回應")image_output = gr.Image(label="餐廳實體照", type="filepath", width=400)map_output = gr.HTML(label="地圖導航")# 事件綁定
app.py+64-51