qwant.py 10 KB

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