__init__.py 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. from os import listdir
  2. from os.path import realpath, dirname, join, isdir
  3. from sys import version_info
  4. from searx.utils import load_module
  5. from collections import defaultdict
  6. if version_info[0] == 3:
  7. unicode = str
  8. answerers_dir = dirname(realpath(__file__))
  9. def load_answerers():
  10. answerers = []
  11. for filename in listdir(answerers_dir):
  12. if not isdir(join(answerers_dir, filename)) or filename.startswith('_'):
  13. continue
  14. module = load_module('answerer.py', join(answerers_dir, filename))
  15. if not hasattr(module, 'keywords') or not isinstance(module.keywords, tuple) or not len(module.keywords):
  16. exit(2)
  17. answerers.append(module)
  18. return answerers
  19. def get_answerers_by_keywords(answerers):
  20. by_keyword = defaultdict(list)
  21. for answerer in answerers:
  22. for keyword in answerer.keywords:
  23. for keyword in answerer.keywords:
  24. by_keyword[keyword].append(answerer.answer)
  25. return by_keyword
  26. def ask(query):
  27. results = []
  28. query_parts = list(filter(None, query.query.split()))
  29. if query_parts[0].decode('utf-8') not in answerers_by_keywords:
  30. return results
  31. for answerer in answerers_by_keywords[query_parts[0].decode('utf-8')]:
  32. result = answerer(query)
  33. if result:
  34. results.append(result)
  35. return results
  36. answerers = load_answerers()
  37. answerers_by_keywords = get_answerers_by_keywords(answerers)