Spaces:
Sleeping
Sleeping
Update cwa_service.py
Browse files- cwa_service.py +98 -10
cwa_service.py
CHANGED
|
@@ -5,11 +5,11 @@ import requests
|
|
| 5 |
import re
|
| 6 |
import pandas as pd
|
| 7 |
from datetime import datetime, timedelta, timezone
|
| 8 |
-
from config import CWA_API_KEY, CWA_ALARM_API, CWA_SIGNIFICANT_API
|
| 9 |
|
| 10 |
TAIPEI_TZ = timezone(timedelta(hours=8))
|
| 11 |
|
| 12 |
-
# --- Helper Functions
|
| 13 |
def _to_float(x):
|
| 14 |
if x is None: return None
|
| 15 |
s = str(x).strip()
|
|
@@ -26,9 +26,56 @@ def _parse_cwa_time(s: str) -> tuple[str, str]:
|
|
| 26 |
except Exception:
|
| 27 |
return (s, "未知")
|
| 28 |
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
def fetch_cwa_alarm_list(limit: int = 5) -> str:
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
return "\n\n".join(lines).strip()
|
| 33 |
|
| 34 |
# --- 顯著有感地震 (E-A0015-001) ---
|
|
@@ -61,7 +108,6 @@ def _parse_significant_earthquakes(obj: dict) -> pd.DataFrame:
|
|
| 61 |
return df
|
| 62 |
|
| 63 |
def fetch_significant_earthquakes(days: int = 7, limit: int = 5) -> str:
|
| 64 |
-
# ... (此函式內容不變) ...
|
| 65 |
if not CWA_API_KEY: return "❌ 顯著地震查詢失敗:管理者尚未設定 CWA_API_KEY。"
|
| 66 |
now = datetime.now(timezone.utc)
|
| 67 |
time_from = (now - timedelta(days=days)).strftime("%Y-%m-%d")
|
|
@@ -90,7 +136,7 @@ def fetch_significant_earthquakes(days: int = 7, limit: int = 5) -> str:
|
|
| 90 |
|
| 91 |
# --- 最新一筆顯著地震 ---
|
| 92 |
def fetch_latest_significant_earthquake() -> dict | None:
|
| 93 |
-
"""
|
| 94 |
if not CWA_API_KEY:
|
| 95 |
raise ValueError("錯誤:尚未設定 CWA_API_KEY Secret。")
|
| 96 |
|
|
@@ -102,21 +148,63 @@ def fetch_latest_significant_earthquake() -> dict | None:
|
|
| 102 |
r.raise_for_status()
|
| 103 |
data = r.json()
|
| 104 |
|
| 105 |
-
# 直接調用最穩健的解析函式
|
| 106 |
df = _parse_significant_earthquakes(data)
|
| 107 |
if df.empty:
|
| 108 |
return None
|
| 109 |
|
| 110 |
-
# 將 DataFrame 的第一筆資料轉為字典
|
| 111 |
latest_eq_data = df.sort_values(by="Time", ascending=False).iloc[0].to_dict()
|
| 112 |
|
| 113 |
-
# 從原始資料中手動加入圖片網址 (因為解析函式沒處理這個)
|
| 114 |
quakes = data.get("records", {}).get("Earthquake", [])
|
| 115 |
if quakes:
|
| 116 |
latest_eq_data["ImageURL"] = quakes[0].get("ReportImageURI")
|
| 117 |
|
| 118 |
-
# 格式化時間字串
|
| 119 |
if pd.notna(latest_eq_data.get("Time")):
|
| 120 |
latest_eq_data["TimeStr"] = latest_eq_data["Time"].strftime('%Y-%m-%d %H:%M')
|
| 121 |
|
| 122 |
return latest_eq_data
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import re
|
| 6 |
import pandas as pd
|
| 7 |
from datetime import datetime, timedelta, timezone
|
| 8 |
+
from config import CWA_API_KEY, CWA_ALARM_API, CWA_SIGNIFICANT_API, CWA_LOCAL_EQ_API
|
| 9 |
|
| 10 |
TAIPEI_TZ = timezone(timedelta(hours=8))
|
| 11 |
|
| 12 |
+
# --- Helper Functions ---
|
| 13 |
def _to_float(x):
|
| 14 |
if x is None: return None
|
| 15 |
s = str(x).strip()
|
|
|
|
| 26 |
except Exception:
|
| 27 |
return (s, "未知")
|
| 28 |
|
| 29 |
+
def _normalize_cwa_area_name(area_name: str) -> str:
|
| 30 |
+
"""自動校正縣市名稱,以符合 CWA API 查詢需求"""
|
| 31 |
+
area_name = area_name.replace("台", "臺")
|
| 32 |
+
if area_name.endswith("市") or area_name.endswith("縣"):
|
| 33 |
+
return area_name
|
| 34 |
+
|
| 35 |
+
major_cities = "臺北,新北,基隆,桃園,新竹,臺中,嘉義,臺南,高雄".split(',')
|
| 36 |
+
if any(city in area_name for city in major_cities):
|
| 37 |
+
return f"{area_name}市"
|
| 38 |
+
else:
|
| 39 |
+
return f"{area_name}縣"
|
| 40 |
+
|
| 41 |
+
# --- 地震預警 (CWA_ALARM_API) ---
|
| 42 |
def fetch_cwa_alarm_list(limit: int = 5) -> str:
|
| 43 |
+
"""抓 CWA 地震預警並格式化輸出。"""
|
| 44 |
+
try:
|
| 45 |
+
r = requests.get(CWA_ALARM_API, timeout=10)
|
| 46 |
+
r.raise_for_status()
|
| 47 |
+
payload = r.json()
|
| 48 |
+
except Exception as e:
|
| 49 |
+
return f"❌ 地震預警查詢失敗:{e}"
|
| 50 |
+
|
| 51 |
+
items = payload.get("data", [])
|
| 52 |
+
if not items:
|
| 53 |
+
return "✅ 目前沒有地震預警。"
|
| 54 |
+
|
| 55 |
+
def _key(it):
|
| 56 |
+
try:
|
| 57 |
+
return datetime.fromisoformat(it.get("originTime", "").replace("Z", "+00:00"))
|
| 58 |
+
except:
|
| 59 |
+
return datetime.min.replace(tzinfo=timezone.utc)
|
| 60 |
+
|
| 61 |
+
items = sorted(items, key=_key, reverse=True)
|
| 62 |
+
lines = ["🚨 地震預警(最新):", "-" * 20]
|
| 63 |
+
for it in items[:limit]:
|
| 64 |
+
mag = _to_float(it.get("magnitudeValue"))
|
| 65 |
+
depth = _to_float(it.get("depth"))
|
| 66 |
+
tw_str, _ = _parse_cwa_time(it.get("originTime", ""))
|
| 67 |
+
identifier = str(it.get('identifier', '—')).replace('{', '{{').replace('}', '}}')
|
| 68 |
+
msg_type = str(it.get('msgType', '—')).replace('{', '{{').replace('}', '}}')
|
| 69 |
+
msg_no = str(it.get('msgNo', '—')).replace('{', '{{').replace('}', '}}')
|
| 70 |
+
areas = str(it.get('alertAreas') or '—').replace('{', '{{').replace('}', '}}')
|
| 71 |
+
mag_str = f"{mag:.1f}" if mag is not None else "—"
|
| 72 |
+
depth_str = f"{depth:.0f}" if depth is not None else "—"
|
| 73 |
+
lines.append(
|
| 74 |
+
f"事件: {identifier} | 類型: {msg_type}#{msg_no}\n"
|
| 75 |
+
f"規模/深度: M{mag_str} / {depth_str} km\n"
|
| 76 |
+
f"時間: {tw_str}(台灣)\n"
|
| 77 |
+
f"預警地區: {areas}"
|
| 78 |
+
)
|
| 79 |
return "\n\n".join(lines).strip()
|
| 80 |
|
| 81 |
# --- 顯著有感地震 (E-A0015-001) ---
|
|
|
|
| 108 |
return df
|
| 109 |
|
| 110 |
def fetch_significant_earthquakes(days: int = 7, limit: int = 5) -> str:
|
|
|
|
| 111 |
if not CWA_API_KEY: return "❌ 顯著地震查詢失敗:管理者尚未設定 CWA_API_KEY。"
|
| 112 |
now = datetime.now(timezone.utc)
|
| 113 |
time_from = (now - timedelta(days=days)).strftime("%Y-%m-%d")
|
|
|
|
| 136 |
|
| 137 |
# --- 最新一筆顯著地震 ---
|
| 138 |
def fetch_latest_significant_earthquake() -> dict | None:
|
| 139 |
+
"""從 CWA 獲取最新一筆顯著地震,並重用現有的解析邏輯"""
|
| 140 |
if not CWA_API_KEY:
|
| 141 |
raise ValueError("錯誤:尚未設定 CWA_API_KEY Secret。")
|
| 142 |
|
|
|
|
| 148 |
r.raise_for_status()
|
| 149 |
data = r.json()
|
| 150 |
|
|
|
|
| 151 |
df = _parse_significant_earthquakes(data)
|
| 152 |
if df.empty:
|
| 153 |
return None
|
| 154 |
|
|
|
|
| 155 |
latest_eq_data = df.sort_values(by="Time", ascending=False).iloc[0].to_dict()
|
| 156 |
|
|
|
|
| 157 |
quakes = data.get("records", {}).get("Earthquake", [])
|
| 158 |
if quakes:
|
| 159 |
latest_eq_data["ImageURL"] = quakes[0].get("ReportImageURI")
|
| 160 |
|
|
|
|
| 161 |
if pd.notna(latest_eq_data.get("Time")):
|
| 162 |
latest_eq_data["TimeStr"] = latest_eq_data["Time"].strftime('%Y-%m-%d %H:%M')
|
| 163 |
|
| 164 |
return latest_eq_data
|
| 165 |
+
|
| 166 |
+
# --- 小區域有感地震 (E-A0016-001) ---
|
| 167 |
+
def fetch_local_earthquakes(area_name: str = "", limit: int = 5) -> str:
|
| 168 |
+
"""從 CWA 獲取小區域有感地震報告。如果 area_name 為空,則查詢全台灣。"""
|
| 169 |
+
if not CWA_API_KEY: return "❌ 查詢失敗:管理者尚未設定 CWA_API_KEY。"
|
| 170 |
+
|
| 171 |
+
params = {"Authorization": CWA_API_KEY, "format": "JSON", "limit": limit}
|
| 172 |
+
title = "🇹🇼 台灣近期小區域有感地震:"
|
| 173 |
+
|
| 174 |
+
if area_name:
|
| 175 |
+
normalized_area = _normalize_cwa_area_name(area_name)
|
| 176 |
+
params["AreaName"] = normalized_area
|
| 177 |
+
title = f"🚨 「{normalized_area}」近期小區域有感地震:"
|
| 178 |
+
|
| 179 |
+
try:
|
| 180 |
+
r = requests.get(CWA_LOCAL_EQ_API, params=params, timeout=15)
|
| 181 |
+
r.raise_for_status()
|
| 182 |
+
data = r.json()
|
| 183 |
+
|
| 184 |
+
earthquakes = data.get("records", {}).get("Earthquake", [])
|
| 185 |
+
if not earthquakes:
|
| 186 |
+
msg = f"✅ 在「{area_name}」" if area_name else "✅ 台灣"
|
| 187 |
+
return f"{msg}近期沒有小區域有感地震報告。"
|
| 188 |
+
|
| 189 |
+
lines = [title, "-" * 20]
|
| 190 |
+
for eq in earthquakes:
|
| 191 |
+
info = eq.get("earthquakeInfo", {})
|
| 192 |
+
epi = info.get("epicenter", {})
|
| 193 |
+
mag = info.get("magnitude", {})
|
| 194 |
+
depth = info.get("depth", {})
|
| 195 |
+
|
| 196 |
+
intensity_areas = eq.get("intensity", {}).get("shakingArea", [])
|
| 197 |
+
area_strs = [f"{area.get('areaDesc')} {area.get('areaIntensity')}級" for area in intensity_areas if area.get("areaIntensity") and float(area.get("areaIntensity", 0)) > 0]
|
| 198 |
+
intensity_str = "、".join(area_strs) if area_strs else "無具體震度回報"
|
| 199 |
+
|
| 200 |
+
lines.append(
|
| 201 |
+
f"報告: {eq.get('reportContent', '—')}\n"
|
| 202 |
+
f"時間: {info.get('originTime', '—')}\n"
|
| 203 |
+
f"地點: {epi.get('location', '—')}\n"
|
| 204 |
+
f"規模: M{mag.get('magnitudeValue', '—')} | 深度: {depth.get('value', '—')} km\n"
|
| 205 |
+
f"主要影響區域: {intensity_str}"
|
| 206 |
+
)
|
| 207 |
+
return "\n\n".join(lines)
|
| 208 |
+
|
| 209 |
+
except Exception as e:
|
| 210 |
+
return f"❌ 小區域地震查詢失敗:{e}"
|