We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Engine without an about property raises an exception
**Version of SearXNG, commit number if you are using on master branch and stipulate if you forked SearXNG**

current master branch

**How did you install SearXNG?**

Add an engine without an about property to your `settings.yml` / e.g.:

```yaml
  - name: locate
    engine: command
    command: ['locate', '{{QUERY}}']
    shortcut: locate
    tokens: [ '123', '456' ]
    disabled: true
    delimiter:
        chars: ' '
        keys: ['line']
```

**What happened?**

    $ make run

Open preferences ..

```
Traceback (most recent call last):
  ...
  File "searxng/searx/webutils.py", line 162, in engine_sort_key
    return (engine.about.get('language', ''), engine.name)
AttributeError: module 'command' has no attribute 'about'
```

**Additional context**

@not-my-profile if you have time, could you please have a look about / thanks!

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `searx/engines/__init__.py`
Content:
```
1 # SPDX-License-Identifier: AGPL-3.0-or-later
2 # lint: pylint
3 """This module implements the engine loader.
4 
5 Load and initialize the ``engines``, see :py:func:`load_engines` and register
6 :py:obj:`engine_shortcuts`.
7 
8 usage::
9 
10     load_engines( settings['engines'] )
11 
12 """
13 
14 import sys
15 import copy
16 from typing import Dict, List, Optional
17 
18 from os.path import realpath, dirname
19 from babel.localedata import locale_identifiers
20 from searx import logger, settings
21 from searx.data import ENGINES_LANGUAGES
22 from searx.network import get
23 from searx.utils import load_module, match_language, gen_useragent
24 
25 
26 logger = logger.getChild('engines')
27 ENGINE_DIR = dirname(realpath(__file__))
28 BABEL_LANGS = [
29     lang_parts[0] + '-' + lang_parts[-1] if len(lang_parts) > 1 else lang_parts[0]
30     for lang_parts in (lang_code.split('_') for lang_code in locale_identifiers())
31 ]
32 ENGINE_DEFAULT_ARGS = {
33     "engine_type": "online",
34     "inactive": False,
35     "disabled": False,
36     "timeout": settings["outgoing"]["request_timeout"],
37     "shortcut": "-",
38     "categories": ["general"],
39     "supported_languages": [],
40     "language_aliases": {},
41     "paging": False,
42     "safesearch": False,
43     "time_range_support": False,
44     "enable_http": False,
45     "display_error_messages": True,
46     "tokens": [],
47 }
48 # set automatically when an engine does not have any tab category
49 OTHER_CATEGORY = 'other'
50 
51 
52 class Engine:  # pylint: disable=too-few-public-methods
53     """This class is currently never initialized and only used for type hinting."""
54 
55     name: str
56     engine: str
57     shortcut: str
58     categories: List[str]
59     supported_languages: List[str]
60     about: dict
61     inactive: bool
62     disabled: bool
63     language_support: bool
64     paging: bool
65     safesearch: bool
66     time_range_support: bool
67     timeout: float
68 
69 
70 # Defaults for the namespace of an engine module, see :py:func:`load_engine`
71 
72 categories = {'general': []}
73 engines: Dict[str, Engine] = {}
74 engine_shortcuts = {}
75 """Simple map of registered *shortcuts* to name of the engine (or ``None``).
76 
77 ::
78 
79     engine_shortcuts[engine.shortcut] = engine.name
80 
81 """
82 
83 
84 def load_engine(engine_data: dict) -> Optional[Engine]:
85     """Load engine from ``engine_data``.
86 
87     :param dict engine_data:  Attributes from YAML ``settings:engines/<engine>``
88     :return: initialized namespace of the ``<engine>``.
89 
90     1. create a namespace and load module of the ``<engine>``
91     2. update namespace with the defaults from :py:obj:`ENGINE_DEFAULT_ARGS`
92     3. update namespace with values from ``engine_data``
93 
94     If engine *is active*, return namespace of the engine, otherwise return
95     ``None``.
96 
97     This function also returns ``None`` if initialization of the namespace fails
98     for one of the following reasons:
99 
100     - engine name contains underscore
101     - engine name is not lowercase
102     - required attribute is not set :py:func:`is_missing_required_attributes`
103 
104     """
105 
106     engine_name = engine_data['name']
107     if '_' in engine_name:
108         logger.error('Engine name contains underscore: "{}"'.format(engine_name))
109         return None
110 
111     if engine_name.lower() != engine_name:
112         logger.warn('Engine name is not lowercase: "{}", converting to lowercase'.format(engine_name))
113         engine_name = engine_name.lower()
114         engine_data['name'] = engine_name
115 
116     # load_module
117     engine_module = engine_data['engine']
118     try:
119         engine = load_module(engine_module + '.py', ENGINE_DIR)
120     except (SyntaxError, KeyboardInterrupt, SystemExit, SystemError, ImportError, RuntimeError):
121         logger.exception('Fatal exception in engine "{}"'.format(engine_module))
122         sys.exit(1)
123     except BaseException:
124         logger.exception('Cannot load engine "{}"'.format(engine_module))
125         return None
126 
127     update_engine_attributes(engine, engine_data)
128     set_language_attributes(engine)
129     update_attributes_for_tor(engine)
130 
131     if not is_engine_active(engine):
132         return None
133 
134     if is_missing_required_attributes(engine):
135         return None
136 
137     set_loggers(engine, engine_name)
138 
139     if not any(cat in settings['categories_as_tabs'] for cat in engine.categories):
140         engine.categories.append(OTHER_CATEGORY)
141 
142     return engine
143 
144 
145 def set_loggers(engine, engine_name):
146     # set the logger for engine
147     engine.logger = logger.getChild(engine_name)
148     # the engine may have load some other engines
149     # may sure the logger is initialized
150     for module_name, module in sys.modules.items():
151         if (
152             module_name.startswith("searx.engines")
153             and module_name != "searx.engines.__init__"
154             and not hasattr(module, "logger")
155         ):
156             module_engine_name = module_name.split(".")[-1]
157             module.logger = logger.getChild(module_engine_name)
158 
159 
160 def update_engine_attributes(engine: Engine, engine_data):
161     # set engine attributes from engine_data
162     for param_name, param_value in engine_data.items():
163         if param_name == 'categories':
164             if isinstance(param_value, str):
165                 param_value = list(map(str.strip, param_value.split(',')))
166             engine.categories = param_value
167         elif hasattr(engine, 'about') and param_name == 'about':
168             engine.about = {**engine.about, **engine_data['about']}
169         else:
170             setattr(engine, param_name, param_value)
171 
172     # set default attributes
173     for arg_name, arg_value in ENGINE_DEFAULT_ARGS.items():
174         if not hasattr(engine, arg_name):
175             setattr(engine, arg_name, copy.deepcopy(arg_value))
176 
177 
178 def set_language_attributes(engine: Engine):
179     # assign supported languages from json file
180     if engine.name in ENGINES_LANGUAGES:
181         engine.supported_languages = ENGINES_LANGUAGES[engine.name]
182 
183     elif engine.engine in ENGINES_LANGUAGES:
184         # The key of the dictionary ENGINES_LANGUAGES is the *engine name*
185         # configured in settings.xml.  When multiple engines are configured in
186         # settings.yml to use the same origin engine (python module) these
187         # additional engines can use the languages from the origin engine.
188         # For this use the configured ``engine: ...`` from settings.yml
189         engine.supported_languages = ENGINES_LANGUAGES[engine.engine]
190 
191     if hasattr(engine, 'language'):
192         # For an engine, when there is `language: ...` in the YAML settings, the
193         # engine supports only one language, in this case
194         # engine.supported_languages should contains this value defined in
195         # settings.yml
196         if engine.language not in engine.supported_languages:
197             raise ValueError(
198                 "settings.yml - engine: '%s' / language: '%s' not supported" % (engine.name, engine.language)
199             )
200 
201         if isinstance(engine.supported_languages, dict):
202             engine.supported_languages = {engine.language: engine.supported_languages[engine.language]}
203         else:
204             engine.supported_languages = [engine.language]
205 
206     # find custom aliases for non standard language codes
207     for engine_lang in engine.supported_languages:
208         iso_lang = match_language(engine_lang, BABEL_LANGS, fallback=None)
209         if (
210             iso_lang
211             and iso_lang != engine_lang
212             and not engine_lang.startswith(iso_lang)
213             and iso_lang not in engine.supported_languages
214         ):
215             engine.language_aliases[iso_lang] = engine_lang
216 
217     # language_support
218     engine.language_support = len(engine.supported_languages) > 0
219 
220     # assign language fetching method if auxiliary method exists
221     if hasattr(engine, '_fetch_supported_languages'):
222         headers = {
223             'User-Agent': gen_useragent(),
224             'Accept-Language': "en-US,en;q=0.5",  # bing needs to set the English language
225         }
226         engine.fetch_supported_languages = (
227             # pylint: disable=protected-access
228             lambda: engine._fetch_supported_languages(get(engine.supported_languages_url, headers=headers))
229         )
230 
231 
232 def update_attributes_for_tor(engine):
233     if settings['outgoing'].get('using_tor_proxy') and hasattr(engine, 'onion_url'):
234         engine.search_url = engine.onion_url + getattr(engine, 'search_path', '')
235         engine.timeout += settings['outgoing'].get('extra_proxy_timeout', 0)
236 
237 
238 def is_missing_required_attributes(engine):
239     """An attribute is required when its name doesn't start with ``_`` (underline).
240     Required attributes must not be ``None``.
241 
242     """
243     missing = False
244     for engine_attr in dir(engine):
245         if not engine_attr.startswith('_') and getattr(engine, engine_attr) is None:
246             logger.error('Missing engine config attribute: "{0}.{1}"'.format(engine.name, engine_attr))
247             missing = True
248     return missing
249 
250 
251 def is_engine_active(engine: Engine):
252     # check if engine is inactive
253     if engine.inactive is True:
254         return False
255 
256     # exclude onion engines if not using tor
257     if 'onions' in engine.categories and not settings['outgoing'].get('using_tor_proxy'):
258         return False
259 
260     return True
261 
262 
263 def register_engine(engine: Engine):
264     if engine.name in engines:
265         logger.error('Engine config error: ambigious name: {0}'.format(engine.name))
266         sys.exit(1)
267     engines[engine.name] = engine
268 
269     if engine.shortcut in engine_shortcuts:
270         logger.error('Engine config error: ambigious shortcut: {0}'.format(engine.shortcut))
271         sys.exit(1)
272     engine_shortcuts[engine.shortcut] = engine.name
273 
274     for category_name in engine.categories:
275         categories.setdefault(category_name, []).append(engine)
276 
277 
278 def load_engines(engine_list):
279     """usage: ``engine_list = settings['engines']``"""
280     engines.clear()
281     engine_shortcuts.clear()
282     categories.clear()
283     categories['general'] = []
284     for engine_data in engine_list:
285         engine = load_engine(engine_data)
286         if engine:
287             register_engine(engine)
288     return engines
289
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/searx/engines/__init__.py b/searx/engines/__init__.py
--- a/searx/engines/__init__.py
+++ b/searx/engines/__init__.py
@@ -44,6 +44,7 @@
     "enable_http": False,
     "display_error_messages": True,
     "tokens": [],
+    "about": {},
 }
 # set automatically when an engine does not have any tab category
 OTHER_CATEGORY = 'other'

{"golden_diff": "diff --git a/searx/engines/__init__.py b/searx/engines/__init__.py\n--- a/searx/engines/__init__.py\n+++ b/searx/engines/__init__.py\n@@ -44,6 +44,7 @@\n     \"enable_http\": False,\n     \"display_error_messages\": True,\n     \"tokens\": [],\n+    \"about\": {},\n }\n # set automatically when an engine does not have any tab category\n OTHER_CATEGORY = 'other'\n", "issue": "Engine without an about property raises an exception\n**Version of SearXNG, commit number if you are using on master branch and stipulate if you forked SearXNG**\r\n\r\ncurrent master branch\r\n\r\n**How did you install SearXNG?**\r\n\r\nAdd an engine without an about property to your `settings.yml` / e.g.:\r\n\r\n```yaml\r\n  - name: locate\r\n    engine: command\r\n    command: ['locate', '{{QUERY}}']\r\n    shortcut: locate\r\n    tokens: [ '123', '456' ]\r\n    disabled: true\r\n    delimiter:\r\n        chars: ' '\r\n        keys: ['line']\r\n```\r\n\r\n**What happened?**\r\n\r\n    $ make run\r\n\r\nOpen preferences ..\r\n\r\n```\r\nTraceback (most recent call last):\r\n  ...\r\n  File \"searxng/searx/webutils.py\", line 162, in engine_sort_key\r\n    return (engine.about.get('language', ''), engine.name)\r\nAttributeError: module 'command' has no attribute 'about'\r\n```\r\n\r\n**Additional context**\r\n\r\n@not-my-profile if you have time, could you please have a look about / thanks!\n", "before_files": [{"content": "# SPDX-License-Identifier: AGPL-3.0-or-later\n# lint: pylint\n\"\"\"This module implements the engine loader.\n\nLoad and initialize the ``engines``, see :py:func:`load_engines` and register\n:py:obj:`engine_shortcuts`.\n\nusage::\n\n    load_engines( settings['engines'] )\n\n\"\"\"\n\nimport sys\nimport copy\nfrom typing import Dict, List, Optional\n\nfrom os.path import realpath, dirname\nfrom babel.localedata import locale_identifiers\nfrom searx import logger, settings\nfrom searx.data import ENGINES_LANGUAGES\nfrom searx.network import get\nfrom searx.utils import load_module, match_language, gen_useragent\n\n\nlogger = logger.getChild('engines')\nENGINE_DIR = dirname(realpath(__file__))\nBABEL_LANGS = [\n    lang_parts[0] + '-' + lang_parts[-1] if len(lang_parts) > 1 else lang_parts[0]\n    for lang_parts in (lang_code.split('_') for lang_code in locale_identifiers())\n]\nENGINE_DEFAULT_ARGS = {\n    \"engine_type\": \"online\",\n    \"inactive\": False,\n    \"disabled\": False,\n    \"timeout\": settings[\"outgoing\"][\"request_timeout\"],\n    \"shortcut\": \"-\",\n    \"categories\": [\"general\"],\n    \"supported_languages\": [],\n    \"language_aliases\": {},\n    \"paging\": False,\n    \"safesearch\": False,\n    \"time_range_support\": False,\n    \"enable_http\": False,\n    \"display_error_messages\": True,\n    \"tokens\": [],\n}\n# set automatically when an engine does not have any tab category\nOTHER_CATEGORY = 'other'\n\n\nclass Engine:  # pylint: disable=too-few-public-methods\n    \"\"\"This class is currently never initialized and only used for type hinting.\"\"\"\n\n    name: str\n    engine: str\n    shortcut: str\n    categories: List[str]\n    supported_languages: List[str]\n    about: dict\n    inactive: bool\n    disabled: bool\n    language_support: bool\n    paging: bool\n    safesearch: bool\n    time_range_support: bool\n    timeout: float\n\n\n# Defaults for the namespace of an engine module, see :py:func:`load_engine`\n\ncategories = {'general': []}\nengines: Dict[str, Engine] = {}\nengine_shortcuts = {}\n\"\"\"Simple map of registered *shortcuts* to name of the engine (or ``None``).\n\n::\n\n    engine_shortcuts[engine.shortcut] = engine.name\n\n\"\"\"\n\n\ndef load_engine(engine_data: dict) -> Optional[Engine]:\n    \"\"\"Load engine from ``engine_data``.\n\n    :param dict engine_data:  Attributes from YAML ``settings:engines/<engine>``\n    :return: initialized namespace of the ``<engine>``.\n\n    1. create a namespace and load module of the ``<engine>``\n    2. update namespace with the defaults from :py:obj:`ENGINE_DEFAULT_ARGS`\n    3. update namespace with values from ``engine_data``\n\n    If engine *is active*, return namespace of the engine, otherwise return\n    ``None``.\n\n    This function also returns ``None`` if initialization of the namespace fails\n    for one of the following reasons:\n\n    - engine name contains underscore\n    - engine name is not lowercase\n    - required attribute is not set :py:func:`is_missing_required_attributes`\n\n    \"\"\"\n\n    engine_name = engine_data['name']\n    if '_' in engine_name:\n        logger.error('Engine name contains underscore: \"{}\"'.format(engine_name))\n        return None\n\n    if engine_name.lower() != engine_name:\n        logger.warn('Engine name is not lowercase: \"{}\", converting to lowercase'.format(engine_name))\n        engine_name = engine_name.lower()\n        engine_data['name'] = engine_name\n\n    # load_module\n    engine_module = engine_data['engine']\n    try:\n        engine = load_module(engine_module + '.py', ENGINE_DIR)\n    except (SyntaxError, KeyboardInterrupt, SystemExit, SystemError, ImportError, RuntimeError):\n        logger.exception('Fatal exception in engine \"{}\"'.format(engine_module))\n        sys.exit(1)\n    except BaseException:\n        logger.exception('Cannot load engine \"{}\"'.format(engine_module))\n        return None\n\n    update_engine_attributes(engine, engine_data)\n    set_language_attributes(engine)\n    update_attributes_for_tor(engine)\n\n    if not is_engine_active(engine):\n        return None\n\n    if is_missing_required_attributes(engine):\n        return None\n\n    set_loggers(engine, engine_name)\n\n    if not any(cat in settings['categories_as_tabs'] for cat in engine.categories):\n        engine.categories.append(OTHER_CATEGORY)\n\n    return engine\n\n\ndef set_loggers(engine, engine_name):\n    # set the logger for engine\n    engine.logger = logger.getChild(engine_name)\n    # the engine may have load some other engines\n    # may sure the logger is initialized\n    for module_name, module in sys.modules.items():\n        if (\n            module_name.startswith(\"searx.engines\")\n            and module_name != \"searx.engines.__init__\"\n            and not hasattr(module, \"logger\")\n        ):\n            module_engine_name = module_name.split(\".\")[-1]\n            module.logger = logger.getChild(module_engine_name)\n\n\ndef update_engine_attributes(engine: Engine, engine_data):\n    # set engine attributes from engine_data\n    for param_name, param_value in engine_data.items():\n        if param_name == 'categories':\n            if isinstance(param_value, str):\n                param_value = list(map(str.strip, param_value.split(',')))\n            engine.categories = param_value\n        elif hasattr(engine, 'about') and param_name == 'about':\n            engine.about = {**engine.about, **engine_data['about']}\n        else:\n            setattr(engine, param_name, param_value)\n\n    # set default attributes\n    for arg_name, arg_value in ENGINE_DEFAULT_ARGS.items():\n        if not hasattr(engine, arg_name):\n            setattr(engine, arg_name, copy.deepcopy(arg_value))\n\n\ndef set_language_attributes(engine: Engine):\n    # assign supported languages from json file\n    if engine.name in ENGINES_LANGUAGES:\n        engine.supported_languages = ENGINES_LANGUAGES[engine.name]\n\n    elif engine.engine in ENGINES_LANGUAGES:\n        # The key of the dictionary ENGINES_LANGUAGES is the *engine name*\n        # configured in settings.xml.  When multiple engines are configured in\n        # settings.yml to use the same origin engine (python module) these\n        # additional engines can use the languages from the origin engine.\n        # For this use the configured ``engine: ...`` from settings.yml\n        engine.supported_languages = ENGINES_LANGUAGES[engine.engine]\n\n    if hasattr(engine, 'language'):\n        # For an engine, when there is `language: ...` in the YAML settings, the\n        # engine supports only one language, in this case\n        # engine.supported_languages should contains this value defined in\n        # settings.yml\n        if engine.language not in engine.supported_languages:\n            raise ValueError(\n                \"settings.yml - engine: '%s' / language: '%s' not supported\" % (engine.name, engine.language)\n            )\n\n        if isinstance(engine.supported_languages, dict):\n            engine.supported_languages = {engine.language: engine.supported_languages[engine.language]}\n        else:\n            engine.supported_languages = [engine.language]\n\n    # find custom aliases for non standard language codes\n    for engine_lang in engine.supported_languages:\n        iso_lang = match_language(engine_lang, BABEL_LANGS, fallback=None)\n        if (\n            iso_lang\n            and iso_lang != engine_lang\n            and not engine_lang.startswith(iso_lang)\n            and iso_lang not in engine.supported_languages\n        ):\n            engine.language_aliases[iso_lang] = engine_lang\n\n    # language_support\n    engine.language_support = len(engine.supported_languages) > 0\n\n    # assign language fetching method if auxiliary method exists\n    if hasattr(engine, '_fetch_supported_languages'):\n        headers = {\n            'User-Agent': gen_useragent(),\n            'Accept-Language': \"en-US,en;q=0.5\",  # bing needs to set the English language\n        }\n        engine.fetch_supported_languages = (\n            # pylint: disable=protected-access\n            lambda: engine._fetch_supported_languages(get(engine.supported_languages_url, headers=headers))\n        )\n\n\ndef update_attributes_for_tor(engine):\n    if settings['outgoing'].get('using_tor_proxy') and hasattr(engine, 'onion_url'):\n        engine.search_url = engine.onion_url + getattr(engine, 'search_path', '')\n        engine.timeout += settings['outgoing'].get('extra_proxy_timeout', 0)\n\n\ndef is_missing_required_attributes(engine):\n    \"\"\"An attribute is required when its name doesn't start with ``_`` (underline).\n    Required attributes must not be ``None``.\n\n    \"\"\"\n    missing = False\n    for engine_attr in dir(engine):\n        if not engine_attr.startswith('_') and getattr(engine, engine_attr) is None:\n            logger.error('Missing engine config attribute: \"{0}.{1}\"'.format(engine.name, engine_attr))\n            missing = True\n    return missing\n\n\ndef is_engine_active(engine: Engine):\n    # check if engine is inactive\n    if engine.inactive is True:\n        return False\n\n    # exclude onion engines if not using tor\n    if 'onions' in engine.categories and not settings['outgoing'].get('using_tor_proxy'):\n        return False\n\n    return True\n\n\ndef register_engine(engine: Engine):\n    if engine.name in engines:\n        logger.error('Engine config error: ambigious name: {0}'.format(engine.name))\n        sys.exit(1)\n    engines[engine.name] = engine\n\n    if engine.shortcut in engine_shortcuts:\n        logger.error('Engine config error: ambigious shortcut: {0}'.format(engine.shortcut))\n        sys.exit(1)\n    engine_shortcuts[engine.shortcut] = engine.name\n\n    for category_name in engine.categories:\n        categories.setdefault(category_name, []).append(engine)\n\n\ndef load_engines(engine_list):\n    \"\"\"usage: ``engine_list = settings['engines']``\"\"\"\n    engines.clear()\n    engine_shortcuts.clear()\n    categories.clear()\n    categories['general'] = []\n    for engine_data in engine_list:\n        engine = load_engine(engine_data)\n        if engine:\n            register_engine(engine)\n    return engines\n", "path": "searx/engines/__init__.py"}], "after_files": [{"content": "# SPDX-License-Identifier: AGPL-3.0-or-later\n# lint: pylint\n\"\"\"This module implements the engine loader.\n\nLoad and initialize the ``engines``, see :py:func:`load_engines` and register\n:py:obj:`engine_shortcuts`.\n\nusage::\n\n    load_engines( settings['engines'] )\n\n\"\"\"\n\nimport sys\nimport copy\nfrom typing import Dict, List, Optional\n\nfrom os.path import realpath, dirname\nfrom babel.localedata import locale_identifiers\nfrom searx import logger, settings\nfrom searx.data import ENGINES_LANGUAGES\nfrom searx.network import get\nfrom searx.utils import load_module, match_language, gen_useragent\n\n\nlogger = logger.getChild('engines')\nENGINE_DIR = dirname(realpath(__file__))\nBABEL_LANGS = [\n    lang_parts[0] + '-' + lang_parts[-1] if len(lang_parts) > 1 else lang_parts[0]\n    for lang_parts in (lang_code.split('_') for lang_code in locale_identifiers())\n]\nENGINE_DEFAULT_ARGS = {\n    \"engine_type\": \"online\",\n    \"inactive\": False,\n    \"disabled\": False,\n    \"timeout\": settings[\"outgoing\"][\"request_timeout\"],\n    \"shortcut\": \"-\",\n    \"categories\": [\"general\"],\n    \"supported_languages\": [],\n    \"language_aliases\": {},\n    \"paging\": False,\n    \"safesearch\": False,\n    \"time_range_support\": False,\n    \"enable_http\": False,\n    \"display_error_messages\": True,\n    \"tokens\": [],\n    \"about\": {},\n}\n# set automatically when an engine does not have any tab category\nOTHER_CATEGORY = 'other'\n\n\nclass Engine:  # pylint: disable=too-few-public-methods\n    \"\"\"This class is currently never initialized and only used for type hinting.\"\"\"\n\n    name: str\n    engine: str\n    shortcut: str\n    categories: List[str]\n    supported_languages: List[str]\n    about: dict\n    inactive: bool\n    disabled: bool\n    language_support: bool\n    paging: bool\n    safesearch: bool\n    time_range_support: bool\n    timeout: float\n\n\n# Defaults for the namespace of an engine module, see :py:func:`load_engine`\n\ncategories = {'general': []}\nengines: Dict[str, Engine] = {}\nengine_shortcuts = {}\n\"\"\"Simple map of registered *shortcuts* to name of the engine (or ``None``).\n\n::\n\n    engine_shortcuts[engine.shortcut] = engine.name\n\n\"\"\"\n\n\ndef load_engine(engine_data: dict) -> Optional[Engine]:\n    \"\"\"Load engine from ``engine_data``.\n\n    :param dict engine_data:  Attributes from YAML ``settings:engines/<engine>``\n    :return: initialized namespace of the ``<engine>``.\n\n    1. create a namespace and load module of the ``<engine>``\n    2. update namespace with the defaults from :py:obj:`ENGINE_DEFAULT_ARGS`\n    3. update namespace with values from ``engine_data``\n\n    If engine *is active*, return namespace of the engine, otherwise return\n    ``None``.\n\n    This function also returns ``None`` if initialization of the namespace fails\n    for one of the following reasons:\n\n    - engine name contains underscore\n    - engine name is not lowercase\n    - required attribute is not set :py:func:`is_missing_required_attributes`\n\n    \"\"\"\n\n    engine_name = engine_data['name']\n    if '_' in engine_name:\n        logger.error('Engine name contains underscore: \"{}\"'.format(engine_name))\n        return None\n\n    if engine_name.lower() != engine_name:\n        logger.warn('Engine name is not lowercase: \"{}\", converting to lowercase'.format(engine_name))\n        engine_name = engine_name.lower()\n        engine_data['name'] = engine_name\n\n    # load_module\n    engine_module = engine_data['engine']\n    try:\n        engine = load_module(engine_module + '.py', ENGINE_DIR)\n    except (SyntaxError, KeyboardInterrupt, SystemExit, SystemError, ImportError, RuntimeError):\n        logger.exception('Fatal exception in engine \"{}\"'.format(engine_module))\n        sys.exit(1)\n    except BaseException:\n        logger.exception('Cannot load engine \"{}\"'.format(engine_module))\n        return None\n\n    update_engine_attributes(engine, engine_data)\n    set_language_attributes(engine)\n    update_attributes_for_tor(engine)\n\n    if not is_engine_active(engine):\n        return None\n\n    if is_missing_required_attributes(engine):\n        return None\n\n    set_loggers(engine, engine_name)\n\n    if not any(cat in settings['categories_as_tabs'] for cat in engine.categories):\n        engine.categories.append(OTHER_CATEGORY)\n\n    return engine\n\n\ndef set_loggers(engine, engine_name):\n    # set the logger for engine\n    engine.logger = logger.getChild(engine_name)\n    # the engine may have load some other engines\n    # may sure the logger is initialized\n    for module_name, module in sys.modules.items():\n        if (\n            module_name.startswith(\"searx.engines\")\n            and module_name != \"searx.engines.__init__\"\n            and not hasattr(module, \"logger\")\n        ):\n            module_engine_name = module_name.split(\".\")[-1]\n            module.logger = logger.getChild(module_engine_name)\n\n\ndef update_engine_attributes(engine: Engine, engine_data):\n    # set engine attributes from engine_data\n    for param_name, param_value in engine_data.items():\n        if param_name == 'categories':\n            if isinstance(param_value, str):\n                param_value = list(map(str.strip, param_value.split(',')))\n            engine.categories = param_value\n        elif hasattr(engine, 'about') and param_name == 'about':\n            engine.about = {**engine.about, **engine_data['about']}\n        else:\n            setattr(engine, param_name, param_value)\n\n    # set default attributes\n    for arg_name, arg_value in ENGINE_DEFAULT_ARGS.items():\n        if not hasattr(engine, arg_name):\n            setattr(engine, arg_name, copy.deepcopy(arg_value))\n\n\ndef set_language_attributes(engine: Engine):\n    # assign supported languages from json file\n    if engine.name in ENGINES_LANGUAGES:\n        engine.supported_languages = ENGINES_LANGUAGES[engine.name]\n\n    elif engine.engine in ENGINES_LANGUAGES:\n        # The key of the dictionary ENGINES_LANGUAGES is the *engine name*\n        # configured in settings.xml.  When multiple engines are configured in\n        # settings.yml to use the same origin engine (python module) these\n        # additional engines can use the languages from the origin engine.\n        # For this use the configured ``engine: ...`` from settings.yml\n        engine.supported_languages = ENGINES_LANGUAGES[engine.engine]\n\n    if hasattr(engine, 'language'):\n        # For an engine, when there is `language: ...` in the YAML settings, the\n        # engine supports only one language, in this case\n        # engine.supported_languages should contains this value defined in\n        # settings.yml\n        if engine.language not in engine.supported_languages:\n            raise ValueError(\n                \"settings.yml - engine: '%s' / language: '%s' not supported\" % (engine.name, engine.language)\n            )\n\n        if isinstance(engine.supported_languages, dict):\n            engine.supported_languages = {engine.language: engine.supported_languages[engine.language]}\n        else:\n            engine.supported_languages = [engine.language]\n\n    # find custom aliases for non standard language codes\n    for engine_lang in engine.supported_languages:\n        iso_lang = match_language(engine_lang, BABEL_LANGS, fallback=None)\n        if (\n            iso_lang\n            and iso_lang != engine_lang\n            and not engine_lang.startswith(iso_lang)\n            and iso_lang not in engine.supported_languages\n        ):\n            engine.language_aliases[iso_lang] = engine_lang\n\n    # language_support\n    engine.language_support = len(engine.supported_languages) > 0\n\n    # assign language fetching method if auxiliary method exists\n    if hasattr(engine, '_fetch_supported_languages'):\n        headers = {\n            'User-Agent': gen_useragent(),\n            'Accept-Language': \"en-US,en;q=0.5\",  # bing needs to set the English language\n        }\n        engine.fetch_supported_languages = (\n            # pylint: disable=protected-access\n            lambda: engine._fetch_supported_languages(get(engine.supported_languages_url, headers=headers))\n        )\n\n\ndef update_attributes_for_tor(engine):\n    if settings['outgoing'].get('using_tor_proxy') and hasattr(engine, 'onion_url'):\n        engine.search_url = engine.onion_url + getattr(engine, 'search_path', '')\n        engine.timeout += settings['outgoing'].get('extra_proxy_timeout', 0)\n\n\ndef is_missing_required_attributes(engine):\n    \"\"\"An attribute is required when its name doesn't start with ``_`` (underline).\n    Required attributes must not be ``None``.\n\n    \"\"\"\n    missing = False\n    for engine_attr in dir(engine):\n        if not engine_attr.startswith('_') and getattr(engine, engine_attr) is None:\n            logger.error('Missing engine config attribute: \"{0}.{1}\"'.format(engine.name, engine_attr))\n            missing = True\n    return missing\n\n\ndef is_engine_active(engine: Engine):\n    # check if engine is inactive\n    if engine.inactive is True:\n        return False\n\n    # exclude onion engines if not using tor\n    if 'onions' in engine.categories and not settings['outgoing'].get('using_tor_proxy'):\n        return False\n\n    return True\n\n\ndef register_engine(engine: Engine):\n    if engine.name in engines:\n        logger.error('Engine config error: ambigious name: {0}'.format(engine.name))\n        sys.exit(1)\n    engines[engine.name] = engine\n\n    if engine.shortcut in engine_shortcuts:\n        logger.error('Engine config error: ambigious shortcut: {0}'.format(engine.shortcut))\n        sys.exit(1)\n    engine_shortcuts[engine.shortcut] = engine.name\n\n    for category_name in engine.categories:\n        categories.setdefault(category_name, []).append(engine)\n\n\ndef load_engines(engine_list):\n    \"\"\"usage: ``engine_list = settings['engines']``\"\"\"\n    engines.clear()\n    engine_shortcuts.clear()\n    categories.clear()\n    categories['general'] = []\n    for engine_data in engine_list:\n        engine = load_engine(engine_data)\n        if engine:\n            register_engine(engine)\n    return engines\n", "path": "searx/engines/__init__.py"}]}