traits.py 9.0 KB

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