Spaces:
Sleeping
Sleeping
chen commited on
Update cwa_service.py
Browse files16 unmodified lines171819202021225 unmodified lines2829303231323320 unmodified lines54555659575859601 unmodified line6263646765666713 unmodified lines8182838788848586878892899091929398991001011021039495969798991081001011022 unmodified lines10510610710810911011111211811912011311411511611711816 unmodified lines return float(m.group()) if m else None
def _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 lines tw_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"震級/深度: 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: """解析 E-A0015-001 的 JSON 資料""" quakes = obj.get("records", {}).get("Earthquake", []) rows = [] for q in quakes:13 unmodified lines df = 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) if pd.api.types.is_datetime64_any_dtype(time_series): df["Time"] = time_series.dt.tz_localize("UTC").dt.tz_convert(TAIPEI_TZ) return df
def 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, } 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 lines lines = [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')}\n" f"地點: {row['Location']}\n" f"震級: M{row['Magnitude']:.1f} | 深度: {row['Depth']:.0f} km\n" 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