open_meteo.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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. about = {
  9. "website": 'https://open-meteo.com',
  10. "wikidata_id": None,
  11. "official_api_documentation": 'https://open-meteo.com/en/docs',
  12. "use_official_api": True,
  13. "require_api_key": False,
  14. "results": "JSON",
  15. }
  16. categories = ["weather"]
  17. geo_url = "https://geocoding-api.open-meteo.com"
  18. api_url = "https://api.open-meteo.com"
  19. 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
  20. def request(query, params):
  21. location_url = f"{geo_url}/v1/search?name={quote_plus(query)}"
  22. resp = get(location_url)
  23. if resp.status_code != 200:
  24. raise SearxEngineAPIException("invalid geo location response code")
  25. json_locations = resp.json().get("results", [])
  26. if len(json_locations) == 0:
  27. raise SearxEngineAPIException("location not found")
  28. location = json_locations[0]
  29. args = {
  30. 'latitude': location['latitude'],
  31. 'longitude': location['longitude'],
  32. 'timeformat': 'unixtime',
  33. 'format': 'json',
  34. 'current': data_of_interest,
  35. 'forecast_days': 7,
  36. 'hourly': data_of_interest,
  37. }
  38. params['url'] = f"{api_url}/v1/forecast?{urlencode(args)}"
  39. return params
  40. def c_to_f(temperature):
  41. return "%.2f" % ((temperature * 1.8) + 32)
  42. def get_direction(degrees):
  43. if degrees < 45 or degrees >= 315:
  44. return "N"
  45. if 45 <= degrees < 135:
  46. return "O"
  47. if 135 <= degrees < 225:
  48. return "S"
  49. return "W"
  50. def generate_condition_table(condition):
  51. res = ""
  52. res += (
  53. f"<tr><td><b>{gettext('Temperature')}</b></td>"
  54. f"<td><b>{condition['temperature_2m']}°C / {c_to_f(condition['temperature_2m'])}°F</b></td></tr>"
  55. )
  56. res += (
  57. f"<tr><td>{gettext('Feels like')}</td><td>{condition['apparent_temperature']}°C / "
  58. f"{c_to_f(condition['apparent_temperature'])}°F</td></tr>"
  59. )
  60. res += (
  61. f"<tr><td>{gettext('Wind')}</td><td>{get_direction(condition['wind_direction_10m'])}, "
  62. f"{condition['wind_direction_10m']}° — "
  63. f"{condition['wind_speed_10m']} km/h</td></tr>"
  64. )
  65. res += f"<tr><td>{gettext('Cloud cover')}</td><td>{condition['cloud_cover']}%</td>"
  66. res += f"<tr><td>{gettext('Humidity')}</td><td>{condition['relative_humidity_2m']}%</td></tr>"
  67. res += f"<tr><td>{gettext('Pressure')}</td><td>{condition['pressure_msl']}hPa</td></tr>"
  68. return res
  69. def response(resp):
  70. data = resp.json()
  71. table_content = generate_condition_table(data['current'])
  72. infobox = f"<table><tbody>{table_content}</tbody></table>"
  73. for index, time in enumerate(data['hourly']['time']):
  74. hourly_data = {}
  75. for key in data_of_interest.split(","):
  76. hourly_data[key] = data['hourly'][key][index]
  77. table_content = generate_condition_table(hourly_data)
  78. infobox += f"<h3>{datetime.utcfromtimestamp(time).strftime('%Y-%m-%d %H:%M')}</h3>"
  79. infobox += f"<table><tbody>{table_content}</tbody></table>"
  80. return [{'infobox': 'Open Meteo', 'content': infobox}]