cwadayi commited on
Commit
ad57946
·
verified ·
1 Parent(s): e87288f

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +321 -0
  2. requirements.txt +9 -0
app.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # app.py (mobile single-column, webhook/Sheets options, TW bbox + legend)
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
+ # Optional: Google Sheets (if available + secret provided)
15
+ try:
16
+ import gspread
17
+ from google.oauth2.service_account import Credentials
18
+ HAS_SHEETS = True
19
+ except Exception:
20
+ HAS_SHEETS = False
21
+
22
+ BASE_URL = "https://opendata.cwa.gov.tw/api/v1/rest/datastore/E-A0015-001"
23
+
24
+ INT_ORDER = {
25
+ "0": 0.0, "1": 1.0, "2": 2.0, "3": 3.0, "4": 4.0,
26
+ "5弱": 5.0, "5-": 5.0, "5+": 5.3, "5強": 5.3,
27
+ "6弱": 6.0, "6-": 6.0, "6+": 6.3, "6強": 6.3,
28
+ "7": 7.0
29
+ }
30
+ INT_FILTER_CHOICES = ["0","1","2","3","4","5弱","5強","6弱","6強","7"]
31
+
32
+ def intensity_to_order(s: str) -> float:
33
+ if s is None:
34
+ return -1.0
35
+ s = str(s).strip().replace("級","").replace(" ", "")
36
+ return INT_ORDER.get(s, -1.0)
37
+
38
+ def validate_iso(dt: str) -> str:
39
+ if not dt:
40
+ return ""
41
+ try:
42
+ datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
43
+ return dt
44
+ except ValueError:
45
+ raise gr.Error("時間格式需為 yyyy-MM-ddThh:mm:ss")
46
+
47
+ def build_params(limit: int|None, offset: int|None, fmt: str, sort: str|None, timeFrom: str|None, timeTo: str|None):
48
+ params = []
49
+ api_key = os.getenv("CWA_API_KEY")
50
+ if not api_key:
51
+ raise gr.Error("缺少授權碼:請到 Space 的 Settings → Repository secrets 新增 CWA_API_KEY。")
52
+ params.append(("Authorization", api_key))
53
+ if limit is not None: params.append(("limit", str(limit)))
54
+ if offset is not None: params.append(("offset", str(offset)))
55
+ if fmt: params.append(("format", fmt))
56
+ if sort: params.append(("sort", sort))
57
+ if timeFrom: params.append(("timeFrom", timeFrom))
58
+ if timeTo: params.append(("timeTo", timeTo))
59
+ return params
60
+
61
+ def http_get(url: str, params: List[Tuple[str,str]]) -> Dict[str, Any]:
62
+ sess = requests.Session()
63
+ resp = sess.get(url, params=params, timeout=(5, 20))
64
+ resp.raise_for_status()
65
+ if "application/json" in resp.headers.get("Content-Type","").lower() or resp.text.strip().startswith("{"):
66
+ return resp.json()
67
+ else:
68
+ return {"raw": resp.text}
69
+
70
+ def extract_records(payload: Dict[str, Any]):
71
+ recs = payload.get("records")
72
+ if isinstance(recs, dict):
73
+ for k, v in recs.items():
74
+ if isinstance(v, list):
75
+ return v
76
+ result = payload.get("result")
77
+ if isinstance(result, dict) and isinstance(result.get("records"), list):
78
+ return result["records"]
79
+ for key in ("Earthquake","earthquakes","data","items"):
80
+ v = payload.get(key)
81
+ if isinstance(v, list):
82
+ return v
83
+ return []
84
+
85
+ def flatten_row(row: Dict[str, Any]) -> Dict[str, Any]:
86
+ out = {}
87
+ for key in ("EarthquakeNo","ReportImageURI","Web","ReportColor","ReportContent"):
88
+ if key in row:
89
+ out[key] = row.get(key)
90
+ eqi = row.get("EarthquakeInfo")
91
+ if isinstance(eqi, dict):
92
+ out["OriginTime"] = eqi.get("OriginTime")
93
+ out["Depth_km"] = eqi.get("FocalDepth")
94
+ mag = eqi.get("EarthquakeMagnitude") or {}
95
+ if isinstance(mag, dict):
96
+ out["Magnitude"] = mag.get("MagnitudeValue")
97
+ out["MagnitudeType"] = mag.get("MagnitudeType")
98
+ epic = eqi.get("Epicenter") or {}
99
+ if isinstance(epic, dict):
100
+ out["Epicenter"] = epic.get("Location")
101
+ out["EpicenterLon"] = epic.get("EpicenterLongitude")
102
+ out["EpicenterLat"] = epic.get("EpicenterLatitude")
103
+ for k in ("OriginTime","originTime","Time"):
104
+ if k in row and "OriginTime" not in out:
105
+ out["OriginTime"] = row.get(k)
106
+ for k in ("Depth","depth","FocalDepth"):
107
+ if k in row and "Depth_km" not in out:
108
+ out["Depth_km"] = row.get(k)
109
+ for k in ("Magnitude","mag"):
110
+ if k in row and "Magnitude" not in out:
111
+ out["Magnitude"] = row.get(k)
112
+ maxint = row.get("Intensity") or row.get("ShakingArea")
113
+ if isinstance(maxint, dict):
114
+ out["MaxIntensity"] = maxint.get("MaxIntensity")
115
+ return out
116
+
117
+ def df_with_types(df: pd.DataFrame) -> pd.DataFrame:
118
+ if "OriginTime" in df.columns:
119
+ try:
120
+ df["OriginTime"] = pd.to_datetime(df["OriginTime"], format="%Y-%m-%dT%H:%M:%S", errors="coerce")
121
+ except Exception:
122
+ pass
123
+ if "Magnitude" in df.columns:
124
+ df["Magnitude"] = pd.to_numeric(df["Magnitude"], errors="coerce")
125
+ if "Depth_km" in df.columns:
126
+ df["Depth_km"] = pd.to_numeric(df["Depth_km"], errors="coerce")
127
+ if "MaxIntensity" in df.columns:
128
+ df["MaxIntensityOrder"] = df["MaxIntensity"].map(intensity_to_order)
129
+ return df
130
+
131
+ def add_tw_bbox(m: folium.Map):
132
+ bounds = [(21.0, 119.0), (26.0, 123.0)]
133
+ folium.Rectangle(bounds=bounds, color="#444", fill=False, weight=2, dash_array="5").add_to(m)
134
+
135
+ def add_legend(m: folium.Map):
136
+ html = """
137
+ <div style='position: fixed; bottom: 10px; right: 10px; z-index:9999; background: rgba(255,255,255,0.9); padding: 8px 10px; border:1px solid #999; border-radius:6px; font-size:12px;'>
138
+ <div style='font-weight:600; margin-bottom:4px;'>圖例</div>
139
+ <div><span style='display:inline-block;width:12px;height:12px;background:#abd9e9;margin-right:6px;border:1px solid #999;'></span> M4.0–4.9</div>
140
+ <div><span style='display:inline-block;width:12px;height:12px;background:#fdae61;margin-right:6px;border:1px solid #999;'></span> M5.0–5.9</div>
141
+ <div><span style='display:inline-block;width:12px;height:12px;background:#d7191c;margin-right:6px;border:1px solid #999;'></span> M≥6.0</div>
142
+ <div style='margin-top:4px;'>圓徑 ≈ 規模 × 2.5</div>
143
+ </div>
144
+ """
145
+ folium.Marker(location=[0,0], icon=folium.DivIcon(html=html)).add_to(m)
146
+
147
+ def make_map(df: pd.DataFrame) -> str:
148
+ if not {"EpicenterLat","EpicenterLon"}.issubset(df.columns):
149
+ return "<p>沒有可用的經緯度資料。</p>"
150
+ valid = df.dropna(subset=["EpicenterLat","EpicenterLon"]).copy()
151
+ if valid.empty:
152
+ return "<p>沒有可用的經緯度資料。</p>"
153
+ try:
154
+ valid["EpicenterLat"] = pd.to_numeric(valid["EpicenterLat"], errors="coerce")
155
+ valid["EpicenterLon"] = pd.to_numeric(valid["EpicenterLon"], errors="coerce")
156
+ except Exception:
157
+ pass
158
+ valid = valid.dropna(subset=["EpicenterLat","EpicenterLon"])
159
+ if valid.empty:
160
+ return "<p>沒有可用的經緯度資料。</p>"
161
+ center_lat = valid["EpicenterLat"].mean()
162
+ center_lon = valid["EpicenterLon"].mean()
163
+ m = folium.Map(location=[center_lat, center_lon], zoom_start=6, tiles="OpenStreetMap")
164
+ add_tw_bbox(m)
165
+ for _, r in valid.iterrows():
166
+ lat = float(r["EpicenterLat"]); lon = float(r["EpicenterLon"])
167
+ mag = r.get("Magnitude", None); itx = r.get("MaxIntensity", "")
168
+ radius = 4.0
169
+ try:
170
+ if pd.notna(mag):
171
+ radius = max(4.0, min(20.0, float(mag) * 2.5))
172
+ except Exception:
173
+ pass
174
+ color = "#2c7bb6"
175
+ try:
176
+ if mag is not None and float(mag) >= 6.0:
177
+ color = "#d7191c"
178
+ elif mag is not None and float(mag) >= 5.0:
179
+ color = "#fdae61"
180
+ elif mag is not None and float(mag) >= 4.0:
181
+ color = "#abd9e9"
182
+ except Exception:
183
+ pass
184
+ popup = folium.Popup(html=f"<b>時間</b>: {r.get('OriginTime','')}<br>"
185
+ f"<b>震央</b>: {r.get('Epicenter','')}<br>"
186
+ f"<b>規模</b>: {mag}<br>"
187
+ f"<b>深度</b>: {r.get('Depth_km','')} km<br>"
188
+ f"<b>最大震度</b>: {itx}", max_width=320)
189
+ folium.CircleMarker(location=[lat, lon], radius=radius, color=color, fill=True, fill_opacity=0.7, popup=popup).add_to(m)
190
+ add_legend(m)
191
+ return m._repr_html_()
192
+
193
+ def push_webhook(url: str, summary: str, df: pd.DataFrame) -> str:
194
+ if not url:
195
+ return "未設定 Webhook URL"
196
+ data = {
197
+ "summary": summary,
198
+ "count": int(len(df)),
199
+ "generated_at": datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),
200
+ "records": df.head(200).to_dict(orient="records")
201
+ }
202
+ try:
203
+ r = requests.post(url, json=data, timeout=10)
204
+ return f"Webhook 回應: {r.status_code}"
205
+ except Exception as e:
206
+ return f"Webhook 失敗: {e}"
207
+
208
+ def push_sheets(spreadsheet_id: str, worksheet_name: str, df: pd.DataFrame) -> str:
209
+ if not HAS_SHEETS:
210
+ return "未安裝 Sheets 套件(gspread / google-auth)"
211
+ if not spreadsheet_id or not worksheet_name:
212
+ return "未設定 Spreadsheet ID 或工作表名稱"
213
+ sa_json = os.getenv("GDRIVE_SERVICE_ACCOUNT_JSON")
214
+ if not sa_json:
215
+ return "缺少 GDRIVE_SERVICE_ACCOUNT_JSON 憑證(請放在 Secrets)"
216
+ try:
217
+ info = json.loads(sa_json)
218
+ scopes = ["https://www.googleapis.com/auth/spreadsheets"]
219
+ creds = Credentials.from_service_account_info(info, scopes=scopes)
220
+ gc = gspread.authorize(creds)
221
+ sh = gc.open_by_key(spreadsheet_id)
222
+ try:
223
+ ws = sh.worksheet(worksheet_name)
224
+ except gspread.exceptions.WorksheetNotFound:
225
+ ws = sh.add_worksheet(title=worksheet_name, rows=1000, cols=40)
226
+ ws.clear()
227
+ if df.empty:
228
+ ws.update("A1", [["No data"]])
229
+ return "已寫入空資料到 Google Sheets"
230
+ values = [list(df.columns)] + df.astype(str).values.tolist()
231
+ ws.update("A1", values)
232
+ return "已寫入 Google Sheets"
233
+ except Exception as e:
234
+ return f"Sheets 失敗: {e}"
235
+
236
+ def fetch(time_from, time_to, limit, offset, fmt, sort, min_intensity, webhook_url, enable_webhook, spreadsheet_id, worksheet_name, enable_sheets):
237
+ time_from = validate_iso(time_from) if time_from else None
238
+ time_to = validate_iso(time_to) if time_to else None
239
+ params = build_params(limit=limit, offset=offset, fmt=fmt, sort=sort, timeFrom=time_from, timeTo=time_to)
240
+ payload = http_get(BASE_URL, params)
241
+ records = extract_records(payload)
242
+ flat = [flatten_row(r) for r in records]
243
+ df = pd.DataFrame(flat)
244
+ df = df_with_types(df)
245
+ if min_intensity:
246
+ thr = intensity_to_order(min_intensity)
247
+ if "MaxIntensityOrder" in df.columns and thr >= 0:
248
+ df = df[df["MaxIntensityOrder"] >= thr]
249
+ if "OriginTime" in df.columns:
250
+ ascending = True if sort == "OriginTime" else False
251
+ df = df.sort_values("OriginTime", ascending=ascending)
252
+ tmpdir = tempfile.mkdtemp(prefix="cwa_")
253
+ csv_path = os.path.join(tmpdir, "cwa_quake.csv")
254
+ json_path = os.path.join(tmpdir, "raw.json")
255
+ df.to_csv(csv_path, index=False, encoding="utf-8")
256
+ with open(json_path, "w", encoding="utf-8") as f:
257
+ json.dump(payload, f, ensure_ascii=False, indent=2)
258
+ total = len(df)
259
+ earliest = latest = ""
260
+ if total and "OriginTime" in df.columns:
261
+ earliest_row = df.iloc[0]; latest_row = df.iloc[-1]
262
+ def fmt_row(r):
263
+ ot = r.get("OriginTime","")
264
+ if isinstance(ot, pd.Timestamp):
265
+ ot = ot.strftime("%Y-%m-%dT%H:%M:%S")
266
+ return f"{ot} | {r.get('Epicenter','')} | M{r.get('Magnitude','')} | 深{r.get('Depth_km','')}km | 震度{r.get('MaxIntensity','')}"
267
+ earliest = "最早: " + fmt_row(earliest_row)
268
+ latest = "最新: " + fmt_row(latest_row)
269
+ summary = f"取得筆數: {total}\n{earliest}\n{latest}"
270
+ html_map = make_map(df)
271
+ if "OriginTime" in df.columns:
272
+ df["OriginTime"] = df["OriginTime"].astype(str)
273
+ webhook_msg = ""
274
+ if enable_webhook and webhook_url:
275
+ webhook_msg = push_webhook(webhook_url, summary, df)
276
+ sheets_msg = ""
277
+ if enable_sheets:
278
+ sheets_msg = push_sheets(spreadsheet_id, worksheet_name, df)
279
+ notes = "\n".join([m for m in [webhook_msg, sheets_msg] if m])
280
+ return df, summary, csv_path, json_path, html_map, notes
281
+
282
+ now = datetime.now()
283
+ TF_DEFAULT = (now - timedelta(days=3)).strftime("%Y-%m-%dT%H:%M:%S")
284
+ TT_DEFAULT = now.strftime("%Y-%m-%dT%H:%M:%S")
285
+
286
+ with gr.Blocks(title="CWA 顯著有感地震報告 (E-A0015-001)") as demo:
287
+ gr.Markdown("# CWA 顯著有感地震報告 (E-A0015-001)")
288
+ gr.Markdown("**此 Space 只使用環境變數 `CWA_API_KEY` 作為授權。** 若要推送到 Google Sheets,請在 Secrets 提供 `GDRIVE_SERVICE_ACCOUNT_JSON`(Service Account JSON)。")
289
+ time_from = gr.Textbox(label="timeFrom yyyy-MM-ddThh:mm:ss", value=TF_DEFAULT)
290
+ time_to = gr.Textbox(label="timeTo yyyy-MM-ddThh:mm:ss", value=TT_DEFAULT)
291
+ sort = gr.Dropdown(choices=[None, "OriginTime"], value=None, label="sort(預設降冪;選 OriginTime 會升冪)")
292
+ min_intensity = gr.Dropdown(choices=INT_FILTER_CHOICES, value=None, label="最小最大震度(過濾)")
293
+ limit = gr.Number(label="limit(筆數上限)", precision=0, value=60)
294
+ offset = gr.Number(label="offset(起始偏移)", precision=0, value=0)
295
+ fmt = gr.Radio(choices=["JSON","XML"], value="JSON", label="回傳格式")
296
+ gr.Markdown("### 推送(選用)")
297
+ with gr.Row():
298
+ webhook_url = gr.Textbox(label="Webhook URL(選填)", placeholder="例如:你的 n8n / Dify / 自有 API")
299
+ enable_webhook = gr.Checkbox(label="查詢後自動 POST 到 Webhook", value=False)
300
+ with gr.Row():
301
+ spreadsheet_id = gr.Textbox(label="Google Sheets Spreadsheet ID(選填)", placeholder="例如:1AbC...")
302
+ worksheet_name = gr.Textbox(label="工作表名稱(例如:Sheet1)", value="Sheet1")
303
+ enable_sheets = gr.Checkbox(label="查詢後寫入 Google Sheets(需設定服務帳戶憑證)", value=False)
304
+ run_btn = gr.Button("查詢", variant="primary")
305
+ out_df = gr.Dataframe(label="查詢結果(扁平化)", interactive=False, wrap=True, datatype="str")
306
+ out_summary = gr.Textbox(label="摘要", interactive=False)
307
+ out_csv = gr.File(label="下載 CSV")
308
+ out_json = gr.File(label="下載原始 JSON")
309
+ out_map = gr.HTML(label="震央地圖")
310
+ out_notes = gr.Textbox(label="推送狀態", interactive=False)
311
+ def on_click(time_from, time_to, limit, offset, fmt, sort, min_intensity, webhook_url, enable_webhook, spreadsheet_id, worksheet_name, enable_sheets):
312
+ df, summary, csv_path, json_path, html_map, notes = fetch(
313
+ time_from, time_to, int(limit) if limit is not None else None, int(offset) if offset is not None else None,
314
+ fmt, sort, min_intensity, webhook_url, enable_webhook, spreadsheet_id, worksheet_name, enable_sheets
315
+ )
316
+ return df, summary, csv_path, json_path, html_map, notes
317
+ run_btn.click(on_click, inputs=[time_from, time_to, limit, offset, fmt, sort, min_intensity, webhook_url, enable_webhook, spreadsheet_id, worksheet_name, enable_sheets],
318
+ outputs=[out_df, out_summary, out_csv, out_json, out_map, out_notes])
319
+
320
+ if __name__ == "__main__":
321
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
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
8
+ gspread>=6.0.0
9
+ google-auth>=2.35.0