open_meteo.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Open Meteo (weather)"""
  3. from urllib.parse import urlencode, quote_plus
  4. from datetime import datetime
  5. from flask_babel import gettext
  6. from searx.network import get
  7. from searx.exceptions import SearxEngineAPIException
  8. from searx.result_types import EngineResults, Weather
  9. about = {
  10. "website": 'https://open-meteo.com',
  11. "wikidata_id": None,
  12. "official_api_documentation": 'https://open-meteo.com/en/docs',
  13. "use_official_api": True,
  14. "require_api_key": False,
  15. "results": "JSON",
  16. }
  17. categories = ["weather"]
  18. geo_url = "https://geocoding-api.open-meteo.com"
  19. api_url = "https://api.open-meteo.com"
  20. data_of_interest = "temperature_2m,relative_humidity_2m,apparent_temperature,cloud_cover,pressure_msl,wind_speed_10m,wind_direction_10m" # pylint: disable=line-too-long
  21. def request(query, params):
  22. location_url = f"{geo_url}/v1/search?name={quote_plus(query)}"
  23. resp = get(location_url)
  24. if resp.status_code != 200:
  25. raise SearxEngineAPIException("invalid geo location response code")
  26. json_locations = resp.json().get("results", [])
  27. if len(json_locations) == 0:
  28. raise SearxEngineAPIException("location not found")
  29. location = json_locations[0]
  30. args = {
  31. 'latitude': location['latitude'],
  32. 'longitude': location['longitude'],
  33. 'timeformat': 'unixtime',
  34. 'format': 'json',
  35. 'current': data_of_interest,
  36. 'forecast_days': 7,
  37. 'hourly': data_of_interest,
  38. }
  39. params['url'] = f"{api_url}/v1/forecast?{urlencode(args)}"
  40. params['location'] = location['name']
  41. return params
  42. def c_to_f(temperature):
  43. return "%.2f" % ((temperature * 1.8) + 32)
  44. def get_direction(degrees):
  45. if degrees < 45 or degrees >= 315:
  46. return "N"
  47. if 45 <= degrees < 135:
  48. return "O"
  49. if 135 <= degrees < 225:
  50. return "S"
  51. return "W"
  52. def build_condition_string(data):
  53. if data['relative_humidity_2m'] > 50:
  54. return "rainy"
  55. if data['cloud_cover'] > 30:
  56. return 'cloudy'
  57. return 'clear sky'
  58. def generate_weather_data(data):
  59. return Weather.DataItem(
  60. condition=build_condition_string(data),
  61. temperature=f"{data['temperature_2m']}°C / {c_to_f(data['temperature_2m'])}°F",
  62. feelsLike=f"{data['apparent_temperature']}°C / {c_to_f(data['apparent_temperature'])}°F",
  63. wind=(
  64. f"{get_direction(data['wind_direction_10m'])}, "
  65. f"{data['wind_direction_10m']}° — "
  66. f"{data['wind_speed_10m']} km/h"
  67. ),
  68. pressure=f"{data['pressure_msl']}hPa",
  69. humidity=f"{data['relative_humidity_2m']}hPa",
  70. attributes={gettext('Cloud cover'): f"{data['cloud_cover']}%"},
  71. )
  72. def response(resp):
  73. res = EngineResults()
  74. json_data = resp.json()
  75. current_weather = generate_weather_data(json_data['current'])
  76. weather_answer = Weather(
  77. location=resp.search_params['location'],
  78. current=current_weather,
  79. )
  80. for index, time in enumerate(json_data['hourly']['time']):
  81. hourly_data = {}
  82. for key in data_of_interest.split(","):
  83. hourly_data[key] = json_data['hourly'][key][index]
  84. forecast_data = generate_weather_data(hourly_data)
  85. forecast_data.time = datetime.fromtimestamp(time).strftime('%Y-%m-%d %H:%M')
  86. weather_answer.forecasts.append(forecast_data)
  87. res.add(weather_answer)
  88. return res