locales.py 15 KB

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