traits.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Engine's traits are fetched from the origin engines and stored in a JSON file
  3. in the *data folder*. Most often traits are languages and region codes and
  4. their mapping from SearXNG's representation to the representation in the origin
  5. search engine. For new traits new properties can be added to the class
  6. :py:class:`EngineTraits`.
  7. To load traits from the persistence :py:obj:`EngineTraitsMap.from_data` can be
  8. used.
  9. """
  10. from __future__ import annotations
  11. import json
  12. import dataclasses
  13. import types
  14. from typing import Dict, Literal, Iterable, Union, Callable, Optional, TYPE_CHECKING
  15. from searx import locales
  16. from searx.data import data_dir, ENGINE_TRAITS
  17. if TYPE_CHECKING:
  18. from . import Engine
  19. class EngineTraitsEncoder(json.JSONEncoder):
  20. """Encodes :class:`EngineTraits` to a serializable object, see
  21. :class:`json.JSONEncoder`."""
  22. def default(self, o):
  23. """Return dictionary of a :class:`EngineTraits` object."""
  24. if isinstance(o, EngineTraits):
  25. return o.__dict__
  26. return super().default(o)
  27. @dataclasses.dataclass
  28. class EngineTraits:
  29. """The class is intended to be instantiated for each engine."""
  30. regions: Dict[str, str] = dataclasses.field(default_factory=dict)
  31. """Maps SearXNG's internal representation of a region to the one of the engine.
  32. SearXNG's internal representation can be parsed by babel and the value is
  33. send to the engine:
  34. .. code:: python
  35. regions ={
  36. 'fr-BE' : <engine's region name>,
  37. }
  38. for key, egnine_region regions.items():
  39. searxng_region = babel.Locale.parse(key, sep='-')
  40. ...
  41. """
  42. languages: Dict[str, str] = dataclasses.field(default_factory=dict)
  43. """Maps SearXNG's internal representation of a language to the one of the engine.
  44. SearXNG's internal representation can be parsed by babel and the value is
  45. send to the engine:
  46. .. code:: python
  47. languages = {
  48. 'ca' : <engine's language name>,
  49. }
  50. for key, egnine_lang in languages.items():
  51. searxng_lang = babel.Locale.parse(key)
  52. ...
  53. """
  54. all_locale: Optional[str] = None
  55. """To which locale value SearXNG's ``all`` language is mapped (shown a "Default
  56. language").
  57. """
  58. data_type: Literal['traits_v1'] = 'traits_v1'
  59. """Data type, default is 'traits_v1'.
  60. """
  61. custom: Dict[str, Union[Dict[str, Dict], Iterable[str]]] = dataclasses.field(default_factory=dict)
  62. """A place to store engine's custom traits, not related to the SearXNG core.
  63. """
  64. def get_language(self, searxng_locale: str, default=None):
  65. """Return engine's language string that *best fits* to SearXNG's locale.
  66. :param searxng_locale: SearXNG's internal representation of locale
  67. selected by the user.
  68. :param default: engine's default language
  69. The *best fits* rules are implemented in
  70. :py:obj:`searx.locales.get_engine_locale`. Except for the special value ``all``
  71. which is determined from :py:obj:`EngineTraits.all_locale`.
  72. """
  73. if searxng_locale == 'all' and self.all_locale is not None:
  74. return self.all_locale
  75. return locales.get_engine_locale(searxng_locale, self.languages, default=default)
  76. def get_region(self, searxng_locale: str, default=None):
  77. """Return engine's region string that best fits to SearXNG's locale.
  78. :param searxng_locale: SearXNG's internal representation of locale
  79. selected by the user.
  80. :param default: engine's default region
  81. The *best fits* rules are implemented in
  82. :py:obj:`searx.locales.get_engine_locale`. Except for the special value ``all``
  83. which is determined from :py:obj:`EngineTraits.all_locale`.
  84. """
  85. if searxng_locale == 'all' and self.all_locale is not None:
  86. return self.all_locale
  87. return locales.get_engine_locale(searxng_locale, self.regions, default=default)
  88. def is_locale_supported(self, searxng_locale: str) -> bool:
  89. """A *locale* (SearXNG's internal representation) is considered to be
  90. supported by the engine if the *region* or the *language* is supported
  91. by the engine.
  92. For verification the functions :py:func:`EngineTraits.get_region` and
  93. :py:func:`EngineTraits.get_language` are used.
  94. """
  95. if self.data_type == 'traits_v1':
  96. return bool(self.get_region(searxng_locale) or self.get_language(searxng_locale))
  97. raise TypeError('engine traits of type %s is unknown' % self.data_type)
  98. def copy(self):
  99. """Create a copy of the dataclass object."""
  100. return EngineTraits(**dataclasses.asdict(self))
  101. @classmethod
  102. def fetch_traits(cls, engine: Engine) -> Union['EngineTraits', None]:
  103. """Call a function ``fetch_traits(engine_traits)`` from engines namespace to fetch
  104. and set properties from the origin engine in the object ``engine_traits``. If
  105. function does not exists, ``None`` is returned.
  106. """
  107. fetch_traits = getattr(engine, 'fetch_traits', None)
  108. engine_traits = None
  109. if fetch_traits:
  110. engine_traits = cls()
  111. fetch_traits(engine_traits)
  112. return engine_traits
  113. def set_traits(self, engine: Engine):
  114. """Set traits from self object in a :py:obj:`.Engine` namespace.
  115. :param engine: engine instance build by :py:func:`searx.engines.load_engine`
  116. """
  117. if self.data_type == 'traits_v1':
  118. self._set_traits_v1(engine)
  119. else:
  120. raise TypeError('engine traits of type %s is unknown' % self.data_type)
  121. def _set_traits_v1(self, engine: Engine):
  122. # For an engine, when there is `language: ...` in the YAML settings the engine
  123. # does support only this one language (region)::
  124. #
  125. # - name: google italian
  126. # engine: google
  127. # language: it
  128. # region: it-IT # type: ignore
  129. traits = self.copy()
  130. _msg = "settings.yml - engine: '%s' / %s: '%s' not supported"
  131. languages = traits.languages
  132. if hasattr(engine, 'language'):
  133. if engine.language not in languages:
  134. raise ValueError(_msg % (engine.name, 'language', engine.language))
  135. traits.languages = {engine.language: languages[engine.language]}
  136. regions = traits.regions
  137. if hasattr(engine, 'region'):
  138. if engine.region not in regions:
  139. raise ValueError(_msg % (engine.name, 'region', engine.region))
  140. traits.regions = {engine.region: regions[engine.region]}
  141. engine.language_support = bool(traits.languages or traits.regions)
  142. # set the copied & modified traits in engine's namespace
  143. engine.traits = traits
  144. class EngineTraitsMap(Dict[str, EngineTraits]):
  145. """A python dictionary to map :class:`EngineTraits` by engine name."""
  146. ENGINE_TRAITS_FILE = (data_dir / 'engine_traits.json').resolve()
  147. """File with persistence of the :py:obj:`EngineTraitsMap`."""
  148. def save_data(self):
  149. """Store EngineTraitsMap in in file :py:obj:`self.ENGINE_TRAITS_FILE`"""
  150. with open(self.ENGINE_TRAITS_FILE, 'w', encoding='utf-8') as f:
  151. json.dump(self, f, indent=2, sort_keys=True, cls=EngineTraitsEncoder)
  152. @classmethod
  153. def from_data(cls) -> 'EngineTraitsMap':
  154. """Instantiate :class:`EngineTraitsMap` object from :py:obj:`ENGINE_TRAITS`"""
  155. obj = cls()
  156. for k, v in ENGINE_TRAITS.items():
  157. obj[k] = EngineTraits(**v)
  158. return obj
  159. @classmethod
  160. def fetch_traits(cls, log: Callable) -> 'EngineTraitsMap':
  161. from searx import engines # pylint: disable=cyclic-import, import-outside-toplevel
  162. names = list(engines.engines)
  163. names.sort()
  164. obj = cls()
  165. for engine_name in names:
  166. engine = engines.engines[engine_name]
  167. traits = EngineTraits.fetch_traits(engine)
  168. if traits is not None:
  169. log("%-20s: SearXNG languages --> %s " % (engine_name, len(traits.languages)))
  170. log("%-20s: SearXNG regions --> %s" % (engine_name, len(traits.regions)))
  171. obj[engine_name] = traits
  172. return obj
  173. def set_traits(self, engine: Engine | types.ModuleType):
  174. """Set traits in a :py:obj:`Engine` namespace.
  175. :param engine: engine instance build by :py:func:`searx.engines.load_engine`
  176. """
  177. engine_traits = EngineTraits(data_type='traits_v1')
  178. if engine.name in self.keys():
  179. engine_traits = self[engine.name]
  180. elif engine.engine in self.keys():
  181. # The key of the dictionary traits_map is the *engine name*
  182. # configured in settings.xml. When multiple engines are configured
  183. # in settings.yml to use the same origin engine (python module)
  184. # these additional engines can use the languages from the origin
  185. # engine. For this use the configured ``engine: ...`` from
  186. # settings.yml
  187. engine_traits = self[engine.engine]
  188. engine_traits.set_traits(engine)