Spaces:
Sleeping
Sleeping
| # usgs_service.py | |
| import requests | |
| import pandas as pd | |
| from datetime import datetime, timedelta, timezone | |
| from config import USGS_API_BASE_URL, CURRENT_YEAR | |
| def _iso(dt: datetime) -> str: | |
| """ε° datetime η©δ»Άζ ΌεΌεηΊ USGS API ιθ¦η ISO 8601 εδΈ²γ""" | |
| return dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S") | |
| def fetch_global_last24h_text(min_mag: float = 5.0, limit: int = 10) -> str: | |
| """εΎ USGS ζ·ειε» 24 ε°ζηε ¨ηι‘―θε°ιγ""" | |
| now_utc = datetime.now(timezone.utc) | |
| since = now_utc - timedelta(hours=24) | |
| params = { | |
| "format": "geojson", | |
| "starttime": _iso(since), | |
| "endtime": _iso(now_utc), | |
| "minmagnitude": float(min_mag), | |
| "limit": int(limit), | |
| "orderby": "time", | |
| } | |
| try: | |
| r = requests.get(USGS_API_BASE_URL, params=params, timeout=15) | |
| r.raise_for_status() | |
| features = r.json().get("features", []) | |
| if not features: | |
| return f"β ιε» 24 ε°ζε §οΌε ¨ηη‘θ¦ζ¨‘ {min_mag} δ»₯δΈηι‘―θε°ιγ" | |
| lines = [f"π¨ θΏ 24 ε°ζε ¨ηι‘―θε°ι (Mβ₯{min_mag}):", "-" * 20] | |
| for f in features: | |
| p = f["properties"] | |
| t_utc = datetime.fromtimestamp(p["time"] / 1000, tz=timezone.utc) | |
| lines.append(f"ιη΄: {p['mag']:.1f} | ζ₯ζζι: {t_utc.strftime('%Y-%m-%d %H:%M')} (UTC)\nε°ι»: {p.get('place','')}") | |
| return "\n\n".join(lines) | |
| except Exception as e: | |
| return f"β ζ₯θ©’ε€±ζ: {e}" | |
| def fetch_taiwan_df_this_year(min_mag: float = 5.0) -> pd.DataFrame | str: | |
| """ζ·εδ»εΉ΄δ»₯δΎε°η£εεηι‘―θε°ιγ""" | |
| now_utc = datetime.now(timezone.utc) | |
| start_of_year_utc = datetime(now_utc.year, 1, 1, tzinfo=timezone.utc) | |
| params = { | |
| "format": "geojson", "starttime": _iso(start_of_year_utc), "endtime": _iso(now_utc), | |
| "minmagnitude": float(min_mag), | |
| "minlatitude": 21, "maxlatitude": 26, | |
| "minlongitude": 119, "maxlongitude": 123, | |
| "limit": 250, "orderby": "time", | |
| } | |
| try: | |
| r = requests.get(USGS_API_BASE_URL, params=params, timeout=20) | |
| r.raise_for_status() | |
| features = r.json().get("features", []) | |
| if not features: | |
| return f"β δ»εΉ΄ ({CURRENT_YEAR} εΉ΄) δ»₯δΎοΌε°η£εεη‘ Mβ₯{min_mag:.1f} ηι‘―θε°ιγ" | |
| rows = [] | |
| for f in features: | |
| p = f["properties"] | |
| lon, lat, *_ = f["geometry"]["coordinates"] | |
| rows.append({ | |
| "latitude": lat, "longitude": lon, "magnitude": p["mag"], | |
| "place": p.get("place", ""), "time_utc": datetime.fromtimestamp(p["time"]/1000, tz=timezone.utc) | |
| }) | |
| return pd.DataFrame(rows) | |
| except Exception as e: | |
| return f"β ζ₯θ©’ε€±ζ: {e}" |