cwadayi commited on
Commit
db9a82e
·
verified ·
1 Parent(s): 3f4ebdf

Upload 2 files

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