autocomplete.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """This module implements functions needed for the autocompleter.
  4. """
  5. # pylint: disable=use-dict-literal
  6. import json
  7. from urllib.parse import urlencode
  8. import lxml
  9. from httpx import HTTPError
  10. from searx import settings
  11. from searx.engines import (
  12. engines,
  13. google,
  14. )
  15. from searx.network import get as http_get
  16. from searx.exceptions import SearxEngineResponseException
  17. def get(*args, **kwargs):
  18. if 'timeout' not in kwargs:
  19. kwargs['timeout'] = settings['outgoing']['request_timeout']
  20. kwargs['raise_for_httperror'] = True
  21. return http_get(*args, **kwargs)
  22. def brave(query, _lang):
  23. # brave search autocompleter
  24. url = 'https://search.brave.com/api/suggest?'
  25. url += urlencode({'q': query})
  26. country = 'all'
  27. # if lang in _brave:
  28. # country = lang
  29. kwargs = {'cookies': {'country': country}}
  30. resp = get(url, **kwargs)
  31. results = []
  32. if resp.ok:
  33. data = resp.json()
  34. for item in data[1]:
  35. results.append(item)
  36. return results
  37. def dbpedia(query, _lang):
  38. # dbpedia autocompleter, no HTTPS
  39. autocomplete_url = 'https://lookup.dbpedia.org/api/search.asmx/KeywordSearch?'
  40. response = get(autocomplete_url + urlencode(dict(QueryString=query)))
  41. results = []
  42. if response.ok:
  43. dom = lxml.etree.fromstring(response.content)
  44. results = dom.xpath('//Result/Label//text()')
  45. return results
  46. def duckduckgo(query, sxng_locale):
  47. """Autocomplete from DuckDuckGo. Supports DuckDuckGo's languages"""
  48. traits = engines['duckduckgo'].traits
  49. args = {
  50. 'q': query,
  51. 'kl': traits.get_region(sxng_locale, traits.all_locale),
  52. }
  53. url = 'https://duckduckgo.com/ac/?type=list&' + urlencode(args)
  54. resp = get(url)
  55. ret_val = []
  56. if resp.ok:
  57. j = resp.json()
  58. if len(j) > 1:
  59. ret_val = j[1]
  60. return ret_val
  61. def google_complete(query, sxng_locale):
  62. """Autocomplete from Google. Supports Google's languages and subdomains
  63. (:py:obj:`searx.engines.google.get_google_info`) by using the async REST
  64. API::
  65. https://{subdomain}/complete/search?{args}
  66. """
  67. google_info = google.get_google_info({'searxng_locale': sxng_locale}, engines['google'].traits)
  68. url = 'https://{subdomain}/complete/search?{args}'
  69. args = urlencode(
  70. {
  71. 'q': query,
  72. 'client': 'gws-wiz',
  73. 'hl': google_info['params']['hl'],
  74. }
  75. )
  76. results = []
  77. resp = get(url.format(subdomain=google_info['subdomain'], args=args))
  78. if resp.ok:
  79. json_txt = resp.text[resp.text.find('[') : resp.text.find(']', -3) + 1]
  80. data = json.loads(json_txt)
  81. for item in data[0]:
  82. results.append(lxml.html.fromstring(item[0]).text_content())
  83. return results
  84. def seznam(query, _lang):
  85. # seznam search autocompleter
  86. url = 'https://suggest.seznam.cz/fulltext/cs?{query}'
  87. resp = get(
  88. url.format(
  89. query=urlencode(
  90. {'phrase': query, 'cursorPosition': len(query), 'format': 'json-2', 'highlight': '1', 'count': '6'}
  91. )
  92. )
  93. )
  94. if not resp.ok:
  95. return []
  96. data = resp.json()
  97. return [
  98. ''.join([part.get('text', '') for part in item.get('text', [])])
  99. for item in data.get('result', [])
  100. if item.get('itemType', None) == 'ItemType.TEXT'
  101. ]
  102. def startpage(query, sxng_locale):
  103. """Autocomplete from Startpage. Supports Startpage's languages"""
  104. lui = engines['startpage'].traits.get_language(sxng_locale, 'english')
  105. url = 'https://startpage.com/suggestions?{query}'
  106. resp = get(url.format(query=urlencode({'q': query, 'segment': 'startpage.udog', 'lui': lui})))
  107. data = resp.json()
  108. return [e['text'] for e in data.get('suggestions', []) if 'text' in e]
  109. def swisscows(query, _lang):
  110. # swisscows autocompleter
  111. url = 'https://swisscows.ch/api/suggest?{query}&itemsCount=5'
  112. resp = json.loads(get(url.format(query=urlencode({'query': query}))).text)
  113. return resp
  114. def qwant(query, sxng_locale):
  115. """Autocomplete from Qwant. Supports Qwant's regions."""
  116. results = []
  117. locale = engines['qwant'].traits.get_region(sxng_locale, 'en_US')
  118. url = 'https://api.qwant.com/v3/suggest?{query}'
  119. resp = get(url.format(query=urlencode({'q': query, 'locale': locale, 'version': '2'})))
  120. if resp.ok:
  121. data = resp.json()
  122. if data['status'] == 'success':
  123. for item in data['data']['items']:
  124. results.append(item['value'])
  125. return results
  126. def wikipedia(query, sxng_locale):
  127. """Autocomplete from Wikipedia. Supports Wikipedia's languages (aka netloc)."""
  128. results = []
  129. eng_traits = engines['wikipedia'].traits
  130. wiki_lang = eng_traits.get_language(sxng_locale, 'en')
  131. wiki_netloc = eng_traits.custom['wiki_netloc'].get(wiki_lang, 'en.wikipedia.org')
  132. url = 'https://{wiki_netloc}/w/api.php?{args}'
  133. args = urlencode(
  134. {
  135. 'action': 'opensearch',
  136. 'format': 'json',
  137. 'formatversion': '2',
  138. 'search': query,
  139. 'namespace': '0',
  140. 'limit': '10',
  141. }
  142. )
  143. resp = get(url.format(args=args, wiki_netloc=wiki_netloc))
  144. if resp.ok:
  145. data = resp.json()
  146. if len(data) > 1:
  147. results = data[1]
  148. return results
  149. def yandex(query, _lang):
  150. # yandex autocompleter
  151. url = "https://suggest.yandex.com/suggest-ff.cgi?{0}"
  152. resp = json.loads(get(url.format(urlencode(dict(part=query)))).text)
  153. if len(resp) > 1:
  154. return resp[1]
  155. return []
  156. backends = {
  157. 'dbpedia': dbpedia,
  158. 'duckduckgo': duckduckgo,
  159. 'google': google_complete,
  160. 'seznam': seznam,
  161. 'startpage': startpage,
  162. 'swisscows': swisscows,
  163. 'qwant': qwant,
  164. 'wikipedia': wikipedia,
  165. 'brave': brave,
  166. 'yandex': yandex,
  167. }
  168. def search_autocomplete(backend_name, query, sxng_locale):
  169. backend = backends.get(backend_name)
  170. if backend is None:
  171. return []
  172. try:
  173. return backend(query, sxng_locale)
  174. except (HTTPError, SearxEngineResponseException):
  175. return []