Spaces:
Sleeping
Sleeping
chen commited on
Update command_handler.py
Browse files1234563 unmodified lines1011121314151617181913 unmodified lines333435363738395 unmodified lines4546474849505152535455565758596061626364656667686970717273747576777879808182838485868788892 unmodified lines92939495969798991001011021031041051061071081091101111121131141151161173 unmodified lines121122123124125126127128129130131132133134# command_handler.py (Help message now includes English translations)import pandas as pdimport refrom linebot.v3.messaging import TextMessage, ImageMessage# 匯入所有服務函式3 unmodified linesfrom config import CURRENT_YEAR, MCP_SERVER_URLdef get_help_message() -> TextMessage:"""[核心修改]產生並回傳包含所有指令的說明文字,並附上英文翻譯。"""text = ("📖 指令列表 (Command List)\n"" (請直接輸入數字 / Please enter a number)\n\n"13 unmodified lines"【AI 與工具 (AI & Tools)】\n""• 7 <問題> - 與 AI 助理對話\n"" (Chat with AI Assistant)\n"" (e.g., 7 2023年臺灣最大地震)\n\n""【基本指令 (Basic Commands)】\n""• 8 - 關於此機器人 (About this Bot)\n""• 9 - 顯示此說明 (Show this Help Message)"5 unmodified linestext = ("🤖 關於我\n\n""我是一個多功能助理機器人,提供地震查詢與 AI 對話功能。\n\n""• 版本: 5.3 (Gemini Command-Only Edition)\n""• 資料來源: CWA, USGS, Google Gemini\n""• 開發者: dayichen")return TextMessage(text=text)def get_taiwan_earthquake_list() -> TextMessage:"""從 USGS 取得今年台灣的地震列表並格式化回覆。"""result = fetch_taiwan_df_this_year()if isinstance(result, pd.DataFrame):count = len(result)lines = [f"🇹🇼 今年 ({CURRENT_YEAR} 年) 台灣區域顯著地震 (M≥5.0),共 {count} 筆:", "-" * 20]for _, row in result.head(15).iterrows():t = row["time_utc"].strftime("%Y-%m-%d %H:%M")lines.append(f"規模: {row['magnitude']:.1f} | 日期時間: {t} (UTC)\n"f"地點: {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"f"時間: {latest_eq.get('TimeStr', '—')}\n"f"地點: {latest_eq.get('Location', '—')}\n"f"規模: M{mag_str} | 深度: {depth_str} km\n"f"報告: {latest_eq.get('URL', '無')}")reply_messages = [TextMessage(text=text_message_content)]if latest_eq.get("ImageURL"):image_url = latest_eq["ImageURL"]2 unmodified linesexcept Exception as e: return [TextMessage(text=f"❌ 查詢最新地震失敗:{e}")]def preprocess_ai_prompt(prompt: str) -> str:"""預處理使用者發給 AI 的問題。"""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_promptreturn promptdef process_message(user_message_raw: str, request_base_url: str) -> list:"""處理使用者輸入的主函式。"""user_message = (user_message_raw or "").strip()if not user_message:return [] # 如果是空訊息,不回應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()]3 unmodified linesif command_key == '8': return [get_info_message()]if command_key == '9': return [get_help_message()]# 只有當指令是 '7' 時,才啟用 AIif command_key == '7':if not arg:return [TextMessage(text="請輸入問題,例如:7 台灣最高的山是哪座?")]# 將問題進行預處理,然後交給 AIprocessed_prompt = preprocess_ai_prompt(arg)return [TextMessage(text=generate_ai_text(processed_prompt))]# 對於所有其他無法識別的訊息 (一般對話),回傳說明指令return [get_help_message()]12345673 unmodified lines1112131415161713 unmodified lines313233343536375 unmodified lines43444546474849505152535455565758596061626364656667686970717273742 unmodified lines77787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311323 unmodified lines136137138139140141142143144# command_handler.py (Improved date keyword pre-processing for AI queries)import pandas as pdimport refrom datetime import datetime, timedeltafrom linebot.v3.messaging import TextMessage, ImageMessage# 匯入所有服務函式3 unmodified linesfrom config import CURRENT_YEAR, MCP_SERVER_URLdef get_help_message() -> TextMessage:"""產生並回傳包含所有指令的說明文字,並附上英文翻譯。"""text = ("📖 指令列表 (Command List)\n"" (請直接輸入數字 / Please enter a number)\n\n"13 unmodified lines"【AI 與工具 (AI & Tools)】\n""• 7 <問題> - 與 AI 助理對話\n"" (Chat with AI Assistant)\n"" (e.g., 7 顯示pws, 7 2024年最大的地震)\n\n""【基本指令 (Basic Commands)】\n""• 8 - 關於此機器人 (About this Bot)\n""• 9 - 顯示此說明 (Show this Help Message)"5 unmodified linestext = ("🤖 關於我\n\n""我是一個多功能助理機器人,提供地震查詢與 AI 對話功能。\n\n""• 版本: 5.4 (Gemini Pre-processor Edition)\n""• 資料來源: CWA, USGS, Google Gemini\n""• 開發者: dayichen")return TextMessage(text=text)def get_taiwan_earthquake_list() -> TextMessage:result = fetch_taiwan_df_this_year()if isinstance(result, pd.DataFrame):count = len(result)lines = [f"🇹🇼 今年 ({CURRENT_YEAR} 年) 台灣區域顯著地震 (M≥5.0),共 {count} 筆:", "-" * 20]for _, row in result.head(15).iterrows():t = row["time_utc"].strftime("%Y-%m-%d %H:%M")lines.append(f"規模: {row['magnitude']:.1f} | 日期時間: {t} (UTC)\n地點: {row['place']}\n報告連結: {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: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----------------------------------\n時間: {latest_eq.get('TimeStr', '—')}\n地點: {latest_eq.get('Location', '—')}\n規模: M{mag_str} | 深度: {depth_str} km\n報告: {latest_eq.get('URL', '無')}")reply_messages = [TextMessage(text=text_message_content)]if latest_eq.get("ImageURL"):image_url = latest_eq["ImageURL"]2 unmodified linesexcept Exception as e: return [TextMessage(text=f"❌ 查詢最新地震失敗:{e}")]def preprocess_ai_prompt(prompt: str) -> str:"""[核心修正]強化預處理:偵測多種時間關鍵字,並將問題改寫為更明確的指令。"""today = datetime.now()year_match = re.search(r"(\d{4})年", prompt)# 建立時間關鍵字與對應日期的字典time_keywords = {"昨天": (today - timedelta(days=1)).strftime("%Y-%m-%d"),"今天": today.strftime("%Y-%m-%d"),"今年": str(today.year),"去年": str(today.year - 1),}# 如果找到 "YYYY年" 的格式,也加入字典if year_match:time_keywords[year_match.group(0)] = year_match.group(1)# 如果訊息中包含 "地震"if "地震" in prompt:for keyword, date_val in time_keywords.items():if keyword in prompt:# 判斷是查詢特定一天還是一整年if len(date_val) == 10: # YYYY-MM-DD 格式start_date = end_date = date_valdate_range_str = date_valelse: # YYYY 格式start_date = f"{date_val}-01-01"end_date = f"{date_val}-12-31"date_range_str = f"{date_val}年"# 根據是否包含"最大"來決定指令內容if "最大" in prompt:new_prompt = f"請幫我呼叫地震搜尋工具,找出從 {start_date} 到 {end_date} 之間,規模最大的地震是哪一個。"else:new_prompt = f"請幫我呼叫地震搜尋工具,查詢從 {start_date} 到 {end_date} 之間發生的所有地震。"print(f"--- AI Prompt Rewritten ---\nOriginal: {prompt}\nNew: {new_prompt}\n---------------------------")return new_promptreturn prompt # 如果沒有匹配,回傳原始問題def process_message(user_message_raw: str, request_base_url: str) -> list:user_message = (user_message_raw or "").strip()if not user_message: return []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()]3 unmodified linesif command_key == '8': return [get_info_message()]if command_key == '9': return [get_help_message()]if command_key == '7':if not arg: return [TextMessage(text="請輸入問題,例如:7 台灣最高的山是哪座?")]processed_prompt = preprocess_ai_prompt(arg)return [TextMessage(text=generate_ai_text(processed_prompt))]return [get_help_message()]
command_handler.py+50-40