Spaces:
Sleeping
Sleeping
chen commited on
Update pws_service.py
Browse files12341 unmodified line678910111213141516171819202122232425262728293031323334353637383940414243444546# pws_service.pyimport requestsimport jsonfrom config import PWS_API_URL1 unmodified linedef fetch_latest_pws_info() -> str:"""從 MCP PWS 伺服器擷取最新的 PWS (Public Weather Service) 發布情形。此端點為 SSE (Server-Sent Events),因此我們需要讀取事件串流。"""try:# 使用 stream=True 來處理伺服器發送的事件串流r = requests.get(PWS_API_URL, timeout=15, stream=True)r.raise_for_status() # 如果 HTTP 狀態碼不是 200,則引發錯誤# 迭代處理從伺服器接收到的每一行資料for line in r.iter_lines():if line:decoded_line = line.decode('utf-8')# SSE 事件的資料通常以 "data: " 開頭if decoded_line.startswith('data:'):# 移除 "data: " 前綴並去除多餘空格,取得 JSON 字串json_data_str = decoded_line[5:].strip()try:# 解析 JSON 字串data = json.loads(json_data_str)# 從解析後的資料中提取報告內容 (假設 key 是 'pws_report')pws_report = data.get("pws_report")if not pws_report:return "❌ PWS 查詢失敗:無法從 API 回應中找到 'pws_report' 欄位。"# 格式化最終要回傳的訊息lines = ["🛰️ 最新 PWS 發布情形:", "----------------------------------", pws_report]return "\n".join(lines)except json.JSONDecodeError:return "❌ PWS 查詢失敗:伺服器回應的格式不正確 (非有效JSON)。"return "❌ PWS 查詢失敗:無法從伺服器串流中解析到有效的 PWS 資料。"except requests.exceptions.RequestException as e:return f"❌ PWS 查詢失敗:無法連接到伺服器。\n錯誤訊息:{e}"except Exception as e:return f"❌ PWS 查詢失敗:發生未預期的錯誤。\n錯誤訊息:{e}"12341 unmodified line6789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354# pws_service.py (Robust Version)import requestsimport jsonfrom config import PWS_API_URL1 unmodified linedef fetch_latest_pws_info() -> str:"""從 MCP PWS 伺服器擷取最新的 PWS (Public Weather Service) 發布情形。此版本經過優化,能穩定處理 Gradio API 的 Server-Sent Events (SSE) 串流。"""final_report = Nonetry:# 使用 stream=True 保持連線,接收伺服器持續發送的事件with requests.get(PWS_API_URL, timeout=20, stream=True) as r:r.raise_for_status() # 確保 HTTP 連線成功# 迭代處理從伺服器接收到的每一行資料for line in r.iter_lines():if line:decoded_line = line.decode('utf-8')# SSE 事件的資料以 "data: " 開頭if decoded_line.startswith('data:'):json_data_str = decoded_line[len('data:'):].strip()try:data = json.loads(json_data_str)# Gradio API 在完成時會發送 'process_completed' 訊息if data.get("msg") == "process_completed":# 最終結果通常在 output['data'][0] 中output_data = data.get("output", {}).get("data", [])if output_data:final_report = output_data[0]break # 收到最終結果,跳出迴圈except (json.JSONDecodeError, KeyError, IndexError):# 如果中途的訊息格式不符或不含所需資料,靜默忽略並繼續等待continue# 迴圈結束後,檢查是否成功取得最終報告if final_report:header = "🛰️ 最新 PWS 發布情形:"separator = "-" * 20return f"{header}\n{separator}\n{final_report}"else:return "❌ PWS 查詢失敗:已連接伺服器,但未收到有效的最終報告資料。"except requests.exceptions.Timeout:return f"❌ PWS 查詢失敗:連線超時,伺服器沒有在 20 秒內回應。"except requests.exceptions.RequestException as e:return f"❌ PWS 查詢失敗:網路連線錯誤。\n錯誤訊息:{e}"except Exception as e:return f"❌ PWS 查詢失敗:發生未預期的錯誤。\n錯誤訊息:{e}"
pws_service.py+37-29