cwadayi commited on
Commit
5f4b7fe
·
verified ·
1 Parent(s): 4bdbdd9

Update usgs_service.py

Browse files
Files changed (1) hide show
  1. usgs_service.py +73 -65
usgs_service.py CHANGED
@@ -1,65 +1,73 @@
1
- # usgs_service.py
2
- import requests
3
- import pandas as pd
4
- from datetime import datetime, timedelta, timezone
5
- from config import USGS_API_BASE_URL, CURRENT_YEAR
6
-
7
- def _iso(dt: datetime) -> str:
8
- """將 datetime 物件格式化為 USGS API 需要的 ISO 8601 字串。"""
9
- return dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S")
10
-
11
- def fetch_global_last24h_text(min_mag: float = 5.0, limit: int = 10) -> str:
12
- """從 USGS 擷取過去 24 小時的全球顯著地震。"""
13
- now_utc = datetime.now(timezone.utc)
14
- since = now_utc - timedelta(hours=24)
15
- params = {
16
- "format": "geojson",
17
- "starttime": _iso(since),
18
- "endtime": _iso(now_utc),
19
- "minmagnitude": float(min_mag),
20
- "limit": int(limit),
21
- "orderby": "time",
22
- }
23
- try:
24
- r = requests.get(USGS_API_BASE_URL, params=params, timeout=15)
25
- r.raise_for_status()
26
- features = r.json().get("features", [])
27
- if not features:
28
- return f"✅ 過去 24 小時內,全球無規模 {min_mag} 以上的顯著地震。"
29
- lines = [f"🚨 近 24 小時全球顯著地震 (M≥{min_mag}):", "-" * 20]
30
- for f in features:
31
- p = f["properties"]
32
- t_utc = datetime.fromtimestamp(p["time"] / 1000, tz=timezone.utc)
33
- lines.append(f"震級: {p['mag']:.1f} | 日期時間: {t_utc.strftime('%Y-%m-%d %H:%M')} (UTC)\n地點: {p.get('place','')}")
34
- return "\n\n".join(lines)
35
- except Exception as e:
36
- return f"❌ 查詢失敗: {e}"
37
-
38
- def fetch_taiwan_df_this_year(min_mag: float = 5.0) -> pd.DataFrame | str:
39
- """擷取今年以來台灣區域的顯著地震。"""
40
- now_utc = datetime.now(timezone.utc)
41
- start_of_year_utc = datetime(now_utc.year, 1, 1, tzinfo=timezone.utc)
42
- params = {
43
- "format": "geojson", "starttime": _iso(start_of_year_utc), "endtime": _iso(now_utc),
44
- "minmagnitude": float(min_mag),
45
- "minlatitude": 21, "maxlatitude": 26,
46
- "minlongitude": 119, "maxlongitude": 123,
47
- "limit": 250, "orderby": "time",
48
- }
49
- try:
50
- r = requests.get(USGS_API_BASE_URL, params=params, timeout=20)
51
- r.raise_for_status()
52
- features = r.json().get("features", [])
53
- if not features:
54
- return f" 今年 ({CURRENT_YEAR} 年) 以來,台灣區域無 M≥{min_mag:.1f} 的顯著地震。"
55
- rows = []
56
- for f in features:
57
- p = f["properties"]
58
- lon, lat, *_ = f["geometry"]["coordinates"]
59
- rows.append({
60
- "latitude": lat, "longitude": lon, "magnitude": p["mag"],
61
- "place": p.get("place", ""), "time_utc": datetime.fromtimestamp(p["time"]/1000, tz=timezone.utc)
62
- })
63
- return pd.DataFrame(rows)
64
- except Exception as e:
65
- return f"❌ 查詢失敗: {e}"
 
 
 
 
 
 
 
 
 
1
+ # usgs_service.py
2
+ import requests
3
+ import pandas as pd
4
+ from datetime import datetime, timedelta, timezone
5
+ from config import USGS_API_BASE_URL, CURRENT_YEAR
6
+
7
+ def _iso(dt: datetime) -> str:
8
+ """將 datetime 物件格式化為 USGS API 需要的 ISO 8601 字串。"""
9
+ return dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S")
10
+
11
+ def fetch_global_last24h_text(min_mag: float = 5.0, limit: int = 10) -> str:
12
+ """從 USGS 擷取過去 24 小時的全球顯著地震。"""
13
+ now_utc = datetime.now(timezone.utc)
14
+ since = now_utc - timedelta(hours=24)
15
+ params = {
16
+ "format": "geojson",
17
+ "starttime": _iso(since),
18
+ "endtime": _iso(now_utc),
19
+ "minmagnitude": float(min_mag),
20
+ "limit": int(limit),
21
+ "orderby": "time-desc", # 改為時間倒序,顯示最新的在最上面
22
+ }
23
+ try:
24
+ r = requests.get(USGS_API_BASE_URL, params=params, timeout=15)
25
+ r.raise_for_status()
26
+ features = r.json().get("features", [])
27
+ if not features:
28
+ return f"✅ 過去 24 小時內,全球無規模 {min_mag} 以上的顯著地震。"
29
+
30
+ lines = [f"🚨 24 小時全球顯著地震 (M≥{min_mag}):", "-" * 20]
31
+ for f in features:
32
+ p = f["properties"]
33
+ t_utc = datetime.fromtimestamp(p["time"] / 1000, tz=timezone.utc)
34
+
35
+ # [修改] 在訊息中加入 p['url'] 報告連結
36
+ lines.append(
37
+ f"震級: {p['mag']:.1f} | 日期時間: {t_utc.strftime('%Y-%m-%d %H:%M')} (UTC)\n"
38
+ f"地點: {p.get('place', 'N/A')}\n"
39
+ f"報告連結: {p.get('url', '無')}"
40
+ )
41
+ return "\n\n".join(lines)
42
+ except Exception as e:
43
+ return f" 查詢失敗: {e}"
44
+
45
+ def fetch_taiwan_df_this_year(min_mag: float = 5.0) -> pd.DataFrame | str:
46
+ """擷取今年以來台灣區域的顯著地震。"""
47
+ now_utc = datetime.now(timezone.utc)
48
+ start_of_year_utc = datetime(now_utc.year, 1, 1, tzinfo=timezone.utc)
49
+ params = {
50
+ "format": "geojson", "starttime": _iso(start_of_year_utc), "endtime": _iso(now_utc),
51
+ "minmagnitude": float(min_mag),
52
+ "minlatitude": 21, "maxlatitude": 26,
53
+ "minlongitude": 119, "maxlongitude": 123,
54
+ "limit": 250, "orderby": "time-desc",
55
+ }
56
+ try:
57
+ r = requests.get(USGS_API_BASE_URL, params=params, timeout=20)
58
+ r.raise_for_status()
59
+ features = r.json().get("features", [])
60
+ if not features:
61
+ return f" 今年 ({CURRENT_YEAR} ) 以來,台灣區域無 M≥{min_mag:.1f} 的顯著地震。"
62
+
63
+ rows = []
64
+ for f in features:
65
+ p = f["properties"]
66
+ lon, lat, *_ = f["geometry"]["coordinates"]
67
+ rows.append({
68
+ "latitude": lat, "longitude": lon, "magnitude": p["mag"],
69
+ "place": p.get("place", ""), "time_utc": datetime.fromtimestamp(p["time"]/1000, tz=timezone.utc)
70
+ })
71
+ return pd.DataFrame(rows)
72
+ except Exception as e:
73
+ return f"❌ 查詢失敗: {e}"