Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -74,69 +74,69 @@ def init_static_data():
|
|
| 74 |
# ==========================================
|
| 75 |
def sync_google_maps(url):
|
| 76 |
global global_df, global_retriever, rag_initialized
|
| 77 |
-
|
| 78 |
-
# 清理網址
|
| 79 |
clean_url = url.strip() if url else ""
|
| 80 |
-
|
| 81 |
if not clean_url or "http" not in clean_url.lower():
|
| 82 |
-
yield "❌ 請輸入
|
| 83 |
return
|
| 84 |
|
| 85 |
try:
|
| 86 |
-
yield "🚀 [1/4]
|
| 87 |
with sync_playwright() as p:
|
| 88 |
browser = p.chromium.launch(headless=True)
|
| 89 |
-
|
| 90 |
-
viewport={'width': 1280, 'height': 800},
|
| 91 |
-
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"
|
| 92 |
-
)
|
| 93 |
-
page = context.new_page()
|
| 94 |
-
|
| 95 |
-
yield "🌐 [2/4] 正在連線至地圖清單..."
|
| 96 |
-
# 使用 domcontentloaded 較快,後續配合 time.sleep 穩定性最高
|
| 97 |
page.goto(clean_url, wait_until="domcontentloaded", timeout=60000)
|
|
|
|
| 98 |
|
| 99 |
-
yield "
|
| 100 |
-
time.sleep(10) # ✅ 現在已經 import time 了,不會再報錯
|
| 101 |
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
# 抓取店名與地址
|
| 105 |
-
titles = page.locator('div.fontHeadlineSmall').all_inner_texts()
|
| 106 |
-
details = page.locator('div.fontBodyMedium').all_inner_texts()
|
| 107 |
|
| 108 |
restaurant_list = []
|
| 109 |
-
for
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
restaurant_list.append({
|
| 114 |
"Name": name,
|
| 115 |
"Address": addr,
|
| 116 |
-
"
|
| 117 |
-
|
| 118 |
"URL": f"https://www.google.com/search?q={urllib.parse.quote(name)}"
|
| 119 |
})
|
| 120 |
-
|
|
|
|
|
|
|
| 121 |
browser.close()
|
| 122 |
|
| 123 |
if not restaurant_list:
|
| 124 |
-
yield "⚠️
|
| 125 |
return
|
| 126 |
|
| 127 |
-
|
| 128 |
-
|
| 129 |
global_df = pd.DataFrame(restaurant_list)
|
| 130 |
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 131 |
-
|
| 132 |
-
metadatas = global_df.to_dict('records')
|
| 133 |
-
|
| 134 |
-
vectorstore = FAISS.from_texts(texts, embeddings, metadatas=metadatas)
|
| 135 |
global_retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
|
| 136 |
-
|
| 137 |
rag_initialized = True
|
| 138 |
-
yield f"✅
|
| 139 |
-
|
| 140 |
except Exception as e:
|
| 141 |
yield f"❌ 系統錯誤:{str(e)}"
|
| 142 |
|
|
@@ -193,48 +193,31 @@ def generate_image_huggingface(prompt):
|
|
| 193 |
except: return None
|
| 194 |
|
| 195 |
def mood_agent_logic(score_input, food_input, diary_input, debug_mode):
|
| 196 |
-
if not rag_initialized
|
| 197 |
-
yield "⚠️ 請先
|
| 198 |
return
|
| 199 |
|
| 200 |
-
# 取得資料
|
| 201 |
restaurant, is_match, rec_categories, mood_reason, all_names = get_restaurant_data(score_input, food_input)
|
| 202 |
|
| 203 |
-
name = restaurant['Name']; address = restaurant['Address']; url = restaurant.get('URL', '#')
|
| 204 |
-
rag_info = str(restaurant.get('RAG_Content', ''))
|
| 205 |
-
|
| 206 |
-
# RAG 檢索增強
|
| 207 |
-
if global_retriever:
|
| 208 |
-
try:
|
| 209 |
-
docs = global_retriever.invoke(name)
|
| 210 |
-
if docs: rag_info = "\n".join([d.page_content for d in docs])
|
| 211 |
-
except: pass
|
| 212 |
-
|
| 213 |
-
# 構造提示詞:如果沒匹配到,要告訴 AI 讓它解釋原因
|
| 214 |
-
match_status_msg = ""
|
| 215 |
-
if not is_match and food_input != "隨便":
|
| 216 |
-
match_status_msg = f"\n(注意:使用者的資料庫中找不到符合 '{food_input}' 的餐廳。請在回應中幽默地提到:雖然目前的清單裡只有這幾間店:[{all_names}],但你還是推薦了這間。)"
|
| 217 |
-
|
| 218 |
-
ai_text = generate_content_with_groq(
|
| 219 |
-
name,
|
| 220 |
-
rag_info + match_status_msg,
|
| 221 |
-
diary_input,
|
| 222 |
-
score_input,
|
| 223 |
-
mood_reason,
|
| 224 |
-
debug_mode
|
| 225 |
-
)
|
| 226 |
-
|
| 227 |
-
# 建立最終回傳訊息
|
| 228 |
prefix = ""
|
| 229 |
if not is_match and food_input != "隨便":
|
| 230 |
-
prefix = f"> 💡 **
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
|
| 232 |
final_response = f"{prefix}### 🍽️ 推薦:{name}\n\n{ai_text}"
|
| 233 |
-
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">🗺️
|
| 234 |
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
yield final_response,
|
| 238 |
|
| 239 |
# ==========================================
|
| 240 |
# 3. 橋接邏輯 (保留原本情緒辨識部分)
|
|
|
|
| 74 |
# ==========================================
|
| 75 |
def sync_google_maps(url):
|
| 76 |
global global_df, global_retriever, rag_initialized
|
|
|
|
|
|
|
| 77 |
clean_url = url.strip() if url else ""
|
|
|
|
| 78 |
if not clean_url or "http" not in clean_url.lower():
|
| 79 |
+
yield "❌ 請輸入有效的網址。"
|
| 80 |
return
|
| 81 |
|
| 82 |
try:
|
| 83 |
+
yield "🚀 [1/4] 啟動瀏覽器並準備抓取實景圖..."
|
| 84 |
with sync_playwright() as p:
|
| 85 |
browser = p.chromium.launch(headless=True)
|
| 86 |
+
page = browser.new_page()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
page.goto(clean_url, wait_until="domcontentloaded", timeout=60000)
|
| 88 |
+
time.sleep(10) # 等待圖片加載
|
| 89 |
|
| 90 |
+
yield "📄 [2/4] 正在解析餐廳資訊與圖片..."
|
|
|
|
| 91 |
|
| 92 |
+
# 定位所有的餐廳卡片
|
| 93 |
+
items = page.locator('div[role="article"]').all()
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
restaurant_list = []
|
| 96 |
+
for item in items:
|
| 97 |
+
try:
|
| 98 |
+
# 抓取店名
|
| 99 |
+
name_el = item.locator('div.fontHeadlineSmall')
|
| 100 |
+
if name_el.count() == 0: continue
|
| 101 |
+
name = name_el.inner_text().strip()
|
| 102 |
+
|
| 103 |
+
# 抓取地址/描述
|
| 104 |
+
detail_el = item.locator('div.fontBodyMedium').first
|
| 105 |
+
addr = detail_el.inner_text().strip() if detail_el.count() > 0 else "位置詳見地圖"
|
| 106 |
+
|
| 107 |
+
# ✅ 抓取圖片網址 (Google Maps 的縮圖通常在 img 標籤中)
|
| 108 |
+
img_el = item.locator('img').first
|
| 109 |
+
img_url = None
|
| 110 |
+
if img_el.count() > 0:
|
| 111 |
+
img_url = img_el.get_attribute('src')
|
| 112 |
+
|
| 113 |
+
# 如果圖片是 Data URL (base64) 或太小,通常代表沒載入成功,可以設個預設圖
|
| 114 |
+
if not img_url or img_url.startswith('data:'):
|
| 115 |
+
img_url = "https://images.unsplash.com/photo-1517248135467-4c7edcad34c4?q=80&w=400" # 預設餐廳美圖
|
| 116 |
+
|
| 117 |
restaurant_list.append({
|
| 118 |
"Name": name,
|
| 119 |
"Address": addr,
|
| 120 |
+
"Image_URL": img_url, # ✅ 新增欄位
|
| 121 |
+
"RAG_Content": f"餐廳:{name},資訊:{addr}",
|
| 122 |
"URL": f"https://www.google.com/search?q={urllib.parse.quote(name)}"
|
| 123 |
})
|
| 124 |
+
except:
|
| 125 |
+
continue
|
| 126 |
+
|
| 127 |
browser.close()
|
| 128 |
|
| 129 |
if not restaurant_list:
|
| 130 |
+
yield "⚠️ 找不到餐廳資訊,請確認連結格式。"
|
| 131 |
return
|
| 132 |
|
| 133 |
+
# 更新向量資料庫
|
|
|
|
| 134 |
global_df = pd.DataFrame(restaurant_list)
|
| 135 |
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 136 |
+
vectorstore = FAISS.from_texts(global_df['RAG_Content'].tolist(), embeddings, metadatas=global_df.to_dict('records'))
|
|
|
|
|
|
|
|
|
|
| 137 |
global_retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
|
|
|
|
| 138 |
rag_initialized = True
|
| 139 |
+
yield f"✅ 同步成功!已載入 {len(restaurant_list)} 間包含實景圖的餐廳。"
|
|
|
|
| 140 |
except Exception as e:
|
| 141 |
yield f"❌ 系統錯誤:{str(e)}"
|
| 142 |
|
|
|
|
| 193 |
except: return None
|
| 194 |
|
| 195 |
def mood_agent_logic(score_input, food_input, diary_input, debug_mode):
|
| 196 |
+
if not rag_initialized:
|
| 197 |
+
yield "⚠️ 請先同步地圖清單!", None, ""
|
| 198 |
return
|
| 199 |
|
| 200 |
+
# 取得推薦資料
|
| 201 |
restaurant, is_match, rec_categories, mood_reason, all_names = get_restaurant_data(score_input, food_input)
|
| 202 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
prefix = ""
|
| 204 |
if not is_match and food_input != "隨便":
|
| 205 |
+
prefix = f"> 💡 **溫馨提示**:名單中沒找到『{food_input}』,目前清單有:**{all_names}**。為您挑選了這一間:\n\n"
|
| 206 |
+
|
| 207 |
+
name = restaurant['Name']
|
| 208 |
+
url = restaurant.get('URL', '#')
|
| 209 |
+
real_img_url = restaurant.get('Image_URL') # ✅ 取得抓到的真實圖片
|
| 210 |
+
rag_info = str(restaurant.get('RAG_Content', ''))
|
| 211 |
+
|
| 212 |
+
# 產生 AI 回應
|
| 213 |
+
ai_text = generate_content_with_groq(name, rag_info, diary_input, score_input, mood_reason)
|
| 214 |
|
| 215 |
final_response = f"{prefix}### 🍽️ 推薦:{name}\n\n{ai_text}"
|
| 216 |
+
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>'
|
| 217 |
|
| 218 |
+
# ✅ 直接回傳圖片網址給 Gradio 的 image_output
|
| 219 |
+
# 注意:Gradio 的 gr.Image 可以直接接收 URL 字串
|
| 220 |
+
yield final_response, real_img_url, map_html
|
| 221 |
|
| 222 |
# ==========================================
|
| 223 |
# 3. 橋接邏輯 (保留原本情緒辨識部分)
|