locales.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. # -*- coding: utf-8 -*-
  2. # SPDX-License-Identifier: AGPL-3.0-or-later
  3. # lint: pylint
  4. """Initialize :py:obj:`LOCALE_NAMES`, :py:obj:`RTL_LOCALES`.
  5. """
  6. from typing import Set
  7. import os
  8. import pathlib
  9. import babel
  10. from babel.support import Translations
  11. import babel.languages
  12. import babel.core
  13. import flask_babel
  14. import flask
  15. from flask.ctx import has_request_context
  16. from searx import logger
  17. logger = logger.getChild('locales')
  18. # safe before monkey patching flask_babel.get_translations
  19. _flask_babel_get_translations = flask_babel.get_translations
  20. LOCALE_NAMES = {}
  21. """Mapping of locales and their description. Locales e.g. 'fr' or 'pt-BR' (see
  22. :py:obj:`locales_initialize`).
  23. :meta hide-value:
  24. """
  25. RTL_LOCALES: Set[str] = set()
  26. """List of *Right-To-Left* locales e.g. 'he' or 'fa-IR' (see
  27. :py:obj:`locales_initialize`)."""
  28. ADDITIONAL_TRANSLATIONS = {
  29. "dv": "ދިވެހި (Dhivehi)",
  30. "oc": "Occitan",
  31. "szl": "Ślōnski (Silesian)",
  32. "pap": "Papiamento",
  33. }
  34. """Additional languages SearXNG has translations for but not supported by
  35. python-babel (see :py:obj:`locales_initialize`)."""
  36. LOCALE_BEST_MATCH = {
  37. "dv": "si",
  38. "oc": 'fr-FR',
  39. "szl": "pl",
  40. "nl-BE": "nl",
  41. "zh-HK": "zh-Hant-TW",
  42. "pap": "pt-BR",
  43. }
  44. """Map a locale we do not have a translations for to a locale we have a
  45. translation for. By example: use Taiwan version of the translation for Hong
  46. Kong."""
  47. def localeselector():
  48. locale = 'en'
  49. if has_request_context():
  50. value = flask.request.preferences.get_value('locale')
  51. if value:
  52. locale = value
  53. # first, set the language that is not supported by babel
  54. if locale in ADDITIONAL_TRANSLATIONS:
  55. flask.request.form['use-translation'] = locale
  56. # second, map locale to a value python-babel supports
  57. locale = LOCALE_BEST_MATCH.get(locale, locale)
  58. if locale == '':
  59. # if there is an error loading the preferences
  60. # the locale is going to be ''
  61. locale = 'en'
  62. # babel uses underscore instead of hyphen.
  63. locale = locale.replace('-', '_')
  64. return locale
  65. def get_translations():
  66. """Monkey patch of :py:obj:`flask_babel.get_translations`"""
  67. if has_request_context():
  68. use_translation = flask.request.form.get('use-translation')
  69. if use_translation in ADDITIONAL_TRANSLATIONS:
  70. babel_ext = flask_babel.current_app.extensions['babel']
  71. return Translations.load(babel_ext.translation_directories[0], use_translation)
  72. return _flask_babel_get_translations()
  73. def get_locale_descr(locale, locale_name):
  74. """Get locale name e.g. 'Français - fr' or 'Português (Brasil) - pt-BR'
  75. :param locale: instance of :py:class:`Locale`
  76. :param locale_name: name e.g. 'fr' or 'pt_BR' (delimiter is *underscore*)
  77. """
  78. native_language, native_territory = _get_locale_descr(locale, locale_name)
  79. english_language, english_territory = _get_locale_descr(locale, 'en')
  80. if native_territory == english_territory:
  81. english_territory = None
  82. if not native_territory and not english_territory:
  83. if native_language == english_language:
  84. return native_language
  85. return native_language + ' (' + english_language + ')'
  86. result = native_language + ', ' + native_territory + ' (' + english_language
  87. if english_territory:
  88. return result + ', ' + english_territory + ')'
  89. return result + ')'
  90. def _get_locale_descr(locale, language_code):
  91. language_name = locale.get_language_name(language_code).capitalize()
  92. if language_name and ('a' <= language_name[0] <= 'z'):
  93. language_name = language_name.capitalize()
  94. terrirtory_name = locale.get_territory_name(language_code)
  95. return language_name, terrirtory_name
  96. def locales_initialize(directory=None):
  97. """Initialize locales environment of the SearXNG session.
  98. - monkey patch :py:obj:`flask_babel.get_translations` by :py:obj:`get_translations`
  99. - init global names :py:obj:`LOCALE_NAMES`, :py:obj:`RTL_LOCALES`
  100. """
  101. directory = directory or pathlib.Path(__file__).parent / 'translations'
  102. logger.debug("locales_initialize: %s", directory)
  103. flask_babel.get_translations = get_translations
  104. for tag, descr in ADDITIONAL_TRANSLATIONS.items():
  105. locale = babel.Locale.parse(LOCALE_BEST_MATCH[tag], sep='-')
  106. LOCALE_NAMES[tag] = descr
  107. if locale.text_direction == 'rtl':
  108. RTL_LOCALES.add(tag)
  109. for tag in LOCALE_BEST_MATCH:
  110. descr = LOCALE_NAMES.get(tag)
  111. if not descr:
  112. locale = babel.Locale.parse(tag, sep='-')
  113. LOCALE_NAMES[tag] = get_locale_descr(locale, tag.replace('-', '_'))
  114. if locale.text_direction == 'rtl':
  115. RTL_LOCALES.add(tag)
  116. for dirname in sorted(os.listdir(directory)):
  117. # Based on https://flask-babel.tkte.ch/_modules/flask_babel.html#Babel.list_translations
  118. if not os.path.isdir(os.path.join(directory, dirname, 'LC_MESSAGES')):
  119. continue
  120. tag = dirname.replace('_', '-')
  121. descr = LOCALE_NAMES.get(tag)
  122. if not descr:
  123. locale = babel.Locale.parse(dirname)
  124. LOCALE_NAMES[tag] = get_locale_descr(locale, dirname)
  125. if locale.text_direction == 'rtl':
  126. RTL_LOCALES.add(tag)
  127. def region_tag(locale: babel.Locale) -> str:
  128. """Returns SearXNG's region tag from the locale (e.g. zh-TW , en-US)."""
  129. if not locale.territory:
  130. raise ValueError('%s missed a territory')
  131. return locale.language + '-' + locale.territory
  132. def language_tag(locale: babel.Locale) -> str:
  133. """Returns SearXNG's language tag from the locale and if exits, the tag
  134. includes the script name (e.g. en, zh_Hant).
  135. """
  136. sxng_lang = locale.language
  137. if locale.script:
  138. sxng_lang += '_' + locale.script
  139. return sxng_lang
  140. def get_offical_locales(
  141. territory: str, languages=None, regional: bool = False, de_facto: bool = True
  142. ) -> Set[babel.Locale]:
  143. """Returns a list of :py:obj:`babel.Locale` with languages from
  144. :py:obj:`babel.languages.get_official_languages`.
  145. :param territory: The territory (country or region) code.
  146. :param languages: A list of language codes the languages from
  147. :py:obj:`babel.languages.get_official_languages` should be in
  148. (intersection). If this argument is ``None``, all official languages in
  149. this territory are used.
  150. :param regional: If the regional flag is set, then languages which are
  151. regionally official are also returned.
  152. :param de_facto: If the de_facto flag is set to `False`, then languages
  153. which are “de facto” official are not returned.
  154. """
  155. ret_val = set()
  156. o_languages = babel.languages.get_official_languages(territory, regional=regional, de_facto=de_facto)
  157. if languages:
  158. languages = [l.lower() for l in languages]
  159. o_languages = set(l for l in o_languages if l.lower() in languages)
  160. for lang in o_languages:
  161. try:
  162. locale = babel.Locale.parse(lang + '_' + territory)
  163. ret_val.add(locale)
  164. except babel.UnknownLocaleError:
  165. continue
  166. return ret_val
  167. def get_engine_locale(searxng_locale, engine_locales, default=None):
  168. """Return engine's language (aka locale) string that best fits to argument
  169. ``searxng_locale``.
  170. Argument ``engine_locales`` is a python dict that maps *SearXNG locales* to
  171. corresponding *engine locales*::
  172. <engine>: {
  173. # SearXNG string : engine-string
  174. 'ca-ES' : 'ca_ES',
  175. 'fr-BE' : 'fr_BE',
  176. 'fr-CA' : 'fr_CA',
  177. 'fr-CH' : 'fr_CH',
  178. 'fr' : 'fr_FR',
  179. ...
  180. 'pl-PL' : 'pl_PL',
  181. 'pt-PT' : 'pt_PT'
  182. ..
  183. 'zh' : 'zh'
  184. 'zh_Hans' : 'zh'
  185. 'zh_Hant' : 'zh-classical'
  186. }
  187. .. hint::
  188. The *SearXNG locale* string has to be known by babel!
  189. If there is no direct 1:1 mapping, this functions tries to narrow down
  190. engine's language (locale). If no value can be determined by these
  191. approximation attempts the ``default`` value is returned.
  192. Assumptions:
  193. A. When user select a language the results should be optimized according to
  194. the selected language.
  195. B. When user select a language and a territory the results should be
  196. optimized with first priority on terrirtory and second on language.
  197. First approximation rule (*by territory*):
  198. When the user selects a locale with terrirtory (and a language), the
  199. territory has priority over the language. If any of the offical languages
  200. in the terrirtory is supported by the engine (``engine_locales``) it will
  201. be used.
  202. Second approximation rule (*by language*):
  203. If "First approximation rule" brings no result or the user selects only a
  204. language without a terrirtory. Check in which territories the language
  205. has an offical status and if one of these territories is supported by the
  206. engine.
  207. """
  208. # pylint: disable=too-many-branches, too-many-return-statements
  209. engine_locale = engine_locales.get(searxng_locale)
  210. if engine_locale is not None:
  211. # There was a 1:1 mapping (e.g. a region "fr-BE --> fr_BE" or a language
  212. # "zh --> zh"), no need to narrow language-script nor territory.
  213. return engine_locale
  214. try:
  215. locale = babel.Locale.parse(searxng_locale, sep='-')
  216. except babel.core.UnknownLocaleError:
  217. try:
  218. locale = babel.Locale.parse(searxng_locale.split('-')[0])
  219. except babel.core.UnknownLocaleError:
  220. return default
  221. searxng_lang = language_tag(locale)
  222. engine_locale = engine_locales.get(searxng_lang)
  223. if engine_locale is not None:
  224. # There was a 1:1 mapping (e.g. "zh-HK --> zh_Hant" or "zh-CN --> zh_Hans")
  225. return engine_locale
  226. # SearXNG's selected locale is not supported by the engine ..
  227. if locale.territory:
  228. # Try to narrow by *offical* languages in the territory (??-XX).
  229. for official_language in babel.languages.get_official_languages(locale.territory, de_facto=True):
  230. searxng_locale = official_language + '-' + locale.territory
  231. engine_locale = engine_locales.get(searxng_locale)
  232. if engine_locale is not None:
  233. return engine_locale
  234. # Engine does not support one of the offical languages in the territory or
  235. # there is only a language selected without a territory.
  236. # Now lets have a look if the searxng_lang (the language selected by the
  237. # user) is a offical language in other territories. If so, check if
  238. # engine does support the searxng_lang in this other territory.
  239. if locale.language:
  240. terr_lang_dict = {}
  241. for territory, langs in babel.core.get_global("territory_languages").items():
  242. if not langs.get(searxng_lang, {}).get('official_status'):
  243. continue
  244. terr_lang_dict[territory] = langs.get(searxng_lang)
  245. # first: check fr-FR, de-DE .. is supported by the engine
  246. # exception: 'en' --> 'en-US'
  247. territory = locale.language.upper()
  248. if territory == 'EN':
  249. territory = 'US'
  250. if terr_lang_dict.get(territory):
  251. searxng_locale = locale.language + '-' + territory
  252. engine_locale = engine_locales.get(searxng_locale)
  253. if engine_locale is not None:
  254. return engine_locale
  255. # second: sort by population_percent and take first match
  256. # drawback of "population percent": if there is a terrirtory with a
  257. # small number of people (e.g 100) but the majority speaks the
  258. # language, then the percentage migth be 100% (--> 100 people) but in
  259. # a different terrirtory with more people (e.g. 10.000) where only 10%
  260. # speak the language the total amount of speaker is higher (--> 200
  261. # people).
  262. #
  263. # By example: The population of Saint-Martin is 33.000, of which 100%
  264. # speak French, but this is less than the 30% of the approximately 2.5
  265. # million Belgian citizens
  266. #
  267. # - 'fr-MF', 'population_percent': 100.0, 'official_status': 'official'
  268. # - 'fr-BE', 'population_percent': 38.0, 'official_status': 'official'
  269. terr_lang_list = []
  270. for k, v in terr_lang_dict.items():
  271. terr_lang_list.append((k, v))
  272. for territory, _lang in sorted(terr_lang_list, key=lambda item: item[1]['population_percent'], reverse=True):
  273. searxng_locale = locale.language + '-' + territory
  274. engine_locale = engine_locales.get(searxng_locale)
  275. if engine_locale is not None:
  276. return engine_locale
  277. # No luck: narrow by "language from territory" and "territory from language"
  278. # does not fit to a locale supported by the engine.
  279. if engine_locale is None:
  280. engine_locale = default
  281. return default