Spaces:
Sleeping
Sleeping
chen commited on
Update command_handler.py
Browse files123456789101112139 unmodified lines232425262728293031322 unmodified lines3536373839404112 unmodified lines54555657585960616263646566676869707172737475763 unmodified lines8081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120# command_handler.py (已簡化為僅支援數字指令)import pandas as pdfrom linebot.v3.messaging import TextMessage, ImageMessage# 匯入所有服務函式from cwa_service import fetch_cwa_alarm_list, fetch_significant_earthquakes, fetch_latest_significant_earthquakefrom usgs_service import fetch_global_last24h_text, fetch_taiwan_df_this_yearfrom plotting_service import create_and_save_mapfrom ai_service import generate_ai_text# (pws_service 的匯入已被移除)from config import CURRENT_YEAR, MCP_SERVER_URLdef get_help_message() -> TextMessage:9 unmodified lines"• 6 - CWA 最近7天顯著有感地震\n\n""【AI 與工具】\n""• 7 <問題> - 與 AI 助理對話\n"" (範例: 7 昨天台北有地震嗎?)\n\n""【基本指令】\n""• 8 - 關於此機器人\n""• 9 - 顯示此說明")return TextMessage(text=text)2 unmodified linestext = ("🤖 關於我\n\n""我是一個多功能助理機器人,提供地震查詢與 AI 對話功能。\n\n""• 版本: 5.1 (Gemini Simplified Edition)\n""• 資料來源: CWA, USGS, Google Gemini\n""• 開發者: dayichen")12 unmodified linesf"地點: {row['place']}\n"f"報告連結: {row.get('url', '無')}")if count > 15:lines.append(f"... (還有 {count-15} 筆資料)")reply_text = "\n\n".join(lines)else:reply_text = resultreturn TextMessage(text=reply_text)def get_latest_earthquake_reply() -> list:"""取得 CWA 最新一筆地震,並組合文字與圖片訊息。"""try:latest_eq = fetch_latest_significant_earthquake()if not latest_eq:return [TextMessage(text="✅ 近期無顯著有感地震報告。")]mag_str = f"{latest_eq['Magnitude']:.1f}" if latest_eq.get('Magnitude') is not None else "—"depth_str = f"{latest_eq['Depth']:.0f}" if latest_eq.get('Depth') is not None else "—"text_message_content = (f"🚨 CWA 最新顯著有感地震\n"f"----------------------------------\n"3 unmodified linesf"報告: {latest_eq.get('URL', '無')}")reply_messages = [TextMessage(text=text_message_content)]if latest_eq.get("ImageURL"):image_url = latest_eq["ImageURL"]reply_messages.append(ImageMessage(original_content_url=image_url, preview_image_url=image_url))return reply_messagesexcept Exception as e:return [TextMessage(text=f"❌ 查詢最新地震失敗:{e}")]def process_message(user_message_raw: str, request_base_url: str) -> list:"""處理使用者輸入的主函式。僅解析數字指令,若非指令則交由 AI 處理。"""user_message = (user_message_raw or "").strip()parts = user_message.split(' ', 1)command_key = parts[0]arg = parts[1].strip() if len(parts) > 1 else ""# 根據數字指令執行對應的動作if command_key == '1': return get_latest_earthquake_reply()if command_key == '2': return [TextMessage(text=fetch_global_last24h_text())]if command_key == '3': return [get_taiwan_earthquake_list()]if command_key == '4': return [TextMessage(text=f"🗺️ 外部地震查詢服務\n\n請點擊以下連結:\n{MCP_SERVER_URL}")]if command_key == '5': return [TextMessage(text=fetch_cwa_alarm_list(limit=5))]if command_key == '6': return [TextMessage(text=fetch_significant_earthquakes(limit=5))]if command_key == '7':prompt = argif not prompt: return [TextMessage(text="請輸入問題,例如:7 台灣最高的山是哪座?")]return [TextMessage(text=generate_ai_text(prompt))]if command_key == '8': return [get_info_message()]if command_key == '9': return [get_help_message()]# 如果輸入的不是 1-9 的指令,則將完整訊息交由 AI 處理return [TextMessage(text=generate_ai_text(user_message))]1234567891011129 unmodified lines22232425262728292 unmodified lines3233343536373812 unmodified lines5152535455565758596061626364656667683 unmodified lines72737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126# command_handler.py (Added keyword pre-processing for AI queries)import pandas as pdimport refrom linebot.v3.messaging import TextMessage, ImageMessage# 匯入所有服務函式from cwa_service import fetch_cwa_alarm_list, fetch_significant_earthquakes, fetch_latest_significant_earthquakefrom usgs_service import fetch_global_last24h_text, fetch_taiwan_df_this_yearfrom ai_service import generate_ai_textfrom config import CURRENT_YEAR, MCP_SERVER_URLdef get_help_message() -> TextMessage:9 unmodified lines"• 6 - CWA 最近7天顯著有感地震\n\n""【AI 與工具】\n""• 7 <問題> - 與 AI 助理對話\n"" (範例: 7 昨天花蓮有地震嗎?)\n"" (範例: 7 2023年臺灣最大地震)")return TextMessage(text=text)2 unmodified linestext = ("🤖 關於我\n\n""我是一個多功能助理機器人,提供地震查詢與 AI 對話功能。\n\n""• 版本: 5.2 (Gemini Advanced Edition)\n""• 資料來源: CWA, USGS, Google Gemini\n""• 開發者: dayichen")12 unmodified linesf"地點: {row['place']}\n"f"報告連結: {row.get('url', '無')}")if count > 15: lines.append(f"... (還有 {count-15} 筆資料)")reply_text = "\n\n".join(lines)else: reply_text = resultreturn TextMessage(text=reply_text)def get_latest_earthquake_reply() -> list:"""取得 CWA 最新一筆地震,並組合文字與圖片訊息。"""try:latest_eq = fetch_latest_significant_earthquake()if not latest_eq: return [TextMessage(text="✅ 近期無顯著有感地震報告。")]mag_str = f"{latest_eq['Magnitude']:.1f}" if latest_eq.get('Magnitude') is not None else "—"depth_str = f"{latest_eq['Depth']:.0f}" if latest_eq.get('Depth') is not None else "—"text_message_content = (f"🚨 CWA 最新顯著有感地震\n"f"----------------------------------\n"3 unmodified linesf"報告: {latest_eq.get('URL', '無')}")reply_messages = [TextMessage(text=text_message_content)]if latest_eq.get("ImageURL"):image_url = latest_eq["ImageURL"]reply_messages.append(ImageMessage(original_content_url=image_url, preview_image_url=image_url))return reply_messagesexcept Exception as e: return [TextMessage(text=f"❌ 查詢最新地震失敗:{e}")]def preprocess_ai_prompt(prompt: str) -> str:"""[新增] 預處理使用者發給 AI 的問題。如果偵測到特定關鍵字組合,就將問題改寫為更明確的指令。"""# 尋找 "YYYY年" 的格式year_match = re.search(r"(\d{4})年", prompt)# 如果同時找到年份和 "最大地震"if year_match and "最大地震" in prompt:year = year_match.group(1)# 改寫成一個非常明確的指令new_prompt = f"請幫我呼叫地震搜尋工具,找出{year}年1月1日至{year}年12月31日之間,規模最大的地震。"print(f"--- AI Prompt Rewritten ---\nOriginal: {prompt}\nNew: {new_prompt}\n---------------------------")return new_prompt# 如果沒有匹配,回傳原始問題return promptdef process_message(user_message_raw: str, request_base_url: str) -> list:"""處理使用者輸入的主函式。"""user_message = (user_message_raw or "").strip()parts = user_message.split(' ', 1)command_key = parts[0]arg = parts[1].strip() if len(parts) > 1 else ""if command_key == '1': return get_latest_earthquake_reply()if command_key == '2': return [TextMessage(text=fetch_global_last24h_text())]if command_key == '3': return [get_taiwan_earthquake_list()]if command_key == '4': return [TextMessage(text=f"🗺️ 外部地震查詢服務\n\n請點擊以下連結:\n{MCP_SERVER_URL}")]if command_key == '5': return [TextMessage(text=fetch_cwa_alarm_list(limit=5))]if command_key == '6': return [TextMessage(text=fetch_significant_earthquakes(limit=5))]if command_key == '8': return [get_info_message()]if command_key == '9': return [get_help_message()]# [核心修改]# 如果是 AI 指令 (7) 或其他無法識別的指令,先經過預處理final_prompt = user_messageif command_key == '7':if not arg: return [TextMessage(text="請輸入問題,例如:7 台灣最高的山是哪座?")]final_prompt = arg # 如果是指令7,只取後面的問題部分# 將最終要發給 AI 的問題傳入預處理函式processed_prompt = preprocess_ai_prompt(final_prompt)return [TextMessage(text=generate_ai_text(processed_prompt))]
command_handler.py+40-34