Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

qweather.py 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. from abc import ABC
  17. import pandas as pd
  18. import requests
  19. from agent.component.base import ComponentBase, ComponentParamBase
  20. class QWeatherParam(ComponentParamBase):
  21. """
  22. Define the QWeather component parameters.
  23. """
  24. def __init__(self):
  25. super().__init__()
  26. self.web_apikey = "xxx"
  27. self.lang = "zh"
  28. self.type = "weather"
  29. self.user_type = 'free'
  30. self.error_code = {
  31. "204": "The request was successful, but the region you are querying does not have the data you need at this time.",
  32. "400": "Request error, may contain incorrect request parameters or missing mandatory request parameters.",
  33. "401": "Authentication fails, possibly using the wrong KEY, wrong digital signature, wrong type of KEY (e.g. using the SDK's KEY to access the Web API).",
  34. "402": "Exceeded the number of accesses or the balance is not enough to support continued access to the service, you can recharge, upgrade the accesses or wait for the accesses to be reset.",
  35. "403": "No access, may be the binding PackageName, BundleID, domain IP address is inconsistent, or the data that requires additional payment.",
  36. "404": "The queried data or region does not exist.",
  37. "429": "Exceeded the limited QPM (number of accesses per minute), please refer to the QPM description",
  38. "500": "No response or timeout, interface service abnormality please contact us"
  39. }
  40. # Weather
  41. self.time_period = 'now'
  42. def check(self):
  43. self.check_empty(self.web_apikey, "BaiduFanyi APPID")
  44. self.check_valid_value(self.type, "Type", ["weather", "indices", "airquality"])
  45. self.check_valid_value(self.user_type, "Free subscription or paid subscription", ["free", "paid"])
  46. self.check_valid_value(self.lang, "Use language",
  47. ['zh', 'zh-hant', 'en', 'de', 'es', 'fr', 'it', 'ja', 'ko', 'ru', 'hi', 'th', 'ar', 'pt',
  48. 'bn', 'ms', 'nl', 'el', 'la', 'sv', 'id', 'pl', 'tr', 'cs', 'et', 'vi', 'fil', 'fi',
  49. 'he', 'is', 'nb'])
  50. self.check_vaild_value(self.time_period, "Time period", ['now', '3d', '7d', '10d', '15d', '30d'])
  51. class QWeather(ComponentBase, ABC):
  52. component_name = "QWeather"
  53. def _run(self, history, **kwargs):
  54. ans = self.get_input()
  55. ans = "".join(ans["content"]) if "content" in ans else ""
  56. if not ans:
  57. return QWeather.be_output("")
  58. try:
  59. response = requests.get(
  60. url="https://geoapi.qweather.com/v2/city/lookup?location=" + ans + "&key=" + self._param.web_apikey).json()
  61. if response["code"] == "200":
  62. location_id = response["location"][0]["id"]
  63. else:
  64. return QWeather.be_output("**Error**" + self._param.error_code[response["code"]])
  65. base_url = "https://api.qweather.com/v7/" if self._param.user_type == 'paid' else "https://devapi.qweather.com/v7/"
  66. if self._param.type == "weather":
  67. url = base_url + "weather/" + self._param.time_period + "?location=" + location_id + "&key=" + self._param.web_apikey + "&lang=" + self._param.lang
  68. response = requests.get(url=url).json()
  69. if response["code"] == "200":
  70. if self._param.time_period == "now":
  71. return QWeather.be_output(str(response["now"]))
  72. else:
  73. qweather_res = [{"content": str(i) + "\n"} for i in response["daily"]]
  74. if not qweather_res:
  75. return QWeather.be_output("")
  76. df = pd.DataFrame(qweather_res)
  77. return df
  78. else:
  79. return QWeather.be_output("**Error**" + self._param.error_code[response["code"]])
  80. elif self._param.type == "indices":
  81. url = base_url + "indices/1d?type=0&location=" + location_id + "&key=" + self._param.web_apikey + "&lang=" + self._param.lang
  82. response = requests.get(url=url).json()
  83. if response["code"] == "200":
  84. indices_res = response["daily"][0]["date"] + "\n" + "\n".join(
  85. [i["name"] + ": " + i["category"] + ", " + i["text"] for i in response["daily"]])
  86. return QWeather.be_output(indices_res)
  87. else:
  88. return QWeather.be_output("**Error**" + self._param.error_code[response["code"]])
  89. elif self._param.type == "airquality":
  90. url = base_url + "air/now?location=" + location_id + "&key=" + self._param.web_apikey + "&lang=" + self._param.lang
  91. response = requests.get(url=url).json()
  92. if response["code"] == "200":
  93. return QWeather.be_output(str(response["now"]))
  94. else:
  95. return QWeather.be_output("**Error**" + self._param.error_code[response["code"]])
  96. except Exception as e:
  97. return QWeather.be_output("**Error**" + str(e))