Spaces:
Sleeping
Sleeping
chen commited on
Update weather_service.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889# weather_service.pyimport requestsfrom config import CWA_API_KEYfrom datetime import datetimeCWA_FORECAST_API = "https://opendata.cwa.gov.tw/api/v1/rest/datastore/F-C0032-001"def _normalize_location_name(loc_name: str) -> str:"""自動校正縣市名稱,以符合 API 要求 (例如 台北 -> 臺北市)"""loc_name = loc_name.replace("台", "臺")if loc_name.endswith("市") or loc_name.endswith("縣"):return loc_namemajor_cities = "臺北,桃園,新竹,臺中,嘉義,臺南,高雄,基隆".split(',')if any(city in loc_name for city in major_cities):return f"{loc_name}市"return f"{loc_name}縣"def _format_time_period(start_str: str, end_str: str) -> str:"""將時間格式化為易讀的時段名稱"""start_dt = datetime.fromisoformat(start_str)start_hour = start_dt.hourif start_hour >= 18 or start_hour < 6:return f"{start_dt.strftime('%m/%d')} 晚上至隔日清晨"elif start_hour >= 6 and start_hour < 18:return f"{start_dt.strftime('%m/%d')} 白天"return f"{start_dt.strftime('%m/%d %H:%M')}"def fetch_forecast_by_location(location_name: str) -> str:"""根據地點名稱查詢未來 36 小時天氣預報。"""if not CWA_API_KEY:return "❌ 天氣預報查詢失敗:管理者尚未設定 CWA_API_KEY。"normalized_loc = _normalize_location_name(location_name)params = {"Authorization": CWA_API_KEY,"format": "JSON","locationName": normalized_loc,"elementName": ["Wx", "PoP", "MinT", "MaxT"],}try:r = requests.get(CWA_FORECAST_API, params=params, timeout=10)r.raise_for_status()data = r.json()if not data.get("records") or not data["records"]["location"]:return f"找不到「{location_name}」的預報資訊。\n請確認是否為台灣的縣市名稱 (例如: 臺北市, 花蓮縣)。"loc_data = data["records"]["location"][0]elements = {elem["elementName"]: elem["time"] for elem in loc_data["weatherElement"]}forecasts = []for i in range(3):try:start_time = elements["Wx"][i]["startTime"]end_time = elements["Wx"][i]["endTime"]wx = elements["Wx"][i]["parameter"]["parameterName"]pop = elements["PoP"][i]["parameter"]["parameterName"]min_t = elements["MinT"][i]["parameter"]["parameterName"]max_t = elements["MaxT"][i]["parameter"]["parameterName"]period_name = _format_time_period(start_time, end_time)forecast_str = (f"➢ {period_name}:\n"f" 天氣:{wx}\n"f" 氣溫:{min_t}°C - {max_t}°C\n"f" 降雨機率:{pop}%")forecasts.append(forecast_str)except (IndexError, KeyError):continueif not forecasts:return f"無法解析「{location_name}」的預報資料。"return f"📍 {loc_data['locationName']} 未來 36 小時天氣預報:\n\n" + "\n\n".join(forecasts)except requests.exceptions.HTTPError as e:if e.response.status_code == 401:return "❌ 預報查詢失敗:CWA 授權金鑰 (API Key) 無效。"return f"❌ 預報查詢失敗:{e}"except Exception as e:return f"❌ 預報查詢失敗:{e}"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485# weather_service.pyimport requestsfrom config import CWA_API_KEY, DATASET_IDSCWA_API_BASE_URL = "https://opendata.cwa.gov.tw/api/v1/rest/datastore/"def _make_cwa_api_request(data_id, params=None):"""一個通用的 CWA API 請求函式"""if not CWA_API_KEY:raise ValueError("錯誤:尚未設定 CWA_API_KEY Secret。")api_url = f"{CWA_API_BASE_URL}{data_id}"base_params = {"Authorization": CWA_API_KEY, "format": "JSON"}if params:base_params.update(params)response = requests.get(api_url, params=base_params, timeout=10)response.raise_for_status() # 如果請求失敗 (e.g., 401, 404, 500), 會在此拋出錯誤data = response.json()if not data.get('success'):raise ValueError("API 回應不成功或資料格式有誤。")return data.get('records', {})def _parse_forecast_data(records, location):"""解析 F-C0032-001 的預報資料並格式化為文字"""location_records = records.get('location', [])if not location_records:return f"找不到「{location}」的預報資訊。\n請確認是否為台灣的縣市名稱 (例如: 臺北市, 花蓮縣)。"weather_elements = location_records[0].get('weatherElement', [])# 用字典來重組資料,以時間為主鍵forecasts = {}for element in weather_elements:element_name = element['elementName']for time_period in element['time']:time_key = f"{time_period['startTime']} ~ {time_period['endTime']}"if time_key not in forecasts:forecasts[time_key] = {}value = time_period['parameter']['parameterName']unit = time_period['parameter'].get('parameterUnit', '')forecasts[time_key][element_name] = f"{value}{unit}"# 格式化輸出result = f"📍 {location} 未來 36 小時天氣預報:\n"for time_period, values in sorted(forecasts.items()):# 將��間字串格式化得更易讀start_time_str = time_period.split(' ~ ')[0]start_dt = datetime.fromisoformat(start_time_str)period_name = f"{start_dt.strftime('%m/%d %H:%M')}"result += (f"\n➢ 時段:{period_name} 開始\n"f" 天氣:{values.get('Wx', 'N/A')}\n"f" 氣溫:{values.get('MinT', '?')}°C - {values.get('MaxT', '?')}°C\n"f" 降雨機率:{values.get('PoP', '?')}%")return resultdef fetch_forecast_by_location(location_name: str) -> str:"""主要的天氣預報查詢函式,由 command_handler 呼叫。它會處理地點名稱的 '台'/'臺' 轉換,並呼叫輔助函式。"""try:# 進行地點名稱的簡易處理,提高 API 成功率processed_location = location_name.replace("台", "臺")if not (processed_location.endswith("市") or processed_location.endswith("縣")):# 根據 Gradio 程式碼的縣市列表,大部分地點都是縣if processed_location in ["臺北", "新北", "基隆", "桃園", "新竹", "臺中", "嘉義", "臺南", "高雄"]:processed_location += "市"else:processed_location += "縣"records = _make_cwa_api_request(DATASET_IDS["天氣預報"],{"locationName": processed_location})return _parse_forecast_data(records, processed_location)except Exception as e:return f"❌ 天氣預報查詢失敗:{e}"
weather_service.py+70-74