locales.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. "oc": "Occitan",
  30. "szl": "Ślōnski (Silesian)",
  31. "pap": "Papiamento",
  32. }
  33. """Additional languages SearXNG has translations for but not supported by
  34. python-babel (see :py:obj:`locales_initialize`)."""
  35. LOCALE_BEST_MATCH = {
  36. "oc": 'fr-FR',
  37. "szl": "pl",
  38. "nl-BE": "nl",
  39. "zh-HK": "zh-Hant-TW",
  40. "pap": "pt-BR",
  41. }
  42. """Map a locale we do not have a translations for to a locale we have a
  43. translation for. By example: use Taiwan version of the translation for Hong
  44. Kong."""
  45. def localeselector():
  46. locale = 'en'
  47. if has_request_context():
  48. value = flask.request.preferences.get_value('locale')
  49. if value:
  50. locale = value
  51. # first, set the language that is not supported by babel
  52. if locale in ADDITIONAL_TRANSLATIONS:
  53. flask.request.form['use-translation'] = locale
  54. # second, map locale to a value python-babel supports
  55. locale = LOCALE_BEST_MATCH.get(locale, locale)
  56. if locale == '':
  57. # if there is an error loading the preferences
  58. # the locale is going to be ''
  59. locale = 'en'
  60. # babel uses underscore instead of hyphen.
  61. locale = locale.replace('-', '_')
  62. return locale
  63. def get_translations():
  64. """Monkey patch of :py:obj:`flask_babel.get_translations`"""
  65. if has_request_context() and flask.request.form.get('use-translation') == 'oc':
  66. babel_ext = flask_babel.current_app.extensions['babel']
  67. return Translations.load(next(babel_ext.translation_directories), 'oc')
  68. if has_request_context() and flask.request.form.get('use-translation') == 'szl':
  69. babel_ext = flask_babel.current_app.extensions['babel']
  70. return Translations.load(next(babel_ext.translation_directories), 'szl')
  71. if has_request_context() and flask.request.form.get('use-translation') == 'pap':
  72. babel_ext = flask_babel.current_app.extensions['babel']
  73. return Translations.load(next(babel_ext.translation_directories), 'pap')
  74. return _flask_babel_get_translations()
  75. def get_locale_descr(locale, locale_name):
  76. """Get locale name e.g. 'Français - fr' or 'Português (Brasil) - pt-BR'
  77. :param locale: instance of :py:class:`Locale`
  78. :param locale_name: name e.g. 'fr' or 'pt_BR' (delimiter is *underscore*)
  79. """
  80. native_language, native_territory = _get_locale_descr(locale, locale_name)
  81. english_language, english_territory = _get_locale_descr(locale, 'en')
  82. if native_territory == english_territory:
  83. english_territory = None
  84. if not native_territory and not english_territory:
  85. if native_language == english_language:
  86. return native_language
  87. return native_language + ' (' + english_language + ')'
  88. result = native_language + ', ' + native_territory + ' (' + english_language
  89. if english_territory:
  90. return result + ', ' + english_territory + ')'
  91. return result + ')'
  92. def _get_locale_descr(locale, language_code):
  93. language_name = locale.get_language_name(language_code).capitalize()
  94. if language_name and ('a' <= language_name[0] <= 'z'):
  95. language_name = language_name.capitalize()
  96. terrirtory_name = locale.get_territory_name(language_code)
  97. return language_name, terrirtory_name
  98. def locales_initialize(directory=None):
  99. """Initialize locales environment of the SearXNG session.
  100. - monkey patch :py:obj:`flask_babel.get_translations` by :py:obj:`get_translations`
  101. - init global names :py:obj:`LOCALE_NAMES`, :py:obj:`RTL_LOCALES`
  102. """
  103. directory = directory or pathlib.Path(__file__).parent / 'translations'
  104. logger.debug("locales_initialize: %s", directory)
  105. flask_babel.get_translations = get_translations
  106. for tag, descr in ADDITIONAL_TRANSLATIONS.items():
  107. LOCALE_NAMES[tag] = descr
  108. for tag in LOCALE_BEST_MATCH:
  109. descr = LOCALE_NAMES.get(tag)
  110. if not descr:
  111. locale = Locale.parse(tag, sep='-')
  112. LOCALE_NAMES[tag] = get_locale_descr(locale, tag.replace('-', '_'))
  113. for dirname in sorted(os.listdir(directory)):
  114. # Based on https://flask-babel.tkte.ch/_modules/flask_babel.html#Babel.list_translations
  115. if not os.path.isdir(os.path.join(directory, dirname, 'LC_MESSAGES')):
  116. continue
  117. tag = dirname.replace('_', '-')
  118. descr = LOCALE_NAMES.get(tag)
  119. if not descr:
  120. locale = Locale.parse(dirname)
  121. LOCALE_NAMES[tag] = get_locale_descr(locale, dirname)
  122. if locale.text_direction == 'rtl':
  123. RTL_LOCALES.add(tag)
  124. def get_engine_locale(searxng_locale, engine_locales, default=None):
  125. """Return engine's language (aka locale) string that best fits to argument
  126. ``searxng_locale``.
  127. Argument ``engine_locales`` is a python dict that maps *SearXNG locales* to
  128. corresponding *engine locales*::
  129. <engine>: {
  130. # SearXNG string : engine-string
  131. 'ca-ES' : 'ca_ES',
  132. 'fr-BE' : 'fr_BE',
  133. 'fr-CA' : 'fr_CA',
  134. 'fr-CH' : 'fr_CH',
  135. 'fr' : 'fr_FR',
  136. ...
  137. 'pl-PL' : 'pl_PL',
  138. 'pt-PT' : 'pt_PT'
  139. }
  140. .. hint::
  141. The *SearXNG locale* string has to be known by babel!
  142. If there is no direct 1:1 mapping, this functions tries to narrow down
  143. engine's language (locale). If no value can be determined by these
  144. approximation attempts the ``default`` value is returned.
  145. Assumptions:
  146. A. When user select a language the results should be optimized according to
  147. the selected language.
  148. B. When user select a language and a territory the results should be
  149. optimized with first priority on terrirtory and second on language.
  150. First approximation rule (*by territory*):
  151. When the user selects a locale with terrirtory (and a language), the
  152. territory has priority over the language. If any of the offical languages
  153. in the terrirtory is supported by the engine (``engine_locales``) it will
  154. be used.
  155. Second approximation rule (*by language*):
  156. If "First approximation rule" brings no result or the user selects only a
  157. language without a terrirtory. Check in which territories the language
  158. has an offical status and if one of these territories is supported by the
  159. engine.
  160. """
  161. # pylint: disable=too-many-branches
  162. engine_locale = engine_locales.get(searxng_locale)
  163. if engine_locale is not None:
  164. # There was a 1:1 mapping (e.g. "fr-BE --> fr_BE" or "fr --> fr_FR"), no
  165. # need to narrow language nor territory.
  166. return engine_locale
  167. try:
  168. locale = babel.Locale.parse(searxng_locale, sep='-')
  169. except babel.core.UnknownLocaleError:
  170. try:
  171. locale = babel.Locale.parse(searxng_locale.split('-')[0])
  172. except babel.core.UnknownLocaleError:
  173. return default
  174. # SearXNG's selected locale is not supported by the engine ..
  175. if locale.territory:
  176. # Try to narrow by *offical* languages in the territory (??-XX).
  177. for official_language in babel.languages.get_official_languages(locale.territory, de_facto=True):
  178. searxng_locale = official_language + '-' + locale.territory
  179. engine_locale = engine_locales.get(searxng_locale)
  180. if engine_locale is not None:
  181. return engine_locale
  182. # Engine does not support one of the offical languages in the territory or
  183. # there is only a language selected without a territory.
  184. # Now lets have a look if the searxng_lang (the language selected by the
  185. # user) is a offical language in other territories. If so, check if
  186. # engine does support the searxng_lang in this other territory.
  187. if locale.language:
  188. searxng_lang = locale.language
  189. if locale.script:
  190. searxng_lang += '_' + locale.script
  191. terr_lang_dict = {}
  192. for territory, langs in babel.core.get_global("territory_languages").items():
  193. if not langs.get(searxng_lang, {}).get('official_status'):
  194. continue
  195. terr_lang_dict[territory] = langs.get(searxng_lang)
  196. # first: check fr-FR, de-DE .. is supported by the engine
  197. # exception: 'en' --> 'en-US'
  198. territory = locale.language.upper()
  199. if territory == 'EN':
  200. territory = 'US'
  201. if terr_lang_dict.get(territory):
  202. searxng_locale = locale.language + '-' + territory
  203. engine_locale = engine_locales.get(searxng_locale)
  204. if engine_locale is not None:
  205. return engine_locale
  206. # second: sort by population_percent and take first match
  207. # drawback of "population percent": if there is a terrirtory with a
  208. # small number of people (e.g 100) but the majority speaks the
  209. # language, then the percentage migth be 100% (--> 100 people) but in
  210. # a different terrirtory with more people (e.g. 10.000) where only 10%
  211. # speak the language the total amount of speaker is higher (--> 200
  212. # people).
  213. #
  214. # By example: The population of Saint-Martin is 33.000, of which 100%
  215. # speak French, but this is less than the 30% of the approximately 2.5
  216. # million Belgian citizens
  217. #
  218. # - 'fr-MF', 'population_percent': 100.0, 'official_status': 'official'
  219. # - 'fr-BE', 'population_percent': 38.0, 'official_status': 'official'
  220. terr_lang_list = []
  221. for k, v in terr_lang_dict.items():
  222. terr_lang_list.append((k, v))
  223. for territory, _lang in sorted(terr_lang_list, key=lambda item: item[1]['population_percent'], reverse=True):
  224. searxng_locale = locale.language + '-' + territory
  225. engine_locale = engine_locales.get(searxng_locale)
  226. if engine_locale is not None:
  227. return engine_locale
  228. # No luck: narrow by "language from territory" and "territory from language"
  229. # does not fit to a locale supported by the engine.
  230. if engine_locale is None:
  231. engine_locale = default
  232. return default