Update app.py
Browse files
app.py
CHANGED
|
@@ -46,7 +46,7 @@ def init_rag_system():
|
|
| 46 |
rag_initialized = True
|
| 47 |
|
| 48 |
# ==========================================
|
| 49 |
-
# 2. 核心功能 (
|
| 50 |
# ==========================================
|
| 51 |
def get_restaurant_data(mood_score_str, food_choice):
|
| 52 |
init_rag_system()
|
|
@@ -73,24 +73,31 @@ def get_restaurant_data(mood_score_str, food_choice):
|
|
| 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 |
|
| 78 |
client = OpenAI(api_key=GROQ_API_KEY, base_url="https://api.groq.com/openai/v1")
|
| 79 |
|
| 80 |
system_prompt = "你是一個幽默、懂吃且善解人意的 AI 朋友..."
|
| 81 |
user_msg = f"【狀態】心情分數:{mood_score}\n【日記】{user_diary}\n【建議原因】{mood_guide_reason}\n【餐廳】{restaurant_name}\n資料:{restaurant_detail}"
|
| 82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
try:
|
| 84 |
response = client.chat.completions.create(model="llama-3.3-70b-versatile", messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_msg}])
|
| 85 |
content = response.choices[0].message.content
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
content += f"\n\n--- 🔧 DEBUG: Groq Prompt ---\n**System:** {system_prompt}\n\n**User:** {user_msg}\n-----------------------"
|
| 90 |
-
# ########################
|
| 91 |
-
|
| 92 |
-
return content
|
| 93 |
-
except Exception as e: return f"Groq Error: {str(e)}"
|
| 94 |
|
| 95 |
def generate_image_huggingface(prompt):
|
| 96 |
if not HF_TOKEN: return None
|
|
@@ -101,26 +108,40 @@ def generate_image_huggingface(prompt):
|
|
| 101 |
|
| 102 |
def mood_agent_logic(score_input, food_input, diary_input, debug_mode):
|
| 103 |
restaurant, is_random, rec_categories, mood_reason = get_restaurant_data(score_input, food_input)
|
| 104 |
-
if restaurant is None: yield "資料庫讀取錯誤", None, ""; return
|
|
|
|
| 105 |
name = restaurant['Name']; address = restaurant['Address']; url = restaurant['URL']; img_prompt = restaurant.get('Visual_prompt')
|
|
|
|
| 106 |
rag_info = str(restaurant.get('RAG_Content', ''))
|
| 107 |
if global_retriever:
|
| 108 |
docs = global_retriever.invoke(name)
|
| 109 |
if docs: rag_info = "\n".join([d.page_content for d in docs])
|
| 110 |
|
| 111 |
-
|
|
|
|
| 112 |
|
| 113 |
-
#
|
|
|
|
| 114 |
if debug_mode:
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
final_response = f"### 🍽️ 推薦:{name}\n\n{ai_text}"
|
| 119 |
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>'
|
| 120 |
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
| 122 |
image_output = generate_image_huggingface(img_prompt)
|
| 123 |
-
yield final_response, image_output, map_html
|
| 124 |
|
| 125 |
|
| 126 |
# ==========================================
|
|
@@ -133,21 +154,17 @@ def _score_to_radio_value(score):
|
|
| 133 |
except: score = 3
|
| 134 |
return mapping.get(score, "3 (普通)")
|
| 135 |
|
| 136 |
-
# 橋接 1:開始
|
| 137 |
def bridge_start_click(st):
|
| 138 |
res = emotion.on_restart(st)
|
| 139 |
return res[1], res[0], gr.update(visible=True), res[5], res[4]
|
| 140 |
|
| 141 |
-
# 橋接 2:停止
|
| 142 |
def bridge_stop_click(st):
|
| 143 |
res = emotion.on_stop(st)
|
| 144 |
return res[1], res[0], gr.update(visible=False), res[5], res[4]
|
| 145 |
|
| 146 |
-
# 橋接 3:Webcam 串流
|
| 147 |
def bridge_predict_frame(frame, st):
|
| 148 |
res = emotion.on_stream(frame, st)
|
| 149 |
out_cam = res[0]; out_result = res[1]; out_st = res[4]; out_btn_start = res[5]
|
| 150 |
-
|
| 151 |
score_update = gr.update(); tabs_update = gr.update(); out_btn_stop = gr.update()
|
| 152 |
|
| 153 |
if out_st.finished and hasattr(out_st, 'final_score'):
|
|
@@ -197,7 +214,12 @@ with gr.Blocks(title="AI 心情食堂", css=combined_css) as demo:
|
|
| 197 |
food_input = gr.Radio(["吃飯", "吃麵", "隨便"], label="2. 想吃什麼", value="隨便")
|
| 198 |
diary_input = gr.Textbox(lines=4, label="3. 心情日記", placeholder="寫下今天發生的事...")
|
| 199 |
debug_mode_btn = gr.Checkbox(label="🔧 開啟除錯模式", value=False)
|
|
|
|
| 200 |
submit_btn = gr.Button("🍱 送出給 Agent", variant="primary")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
with gr.Column(scale=1):
|
| 203 |
agent_output = gr.Markdown(label="AI 回應")
|
|
@@ -232,7 +254,7 @@ with gr.Blocks(title="AI 心情食堂", css=combined_css) as demo:
|
|
| 232 |
submit_btn.click(
|
| 233 |
fn=mood_agent_logic,
|
| 234 |
inputs=[score_input, food_input, diary_input, debug_mode_btn],
|
| 235 |
-
outputs=[agent_output, image_output, map_output]
|
| 236 |
)
|
| 237 |
|
| 238 |
if __name__ == "__main__":
|
|
|
|
| 46 |
rag_initialized = True
|
| 47 |
|
| 48 |
# ==========================================
|
| 49 |
+
# 2. 核心功能 (修改:回傳分開的除錯資訊)
|
| 50 |
# ==========================================
|
| 51 |
def get_restaurant_data(mood_score_str, food_choice):
|
| 52 |
init_rag_system()
|
|
|
|
| 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 |
|
| 78 |
client = OpenAI(api_key=GROQ_API_KEY, base_url="https://api.groq.com/openai/v1")
|
| 79 |
|
| 80 |
system_prompt = "你是一個幽默、懂吃且善解人意的 AI 朋友..."
|
| 81 |
user_msg = f"【狀態】心情分數:{mood_score}\n【日記】{user_diary}\n【建議原因】{mood_guide_reason}\n【餐廳】{restaurant_name}\n資料:{restaurant_detail}"
|
| 82 |
|
| 83 |
+
# 準備除錯資訊
|
| 84 |
+
debug_log = ""
|
| 85 |
+
if debug_mode:
|
| 86 |
+
debug_log = f"""
|
| 87 |
+
### 🔧 Groq Prompt Debug
|
| 88 |
+
**System Prompt:**
|
| 89 |
+
{system_prompt}
|
| 90 |
+
|
| 91 |
+
**User Message:**
|
| 92 |
+
{user_msg}
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
try:
|
| 96 |
response = client.chat.completions.create(model="llama-3.3-70b-versatile", messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_msg}])
|
| 97 |
content = response.choices[0].message.content
|
| 98 |
+
return content, debug_log # 回傳 (內容, 除錯資訊)
|
| 99 |
+
except Exception as e:
|
| 100 |
+
return f"Groq Error: {str(e)}", debug_log
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
def generate_image_huggingface(prompt):
|
| 103 |
if not HF_TOKEN: return None
|
|
|
|
| 108 |
|
| 109 |
def mood_agent_logic(score_input, food_input, diary_input, debug_mode):
|
| 110 |
restaurant, is_random, rec_categories, mood_reason = get_restaurant_data(score_input, food_input)
|
| 111 |
+
if restaurant is None: yield "資料庫讀取錯誤", None, "", gr.update(); return
|
| 112 |
+
|
| 113 |
name = restaurant['Name']; address = restaurant['Address']; url = restaurant['URL']; img_prompt = restaurant.get('Visual_prompt')
|
| 114 |
+
|
| 115 |
rag_info = str(restaurant.get('RAG_Content', ''))
|
| 116 |
if global_retriever:
|
| 117 |
docs = global_retriever.invoke(name)
|
| 118 |
if docs: rag_info = "\n".join([d.page_content for d in docs])
|
| 119 |
|
| 120 |
+
# 呼叫 Groq 生成內容與取得除錯資訊
|
| 121 |
+
ai_text, groq_debug_log = generate_content_with_groq(name, rag_info, diary_input, score_input, mood_reason, debug_mode)
|
| 122 |
|
| 123 |
+
# 準備完整的除錯資訊 (包含圖片 Prompt)
|
| 124 |
+
full_debug_log = ""
|
| 125 |
if debug_mode:
|
| 126 |
+
img_debug_log = f"""
|
| 127 |
+
### 🎨 Image Prompt Debug
|
| 128 |
+
**Visual Prompt:**
|
| 129 |
+
{img_prompt}
|
| 130 |
+
"""
|
| 131 |
+
full_debug_log = groq_debug_log + "\n\n" + img_debug_log
|
| 132 |
+
|
| 133 |
+
# 設定除錯視窗的狀態 (有勾選才顯示)
|
| 134 |
+
debug_output_update = gr.update(value=full_debug_log, visible=debug_mode)
|
| 135 |
|
| 136 |
final_response = f"### 🍽️ 推薦:{name}\n\n{ai_text}"
|
| 137 |
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>'
|
| 138 |
|
| 139 |
+
# 先回傳文字與除錯資訊
|
| 140 |
+
yield final_response, None, map_html, debug_output_update
|
| 141 |
+
|
| 142 |
+
# 再回傳圖片
|
| 143 |
image_output = generate_image_huggingface(img_prompt)
|
| 144 |
+
yield final_response, image_output, map_html, debug_output_update
|
| 145 |
|
| 146 |
|
| 147 |
# ==========================================
|
|
|
|
| 154 |
except: score = 3
|
| 155 |
return mapping.get(score, "3 (普通)")
|
| 156 |
|
|
|
|
| 157 |
def bridge_start_click(st):
|
| 158 |
res = emotion.on_restart(st)
|
| 159 |
return res[1], res[0], gr.update(visible=True), res[5], res[4]
|
| 160 |
|
|
|
|
| 161 |
def bridge_stop_click(st):
|
| 162 |
res = emotion.on_stop(st)
|
| 163 |
return res[1], res[0], gr.update(visible=False), res[5], res[4]
|
| 164 |
|
|
|
|
| 165 |
def bridge_predict_frame(frame, st):
|
| 166 |
res = emotion.on_stream(frame, st)
|
| 167 |
out_cam = res[0]; out_result = res[1]; out_st = res[4]; out_btn_start = res[5]
|
|
|
|
| 168 |
score_update = gr.update(); tabs_update = gr.update(); out_btn_stop = gr.update()
|
| 169 |
|
| 170 |
if out_st.finished and hasattr(out_st, 'final_score'):
|
|
|
|
| 214 |
food_input = gr.Radio(["吃飯", "吃麵", "隨便"], label="2. 想吃什麼", value="隨便")
|
| 215 |
diary_input = gr.Textbox(lines=4, label="3. 心情日記", placeholder="寫下今天發生的事...")
|
| 216 |
debug_mode_btn = gr.Checkbox(label="🔧 開啟除錯模式", value=False)
|
| 217 |
+
|
| 218 |
submit_btn = gr.Button("🍱 送出給 Agent", variant="primary")
|
| 219 |
+
|
| 220 |
+
# --- [新增] 除錯資訊顯示區 (位於按鈕下方) ---
|
| 221 |
+
debug_output = gr.Markdown(label="除錯資訊 (Debug Log)", visible=False)
|
| 222 |
+
# ----------------------------------------
|
| 223 |
|
| 224 |
with gr.Column(scale=1):
|
| 225 |
agent_output = gr.Markdown(label="AI 回應")
|
|
|
|
| 254 |
submit_btn.click(
|
| 255 |
fn=mood_agent_logic,
|
| 256 |
inputs=[score_input, food_input, diary_input, debug_mode_btn],
|
| 257 |
+
outputs=[agent_output, image_output, map_output, debug_output] # 加入 debug_output
|
| 258 |
)
|
| 259 |
|
| 260 |
if __name__ == "__main__":
|