locales.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """
  3. SearXNG’s locale data
  4. =====================
  5. The variables :py:obj:`RTL_LOCALES` and :py:obj:`LOCALE_NAMES` are loaded from
  6. :origin:`searx/data/locales.json` / see :py:obj:`locales_initialize` and
  7. :ref:`update_locales.py`.
  8. .. hint::
  9. Whenever the value of :py:obj:`ADDITIONAL_TRANSLATIONS` or
  10. :py:obj:`LOCALE_BEST_MATCH` is modified, the
  11. :origin:`searx/data/locales.json` needs to be rebuild::
  12. ./manage data.locales
  13. SearXNG's locale codes
  14. ======================
  15. .. automodule:: searx.sxng_locales
  16. :members:
  17. SearXNG’s locale implementations
  18. ================================
  19. """
  20. from __future__ import annotations
  21. from pathlib import Path
  22. import babel
  23. from babel.support import Translations
  24. import babel.languages
  25. import babel.core
  26. import flask_babel
  27. from flask.ctx import has_request_context
  28. from searx import (
  29. data,
  30. logger,
  31. searx_dir,
  32. )
  33. from searx.extended_types import sxng_request
  34. logger = logger.getChild('locales')
  35. # safe before monkey patching flask_babel.get_translations
  36. _flask_babel_get_translations = flask_babel.get_translations
  37. LOCALE_NAMES = {}
  38. """Mapping of locales and their description. Locales e.g. 'fr' or 'pt-BR' (see
  39. :py:obj:`locales_initialize`).
  40. :meta hide-value:
  41. """
  42. RTL_LOCALES: set[str] = set()
  43. """List of *Right-To-Left* locales e.g. 'he' or 'fa-IR' (see
  44. :py:obj:`locales_initialize`)."""
  45. ADDITIONAL_TRANSLATIONS = {
  46. "dv": "ދިވެހި (Dhivehi)",
  47. "oc": "Occitan",
  48. "szl": "Ślōnski (Silesian)",
  49. "pap": "Papiamento",
  50. }
  51. """Additional languages SearXNG has translations for but not supported by
  52. python-babel (see :py:obj:`locales_initialize`)."""
  53. LOCALE_BEST_MATCH = {
  54. "dv": "si",
  55. "oc": 'fr-FR',
  56. "szl": "pl",
  57. "nl-BE": "nl",
  58. "zh-HK": "zh-Hant-TW",
  59. "pap": "pt-BR",
  60. }
  61. """Map a locale we do not have a translations for to a locale we have a
  62. translation for. By example: use Taiwan version of the translation for Hong
  63. Kong."""
  64. def localeselector():
  65. locale = 'en'
  66. if has_request_context():
  67. value = sxng_request.preferences.get_value('locale')
  68. if value:
  69. locale = value
  70. # first, set the language that is not supported by babel
  71. if locale in ADDITIONAL_TRANSLATIONS:
  72. sxng_request.form['use-translation'] = locale
  73. # second, map locale to a value python-babel supports
  74. locale = LOCALE_BEST_MATCH.get(locale, locale)
  75. if locale == '':
  76. # if there is an error loading the preferences
  77. # the locale is going to be ''
  78. locale = 'en'
  79. # babel uses underscore instead of hyphen.
  80. locale = locale.replace('-', '_')
  81. return locale
  82. def get_translations():
  83. """Monkey patch of :py:obj:`flask_babel.get_translations`"""
  84. if has_request_context():
  85. use_translation = sxng_request.form.get('use-translation')
  86. if use_translation in ADDITIONAL_TRANSLATIONS:
  87. babel_ext = flask_babel.current_app.extensions['babel']
  88. return Translations.load(babel_ext.translation_directories[0], use_translation)
  89. return _flask_babel_get_translations()
  90. _TR_LOCALES: list[str] = []
  91. def get_translation_locales() -> list[str]:
  92. """Returns the list of translation locales (*underscore*). The list is
  93. generated from the translation folders in :origin:`searx/translations`"""
  94. global _TR_LOCALES # pylint:disable=global-statement
  95. if _TR_LOCALES:
  96. return _TR_LOCALES
  97. tr_locales = []
  98. for folder in (Path(searx_dir) / 'translations').iterdir():
  99. if not folder.is_dir():
  100. continue
  101. if not (folder / 'LC_MESSAGES').is_dir():
  102. continue
  103. tr_locales.append(folder.name)
  104. _TR_LOCALES = sorted(tr_locales)
  105. return _TR_LOCALES
  106. def locales_initialize():
  107. """Initialize locales environment of the SearXNG session.
  108. - monkey patch :py:obj:`flask_babel.get_translations` by :py:obj:`get_translations`
  109. - init global names :py:obj:`LOCALE_NAMES`, :py:obj:`RTL_LOCALES`
  110. """
  111. flask_babel.get_translations = get_translations
  112. LOCALE_NAMES.update(data.LOCALES["LOCALE_NAMES"])
  113. RTL_LOCALES.update(data.LOCALES["RTL_LOCALES"])
  114. def region_tag(locale: babel.Locale) -> str:
  115. """Returns SearXNG's region tag from the locale (e.g. zh-TW , en-US)."""
  116. if not locale.territory:
  117. raise ValueError('babel.Locale %s: missed a territory' % locale)
  118. return locale.language + '-' + locale.territory
  119. def language_tag(locale: babel.Locale) -> str:
  120. """Returns SearXNG's language tag from the locale and if exits, the tag
  121. includes the script name (e.g. en, zh_Hant).
  122. """
  123. sxng_lang = locale.language
  124. if locale.script:
  125. sxng_lang += '_' + locale.script
  126. return sxng_lang
  127. def get_locale(locale_tag: str) -> babel.Locale | None:
  128. """Returns a :py:obj:`babel.Locale` object parsed from argument
  129. ``locale_tag``"""
  130. try:
  131. locale = babel.Locale.parse(locale_tag, sep='-')
  132. return locale
  133. except babel.core.UnknownLocaleError:
  134. return None
  135. def get_official_locales(
  136. territory: str, languages=None, regional: bool = False, de_facto: bool = True
  137. ) -> set[babel.Locale]:
  138. """Returns a list of :py:obj:`babel.Locale` with languages from
  139. :py:obj:`babel.languages.get_official_languages`.
  140. :param territory: The territory (country or region) code.
  141. :param languages: A list of language codes the languages from
  142. :py:obj:`babel.languages.get_official_languages` should be in
  143. (intersection). If this argument is ``None``, all official languages in
  144. this territory are used.
  145. :param regional: If the regional flag is set, then languages which are
  146. regionally official are also returned.
  147. :param de_facto: If the de_facto flag is set to `False`, then languages
  148. which are “de facto” official are not returned.
  149. """
  150. ret_val = set()
  151. o_languages = babel.languages.get_official_languages(territory, regional=regional, de_facto=de_facto)
  152. if languages:
  153. languages = [l.lower() for l in languages]
  154. o_languages = set(l for l in o_languages if l.lower() in languages)
  155. for lang in o_languages:
  156. try:
  157. locale = babel.Locale.parse(lang + '_' + territory)
  158. ret_val.add(locale)
  159. except babel.UnknownLocaleError:
  160. continue
  161. return ret_val
  162. def get_engine_locale(searxng_locale, engine_locales, default=None):
  163. """Return engine's language (aka locale) string that best fits to argument
  164. ``searxng_locale``.
  165. Argument ``engine_locales`` is a python dict that maps *SearXNG locales* to
  166. corresponding *engine locales*::
  167. <engine>: {
  168. # SearXNG string : engine-string
  169. 'ca-ES' : 'ca_ES',
  170. 'fr-BE' : 'fr_BE',
  171. 'fr-CA' : 'fr_CA',
  172. 'fr-CH' : 'fr_CH',
  173. 'fr' : 'fr_FR',
  174. ...
  175. 'pl-PL' : 'pl_PL',
  176. 'pt-PT' : 'pt_PT'
  177. ..
  178. 'zh' : 'zh'
  179. 'zh_Hans' : 'zh'
  180. 'zh_Hant' : 'zh_TW'
  181. }
  182. .. hint::
  183. The *SearXNG locale* string has to be known by babel!
  184. If there is no direct 1:1 mapping, this functions tries to narrow down
  185. engine's language (locale). If no value can be determined by these
  186. approximation attempts the ``default`` value is returned.
  187. Assumptions:
  188. A. When user select a language the results should be optimized according to
  189. the selected language.
  190. B. When user select a language and a territory the results should be
  191. optimized with first priority on territory and second on language.
  192. First approximation rule (*by territory*):
  193. When the user selects a locale with territory (and a language), the
  194. territory has priority over the language. If any of the official languages
  195. in the territory is supported by the engine (``engine_locales``) it will
  196. be used.
  197. Second approximation rule (*by language*):
  198. If "First approximation rule" brings no result or the user selects only a
  199. language without a territory. Check in which territories the language
  200. has an official status and if one of these territories is supported by the
  201. engine.
  202. """
  203. # pylint: disable=too-many-branches, too-many-return-statements
  204. engine_locale = engine_locales.get(searxng_locale)
  205. if engine_locale is not None:
  206. # There was a 1:1 mapping (e.g. a region "fr-BE --> fr_BE" or a language
  207. # "zh --> zh"), no need to narrow language-script nor territory.
  208. return engine_locale
  209. try:
  210. locale = babel.Locale.parse(searxng_locale, sep='-')
  211. except babel.core.UnknownLocaleError:
  212. try:
  213. locale = babel.Locale.parse(searxng_locale.split('-')[0])
  214. except babel.core.UnknownLocaleError:
  215. return default
  216. searxng_lang = language_tag(locale)
  217. engine_locale = engine_locales.get(searxng_lang)
  218. if engine_locale is not None:
  219. # There was a 1:1 mapping (e.g. "zh-HK --> zh_Hant" or "zh-CN --> zh_Hans")
  220. return engine_locale
  221. # SearXNG's selected locale is not supported by the engine ..
  222. if locale.territory:
  223. # Try to narrow by *official* languages in the territory (??-XX).
  224. for official_language in babel.languages.get_official_languages(locale.territory, de_facto=True):
  225. searxng_locale = official_language + '-' + locale.territory
  226. engine_locale = engine_locales.get(searxng_locale)
  227. if engine_locale is not None:
  228. return engine_locale
  229. # Engine does not support one of the official languages in the territory or
  230. # there is only a language selected without a territory.
  231. # Now lets have a look if the searxng_lang (the language selected by the
  232. # user) is a official language in other territories. If so, check if
  233. # engine does support the searxng_lang in this other territory.
  234. if locale.language:
  235. terr_lang_dict = {}
  236. for territory, langs in babel.core.get_global("territory_languages").items():
  237. if not langs.get(searxng_lang, {}).get('official_status'):
  238. continue
  239. terr_lang_dict[territory] = langs.get(searxng_lang)
  240. # first: check fr-FR, de-DE .. is supported by the engine
  241. # exception: 'en' --> 'en-US'
  242. territory = locale.language.upper()
  243. if territory == 'EN':
  244. territory = 'US'
  245. if terr_lang_dict.get(territory):
  246. searxng_locale = locale.language + '-' + territory
  247. engine_locale = engine_locales.get(searxng_locale)
  248. if engine_locale is not None:
  249. return engine_locale
  250. # second: sort by population_percent and take first match
  251. # drawback of "population percent": if there is a territory with a
  252. # small number of people (e.g 100) but the majority speaks the
  253. # language, then the percentage might be 100% (--> 100 people) but in
  254. # a different territory with more people (e.g. 10.000) where only 10%
  255. # speak the language the total amount of speaker is higher (--> 200
  256. # people).
  257. #
  258. # By example: The population of Saint-Martin is 33.000, of which 100%
  259. # speak French, but this is less than the 30% of the approximately 2.5
  260. # million Belgian citizens
  261. #
  262. # - 'fr-MF', 'population_percent': 100.0, 'official_status': 'official'
  263. # - 'fr-BE', 'population_percent': 38.0, 'official_status': 'official'
  264. terr_lang_list = []
  265. for k, v in terr_lang_dict.items():
  266. terr_lang_list.append((k, v))
  267. for territory, _lang in sorted(terr_lang_list, key=lambda item: item[1]['population_percent'], reverse=True):
  268. searxng_locale = locale.language + '-' + territory
  269. engine_locale = engine_locales.get(searxng_locale)
  270. if engine_locale is not None:
  271. return engine_locale
  272. # No luck: narrow by "language from territory" and "territory from language"
  273. # does not fit to a locale supported by the engine.
  274. if engine_locale is None:
  275. engine_locale = default
  276. return default
  277. def match_locale(searxng_locale: str, locale_tag_list: list[str], fallback: str | None = None) -> str | None:
  278. """Return tag from ``locale_tag_list`` that best fits to ``searxng_locale``.
  279. :param str searxng_locale: SearXNG's internal representation of locale (de,
  280. de-DE, fr-BE, zh, zh-CN, zh-TW ..).
  281. :param list locale_tag_list: The list of locale tags to select from
  282. :param str fallback: fallback locale tag (if unset --> ``None``)
  283. The rules to find a match are implemented in :py:obj:`get_engine_locale`,
  284. the ``engine_locales`` is build up by :py:obj:`build_engine_locales`.
  285. .. hint::
  286. The *SearXNG locale* string and the members of ``locale_tag_list`` has to
  287. be known by babel! The :py:obj:`ADDITIONAL_TRANSLATIONS` are used in the
  288. UI and are not known by babel --> will be ignored.
  289. """
  290. # searxng_locale = 'es'
  291. # locale_tag_list = ['es-AR', 'es-ES', 'es-MX']
  292. if not searxng_locale:
  293. return fallback
  294. locale = get_locale(searxng_locale)
  295. if locale is None:
  296. return fallback
  297. # normalize to a SearXNG locale that can be passed to get_engine_locale
  298. searxng_locale = language_tag(locale)
  299. if locale.territory:
  300. searxng_locale = region_tag(locale)
  301. # clean up locale_tag_list
  302. tag_list = []
  303. for tag in locale_tag_list:
  304. if tag in ('all', 'auto') or tag in ADDITIONAL_TRANSLATIONS:
  305. continue
  306. tag_list.append(tag)
  307. # emulate fetch_traits
  308. engine_locales = build_engine_locales(tag_list)
  309. return get_engine_locale(searxng_locale, engine_locales, default=fallback)
  310. def build_engine_locales(tag_list: list[str]):
  311. """From a list of locale tags a dictionary is build that can be passed by
  312. argument ``engine_locales`` to :py:obj:`get_engine_locale`. This function
  313. is mainly used by :py:obj:`match_locale` and is similar to what the
  314. ``fetch_traits(..)`` function of engines do.
  315. If there are territory codes in the ``tag_list`` that have a *script code*
  316. additional keys are added to the returned dictionary.
  317. .. code:: python
  318. >>> import locales
  319. >>> engine_locales = locales.build_engine_locales(['en', 'en-US', 'zh', 'zh-CN', 'zh-TW'])
  320. >>> engine_locales
  321. {
  322. 'en': 'en', 'en-US': 'en-US',
  323. 'zh': 'zh', 'zh-CN': 'zh-CN', 'zh_Hans': 'zh-CN',
  324. 'zh-TW': 'zh-TW', 'zh_Hant': 'zh-TW'
  325. }
  326. >>> get_engine_locale('zh-Hans', engine_locales)
  327. 'zh-CN'
  328. This function is a good example to understand the language/region model
  329. of SearXNG:
  330. SearXNG only distinguishes between **search languages** and **search
  331. regions**, by adding the *script-tags*, languages with *script-tags* can
  332. be assigned to the **regions** that SearXNG supports.
  333. """
  334. engine_locales = {}
  335. for tag in tag_list:
  336. locale = get_locale(tag)
  337. if locale is None:
  338. logger.warning("build_engine_locales: skip locale tag %s / unknown by babel", tag)
  339. continue
  340. if locale.territory:
  341. engine_locales[region_tag(locale)] = tag
  342. if locale.script:
  343. engine_locales[language_tag(locale)] = tag
  344. else:
  345. engine_locales[language_tag(locale)] = tag
  346. return engine_locales