Update app.py
Browse files
app.py
CHANGED
|
@@ -10,131 +10,49 @@ 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 |
# ==========================================
|
| 16 |
-
# 0. 環境變數
|
| 17 |
# ==========================================
|
| 18 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 19 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 20 |
|
| 21 |
-
# 全域變數
|
| 22 |
global_df = None
|
| 23 |
global_mood_df = None
|
| 24 |
global_retriever = None
|
| 25 |
rag_initialized = False
|
| 26 |
|
| 27 |
-
# ==========================================
|
| 28 |
-
# 1. 系統初始化 (讀取 CSV + 讀取 FAISS)
|
| 29 |
-
# ==========================================
|
| 30 |
def init_rag_system():
|
| 31 |
global global_df, global_mood_df, global_retriever, rag_initialized
|
| 32 |
-
|
| 33 |
if rag_initialized: return
|
| 34 |
-
|
| 35 |
-
print("⏳ 正在初始化系統...")
|
| 36 |
-
|
| 37 |
-
# --- A. 讀取 CSV (用於篩選與對照) ---
|
| 38 |
try:
|
| 39 |
global_df = pd.read_csv('restaurants.csv')
|
| 40 |
global_df['RAG_Content'] = global_df['RAG_Content'].fillna("")
|
| 41 |
global_df['Category'] = global_df['Category'].fillna("其他")
|
| 42 |
-
|
| 43 |
global_mood_df = pd.read_csv('mood_food_guide.csv')
|
| 44 |
-
|
| 45 |
-
except Exception as e:
|
| 46 |
-
print(f"❌ CSV 讀取失敗: {e}")
|
| 47 |
-
return
|
| 48 |
-
|
| 49 |
-
# --- B. 讀取預先建立好的 FAISS 索引 ---
|
| 50 |
if os.path.exists("faiss_index"):
|
| 51 |
try:
|
| 52 |
-
print("⏳ 正在載入 FAISS 向量資料庫...")
|
| 53 |
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 54 |
-
|
| 55 |
-
vectorstore = FAISS.load_local(
|
| 56 |
-
"faiss_index",
|
| 57 |
-
embeddings,
|
| 58 |
-
allow_dangerous_deserialization=True
|
| 59 |
-
)
|
| 60 |
global_retriever = vectorstore.as_retriever(search_kwargs={"k": 3})
|
| 61 |
-
|
| 62 |
-
except Exception as e:
|
| 63 |
-
print(f"❌ FAISS 載入失敗: {e}")
|
| 64 |
-
else:
|
| 65 |
-
print("⚠️ 警告:找不到 'faiss_index' 資料夾,RAG 功能將無法使用。")
|
| 66 |
-
print("請先執行 build_index.py 並上傳資料夾。")
|
| 67 |
-
|
| 68 |
rag_initialized = True
|
| 69 |
|
| 70 |
# ==========================================
|
| 71 |
-
# 2.
|
| 72 |
-
# ==========================================
|
| 73 |
-
custom_css = """
|
| 74 |
-
#hidden_tabs > .tab-nav { display: none !important; visibility: hidden !important; }
|
| 75 |
-
#hidden_tabs > div > button { display: none !important; }
|
| 76 |
-
.vertical-radio fieldset { display: flex !important; flex-direction: column !important; gap: 12px !important; }
|
| 77 |
-
.vertical-radio label { width: 100% !important; margin: 0 !important; display: flex !important; }
|
| 78 |
-
"""
|
| 79 |
-
|
| 80 |
-
# 設定圖片路徑
|
| 81 |
-
img_path_1 = "images/image_0.png"
|
| 82 |
-
img_path_2 = "images/image_1.png"
|
| 83 |
-
img_path_3 = "images/image_2.png" # Q3
|
| 84 |
-
img_path_4 = "images/image_3.png" # Q4
|
| 85 |
-
img_path_5 = "images/image_4.png" # Q5
|
| 86 |
-
|
| 87 |
-
if not os.path.exists("images"): os.makedirs("images")
|
| 88 |
-
for p in [img_path_1, img_path_2, img_path_3, img_path_4, img_path_5]:
|
| 89 |
-
if not os.path.exists(p):
|
| 90 |
-
Image.new('RGB', (400, 300), color='lightgray').save(p)
|
| 91 |
-
|
| 92 |
-
# --- 選項設定 ---
|
| 93 |
-
q1_options_map = {
|
| 94 |
-
"不要再問白癡問題了我只想吃飯": "現實主義者 (只想吃飯)",
|
| 95 |
-
"去過隱居生活": "隱士 (嚮往平靜)",
|
| 96 |
-
"加入禁衛軍,保衛這個世界": "守護者 (充滿正義感)",
|
| 97 |
-
"神羅天征,毀滅這個世界": "破壞神 (心情可能很差或很中二)"
|
| 98 |
-
}
|
| 99 |
-
q2_options_map = {
|
| 100 |
-
"不要再問白癡問題了我只想吃飯": "無魔法 (飢餓度MAX)",
|
| 101 |
-
"麵包形狀的魔法炸彈": "爆炸魔法 (喜歡刺激/重口味)",
|
| 102 |
-
"毒氣的生化魔法": "毒氣魔法 (可能想吃臭豆腐或特殊風味)",
|
| 103 |
-
"領域展開:無量空處": "領域展開 (思緒混亂或想放空)"
|
| 104 |
-
}
|
| 105 |
-
q3_options_map = {
|
| 106 |
-
"不要在問白癡問題了我只想吃飯": "現實主義者 (只想吃飯)",
|
| 107 |
-
"歐洲": "嚮往歐洲 (浪漫/西式)",
|
| 108 |
-
"日本": "嚮往日本 (精緻/日式)",
|
| 109 |
-
"泰國": "嚮往泰國 (熱情/酸辣)",
|
| 110 |
-
"轉身搭機捷回家": "戀家 (只想回家)"
|
| 111 |
-
}
|
| 112 |
-
q4_options_map = {
|
| 113 |
-
"轉頭回家睡覺": "獨行俠 (想睡覺)",
|
| 114 |
-
"看起來很會玩的帥潮": "外向 (找帥潮)",
|
| 115 |
-
"感覺是動漫宅的同好": "御宅族 (找同好)",
|
| 116 |
-
"有興趣的異性": "大膽 (找異性)"
|
| 117 |
-
}
|
| 118 |
-
q5_options_map = {
|
| 119 |
-
"甚麼都不想": "放空 (什麼都不想)",
|
| 120 |
-
"來自星星的你": "韓��迷 (浪漫愛情)",
|
| 121 |
-
"進擊的巨人": "動漫迷 (熱血戰鬥)",
|
| 122 |
-
"洛基": "美劇迷 (懸疑燒腦)"
|
| 123 |
-
}
|
| 124 |
-
|
| 125 |
# ==========================================
|
| 126 |
-
# 3. 核心功能
|
| 127 |
-
# ==========================================
|
| 128 |
-
|
| 129 |
def get_restaurant_data(mood_score_str, food_choice):
|
| 130 |
init_rag_system()
|
| 131 |
if global_df is None or global_df.empty: return None, True, "資料庫未載入", "無建議"
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
score = int(str(mood_score_str).split(' ')[0])
|
| 135 |
-
except:
|
| 136 |
-
score = 3
|
| 137 |
-
|
| 138 |
mood_info = global_mood_df[global_mood_df['分數'] == score]
|
| 139 |
if not mood_info.empty:
|
| 140 |
rec_categories = mood_info.iloc[0]['推薦料理類別']
|
|
@@ -142,253 +60,206 @@ def get_restaurant_data(mood_score_str, food_choice):
|
|
| 142 |
else:
|
| 143 |
rec_categories = ""
|
| 144 |
mood_reason = "隨意探索"
|
| 145 |
-
|
| 146 |
candidates = global_df.copy()
|
| 147 |
-
|
| 148 |
if rec_categories:
|
| 149 |
candidates = candidates[candidates['Category'].apply(lambda x: str(x) in str(rec_categories) or str(rec_categories) in str(x))]
|
| 150 |
-
|
| 151 |
food_keyword = "飯" if food_choice == "吃飯" else "麵" if food_choice == "吃麵" else ""
|
| 152 |
if food_keyword:
|
| 153 |
-
candidates = candidates[
|
| 154 |
-
candidates['Name'].str.contains(food_keyword, case=False, na=False) |
|
| 155 |
-
candidates['RAG_Content'].str.contains(food_keyword, case=False, na=False)
|
| 156 |
-
]
|
| 157 |
-
|
| 158 |
if candidates.empty:
|
| 159 |
-
result = global_df.sample(1).iloc[0]
|
| 160 |
-
is_random = True
|
| 161 |
else:
|
| 162 |
-
result = candidates.sample(1).iloc[0]
|
| 163 |
-
is_random = False
|
| 164 |
-
|
| 165 |
return result, is_random, rec_categories, mood_reason
|
| 166 |
|
| 167 |
-
|
| 168 |
-
def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, mood_score, quiz_result, mood_guide_reason, debug_mode=False):
|
| 169 |
if not GROQ_API_KEY: return "⚠️ 請設定 GROQ_API_KEY"
|
| 170 |
-
|
| 171 |
client = OpenAI(api_key=GROQ_API_KEY, base_url="https://api.groq.com/openai/v1")
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
user_msg = f"""
|
| 176 |
-
【狀態】心情分數:{mood_score},日記:{user_diary}
|
| 177 |
-
|
| 178 |
-
【五題測驗結果】
|
| 179 |
-
1. 人設直覺:{quiz_result.get('q1', '未知')}
|
| 180 |
-
2. 魔法適性:{quiz_result.get('q2', '未知')}
|
| 181 |
-
3. 旅遊偏好:{quiz_result.get('q3', '未知')}
|
| 182 |
-
4. 社交選擇:{quiz_result.get('q4', '未知')}
|
| 183 |
-
5. 追劇偏好:{quiz_result.get('q5', '未知')}
|
| 184 |
-
|
| 185 |
-
【心情美食指南建議】
|
| 186 |
-
因為分數是 {mood_score},建議吃這類食物的原因是:「{mood_guide_reason}」。
|
| 187 |
-
|
| 188 |
-
【推薦餐廳】
|
| 189 |
-
名稱:{restaurant_name}
|
| 190 |
-
資料:{restaurant_detail}
|
| 191 |
-
|
| 192 |
-
任務:
|
| 193 |
-
請用繁體中文寫一段溫暖有趣的回覆:
|
| 194 |
-
1. 綜合回應他的日記與上述 5 個測驗結果。
|
| 195 |
-
2. 引用「心情美食指南」的原因。
|
| 196 |
-
3. 介紹這家餐廳的特色。
|
| 197 |
-
(只需要回覆文字內容)
|
| 198 |
-
"""
|
| 199 |
-
|
| 200 |
try:
|
| 201 |
-
response = client.chat.completions.create(
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
content = response.choices[0].message.content
|
| 205 |
-
|
| 206 |
-
# [修改] 如果開啟除錯模式,附加 Prompt 資訊
|
| 207 |
-
if debug_mode:
|
| 208 |
-
debug_info = f"""
|
| 209 |
-
\n\n--- 🛠️ [DEBUG] LLM Prompt 檢查 ---
|
| 210 |
-
\n**System Prompt:**\n{system_prompt}
|
| 211 |
-
\n**User Message:**\n{user_msg}
|
| 212 |
-
\n-----------------------------------
|
| 213 |
-
"""
|
| 214 |
-
return content + debug_info
|
| 215 |
-
|
| 216 |
-
return content
|
| 217 |
-
except Exception as e:
|
| 218 |
-
return f"Groq Error: {str(e)}"
|
| 219 |
|
| 220 |
def generate_image_huggingface(prompt):
|
| 221 |
if not HF_TOKEN: return None
|
| 222 |
-
if not prompt or pd.isna(prompt): prompt = "Delicious gourmet food, photorealistic, 8k"
|
| 223 |
-
|
| 224 |
try:
|
| 225 |
hf_client = InferenceClient(token=HF_TOKEN)
|
| 226 |
return hf_client.text_to_image(prompt=prompt, model="stabilityai/stable-diffusion-xl-base-1.0")
|
| 227 |
-
except
|
| 228 |
-
print(f"❌ 生圖失敗: {e}")
|
| 229 |
-
return None
|
| 230 |
|
| 231 |
-
|
| 232 |
-
def mood_agent_logic(score_input, food_input, diary_input, quiz_state, debug_mode):
|
| 233 |
restaurant, is_random, rec_categories, mood_reason = get_restaurant_data(score_input, food_input)
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
yield "資料庫讀取錯誤", None, ""
|
| 237 |
-
return
|
| 238 |
-
|
| 239 |
-
name = restaurant['Name']
|
| 240 |
-
address = restaurant['Address']
|
| 241 |
-
url = restaurant['URL']
|
| 242 |
-
img_prompt = restaurant.get('Visual_prompt')
|
| 243 |
-
note = "(隨機推薦)" if is_random else ""
|
| 244 |
-
|
| 245 |
-
# RAG 檢索
|
| 246 |
rag_info = str(restaurant.get('RAG_Content', ''))
|
| 247 |
if global_retriever:
|
| 248 |
docs = global_retriever.invoke(name)
|
| 249 |
-
if docs:
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
# [修改] 傳入 debug_mode
|
| 253 |
-
ai_text = generate_content_with_groq(name, rag_info, diary_input, score_input, quiz_state, mood_reason, debug_mode)
|
| 254 |
-
|
| 255 |
-
# [修改] 如果開啟除錯模式,附加圖片 Prompt 資訊
|
| 256 |
-
if debug_mode:
|
| 257 |
-
img_debug_info = f"""
|
| 258 |
-
\n\n--- 🛠️ [DEBUG] 圖片生成檢查 ---
|
| 259 |
-
\n**使用的 Visual Prompt:**\n{img_prompt}
|
| 260 |
-
\n(如果上方圖片為空白,可能是 HF API 忙碌或 Prompt 無效)
|
| 261 |
-
\n-----------------------------------
|
| 262 |
-
"""
|
| 263 |
-
ai_text += img_debug_info
|
| 264 |
-
|
| 265 |
-
final_response = f"### 🍽️ 推薦:{name} {note}\n\n{ai_text}"
|
| 266 |
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>'
|
| 267 |
-
|
| 268 |
yield final_response, None, map_html
|
| 269 |
image_output = generate_image_huggingface(img_prompt)
|
| 270 |
yield final_response, image_output, map_html
|
| 271 |
|
|
|
|
| 272 |
# ==========================================
|
| 273 |
-
#
|
| 274 |
# ==========================================
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
|
| 300 |
# ==========================================
|
| 301 |
-
#
|
| 302 |
# ==========================================
|
| 303 |
-
with gr.Blocks(title="AI 心情食堂") as demo:
|
| 304 |
-
gr.HTML(f"<style>{custom_css}</style>")
|
| 305 |
-
quiz_state = gr.State(value={})
|
| 306 |
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
gr.
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
gr.
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
btn_q3_next = gr.Button("下一頁 ➔", interactive=False)
|
| 334 |
-
|
| 335 |
-
# Tab 3: Q4
|
| 336 |
-
with gr.TabItem("Q4", id=3):
|
| 337 |
-
with gr.Column():
|
| 338 |
-
gr.Markdown("### 🔮 第四題:社交場合")
|
| 339 |
-
gr.Image(value=img_path_4, type="filepath", label="請觀察圖片", height=300)
|
| 340 |
-
gr.Markdown("**問題四:你是小大一,班上還不熟,現在你正參加你們班上的認識彼此的活動,下列哪一個人是你會選擇搭話的人?**")
|
| 341 |
-
radio_q4 = gr.Radio(choices=list(q4_options_map.keys()), label="請選擇", elem_classes="vertical-radio")
|
| 342 |
-
btn_q4_next = gr.Button("下一頁 ➔", interactive=False)
|
| 343 |
-
|
| 344 |
-
# Tab 4: Q5
|
| 345 |
-
with gr.TabItem("Q5", id=4):
|
| 346 |
-
with gr.Column():
|
| 347 |
-
gr.Markdown("### 🔮 第五題:追劇時光")
|
| 348 |
-
gr.Image(value=img_path_5, type="filepath", label="請觀察圖片", height=300)
|
| 349 |
-
gr.Markdown("**問題五:假設失憶了忘記以下所列的劇的劇情,而你現在閒了下來剛好想看劇,你會想看哪一部?**")
|
| 350 |
-
radio_q5 = gr.Radio(choices=list(q5_options_map.keys()), label="請選擇", elem_classes="vertical-radio")
|
| 351 |
-
btn_q5_finish = gr.Button("完成測驗 ➔", interactive=False)
|
| 352 |
-
|
| 353 |
-
# Tab 5: Main
|
| 354 |
-
with gr.TabItem("Main", id=5):
|
| 355 |
with gr.Column():
|
| 356 |
-
gr.Markdown(f"## 🍱
|
| 357 |
with gr.Row():
|
| 358 |
with gr.Column(scale=1):
|
| 359 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 360 |
food_input = gr.Radio(["吃飯", "吃麵", "隨便"], label="2. 想吃什麼", value="隨便")
|
| 361 |
diary_input = gr.Textbox(lines=4, label="3. 心情日記", placeholder="寫下今天發生的事...")
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
submit_btn = gr.Button("送出給 Agent", variant="primary")
|
| 367 |
with gr.Column(scale=1):
|
| 368 |
agent_output = gr.Markdown(label="AI 回應")
|
| 369 |
image_output = gr.Image(label="AI 推薦美食圖", type="pil", width=400)
|
| 370 |
map_output = gr.HTML(label="地圖導航")
|
| 371 |
|
| 372 |
-
#
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
radio_q2.change(fn=handle_q2_change, inputs=[radio_q2, quiz_state], outputs=[quiz_state, btn_q2_next])
|
| 377 |
-
btn_q2_next.click(fn=lambda: gr.Tabs(selected=2), outputs=tabs)
|
| 378 |
|
| 379 |
-
|
| 380 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
|
| 382 |
-
|
| 383 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 384 |
|
| 385 |
-
|
| 386 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 387 |
|
| 388 |
-
# [修改] 加入 debug_mode_btn 到輸入
|
| 389 |
submit_btn.click(
|
| 390 |
fn=mood_agent_logic,
|
| 391 |
-
inputs=[score_input, food_input, diary_input,
|
| 392 |
outputs=[agent_output, image_output, map_output]
|
| 393 |
)
|
| 394 |
|
|
|
|
| 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]['推薦料理類別']
|
|
|
|
| 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 |
|