locales.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. from babel import Locale
  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 = 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 = 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 = 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 get_engine_locale(searxng_locale, engine_locales, default=None):
  128. """Return engine's language (aka locale) string that best fits to argument
  129. ``searxng_locale``.
  130. Argument ``engine_locales`` is a python dict that maps *SearXNG locales* to
  131. corresponding *engine locales*::
  132. <engine>: {
  133. # SearXNG string : engine-string
  134. 'ca-ES' : 'ca_ES',
  135. 'fr-BE' : 'fr_BE',
  136. 'fr-CA' : 'fr_CA',
  137. 'fr-CH' : 'fr_CH',
  138. 'fr' : 'fr_FR',
  139. ...
  140. 'pl-PL' : 'pl_PL',
  141. 'pt-PT' : 'pt_PT'
  142. }
  143. .. hint::
  144. The *SearXNG locale* string has to be known by babel!
  145. If there is no direct 1:1 mapping, this functions tries to narrow down
  146. engine's language (locale). If no value can be determined by these
  147. approximation attempts the ``default`` value is returned.
  148. Assumptions:
  149. A. When user select a language the results should be optimized according to
  150. the selected language.
  151. B. When user select a language and a territory the results should be
  152. optimized with first priority on terrirtory and second on language.
  153. First approximation rule (*by territory*):
  154. When the user selects a locale with terrirtory (and a language), the
  155. territory has priority over the language. If any of the offical languages
  156. in the terrirtory is supported by the engine (``engine_locales``) it will
  157. be used.
  158. Second approximation rule (*by language*):
  159. If "First approximation rule" brings no result or the user selects only a
  160. language without a terrirtory. Check in which territories the language
  161. has an offical status and if one of these territories is supported by the
  162. engine.
  163. """
  164. # pylint: disable=too-many-branches
  165. engine_locale = engine_locales.get(searxng_locale)
  166. if engine_locale is not None:
  167. # There was a 1:1 mapping (e.g. "fr-BE --> fr_BE" or "fr --> fr_FR"), no
  168. # need to narrow language nor territory.
  169. return engine_locale
  170. try:
  171. locale = babel.Locale.parse(searxng_locale, sep='-')
  172. except babel.core.UnknownLocaleError:
  173. try:
  174. locale = babel.Locale.parse(searxng_locale.split('-')[0])
  175. except babel.core.UnknownLocaleError:
  176. return default
  177. # SearXNG's selected locale is not supported by the engine ..
  178. if locale.territory:
  179. # Try to narrow by *offical* languages in the territory (??-XX).
  180. for official_language in babel.languages.get_official_languages(locale.territory, de_facto=True):
  181. searxng_locale = official_language + '-' + locale.territory
  182. engine_locale = engine_locales.get(searxng_locale)
  183. if engine_locale is not None:
  184. return engine_locale
  185. # Engine does not support one of the offical languages in the territory or
  186. # there is only a language selected without a territory.
  187. # Now lets have a look if the searxng_lang (the language selected by the
  188. # user) is a offical language in other territories. If so, check if
  189. # engine does support the searxng_lang in this other territory.
  190. if locale.language:
  191. searxng_lang = locale.language
  192. if locale.script:
  193. searxng_lang += '_' + locale.script
  194. terr_lang_dict = {}
  195. for territory, langs in babel.core.get_global("territory_languages").items():
  196. if not langs.get(searxng_lang, {}).get('official_status'):
  197. continue
  198. terr_lang_dict[territory] = langs.get(searxng_lang)
  199. # first: check fr-FR, de-DE .. is supported by the engine
  200. # exception: 'en' --> 'en-US'
  201. territory = locale.language.upper()
  202. if territory == 'EN':
  203. territory = 'US'
  204. if terr_lang_dict.get(territory):
  205. searxng_locale = locale.language + '-' + territory
  206. engine_locale = engine_locales.get(searxng_locale)
  207. if engine_locale is not None:
  208. return engine_locale
  209. # second: sort by population_percent and take first match
  210. # drawback of "population percent": if there is a terrirtory with a
  211. # small number of people (e.g 100) but the majority speaks the
  212. # language, then the percentage migth be 100% (--> 100 people) but in
  213. # a different terrirtory with more people (e.g. 10.000) where only 10%
  214. # speak the language the total amount of speaker is higher (--> 200
  215. # people).
  216. #
  217. # By example: The population of Saint-Martin is 33.000, of which 100%
  218. # speak French, but this is less than the 30% of the approximately 2.5
  219. # million Belgian citizens
  220. #
  221. # - 'fr-MF', 'population_percent': 100.0, 'official_status': 'official'
  222. # - 'fr-BE', 'population_percent': 38.0, 'official_status': 'official'
  223. terr_lang_list = []
  224. for k, v in terr_lang_dict.items():
  225. terr_lang_list.append((k, v))
  226. for territory, _lang in sorted(terr_lang_list, key=lambda item: item[1]['population_percent'], reverse=True):
  227. searxng_locale = locale.language + '-' + territory
  228. engine_locale = engine_locales.get(searxng_locale)
  229. if engine_locale is not None:
  230. return engine_locale
  231. # No luck: narrow by "language from territory" and "territory from language"
  232. # does not fit to a locale supported by the engine.
  233. if engine_locale is None:
  234. engine_locale = default
  235. return default