.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
duckduckgo_weather.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""
3DuckDuckGo Weather
4~~~~~~~~~~~~~~~~~~
5"""
6
7import typing as t
8from json import loads
9from urllib.parse import quote
10
11from dateutil import parser as date_parser
12
13from searx.engines.duckduckgo import fetch_traits # pylint: disable=unused-import
14from searx.engines.duckduckgo import get_ddg_lang
15
16from searx.result_types import EngineResults
17from searx.extended_types import SXNG_Response
18from searx import weather
19
20
21about = {
22 "website": 'https://duckduckgo.com/',
23 "wikidata_id": 'Q12805',
24 "official_api_documentation": None,
25 "use_official_api": True,
26 "require_api_key": False,
27 "results": "JSON",
28}
29
30send_accept_language_header = True
31
32# engine dependent config
33categories = ["weather"]
34base_url = "https://duckduckgo.com/js/spice/forecast/{query}/{lang}"
35
36# adapted from https://gist.github.com/mikesprague/048a93b832e2862050356ca233ef4dc1
37WEATHERKIT_TO_CONDITION: dict[str, weather.WeatherConditionType] = {
38 "BlowingDust": "fog",
39 "Clear": "clear sky",
40 "Cloudy": "cloudy",
41 "Foggy": "fog",
42 "Haze": "fog",
43 "MostlyClear": "clear sky",
44 "MostlyCloudy": "partly cloudy",
45 "PartlyCloudy": "partly cloudy",
46 "Smoky": "fog",
47 "Breezy": "partly cloudy",
48 "Windy": "partly cloudy",
49 "Drizzle": "light rain",
50 "HeavyRain": "heavy rain",
51 "IsolatedThunderstorms": "rain and thunder",
52 "Rain": "rain",
53 "SunShowers": "rain",
54 "ScatteredThunderstorms": "heavy rain and thunder",
55 "StrongStorms": "heavy rain and thunder",
56 "Thunderstorms": "rain and thunder",
57 "Frigid": "clear sky",
58 "Hail": "heavy rain",
59 "Hot": "clear sky",
60 "Flurries": "light snow",
61 "Sleet": "sleet",
62 "Snow": "light snow",
63 "SunFlurries": "light snow",
64 "WintryMix": "sleet",
65 "Blizzard": "heavy snow",
66 "BlowingSnow": "heavy snow",
67 "FreezingDrizzle": "light sleet",
68 "FreezingRain": "sleet",
69 "HeavySnow": "heavy snow",
70 "Hurricane": "rain and thunder",
71 "TropicalStorm": "rain and thunder",
72}
73
74
75def _weather_data(location: weather.GeoLocation, data: dict[str, t.Any]):
76
77 return EngineResults.types.WeatherAnswer.Item(
78 location=location,
79 temperature=weather.Temperature(unit="°C", value=data['temperature']),
80 condition=WEATHERKIT_TO_CONDITION[data["conditionCode"]],
81 feels_like=weather.Temperature(unit="°C", value=data['temperatureApparent']),
82 wind_from=weather.Compass(data["windDirection"]),
83 wind_speed=weather.WindSpeed(data["windSpeed"], unit="mi/h"),
84 pressure=weather.Pressure(data["pressure"], unit="hPa"),
85 humidity=weather.RelativeHumidity(data["humidity"] * 100),
86 cloud_cover=data["cloudCover"] * 100,
87 )
88
89
90def request(query: str, params: dict[str, t.Any]):
91
92 eng_region = traits.get_region(params['searxng_locale'], traits.all_locale)
93 eng_lang = get_ddg_lang(traits, params['searxng_locale'])
94
95 # !ddw paris :es-AR --> {'ad': 'es_AR', 'ah': 'ar-es', 'l': 'ar-es'}
96 params['cookies']['ad'] = eng_lang
97 params['cookies']['ah'] = eng_region
98 params['cookies']['l'] = eng_region
99 logger.debug("cookies: %s", params['cookies'])
100
101 params["url"] = base_url.format(query=quote(query), lang=eng_lang.split('_')[0])
102 return params
103
104
105def response(resp: SXNG_Response):
106 res = EngineResults()
107
108 if resp.text.strip() == "ddg_spice_forecast();":
109 return res
110
111 json_data = loads(resp.text[resp.text.find('\n') + 1 : resp.text.rfind('\n') - 2])
112
113 geoloc = weather.GeoLocation.by_query(resp.search_params["query"])
114
115 weather_answer = EngineResults.types.WeatherAnswer(
116 current=_weather_data(geoloc, json_data["currentWeather"]),
117 service="duckduckgo weather",
118 )
119
120 for forecast in json_data['forecastHourly']['hours']:
121 forecast_time = date_parser.parse(forecast['forecastStart'])
122 forecast_data = _weather_data(geoloc, forecast)
123 forecast_data.datetime = weather.DateTime(forecast_time)
124 weather_answer.forecasts.append(forecast_data)
125
126 res.add(weather_answer)
127 return res
request(str query, dict[str, t.Any] params)
_weather_data(weather.GeoLocation location, dict[str, t.Any] data)