Spaces:
Sleeping
Sleeping
chen commited on
Update cwa_service.py
Browse files16 unmodified lines171819202122235 unmodified lines2930313233343520 unmodified lines565758596061621 unmodified line6465666768697013 unmodified lines848586878889909192939495969798991001011021031041051061071081091101112 unmodified lines11411511611711811912012112212316 unmodified linesreturn float(m.group()) if m else Nonedef _parse_cwa_time(s: str) -> tuple[str, str]:"""回傳 (台灣時間, UTC);若字串無時區,預設視為台灣時間。"""if not s: return ("未知", "未知")try:dt = datetime.fromisoformat(s.replace("Z", "+00:00"))5 unmodified lines# --- 地震預警 (CWA_ALARM_API) ---def fetch_cwa_alarm_list(limit: int = 5) -> str:"""抓 CWA 地震預警並格式化輸出。"""try:r = requests.get(CWA_ALARM_API, timeout=10)r.raise_for_status()20 unmodified linestw_str, utc_str = _parse_cwa_time(it.get("originTime", ""))lines.append(f"事件: {it.get('identifier', '—')} | 類型: {it.get('msgType', '—')}#{it.get('msgNo', '—')}\n"f"震級/深度: M{mag:.1f} / {depth:.0f} km\n"f"時間: {tw_str}(台灣)\n"f"預警地區: {it.get('alertAreas') or '—'}")1 unmodified line# --- 顯著有感地震 (E-A0015-001) ---def _parse_significant_earthquakes(obj: dict) -> pd.DataFrame:"""解析 E-A0015-001 的 JSON 資料"""quakes = obj.get("records", {}).get("Earthquake", [])rows = []for q in quakes:13 unmodified linesdf = pd.DataFrame(rows)if not df.empty and "Time" in df.columns:time_series = pd.to_datetime(df["Time"], errors="coerce")# [修正] 先用 tz_localize('UTC') 賦予 UTC 時區,再用 tz_convert 轉換為台北時區df["Time"] = time_series.dt.tz_localize("UTC").dt.tz_convert(TAIPEI_TZ)return dfdef fetch_significant_earthquakes(days: int = 7, limit: int = 5) -> str:"""從 CWA 獲取最新的顯著有感地震"""if not CWA_API_KEY:return "❌ 顯著地震查詢失敗:管理者尚未設定 CWA_API_KEY。"now = datetime.now(timezone.utc)time_from = (now - timedelta(days=days)).strftime("%Y-%m-%d")params = {"Authorization": CWA_API_KEY,"format": "JSON","timeFrom": time_from,}try:r = requests.get(CWA_SIGNIFICANT_API, params=params, timeout=15)r.raise_for_status()data = r.json()df = _parse_significant_earthquakes(data)if df.empty:return f"✅ 過去 {days} 天內沒有顯著有感地震報告。"2 unmodified lineslines = [f"🚨 CWA 最新顯著有感地震 (近{days}天內):", "-" * 20]for _, row in df.iterrows():lines.append(f"時間: {row['Time'].strftime('%Y-%m-%d %H:%M')}\n"f"地點: {row['Location']}\n"f"震級: M{row['Magnitude']:.1f} | 深度: {row['Depth']:.0f} km\n"f"報告: {row['URL'] or '無'}")return "\n\n".join(lines)16 unmodified lines1718192021225 unmodified lines28293031323320 unmodified lines545556575859601 unmodified line62636465666713 unmodified lines818283848586878889909192939495969798991001011022 unmodified lines10510610710810911011111211311411511611711816 unmodified linesreturn float(m.group()) if m else Nonedef _parse_cwa_time(s: str) -> tuple[str, str]:if not s: return ("未知", "未知")try:dt = datetime.fromisoformat(s.replace("Z", "+00:00"))5 unmodified lines# --- 地震預警 (CWA_ALARM_API) ---def fetch_cwa_alarm_list(limit: int = 5) -> str:try:r = requests.get(CWA_ALARM_API, timeout=10)r.raise_for_status()20 unmodified linestw_str, utc_str = _parse_cwa_time(it.get("originTime", ""))lines.append(f"事件: {it.get('identifier', '—')} | 類型: {it.get('msgType', '—')}#{it.get('msgNo', '—')}\n"f"震級/深度: M{mag:.1f if mag is not None else '—'} / {depth:.0f if depth is not None else '—'} km\n"f"時間: {tw_str}(台灣)\n"f"預警地區: {it.get('alertAreas') or '—'}")1 unmodified line# --- 顯著有感地震 (E-A0015-001) ---def _parse_significant_earthquakes(obj: dict) -> pd.DataFrame:quakes = obj.get("records", {}).get("Earthquake", [])rows = []for q in quakes:13 unmodified linesdf = pd.DataFrame(rows)if not df.empty and "Time" in df.columns:time_series = pd.to_datetime(df["Time"], errors="coerce")if pd.api.types.is_datetime64_any_dtype(time_series):df["Time"] = time_series.dt.tz_localize("UTC").dt.tz_convert(TAIPEI_TZ)return dfdef fetch_significant_earthquakes(days: int = 7, limit: int = 5) -> str:if not CWA_API_KEY:return "❌ 顯著地震查詢失敗:管理者尚未設定 CWA_API_KEY。"now = datetime.now(timezone.utc)time_from = (now - timedelta(days=days)).strftime("%Y-%m-%d")params = {"Authorization": CWA_API_KEY, "format": "JSON", "timeFrom": time_from}try:r = requests.get(CWA_SIGNIFICANT_API, params=params, timeout=15)r.raise_for_status()data = r.json()df = _parse_significant_earthquakes(data)if df.empty:return f"✅ 過去 {days} 天內沒有顯著有感地震報告。"2 unmodified lineslines = [f"🚨 CWA 最新顯著有感地震 (近{days}天內):", "-" * 20]for _, row in df.iterrows():# [修正] 在格式化前,先檢查值是否存在mag_str = f"{row['Magnitude']:.1f}" if pd.notna(row['Magnitude']) else "—"depth_str = f"{row['Depth']:.0f}" if pd.notna(row['Depth']) else "—"lines.append(f"時間: {row['Time'].strftime('%Y-%m-%d %H:%M') if pd.notna(row['Time']) else '—'}\n"f"地點: {row['Location'] or '—'}\n"f"震級: M{mag_str} | 深度: {depth_str} km\n"f"報告: {row['URL'] or '無'}")return "\n\n".join(lines)
cwa_service.py+12-17