Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,7 +8,7 @@ import pandas as pd
|
|
| 8 |
import matplotlib.pyplot as plt
|
| 9 |
import gradio as gr
|
| 10 |
|
| 11 |
-
# ----------
|
| 12 |
try:
|
| 13 |
import tabulate as _tabulate # noqa: F401
|
| 14 |
HAS_TABULATE = True
|
|
@@ -22,13 +22,13 @@ try:
|
|
| 22 |
except Exception:
|
| 23 |
HAS_PYGMT = False
|
| 24 |
|
| 25 |
-
# ---- 自動抓取 PyGMT
|
| 26 |
if 'HAS_PYGMT' in globals() and HAS_PYGMT:
|
| 27 |
try:
|
| 28 |
-
pygmt.which("@gshhg", download=True)
|
| 29 |
-
pygmt.which("@dcw", download=True)
|
|
|
|
| 30 |
except Exception:
|
| 31 |
-
# 若下載失敗就靜默忽略,之後會走 matplotlib 備援
|
| 32 |
pass
|
| 33 |
|
| 34 |
# -----------------------------
|
|
@@ -40,7 +40,6 @@ def _fmt(dt: datetime) -> str:
|
|
| 40 |
return dt.strftime("%Y-%m-%dT%H:%M:%S")
|
| 41 |
|
| 42 |
def set_time_range(hours=None, days=None):
|
| 43 |
-
"""依台北時間回傳 (timeFrom, timeTo) 字串"""
|
| 44 |
now = datetime.now(TAIPEI_TZ)
|
| 45 |
if hours is not None:
|
| 46 |
t_from = now - timedelta(hours=hours)
|
|
@@ -65,15 +64,10 @@ def fetch_reports(time_from, time_to):
|
|
| 65 |
return r.json()
|
| 66 |
|
| 67 |
# -----------------------------
|
| 68 |
-
# JSON
|
| 69 |
# -----------------------------
|
| 70 |
def _to_float(x):
|
| 71 |
-
"""
|
| 72 |
-
將各種數字表達轉成 float:
|
| 73 |
-
- 純數字:23.5
|
| 74 |
-
- 含單位/文字:'23.5°N'、'121.6 E'、'25.3 公里' -> 擷取第一個浮點數
|
| 75 |
-
- 其他不可解析 -> None
|
| 76 |
-
"""
|
| 77 |
if x is None:
|
| 78 |
return None
|
| 79 |
if isinstance(x, (int, float)):
|
|
@@ -85,11 +79,6 @@ def _to_float(x):
|
|
| 85 |
return float(m.group()) if m else None
|
| 86 |
|
| 87 |
def parse_ea0015(obj):
|
| 88 |
-
"""
|
| 89 |
-
解析 CWA E-A0015-001
|
| 90 |
-
主要欄位在 records.earthquake[].EarthquakeInfo.*
|
| 91 |
-
取出:OriginTime, Lat, Lon, Depth_km, Magnitude, Location, ReportURL
|
| 92 |
-
"""
|
| 93 |
records = obj.get("records") or obj.get("Records") or {}
|
| 94 |
quakes = records.get("earthquake") or records.get("Earthquake") or []
|
| 95 |
if not isinstance(quakes, list):
|
|
@@ -99,8 +88,6 @@ def parse_ea0015(obj):
|
|
| 99 |
for q in quakes:
|
| 100 |
ei = q.get("EarthquakeInfo") or q.get("earthquakeInfo") or {}
|
| 101 |
epic = ei.get("Epicenter") or ei.get("epicenter") or {}
|
| 102 |
-
|
| 103 |
-
# Magnitude 可能在 Magnitude 或 EarthquakeMagnitude
|
| 104 |
mago = (
|
| 105 |
ei.get("Magnitude") or ei.get("magnitude")
|
| 106 |
or ei.get("EarthquakeMagnitude") or ei.get("earthquakeMagnitude")
|
|
@@ -112,7 +99,6 @@ def parse_ea0015(obj):
|
|
| 112 |
or q.get("OriginTime") or q.get("originTime")
|
| 113 |
)
|
| 114 |
|
| 115 |
-
# 經緯度多種鍵名
|
| 116 |
lat_raw = (
|
| 117 |
epic.get("EpicenterLat") or epic.get("epicenterLat")
|
| 118 |
or epic.get("EpicenterLatitude") or epic.get("epicenterLatitude")
|
|
@@ -124,14 +110,12 @@ def parse_ea0015(obj):
|
|
| 124 |
or epic.get("Lon") or epic.get("lon")
|
| 125 |
)
|
| 126 |
|
| 127 |
-
# 深度:Depth / FocalDepth / FocalDepthKm / depth / focalDepth...
|
| 128 |
depth_raw = (
|
| 129 |
ei.get("Depth") or ei.get("depth")
|
| 130 |
or ei.get("FocalDepth") or ei.get("focalDepth")
|
| 131 |
or ei.get("FocalDepthKm") or ei.get("focalDepthKm")
|
| 132 |
)
|
| 133 |
|
| 134 |
-
# 規模:MagnitudeValue / value / Magnitude / magnitude
|
| 135 |
mag_raw = (
|
| 136 |
mago.get("MagnitudeValue") or mago.get("magnitudeValue")
|
| 137 |
or mago.get("Value") or mago.get("value")
|
|
@@ -159,7 +143,7 @@ def parse_ea0015(obj):
|
|
| 159 |
return df
|
| 160 |
|
| 161 |
# -----------------------------
|
| 162 |
-
#
|
| 163 |
# -----------------------------
|
| 164 |
def _save_fig_to_tmp(fig, suffix=".png", dpi=180):
|
| 165 |
outpath = tempfile.NamedTemporaryFile(delete=False, suffix=suffix).name
|
|
@@ -180,7 +164,6 @@ def plot_trend_path(df):
|
|
| 180 |
return _save_fig_to_tmp(fig)
|
| 181 |
|
| 182 |
def _auto_region_from_df(d, pad=0.5):
|
| 183 |
-
"""由資料自動推算地圖範圍,並加上邊界緩衝(degrees)。"""
|
| 184 |
lon_min = float(pd.to_numeric(d["Lon"], errors="coerce").min())
|
| 185 |
lon_max = float(pd.to_numeric(d["Lon"], errors="coerce").max())
|
| 186 |
lat_min = float(pd.to_numeric(d["Lat"], errors="coerce").min())
|
|
@@ -188,14 +171,9 @@ def _auto_region_from_df(d, pad=0.5):
|
|
| 188 |
return [lon_min - pad, lon_max + pad, lat_min - pad, lat_max + pad]
|
| 189 |
|
| 190 |
def plot_map_path(df):
|
| 191 |
-
"""
|
| 192 |
-
優先使用 PyGMT 畫台灣地圖(含海岸線);若不可用則退回 matplotlib。
|
| 193 |
-
- 自動依據資料決定地圖範圍(避免漏點)
|
| 194 |
-
- 顏色:深度(km);大小:規模
|
| 195 |
-
"""
|
| 196 |
if df.empty:
|
| 197 |
return None
|
| 198 |
-
|
| 199 |
d = df.dropna(subset=["Lon", "Lat"]).copy()
|
| 200 |
if d.empty:
|
| 201 |
return None
|
|
@@ -203,19 +181,44 @@ def plot_map_path(df):
|
|
| 203 |
d["Magnitude"] = pd.to_numeric(d["Magnitude"], errors="coerce").fillna(0).clip(lower=0)
|
| 204 |
d["Depth_km"] = pd.to_numeric(d["Depth_km"], errors="coerce").fillna(0)
|
| 205 |
|
| 206 |
-
# --- PyGMT
|
| 207 |
if HAS_PYGMT:
|
| 208 |
-
d["Size"] = 0.06 * (d["Magnitude"] + 1.5) # cm
|
| 209 |
region = _auto_region_from_df(d, pad=0.5)
|
| 210 |
|
| 211 |
fig = pygmt.Figure()
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
fig.plot(
|
| 220 |
data=d, x="Lon", y="Lat",
|
| 221 |
style="c", size="Size",
|
|
@@ -228,14 +231,13 @@ def plot_map_path(df):
|
|
| 228 |
fig.savefig(outpath, dpi=220)
|
| 229 |
return outpath
|
| 230 |
|
| 231 |
-
# --- Matplotlib
|
| 232 |
region = _auto_region_from_df(d, pad=0.5)
|
| 233 |
lon_min, lon_max, lat_min, lat_max = region
|
| 234 |
|
| 235 |
fig, ax = plt.subplots(figsize=(6, 6))
|
| 236 |
ax.set_xlim(lon_min, lon_max)
|
| 237 |
ax.set_ylim(lat_min, lat_max)
|
| 238 |
-
|
| 239 |
s = (d["Magnitude"] + 2) ** 3
|
| 240 |
sc = ax.scatter(d["Lon"], d["Lat"], s=s, c=d["Depth_km"], alpha=0.85, edgecolor="black")
|
| 241 |
cb = plt.colorbar(sc, ax=ax, fraction=0.046, pad=0.04)
|
|
@@ -247,7 +249,7 @@ def plot_map_path(df):
|
|
| 247 |
return _save_fig_to_tmp(fig)
|
| 248 |
|
| 249 |
# -----------------------------
|
| 250 |
-
#
|
| 251 |
# -----------------------------
|
| 252 |
def _format_taipei(series):
|
| 253 |
try:
|
|
@@ -344,13 +346,11 @@ with gr.Blocks(fill_height=True) as demo:
|
|
| 344 |
map_out = gr.Image(label="台灣範圍圖(PyGMT)", type="filepath")
|
| 345 |
dl_btn = gr.DownloadButton(label="下載 CSV") # 回傳路徑即可
|
| 346 |
|
| 347 |
-
# 快速鍵
|
| 348 |
btn_12h.click(lambda: set_time_range(hours=12), outputs=[time_from, time_to])
|
| 349 |
btn_24h.click(lambda: set_time_range(hours=24), outputs=[time_from, time_to])
|
| 350 |
btn_3d.click(lambda: set_time_range(days=3), outputs=[time_from, time_to])
|
| 351 |
btn_5d.click(lambda: set_time_range(days=5), outputs=[time_from, time_to])
|
| 352 |
|
| 353 |
-
# 查詢
|
| 354 |
run_btn.click(
|
| 355 |
query_and_render,
|
| 356 |
inputs=[time_from, time_to, sort_dd],
|
|
|
|
| 8 |
import matplotlib.pyplot as plt
|
| 9 |
import gradio as gr
|
| 10 |
|
| 11 |
+
# ---------- 可選依賴偵測 ----------
|
| 12 |
try:
|
| 13 |
import tabulate as _tabulate # noqa: F401
|
| 14 |
HAS_TABULATE = True
|
|
|
|
| 22 |
except Exception:
|
| 23 |
HAS_PYGMT = False
|
| 24 |
|
| 25 |
+
# ---- 自動抓取 PyGMT 所需資料(若可用) ----
|
| 26 |
if 'HAS_PYGMT' in globals() and HAS_PYGMT:
|
| 27 |
try:
|
| 28 |
+
pygmt.which("@gshhg", download=True) # 海岸線
|
| 29 |
+
pygmt.which("@dcw", download=True) # 國界
|
| 30 |
+
pygmt.which("@earth_relief_04m", download=True) # 地形備援
|
| 31 |
except Exception:
|
|
|
|
| 32 |
pass
|
| 33 |
|
| 34 |
# -----------------------------
|
|
|
|
| 40 |
return dt.strftime("%Y-%m-%dT%H:%M:%S")
|
| 41 |
|
| 42 |
def set_time_range(hours=None, days=None):
|
|
|
|
| 43 |
now = datetime.now(TAIPEI_TZ)
|
| 44 |
if hours is not None:
|
| 45 |
t_from = now - timedelta(hours=hours)
|
|
|
|
| 64 |
return r.json()
|
| 65 |
|
| 66 |
# -----------------------------
|
| 67 |
+
# 解析 JSON
|
| 68 |
# -----------------------------
|
| 69 |
def _to_float(x):
|
| 70 |
+
"""將字串(含單位)抽出第一個數字成 float;失敗回 None。"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
if x is None:
|
| 72 |
return None
|
| 73 |
if isinstance(x, (int, float)):
|
|
|
|
| 79 |
return float(m.group()) if m else None
|
| 80 |
|
| 81 |
def parse_ea0015(obj):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
records = obj.get("records") or obj.get("Records") or {}
|
| 83 |
quakes = records.get("earthquake") or records.get("Earthquake") or []
|
| 84 |
if not isinstance(quakes, list):
|
|
|
|
| 88 |
for q in quakes:
|
| 89 |
ei = q.get("EarthquakeInfo") or q.get("earthquakeInfo") or {}
|
| 90 |
epic = ei.get("Epicenter") or ei.get("epicenter") or {}
|
|
|
|
|
|
|
| 91 |
mago = (
|
| 92 |
ei.get("Magnitude") or ei.get("magnitude")
|
| 93 |
or ei.get("EarthquakeMagnitude") or ei.get("earthquakeMagnitude")
|
|
|
|
| 99 |
or q.get("OriginTime") or q.get("originTime")
|
| 100 |
)
|
| 101 |
|
|
|
|
| 102 |
lat_raw = (
|
| 103 |
epic.get("EpicenterLat") or epic.get("epicenterLat")
|
| 104 |
or epic.get("EpicenterLatitude") or epic.get("epicenterLatitude")
|
|
|
|
| 110 |
or epic.get("Lon") or epic.get("lon")
|
| 111 |
)
|
| 112 |
|
|
|
|
| 113 |
depth_raw = (
|
| 114 |
ei.get("Depth") or ei.get("depth")
|
| 115 |
or ei.get("FocalDepth") or ei.get("focalDepth")
|
| 116 |
or ei.get("FocalDepthKm") or ei.get("focalDepthKm")
|
| 117 |
)
|
| 118 |
|
|
|
|
| 119 |
mag_raw = (
|
| 120 |
mago.get("MagnitudeValue") or mago.get("magnitudeValue")
|
| 121 |
or mago.get("Value") or mago.get("value")
|
|
|
|
| 143 |
return df
|
| 144 |
|
| 145 |
# -----------------------------
|
| 146 |
+
# 視覺化
|
| 147 |
# -----------------------------
|
| 148 |
def _save_fig_to_tmp(fig, suffix=".png", dpi=180):
|
| 149 |
outpath = tempfile.NamedTemporaryFile(delete=False, suffix=suffix).name
|
|
|
|
| 164 |
return _save_fig_to_tmp(fig)
|
| 165 |
|
| 166 |
def _auto_region_from_df(d, pad=0.5):
|
|
|
|
| 167 |
lon_min = float(pd.to_numeric(d["Lon"], errors="coerce").min())
|
| 168 |
lon_max = float(pd.to_numeric(d["Lon"], errors="coerce").max())
|
| 169 |
lat_min = float(pd.to_numeric(d["Lat"], errors="coerce").min())
|
|
|
|
| 171 |
return [lon_min - pad, lon_max + pad, lat_min - pad, lat_max + pad]
|
| 172 |
|
| 173 |
def plot_map_path(df):
|
| 174 |
+
"""PyGMT(含海岸線三段式備援)→ 失敗退回 Matplotlib。"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
if df.empty:
|
| 176 |
return None
|
|
|
|
| 177 |
d = df.dropna(subset=["Lon", "Lat"]).copy()
|
| 178 |
if d.empty:
|
| 179 |
return None
|
|
|
|
| 181 |
d["Magnitude"] = pd.to_numeric(d["Magnitude"], errors="coerce").fillna(0).clip(lower=0)
|
| 182 |
d["Depth_km"] = pd.to_numeric(d["Depth_km"], errors="coerce").fillna(0)
|
| 183 |
|
| 184 |
+
# --- PyGMT 版 ---
|
| 185 |
if HAS_PYGMT:
|
| 186 |
+
d["Size"] = 0.06 * (d["Magnitude"] + 1.5) # 圓半徑(cm)
|
| 187 |
region = _auto_region_from_df(d, pad=0.5)
|
| 188 |
|
| 189 |
fig = pygmt.Figure()
|
| 190 |
+
drew_background = False
|
| 191 |
+
# 1) GSHHG 海岸線
|
| 192 |
+
try:
|
| 193 |
+
fig.coast(
|
| 194 |
+
region=region, projection="M12c",
|
| 195 |
+
resolution="i",
|
| 196 |
+
land="lightgray", water="lightblue",
|
| 197 |
+
shorelines="0.8p,black", borders="1/0.6p,black",
|
| 198 |
+
frame=["WSen", "xaf", "yaf"]
|
| 199 |
+
)
|
| 200 |
+
drew_background = True
|
| 201 |
+
except Exception:
|
| 202 |
+
pass
|
| 203 |
+
# 2) DCW 台灣填色
|
| 204 |
+
if not drew_background:
|
| 205 |
+
try:
|
| 206 |
+
fig.coast(region=region, projection="M12c",
|
| 207 |
+
water="lightblue", frame=["WSen", "xaf", "yaf"])
|
| 208 |
+
fig.coast(region=region, projection="M12c", dcw="TW+glightgray")
|
| 209 |
+
drew_background = True
|
| 210 |
+
except Exception:
|
| 211 |
+
pass
|
| 212 |
+
# 3) 地形格網 +(可用則)海岸線
|
| 213 |
+
if not drew_background:
|
| 214 |
+
fig.grdimage("@earth_relief_04m", region=region, projection="M12c", cmap="gray")
|
| 215 |
+
try:
|
| 216 |
+
fig.coast(region=region, projection="M12c",
|
| 217 |
+
shorelines="0.8p,black", frame=["WSen", "xaf", "yaf"])
|
| 218 |
+
except Exception:
|
| 219 |
+
fig.basemap(region=region, projection="M12c", frame=["WSen", "xaf", "yaf"])
|
| 220 |
+
|
| 221 |
+
# 畫震央
|
| 222 |
fig.plot(
|
| 223 |
data=d, x="Lon", y="Lat",
|
| 224 |
style="c", size="Size",
|
|
|
|
| 231 |
fig.savefig(outpath, dpi=220)
|
| 232 |
return outpath
|
| 233 |
|
| 234 |
+
# --- Matplotlib 備援(無海岸線,只畫散點) ---
|
| 235 |
region = _auto_region_from_df(d, pad=0.5)
|
| 236 |
lon_min, lon_max, lat_min, lat_max = region
|
| 237 |
|
| 238 |
fig, ax = plt.subplots(figsize=(6, 6))
|
| 239 |
ax.set_xlim(lon_min, lon_max)
|
| 240 |
ax.set_ylim(lat_min, lat_max)
|
|
|
|
| 241 |
s = (d["Magnitude"] + 2) ** 3
|
| 242 |
sc = ax.scatter(d["Lon"], d["Lat"], s=s, c=d["Depth_km"], alpha=0.85, edgecolor="black")
|
| 243 |
cb = plt.colorbar(sc, ax=ax, fraction=0.046, pad=0.04)
|
|
|
|
| 249 |
return _save_fig_to_tmp(fig)
|
| 250 |
|
| 251 |
# -----------------------------
|
| 252 |
+
# 表格輸出
|
| 253 |
# -----------------------------
|
| 254 |
def _format_taipei(series):
|
| 255 |
try:
|
|
|
|
| 346 |
map_out = gr.Image(label="台灣範圍圖(PyGMT)", type="filepath")
|
| 347 |
dl_btn = gr.DownloadButton(label="下載 CSV") # 回傳路徑即可
|
| 348 |
|
|
|
|
| 349 |
btn_12h.click(lambda: set_time_range(hours=12), outputs=[time_from, time_to])
|
| 350 |
btn_24h.click(lambda: set_time_range(hours=24), outputs=[time_from, time_to])
|
| 351 |
btn_3d.click(lambda: set_time_range(days=3), outputs=[time_from, time_to])
|
| 352 |
btn_5d.click(lambda: set_time_range(days=5), outputs=[time_from, time_to])
|
| 353 |
|
|
|
|
| 354 |
run_btn.click(
|
| 355 |
query_and_render,
|
| 356 |
inputs=[time_from, time_to, sort_dd],
|