__init__.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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 os.path import realpath, dirname, splitext, join
  15. import sys
  16. from imp import load_source
  17. from flask.ext.babel import gettext
  18. from operator import itemgetter
  19. from searx import settings
  20. from searx import logger
  21. logger = logger.getChild('engines')
  22. engine_dir = dirname(realpath(__file__))
  23. engines = {}
  24. categories = {'general': []}
  25. engine_shortcuts = {}
  26. def load_module(filename):
  27. modname = splitext(filename)[0]
  28. if modname in sys.modules:
  29. del sys.modules[modname]
  30. filepath = join(engine_dir, filename)
  31. module = load_source(modname, filepath)
  32. module.name = modname
  33. return module
  34. def load_engine(engine_data):
  35. engine_name = engine_data['engine']
  36. engine = load_module(engine_name + '.py')
  37. for param_name in engine_data:
  38. if param_name == 'engine':
  39. continue
  40. if param_name == 'categories':
  41. if engine_data['categories'] == 'none':
  42. engine.categories = []
  43. else:
  44. engine.categories = map(
  45. str.strip, engine_data['categories'].split(','))
  46. continue
  47. setattr(engine, param_name, engine_data[param_name])
  48. if not hasattr(engine, 'paging'):
  49. engine.paging = False
  50. if not hasattr(engine, 'categories'):
  51. engine.categories = ['general']
  52. if not hasattr(engine, 'language_support'):
  53. engine.language_support = True
  54. if not hasattr(engine, 'safesearch'):
  55. engine.safesearch = False
  56. if not hasattr(engine, 'timeout'):
  57. engine.timeout = settings['outgoing']['request_timeout']
  58. if not hasattr(engine, 'shortcut'):
  59. engine.shortcut = ''
  60. if not hasattr(engine, 'disabled'):
  61. engine.disabled = False
  62. # checking required variables
  63. for engine_attr in dir(engine):
  64. if engine_attr.startswith('_'):
  65. continue
  66. if getattr(engine, engine_attr) is None:
  67. logger.error('Missing engine config attribute: "{0}.{1}"'
  68. .format(engine.name, engine_attr))
  69. sys.exit(1)
  70. engine.stats = {
  71. 'result_count': 0,
  72. 'search_count': 0,
  73. 'page_load_time': 0,
  74. 'score_count': 0,
  75. 'errors': 0
  76. }
  77. if hasattr(engine, 'categories'):
  78. for category_name in engine.categories:
  79. categories.setdefault(category_name, []).append(engine)
  80. else:
  81. categories['general'].append(engine)
  82. if engine.shortcut:
  83. if engine.shortcut in engine_shortcuts:
  84. logger.error('Engine config error: ambigious shortcut: {0}'
  85. .format(engine.shortcut))
  86. sys.exit(1)
  87. engine_shortcuts[engine.shortcut] = engine.name
  88. return engine
  89. def get_engines_stats():
  90. # TODO refactor
  91. pageloads = []
  92. results = []
  93. scores = []
  94. errors = []
  95. scores_per_result = []
  96. max_pageload = max_results = max_score = max_errors = max_score_per_result = 0 # noqa
  97. for engine in engines.values():
  98. if engine.stats['search_count'] == 0:
  99. continue
  100. results_num = \
  101. engine.stats['result_count'] / float(engine.stats['search_count'])
  102. load_times = engine.stats['page_load_time'] / float(engine.stats['search_count']) # noqa
  103. if results_num:
  104. score = engine.stats['score_count'] / float(engine.stats['search_count']) # noqa
  105. score_per_result = score / results_num
  106. else:
  107. score = score_per_result = 0.0
  108. max_results = max(results_num, max_results)
  109. max_pageload = max(load_times, max_pageload)
  110. max_score = max(score, max_score)
  111. max_score_per_result = max(score_per_result, max_score_per_result)
  112. max_errors = max(max_errors, engine.stats['errors'])
  113. pageloads.append({'avg': load_times, 'name': engine.name})
  114. results.append({'avg': results_num, 'name': engine.name})
  115. scores.append({'avg': score, 'name': engine.name})
  116. errors.append({'avg': engine.stats['errors'], 'name': engine.name})
  117. scores_per_result.append({
  118. 'avg': score_per_result,
  119. 'name': engine.name
  120. })
  121. for engine in pageloads:
  122. if max_pageload:
  123. engine['percentage'] = int(engine['avg'] / max_pageload * 100)
  124. else:
  125. engine['percentage'] = 0
  126. for engine in results:
  127. if max_results:
  128. engine['percentage'] = int(engine['avg'] / max_results * 100)
  129. else:
  130. engine['percentage'] = 0
  131. for engine in scores:
  132. if max_score:
  133. engine['percentage'] = int(engine['avg'] / max_score * 100)
  134. else:
  135. engine['percentage'] = 0
  136. for engine in scores_per_result:
  137. if max_score_per_result:
  138. engine['percentage'] = int(engine['avg']
  139. / max_score_per_result * 100)
  140. else:
  141. engine['percentage'] = 0
  142. for engine in errors:
  143. if max_errors:
  144. engine['percentage'] = int(float(engine['avg']) / max_errors * 100)
  145. else:
  146. engine['percentage'] = 0
  147. return [
  148. (
  149. gettext('Page loads (sec)'),
  150. sorted(pageloads, key=itemgetter('avg'))
  151. ),
  152. (
  153. gettext('Number of results'),
  154. sorted(results, key=itemgetter('avg'), reverse=True)
  155. ),
  156. (
  157. gettext('Scores'),
  158. sorted(scores, key=itemgetter('avg'), reverse=True)
  159. ),
  160. (
  161. gettext('Scores per result'),
  162. sorted(scores_per_result, key=itemgetter('avg'), reverse=True)
  163. ),
  164. (
  165. gettext('Errors'),
  166. sorted(errors, key=itemgetter('avg'), reverse=True)
  167. ),
  168. ]
  169. if 'engines' not in settings or not settings['engines']:
  170. logger.error('No engines found. Edit your settings.yml')
  171. exit(2)
  172. for engine_data in settings['engines']:
  173. engine = load_engine(engine_data)
  174. engines[engine.name] = engine