PhilipL commited on
Commit
bd4e5df
·
verified ·
1 Parent(s): b46a38f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -68
app.py CHANGED
@@ -13,7 +13,6 @@ from langchain_huggingface import HuggingFaceEmbeddings
13
  from langchain_community.vectorstores import FAISS
14
  from PIL import Image
15
  from dotenv import load_dotenv
16
- # 【新增】確保匯入 OpenAI 類別,避免 NameError
17
  from openai import OpenAI
18
 
19
  # --- 匯入組員的模組 ---
@@ -22,13 +21,11 @@ import emotion
22
 
23
  load_dotenv()
24
 
25
- # 強制設定 Playwright 瀏覽器路徑
26
  os.environ["PLAYWRIGHT_BROWSERS_PATH"] = "/home/user/.cache/ms-playwright"
27
 
28
- # 【修改】優化環境檢查邏輯
29
  try:
30
  if not os.path.exists(os.environ["PLAYWRIGHT_BROWSERS_PATH"]):
31
- print("正在為環境下載 Chromium...")
32
  subprocess.run(["python3", "-m", "playwright", "install", "chromium"], check=True)
33
  except Exception as e:
34
  print(f"Playwright 初始化提示: {e}")
@@ -57,13 +54,13 @@ def init_static_data():
57
  })
58
 
59
  # ==========================================
60
- # 1. 【核心優化】動態同步功能:採用錨點定位法抓取圖片
61
  # ==========================================
62
  def sync_google_maps(url):
63
  global global_df, global_retriever, rag_initialized
64
  clean_url = url.strip() if url else ""
65
  if not clean_url or "http" not in clean_url.lower():
66
- yield "❌ 請輸入包含 http 的有效分享連結。"
67
  return
68
 
69
  try:
@@ -73,65 +70,59 @@ def sync_google_maps(url):
73
  context = 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")
74
  page = context.new_page()
75
 
76
- yield "🌐 [2/4] 正在連線至地圖清單頁面..."
77
- # 【修改】使用 networkidle 確保大部分內容已下載
78
- page.goto(clean_url, wait_until="networkidle", timeout=60000)
79
 
80
- # 【新增】執行捲動以觸發圖片延遲載入 (Lazy Loading)
81
- yield "⏳ [3/4] 正在捲動頁面以讀取餐廳實景圖..."
82
- page.mouse.wheel(0, 2000)
83
- time.sleep(5)
84
 
85
- yield "📄 [4/4] 正在解析地點資料與對應照片..."
 
 
 
86
 
87
- # 【修改】改用店名作為「錨點」來尋找內容
88
- # Google Maps 清單店名通常使用這個 class
89
- name_selectors = ['div.fontHeadlineSmall', 'div.q09ZMe']
 
90
  titles_found = []
91
  for selector in name_selectors:
92
- elements = page.locator(selector).all()
93
- if elements:
94
- titles_found = elements
95
  break
96
 
97
  restaurant_list = []
98
- for i, el in enumerate(titles_found):
99
  try:
100
  name = el.inner_text().strip()
101
  if not name: continue
102
 
103
- # 【新增】根據店名元素定位其所屬的整塊區塊 (Container)
104
- # 這能確保抓到的圖片是「這一間餐廳」的,而不是上一間或下一間的
105
  container = page.locator(f"//div[contains(text(), '{name}')]/ancestor::div[img or @role='article']").first
106
 
107
- # 抓取地址資訊
108
- addr = "位置詳見地圖"
109
  addr_el = container.locator('div.fontBodyMedium').first
110
  if addr_el.count() > 0:
111
  addr = addr_el.inner_text().strip()
112
 
113
- # 【核心修改】精確抓取該區塊內的圖片 URL
114
- # 預設圖 (避免抓不到時空白)
115
  img_url = "https://images.unsplash.com/photo-1555396273-367ea4eb4db5?q=80&w=400"
116
-
117
- # 在該容器內尋找所有圖片,過濾掉圖示或小圖
118
  images = container.locator('img').all()
119
  for img in images:
120
  src = img.get_attribute('src')
121
- # 過濾掉 base64 佔位圖與微小的圖示
122
- if src and not src.startswith('data:') and ("=w" in src or "googleusercontent" in src):
123
- # 將縮圖參數改為較大的尺寸 (例如 400x400)
124
- if "=w" in src:
125
- img_url = src.split('=w')[0] + "=w400-h400-p-k-no"
126
- else:
127
- img_url = src
128
- break # 抓到第一張有效的就跳出
129
 
130
  restaurant_list.append({
131
  "Name": name,
132
  "Address": addr,
133
  "Image_URL": img_url,
134
- "RAG_Content": f"推薦餐廳:{name},細節:{addr}",
135
  "URL": f"https://www.google.com/search?q={urllib.parse.quote(name)}"
136
  })
137
  except: continue
@@ -139,79 +130,61 @@ def sync_google_maps(url):
139
  browser.close()
140
 
141
  if not restaurant_list:
142
- yield "⚠️ 抓取失敗:在頁面上找不到地點。請確認您的連結是『Send link to view』產生的格式,且清單已設為公開。"
143
  return
144
 
145
- # 更新 RAG 向量資料庫
146
  global_df = pd.DataFrame(restaurant_list)
147
  embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
148
  vectorstore = FAISS.from_texts(global_df['RAG_Content'].tolist(), embeddings, metadatas=global_df.to_dict('records'))
149
  global_retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
150
  rag_initialized = True
151
- yield f"✅ 同步成功!已載入 {len(restaurant_list)} 間包含專屬照片的餐廳。"
152
 
153
  except Exception as e:
154
  yield f"❌ 系統錯誤:{str(e)}"
155
 
156
  # ==========================================
157
- # 2. 推薦邏輯 (維持穩定版本)
158
  # ==========================================
159
  def get_restaurant_data(mood_score_str, food_choice):
160
  init_static_data()
161
- if global_df is None or global_df.empty:
162
- return None, False, "", "", ""
163
-
164
  all_names = "、".join(global_df['Name'].tolist())
165
  try: score = int(str(mood_score_str).split(' ')[0])
166
  except: score = 3
167
-
168
  mood_reason = global_mood_df[global_mood_df['分數'] == score].iloc[0]['原因']
169
  candidates = global_df.copy()
170
  food_keyword = "飯" if food_choice == "吃飯" else "麵" if food_choice == "吃麵" else ""
171
-
172
  is_match = True
173
  if food_keyword:
174
  filtered = candidates[candidates['Name'].str.contains(food_keyword) | candidates['RAG_Content'].str.contains(food_keyword)]
175
- if not filtered.empty:
176
- candidates = filtered
177
- else:
178
- is_match = False
179
-
180
  result = candidates.sample(1).iloc[0]
181
  return result, is_match, "口袋名單", mood_reason, all_names
182
 
183
- # ==========================================
184
- # 3. Agent 邏輯:整合實景照片輸出
185
- # ==========================================
186
  def mood_agent_logic(score_input, food_input, diary_input):
187
  if not rag_initialized:
188
- yield "⚠️ 請先同步地圖清單!", None, ""
189
  return
190
-
191
  restaurant, is_match, rec_categories, mood_reason, all_names = get_restaurant_data(score_input, food_input)
192
-
193
- # 組合回應前綴
194
  prefix = ""
195
  status_hint = ""
196
  if not is_match and food_input != "隨便":
197
- prefix = f"> 💡 **小撇步**:沒找到符合「{food_input}」的店,目前清單有:**{all_names}**。推薦這間給你:\n\n"
198
- status_hint = f"\n(注意:目前清單中找不到 '{food_input}',請以朋友口吻解釋為何先推薦這間。)"
199
-
200
  name = restaurant['Name']
201
  url = restaurant.get('URL', '#')
202
- # 【修改】使用抓取到的實境圖網址
203
  real_img_url = restaurant.get('Image_URL')
204
  rag_info = str(restaurant.get('RAG_Content', '')) + status_hint
205
-
206
  ai_text = generate_content_with_groq(name, rag_info, diary_input, score_input, mood_reason)
207
-
208
  final_response = f"{prefix}### 🍽️ 推薦:{name}\n\n{ai_text}"
209
  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>'
210
-
211
  yield final_response, real_img_url, map_html
212
 
213
  # ==========================================
214
- # 4. 輔助函數與 Gradio (保持穩定)
215
  # ==========================================
216
  def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, mood_score, mood_guide_reason):
217
  if not GROQ_API_KEY: return "⚠️ 未設定 GROQ_API_KEY"
@@ -223,7 +196,7 @@ def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, m
223
  return response.choices[0].message.content
224
  except Exception as e: return f"Groq Error: {str(e)}"
225
 
226
- # --- 橋接邏輯 (情緒辨識) ---
227
  def _score_to_radio_value(score):
228
  mapping = {1: "1 (心情差)", 2: "2 (不太好)", 3: "3 (普通)", 4: "4 (不錯)", 5: "5 (超棒)"}
229
  try: score = int(score)
 
13
  from langchain_community.vectorstores import FAISS
14
  from PIL import Image
15
  from dotenv import load_dotenv
 
16
  from openai import OpenAI
17
 
18
  # --- 匯入組員的模組 ---
 
21
 
22
  load_dotenv()
23
 
24
+ # 強制設定 Playwright 瀏覽器存放於 user 目錄
25
  os.environ["PLAYWRIGHT_BROWSERS_PATH"] = "/home/user/.cache/ms-playwright"
26
 
 
27
  try:
28
  if not os.path.exists(os.environ["PLAYWRIGHT_BROWSERS_PATH"]):
 
29
  subprocess.run(["python3", "-m", "playwright", "install", "chromium"], check=True)
30
  except Exception as e:
31
  print(f"Playwright 初始化提示: {e}")
 
54
  })
55
 
56
  # ==========================================
57
+ # 1. 【核心修正】動態同步功能:解決逾時與圖片錯誤問題
58
  # ==========================================
59
  def sync_google_maps(url):
60
  global global_df, global_retriever, rag_initialized
61
  clean_url = url.strip() if url else ""
62
  if not clean_url or "http" not in clean_url.lower():
63
+ yield "❌ 請輸入有效的分享連結。"
64
  return
65
 
66
  try:
 
70
  context = 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")
71
  page = context.new_page()
72
 
73
+ yield "🌐 [2/4] 正在連線地圖網頁 (優化等待策略)..."
74
+ # 【關鍵修正】改用 domcontentloaded 避免 networkidle 導致的逾時
75
+ page.goto(clean_url, wait_until="domcontentloaded", timeout=60000)
76
 
77
+ # 【新增】給予固定緩衝時間讓 JavaScript 渲染主要清單
78
+ time.sleep(8)
 
 
79
 
80
+ yield "⏳ [3/4] 正在捲動頁面以讀取實景照片..."
81
+ # 捲動並等待圖片 Lazy Load
82
+ page.mouse.wheel(0, 1500)
83
+ time.sleep(4)
84
 
85
+ yield "📄 [4/4] 正在解析地點與提取專屬圖片..."
86
+
87
+ # 使用更廣泛的選擇器來尋找店名
88
+ name_selectors = ['div.fontHeadlineSmall', 'div.q09ZMe', 'div.XG479b']
89
  titles_found = []
90
  for selector in name_selectors:
91
+ els = page.locator(selector).all()
92
+ if len(els) > 0:
93
+ titles_found = els
94
  break
95
 
96
  restaurant_list = []
97
+ for el in titles_found:
98
  try:
99
  name = el.inner_text().strip()
100
  if not name: continue
101
 
102
+ # 【核心修正】錨點定位:根據店名往上找最近的容器,確保圖片與店名匹配
 
103
  container = page.locator(f"//div[contains(text(), '{name}')]/ancestor::div[img or @role='article']").first
104
 
105
+ # 抓取地址
106
+ addr = "位置見地圖"
107
  addr_el = container.locator('div.fontBodyMedium').first
108
  if addr_el.count() > 0:
109
  addr = addr_el.inner_text().strip()
110
 
111
+ # 抓取圖片:排除 base64 佔位符
 
112
  img_url = "https://images.unsplash.com/photo-1555396273-367ea4eb4db5?q=80&w=400"
 
 
113
  images = container.locator('img').all()
114
  for img in images:
115
  src = img.get_attribute('src')
116
+ if src and not src.startswith('data:') and ("google" in src or "lh3" in src):
117
+ # 將縮圖轉為大圖
118
+ img_url = src.split('=w')[0] + "=w400-h400-p-k-no" if "=w" in src else src
119
+ break
 
 
 
 
120
 
121
  restaurant_list.append({
122
  "Name": name,
123
  "Address": addr,
124
  "Image_URL": img_url,
125
+ "RAG_Content": f"餐廳:{name},細節:{addr}",
126
  "URL": f"https://www.google.com/search?q={urllib.parse.quote(name)}"
127
  })
128
  except: continue
 
130
  browser.close()
131
 
132
  if not restaurant_list:
133
+ yield "⚠️ 抓取失敗:頁面上找不到餐廳。請確認連結格式與公開權限。"
134
  return
135
 
136
+ # 更新 RAG 系統
137
  global_df = pd.DataFrame(restaurant_list)
138
  embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
139
  vectorstore = FAISS.from_texts(global_df['RAG_Content'].tolist(), embeddings, metadatas=global_df.to_dict('records'))
140
  global_retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
141
  rag_initialized = True
142
+ yield f"✅ 同步成功!已載入 {len(restaurant_list)} 間餐廳實景照片。"
143
 
144
  except Exception as e:
145
  yield f"❌ 系統錯誤:{str(e)}"
146
 
147
  # ==========================================
148
+ # 2. 推薦與 Agent 邏輯 (配合實景圖顯示)
149
  # ==========================================
150
  def get_restaurant_data(mood_score_str, food_choice):
151
  init_static_data()
152
+ if global_df is None or global_df.empty: return None, False, "", "", ""
 
 
153
  all_names = "、".join(global_df['Name'].tolist())
154
  try: score = int(str(mood_score_str).split(' ')[0])
155
  except: score = 3
 
156
  mood_reason = global_mood_df[global_mood_df['分數'] == score].iloc[0]['原因']
157
  candidates = global_df.copy()
158
  food_keyword = "飯" if food_choice == "吃飯" else "麵" if food_choice == "吃麵" else ""
 
159
  is_match = True
160
  if food_keyword:
161
  filtered = candidates[candidates['Name'].str.contains(food_keyword) | candidates['RAG_Content'].str.contains(food_keyword)]
162
+ if not filtered.empty: candidates = filtered
163
+ else: is_match = False
 
 
 
164
  result = candidates.sample(1).iloc[0]
165
  return result, is_match, "口袋名單", mood_reason, all_names
166
 
 
 
 
167
  def mood_agent_logic(score_input, food_input, diary_input):
168
  if not rag_initialized:
169
+ yield "⚠️ 請先點擊同步按鈕!", None, ""
170
  return
 
171
  restaurant, is_match, rec_categories, mood_reason, all_names = get_restaurant_data(score_input, food_input)
 
 
172
  prefix = ""
173
  status_hint = ""
174
  if not is_match and food_input != "隨便":
175
+ prefix = f"> 💡 **小撇步**:沒找到「{food_input}」,目前清單有:**{all_names}**。推薦這間給你:\n\n"
176
+ status_hint = f"\n(注意:目前清單中找不到 '{food_input}',請以幽默口吻解釋推薦。)"
 
177
  name = restaurant['Name']
178
  url = restaurant.get('URL', '#')
 
179
  real_img_url = restaurant.get('Image_URL')
180
  rag_info = str(restaurant.get('RAG_Content', '')) + status_hint
 
181
  ai_text = generate_content_with_groq(name, rag_info, diary_input, score_input, mood_reason)
 
182
  final_response = f"{prefix}### 🍽️ 推薦:{name}\n\n{ai_text}"
183
  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>'
 
184
  yield final_response, real_img_url, map_html
185
 
186
  # ==========================================
187
+ # 3. 輔助功能與 Gradio (保持穩定)
188
  # ==========================================
189
  def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, mood_score, mood_guide_reason):
190
  if not GROQ_API_KEY: return "⚠️ 未設定 GROQ_API_KEY"
 
196
  return response.choices[0].message.content
197
  except Exception as e: return f"Groq Error: {str(e)}"
198
 
199
+ # --- 橋接邏輯 ---
200
  def _score_to_radio_value(score):
201
  mapping = {1: "1 (心情差)", 2: "2 (不太好)", 3: "3 (普通)", 4: "4 (不錯)", 5: "5 (超棒)"}
202
  try: score = int(score)