2024-03-11 13:06:26 +00:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
# pylint: disable=missing-module-docstring
|
|
|
|
|
|
|
|
import sys
|
2016-11-19 19:53:51 +00:00
|
|
|
from os import listdir
|
|
|
|
from os.path import realpath, dirname, join, isdir
|
|
|
|
from collections import defaultdict
|
|
|
|
|
2024-03-11 13:06:26 +00:00
|
|
|
from searx.utils import load_module
|
2016-11-19 19:53:51 +00:00
|
|
|
|
|
|
|
answerers_dir = dirname(realpath(__file__))
|
|
|
|
|
|
|
|
|
|
|
|
def load_answerers():
|
2024-03-11 13:06:26 +00:00
|
|
|
answerers = [] # pylint: disable=redefined-outer-name
|
|
|
|
|
2016-11-19 19:53:51 +00:00
|
|
|
for filename in listdir(answerers_dir):
|
2016-11-30 17:43:03 +00:00
|
|
|
if not isdir(join(answerers_dir, filename)) or filename.startswith('_'):
|
2016-11-19 19:53:51 +00:00
|
|
|
continue
|
|
|
|
module = load_module('answerer.py', join(answerers_dir, filename))
|
2024-03-11 13:06:26 +00:00
|
|
|
if not hasattr(module, 'keywords') or not isinstance(module.keywords, tuple) or not module.keywords:
|
|
|
|
sys.exit(2)
|
2016-11-19 19:53:51 +00:00
|
|
|
answerers.append(module)
|
|
|
|
return answerers
|
|
|
|
|
|
|
|
|
2024-03-11 13:06:26 +00:00
|
|
|
def get_answerers_by_keywords(answerers): # pylint:disable=redefined-outer-name
|
2016-11-19 19:53:51 +00:00
|
|
|
by_keyword = defaultdict(list)
|
|
|
|
for answerer in answerers:
|
|
|
|
for keyword in answerer.keywords:
|
|
|
|
for keyword in answerer.keywords:
|
|
|
|
by_keyword[keyword].append(answerer.answer)
|
|
|
|
return by_keyword
|
|
|
|
|
|
|
|
|
|
|
|
def ask(query):
|
|
|
|
results = []
|
2016-11-30 17:43:03 +00:00
|
|
|
query_parts = list(filter(None, query.query.split()))
|
2016-11-19 19:53:51 +00:00
|
|
|
|
2021-02-22 17:10:57 +00:00
|
|
|
if not query_parts or query_parts[0] not in answerers_by_keywords:
|
2016-11-19 19:53:51 +00:00
|
|
|
return results
|
|
|
|
|
2020-08-11 14:25:03 +00:00
|
|
|
for answerer in answerers_by_keywords[query_parts[0]]:
|
2016-11-19 19:53:51 +00:00
|
|
|
result = answerer(query)
|
|
|
|
if result:
|
|
|
|
results.append(result)
|
|
|
|
return results
|
|
|
|
|
|
|
|
|
|
|
|
answerers = load_answerers()
|
|
|
|
answerers_by_keywords = get_answerers_by_keywords(answerers)
|