Upload app.py
Browse files
app.py
CHANGED
|
@@ -18,7 +18,7 @@ from PIL import Image
|
|
| 18 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 19 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 20 |
|
| 21 |
-
# --- 資料讀取
|
| 22 |
df = pd.DataFrame()
|
| 23 |
try:
|
| 24 |
df = pd.read_csv('google_maps_rag_data.csv')
|
|
@@ -42,8 +42,23 @@ try:
|
|
| 42 |
if 'Mood_Tags' not in df.columns:
|
| 43 |
df['Mood_Tags'] = df.apply(classify_mood, axis=1)
|
| 44 |
except:
|
| 45 |
-
print("⚠️ 找不到
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
retriever = None
|
| 48 |
if not df.empty:
|
| 49 |
loader = DataFrameLoader(df, page_content_column="RAG_Content")
|
|
@@ -127,7 +142,10 @@ def get_restaurant_data(mood_score_str, food_choice):
|
|
| 127 |
return candidates.sample(1).iloc[0], False
|
| 128 |
|
| 129 |
def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, mood_score, quiz_result):
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
client = OpenAI(api_key=GROQ_API_KEY, base_url="https://api.groq.com/openai/v1")
|
| 133 |
|
|
@@ -146,36 +164,31 @@ def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, m
|
|
| 146 |
餐廳名稱:{restaurant_name}
|
| 147 |
詳細資料:{restaurant_detail}
|
| 148 |
|
| 149 |
-
請完成
|
| 150 |
-
|
| 151 |
- 結合「日記」與「前測人設」給予回應。
|
| 152 |
- 推薦上述餐廳,說明為什麼這家店適合他。
|
| 153 |
-
|
| 154 |
-
2. 【圖片 Prompt】:提供一個英文 Image Prompt。
|
| 155 |
-
- 根據「詳細資料」中的具體食物描述。
|
| 156 |
-
- 風格:Cinematic lighting, photorealistic, 8k, close-up food shot.
|
| 157 |
-
- 格式:直接給 Prompt 文字,不要加引號。
|
| 158 |
"""
|
| 159 |
try:
|
| 160 |
response = client.chat.completions.create(
|
| 161 |
-
model="llama-3.3-70b-versatile",
|
|
|
|
| 162 |
)
|
| 163 |
content = response.choices[0].message.content
|
| 164 |
-
|
| 165 |
-
parts = content.split("Prompt:" if "Prompt:" in content else "Prompt:")
|
| 166 |
-
return parts[0].replace("回應:", "").strip(), parts[1].strip()
|
| 167 |
-
return content, f"Delicious food from {restaurant_name}, photorealistic, 8k"
|
| 168 |
except Exception as e:
|
| 169 |
-
return f"Groq Error: {str(e)}"
|
| 170 |
|
| 171 |
def generate_image_huggingface(prompt):
|
| 172 |
if not HF_TOKEN: return None
|
| 173 |
try:
|
| 174 |
hf_client = InferenceClient(token=HF_TOKEN)
|
|
|
|
| 175 |
return hf_client.text_to_image(prompt=prompt, model="stabilityai/stable-diffusion-xl-base-1.0")
|
| 176 |
except: return None
|
| 177 |
|
| 178 |
-
# --- 主邏輯 Agent ---
|
| 179 |
def mood_agent_logic(score_input, food_input, diary_input, quiz_state):
|
| 180 |
restaurant, is_random = get_restaurant_data(score_input, food_input)
|
| 181 |
if restaurant is None:
|
|
@@ -187,17 +200,43 @@ def mood_agent_logic(score_input, food_input, diary_input, quiz_state):
|
|
| 187 |
url = restaurant['URL']
|
| 188 |
note = "(隨機推薦)" if is_random else ""
|
| 189 |
|
|
|
|
| 190 |
rag_info = str(restaurant['RAG_Content'])
|
| 191 |
if retriever:
|
| 192 |
docs = retriever.invoke(name)
|
| 193 |
if docs: rag_info = "\n".join([d.page_content for d in docs])
|
| 194 |
|
| 195 |
-
|
| 196 |
-
|
| 197 |
|
|
|
|
| 198 |
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>'
|
| 199 |
|
|
|
|
| 200 |
yield final_response, None, map_html
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
image_output = generate_image_huggingface(img_prompt)
|
| 202 |
yield final_response, image_output, map_html
|
| 203 |
|
|
@@ -215,7 +254,6 @@ def handle_q2_change(selected_label, current_state):
|
|
| 215 |
current_state["q2"] = q2_options_map[selected_label]
|
| 216 |
return current_state, gr.Button(interactive=True, variant="primary", value="完成測驗 (前往點餐) ➔")
|
| 217 |
|
| 218 |
-
# 🟢 換頁邏輯:回傳 gr.update 來控制 Column 的 visible
|
| 219 |
def go_to_page_2():
|
| 220 |
return gr.update(visible=False), gr.update(visible=True)
|
| 221 |
|
|
@@ -231,7 +269,7 @@ with gr.Blocks(title="AI 心情食堂") as demo:
|
|
| 231 |
gr.HTML(f"<style>{custom_css}</style>")
|
| 232 |
quiz_state = gr.State(value={})
|
| 233 |
|
| 234 |
-
# ------ Page 1: 測驗第一題
|
| 235 |
with gr.Column(visible=True) as page_1_col:
|
| 236 |
gr.Markdown("### 🔮 第一題:直覺測試")
|
| 237 |
gr.Image(value=img_path_1, type="filepath", label="請觀察圖片", height=300)
|
|
@@ -239,7 +277,7 @@ with gr.Blocks(title="AI 心情食堂") as demo:
|
|
| 239 |
radio_q1 = gr.Radio(choices=list(q1_options_map.keys()), label="請選擇", elem_classes="vertical-radio")
|
| 240 |
btn_q1_next = gr.Button("下一頁 ➔", interactive=False)
|
| 241 |
|
| 242 |
-
# ------ Page 2: 測驗第二題
|
| 243 |
with gr.Column(visible=False) as page_2_col:
|
| 244 |
gr.Markdown("### 🔮 第二題:魔法適性")
|
| 245 |
gr.Image(value=img_path_2, type="filepath", label="請觀察圖片", height=300)
|
|
@@ -247,7 +285,7 @@ with gr.Blocks(title="AI 心情食堂") as demo:
|
|
| 247 |
radio_q2 = gr.Radio(choices=list(q2_options_map.keys()), label="請選擇", elem_classes="vertical-radio")
|
| 248 |
btn_q2_finish = gr.Button("完成測驗 ➔", interactive=False)
|
| 249 |
|
| 250 |
-
# ------ Page 3: 主功能
|
| 251 |
with gr.Column(visible=False) as main_app_col:
|
| 252 |
gr.Markdown(f"## 🍱 AI 心情食堂導航")
|
| 253 |
gr.Markdown("測驗結束!現在,告訴我你真正想吃什麼吧!")
|
|
@@ -265,20 +303,11 @@ with gr.Blocks(title="AI 心情食堂") as demo:
|
|
| 265 |
map_output = gr.HTML(label="地圖導航")
|
| 266 |
|
| 267 |
# ------ 事件綁定 ------
|
| 268 |
-
|
| 269 |
-
# Q1: 選擇 -> 啟用按鈕
|
| 270 |
radio_q1.change(fn=handle_q1_change, inputs=[radio_q1, quiz_state], outputs=[quiz_state, btn_q1_next])
|
| 271 |
-
|
| 272 |
-
# Q1: 按鈕 -> 隱藏 Page 1, 顯示 Page 2
|
| 273 |
btn_q1_next.click(fn=go_to_page_2, outputs=[page_1_col, page_2_col])
|
| 274 |
-
|
| 275 |
-
# Q2: 選擇 -> 啟用按鈕
|
| 276 |
radio_q2.change(fn=handle_q2_change, inputs=[radio_q2, quiz_state], outputs=[quiz_state, btn_q2_finish])
|
| 277 |
-
|
| 278 |
-
# Q2: 按鈕 -> 隱藏 Page 2, 顯示 Main App
|
| 279 |
btn_q2_finish.click(fn=go_to_main_app, outputs=[page_2_col, main_app_col])
|
| 280 |
|
| 281 |
-
# Main: 送出 -> 執行 Agent
|
| 282 |
submit_btn.click(
|
| 283 |
fn=mood_agent_logic,
|
| 284 |
inputs=[score_input, food_input, diary_input, quiz_state],
|
|
|
|
| 18 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 19 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 20 |
|
| 21 |
+
# --- 1. 資料讀取 (主要資料庫) ---
|
| 22 |
df = pd.DataFrame()
|
| 23 |
try:
|
| 24 |
df = pd.read_csv('google_maps_rag_data.csv')
|
|
|
|
| 42 |
if 'Mood_Tags' not in df.columns:
|
| 43 |
df['Mood_Tags'] = df.apply(classify_mood, axis=1)
|
| 44 |
except:
|
| 45 |
+
print("⚠️ 找不到 google_maps_rag_data.csv,RAG 功能將受限")
|
| 46 |
|
| 47 |
+
# --- 2. 資料讀取 (Prompt 資料庫) [新增/修改部分] ---
|
| 48 |
+
df_prompts = pd.DataFrame()
|
| 49 |
+
try:
|
| 50 |
+
df_prompts = pd.read_csv('restaurants_prompts_v6.csv')
|
| 51 |
+
# 確保以 Name 為索引,方便快速查詢
|
| 52 |
+
# 假設 CSV 欄位名稱是 'Name' 和 'Image_Prompt',如果不一樣請在這裡改
|
| 53 |
+
if 'Name' in df_prompts.columns:
|
| 54 |
+
df_prompts.set_index('Name', inplace=True)
|
| 55 |
+
else:
|
| 56 |
+
print("⚠️ Prompt CSV 中找不到 'Name' 欄位")
|
| 57 |
+
except:
|
| 58 |
+
print("⚠️ 找不到 restaurants_prompts_v6.csv,將使用預設 Prompt")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# --- RAG 建置 ---
|
| 62 |
retriever = None
|
| 63 |
if not df.empty:
|
| 64 |
loader = DataFrameLoader(df, page_content_column="RAG_Content")
|
|
|
|
| 142 |
return candidates.sample(1).iloc[0], False
|
| 143 |
|
| 144 |
def generate_content_with_groq(restaurant_name, restaurant_detail, user_diary, mood_score, quiz_result):
|
| 145 |
+
"""
|
| 146 |
+
修改說明:這裡不再生成 Image Prompt,只專注於生成文字回應。
|
| 147 |
+
"""
|
| 148 |
+
if not GROQ_API_KEY: return "⚠️ 請設定 GROQ_API_KEY"
|
| 149 |
|
| 150 |
client = OpenAI(api_key=GROQ_API_KEY, base_url="https://api.groq.com/openai/v1")
|
| 151 |
|
|
|
|
| 164 |
餐廳名稱:{restaurant_name}
|
| 165 |
詳細資料:{restaurant_detail}
|
| 166 |
|
| 167 |
+
請完成任務:
|
| 168 |
+
【回應內容】:用繁體中文寫一段溫暖有趣的回覆。
|
| 169 |
- 結合「日記」與「前測人設」給予回應。
|
| 170 |
- 推薦上述餐廳,說明為什麼這家店適合他。
|
| 171 |
+
- 不需要提供圖片 Prompt,直接回覆內容即可。
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
"""
|
| 173 |
try:
|
| 174 |
response = client.chat.completions.create(
|
| 175 |
+
model="llama-3.3-70b-versatile",
|
| 176 |
+
messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_msg}]
|
| 177 |
)
|
| 178 |
content = response.choices[0].message.content
|
| 179 |
+
return content
|
|
|
|
|
|
|
|
|
|
| 180 |
except Exception as e:
|
| 181 |
+
return f"Groq Error: {str(e)}"
|
| 182 |
|
| 183 |
def generate_image_huggingface(prompt):
|
| 184 |
if not HF_TOKEN: return None
|
| 185 |
try:
|
| 186 |
hf_client = InferenceClient(token=HF_TOKEN)
|
| 187 |
+
# 您可以使用原本的模型,或嘗試其他模型
|
| 188 |
return hf_client.text_to_image(prompt=prompt, model="stabilityai/stable-diffusion-xl-base-1.0")
|
| 189 |
except: return None
|
| 190 |
|
| 191 |
+
# --- 主邏輯 Agent (已修改圖片 Prompt 來源) ---
|
| 192 |
def mood_agent_logic(score_input, food_input, diary_input, quiz_state):
|
| 193 |
restaurant, is_random = get_restaurant_data(score_input, food_input)
|
| 194 |
if restaurant is None:
|
|
|
|
| 200 |
url = restaurant['URL']
|
| 201 |
note = "(隨機推薦)" if is_random else ""
|
| 202 |
|
| 203 |
+
# 1. 處理 RAG 內容
|
| 204 |
rag_info = str(restaurant['RAG_Content'])
|
| 205 |
if retriever:
|
| 206 |
docs = retriever.invoke(name)
|
| 207 |
if docs: rag_info = "\n".join([d.page_content for d in docs])
|
| 208 |
|
| 209 |
+
# 2. 呼叫 LLM 產生文字回應 (不再產生 Prompt)
|
| 210 |
+
ai_text = generate_content_with_groq(name, rag_info, diary_input, score_input, quiz_state)
|
| 211 |
|
| 212 |
+
final_response = f"### 🍽️ 推薦:{name} {note}\n\n{ai_text}"
|
| 213 |
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>'
|
| 214 |
|
| 215 |
+
# 3. 先回傳文字與地圖
|
| 216 |
yield final_response, None, map_html
|
| 217 |
+
|
| 218 |
+
# 4. 查找 CSV 獲取 Prompt 並生成圖片 [修改重點]
|
| 219 |
+
img_prompt = f"Delicious food from {name}, cinematic lighting, 8k" # 預設值
|
| 220 |
+
|
| 221 |
+
if not df_prompts.empty and name in df_prompts.index:
|
| 222 |
+
try:
|
| 223 |
+
# 假設 CSV 中存 Prompt 的欄位叫 'Image_Prompt',如果不一樣請修改這裡
|
| 224 |
+
csv_prompt = df_prompts.loc[name, 'Image_Prompt']
|
| 225 |
+
# 如果有多筆資料 (重複名稱),取第一筆
|
| 226 |
+
if isinstance(csv_prompt, pd.Series):
|
| 227 |
+
csv_prompt = csv_prompt.iloc[0]
|
| 228 |
+
|
| 229 |
+
if pd.notna(csv_prompt) and str(csv_prompt).strip() != "":
|
| 230 |
+
img_prompt = str(csv_prompt)
|
| 231 |
+
print(f"✅ 使用 CSV Prompt ({name}): {img_prompt[:30]}...")
|
| 232 |
+
else:
|
| 233 |
+
print(f"⚠️ 餐廳 {name} 在 CSV 中,但 Prompt 空白,使用預設值")
|
| 234 |
+
except Exception as e:
|
| 235 |
+
print(f"⚠️ 讀取 Prompt 發生錯誤: {e}")
|
| 236 |
+
else:
|
| 237 |
+
print(f"ℹ️ 餐廳 {name} 不在 Prompts CSV 中,使用預設生成規則")
|
| 238 |
+
|
| 239 |
+
# 5. 生成圖片
|
| 240 |
image_output = generate_image_huggingface(img_prompt)
|
| 241 |
yield final_response, image_output, map_html
|
| 242 |
|
|
|
|
| 254 |
current_state["q2"] = q2_options_map[selected_label]
|
| 255 |
return current_state, gr.Button(interactive=True, variant="primary", value="完成測驗 (前往點餐) ➔")
|
| 256 |
|
|
|
|
| 257 |
def go_to_page_2():
|
| 258 |
return gr.update(visible=False), gr.update(visible=True)
|
| 259 |
|
|
|
|
| 269 |
gr.HTML(f"<style>{custom_css}</style>")
|
| 270 |
quiz_state = gr.State(value={})
|
| 271 |
|
| 272 |
+
# ------ Page 1: 測驗第一題 ------
|
| 273 |
with gr.Column(visible=True) as page_1_col:
|
| 274 |
gr.Markdown("### 🔮 第一題:直覺測試")
|
| 275 |
gr.Image(value=img_path_1, type="filepath", label="請觀察圖片", height=300)
|
|
|
|
| 277 |
radio_q1 = gr.Radio(choices=list(q1_options_map.keys()), label="請選擇", elem_classes="vertical-radio")
|
| 278 |
btn_q1_next = gr.Button("下一頁 ➔", interactive=False)
|
| 279 |
|
| 280 |
+
# ------ Page 2: 測驗第二題 ------
|
| 281 |
with gr.Column(visible=False) as page_2_col:
|
| 282 |
gr.Markdown("### 🔮 第二題:魔法適性")
|
| 283 |
gr.Image(value=img_path_2, type="filepath", label="請觀察圖片", height=300)
|
|
|
|
| 285 |
radio_q2 = gr.Radio(choices=list(q2_options_map.keys()), label="請選擇", elem_classes="vertical-radio")
|
| 286 |
btn_q2_finish = gr.Button("完成測驗 ➔", interactive=False)
|
| 287 |
|
| 288 |
+
# ------ Page 3: 主功能 ------
|
| 289 |
with gr.Column(visible=False) as main_app_col:
|
| 290 |
gr.Markdown(f"## 🍱 AI 心情食堂導航")
|
| 291 |
gr.Markdown("測驗結束!現在,告訴我你真正想吃什麼吧!")
|
|
|
|
| 303 |
map_output = gr.HTML(label="地圖導航")
|
| 304 |
|
| 305 |
# ------ 事件綁定 ------
|
|
|
|
|
|
|
| 306 |
radio_q1.change(fn=handle_q1_change, inputs=[radio_q1, quiz_state], outputs=[quiz_state, btn_q1_next])
|
|
|
|
|
|
|
| 307 |
btn_q1_next.click(fn=go_to_page_2, outputs=[page_1_col, page_2_col])
|
|
|
|
|
|
|
| 308 |
radio_q2.change(fn=handle_q2_change, inputs=[radio_q2, quiz_state], outputs=[quiz_state, btn_q2_finish])
|
|
|
|
|
|
|
| 309 |
btn_q2_finish.click(fn=go_to_main_app, outputs=[page_2_col, main_app_col])
|
| 310 |
|
|
|
|
| 311 |
submit_btn.click(
|
| 312 |
fn=mood_agent_logic,
|
| 313 |
inputs=[score_input, food_input, diary_input, quiz_state],
|