Spaces:
Sleeping
Sleeping
chen commited on
Update weather_service.py
Browse files4 unmodified lines567891011121314151617181920212211 unmodified lines3435363738394041424344454647484950515253545556575829 unmodified lines888990914 unmodified linesCWA_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)11 unmodified linesif not CWA_AUTH_KEY:return "❌ 天氣預報查詢失敗:管理者尚未設定 CWA_AUTH_KEY。"normalized_loc = _normalize_location_name(location_name)params = {"Authorization": CWA_AUTH_KEY,"format": "JSON","locationName": normalized_loc,# [修改] 將 elementName 改為列表格式,以符合 API 規範"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 = []29 unmodified linesreturn f"❌ 預報查詢失敗:{e}"except Exception as e:return f"❌ 預報查詢失敗:{e}"4 unmodified lines567891011 unmodified lines222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676829 unmodified lines98991004 unmodified linesCWA_FORECAST_API = "https://opendata.cwa.gov.tw/api/v1/rest/datastore/F-C0032-001"def _format_time_period(start_str: str, end_str: str) -> str:"""將時間格式化為易讀的時段名稱"""start_dt = datetime.fromisoformat(start_str)11 unmodified linesif not CWA_AUTH_KEY:return "❌ 天氣預報查詢失敗:管理者尚未設定 CWA_AUTH_KEY。"params = {"Authorization": CWA_AUTH_KEY,"format": "JSON",# [修改] 移除 locationName 參數,一次獲取所有縣市的資料"elementName": ["Wx", "PoP", "MinT", "MaxT"],}try:r = requests.get(CWA_FORECAST_API, params=params, timeout=15)r.raise_for_status()data = r.json()if not data.get("records") or not data["records"]["location"]:return "❌ 無法從 CWA 獲取任何天氣預報資料。"all_locations = data["records"]["location"]# [修改] 在所有回傳的資料中,手動尋找使用者指定的地點normalized_input = location_name.replace("台", "臺")if not (normalized_input.endswith("市") or normalized_input.endswith("縣")):normalized_input += "市" # 預設加上 "市" 來比對target_location = Nonefor loc in all_locations:if loc["locationName"] == normalized_input:target_location = locbreak# 如果找不到 "市",試試看 "縣"if not target_location:normalized_input = normalized_input.replace("市", "縣")for loc in all_locations:if loc["locationName"] == normalized_input:target_location = locbreakif not target_location:return f"找不到「{location_name}」的預報資訊。\n請確認是否為台灣的縣市名稱 (例如: 臺北市, 花蓮縣)。"# --- 找到地點後,格式化輸出 (邏輯不變) ---loc_data = target_locationelements = {elem["elementName"]: elem["time"] for elem in loc_data["weatherElement"]}forecasts = []29 unmodified linesreturn f"❌ 預報查詢失敗:{e}"except Exception as e:return f"❌ 預報查詢失敗:{e}"
weather_service.py+28-19