Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -14,7 +14,7 @@ from PIL import Image
|
|
| 14 |
from dotenv import load_dotenv
|
| 15 |
|
| 16 |
# ==========================================
|
| 17 |
-
# Step 0: 環境安裝檢查
|
| 18 |
# ==========================================
|
| 19 |
def install_playwright():
|
| 20 |
"""確保 Playwright 瀏覽器核心有安裝"""
|
|
@@ -29,39 +29,24 @@ def install_playwright():
|
|
| 29 |
|
| 30 |
print("🔄 檢查 Chromium 瀏覽器...")
|
| 31 |
try:
|
|
|
|
| 32 |
if not os.path.exists(os.environ["PLAYWRIGHT_BROWSERS_PATH"]):
|
| 33 |
subprocess.run([sys.executable, "-m", "playwright", "install", "chromium"], check=True)
|
| 34 |
except Exception as e:
|
| 35 |
print(f"⚠️ 瀏覽器安裝警告: {e}")
|
| 36 |
|
|
|
|
| 37 |
install_playwright()
|
|
|
|
|
|
|
| 38 |
from playwright.sync_api import sync_playwright
|
| 39 |
|
| 40 |
load_dotenv()
|
| 41 |
|
| 42 |
# ==========================================
|
| 43 |
-
# 模組載入 (
|
| 44 |
# ==========================================
|
| 45 |
-
|
| 46 |
-
import emotion
|
| 47 |
-
print("✅ 成功載入 emotion 模組")
|
| 48 |
-
except ImportError as e:
|
| 49 |
-
print(f"❌ 嚴重錯誤:無法載入 emotion 模組。請檢查 requirements.txt 與模型檔。錯誤:{e}")
|
| 50 |
-
# 這裡選擇不崩潰,而是讓情緒功能失效,避免影響主功能
|
| 51 |
-
class MockEmotion:
|
| 52 |
-
css = ""
|
| 53 |
-
class AppState: pass
|
| 54 |
-
@staticmethod
|
| 55 |
-
def _hint_html(s): return f"<div style='color:red'>⚠️ Emotion 模組載入失敗: {e}</div><br>{s}"
|
| 56 |
-
@staticmethod
|
| 57 |
-
def on_restart(st): return [None]*10
|
| 58 |
-
@staticmethod
|
| 59 |
-
def on_stop(st): return [None]*10
|
| 60 |
-
@staticmethod
|
| 61 |
-
def on_stream(frame, st): return [frame, None, None, None, st, gr.update(), gr.update()]
|
| 62 |
-
@staticmethod
|
| 63 |
-
def on_upload(img, st): return [None, gr.update(), gr.Tabs(), st]
|
| 64 |
-
emotion = MockEmotion()
|
| 65 |
|
| 66 |
# ==========================================
|
| 67 |
# 0. 環境變數 & 1. 資料初始化
|
|
@@ -75,17 +60,21 @@ global_retriever = None
|
|
| 75 |
rag_initialized = False
|
| 76 |
|
| 77 |
def init_static_data():
|
| 78 |
-
"""初始化靜態的心情資料
|
| 79 |
global global_mood_df
|
| 80 |
if global_mood_df is None:
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
# ==========================================
|
| 91 |
# 2. Google Maps 爬蟲功能
|
|
@@ -147,22 +136,24 @@ def sync_google_maps(url):
|
|
| 147 |
# 3. 核心功能 (AI Agent)
|
| 148 |
# ==========================================
|
| 149 |
def get_restaurant_data(mood_score_str, food_choice):
|
| 150 |
-
init_static_data()
|
| 151 |
|
| 152 |
if global_df is None or global_df.empty:
|
| 153 |
return None, True, "", "資料庫未載入,無建議"
|
| 154 |
|
|
|
|
| 155 |
try: score = int(str(mood_score_str).split(' ')[0])
|
| 156 |
except: score = 3
|
| 157 |
|
| 158 |
-
# 從 CSV
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
|
|
|
| 166 |
|
| 167 |
candidates = global_df.copy()
|
| 168 |
food_keyword = "飯" if food_choice == "吃飯" else "麵" if food_choice == "吃麵" else ""
|
|
@@ -255,7 +246,10 @@ def mood_agent_logic(score_input, food_input, diary_input, debug_mode):
|
|
| 255 |
final_response = f"{prefix}### 🍽️ 推薦:{name}\n\n{ai_text}"
|
| 256 |
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>'
|
| 257 |
|
|
|
|
| 258 |
yield final_response, None, map_html, debug_output_update
|
|
|
|
|
|
|
| 259 |
image_output = generate_image_huggingface(img_prompt)
|
| 260 |
yield final_response, image_output, map_html, debug_output_update
|
| 261 |
|
|
@@ -327,7 +321,6 @@ with gr.Blocks(title="AI 心情食堂", css=css_) as demo:
|
|
| 327 |
btn_stop = gr.Button("⏹️ 停止", variant="secondary", visible=False)
|
| 328 |
cam = gr.Image(sources=["webcam"], streaming=True, type="numpy", label="攝影機畫面", visible=False)
|
| 329 |
result_markdown = gr.Markdown(emotion._hint_html("請按「開啟攝影機辨識」並允許瀏覽器使用相機。"))
|
| 330 |
-
upload_img = gr.Image(sources=["upload"], type="numpy", label="上傳照片")
|
| 331 |
btn_go_dining = gr.Button("🚀 確定心情,來找餐廳!", variant="primary", visible=False, size="lg")
|
| 332 |
|
| 333 |
# Tab 2
|
|
@@ -362,7 +355,13 @@ with gr.Blocks(title="AI 心情食堂", css=css_) as demo:
|
|
| 362 |
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])
|
| 363 |
upload_img.change(fn=bridge_predict_upload, inputs=[upload_img, st_state], outputs=[result_markdown, score_input, tabs, st_state])
|
| 364 |
btn_go_dining.click(fn=lambda: gr.Tabs(selected=1), inputs=None, outputs=tabs)
|
| 365 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 366 |
|
| 367 |
if __name__ == "__main__":
|
| 368 |
demo.launch(ssr_mode=False)
|
|
|
|
| 14 |
from dotenv import load_dotenv
|
| 15 |
|
| 16 |
# ==========================================
|
| 17 |
+
# Step 0: 環境安裝檢查 (僅保留 Playwright)
|
| 18 |
# ==========================================
|
| 19 |
def install_playwright():
|
| 20 |
"""確保 Playwright 瀏覽器核心有安裝"""
|
|
|
|
| 29 |
|
| 30 |
print("🔄 檢查 Chromium 瀏覽器...")
|
| 31 |
try:
|
| 32 |
+
# 檢查是否已安裝,若無則安裝
|
| 33 |
if not os.path.exists(os.environ["PLAYWRIGHT_BROWSERS_PATH"]):
|
| 34 |
subprocess.run([sys.executable, "-m", "playwright", "install", "chromium"], check=True)
|
| 35 |
except Exception as e:
|
| 36 |
print(f"⚠️ 瀏覽器安裝警告: {e}")
|
| 37 |
|
| 38 |
+
# 執行安裝
|
| 39 |
install_playwright()
|
| 40 |
+
|
| 41 |
+
# 延遲匯入
|
| 42 |
from playwright.sync_api import sync_playwright
|
| 43 |
|
| 44 |
load_dotenv()
|
| 45 |
|
| 46 |
# ==========================================
|
| 47 |
+
# 模組載入 (emotion 模組)
|
| 48 |
# ==========================================
|
| 49 |
+
import emotion
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
# ==========================================
|
| 52 |
# 0. 環境變數 & 1. 資料初始化
|
|
|
|
| 60 |
rag_initialized = False
|
| 61 |
|
| 62 |
def init_static_data():
|
| 63 |
+
"""初始化靜態的心情資料:讀取外部 CSV"""
|
| 64 |
global global_mood_df
|
| 65 |
if global_mood_df is None:
|
| 66 |
+
csv_path = 'mood_food_guide.csv'
|
| 67 |
+
if os.path.exists(csv_path):
|
| 68 |
+
try:
|
| 69 |
+
# 讀取 CSV,確保欄位正確
|
| 70 |
+
global_mood_df = pd.read_csv(csv_path)
|
| 71 |
+
print(f"✅ 成功載入心情指南:{csv_path}")
|
| 72 |
+
except Exception as e:
|
| 73 |
+
print(f"❌ 讀取 CSV 失敗: {e}")
|
| 74 |
+
global_mood_df = pd.DataFrame() # 建立空表防止後續報錯
|
| 75 |
+
else:
|
| 76 |
+
print(f"⚠️ 警告:找不到 {csv_path},請確認檔案已上傳至 Space。")
|
| 77 |
+
global_mood_df = pd.DataFrame()
|
| 78 |
|
| 79 |
# ==========================================
|
| 80 |
# 2. Google Maps 爬蟲功能
|
|
|
|
| 136 |
# 3. 核心功能 (AI Agent)
|
| 137 |
# ==========================================
|
| 138 |
def get_restaurant_data(mood_score_str, food_choice):
|
| 139 |
+
init_static_data() # 確保心情指南已載入
|
| 140 |
|
| 141 |
if global_df is None or global_df.empty:
|
| 142 |
return None, True, "", "資料庫未載入,無建議"
|
| 143 |
|
| 144 |
+
# 解析分數 (例如 "3 (普通)" -> 3)
|
| 145 |
try: score = int(str(mood_score_str).split(' ')[0])
|
| 146 |
except: score = 3
|
| 147 |
|
| 148 |
+
# 從 CSV 資料中查找對應的推薦類別與原因
|
| 149 |
+
rec_categories = ""
|
| 150 |
+
mood_reason = "隨意探索"
|
| 151 |
+
|
| 152 |
+
if global_mood_df is not None and not global_mood_df.empty:
|
| 153 |
+
mood_info = global_mood_df[global_mood_df['分數'] == score]
|
| 154 |
+
if not mood_info.empty:
|
| 155 |
+
rec_categories = mood_info.iloc[0]['推薦料理類別']
|
| 156 |
+
mood_reason = mood_info.iloc[0]['原因']
|
| 157 |
|
| 158 |
candidates = global_df.copy()
|
| 159 |
food_keyword = "飯" if food_choice == "吃飯" else "麵" if food_choice == "吃麵" else ""
|
|
|
|
| 246 |
final_response = f"{prefix}### 🍽️ 推薦:{name}\n\n{ai_text}"
|
| 247 |
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>'
|
| 248 |
|
| 249 |
+
# 先回傳文字
|
| 250 |
yield final_response, None, map_html, debug_output_update
|
| 251 |
+
|
| 252 |
+
# 再回傳圖片
|
| 253 |
image_output = generate_image_huggingface(img_prompt)
|
| 254 |
yield final_response, image_output, map_html, debug_output_update
|
| 255 |
|
|
|
|
| 321 |
btn_stop = gr.Button("⏹️ 停止", variant="secondary", visible=False)
|
| 322 |
cam = gr.Image(sources=["webcam"], streaming=True, type="numpy", label="攝影機畫面", visible=False)
|
| 323 |
result_markdown = gr.Markdown(emotion._hint_html("請按「開啟攝影機辨識」並允許瀏覽器使用相機。"))
|
|
|
|
| 324 |
btn_go_dining = gr.Button("🚀 確定心情,來找餐廳!", variant="primary", visible=False, size="lg")
|
| 325 |
|
| 326 |
# Tab 2
|
|
|
|
| 355 |
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])
|
| 356 |
upload_img.change(fn=bridge_predict_upload, inputs=[upload_img, st_state], outputs=[result_markdown, score_input, tabs, st_state])
|
| 357 |
btn_go_dining.click(fn=lambda: gr.Tabs(selected=1), inputs=None, outputs=tabs)
|
| 358 |
+
|
| 359 |
+
# debug_mode
|
| 360 |
+
submit_btn.click(
|
| 361 |
+
fn=mood_agent_logic,
|
| 362 |
+
inputs=[score_input, food_input, diary_input, debug_mode_btn],
|
| 363 |
+
outputs=[agent_output, image_output, map_output, debug_output]
|
| 364 |
+
)
|
| 365 |
|
| 366 |
if __name__ == "__main__":
|
| 367 |
demo.launch(ssr_mode=False)
|