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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from openai import OpenAI
|
| 3 |
+
from huggingface_hub import InferenceClient
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
import requests
|
| 7 |
+
import urllib.parse
|
| 8 |
+
import pandas as pd
|
| 9 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
| 10 |
+
from langchain_community.vectorstores import FAISS
|
| 11 |
+
from PIL import Image
|
| 12 |
+
from dotenv import load_dotenv
|
| 13 |
+
|
| 14 |
+
# --- 匯入組員的模組 ---
|
| 15 |
+
import emotion
|
| 16 |
+
# ---------------------------
|
| 17 |
+
|
| 18 |
+
load_dotenv()
|
| 19 |
+
|
| 20 |
+
# ==========================================
|
| 21 |
+
# 0. 環境變數 & 1. 系統初始化 (保持不變)
|
| 22 |
+
# ==========================================
|
| 23 |
+
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 24 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 25 |
+
|
| 26 |
+
global_df = None
|
| 27 |
+
global_mood_df = None
|
| 28 |
+
global_retriever = None
|
| 29 |
+
rag_initialized = False
|
| 30 |
+
|
| 31 |
+
def init_rag_system():
|
| 32 |
+
global global_df, global_mood_df, global_retriever, rag_initialized
|
| 33 |
+
if rag_initialized: return
|
| 34 |
+
try:
|
| 35 |
+
global_df = pd.read_csv('restaurants.csv')
|
| 36 |
+
global_df['RAG_Content'] = global_df['RAG_Content'].fillna("")
|
| 37 |
+
global_df['Category'] = global_df['Category'].fillna("其他")
|
| 38 |
+
global_mood_df = pd.read_csv('mood_food_guide.csv')
|
| 39 |
+
except Exception: pass
|
| 40 |
+
if os.path.exists("faiss_index"):
|
| 41 |
+
try:
|
| 42 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 43 |
+
vectorstore = FAISS.load_local("faiss_index", embeddings, allow_dangerous_deserialization=True)
|
| 44 |
+
global_retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
|
| 45 |
+
except Exception: pass
|
| 46 |
+
rag_initialized = True
|
| 47 |
+
|
| 48 |
+
# ==========================================
|
| 49 |
+
# 2. 核心功能 (保持不變)
|
| 50 |
+
# ==========================================
|
| 51 |
+
def get_restaurant_data(mood_score_str, food_choice):
|
| 52 |
+
init_rag_system()
|
| 53 |
+
if global_df is None or global_df.empty: return None, True, "資料庫未載入", "無建議"
|
| 54 |
+
try: score = int(str(mood_score_str).split(' ')[0])
|
| 55 |
+
except: score = 3
|
| 56 |
+
mood_info = global_mood_df[global_mood_df['分數'] == score]
|
| 57 |
+
if not mood_info.empty:
|
| 58 |
+
rec_categories = mood_info.iloc[0]['推薦料理類別']
|
| 59 |
+
mood_reason = mood_info.iloc[0]['原因']
|
| 60 |
+
else:
|
| 61 |
+
rec_categories = ""
|
| 62 |
+
mood_reason = "隨意探索"
|
| 63 |
+
candidates = global_df.copy()
|
| 64 |
+
if rec_categories:
|
| 65 |
+
candidates = candidates[candidates['Category'].apply(lambda x: str(x) in str(rec_categories) or str(rec_categories) in str(x))]
|
| 66 |
+
food_keyword = "飯" if food_choice == "吃飯" else "麵" if food_choice == "吃麵" else ""
|
| 67 |
+
if food_keyword:
|
| 68 |
+
candidates = candidates[candidates['Name'].str.contains(food_keyword, case=False, na=False) | candidates['RAG_Content'].str.contains(food_keyword, case=False, na=False)]
|
| 69 |
+
if candidates.empty:
|
| 70 |
+
result = global_df.sample(1).iloc[0]; is_random = True
|
| 71 |
+
else:
|
| 72 |
+
result = candidates.sample(1).iloc[0]; is_random = False
|
| 73 |
+
return result, is_random, rec_categories, mood_reason
|
| 74 |
+
|
| 75 |
+
def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, mood_score, mood_guide_reason, debug_mode=False):
|
| 76 |
+
if not GROQ_API_KEY: return "⚠️ 請設定 GROQ_API_KEY"
|
| 77 |
+
client = OpenAI(api_key=GROQ_API_KEY, base_url="https://api.groq.com/openai/v1")
|
| 78 |
+
system_prompt = "你是一個幽默、懂吃且善解人意的 AI 朋友..."
|
| 79 |
+
user_msg = f"【狀態】心情分數:{mood_score}\n【日記】{user_diary}\n【建議原因】{mood_guide_reason}\n【餐廳】{restaurant_name}\n資料:{restaurant_detail}"
|
| 80 |
+
try:
|
| 81 |
+
response = client.chat.completions.create(model="llama-3.3-70b-versatile", messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_msg}])
|
| 82 |
+
return response.choices[0].message.content
|
| 83 |
+
except Exception as e: return f"Groq Error: {str(e)}"
|
| 84 |
+
|
| 85 |
+
def generate_image_huggingface(prompt):
|
| 86 |
+
if not HF_TOKEN: return None
|
| 87 |
+
try:
|
| 88 |
+
hf_client = InferenceClient(token=HF_TOKEN)
|
| 89 |
+
return hf_client.text_to_image(prompt=prompt, model="stabilityai/stable-diffusion-xl-base-1.0")
|
| 90 |
+
except: return None
|
| 91 |
+
|
| 92 |
+
def mood_agent_logic(score_input, food_input, diary_input, debug_mode):
|
| 93 |
+
restaurant, is_random, rec_categories, mood_reason = get_restaurant_data(score_input, food_input)
|
| 94 |
+
if restaurant is None: yield "資料庫讀取錯誤", None, ""; return
|
| 95 |
+
name = restaurant['Name']; address = restaurant['Address']; url = restaurant['URL']; img_prompt = restaurant.get('Visual_prompt')
|
| 96 |
+
rag_info = str(restaurant.get('RAG_Content', ''))
|
| 97 |
+
if global_retriever:
|
| 98 |
+
docs = global_retriever.invoke(name)
|
| 99 |
+
if docs: rag_info = "\n".join([d.page_content for d in docs])
|
| 100 |
+
ai_text = generate_content_with_groq(name, rag_info, diary_input, score_input, mood_reason, debug_mode)
|
| 101 |
+
final_response = f"### 🍽️ 推薦:{name}\n\n{ai_text}"
|
| 102 |
+
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>'
|
| 103 |
+
yield final_response, None, map_html
|
| 104 |
+
image_output = generate_image_huggingface(img_prompt)
|
| 105 |
+
yield final_response, image_output, map_html
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# ==========================================
|
| 109 |
+
# 3. [修正版] 橋接邏輯 (Bridge Functions)
|
| 110 |
+
# ==========================================
|
| 111 |
+
|
| 112 |
+
# 這是 app.py 自己的格式 (注意:這裡是半形括號)
|
| 113 |
+
def _score_to_radio_value(score):
|
| 114 |
+
mapping = {1: "1 (心情差)", 2: "2 (不太好)", 3: "3 (普通)", 4: "4 (不錯)", 5: "5 (超棒)"}
|
| 115 |
+
# 預防萬一 score 是 None 或其他怪怪的值
|
| 116 |
+
try:
|
| 117 |
+
score = int(score)
|
| 118 |
+
except:
|
| 119 |
+
score = 3
|
| 120 |
+
return mapping.get(score, "3 (普通)")
|
| 121 |
+
|
| 122 |
+
# 橋接 1:開始
|
| 123 |
+
def bridge_start_click(st):
|
| 124 |
+
res = emotion.on_restart(st)
|
| 125 |
+
return res[1], res[0], gr.update(visible=True), res[5], res[4]
|
| 126 |
+
|
| 127 |
+
# 橋接 2:停止
|
| 128 |
+
def bridge_stop_click(st):
|
| 129 |
+
res = emotion.on_stop(st)
|
| 130 |
+
return res[1], res[0], gr.update(visible=False), res[5], res[4]
|
| 131 |
+
|
| 132 |
+
# 橋接 3:Webcam 串流 (修正分數填入問題)
|
| 133 |
+
def bridge_predict_frame(frame, st):
|
| 134 |
+
res = emotion.on_stream(frame, st)
|
| 135 |
+
|
| 136 |
+
out_cam = res[0]
|
| 137 |
+
out_result = res[1]
|
| 138 |
+
# out_mood = res[2] # ❌ 我們不使用隊友回傳的 UI 更新,因為括號格式不同
|
| 139 |
+
out_st = res[4]
|
| 140 |
+
out_btn_start = res[5]
|
| 141 |
+
|
| 142 |
+
score_update = gr.update()
|
| 143 |
+
tabs_update = gr.update()
|
| 144 |
+
out_btn_stop = gr.update()
|
| 145 |
+
|
| 146 |
+
# 如果辨識完成,我們自己產生一個符合 app.py 格式的 UI 更新
|
| 147 |
+
if out_st.finished and hasattr(out_st, 'final_score'):
|
| 148 |
+
# ✅ 使用 _score_to_radio_value 將整數轉換為半形括號字串
|
| 149 |
+
new_val = _score_to_radio_value(out_st.final_score)
|
| 150 |
+
score_update = gr.update(value=new_val)
|
| 151 |
+
|
| 152 |
+
tabs_update = gr.Tabs(selected=1)
|
| 153 |
+
out_btn_stop = gr.update(visible=False)
|
| 154 |
+
|
| 155 |
+
return out_cam, out_result, out_st, out_btn_stop, out_btn_start, score_update, tabs_update
|
| 156 |
+
|
| 157 |
+
# 橋接 4:圖片上傳 (修正分數填入問題)
|
| 158 |
+
def bridge_predict_upload(img, st):
|
| 159 |
+
res = emotion.on_upload(img, st)
|
| 160 |
+
|
| 161 |
+
out_result = res[0]
|
| 162 |
+
# out_mood = res[1] # ❌ 同樣忽略隊友的格式
|
| 163 |
+
out_st = res[2]
|
| 164 |
+
|
| 165 |
+
score_update = gr.update()
|
| 166 |
+
tabs_update = gr.update()
|
| 167 |
+
|
| 168 |
+
if out_st.finished and hasattr(out_st, 'final_score'):
|
| 169 |
+
# ✅ 使用 _score_to_radio_value 將整數轉換為半形括號字串
|
| 170 |
+
new_val = _score_to_radio_value(out_st.final_score)
|
| 171 |
+
score_update = gr.update(value=new_val)
|
| 172 |
+
|
| 173 |
+
tabs_update = gr.Tabs(selected=1)
|
| 174 |
+
|
| 175 |
+
return out_result, score_update, tabs_update, out_st
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
# ==========================================
|
| 179 |
+
# 4. Gradio 介面建構
|
| 180 |
+
# ==========================================
|
| 181 |
+
|
| 182 |
+
combined_css = emotion.css
|
| 183 |
+
|
| 184 |
+
with gr.Blocks(title="AI 心情食堂", css=combined_css) as demo:
|
| 185 |
+
|
| 186 |
+
st_state = gr.State(emotion.AppState())
|
| 187 |
+
|
| 188 |
+
with gr.Tabs() as tabs:
|
| 189 |
+
|
| 190 |
+
# Tab 1: 情緒辨識
|
| 191 |
+
with gr.TabItem("😊 情緒辨識 (Step 1)", id=0):
|
| 192 |
+
with gr.Column(elem_id="app_container"):
|
| 193 |
+
gr.Markdown("### 第一步:測測你的心情能量\n讓 AI 看看你的表情,自動幫你決定心情分數!(辨識完畢會自動跳轉)")
|
| 194 |
+
|
| 195 |
+
with gr.Row():
|
| 196 |
+
btn_start = gr.Button("📸 開啟攝影機辨識", variant="primary")
|
| 197 |
+
btn_stop = gr.Button("⏹️ 停止", variant="secondary", visible=False)
|
| 198 |
+
|
| 199 |
+
cam = gr.Image(sources=["webcam"], streaming=True, type="numpy", label="攝影機畫面", visible=False)
|
| 200 |
+
result_markdown = gr.Markdown(emotion._hint_html("請按「開啟攝影機辨識」或下方上傳照片。"))
|
| 201 |
+
|
| 202 |
+
gr.Markdown("---")
|
| 203 |
+
gr.Markdown("### 或者:上傳照片")
|
| 204 |
+
upload_img = gr.Image(sources=["upload"], type="numpy", label="上傳照片")
|
| 205 |
+
|
| 206 |
+
# Tab 2: 主功能區
|
| 207 |
+
with gr.TabItem("🍽️ AI 心情食堂 (Step 2)", id=1):
|
| 208 |
+
with gr.Column():
|
| 209 |
+
gr.Markdown(f"## 🍱 今天想吃點什麼?")
|
| 210 |
+
with gr.Row():
|
| 211 |
+
with gr.Column(scale=1):
|
| 212 |
+
# 这里的 Radio 选项使用的是半形括号
|
| 213 |
+
score_input = gr.Radio(
|
| 214 |
+
["1 (心情差)", "2 (不太好)", "3 (普通)", "4 (不錯)", "5 (超棒)"],
|
| 215 |
+
label="1. 心情分數 (由 Tab 1 自動填入)",
|
| 216 |
+
value="3 (普通)"
|
| 217 |
+
)
|
| 218 |
+
food_input = gr.Radio(["吃飯", "吃麵", "隨便"], label="2. 想吃什麼", value="隨便")
|
| 219 |
+
diary_input = gr.Textbox(lines=4, label="3. 心情日記", placeholder="寫下今天發生的事...")
|
| 220 |
+
debug_mode_btn = gr.Checkbox(label="🔧 開啟除錯模式", value=False)
|
| 221 |
+
submit_btn = gr.Button("🍱 送出給 Agent", variant="primary")
|
| 222 |
+
|
| 223 |
+
with gr.Column(scale=1):
|
| 224 |
+
agent_output = gr.Markdown(label="AI 回應")
|
| 225 |
+
image_output = gr.Image(label="AI 推薦美食圖", type="pil", width=400)
|
| 226 |
+
map_output = gr.HTML(label="地圖導航")
|
| 227 |
+
|
| 228 |
+
# ==========================================
|
| 229 |
+
# 事件綁定
|
| 230 |
+
# ==========================================
|
| 231 |
+
|
| 232 |
+
btn_start.click(
|
| 233 |
+
fn=bridge_start_click,
|
| 234 |
+
inputs=[st_state],
|
| 235 |
+
outputs=[result_markdown, cam, btn_stop, btn_start, st_state],
|
| 236 |
+
show_progress="minimal"
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
btn_stop.click(
|
| 240 |
+
fn=bridge_stop_click,
|
| 241 |
+
inputs=[st_state],
|
| 242 |
+
outputs=[result_markdown, cam, btn_stop, btn_start, st_state],
|
| 243 |
+
show_progress="minimal"
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
cam.stream(
|
| 247 |
+
fn=bridge_predict_frame,
|
| 248 |
+
inputs=[cam, st_state],
|
| 249 |
+
outputs=[cam, result_markdown, st_state, btn_stop, btn_start, score_input, tabs],
|
| 250 |
+
show_progress="minimal"
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
upload_img.change(
|
| 254 |
+
fn=bridge_predict_upload,
|
| 255 |
+
inputs=[upload_img, st_state],
|
| 256 |
+
outputs=[result_markdown, score_input, tabs, st_state],
|
| 257 |
+
show_progress="minimal"
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
submit_btn.click(
|
| 261 |
+
fn=mood_agent_logic,
|
| 262 |
+
inputs=[score_input, food_input, diary_input, debug_mode_btn],
|
| 263 |
+
outputs=[agent_output, image_output, map_output]
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
if __name__ == "__main__":
|
| 267 |
+
demo.launch(ssr_mode=False)
|