locales.py 10 KB

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