autocomplete.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. '''
  2. searx is free software: you can redistribute it and/or modify
  3. it under the terms of the GNU Affero General Public License as published by
  4. the Free Software Foundation, either version 3 of the License, or
  5. (at your option) any later version.
  6. searx is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. GNU Affero General Public License for more details.
  10. You should have received a copy of the GNU Affero General Public License
  11. along with searx. If not, see < http://www.gnu.org/licenses/ >.
  12. (C) 2013- by Adam Tauber, <asciimoo@gmail.com>
  13. '''
  14. from lxml import etree
  15. from json import loads
  16. from urllib.parse import urlencode
  17. from httpx import HTTPError
  18. from searx import settings
  19. from searx.data import ENGINES_LANGUAGES
  20. from searx.network import get as http_get
  21. from searx.exceptions import SearxEngineResponseException
  22. def get(*args, **kwargs):
  23. if 'timeout' not in kwargs:
  24. kwargs['timeout'] = settings['outgoing']['request_timeout']
  25. kwargs['raise_for_httperror'] = True
  26. return http_get(*args, **kwargs)
  27. def dbpedia(query, lang):
  28. # dbpedia autocompleter, no HTTPS
  29. autocomplete_url = 'https://lookup.dbpedia.org/api/search.asmx/KeywordSearch?'
  30. response = get(autocomplete_url + urlencode(dict(QueryString=query)))
  31. results = []
  32. if response.ok:
  33. dom = etree.fromstring(response.content)
  34. results = dom.xpath('//Result/Label//text()')
  35. return results
  36. def duckduckgo(query, lang):
  37. # duckduckgo autocompleter
  38. url = 'https://ac.duckduckgo.com/ac/?{0}&type=list'
  39. resp = loads(get(url.format(urlencode(dict(q=query)))).text)
  40. if len(resp) > 1:
  41. return resp[1]
  42. return []
  43. def google(query, lang):
  44. # google autocompleter
  45. autocomplete_url = 'https://suggestqueries.google.com/complete/search?client=toolbar&'
  46. response = get(autocomplete_url + urlencode(dict(hl=lang, q=query)))
  47. results = []
  48. if response.ok:
  49. dom = etree.fromstring(response.text)
  50. results = dom.xpath('//suggestion/@data')
  51. return results
  52. def startpage(query, lang):
  53. # startpage autocompleter
  54. lui = ENGINES_LANGUAGES['startpage'].get(lang, 'english')
  55. url = 'https://startpage.com/suggestions?{query}'
  56. resp = get(url.format(query=urlencode({'q': query, 'segment': 'startpage.udog', 'lui': lui})))
  57. data = resp.json()
  58. return [e['text'] for e in data.get('suggestions', []) if 'text' in e]
  59. def swisscows(query, lang):
  60. # swisscows autocompleter
  61. url = 'https://swisscows.ch/api/suggest?{query}&itemsCount=5'
  62. resp = loads(get(url.format(query=urlencode({'query': query}))).text)
  63. return resp
  64. def qwant(query, lang):
  65. # qwant autocompleter (additional parameter : lang=en_en&count=xxx )
  66. url = 'https://api.qwant.com/api/suggest?{query}'
  67. resp = get(url.format(query=urlencode({'q': query, 'lang': lang})))
  68. results = []
  69. if resp.ok:
  70. data = loads(resp.text)
  71. if data['status'] == 'success':
  72. for item in data['data']['items']:
  73. results.append(item['value'])
  74. return results
  75. def wikipedia(query, lang):
  76. # wikipedia autocompleter
  77. url = 'https://' + lang + '.wikipedia.org/w/api.php?action=opensearch&{0}&limit=10&namespace=0&format=json'
  78. resp = loads(get(url.format(urlencode(dict(search=query)))).text)
  79. if len(resp) > 1:
  80. return resp[1]
  81. return []
  82. backends = {
  83. 'dbpedia': dbpedia,
  84. 'duckduckgo': duckduckgo,
  85. 'google': google,
  86. 'startpage': startpage,
  87. 'swisscows': swisscows,
  88. 'qwant': qwant,
  89. 'wikipedia': wikipedia,
  90. }
  91. def search_autocomplete(backend_name, query, lang):
  92. backend = backends.get(backend_name)
  93. if backend is None:
  94. return []
  95. try:
  96. return backend(query, lang)
  97. except (HTTPError, SearxEngineResponseException):
  98. return []