qwant.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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
  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
  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. msg = ",".join(
  140. data.get(
  141. 'message',
  142. [
  143. 'unknown',
  144. ],
  145. )
  146. )
  147. raise SearxEngineAPIException('API error::' + msg)
  148. # raise for other errors
  149. raise_for_httperror(resp)
  150. if qwant_categ == 'web':
  151. # The WEB query contains a list named 'mainline'. This list can contain
  152. # different result types (e.g. mainline[0]['type'] returns type of the
  153. # result items in mainline[0]['items']
  154. mainline = data.get('result', {}).get('items', {}).get('mainline', {})
  155. else:
  156. # Queries on News, Images and Videos do not have a list named 'mainline'
  157. # in the response. The result items are directly in the list
  158. # result['items'].
  159. mainline = data.get('result', {}).get('items', [])
  160. mainline = [
  161. {'type': qwant_categ, 'items': mainline},
  162. ]
  163. # return empty array if there are no results
  164. if not mainline:
  165. return []
  166. for row in mainline:
  167. mainline_type = row.get('type', 'web')
  168. if mainline_type != qwant_categ:
  169. continue
  170. if mainline_type == 'ads':
  171. # ignore adds
  172. continue
  173. mainline_items = row.get('items', [])
  174. for item in mainline_items:
  175. title = item.get('title', None)
  176. res_url = item.get('url', None)
  177. if mainline_type == 'web':
  178. content = item['desc']
  179. results.append(
  180. {
  181. 'title': title,
  182. 'url': res_url,
  183. 'content': content,
  184. }
  185. )
  186. elif mainline_type == 'news':
  187. pub_date = item['date']
  188. if pub_date is not None:
  189. pub_date = datetime.fromtimestamp(pub_date)
  190. news_media = item.get('media', [])
  191. img_src = None
  192. if news_media:
  193. img_src = news_media[0].get('pict', {}).get('url', None)
  194. results.append(
  195. {
  196. 'title': title,
  197. 'url': res_url,
  198. 'publishedDate': pub_date,
  199. 'img_src': img_src,
  200. }
  201. )
  202. elif mainline_type == 'images':
  203. thumbnail = item['thumbnail']
  204. img_src = item['media']
  205. results.append(
  206. {
  207. 'title': title,
  208. 'url': res_url,
  209. 'template': 'images.html',
  210. 'thumbnail_src': thumbnail,
  211. 'img_src': img_src,
  212. }
  213. )
  214. elif mainline_type == 'videos':
  215. # some videos do not have a description: while qwant-video
  216. # returns an empty string, such video from a qwant-web query
  217. # miss the 'desc' key.
  218. d, s, c = item.get('desc'), item.get('source'), item.get('channel')
  219. content_parts = []
  220. if d:
  221. content_parts.append(d)
  222. if s:
  223. content_parts.append("%s: %s " % (gettext("Source"), s))
  224. if c:
  225. content_parts.append("%s: %s " % (gettext("Channel"), c))
  226. content = ' // '.join(content_parts)
  227. length = item['duration']
  228. if length is not None:
  229. length = timedelta(milliseconds=length)
  230. pub_date = item['date']
  231. if pub_date is not None:
  232. pub_date = datetime.fromtimestamp(pub_date)
  233. thumbnail = item['thumbnail']
  234. # from some locations (DE and others?) the s2 link do
  235. # response a 'Please wait ..' but does not deliver the thumbnail
  236. thumbnail = thumbnail.replace('https://s2.qwant.com', 'https://s1.qwant.com', 1)
  237. results.append(
  238. {
  239. 'title': title,
  240. 'url': res_url,
  241. 'content': content,
  242. 'publishedDate': pub_date,
  243. 'thumbnail': thumbnail,
  244. 'template': 'videos.html',
  245. 'length': length,
  246. }
  247. )
  248. return results
  249. def fetch_traits(engine_traits: EngineTraits):
  250. # pylint: disable=import-outside-toplevel
  251. from searx import network
  252. from searx.locales import region_tag
  253. resp = network.get(about['website'])
  254. text = resp.text
  255. text = text[text.find('INITIAL_PROPS') :]
  256. text = text[text.find('{') : text.find('</script>')]
  257. q_initial_props = loads(text)
  258. q_locales = q_initial_props.get('locales')
  259. eng_tag_list = set()
  260. for country, v in q_locales.items():
  261. for lang in v['langs']:
  262. _locale = "{lang}_{country}".format(lang=lang, country=country)
  263. if qwant_categ == 'news' and _locale.lower() not in qwant_news_locales:
  264. # qwant-news does not support all locales from qwant-web:
  265. continue
  266. eng_tag_list.add(_locale)
  267. for eng_tag in eng_tag_list:
  268. try:
  269. sxng_tag = region_tag(babel.Locale.parse(eng_tag, sep='_'))
  270. except babel.UnknownLocaleError:
  271. print("ERROR: can't determine babel locale of quant's locale %s" % eng_tag)
  272. continue
  273. conflict = engine_traits.regions.get(sxng_tag)
  274. if conflict:
  275. if conflict != eng_tag:
  276. print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, eng_tag))
  277. continue
  278. engine_traits.regions[sxng_tag] = eng_tag