qwant.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """This engine uses the Qwant API (https://api.qwant.com/v3) to implement Qwant
  3. -Web, -News, -Images and -Videos. The API is undocumented but can be reverse
  4. engineered by reading the network log of https://www.qwant.com/ queries.
  5. For Qwant's *web-search* two alternatives are implemented:
  6. - ``web``: uses the :py:obj:`api_url` which returns a JSON structure
  7. - ``web-lite``: uses the :py:obj:`web_lite_url` which returns a HTML page
  8. Configuration
  9. =============
  10. The engine has the following additional settings:
  11. - :py:obj:`qwant_categ`
  12. This implementation is used by different qwant engines in the :ref:`settings.yml
  13. <settings engines>`:
  14. .. code:: yaml
  15. - name: qwant
  16. qwant_categ: web-lite # alternatively use 'web'
  17. ...
  18. - name: qwant news
  19. qwant_categ: news
  20. ...
  21. - name: qwant images
  22. qwant_categ: images
  23. ...
  24. - name: qwant videos
  25. qwant_categ: videos
  26. ...
  27. Implementations
  28. ===============
  29. """
  30. from datetime import (
  31. datetime,
  32. timedelta,
  33. )
  34. from json import loads
  35. from urllib.parse import urlencode
  36. from flask_babel import gettext
  37. import babel
  38. import lxml
  39. from searx.exceptions import (
  40. SearxEngineAPIException,
  41. SearxEngineTooManyRequestsException,
  42. SearxEngineCaptchaException,
  43. )
  44. from searx.network import raise_for_httperror
  45. from searx.enginelib.traits import EngineTraits
  46. from searx.utils import (
  47. eval_xpath,
  48. eval_xpath_list,
  49. extract_text,
  50. get_embeded_stream_url,
  51. )
  52. traits: EngineTraits
  53. # about
  54. about = {
  55. "website": 'https://www.qwant.com/',
  56. "wikidata_id": 'Q14657870',
  57. "official_api_documentation": None,
  58. "use_official_api": True,
  59. "require_api_key": False,
  60. "results": 'JSON',
  61. }
  62. # engine dependent config
  63. categories = []
  64. paging = True
  65. max_page = 5
  66. """5 pages maximum (``&p=5``): Trying to do more just results in an improper
  67. redirect"""
  68. qwant_categ = None
  69. """One of ``web-lite`` (or ``web``), ``news``, ``images`` or ``videos``"""
  70. safesearch = True
  71. # safe_search_map = {0: '&safesearch=0', 1: '&safesearch=1', 2: '&safesearch=2'}
  72. # fmt: off
  73. qwant_news_locales = [
  74. 'ca_ad', 'ca_es', 'ca_fr', 'co_fr', 'de_at', 'de_ch', 'de_de', 'en_au',
  75. 'en_ca', 'en_gb', 'en_ie', 'en_my', 'en_nz', 'en_us', 'es_ad', 'es_ar',
  76. 'es_cl', 'es_co', 'es_es', 'es_mx', 'es_pe', 'eu_es', 'eu_fr', 'fc_ca',
  77. 'fr_ad', 'fr_be', 'fr_ca', 'fr_ch', 'fr_fr', 'it_ch', 'it_it', 'nl_be',
  78. 'nl_nl', 'pt_ad', 'pt_pt',
  79. ]
  80. # fmt: on
  81. # search-url
  82. api_url = 'https://api.qwant.com/v3/search/'
  83. """URL of Qwant's API (JSON)"""
  84. web_lite_url = 'https://lite.qwant.com/'
  85. """URL of Qwant-Lite (HTML)"""
  86. def request(query, params):
  87. """Qwant search request"""
  88. if not query:
  89. return None
  90. q_locale = traits.get_region(params["searxng_locale"], default='en_US')
  91. url = api_url + f'{qwant_categ}?'
  92. args = {'q': query}
  93. params['raise_for_httperror'] = False
  94. if qwant_categ == 'web-lite':
  95. url = web_lite_url + '?'
  96. args['locale'] = q_locale.lower()
  97. args['l'] = q_locale.split('_')[0]
  98. args['s'] = params['safesearch']
  99. args['p'] = params['pageno']
  100. params['raise_for_httperror'] = True
  101. elif qwant_categ == 'images':
  102. args['locale'] = q_locale
  103. args['safesearch'] = params['safesearch']
  104. args['count'] = 50
  105. args['tgp'] = 3
  106. args['offset'] = (params['pageno'] - 1) * args['count']
  107. else: # web, news, videos
  108. args['locale'] = q_locale
  109. args['safesearch'] = params['safesearch']
  110. args['count'] = 10
  111. args['llm'] = 'false'
  112. args['tgp'] = 3
  113. args['offset'] = (params['pageno'] - 1) * args['count']
  114. params['url'] = url + urlencode(args)
  115. return params
  116. def response(resp):
  117. if qwant_categ == 'web-lite':
  118. return parse_web_lite(resp)
  119. return parse_web_api(resp)
  120. def parse_web_lite(resp):
  121. """Parse results from Qwant-Lite"""
  122. results = []
  123. dom = lxml.html.fromstring(resp.text)
  124. for item in eval_xpath_list(dom, '//section/article'):
  125. if eval_xpath(item, "./span[contains(@class, 'tooltip')]"):
  126. # ignore randomly interspersed advertising adds
  127. continue
  128. results.append(
  129. {
  130. 'url': extract_text(eval_xpath(item, "./span[contains(@class, 'url partner')]")),
  131. 'title': extract_text(eval_xpath(item, './h2/a')),
  132. 'content': extract_text(eval_xpath(item, './p')),
  133. }
  134. )
  135. return results
  136. def parse_web_api(resp):
  137. """Parse results from Qwant's API"""
  138. # pylint: disable=too-many-locals, too-many-branches, too-many-statements
  139. results = []
  140. # load JSON result
  141. search_results = loads(resp.text)
  142. data = search_results.get('data', {})
  143. # check for an API error
  144. if search_results.get('status') != 'success':
  145. error_code = data.get('error_code')
  146. if error_code == 24:
  147. raise SearxEngineTooManyRequestsException()
  148. if search_results.get("data", {}).get("error_data", {}).get("captchaUrl") is not None:
  149. raise SearxEngineCaptchaException()
  150. msg = ",".join(data.get('message', ['unknown']))
  151. raise SearxEngineAPIException(f"{msg} ({error_code})")
  152. # raise for other errors
  153. raise_for_httperror(resp)
  154. if qwant_categ == 'web':
  155. # The WEB query contains a list named 'mainline'. This list can contain
  156. # different result types (e.g. mainline[0]['type'] returns type of the
  157. # result items in mainline[0]['items']
  158. mainline = data.get('result', {}).get('items', {}).get('mainline', {})
  159. else:
  160. # Queries on News, Images and Videos do not have a list named 'mainline'
  161. # in the response. The result items are directly in the list
  162. # result['items'].
  163. mainline = data.get('result', {}).get('items', [])
  164. mainline = [
  165. {'type': qwant_categ, 'items': mainline},
  166. ]
  167. # return empty array if there are no results
  168. if not mainline:
  169. return []
  170. for row in mainline:
  171. mainline_type = row.get('type', 'web')
  172. if mainline_type != qwant_categ:
  173. continue
  174. if mainline_type == 'ads':
  175. # ignore adds
  176. continue
  177. mainline_items = row.get('items', [])
  178. for item in mainline_items:
  179. title = item.get('title', None)
  180. res_url = item.get('url', None)
  181. if mainline_type == 'web':
  182. content = item['desc']
  183. results.append(
  184. {
  185. 'title': title,
  186. 'url': res_url,
  187. 'content': content,
  188. }
  189. )
  190. elif mainline_type == 'news':
  191. pub_date = item['date']
  192. if pub_date is not None:
  193. pub_date = datetime.fromtimestamp(pub_date)
  194. news_media = item.get('media', [])
  195. thumbnail = None
  196. if news_media:
  197. thumbnail = news_media[0].get('pict', {}).get('url', None)
  198. results.append(
  199. {
  200. 'title': title,
  201. 'url': res_url,
  202. 'publishedDate': pub_date,
  203. 'thumbnail': thumbnail,
  204. }
  205. )
  206. elif mainline_type == 'images':
  207. thumbnail = item['thumbnail']
  208. img_src = item['media']
  209. results.append(
  210. {
  211. 'title': title,
  212. 'url': res_url,
  213. 'template': 'images.html',
  214. 'thumbnail_src': thumbnail,
  215. 'img_src': img_src,
  216. 'resolution': f"{item['width']} x {item['height']}",
  217. 'img_format': item.get('thumb_type'),
  218. }
  219. )
  220. elif mainline_type == 'videos':
  221. # some videos do not have a description: while qwant-video
  222. # returns an empty string, such video from a qwant-web query
  223. # miss the 'desc' key.
  224. d, s, c = item.get('desc'), item.get('source'), item.get('channel')
  225. content_parts = []
  226. if d:
  227. content_parts.append(d)
  228. if s:
  229. content_parts.append("%s: %s " % (gettext("Source"), s))
  230. if c:
  231. content_parts.append("%s: %s " % (gettext("Channel"), c))
  232. content = ' // '.join(content_parts)
  233. length = item['duration']
  234. if length is not None:
  235. length = timedelta(milliseconds=length)
  236. pub_date = item['date']
  237. if pub_date is not None:
  238. pub_date = datetime.fromtimestamp(pub_date)
  239. thumbnail = item['thumbnail']
  240. # from some locations (DE and others?) the s2 link do
  241. # response a 'Please wait ..' but does not deliver the thumbnail
  242. thumbnail = thumbnail.replace('https://s2.qwant.com', 'https://s1.qwant.com', 1)
  243. results.append(
  244. {
  245. 'title': title,
  246. 'url': res_url,
  247. 'content': content,
  248. 'iframe_src': get_embeded_stream_url(res_url),
  249. 'publishedDate': pub_date,
  250. 'thumbnail': thumbnail,
  251. 'template': 'videos.html',
  252. 'length': length,
  253. }
  254. )
  255. return results
  256. def fetch_traits(engine_traits: EngineTraits):
  257. # pylint: disable=import-outside-toplevel
  258. from searx import network
  259. from searx.locales import region_tag
  260. from searx.utils import extr
  261. resp = network.get(about['website'])
  262. json_string = extr(resp.text, 'INITIAL_PROPS = ', '</script>')
  263. q_initial_props = loads(json_string)
  264. q_locales = q_initial_props.get('locales')
  265. eng_tag_list = set()
  266. for country, v in q_locales.items():
  267. for lang in v['langs']:
  268. _locale = "{lang}_{country}".format(lang=lang, country=country)
  269. if qwant_categ == 'news' and _locale.lower() not in qwant_news_locales:
  270. # qwant-news does not support all locales from qwant-web:
  271. continue
  272. eng_tag_list.add(_locale)
  273. for eng_tag in eng_tag_list:
  274. try:
  275. sxng_tag = region_tag(babel.Locale.parse(eng_tag, sep='_'))
  276. except babel.UnknownLocaleError:
  277. print("ERROR: can't determine babel locale of quant's locale %s" % eng_tag)
  278. continue
  279. conflict = engine_traits.regions.get(sxng_tag)
  280. if conflict:
  281. if conflict != eng_tag:
  282. print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, eng_tag))
  283. continue
  284. engine_traits.regions[sxng_tag] = eng_tag