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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# app.py (last-3-days default, no API key field)
|
| 3 |
+
import os
|
| 4 |
+
import json
|
| 5 |
+
import tempfile
|
| 6 |
+
from datetime import datetime, timedelta
|
| 7 |
+
from typing import List, Dict, Any, Tuple
|
| 8 |
+
|
| 9 |
+
import gradio as gr
|
| 10 |
+
import pandas as pd
|
| 11 |
+
import requests
|
| 12 |
+
import folium
|
| 13 |
+
|
| 14 |
+
BASE_URL = "https://opendata.cwa.gov.tw/api/v1/rest/datastore/E-A0015-001"
|
| 15 |
+
AREAS = ["宜蘭縣","花蓮縣","臺東縣","澎湖縣","金門縣","連江縣","臺北市","新北市","桃園市","臺中市","臺南市","高雄市","基隆市","新竹縣","新竹市","苗栗縣","彰化縣","南投縣","雲林縣","嘉義縣","嘉義市","屏東縣"]
|
| 16 |
+
|
| 17 |
+
INT_ORDER = {
|
| 18 |
+
"0": 0.0, "1": 1.0, "2": 2.0, "3": 3.0, "4": 4.0,
|
| 19 |
+
"5弱": 5.0, "5-": 5.0, "5+": 5.3, "5強": 5.3,
|
| 20 |
+
"6弱": 6.0, "6-": 6.0, "6+": 6.3, "6強": 6.3,
|
| 21 |
+
"7": 7.0
|
| 22 |
+
}
|
| 23 |
+
INT_FILTER_CHOICES = ["0","1","2","3","4","5弱","5強","6弱","6強","7"]
|
| 24 |
+
|
| 25 |
+
def intensity_to_order(s: str) -> float:
|
| 26 |
+
if s is None:
|
| 27 |
+
return -1.0
|
| 28 |
+
s = str(s).strip().replace("級","").replace(" ", "")
|
| 29 |
+
return INT_ORDER.get(s, -1.0)
|
| 30 |
+
|
| 31 |
+
def validate_iso(dt: str) -> str:
|
| 32 |
+
if not dt:
|
| 33 |
+
return ""
|
| 34 |
+
try:
|
| 35 |
+
datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
|
| 36 |
+
return dt
|
| 37 |
+
except ValueError:
|
| 38 |
+
raise gr.Error("時間格式需為 yyyy-MM-ddThh:mm:ss")
|
| 39 |
+
|
| 40 |
+
def build_params(limit: int|None, offset: int|None, fmt: str, areas: List[str], stations: List[str], sort: str|None, timeFrom: str|None, timeTo: str|None):
|
| 41 |
+
params = []
|
| 42 |
+
# Use only env var for auth
|
| 43 |
+
api_key = os.getenv("CWA_API_KEY")
|
| 44 |
+
if not api_key:
|
| 45 |
+
raise gr.Error("缺少授權碼:請到 Space 的 Settings → Repository secrets 新增 CWA_API_KEY。")
|
| 46 |
+
params.append(("Authorization", api_key))
|
| 47 |
+
|
| 48 |
+
if limit is not None: params.append(("limit", str(limit)))
|
| 49 |
+
if offset is not None: params.append(("offset", str(offset)))
|
| 50 |
+
if fmt: params.append(("format", fmt))
|
| 51 |
+
for a in (areas or []):
|
| 52 |
+
params.append(("AreaName", a))
|
| 53 |
+
for s in (stations or []):
|
| 54 |
+
params.append(("StationName", s))
|
| 55 |
+
if sort: params.append(("sort", sort))
|
| 56 |
+
if timeFrom: params.append(("timeFrom", timeFrom))
|
| 57 |
+
if timeTo: params.append(("timeTo", timeTo))
|
| 58 |
+
return params
|
| 59 |
+
|
| 60 |
+
def http_get(url: str, params: List[Tuple[str,str]]) -> Dict[str, Any]:
|
| 61 |
+
sess = requests.Session()
|
| 62 |
+
resp = sess.get(url, params=params, timeout=(5, 20))
|
| 63 |
+
resp.raise_for_status()
|
| 64 |
+
if "application/json" in resp.headers.get("Content-Type","").lower() or resp.text.strip().startswith("{"):
|
| 65 |
+
return resp.json()
|
| 66 |
+
else:
|
| 67 |
+
return {"raw": resp.text}
|
| 68 |
+
|
| 69 |
+
def extract_records(payload: Dict[str, Any]):
|
| 70 |
+
recs = payload.get("records")
|
| 71 |
+
if isinstance(recs, dict):
|
| 72 |
+
for k, v in recs.items():
|
| 73 |
+
if isinstance(v, list):
|
| 74 |
+
return v
|
| 75 |
+
result = payload.get("result")
|
| 76 |
+
if isinstance(result, dict) and isinstance(result.get("records"), list):
|
| 77 |
+
return result["records"]
|
| 78 |
+
for key in ("Earthquake","earthquakes","data","items"):
|
| 79 |
+
v = payload.get(key)
|
| 80 |
+
if isinstance(v, list):
|
| 81 |
+
return v
|
| 82 |
+
return []
|
| 83 |
+
|
| 84 |
+
def flatten_row(row: Dict[str, Any]) -> Dict[str, Any]:
|
| 85 |
+
out = {}
|
| 86 |
+
for key in ("EarthquakeNo","ReportImageURI","Web","ReportColor","ReportContent"):
|
| 87 |
+
if key in row:
|
| 88 |
+
out[key] = row.get(key)
|
| 89 |
+
eqi = row.get("EarthquakeInfo")
|
| 90 |
+
if isinstance(eqi, dict):
|
| 91 |
+
out["OriginTime"] = eqi.get("OriginTime")
|
| 92 |
+
out["Depth_km"] = eqi.get("FocalDepth")
|
| 93 |
+
mag = eqi.get("EarthquakeMagnitude") or {}
|
| 94 |
+
if isinstance(mag, dict):
|
| 95 |
+
out["Magnitude"] = mag.get("MagnitudeValue")
|
| 96 |
+
out["MagnitudeType"] = mag.get("MagnitudeType")
|
| 97 |
+
epic = eqi.get("Epicenter") or {}
|
| 98 |
+
if isinstance(epic, dict):
|
| 99 |
+
out["Epicenter"] = epic.get("Location")
|
| 100 |
+
out["EpicenterLon"] = epic.get("EpicenterLongitude")
|
| 101 |
+
out["EpicenterLat"] = epic.get("EpicenterLatitude")
|
| 102 |
+
for k in ("OriginTime","originTime","Time"):
|
| 103 |
+
if k in row and "OriginTime" not in out:
|
| 104 |
+
out["OriginTime"] = row.get(k)
|
| 105 |
+
for k in ("Depth","depth","FocalDepth"):
|
| 106 |
+
if k in row and "Depth_km" not in out:
|
| 107 |
+
out["Depth_km"] = row.get(k)
|
| 108 |
+
for k in ("Magnitude","mag"):
|
| 109 |
+
if k in row and "Magnitude" not in out:
|
| 110 |
+
out["Magnitude"] = row.get(k)
|
| 111 |
+
maxint = row.get("Intensity") or row.get("ShakingArea")
|
| 112 |
+
if isinstance(maxint, dict):
|
| 113 |
+
out["MaxIntensity"] = maxint.get("MaxIntensity")
|
| 114 |
+
return out
|
| 115 |
+
|
| 116 |
+
def df_with_types(df: pd.DataFrame) -> pd.DataFrame:
|
| 117 |
+
if "OriginTime" in df.columns:
|
| 118 |
+
try:
|
| 119 |
+
df["OriginTime"] = pd.to_datetime(df["OriginTime"], format="%Y-%m-%dT%H:%M:%S", errors="coerce")
|
| 120 |
+
except Exception:
|
| 121 |
+
pass
|
| 122 |
+
if "Magnitude" in df.columns:
|
| 123 |
+
df["Magnitude"] = pd.to_numeric(df["Magnitude"], errors="coerce")
|
| 124 |
+
if "Depth_km" in df.columns:
|
| 125 |
+
df["Depth_km"] = pd.to_numeric(df["Depth_km"], errors="coerce")
|
| 126 |
+
if "MaxIntensity" in df.columns:
|
| 127 |
+
df["MaxIntensityOrder"] = df["MaxIntensity"].map(intensity_to_order)
|
| 128 |
+
return df
|
| 129 |
+
|
| 130 |
+
def make_map(df: pd.DataFrame) -> str:
|
| 131 |
+
if not {"EpicenterLat","EpicenterLon"}.issubset(df.columns):
|
| 132 |
+
return "<p>沒有可用的經緯度資料。</p>"
|
| 133 |
+
valid = df.dropna(subset=["EpicenterLat","EpicenterLon"]).copy()
|
| 134 |
+
if valid.empty:
|
| 135 |
+
return "<p>沒有可用的經緯度資料。</p>"
|
| 136 |
+
try:
|
| 137 |
+
valid["EpicenterLat"] = pd.to_numeric(valid["EpicenterLat"], errors="coerce")
|
| 138 |
+
valid["EpicenterLon"] = pd.to_numeric(valid["EpicenterLon"], errors="coerce")
|
| 139 |
+
except Exception:
|
| 140 |
+
pass
|
| 141 |
+
valid = valid.dropna(subset=["EpicenterLat","EpicenterLon"])
|
| 142 |
+
if valid.empty:
|
| 143 |
+
return "<p>沒有可用的經緯度資料。</p>"
|
| 144 |
+
center_lat = valid["EpicenterLat"].mean()
|
| 145 |
+
center_lon = valid["EpicenterLon"].mean()
|
| 146 |
+
m = folium.Map(location=[center_lat, center_lon], zoom_start=6, tiles="OpenStreetMap")
|
| 147 |
+
for _, r in valid.iterrows():
|
| 148 |
+
lat = float(r["EpicenterLat"]); lon = float(r["EpicenterLon"])
|
| 149 |
+
mag = r.get("Magnitude", None); itx = r.get("MaxIntensity", "")
|
| 150 |
+
radius = 4.0
|
| 151 |
+
try:
|
| 152 |
+
if pd.notna(mag):
|
| 153 |
+
radius = max(4.0, min(20.0, float(mag) * 2.5))
|
| 154 |
+
except Exception:
|
| 155 |
+
pass
|
| 156 |
+
color = "#2c7bb6"
|
| 157 |
+
try:
|
| 158 |
+
if mag is not None and float(mag) >= 6.0:
|
| 159 |
+
color = "#d7191c"
|
| 160 |
+
elif mag is not None and float(mag) >= 5.0:
|
| 161 |
+
color = "#fdae61"
|
| 162 |
+
elif mag is not None and float(mag) >= 4.0:
|
| 163 |
+
color = "#abd9e9"
|
| 164 |
+
except Exception:
|
| 165 |
+
pass
|
| 166 |
+
popup = folium.Popup(html=f"<b>時間</b>: {r.get('OriginTime','')}<br>"
|
| 167 |
+
f"<b>震央</b>: {r.get('Epicenter','')}<br>"
|
| 168 |
+
f"<b>規模</b>: {mag}<br>"
|
| 169 |
+
f"<b>深度</b>: {r.get('Depth_km','')} km<br>"
|
| 170 |
+
f"<b>最大震度</b>: {itx}", max_width=320)
|
| 171 |
+
folium.CircleMarker(location=[lat, lon], radius=radius, color=color, fill=True, fill_opacity=0.7, popup=popup).add_to(m)
|
| 172 |
+
return m._repr_html_()
|
| 173 |
+
|
| 174 |
+
def fetch(time_from, time_to, limit, offset, fmt, sel_areas, stations, sort, min_intensity):
|
| 175 |
+
time_from = validate_iso(time_from) if time_from else None
|
| 176 |
+
time_to = validate_iso(time_to) if time_to else None
|
| 177 |
+
params = build_params(limit=limit, offset=offset, fmt=fmt, areas=sel_areas, stations=stations, sort=sort, timeFrom=time_from, timeTo=time_to)
|
| 178 |
+
payload = http_get(BASE_URL, params)
|
| 179 |
+
records = extract_records(payload)
|
| 180 |
+
flat = [flatten_row(r) for r in records]
|
| 181 |
+
df = pd.DataFrame(flat)
|
| 182 |
+
df = df_with_types(df)
|
| 183 |
+
|
| 184 |
+
if min_intensity:
|
| 185 |
+
thr = intensity_to_order(min_intensity)
|
| 186 |
+
if "MaxIntensityOrder" in df.columns and thr >= 0:
|
| 187 |
+
df = df[df["MaxIntensityOrder"] >= thr]
|
| 188 |
+
if "OriginTime" in df.columns:
|
| 189 |
+
ascending = True if sort == "OriginTime" else False
|
| 190 |
+
df = df.sort_values("OriginTime", ascending=ascending)
|
| 191 |
+
|
| 192 |
+
tmpdir = tempfile.mkdtemp(prefix="cwa_")
|
| 193 |
+
csv_path = os.path.join(tmpdir, "cwa_quake.csv")
|
| 194 |
+
json_path = os.path.join(tmpdir, "raw.json")
|
| 195 |
+
df.to_csv(csv_path, index=False, encoding="utf-8")
|
| 196 |
+
with open(json_path, "w", encoding="utf-8") as f:
|
| 197 |
+
json.dump(payload, f, ensure_ascii=False, indent=2)
|
| 198 |
+
|
| 199 |
+
total = len(df)
|
| 200 |
+
earliest = latest = ""
|
| 201 |
+
if total and "OriginTime" in df.columns:
|
| 202 |
+
earliest_row = df.iloc[0]; latest_row = df.iloc[-1]
|
| 203 |
+
def fmt_row(r):
|
| 204 |
+
ot = r.get("OriginTime","")
|
| 205 |
+
if isinstance(ot, pd.Timestamp):
|
| 206 |
+
ot = ot.strftime("%Y-%m-%dT%H:%M:%S")
|
| 207 |
+
return f"{ot} | {r.get('Epicenter','')} | M{r.get('Magnitude','')} | 深{r.get('Depth_km','')}km | 震度{r.get('MaxIntensity','')}"
|
| 208 |
+
earliest = "最早: " + fmt_row(earliest_row)
|
| 209 |
+
latest = "最新: " + fmt_row(latest_row)
|
| 210 |
+
|
| 211 |
+
summary = f"取得筆數: {total}\n{earliest}\n{latest}"
|
| 212 |
+
html_map = make_map(df)
|
| 213 |
+
if "OriginTime" in df.columns:
|
| 214 |
+
df["OriginTime"] = df["OriginTime"].astype(str)
|
| 215 |
+
return df, summary, csv_path, json_path, html_map
|
| 216 |
+
|
| 217 |
+
def last_3days(limit, offset, fmt, sel_areas, stations, sort, min_intensity):
|
| 218 |
+
now = datetime.now()
|
| 219 |
+
tf = (now - timedelta(days=3)).strftime("%Y-%m-%dT%H:%M:%S")
|
| 220 |
+
tt = now.strftime("%Y-%m-%dT%H:%M:%S")
|
| 221 |
+
return fetch(tf, tt, limit, offset, fmt, sel_areas, stations, sort, min_intensity)
|
| 222 |
+
|
| 223 |
+
with gr.Blocks(title="CWA 顯著有感地震報告 (E-A0015-001)") as demo:
|
| 224 |
+
gr.Markdown("# CWA 顯著有感地震報告 (E-A0015-001)")
|
| 225 |
+
gr.Markdown("**此 Space 只使用環境變數 `CWA_API_KEY` 作為授權。請到 Settings → Repository secrets 設定。**")
|
| 226 |
+
with gr.Row():
|
| 227 |
+
with gr.Column(scale=1):
|
| 228 |
+
time_from = gr.Textbox(label="timeFrom yyyy-MM-ddThh:mm:ss", value="2025-08-07T13:24:48", placeholder="yyyy-MM-ddThh:mm:ss")
|
| 229 |
+
time_to = gr.Textbox(label="timeTo yyyy-MM-ddThh:mm:ss", value="2025-08-10T13:24:48", placeholder="yyyy-MM-ddThh:mm:ss")
|
| 230 |
+
areas = gr.CheckboxGroup(choices=AREAS, label="AreaName(可複選)")
|
| 231 |
+
stations = gr.Textbox(label="StationName(以逗號分隔,可留空)", placeholder="例如:台北、花蓮...")
|
| 232 |
+
sort = gr.Dropdown(choices=[None, "OriginTime"], value=None, label="sort(預設降冪;選 OriginTime 會升冪)")
|
| 233 |
+
min_intensity = gr.Dropdown(choices=INT_FILTER_CHOICES, value=None, label="最小最大震度(過濾)")
|
| 234 |
+
with gr.Row():
|
| 235 |
+
limit = gr.Number(label="limit(筆數上限)", precision=0)
|
| 236 |
+
offset = gr.Number(label="offset(起始偏移)", precision=0, value=0)
|
| 237 |
+
fmt = gr.Radio(choices=["JSON","XML"], value="JSON", label="回傳格式")
|
| 238 |
+
with gr.Row():
|
| 239 |
+
run_btn = gr.Button("查詢", variant="primary")
|
| 240 |
+
last3_btn = gr.Button("重設為最近 3 天", variant="secondary")
|
| 241 |
+
with gr.Column(scale=2):
|
| 242 |
+
out_df = gr.Dataframe(label="查詢結果(扁平化)", interactive=False, wrap=True, datatype="str")
|
| 243 |
+
out_summary = gr.Textbox(label="摘要", interactive=False)
|
| 244 |
+
out_csv = gr.File(label="下載 CSV")
|
| 245 |
+
out_json = gr.File(label="下載原始 JSON")
|
| 246 |
+
out_map = gr.HTML(label="震央地圖")
|
| 247 |
+
|
| 248 |
+
def on_click(time_from, time_to, limit, offset, fmt, areas_sel, stations_txt, sort, min_intensity):
|
| 249 |
+
stations_list = [s.strip() for s in (stations_txt or "").split(",") if s.strip()]
|
| 250 |
+
df, summary, csv_path, json_path, html_map = fetch(time_from, time_to, int(limit) if limit is not None else None, int(offset) if offset is not None else None, fmt, areas_sel, stations_list, sort, min_intensity)
|
| 251 |
+
return df, summary, csv_path, json_path, html_map
|
| 252 |
+
|
| 253 |
+
def on_last3(limit, offset, fmt, areas_sel, stations_txt, sort, min_intensity):
|
| 254 |
+
stations_list = [s.strip() for s in (stations_txt or "").split(",") if s.strip()]
|
| 255 |
+
df, summary, csv_path, json_path, html_map = last_3days(int(limit) if limit is not None else None, int(offset) if offset is not None else None, fmt, areas_sel, stations_list, sort, min_intensity)
|
| 256 |
+
return df, summary, csv_path, json_path, html_map
|
| 257 |
+
|
| 258 |
+
run_btn.click(on_click, inputs=[time_from, time_to, limit, offset, fmt, areas, stations, sort, min_intensity], outputs=[out_df, out_summary, out_csv, out_json, out_map])
|
| 259 |
+
last3_btn.click(on_last3, inputs=[limit, offset, fmt, areas, stations, sort, min_intensity], outputs=[out_df, out_summary, out_csv, out_json, out_map])
|
| 260 |
+
|
| 261 |
+
if __name__ == "__main__":
|
| 262 |
+
demo.launch()
|