Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,11 +1,11 @@
|
|
| 1 |
-
# 我發現如果改成使用連結建立動態的資料庫會有一些問題
|
| 2 |
-
# 1. 生成圖片會沒辦法固定prompt
|
| 3 |
-
# 2. 要用其他方式來處理分類餐廳的問題,因為餐廳的名字有些很奇怪
|
| 4 |
-
# 最後的版本: 動態資料庫 + Hugging Face圖片
|
| 5 |
-
|
| 6 |
import os
|
| 7 |
import subprocess
|
| 8 |
import sys
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
# ==========================================
|
| 11 |
# Step 0: 強制安裝檢查 (解決 ModuleNotFoundError)
|
|
@@ -36,29 +36,24 @@ install_dependencies()
|
|
| 36 |
# ==========================================
|
| 37 |
# 程式正式開始
|
| 38 |
# ==========================================
|
| 39 |
-
import urllib.parse
|
| 40 |
-
import time
|
| 41 |
-
import pandas as pd
|
| 42 |
-
from dotenv import load_dotenv
|
| 43 |
-
|
| 44 |
-
# --- 匯入核心模組 ---
|
| 45 |
import gradio as gr
|
|
|
|
|
|
|
| 46 |
from playwright.sync_api import sync_playwright
|
| 47 |
from langchain_huggingface import HuggingFaceEmbeddings
|
| 48 |
from langchain_community.vectorstores import FAISS
|
| 49 |
-
from
|
| 50 |
-
from huggingface_hub import InferenceClient
|
| 51 |
|
| 52 |
# 嘗試匯入組員的模組
|
| 53 |
try:
|
| 54 |
-
import emotion
|
| 55 |
except ImportError:
|
| 56 |
print("警告:找不到 emotion 模組,請確保同級目錄下有 emotion.py。")
|
| 57 |
|
| 58 |
load_dotenv()
|
| 59 |
|
| 60 |
# ==========================================
|
| 61 |
-
# 0.
|
| 62 |
# ==========================================
|
| 63 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 64 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
|
@@ -69,11 +64,13 @@ global_retriever = None
|
|
| 69 |
rag_initialized = False
|
| 70 |
|
| 71 |
def init_static_data():
|
|
|
|
| 72 |
global global_mood_df
|
| 73 |
if global_mood_df is None:
|
| 74 |
try:
|
| 75 |
global_mood_df = pd.read_csv('mood_food_guide.csv')
|
| 76 |
except:
|
|
|
|
| 77 |
global_mood_df = pd.DataFrame({
|
| 78 |
'分數': [1, 2, 3, 4, 5],
|
| 79 |
'推薦料理類別': ["療癒系", "暖胃", "隨意", "豐富", "大餐"],
|
|
@@ -81,13 +78,13 @@ def init_static_data():
|
|
| 81 |
})
|
| 82 |
|
| 83 |
# ==========================================
|
| 84 |
-
#
|
| 85 |
# ==========================================
|
| 86 |
def sync_google_maps(url):
|
| 87 |
global global_df, global_retriever, rag_initialized
|
| 88 |
clean_url = url.strip() if url else ""
|
| 89 |
if not clean_url or "http" not in clean_url.lower():
|
| 90 |
-
yield "❌ 請輸入有效的
|
| 91 |
return
|
| 92 |
|
| 93 |
try:
|
|
@@ -97,7 +94,7 @@ def sync_google_maps(url):
|
|
| 97 |
page = browser.new_page()
|
| 98 |
yield "🌐 [2/4] 連線中..."
|
| 99 |
page.goto(clean_url, wait_until="domcontentloaded", timeout=60000)
|
| 100 |
-
yield "⏳ [3/4] 等待列表加載..."
|
| 101 |
time.sleep(10)
|
| 102 |
yield "📄 [4/4] 解析餐廳資訊..."
|
| 103 |
|
|
@@ -112,6 +109,7 @@ def sync_google_maps(url):
|
|
| 112 |
restaurant_list.append({
|
| 113 |
"Name": name,
|
| 114 |
"Address": addr,
|
|
|
|
| 115 |
"RAG_Content": f"餐廳:{name},資訊:{addr}",
|
| 116 |
"URL": f"https://www.google.com/search?q={urllib.parse.quote(name)}"
|
| 117 |
})
|
|
@@ -122,118 +120,148 @@ def sync_google_maps(url):
|
|
| 122 |
return
|
| 123 |
|
| 124 |
global_df = pd.DataFrame(restaurant_list)
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
rag_initialized = True
|
| 129 |
-
yield f"✅ 同步成功!
|
| 130 |
except Exception as e:
|
| 131 |
yield f"❌ 系統錯誤:{str(e)}"
|
| 132 |
|
| 133 |
# ==========================================
|
| 134 |
-
#
|
| 135 |
-
# ==========================================
|
| 136 |
-
def generate_image_huggingface(prompt):
|
| 137 |
-
"""使用 Hugging Face 的 SDXL 模型生成圖片"""
|
| 138 |
-
if not HF_TOKEN:
|
| 139 |
-
print("⚠️ 未設定 HF_TOKEN,無法生成圖片")
|
| 140 |
-
return None
|
| 141 |
-
try:
|
| 142 |
-
hf_client = InferenceClient(token=HF_TOKEN)
|
| 143 |
-
# 加入負面提示詞以提升品質
|
| 144 |
-
image = hf_client.text_to_image(
|
| 145 |
-
prompt=prompt,
|
| 146 |
-
negative_prompt="blurry, low quality, distortion, text, watermark",
|
| 147 |
-
model="stabilityai/stable-diffusion-xl-base-1.0"
|
| 148 |
-
)
|
| 149 |
-
return image
|
| 150 |
-
except Exception as e:
|
| 151 |
-
print(f"圖片生成失敗: {e}")
|
| 152 |
-
return None
|
| 153 |
-
|
| 154 |
-
# ==========================================
|
| 155 |
-
# 3. 推薦主邏輯
|
| 156 |
# ==========================================
|
| 157 |
def get_restaurant_data(mood_score_str, food_choice):
|
| 158 |
-
init_static_data()
|
|
|
|
| 159 |
if global_df is None or global_df.empty:
|
| 160 |
return None, True, "資料庫未載入", "尚未同步地圖資料", ""
|
| 161 |
|
|
|
|
| 162 |
all_names = "、".join(global_df['Name'].tolist())
|
|
|
|
| 163 |
try: score = int(str(mood_score_str).split(' ')[0])
|
| 164 |
except: score = 3
|
| 165 |
|
| 166 |
mood_info = global_mood_df[global_mood_df['分數'] == score]
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
| 168 |
|
| 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 |
def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, mood_score, mood_guide_reason):
|
| 184 |
-
if not GROQ_API_KEY: return "⚠️ 請
|
|
|
|
| 185 |
client = OpenAI(api_key=GROQ_API_KEY, base_url="https://api.groq.com/openai/v1")
|
| 186 |
-
|
| 187 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
try:
|
| 189 |
response = client.chat.completions.create(model="llama-3.3-70b-versatile", messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_msg}])
|
| 190 |
-
|
| 191 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
|
| 193 |
def mood_agent_logic(score_input, food_input, diary_input, show_prompt):
|
| 194 |
if not rag_initialized:
|
| 195 |
-
yield "⚠️ 請先同步地圖清單!", None, "", ""
|
| 196 |
return
|
| 197 |
-
|
| 198 |
restaurant, is_match, _, mood_reason, all_names = get_restaurant_data(score_input, food_input)
|
| 199 |
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
name = restaurant['Name']
|
| 205 |
info = restaurant.get('RAG_Content', '')
|
| 206 |
url = restaurant.get('URL', '#')
|
| 207 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
# 1. 生成文字
|
| 209 |
ai_text = generate_content_with_groq(name, info, diary_input, score_input, mood_reason)
|
| 210 |
-
|
| 211 |
|
| 212 |
-
# 2. 生成圖片 Prompt
|
| 213 |
-
prompt = f"Delicious food photography of {name}, {info}. high quality, photorealistic, 8k, cinematic lighting, appetizing, restaurant atmosphere"
|
| 214 |
|
| 215 |
-
# 決定是否回傳 prompt 文字
|
| 216 |
prompt_output_text = prompt if show_prompt else ""
|
| 217 |
-
|
| 218 |
-
nav_button = f'<div style="text-align:center; margin-top:15px;"><a href="{url}" target="_blank" style="background:#4285F4;color:white;padding:12px 24px;border-radius:30px;text-decoration:none;font-weight:bold;font-size:16px;">📍 前往 Google Maps 導航</a></div>'
|
| 219 |
|
| 220 |
# 先回傳文字
|
| 221 |
-
yield
|
| 222 |
|
| 223 |
# 3. 生成圖片
|
| 224 |
-
|
| 225 |
-
yield
|
| 226 |
|
| 227 |
# ==========================================
|
| 228 |
-
# 4. 橋接
|
| 229 |
# ==========================================
|
| 230 |
def _score_to_radio_value(score):
|
| 231 |
mapping = {1: "1 (心情差)", 2: "2 (不太好)", 3: "3 (普通)", 4: "4 (不錯)", 5: "5 (超棒)"}
|
| 232 |
-
|
|
|
|
|
|
|
| 233 |
|
| 234 |
def bridge_start_click(st):
|
| 235 |
res = emotion.on_restart(st)
|
| 236 |
-
return res[1], res[0], gr.update(visible=True), res[5], res[4]
|
| 237 |
|
| 238 |
def bridge_stop_click(st):
|
| 239 |
res = emotion.on_stop(st)
|
|
@@ -241,91 +269,121 @@ def bridge_stop_click(st):
|
|
| 241 |
|
| 242 |
def bridge_predict_frame(frame, st):
|
| 243 |
res = emotion.on_stream(frame, st)
|
| 244 |
-
out_cam
|
| 245 |
-
score_update
|
| 246 |
-
|
| 247 |
-
new_val = _score_to_radio_value(out_st.final_score)
|
| 248 |
-
score_update = gr.update(value=new_val)
|
| 249 |
-
tabs_update = gr.Tabs(selected=1)
|
| 250 |
-
out_btn_stop = gr.update(visible=False)
|
| 251 |
-
return out_cam, out_result, out_st, out_btn_stop, out_btn_start, score_update, tabs_update
|
| 252 |
|
| 253 |
-
def bridge_predict_upload(img, st):
|
| 254 |
-
res = emotion.on_upload(img, st)
|
| 255 |
-
out_result, out_st = res[0], res[2]
|
| 256 |
-
score_update, tabs_update = gr.update(), gr.update()
|
| 257 |
if out_st.finished and hasattr(out_st, 'final_score'):
|
| 258 |
new_val = _score_to_radio_value(out_st.final_score)
|
| 259 |
score_update = gr.update(value=new_val)
|
| 260 |
-
|
| 261 |
-
|
|
|
|
|
|
|
| 262 |
|
| 263 |
# ==========================================
|
| 264 |
-
# 5. Gradio
|
| 265 |
# ==========================================
|
| 266 |
-
|
|
|
|
|
|
|
|
|
|
| 267 |
st_state = gr.State(emotion.AppState())
|
| 268 |
|
| 269 |
with gr.Tabs() as tabs:
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
|
|
|
|
|
|
| 274 |
with gr.Row():
|
| 275 |
-
btn_start = gr.Button("開啟攝影機", variant="primary")
|
| 276 |
-
btn_stop = gr.Button("停止", variant="secondary", visible=False)
|
|
|
|
| 277 |
cam = gr.Image(sources=["webcam"], streaming=True, type="numpy", label="攝影機畫面", visible=False)
|
| 278 |
-
result_markdown = gr.Markdown("請按
|
| 279 |
-
|
| 280 |
|
| 281 |
-
#
|
| 282 |
-
with gr.TabItem("🍽️
|
| 283 |
with gr.Column():
|
| 284 |
-
|
|
|
|
|
|
|
| 285 |
with gr.Row():
|
| 286 |
-
map_url = gr.Textbox(label="
|
| 287 |
-
sync_btn = gr.Button("🔄 同步清單", variant="secondary")
|
| 288 |
-
sync_msg = gr.Markdown("ℹ️ 尚未同步")
|
| 289 |
|
| 290 |
gr.Markdown("---")
|
|
|
|
| 291 |
|
| 292 |
with gr.Row():
|
| 293 |
with gr.Column(scale=1):
|
| 294 |
score_input = gr.Radio(
|
| 295 |
["1 (心情差)", "2 (不太好)", "3 (普通)", "4 (不錯)", "5 (超棒)"],
|
| 296 |
-
label="心情分數",
|
| 297 |
value="3 (普通)"
|
| 298 |
)
|
| 299 |
-
food_input = gr.Radio(["吃飯", "吃麵", "隨便"], label="想吃什麼
|
| 300 |
-
diary_input = gr.Textbox(lines=3, label="心情日記", placeholder="今天發生
|
| 301 |
|
| 302 |
-
#
|
| 303 |
show_prompt_chk = gr.Checkbox(label="顯示生成圖片的 Prompt (指令)", value=False)
|
| 304 |
|
| 305 |
submit_btn = gr.Button("🍱 推薦美食", variant="primary")
|
| 306 |
|
| 307 |
with gr.Column(scale=1):
|
| 308 |
-
agent_output = gr.Markdown(label="AI
|
| 309 |
-
|
| 310 |
|
| 311 |
-
#
|
| 312 |
prompt_output = gr.Textbox(label="圖片生成指令 (Prompt)", visible=True, interactive=False)
|
| 313 |
|
| 314 |
-
|
| 315 |
|
|
|
|
| 316 |
# 事件綁定
|
|
|
|
|
|
|
|
|
|
| 317 |
sync_btn.click(fn=sync_google_maps, inputs=[map_url], outputs=[sync_msg])
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
submit_btn.click(
|
| 325 |
-
fn=mood_agent_logic,
|
| 326 |
-
inputs=[score_input, food_input, diary_input, show_prompt_chk],
|
| 327 |
-
outputs=[agent_output,
|
| 328 |
)
|
| 329 |
|
| 330 |
if __name__ == "__main__":
|
| 331 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import subprocess
|
| 3 |
import sys
|
| 4 |
+
import urllib.parse
|
| 5 |
+
import time
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import requests
|
| 8 |
+
from dotenv import load_dotenv
|
| 9 |
|
| 10 |
# ==========================================
|
| 11 |
# Step 0: 強制安裝檢查 (解決 ModuleNotFoundError)
|
|
|
|
| 36 |
# ==========================================
|
| 37 |
# 程式正式開始
|
| 38 |
# ==========================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
import gradio as gr
|
| 40 |
+
from openai import OpenAI
|
| 41 |
+
from huggingface_hub import InferenceClient
|
| 42 |
from playwright.sync_api import sync_playwright
|
| 43 |
from langchain_huggingface import HuggingFaceEmbeddings
|
| 44 |
from langchain_community.vectorstores import FAISS
|
| 45 |
+
from PIL import Image
|
|
|
|
| 46 |
|
| 47 |
# 嘗試匯入組員的模組
|
| 48 |
try:
|
| 49 |
+
import emotion # 情緒辨識
|
| 50 |
except ImportError:
|
| 51 |
print("警告:找不到 emotion 模組,請確保同級目錄下有 emotion.py。")
|
| 52 |
|
| 53 |
load_dotenv()
|
| 54 |
|
| 55 |
# ==========================================
|
| 56 |
+
# 0. 環境變數 & 1. 系統初始化
|
| 57 |
# ==========================================
|
| 58 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 59 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
|
|
|
| 64 |
rag_initialized = False
|
| 65 |
|
| 66 |
def init_static_data():
|
| 67 |
+
"""初始化靜態的心情資料 (心情指南)"""
|
| 68 |
global global_mood_df
|
| 69 |
if global_mood_df is None:
|
| 70 |
try:
|
| 71 |
global_mood_df = pd.read_csv('mood_food_guide.csv')
|
| 72 |
except:
|
| 73 |
+
# 如果沒有 csv,使用預設資料
|
| 74 |
global_mood_df = pd.DataFrame({
|
| 75 |
'分數': [1, 2, 3, 4, 5],
|
| 76 |
'推薦料理類別': ["療癒系", "暖胃", "隨意", "豐富", "大餐"],
|
|
|
|
| 78 |
})
|
| 79 |
|
| 80 |
# ==========================================
|
| 81 |
+
# 2. Google Maps 爬蟲功能 (取代原本的靜態 CSV)
|
| 82 |
# ==========================================
|
| 83 |
def sync_google_maps(url):
|
| 84 |
global global_df, global_retriever, rag_initialized
|
| 85 |
clean_url = url.strip() if url else ""
|
| 86 |
if not clean_url or "http" not in clean_url.lower():
|
| 87 |
+
yield "❌ 請輸入有效的 Google Maps 分享連結。"
|
| 88 |
return
|
| 89 |
|
| 90 |
try:
|
|
|
|
| 94 |
page = browser.new_page()
|
| 95 |
yield "🌐 [2/4] 連線中..."
|
| 96 |
page.goto(clean_url, wait_until="domcontentloaded", timeout=60000)
|
| 97 |
+
yield "⏳ [3/4] 等待列表加載 (約 10 秒)..."
|
| 98 |
time.sleep(10)
|
| 99 |
yield "📄 [4/4] 解析餐廳資訊..."
|
| 100 |
|
|
|
|
| 109 |
restaurant_list.append({
|
| 110 |
"Name": name,
|
| 111 |
"Address": addr,
|
| 112 |
+
"Category": "未分類", # 爬蟲暫時無法精確抓取類別,設為預設
|
| 113 |
"RAG_Content": f"餐廳:{name},資訊:{addr}",
|
| 114 |
"URL": f"https://www.google.com/search?q={urllib.parse.quote(name)}"
|
| 115 |
})
|
|
|
|
| 120 |
return
|
| 121 |
|
| 122 |
global_df = pd.DataFrame(restaurant_list)
|
| 123 |
+
|
| 124 |
+
# 建立簡易 RAG 索引
|
| 125 |
+
try:
|
| 126 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 127 |
+
vectorstore = FAISS.from_texts(global_df['RAG_Content'].tolist(), embeddings, metadatas=global_df.to_dict('records'))
|
| 128 |
+
global_retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
|
| 129 |
+
except Exception as e:
|
| 130 |
+
print(f"RAG 初始化警告: {e}")
|
| 131 |
+
|
| 132 |
rag_initialized = True
|
| 133 |
+
yield f"✅ 同步成功!已載入 {len(restaurant_list)} 間餐廳。"
|
| 134 |
except Exception as e:
|
| 135 |
yield f"❌ 系統錯誤:{str(e)}"
|
| 136 |
|
| 137 |
# ==========================================
|
| 138 |
+
# 3. 核心功能 (推薦與生成)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
# ==========================================
|
| 140 |
def get_restaurant_data(mood_score_str, food_choice):
|
| 141 |
+
init_static_data() # 確保心情指南已載入
|
| 142 |
+
|
| 143 |
if global_df is None or global_df.empty:
|
| 144 |
return None, True, "資料庫未載入", "尚未同步地圖資料", ""
|
| 145 |
|
| 146 |
+
# 取得所有餐廳名稱供 fallback 參考
|
| 147 |
all_names = "、".join(global_df['Name'].tolist())
|
| 148 |
+
|
| 149 |
try: score = int(str(mood_score_str).split(' ')[0])
|
| 150 |
except: score = 3
|
| 151 |
|
| 152 |
mood_info = global_mood_df[global_mood_df['分數'] == score]
|
| 153 |
+
if not mood_info.empty:
|
| 154 |
+
mood_reason = mood_info.iloc[0]['原因']
|
| 155 |
+
else:
|
| 156 |
+
mood_reason = "隨意探索"
|
| 157 |
|
| 158 |
candidates = global_df.copy()
|
|
|
|
| 159 |
|
| 160 |
+
# 關鍵字篩選
|
| 161 |
+
food_keyword = "飯" if food_choice == "吃飯" else "麵" if food_choice == "吃麵" else ""
|
| 162 |
is_match = True
|
| 163 |
+
|
| 164 |
if food_keyword:
|
| 165 |
+
filtered = candidates[candidates['Name'].str.contains(food_keyword, case=False, na=False) | candidates['RAG_Content'].str.contains(food_keyword, case=False, na=False)]
|
| 166 |
if not filtered.empty:
|
| 167 |
candidates = filtered
|
| 168 |
else:
|
| 169 |
+
is_match = False # 沒找到符合的,但還是會回傳隨機的
|
| 170 |
+
|
| 171 |
result = candidates.sample(1).iloc[0]
|
| 172 |
return result, is_match, "個人清單", mood_reason, all_names
|
| 173 |
|
| 174 |
def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, mood_score, mood_guide_reason):
|
| 175 |
+
if not GROQ_API_KEY: return "⚠️ 請設定 GROQ_API_KEY"
|
| 176 |
+
|
| 177 |
client = OpenAI(api_key=GROQ_API_KEY, base_url="https://api.groq.com/openai/v1")
|
| 178 |
+
|
| 179 |
+
system_prompt = "你是一個幽默、懂吃且善解人意的 AI 朋友。請根據使用者的日記、心情以及餐廳資訊來推薦。"
|
| 180 |
+
user_msg = f"""
|
| 181 |
+
【狀態】心情分數:{mood_score},日記:{user_diary}
|
| 182 |
+
【心情指南建議】原因:「{mood_guide_reason}」。
|
| 183 |
+
|
| 184 |
+
【推薦餐廳】
|
| 185 |
+
名稱:{restaurant_name}
|
| 186 |
+
資料:{restaurant_detail}
|
| 187 |
+
|
| 188 |
+
任務:
|
| 189 |
+
請用繁體中文寫一段溫暖有趣的回覆:
|
| 190 |
+
1. 回應他的日記。
|
| 191 |
+
2. 結合心情指南與這家餐廳的特色進行推薦。
|
| 192 |
+
(不需要過長的開頭,直接切入重點)
|
| 193 |
+
"""
|
| 194 |
try:
|
| 195 |
response = client.chat.completions.create(model="llama-3.3-70b-versatile", messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_msg}])
|
| 196 |
+
content = response.choices[0].message.content
|
| 197 |
+
return content
|
| 198 |
+
except Exception as e:
|
| 199 |
+
return f"Groq Error: {str(e)}"
|
| 200 |
+
|
| 201 |
+
def generate_image_huggingface(prompt):
|
| 202 |
+
"""使用 Hugging Face 的 SDXL 模型生成圖片"""
|
| 203 |
+
if not HF_TOKEN: return None
|
| 204 |
+
try:
|
| 205 |
+
hf_client = InferenceClient(token=HF_TOKEN)
|
| 206 |
+
# 加入負面提示詞以提升品質
|
| 207 |
+
return hf_client.text_to_image(
|
| 208 |
+
prompt=prompt,
|
| 209 |
+
negative_prompt="blurry, low quality, distortion, text, watermark, bad anatomy",
|
| 210 |
+
model="stabilityai/stable-diffusion-xl-base-1.0"
|
| 211 |
+
)
|
| 212 |
+
except Exception as e:
|
| 213 |
+
print(f"圖片生成失敗: {e}")
|
| 214 |
+
return None
|
| 215 |
|
| 216 |
def mood_agent_logic(score_input, food_input, diary_input, show_prompt):
|
| 217 |
if not rag_initialized:
|
| 218 |
+
yield "⚠️ 請先點擊上方按鈕同步地圖清單!", None, "", ""
|
| 219 |
return
|
| 220 |
+
|
| 221 |
restaurant, is_match, _, mood_reason, all_names = get_restaurant_data(score_input, food_input)
|
| 222 |
|
| 223 |
+
if restaurant is None:
|
| 224 |
+
yield "資料庫讀取錯誤", None, "", ""
|
| 225 |
+
return
|
| 226 |
+
|
| 227 |
name = restaurant['Name']
|
| 228 |
info = restaurant.get('RAG_Content', '')
|
| 229 |
url = restaurant.get('URL', '#')
|
| 230 |
|
| 231 |
+
# 處理未命中提示
|
| 232 |
+
prefix = ""
|
| 233 |
+
if not is_match and food_input != "隨便":
|
| 234 |
+
prefix = f"> 💡 **溫馨提示**:清單中暫無『{food_input}』,已從現有名單挑選最適合的店!\n\n"
|
| 235 |
+
|
| 236 |
# 1. 生成文字
|
| 237 |
ai_text = generate_content_with_groq(name, info, diary_input, score_input, mood_reason)
|
| 238 |
+
final_response = f"{prefix}### 🍽️ 推薦:{name}\n\n{ai_text}"
|
| 239 |
|
| 240 |
+
# 2. 動態生成圖片 Prompt
|
| 241 |
+
prompt = f"Delicious food photography of {name}, {info}. high quality, photorealistic, 8k, cinematic lighting, appetizing, restaurant atmosphere, 50mm lens"
|
| 242 |
|
|
|
|
| 243 |
prompt_output_text = prompt if show_prompt else ""
|
| 244 |
+
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>'
|
|
|
|
| 245 |
|
| 246 |
# 先回傳文字
|
| 247 |
+
yield final_response, None, map_html, prompt_output_text
|
| 248 |
|
| 249 |
# 3. 生成圖片
|
| 250 |
+
image_output = generate_image_huggingface(prompt)
|
| 251 |
+
yield final_response, image_output, map_html, prompt_output_text
|
| 252 |
|
| 253 |
# ==========================================
|
| 254 |
+
# 4. 橋接邏輯 (Emotion Bridge)
|
| 255 |
# ==========================================
|
| 256 |
def _score_to_radio_value(score):
|
| 257 |
mapping = {1: "1 (心情差)", 2: "2 (不太好)", 3: "3 (普通)", 4: "4 (不錯)", 5: "5 (超棒)"}
|
| 258 |
+
try: score = int(score)
|
| 259 |
+
except: score = 3
|
| 260 |
+
return mapping.get(score, "3 (普通)")
|
| 261 |
|
| 262 |
def bridge_start_click(st):
|
| 263 |
res = emotion.on_restart(st)
|
| 264 |
+
return res[1], res[0], gr.update(visible=True), res[5], res[4], gr.update(visible=False)
|
| 265 |
|
| 266 |
def bridge_stop_click(st):
|
| 267 |
res = emotion.on_stop(st)
|
|
|
|
| 269 |
|
| 270 |
def bridge_predict_frame(frame, st):
|
| 271 |
res = emotion.on_stream(frame, st)
|
| 272 |
+
out_cam = res[0]; out_result = res[1]; out_st = res[4]; out_btn_start = res[5]
|
| 273 |
+
score_update = gr.update(); out_btn_stop = gr.update()
|
| 274 |
+
btn_go_visible = gr.update(visible=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
if out_st.finished and hasattr(out_st, 'final_score'):
|
| 277 |
new_val = _score_to_radio_value(out_st.final_score)
|
| 278 |
score_update = gr.update(value=new_val)
|
| 279 |
+
out_btn_stop = gr.update(visible=False)
|
| 280 |
+
btn_go_visible = gr.update(visible=True)
|
| 281 |
+
|
| 282 |
+
return out_cam, out_result, out_st, out_btn_stop, out_btn_start, score_update, btn_go_visible
|
| 283 |
|
| 284 |
# ==========================================
|
| 285 |
+
# 5. Gradio 介面建構
|
| 286 |
# ==========================================
|
| 287 |
+
css_ = "#app_container { max-width: 960px; margin: 0 auto; }"
|
| 288 |
+
|
| 289 |
+
with gr.Blocks(title="AI 心情食堂", css=css_) as demo:
|
| 290 |
+
|
| 291 |
st_state = gr.State(emotion.AppState())
|
| 292 |
|
| 293 |
with gr.Tabs() as tabs:
|
| 294 |
+
|
| 295 |
+
# Tab 1: 情緒辨識
|
| 296 |
+
with gr.TabItem("😊 情緒辨識 (Step 1)", id=0):
|
| 297 |
+
with gr.Column(elem_id="app_container"):
|
| 298 |
+
gr.Markdown("### 第一步:測測你的心情能量\n讓 AI 看看你的表情,自動幫你決定心情分數!(辨識完畢會自動跳轉)")
|
| 299 |
+
|
| 300 |
with gr.Row():
|
| 301 |
+
btn_start = gr.Button("📸 開啟攝影機辨識", variant="primary")
|
| 302 |
+
btn_stop = gr.Button("⏹️ 停止", variant="secondary", visible=False)
|
| 303 |
+
|
| 304 |
cam = gr.Image(sources=["webcam"], streaming=True, type="numpy", label="攝影機畫面", visible=False)
|
| 305 |
+
result_markdown = gr.Markdown(emotion._hint_html("請按「開啟攝影機辨識」並允許瀏覽器使用相機。"))
|
| 306 |
+
btn_go_dining = gr.Button("🚀 確定心情,來找餐廳!", variant="primary", visible=False, size="lg")
|
| 307 |
|
| 308 |
+
# Tab 2: 主功能區
|
| 309 |
+
with gr.TabItem("🍽️ AI 心情食堂 (Step 2)", id=1):
|
| 310 |
with gr.Column():
|
| 311 |
+
|
| 312 |
+
# 新增:爬蟲同步區塊
|
| 313 |
+
gr.Markdown("### 🔗 載入你的口袋名單")
|
| 314 |
with gr.Row():
|
| 315 |
+
map_url = gr.Textbox(label="Google Maps 分享連結", placeholder="請貼上清單的分享連結...", scale=3)
|
| 316 |
+
sync_btn = gr.Button("🔄 同步清單", variant="secondary", scale=1)
|
| 317 |
+
sync_msg = gr.Markdown("ℹ️ 尚未同步資料庫")
|
| 318 |
|
| 319 |
gr.Markdown("---")
|
| 320 |
+
gr.Markdown(f"## 🍱 今天想吃點什麼?")
|
| 321 |
|
| 322 |
with gr.Row():
|
| 323 |
with gr.Column(scale=1):
|
| 324 |
score_input = gr.Radio(
|
| 325 |
["1 (心情差)", "2 (不太好)", "3 (普通)", "4 (不錯)", "5 (超棒)"],
|
| 326 |
+
label="1. 心情分數 (由 Tab 1 自動填入)",
|
| 327 |
value="3 (普通)"
|
| 328 |
)
|
| 329 |
+
food_input = gr.Radio(["吃飯", "吃麵", "隨便"], label="2. 想吃什麼", value="隨便")
|
| 330 |
+
diary_input = gr.Textbox(lines=3, label="3. 心情日記", placeholder="寫下今天發生的事...")
|
| 331 |
|
| 332 |
+
# 新增:Prompt 檢查選項
|
| 333 |
show_prompt_chk = gr.Checkbox(label="顯示生成圖片的 Prompt (指令)", value=False)
|
| 334 |
|
| 335 |
submit_btn = gr.Button("🍱 推薦美食", variant="primary")
|
| 336 |
|
| 337 |
with gr.Column(scale=1):
|
| 338 |
+
agent_output = gr.Markdown(label="AI 回應")
|
| 339 |
+
image_output = gr.Image(label="AI 根據餐廳資訊生成的圖片", type="pil", width=400)
|
| 340 |
|
| 341 |
+
# 新增:Prompt 輸出框 (唯讀)
|
| 342 |
prompt_output = gr.Textbox(label="圖片生成指令 (Prompt)", visible=True, interactive=False)
|
| 343 |
|
| 344 |
+
map_output = gr.HTML(label="地圖導航")
|
| 345 |
|
| 346 |
+
# ==========================================
|
| 347 |
# 事件綁定
|
| 348 |
+
# ==========================================
|
| 349 |
+
|
| 350 |
+
# 綁定爬蟲同步按鈕
|
| 351 |
sync_btn.click(fn=sync_google_maps, inputs=[map_url], outputs=[sync_msg])
|
| 352 |
+
|
| 353 |
+
# 情緒辨識按鈕
|
| 354 |
+
btn_start.click(
|
| 355 |
+
fn=bridge_start_click,
|
| 356 |
+
inputs=[st_state],
|
| 357 |
+
outputs=[result_markdown, cam, btn_stop, btn_start, st_state, btn_go_dining],
|
| 358 |
+
show_progress="minimal"
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
btn_stop.click(
|
| 362 |
+
fn=bridge_stop_click,
|
| 363 |
+
inputs=[st_state],
|
| 364 |
+
outputs=[result_markdown, cam, btn_stop, btn_start, st_state],
|
| 365 |
+
show_progress="minimal"
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
cam.stream(
|
| 369 |
+
fn=bridge_predict_frame,
|
| 370 |
+
inputs=[cam, st_state],
|
| 371 |
+
outputs=[cam, result_markdown, st_state, btn_stop, btn_start, score_input, btn_go_dining],
|
| 372 |
+
show_progress="minimal"
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
btn_go_dining.click(
|
| 376 |
+
fn=lambda: gr.Tabs(selected=1),
|
| 377 |
+
inputs=None,
|
| 378 |
+
outputs=tabs
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
# 送出推薦 (加入 show_prompt 邏輯)
|
| 382 |
submit_btn.click(
|
| 383 |
+
fn=mood_agent_logic,
|
| 384 |
+
inputs=[score_input, food_input, diary_input, show_prompt_chk],
|
| 385 |
+
outputs=[agent_output, image_output, map_output, prompt_output]
|
| 386 |
)
|
| 387 |
|
| 388 |
if __name__ == "__main__":
|
| 389 |
+
demo.launch(ssr_mode=False)
|