__init__.py 1.3 KB

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