__init__.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. import sys
  15. import threading
  16. from os.path import realpath, dirname
  17. from babel.localedata import locale_identifiers
  18. from urllib.parse import urlparse
  19. from flask_babel import gettext
  20. from operator import itemgetter
  21. from searx import settings
  22. from searx import logger
  23. from searx.data import ENGINES_LANGUAGES
  24. from searx.exceptions import SearxEngineResponseException
  25. from searx.poolrequests import get, get_proxy_cycles
  26. from searx.utils import load_module, match_language, get_engine_from_settings, gen_useragent
  27. logger = logger.getChild('engines')
  28. engine_dir = dirname(realpath(__file__))
  29. engines = {}
  30. categories = {'general': []}
  31. babel_langs = [lang_parts[0] + '-' + lang_parts[-1] if len(lang_parts) > 1 else lang_parts[0]
  32. for lang_parts in (lang_code.split('_') for lang_code in locale_identifiers())]
  33. engine_shortcuts = {}
  34. engine_default_args = {'paging': False,
  35. 'categories': ['general'],
  36. 'supported_languages': [],
  37. 'safesearch': False,
  38. 'timeout': settings['outgoing']['request_timeout'],
  39. 'shortcut': '-',
  40. 'disabled': False,
  41. 'suspend_end_time': 0,
  42. 'continuous_errors': 0,
  43. 'time_range_support': False,
  44. 'engine_type': 'online',
  45. 'display_error_messages': True,
  46. 'tokens': []}
  47. def load_engine(engine_data):
  48. engine_name = engine_data['name']
  49. if '_' in engine_name:
  50. logger.error('Engine name contains underscore: "{}"'.format(engine_name))
  51. sys.exit(1)
  52. if engine_name.lower() != engine_name:
  53. logger.warn('Engine name is not lowercase: "{}", converting to lowercase'.format(engine_name))
  54. engine_name = engine_name.lower()
  55. engine_data['name'] = engine_name
  56. engine_module = engine_data['engine']
  57. try:
  58. engine = load_module(engine_module + '.py', engine_dir)
  59. except (SyntaxError, KeyboardInterrupt, SystemExit, SystemError, ImportError, RuntimeError):
  60. logger.exception('Fatal exception in engine "{}"'.format(engine_module))
  61. sys.exit(1)
  62. except:
  63. logger.exception('Cannot load engine "{}"'.format(engine_module))
  64. return None
  65. for param_name, param_value in engine_data.items():
  66. if param_name == 'engine':
  67. pass
  68. elif param_name == 'categories':
  69. if param_value == 'none':
  70. engine.categories = []
  71. else:
  72. engine.categories = list(map(str.strip, param_value.split(',')))
  73. elif param_name == 'proxies':
  74. engine.proxies = get_proxy_cycles(param_value)
  75. else:
  76. setattr(engine, param_name, param_value)
  77. for arg_name, arg_value in engine_default_args.items():
  78. if not hasattr(engine, arg_name):
  79. setattr(engine, arg_name, arg_value)
  80. # checking required variables
  81. for engine_attr in dir(engine):
  82. if engine_attr.startswith('_'):
  83. continue
  84. if engine_attr == 'inactive' and getattr(engine, engine_attr) is True:
  85. return None
  86. if getattr(engine, engine_attr) is None:
  87. logger.error('Missing engine config attribute: "{0}.{1}"'
  88. .format(engine.name, engine_attr))
  89. sys.exit(1)
  90. # assign supported languages from json file
  91. if engine_data['name'] in ENGINES_LANGUAGES:
  92. setattr(engine, 'supported_languages', ENGINES_LANGUAGES[engine_data['name']])
  93. # find custom aliases for non standard language codes
  94. if hasattr(engine, 'supported_languages'):
  95. if hasattr(engine, 'language_aliases'):
  96. language_aliases = getattr(engine, 'language_aliases')
  97. else:
  98. language_aliases = {}
  99. for engine_lang in getattr(engine, 'supported_languages'):
  100. iso_lang = match_language(engine_lang, babel_langs, fallback=None)
  101. if iso_lang and iso_lang != engine_lang and not engine_lang.startswith(iso_lang) and \
  102. iso_lang not in getattr(engine, 'supported_languages'):
  103. language_aliases[iso_lang] = engine_lang
  104. setattr(engine, 'language_aliases', language_aliases)
  105. # language_support
  106. setattr(engine, 'language_support', len(getattr(engine, 'supported_languages', [])) > 0)
  107. # assign language fetching method if auxiliary method exists
  108. if hasattr(engine, '_fetch_supported_languages'):
  109. headers = {
  110. 'User-Agent': gen_useragent(),
  111. 'Accept-Language': 'ja-JP,ja;q=0.8,en-US;q=0.5,en;q=0.3', # bing needs a non-English language
  112. }
  113. setattr(engine, 'fetch_supported_languages',
  114. lambda: engine._fetch_supported_languages(get(engine.supported_languages_url, headers=headers)))
  115. engine.stats = {
  116. 'sent_search_count': 0, # sent search
  117. 'search_count': 0, # succesful search
  118. 'result_count': 0,
  119. 'engine_time': 0,
  120. 'engine_time_count': 0,
  121. 'score_count': 0,
  122. 'errors': 0
  123. }
  124. engine_type = getattr(engine, 'engine_type', 'online')
  125. if engine_type != 'offline':
  126. engine.stats['page_load_time'] = 0
  127. engine.stats['page_load_count'] = 0
  128. # tor related settings
  129. if settings['outgoing'].get('using_tor_proxy'):
  130. # use onion url if using tor.
  131. if hasattr(engine, 'onion_url'):
  132. engine.search_url = engine.onion_url + getattr(engine, 'search_path', '')
  133. elif 'onions' in engine.categories:
  134. # exclude onion engines if not using tor.
  135. return None
  136. engine.timeout += settings['outgoing'].get('extra_proxy_timeout', 0)
  137. for category_name in engine.categories:
  138. categories.setdefault(category_name, []).append(engine)
  139. if engine.shortcut in engine_shortcuts:
  140. logger.error('Engine config error: ambigious shortcut: {0}'.format(engine.shortcut))
  141. sys.exit(1)
  142. engine_shortcuts[engine.shortcut] = engine.name
  143. return engine
  144. def to_percentage(stats, maxvalue):
  145. for engine_stat in stats:
  146. if maxvalue:
  147. engine_stat['percentage'] = int(engine_stat['avg'] / maxvalue * 100)
  148. else:
  149. engine_stat['percentage'] = 0
  150. return stats
  151. def get_engines_stats(preferences):
  152. # TODO refactor
  153. pageloads = []
  154. engine_times = []
  155. results = []
  156. scores = []
  157. errors = []
  158. scores_per_result = []
  159. max_pageload = max_engine_times = max_results = max_score = max_errors = max_score_per_result = 0 # noqa
  160. for engine in engines.values():
  161. if not preferences.validate_token(engine):
  162. continue
  163. if engine.stats['search_count'] == 0:
  164. continue
  165. results_num = \
  166. engine.stats['result_count'] / float(engine.stats['search_count'])
  167. if engine.stats['engine_time_count'] != 0:
  168. this_engine_time = engine.stats['engine_time'] / float(engine.stats['engine_time_count']) # noqa
  169. else:
  170. this_engine_time = 0
  171. if results_num:
  172. score = engine.stats['score_count'] / float(engine.stats['search_count']) # noqa
  173. score_per_result = score / results_num
  174. else:
  175. score = score_per_result = 0.0
  176. if engine.engine_type != 'offline':
  177. load_times = 0
  178. if engine.stats['page_load_count'] != 0:
  179. load_times = engine.stats['page_load_time'] / float(engine.stats['page_load_count']) # noqa
  180. max_pageload = max(load_times, max_pageload)
  181. pageloads.append({'avg': load_times, 'name': engine.name})
  182. max_engine_times = max(this_engine_time, max_engine_times)
  183. max_results = max(results_num, max_results)
  184. max_score = max(score, max_score)
  185. max_score_per_result = max(score_per_result, max_score_per_result)
  186. max_errors = max(max_errors, engine.stats['errors'])
  187. engine_times.append({'avg': this_engine_time, 'name': engine.name})
  188. results.append({'avg': results_num, 'name': engine.name})
  189. scores.append({'avg': score, 'name': engine.name})
  190. errors.append({'avg': engine.stats['errors'], 'name': engine.name})
  191. scores_per_result.append({
  192. 'avg': score_per_result,
  193. 'name': engine.name
  194. })
  195. pageloads = to_percentage(pageloads, max_pageload)
  196. engine_times = to_percentage(engine_times, max_engine_times)
  197. results = to_percentage(results, max_results)
  198. scores = to_percentage(scores, max_score)
  199. scores_per_result = to_percentage(scores_per_result, max_score_per_result)
  200. errors = to_percentage(errors, max_errors)
  201. return [
  202. (
  203. gettext('Engine time (sec)'),
  204. sorted(engine_times, key=itemgetter('avg'))
  205. ),
  206. (
  207. gettext('Page loads (sec)'),
  208. sorted(pageloads, key=itemgetter('avg'))
  209. ),
  210. (
  211. gettext('Number of results'),
  212. sorted(results, key=itemgetter('avg'), reverse=True)
  213. ),
  214. (
  215. gettext('Scores'),
  216. sorted(scores, key=itemgetter('avg'), reverse=True)
  217. ),
  218. (
  219. gettext('Scores per result'),
  220. sorted(scores_per_result, key=itemgetter('avg'), reverse=True)
  221. ),
  222. (
  223. gettext('Errors'),
  224. sorted(errors, key=itemgetter('avg'), reverse=True)
  225. ),
  226. ]
  227. def load_engines(engine_list):
  228. global engines, engine_shortcuts
  229. engines.clear()
  230. engine_shortcuts.clear()
  231. for engine_data in engine_list:
  232. engine = load_engine(engine_data)
  233. if engine is not None:
  234. engines[engine.name] = engine
  235. return engines
  236. def initialize_engines(engine_list):
  237. load_engines(engine_list)
  238. def engine_init(engine_name, init_fn):
  239. try:
  240. init_fn(get_engine_from_settings(engine_name))
  241. except SearxEngineResponseException as exc:
  242. logger.warn('%s engine: Fail to initialize // %s', engine_name, exc)
  243. except Exception:
  244. logger.exception('%s engine: Fail to initialize', engine_name)
  245. else:
  246. logger.debug('%s engine: Initialized', engine_name)
  247. for engine_name, engine in engines.items():
  248. if hasattr(engine, 'init'):
  249. init_fn = getattr(engine, 'init')
  250. if init_fn:
  251. logger.debug('%s engine: Starting background initialization', engine_name)
  252. threading.Thread(target=engine_init, args=(engine_name, init_fn)).start()
  253. _set_https_support_for_engine(engine)
  254. def _set_https_support_for_engine(engine):
  255. # check HTTPS support if it is not disabled
  256. if engine.engine_type != 'offline' and not hasattr(engine, 'https_support'):
  257. params = engine.request('http_test', {
  258. 'method': 'GET',
  259. 'headers': {},
  260. 'data': {},
  261. 'url': '',
  262. 'cookies': {},
  263. 'verify': True,
  264. 'auth': None,
  265. 'pageno': 1,
  266. 'time_range': None,
  267. 'language': '',
  268. 'safesearch': False,
  269. 'is_test': True,
  270. 'category': 'files',
  271. 'raise_for_status': True,
  272. 'engine_data': {},
  273. })
  274. if 'url' not in params:
  275. return
  276. parsed_url = urlparse(params['url'])
  277. https_support = parsed_url.scheme == 'https'
  278. setattr(engine, 'https_support', https_support)