Spaces:
Running
Running
更新 6 個檔(discordbot.py、vb_radar.py、vb_qpf.py、north_towns.json…)
Browse files- data/geo/north_towns.json +0 -0
- discordbot.py +12 -5
- vb_qpf.py +232 -104
- vb_radar.py +34 -6
data/geo/north_towns.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
discordbot.py
CHANGED
|
@@ -5743,12 +5743,13 @@ async def cmd_rain(interaction: discord.Interaction, place: Optional[str] = None
|
|
| 5743 |
qpf_task = None
|
| 5744 |
if _qpf is not None and _radar is not None:
|
| 5745 |
def _qpf_job():
|
| 5746 |
-
|
| 5747 |
try:
|
| 5748 |
-
|
|
|
|
| 5749 |
except Exception:
|
| 5750 |
-
|
| 5751 |
-
return _qpf.image_for(p, lat, lon, dict(_wx.TAIPEI_SPOTS),
|
| 5752 |
qpf_task = asyncio.create_task(asyncio.wait_for(asyncio.to_thread(_qpf_job), timeout=45.0))
|
| 5753 |
# 先試 GBM 機率預報;模型檔或歷史不足才退回規則式描述
|
| 5754 |
txt = ""
|
|
@@ -5812,7 +5813,7 @@ async def cmd_rain(interaction: discord.Interaction, place: Optional[str] = None
|
|
| 5812 |
if i == 0:
|
| 5813 |
if png:
|
| 5814 |
import io as _io
|
| 5815 |
-
await interaction.followup.send(chunk, file=discord.File(_io.BytesIO(png), filename="rain_map.
|
| 5816 |
else:
|
| 5817 |
await interaction.followup.send(chunk)
|
| 5818 |
else:
|
|
@@ -9443,6 +9444,12 @@ async def on_ready():
|
|
| 9443 |
_FR.start(SUPABASE_URL, SUPABASE_KEY, cwa=bool(CWA_API_KEY))
|
| 9444 |
except Exception as _fr_e:
|
| 9445 |
print(f"逐時存檔啟動失敗:{_fr_e}", flush=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9446 |
# ── 看門狗:任何累積器 24 小時沒成功 → 提醒頻道講一聲;恢復也講。/health 有「看門狗」一行。──
|
| 9447 |
try:
|
| 9448 |
import vb_watchdog as _WD
|
|
|
|
| 5743 |
qpf_task = None
|
| 5744 |
if _qpf is not None and _radar is not None:
|
| 5745 |
def _qpf_job():
|
| 5746 |
+
frames = []
|
| 5747 |
try:
|
| 5748 |
+
_radar.grid() # 確保最新一張在快取
|
| 5749 |
+
frames = _radar.history(_qpf.PAST_FRAMES) # 過去一小時每 10 分鐘(背景執行緒平時就在補)
|
| 5750 |
except Exception:
|
| 5751 |
+
frames = []
|
| 5752 |
+
return _qpf.image_for(p, lat, lon, dict(_wx.TAIPEI_SPOTS), frames)
|
| 5753 |
qpf_task = asyncio.create_task(asyncio.wait_for(asyncio.to_thread(_qpf_job), timeout=45.0))
|
| 5754 |
# 先試 GBM 機率預報;模型檔或歷史不足才退回規則式描述
|
| 5755 |
txt = ""
|
|
|
|
| 5813 |
if i == 0:
|
| 5814 |
if png:
|
| 5815 |
import io as _io
|
| 5816 |
+
await interaction.followup.send(chunk, file=discord.File(_io.BytesIO(png), filename="rain_map.gif"))
|
| 5817 |
else:
|
| 5818 |
await interaction.followup.send(chunk)
|
| 5819 |
else:
|
|
|
|
| 9444 |
_FR.start(SUPABASE_URL, SUPABASE_KEY, cwa=bool(CWA_API_KEY))
|
| 9445 |
except Exception as _fr_e:
|
| 9446 |
print(f"逐時存檔啟動失敗:{_fr_e}", flush=True)
|
| 9447 |
+
# ── /rain 附圖的背景抓取(2026-09-11):每 10 分鐘一張雷達進 vb_radar 快取、一張 QPESUMS 預報;開機回填最近 6 張 ──
|
| 9448 |
+
try:
|
| 9449 |
+
if _qpf is not None and CWA_API_KEY:
|
| 9450 |
+
_qpf.start()
|
| 9451 |
+
except Exception as _qp_e:
|
| 9452 |
+
print(f"預報圖背景抓取啟動失敗:{_qp_e}", flush=True)
|
| 9453 |
# ── 看門狗:任何累積器 24 小時沒成功 → 提醒頻道講一聲;恢復也講。/health 有「看門狗」一行。──
|
| 9454 |
try:
|
| 9455 |
import vb_watchdog as _WD
|
vb_qpf.py
CHANGED
|
@@ -1,14 +1,17 @@
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
-
"""/rain 的附圖:以你選的位置為中心
|
| 3 |
-
(氣象署 QPESUMS 雷達定量降雨預報 F-B0046-001)。
|
| 4 |
-
|
| 5 |
-
★資料源(2026-09-11 查證):
|
| 6 |
-
格點 441×561、0.0125°、起點 118E/20N
|
| 7 |
-
|
| 8 |
-
★
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
| 12 |
"""
|
| 13 |
import datetime as dt
|
| 14 |
import io
|
|
@@ -28,14 +31,28 @@ TTL_SEC = 600
|
|
| 28 |
MAX_LAG_MIN = 75 # 產品時間離現在太久就不當「未來 1 小時」用
|
| 29 |
MISSING = -90.0
|
| 30 |
RADIUS_KM = 25.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
TW_TZ = dt.timezone(dt.timedelta(hours=8))
|
| 32 |
UA = {"User-Agent": "vanilla-bot qpf/1.0"}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
_CACHE: Dict[str, Any] = {"at": 0.0, "grid": None}
|
| 35 |
-
_STATUS: Dict[str, Any] = {"n_ok": 0, "n_fail": 0, "last_ok": None, "last_err": ""
|
|
|
|
| 36 |
_LOCK = threading.Lock()
|
|
|
|
|
|
|
| 37 |
|
| 38 |
-
Grid = Tuple[str, np.ndarray, np.ndarray, np.ndarray] # (
|
| 39 |
|
| 40 |
|
| 41 |
def _mask(s: Any) -> str:
|
|
@@ -50,6 +67,7 @@ def _now_tw() -> dt.datetime:
|
|
| 50 |
return dt.datetime.now(TW_TZ).replace(tzinfo=None)
|
| 51 |
|
| 52 |
|
|
|
|
| 53 |
def parse(doc: Dict[str, Any]) -> Optional[Grid]:
|
| 54 |
"""fileapi 的 JSON → 格點;規格認不出回 None(不猜)。"""
|
| 55 |
try:
|
|
@@ -106,6 +124,7 @@ def fetch(get=None, now: Optional[float] = None) -> Optional[Grid]:
|
|
| 106 |
return g
|
| 107 |
|
| 108 |
|
|
|
|
| 109 |
def crop(g: Grid, lat: float, lon: float, radius_km: float = RADIUS_KM) -> Optional[Tuple[np.ndarray, np.ndarray, np.ndarray]]:
|
| 110 |
"""裁出 (lat±, lon±) 的子格點。回 (lat 軸, lon 軸, 值);位置在框外回 None。"""
|
| 111 |
_ts, LA, LO, V = g
|
|
@@ -119,7 +138,7 @@ def crop(g: Grid, lat: float, lon: float, radius_km: float = RADIUS_KM) -> Optio
|
|
| 119 |
|
| 120 |
|
| 121 |
def grid_from_points(ts: str, la: np.ndarray, lo: np.ndarray, va: np.ndarray) -> Optional[Grid]:
|
| 122 |
-
"""vb_radar
|
| 123 |
la, lo, va = np.asarray(la, dtype=np.float64), np.asarray(lo, dtype=np.float64), np.asarray(va, dtype=np.float32)
|
| 124 |
ula, ulo = np.unique(np.round(la, 4)), np.unique(np.round(lo, 4))
|
| 125 |
if ula.size * ulo.size != la.size:
|
|
@@ -153,85 +172,23 @@ def summary(g: Grid, lat: float, lon: float) -> Dict[str, Optional[float]]:
|
|
| 153 |
return {"q3": q3, "q20": q20, "dir": dirs[int((ang + 22.5) // 45) % 8], "d20": float(dkm[iy, ix])}
|
| 154 |
|
| 155 |
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
ax.plot(r * np.cos(th), r * np.sin(th), color="#445", lw=0.6, ls="--", alpha=0.7)
|
| 169 |
-
ax.text(r * 0.72, r * 0.72, "%d km" % r, fontsize=7, color="#445", alpha=0.8)
|
| 170 |
-
for name, (la2, lo2) in landmarks.items():
|
| 171 |
-
x, y = (lo2 - lon) * 111.32 * cos, (la2 - lat) * 110.6
|
| 172 |
-
if abs(x) < RADIUS_KM and abs(y) < RADIUS_KM and math.hypot(x, y) > 5.0: # 中心 5 km 內的地標不標,免得跟 X 擠成一團
|
| 173 |
-
ax.plot(x, y, "o", ms=2.5, color="#333")
|
| 174 |
-
ax.text(x + 0.6, y + 0.6, name, fontsize=7, color="#333")
|
| 175 |
-
ax.plot(0, 0, "x", ms=11, mew=2.2, color="#d00000")
|
| 176 |
-
ax.set_xlim(-RADIUS_KM, RADIUS_KM)
|
| 177 |
-
ax.set_ylim(-RADIUS_KM, RADIUS_KM)
|
| 178 |
-
ax.set_aspect("equal")
|
| 179 |
-
ax.set_xticks([-20, -10, 0, 10, 20])
|
| 180 |
-
ax.set_yticks([-20, -10, 0, 10, 20])
|
| 181 |
-
ax.tick_params(labelsize=7)
|
| 182 |
-
ax.set_xlabel("東西 (km)", fontsize=8)
|
| 183 |
-
ax.set_title(title, fontsize=9.5)
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
def render(place: str, lat: float, lon: float, qpf: Optional[Grid], now: Optional[Grid],
|
| 187 |
-
landmarks: Optional[Dict[str, Tuple[float, float]]] = None) -> Optional[bytes]:
|
| 188 |
-
"""左「現在」右「未來 1 小時」的 PNG;兩張都沒有回 None。"""
|
| 189 |
-
if qpf is None and now is None:
|
| 190 |
-
return None
|
| 191 |
-
import matplotlib
|
| 192 |
-
matplotlib.use("Agg")
|
| 193 |
-
import matplotlib.pyplot as plt
|
| 194 |
-
fnt = _cjk_font()
|
| 195 |
-
if fnt:
|
| 196 |
-
plt.rcParams["font.family"] = fnt
|
| 197 |
-
plt.rcParams["axes.unicode_minus"] = False
|
| 198 |
-
subs = []
|
| 199 |
-
if now is not None:
|
| 200 |
-
c = crop(now, lat, lon)
|
| 201 |
-
if c is not None:
|
| 202 |
-
subs.append((c, "現在:雷達過去 1 小時實測(NCDR %s)" % _hhmm(now[0])))
|
| 203 |
-
if qpf is not None:
|
| 204 |
-
c = crop(qpf, lat, lon)
|
| 205 |
-
if c is not None:
|
| 206 |
-
subs.append((c, "未來 1 小時:QPESUMS 雷達預報(氣象署 %s 起算)" % _hhmm(qpf[0])))
|
| 207 |
-
if not subs:
|
| 208 |
-
return None
|
| 209 |
-
vmax = max(10.0, float(np.nanmax([np.nanmax(s[0][2]) if np.isfinite(s[0][2]).any() else 0.0 for s in subs])))
|
| 210 |
-
vmax = float(min(80.0, math.ceil(vmax / 5.0) * 5.0))
|
| 211 |
-
fig, axes = plt.subplots(1, len(subs), figsize=(4.6 * len(subs) + 0.9, 4.9), dpi=130)
|
| 212 |
-
axes = np.atleast_1d(axes)
|
| 213 |
-
for ax, (sub, title) in zip(axes, subs):
|
| 214 |
-
_panel(ax, sub, lat, lon, title, landmarks or {}, vmax)
|
| 215 |
-
axes[0].set_ylabel("南北 (km)", fontsize=8)
|
| 216 |
-
import matplotlib.colors as mcolors
|
| 217 |
-
import matplotlib.cm as cm
|
| 218 |
-
sm = cm.ScalarMappable(norm=mcolors.Normalize(0.5, vmax), cmap=axes[0].collections[0].get_cmap())
|
| 219 |
-
cb = fig.colorbar(sm, ax=axes.tolist(), fraction=0.03, pad=0.02)
|
| 220 |
-
cb.set_label("mm(一小時)", fontsize=8)
|
| 221 |
-
cb.ax.tick_params(labelsize=7)
|
| 222 |
-
fig.suptitle("%s 周圍 ±%d km 紅色 X=你的位置" % (place, int(RADIUS_KM)), fontsize=10)
|
| 223 |
-
buf = io.BytesIO()
|
| 224 |
-
fig.savefig(buf, format="png", bbox_inches="tight")
|
| 225 |
-
plt.close(fig)
|
| 226 |
-
return buf.getvalue()
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
_FONT: Dict[str, Optional[str]] = {"name": None}
|
| 230 |
|
| 231 |
|
| 232 |
def _cjk_font() -> str:
|
| 233 |
"""中日韓字體:跟 /sb chart 同一套——Windows 微軟正黑、Space 是 Dockerfile 單檔抓的 Noto CJK TC。
|
| 234 |
-
★要用 addfont 明確登記:matplotlib 的字體快取不一定掃到 /usr/share/fonts/opentype/noto。找不到回空字串
|
| 235 |
if _FONT["name"] is not None:
|
| 236 |
return _FONT["name"]
|
| 237 |
from matplotlib import font_manager
|
|
@@ -250,6 +207,83 @@ def _cjk_font() -> str:
|
|
| 250 |
return ""
|
| 251 |
|
| 252 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
def _hhmm(ts: str) -> str:
|
| 254 |
try:
|
| 255 |
return dt.datetime.strptime(ts, "%Y%m%d%H%M").strftime("%H:%M")
|
|
@@ -257,10 +291,39 @@ def _hhmm(ts: str) -> str:
|
|
| 257 |
return ts
|
| 258 |
|
| 259 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
def lines(qpf: Optional[Grid], lat: float, lon: float, now_tw: Optional[dt.datetime] = None) -> List[str]:
|
| 261 |
"""圖下面那幾行字。"""
|
| 262 |
if qpf is None:
|
| 263 |
-
return [" 🗺 附圖:
|
| 264 |
t0 = dt.datetime.strptime(qpf[0], "%Y%m%d%H%M")
|
| 265 |
lag = int(((now_tw or _now_tw()) - t0).total_seconds() // 60)
|
| 266 |
if lag > MAX_LAG_MIN:
|
|
@@ -276,35 +339,100 @@ def lines(qpf: Optional[Grid], lat: float, lon: float, now_tw: Optional[dt.datet
|
|
| 276 |
if s.get("q20") and s["q20"] >= 0.5:
|
| 277 |
head += ";最近的預報雨區 %s方 %.0f km(%.1f mm)" % (s["dir"], s["d20"], s["q20"])
|
| 278 |
return [head,
|
| 279 |
-
" -# 圖:
|
| 280 |
-
"**還沒生成的對流它看不到**——那是上面機率在補的那一塊;
|
| 281 |
|
| 282 |
|
| 283 |
def image_for(place: str, lat: float, lon: float, landmarks: Optional[Dict[str, Tuple[float, float]]] = None,
|
| 284 |
-
|
| 285 |
-
"""/rain 用的一站式:抓 QPF(快取)、把雷達點列表排成格點、畫
|
| 286 |
qpf = fetch()
|
| 287 |
-
|
| 288 |
-
|
| 289 |
try:
|
| 290 |
-
|
|
|
|
|
|
|
| 291 |
except Exception:
|
| 292 |
-
|
| 293 |
try:
|
| 294 |
-
|
|
|
|
| 295 |
except Exception as e:
|
| 296 |
-
_STATUS["
|
| 297 |
-
|
| 298 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
|
| 300 |
|
| 301 |
def line() -> str:
|
| 302 |
st = _STATUS
|
| 303 |
-
return "QPESUMS 一小時預報圖(F-B0046-001):抓取 成功 %d 失敗 %d、最近
|
| 304 |
-
st["n_ok"], st["n_fail"], st["last_ok"] or "無",
|
|
|
|
|
|
|
| 305 |
|
| 306 |
|
| 307 |
def reset() -> None:
|
| 308 |
with _LOCK:
|
| 309 |
_CACHE.update(at=0.0, grid=None)
|
| 310 |
-
_STATUS.update(n_ok=0, n_fail=0, last_ok=None, last_err="")
|
|
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
+
"""/rain 的附圖(動態 GIF):以你選的位置為中心、氣象署 App 那種黑底行政區底圖,過去一小時每 10 分鐘一張雷達實測
|
| 3 |
+
(NCDR QPE),最後一張是「未來 1 小時」(氣象署 QPESUMS 雷達定量降雨預報 F-B0046-001)。
|
| 4 |
+
|
| 5 |
+
★資料源(2026-09-11 查證):
|
| 6 |
+
· F-B0046-001「未來1小時雷達定量降雨預報」:fileapi JSON,每 10 分鐘一張,格點 441×561、0.0125°、起點 118E/20N
|
| 7 |
+
(跟 O-B0045-001 QPE 同一個框),值 mm、缺值 −99。DateTime 是起算時間,預報的是接下來一小時的累積雨量。
|
| 8 |
+
★只有「一小時累積」一種——NCDR 與氣象署都沒有 10 分鐘一步的預報格點(2026-09-11 探過 polaqpf/polaqpn 各種名稱都 404),
|
| 9 |
+
所以動畫的「未來」只有一張,會停久一點。
|
| 10 |
+
· 過去一小時:vb_radar 的 10 分鐘 QPE(NCDR polaqpe_01,滾動一小時累積)。`start()` 開一條背景執行緒每 10 分鐘抓一張、
|
| 11 |
+
開機先回填最近 6 張(每張隔 20 秒,對 NCDR 的禮貌間隔跟 wx_qpe 一樣),/rain 畫圖時直接用快取,不多打。
|
| 12 |
+
★它是**雷達外推**:對已經存在、正在移動的雨很準;對還沒生成的對流看不到——那正是模型補的那一塊,文字要講。
|
| 13 |
+
★底圖:`data/geo/north_towns.json`(wx_geo_build.py 從 g0v/twgeojson(CC0)裁的北台灣鄉鎮/縣市界線),沒有這個檔就只畫格點。
|
| 14 |
+
★色階:仿氣象署雨量圖的分級(mm),寫死在 BINS/COLORS。
|
| 15 |
"""
|
| 16 |
import datetime as dt
|
| 17 |
import io
|
|
|
|
| 31 |
MAX_LAG_MIN = 75 # 產品時間離現在太久就不當「未來 1 小時」用
|
| 32 |
MISSING = -90.0
|
| 33 |
RADIUS_KM = 25.0
|
| 34 |
+
PAST_FRAMES = 6 # 過去一小時:6 張 10 分鐘格點
|
| 35 |
+
FRAME_MS = 650 # 動畫每張停多久
|
| 36 |
+
LAST_MS = 2600 # 「未來 1 小時」那張停多久
|
| 37 |
+
GEO_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "geo", "north_towns.json")
|
| 38 |
+
KEEPER_EVERY = 600
|
| 39 |
+
KEEPER_FIRST_DELAY = 45
|
| 40 |
+
BACKFILL_GAP = 20.0
|
| 41 |
TW_TZ = dt.timezone(dt.timedelta(hours=8))
|
| 42 |
UA = {"User-Agent": "vanilla-bot qpf/1.0"}
|
| 43 |
+
# 仿氣象署雨量色階(mm/小時累積):邊界與顏色一一對應(len(COLORS) == len(BINS) - 1)
|
| 44 |
+
BINS = [0.5, 1, 2, 5, 10, 15, 20, 30, 40, 50, 70, 100, 150, 200]
|
| 45 |
+
COLORS = ["#5f5a7a", "#8d8d8d", "#0b6b0b", "#149914", "#3ce03c", "#f5f500", "#ffb400",
|
| 46 |
+
"#ff6a00", "#ff1f1f", "#c40000", "#ff33ff", "#b400c8", "#5a0080"]
|
| 47 |
|
| 48 |
_CACHE: Dict[str, Any] = {"at": 0.0, "grid": None}
|
| 49 |
+
_STATUS: Dict[str, Any] = {"n_ok": 0, "n_fail": 0, "last_ok": None, "last_err": "", "keeper": False,
|
| 50 |
+
"frames": 0, "renders": 0, "render_err": ""}
|
| 51 |
_LOCK = threading.Lock()
|
| 52 |
+
_GEO: Dict[str, Any] = {"path": None, "data": None}
|
| 53 |
+
_FONT: Dict[str, Optional[str]] = {"name": None}
|
| 54 |
|
| 55 |
+
Grid = Tuple[str, np.ndarray, np.ndarray, np.ndarray] # (時間 'YYYYMMDDHHMM' 台灣, lat[ny], lon[nx], val[ny,nx])
|
| 56 |
|
| 57 |
|
| 58 |
def _mask(s: Any) -> str:
|
|
|
|
| 67 |
return dt.datetime.now(TW_TZ).replace(tzinfo=None)
|
| 68 |
|
| 69 |
|
| 70 |
+
# ── 預報格點 ───────────────────────────────────────────────────────
|
| 71 |
def parse(doc: Dict[str, Any]) -> Optional[Grid]:
|
| 72 |
"""fileapi 的 JSON → 格點;規格認不出回 None(不猜)。"""
|
| 73 |
try:
|
|
|
|
| 124 |
return g
|
| 125 |
|
| 126 |
|
| 127 |
+
# ── 格點工具 ──────────────────────────────────────────��────────────
|
| 128 |
def crop(g: Grid, lat: float, lon: float, radius_km: float = RADIUS_KM) -> Optional[Tuple[np.ndarray, np.ndarray, np.ndarray]]:
|
| 129 |
"""裁出 (lat±, lon±) 的子格點。回 (lat 軸, lon 軸, 值);位置在框外回 None。"""
|
| 130 |
_ts, LA, LO, V = g
|
|
|
|
| 138 |
|
| 139 |
|
| 140 |
def grid_from_points(ts: str, la: np.ndarray, lo: np.ndarray, va: np.ndarray) -> Optional[Grid]:
|
| 141 |
+
"""vb_radar 給的是點列表(lat/lon/val 各一維、只有盆地框)→ 排成規則格點。格點不規則就回 None。"""
|
| 142 |
la, lo, va = np.asarray(la, dtype=np.float64), np.asarray(lo, dtype=np.float64), np.asarray(va, dtype=np.float32)
|
| 143 |
ula, ulo = np.unique(np.round(la, 4)), np.unique(np.round(lo, 4))
|
| 144 |
if ula.size * ulo.size != la.size:
|
|
|
|
| 172 |
return {"q3": q3, "q20": q20, "dir": dirs[int((ang + 22.5) // 45) % 8], "d20": float(dkm[iy, ix])}
|
| 173 |
|
| 174 |
|
| 175 |
+
# ── 底圖 ───────────────────────────────────────────────────────────
|
| 176 |
+
def load_geo(path: Optional[str] = None) -> Optional[Dict[str, Any]]:
|
| 177 |
+
p = path or GEO_PATH
|
| 178 |
+
if _GEO["path"] == p:
|
| 179 |
+
return _GEO["data"]
|
| 180 |
+
try:
|
| 181 |
+
with open(p, encoding="utf-8") as f:
|
| 182 |
+
d = json.load(f)
|
| 183 |
+
except (OSError, ValueError):
|
| 184 |
+
d = None
|
| 185 |
+
_GEO.update(path=p, data=d)
|
| 186 |
+
return d
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
|
| 188 |
|
| 189 |
def _cjk_font() -> str:
|
| 190 |
"""中日韓字體:跟 /sb chart 同一套——Windows 微軟正黑、Space 是 Dockerfile 單檔抓的 Noto CJK TC。
|
| 191 |
+
★要用 addfont 明確登記:matplotlib 的字體快取不一定掃到 /usr/share/fonts/opentype/noto。找不到回空字串。"""
|
| 192 |
if _FONT["name"] is not None:
|
| 193 |
return _FONT["name"]
|
| 194 |
from matplotlib import font_manager
|
|
|
|
| 207 |
return ""
|
| 208 |
|
| 209 |
|
| 210 |
+
def _km_xy(lat: float, lon: float, la2, lo2):
|
| 211 |
+
cos = math.cos(math.radians(lat))
|
| 212 |
+
return (np.asarray(lo2, dtype=float) - lon) * 111.32 * cos, (np.asarray(la2, dtype=float) - lat) * 110.6
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def _draw_frame(place: str, lat: float, lon: float, sub, title: str, tag: str, geo: Optional[Dict[str, Any]]):
|
| 216 |
+
"""一張影格(PIL.Image,RGB)。黑底、行政區界線、鄉鎮名、雨量格點、紅 X。"""
|
| 217 |
+
import matplotlib
|
| 218 |
+
matplotlib.use("Agg")
|
| 219 |
+
import matplotlib.cm as mcm
|
| 220 |
+
import matplotlib.colors as mcolors
|
| 221 |
+
from matplotlib.figure import Figure
|
| 222 |
+
from PIL import Image
|
| 223 |
+
fnt = _cjk_font()
|
| 224 |
+
if fnt:
|
| 225 |
+
matplotlib.rcParams["font.family"] = fnt
|
| 226 |
+
matplotlib.rcParams["axes.unicode_minus"] = False
|
| 227 |
+
R = RADIUS_KM
|
| 228 |
+
fig = Figure(figsize=(6.4, 6.4), dpi=105, facecolor="#101010")
|
| 229 |
+
ax = fig.add_axes([0.02, 0.02, 0.84, 0.90])
|
| 230 |
+
ax.set_facecolor("#000000")
|
| 231 |
+
cmap = mcolors.ListedColormap(COLORS)
|
| 232 |
+
norm = mcolors.BoundaryNorm(BINS, cmap.N)
|
| 233 |
+
if sub is not None:
|
| 234 |
+
LA, LO, V = sub
|
| 235 |
+
X, Y = _km_xy(lat, lon, LA, LO)
|
| 236 |
+
Vp = np.where(np.isfinite(V) & (V >= BINS[0]), V, np.nan)
|
| 237 |
+
ax.pcolormesh(X, Y, Vp, cmap=cmap, norm=norm, shading="nearest", zorder=1)
|
| 238 |
+
if geo:
|
| 239 |
+
for t in geo.get("towns") or []:
|
| 240 |
+
for ring in t["rings"]:
|
| 241 |
+
arr = np.asarray(ring, dtype=float)
|
| 242 |
+
x, y = _km_xy(lat, lon, arr[:, 1], arr[:, 0])
|
| 243 |
+
if (np.abs(x) < R * 1.3).any() and (np.abs(y) < R * 1.3).any():
|
| 244 |
+
ax.plot(x, y, color="#9a9a9a", lw=0.55, alpha=0.9, zorder=2)
|
| 245 |
+
big = max(t["rings"], key=len) # 名字放最大那個環的中心
|
| 246 |
+
arr = np.asarray(big, dtype=float)
|
| 247 |
+
bx, by = _km_xy(lat, lon, arr[:, 1], arr[:, 0])
|
| 248 |
+
cx, cy = float(bx.mean()), float(by.mean())
|
| 249 |
+
span = max(float(bx.max() - bx.min()), float(by.max() - by.min()))
|
| 250 |
+
# ★太小的區(市中心那幾個 2–3 km 寬的)名字會疊在一起,不標;離 X 太近的也不標
|
| 251 |
+
if span >= 3.5 and abs(cx) < R * 0.96 and abs(cy) < R * 0.96 and math.hypot(cx, cy) > 2.0:
|
| 252 |
+
ax.text(cx, cy, t["n"], fontsize=7, color="#e6e6e6", ha="center", va="center", zorder=4, alpha=0.95)
|
| 253 |
+
for c in geo.get("counties") or []:
|
| 254 |
+
for ring in c["rings"]:
|
| 255 |
+
arr = np.asarray(ring, dtype=float)
|
| 256 |
+
x, y = _km_xy(lat, lon, arr[:, 1], arr[:, 0])
|
| 257 |
+
if (np.abs(x) < R * 1.3).any() and (np.abs(y) < R * 1.3).any():
|
| 258 |
+
ax.plot(x, y, color="#ffffff", lw=1.4, alpha=0.95, zorder=3)
|
| 259 |
+
for r in (10, 20):
|
| 260 |
+
th = np.linspace(0, 2 * math.pi, 120)
|
| 261 |
+
ax.plot(r * np.cos(th), r * np.sin(th), color="#66aaff", lw=0.5, ls=":", alpha=0.6, zorder=3)
|
| 262 |
+
ax.text(r * 0.707, r * 0.707, "%d km" % r, fontsize=6.5, color="#66aaff", alpha=0.8, zorder=4)
|
| 263 |
+
ax.plot(0, 0, "x", ms=12, mew=2.6, color="#ff2020", zorder=6)
|
| 264 |
+
ax.text(0.9, 0.9, place, fontsize=9, color="#ff5050", fontweight="bold", zorder=6)
|
| 265 |
+
ax.set_xlim(-R, R)
|
| 266 |
+
ax.set_ylim(-R, R)
|
| 267 |
+
ax.set_aspect("equal")
|
| 268 |
+
ax.set_xticks([])
|
| 269 |
+
ax.set_yticks([])
|
| 270 |
+
for sp in ax.spines.values():
|
| 271 |
+
sp.set_edgecolor("#333")
|
| 272 |
+
ax.set_title(title, fontsize=10, color="#f0f0f0", pad=6)
|
| 273 |
+
ax.text(0.01, 0.985, tag, transform=ax.transAxes, fontsize=8, color="#bbbbbb", va="top", zorder=7,
|
| 274 |
+
bbox=dict(boxstyle="round,pad=0.25", fc="#202020", ec="#444", alpha=0.85))
|
| 275 |
+
cax = fig.add_axes([0.885, 0.08, 0.03, 0.78])
|
| 276 |
+
cb = fig.colorbar(mcm.ScalarMappable(norm=norm, cmap=cmap), cax=cax, boundaries=BINS, ticks=BINS, spacing="uniform")
|
| 277 |
+
cb.ax.set_yticklabels(["%g" % b for b in BINS], fontsize=6.5, color="#dddddd")
|
| 278 |
+
cb.ax.tick_params(length=0)
|
| 279 |
+
cb.outline.set_edgecolor("#444")
|
| 280 |
+
cb.set_label("mm/小時", fontsize=7.5, color="#dddddd")
|
| 281 |
+
buf = io.BytesIO()
|
| 282 |
+
fig.savefig(buf, format="png", facecolor=fig.get_facecolor())
|
| 283 |
+
buf.seek(0)
|
| 284 |
+
return Image.open(buf).convert("RGB")
|
| 285 |
+
|
| 286 |
+
|
| 287 |
def _hhmm(ts: str) -> str:
|
| 288 |
try:
|
| 289 |
return dt.datetime.strptime(ts, "%Y%m%d%H%M").strftime("%H:%M")
|
|
|
|
| 291 |
return ts
|
| 292 |
|
| 293 |
|
| 294 |
+
def render(place: str, lat: float, lon: float, qpf: Optional[Grid], frames: Optional[List[Grid]],
|
| 295 |
+
landmarks: Optional[Dict[str, Tuple[float, float]]] = None, geo: Optional[Dict[str, Any]] = None) -> Optional[bytes]:
|
| 296 |
+
"""動態 GIF:過去一小時每 10 分鐘一張(由舊到新)→ 最後一張「未來 1 小時」停久一點。什麼都沒有回 None。
|
| 297 |
+
landmarks 保留參數相容(底圖有鄉鎮名之後不再另外標)。"""
|
| 298 |
+
seq: List[Tuple[Any, str, str, int]] = []
|
| 299 |
+
past = [f for f in (frames or []) if crop(f, lat, lon) is not None][-PAST_FRAMES:]
|
| 300 |
+
for i, f in enumerate(past, 1):
|
| 301 |
+
seq.append((crop(f, lat, lon), "過去 1 小時累積雨量 至 %s(NCDR 雷達實測)" % _hhmm(f[0]),
|
| 302 |
+
"實測 %d/%d" % (i, len(past)), FRAME_MS))
|
| 303 |
+
if qpf is not None and crop(qpf, lat, lon) is not None:
|
| 304 |
+
t0 = dt.datetime.strptime(qpf[0], "%Y%m%d%H%M")
|
| 305 |
+
t1 = t0 + dt.timedelta(hours=1)
|
| 306 |
+
seq.append((crop(qpf, lat, lon), "未來 1 小時預報 %s–%s(氣象署 QPESUMS 雷達外推)" % (_hhmm(qpf[0]), t1.strftime("%H:%M")),
|
| 307 |
+
"未來 1 小時", LAST_MS))
|
| 308 |
+
if not seq:
|
| 309 |
+
return None
|
| 310 |
+
geo = geo if geo is not None else load_geo()
|
| 311 |
+
imgs = []
|
| 312 |
+
for sub, title, tag, _ms in seq:
|
| 313 |
+
im = _draw_frame(place, lat, lon, sub, title, tag, geo)
|
| 314 |
+
imgs.append(im.quantize(colors=160, method=0))
|
| 315 |
+
out = io.BytesIO()
|
| 316 |
+
imgs[0].save(out, format="GIF", save_all=True, append_images=imgs[1:], duration=[s[3] for s in seq], loop=0,
|
| 317 |
+
optimize=False, disposal=2)
|
| 318 |
+
_STATUS["renders"] += 1
|
| 319 |
+
_STATUS["frames"] = len(seq)
|
| 320 |
+
return out.getvalue()
|
| 321 |
+
|
| 322 |
+
|
| 323 |
def lines(qpf: Optional[Grid], lat: float, lon: float, now_tw: Optional[dt.datetime] = None) -> List[str]:
|
| 324 |
"""圖下面那幾行字。"""
|
| 325 |
if qpf is None:
|
| 326 |
+
return [" 🗺 附圖:過去 1 小時雷達實測;QPESUMS 未來 1 小時預報這次抓不到"]
|
| 327 |
t0 = dt.datetime.strptime(qpf[0], "%Y%m%d%H%M")
|
| 328 |
lag = int(((now_tw or _now_tw()) - t0).total_seconds() // 60)
|
| 329 |
if lag > MAX_LAG_MIN:
|
|
|
|
| 339 |
if s.get("q20") and s["q20"] >= 0.5:
|
| 340 |
head += ";最近的預報雨區 %s方 %.0f km(%.1f mm)" % (s["dir"], s["d20"], s["q20"])
|
| 341 |
return [head,
|
| 342 |
+
" -# 動圖:前幾張=過去一小時每 10 分鐘的實測,最後一張=未來 1 小時外推。外推只會移動已經存在的雨,"
|
| 343 |
+
"**還沒生成的對流它看不到**——那是上面機率在補的那一塊;最後一張沒雨不等於不會下"]
|
| 344 |
|
| 345 |
|
| 346 |
def image_for(place: str, lat: float, lon: float, landmarks: Optional[Dict[str, Tuple[float, float]]] = None,
|
| 347 |
+
radar_frames: Optional[List[Tuple]] = None) -> Tuple[Optional[bytes], Optional[Grid]]:
|
| 348 |
+
"""/rain 用的一站式:抓 QPF(快取)、把雷達點列表排成格點、畫 GIF。回 (gif 或 None, qpf 格點或 None)。"""
|
| 349 |
qpf = fetch()
|
| 350 |
+
frames: List[Grid] = []
|
| 351 |
+
for rg in radar_frames or []:
|
| 352 |
try:
|
| 353 |
+
g = grid_from_points(rg[0], rg[1], rg[2], rg[3])
|
| 354 |
+
if g is not None:
|
| 355 |
+
frames.append(g)
|
| 356 |
except Exception:
|
| 357 |
+
continue
|
| 358 |
try:
|
| 359 |
+
gif = render(place, lat, lon, qpf, frames, landmarks)
|
| 360 |
+
_STATUS["render_err"] = ""
|
| 361 |
except Exception as e:
|
| 362 |
+
_STATUS["render_err"] = _mask("%s: %s" % (type(e).__name__, str(e)[:80]))
|
| 363 |
+
gif = None
|
| 364 |
+
return gif, qpf
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
# ── 背景:每 10 分鐘抓一張雷達(進 vb_radar 的快取)與一張預報,開機回填最近 6 張 ─────────
|
| 368 |
+
_K: Dict[str, Any] = {"thread": None}
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def keeper_once(backfill: bool = False, sleep=time.sleep) -> int:
|
| 372 |
+
"""抓最新雷達+預報;backfill=True 先把最近 PAST_FRAMES 張缺的補齊(每張隔 BACKFILL_GAP 秒)。回這次抓到幾張雷達。"""
|
| 373 |
+
import vb_radar as RD
|
| 374 |
+
n = 0
|
| 375 |
+
if backfill:
|
| 376 |
+
now = _now_tw() - dt.timedelta(minutes=RD.LAG_MIN)
|
| 377 |
+
now = now.replace(minute=(now.minute // 10) * 10, second=0, microsecond=0)
|
| 378 |
+
want = [(now - dt.timedelta(minutes=10 * k)).strftime("%Y%m%d%H%M") for k in range(PAST_FRAMES - 1, -1, -1)]
|
| 379 |
+
have = {f[0] for f in RD.history(PAST_FRAMES + 2)}
|
| 380 |
+
for ts in want:
|
| 381 |
+
if ts in have:
|
| 382 |
+
continue
|
| 383 |
+
if n:
|
| 384 |
+
sleep(BACKFILL_GAP)
|
| 385 |
+
if RD.ensure(ts) is not None:
|
| 386 |
+
n += 1
|
| 387 |
+
else:
|
| 388 |
+
if RD.grid() is not None:
|
| 389 |
+
n += 1
|
| 390 |
+
fetch()
|
| 391 |
+
_STATUS["frames"] = len(RD.history(PAST_FRAMES))
|
| 392 |
+
return n
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def start(log=lambda s: print(s, flush=True)) -> bool:
|
| 396 |
+
if _K["thread"] is not None:
|
| 397 |
+
return False
|
| 398 |
+
if os.getenv("WX_QPF", "on").strip().lower() == "off":
|
| 399 |
+
log("[預報圖] WX_QPF=off,不啟動背景抓取(/rain 仍會現抓當下那張)")
|
| 400 |
+
return False
|
| 401 |
+
|
| 402 |
+
def _loop() -> None:
|
| 403 |
+
time.sleep(KEEPER_FIRST_DELAY)
|
| 404 |
+
first = True
|
| 405 |
+
while True:
|
| 406 |
+
try:
|
| 407 |
+
keeper_once(backfill=first)
|
| 408 |
+
first = False
|
| 409 |
+
except Exception as e:
|
| 410 |
+
_STATUS["last_err"] = _mask("keeper %s: %s" % (type(e).__name__, str(e)[:80]))
|
| 411 |
+
try:
|
| 412 |
+
import vb_quiet as Q
|
| 413 |
+
Q.quiet("qpf.keeper", e)
|
| 414 |
+
except Exception:
|
| 415 |
+
pass
|
| 416 |
+
time.sleep(KEEPER_EVERY)
|
| 417 |
+
t = threading.Thread(target=_loop, daemon=True, name="vb_qpf")
|
| 418 |
+
t.start()
|
| 419 |
+
_K["thread"] = t
|
| 420 |
+
_STATUS["keeper"] = True
|
| 421 |
+
log("[預報圖] 已啟動:開機回填最近 %d 張雷達(每張隔 %.0f 秒),之後每 %d 秒抓一張雷達+一張 QPESUMS 預報" % (
|
| 422 |
+
PAST_FRAMES, BACKFILL_GAP, KEEPER_EVERY))
|
| 423 |
+
return True
|
| 424 |
|
| 425 |
|
| 426 |
def line() -> str:
|
| 427 |
st = _STATUS
|
| 428 |
+
return "QPESUMS 一小時預報圖(F-B0046-001):預報抓取 成功 %d 失敗 %d、最近 %s;雷達影格 %d 張在快取;畫過 %d 次%s%s" % (
|
| 429 |
+
st["n_ok"], st["n_fail"], st["last_ok"] or "無", st["frames"], st["renders"],
|
| 430 |
+
(";最近錯誤 " + st["last_err"]) if st["last_err"] else "",
|
| 431 |
+
(";畫圖錯誤 " + st["render_err"]) if st["render_err"] else "")
|
| 432 |
|
| 433 |
|
| 434 |
def reset() -> None:
|
| 435 |
with _LOCK:
|
| 436 |
_CACHE.update(at=0.0, grid=None)
|
| 437 |
+
_STATUS.update(n_ok=0, n_fail=0, last_ok=None, last_err="", frames=0, renders=0, render_err="")
|
| 438 |
+
_GEO.update(path=None, data=None)
|
vb_radar.py
CHANGED
|
@@ -206,24 +206,52 @@ def _fetch(ts: str, timeout: int = 25):
|
|
| 206 |
return _parse(r.content)
|
| 207 |
|
| 208 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
def grid(now: Optional[dt.datetime] = None):
|
| 210 |
-
"""回 (時間戳, lat, lon, val)。取不到回 None——呼叫端必須能接受沒有。
|
|
|
|
| 211 |
if not ENABLED:
|
| 212 |
return None
|
| 213 |
-
import time as _clock
|
| 214 |
for ts in _slots(now):
|
| 215 |
hit = _CACHE.get(ts)
|
| 216 |
-
if hit
|
| 217 |
return (ts,) + hit[1]
|
| 218 |
g = _fetch(ts)
|
| 219 |
if g is not None:
|
| 220 |
-
|
| 221 |
-
for k in sorted(_CACHE)[:-4]: # 只留最近 4 筆
|
| 222 |
-
_CACHE.pop(k, None)
|
| 223 |
return (ts,) + g
|
| 224 |
return None
|
| 225 |
|
| 226 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
def _max_within(g, lat: float, lon: float, radius_km: float) -> Optional[float]:
|
| 228 |
"""回半徑內的最大值。範圍內沒有格點、或有效格點不足一半,回 None。
|
| 229 |
|
|
|
|
| 206 |
return _parse(r.content)
|
| 207 |
|
| 208 |
|
| 209 |
+
KEEP_FRAMES = 8 # 快取留最近幾張 10 分鐘格點(/rain 附圖的動畫要過去一小時的每一張)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def _put(ts: str, g) -> None:
|
| 213 |
+
import time as _clock
|
| 214 |
+
_CACHE[ts] = (_clock.time(), g)
|
| 215 |
+
for k in sorted(_CACHE)[:-KEEP_FRAMES]:
|
| 216 |
+
_CACHE.pop(k, None)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
def grid(now: Optional[dt.datetime] = None):
|
| 220 |
+
"""回 (時間戳, lat, lon, val)。取不到回 None——呼叫端必須能接受沒有。
|
| 221 |
+
★同一個時間戳的格點是不變的:快取有就用,不看 TTL(TTL 的意義只在「有沒有更新的時槽」,那由 _slots 決定)。"""
|
| 222 |
if not ENABLED:
|
| 223 |
return None
|
|
|
|
| 224 |
for ts in _slots(now):
|
| 225 |
hit = _CACHE.get(ts)
|
| 226 |
+
if hit:
|
| 227 |
return (ts,) + hit[1]
|
| 228 |
g = _fetch(ts)
|
| 229 |
if g is not None:
|
| 230 |
+
_put(ts, g)
|
|
|
|
|
|
|
| 231 |
return (ts,) + g
|
| 232 |
return None
|
| 233 |
|
| 234 |
|
| 235 |
+
def ensure(ts: str):
|
| 236 |
+
"""確保某個 10 分鐘時槽在快取裡(附圖動畫回填用)。回 (ts, lat, lon, val) 或 None。"""
|
| 237 |
+
if not ENABLED:
|
| 238 |
+
return None
|
| 239 |
+
hit = _CACHE.get(ts)
|
| 240 |
+
if hit:
|
| 241 |
+
return (ts,) + hit[1]
|
| 242 |
+
g = _fetch(ts)
|
| 243 |
+
if g is None:
|
| 244 |
+
return None
|
| 245 |
+
_put(ts, g)
|
| 246 |
+
return (ts,) + g
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def history(n: int = 6, before: Optional[str] = None):
|
| 250 |
+
"""快取裡最近 n 張(由舊到新);before 給了就只取 ≤ before 的。這些是歷史,時間戳就是身分,不看 TTL。"""
|
| 251 |
+
keys = sorted(k for k in _CACHE if not before or k <= before)[-n:]
|
| 252 |
+
return [(k,) + _CACHE[k][1] for k in keys]
|
| 253 |
+
|
| 254 |
+
|
| 255 |
def _max_within(g, lat: float, lon: float, radius_km: float) -> Optional[float]:
|
| 256 |
"""回半徑內的最大值。範圍內沒有格點、或有效格點不足一半,回 None。
|
| 257 |
|