__init__.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. from os import listdir
  16. from imp import load_source
  17. import grequests
  18. from itertools import izip_longest, chain
  19. from operator import itemgetter
  20. engine_dir = dirname(realpath(__file__))
  21. engines = {}
  22. for filename in listdir(engine_dir):
  23. modname = splitext(filename)[0]
  24. if filename.startswith('_') or not filename.endswith('.py'):
  25. continue
  26. filepath = join(engine_dir, filename)
  27. engine = load_source(modname, filepath)
  28. if not hasattr(engine, 'request') or not hasattr(engine, 'response'):
  29. continue
  30. engines[modname] = engine
  31. def default_request_params():
  32. return {'method': 'GET', 'headers': {}, 'data': {}, 'url': ''}
  33. def make_callback(engine_name, results, callback):
  34. def process_callback(response, **kwargs):
  35. cb_res = []
  36. for result in callback(response):
  37. result['engine'] = engine_name
  38. cb_res.append(result)
  39. results[engine_name] = cb_res
  40. return process_callback
  41. def search(query, request, selected_engines):
  42. global engines
  43. requests = []
  44. results = {}
  45. user_agent = request.headers.get('User-Agent', '')
  46. for ename, engine in engines.items():
  47. if ename not in selected_engines:
  48. continue
  49. headers = default_request_params()
  50. headers['User-Agent'] = user_agent
  51. request_params = engine.request(query, headers)
  52. callback = make_callback(ename, results, engine.response)
  53. if request_params['method'] == 'GET':
  54. req = grequests.get(request_params['url']
  55. ,headers=headers
  56. ,hooks=dict(response=callback)
  57. )
  58. else:
  59. req = grequests.post(request_params['url']
  60. ,data=request_params['data']
  61. ,headers=headers
  62. ,hooks=dict(response=callback)
  63. )
  64. requests.append(req)
  65. grequests.map(requests)
  66. flat_res = list(filter(None, chain(*izip_longest(*results.values()))))
  67. flat_len = len(flat_res)
  68. results = []
  69. # deduplication + scoring
  70. for i,res in enumerate(flat_res):
  71. score = flat_len - i
  72. duplicated = False
  73. for new_res in results:
  74. if res['url'] == new_res['url']:
  75. duplicated = new_res
  76. break
  77. if duplicated:
  78. if len(res['content']) > len(duplicated):
  79. duplicated['content'] = res['content']
  80. duplicated['score'] += score
  81. else:
  82. res['score'] = score
  83. results.append(res)
  84. return sorted(results, key=itemgetter('score'), reverse=True)