locales.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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, Optional, List
  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_locale(locale_tag: str) -> Optional[babel.Locale]:
  141. """Returns a :py:obj:`babel.Locale` object parsed from argument
  142. ``locale_tag``"""
  143. try:
  144. locale = babel.Locale.parse(locale_tag, sep='-')
  145. return locale
  146. except babel.core.UnknownLocaleError:
  147. return None
  148. def get_offical_locales(
  149. territory: str, languages=None, regional: bool = False, de_facto: bool = True
  150. ) -> Set[babel.Locale]:
  151. """Returns a list of :py:obj:`babel.Locale` with languages from
  152. :py:obj:`babel.languages.get_official_languages`.
  153. :param territory: The territory (country or region) code.
  154. :param languages: A list of language codes the languages from
  155. :py:obj:`babel.languages.get_official_languages` should be in
  156. (intersection). If this argument is ``None``, all official languages in
  157. this territory are used.
  158. :param regional: If the regional flag is set, then languages which are
  159. regionally official are also returned.
  160. :param de_facto: If the de_facto flag is set to `False`, then languages
  161. which are “de facto” official are not returned.
  162. """
  163. ret_val = set()
  164. o_languages = babel.languages.get_official_languages(territory, regional=regional, de_facto=de_facto)
  165. if languages:
  166. languages = [l.lower() for l in languages]
  167. o_languages = set(l for l in o_languages if l.lower() in languages)
  168. for lang in o_languages:
  169. try:
  170. locale = babel.Locale.parse(lang + '_' + territory)
  171. ret_val.add(locale)
  172. except babel.UnknownLocaleError:
  173. continue
  174. return ret_val
  175. def get_engine_locale(searxng_locale, engine_locales, default=None):
  176. """Return engine's language (aka locale) string that best fits to argument
  177. ``searxng_locale``.
  178. Argument ``engine_locales`` is a python dict that maps *SearXNG locales* to
  179. corresponding *engine locales*::
  180. <engine>: {
  181. # SearXNG string : engine-string
  182. 'ca-ES' : 'ca_ES',
  183. 'fr-BE' : 'fr_BE',
  184. 'fr-CA' : 'fr_CA',
  185. 'fr-CH' : 'fr_CH',
  186. 'fr' : 'fr_FR',
  187. ...
  188. 'pl-PL' : 'pl_PL',
  189. 'pt-PT' : 'pt_PT'
  190. ..
  191. 'zh' : 'zh'
  192. 'zh_Hans' : 'zh'
  193. 'zh_Hant' : 'zh_TW'
  194. }
  195. .. hint::
  196. The *SearXNG locale* string has to be known by babel!
  197. If there is no direct 1:1 mapping, this functions tries to narrow down
  198. engine's language (locale). If no value can be determined by these
  199. approximation attempts the ``default`` value is returned.
  200. Assumptions:
  201. A. When user select a language the results should be optimized according to
  202. the selected language.
  203. B. When user select a language and a territory the results should be
  204. optimized with first priority on terrirtory and second on language.
  205. First approximation rule (*by territory*):
  206. When the user selects a locale with terrirtory (and a language), the
  207. territory has priority over the language. If any of the offical languages
  208. in the terrirtory is supported by the engine (``engine_locales``) it will
  209. be used.
  210. Second approximation rule (*by language*):
  211. If "First approximation rule" brings no result or the user selects only a
  212. language without a terrirtory. Check in which territories the language
  213. has an offical status and if one of these territories is supported by the
  214. engine.
  215. """
  216. # pylint: disable=too-many-branches, too-many-return-statements
  217. engine_locale = engine_locales.get(searxng_locale)
  218. if engine_locale is not None:
  219. # There was a 1:1 mapping (e.g. a region "fr-BE --> fr_BE" or a language
  220. # "zh --> zh"), no need to narrow language-script nor territory.
  221. return engine_locale
  222. try:
  223. locale = babel.Locale.parse(searxng_locale, sep='-')
  224. except babel.core.UnknownLocaleError:
  225. try:
  226. locale = babel.Locale.parse(searxng_locale.split('-')[0])
  227. except babel.core.UnknownLocaleError:
  228. return default
  229. searxng_lang = language_tag(locale)
  230. engine_locale = engine_locales.get(searxng_lang)
  231. if engine_locale is not None:
  232. # There was a 1:1 mapping (e.g. "zh-HK --> zh_Hant" or "zh-CN --> zh_Hans")
  233. return engine_locale
  234. # SearXNG's selected locale is not supported by the engine ..
  235. if locale.territory:
  236. # Try to narrow by *offical* languages in the territory (??-XX).
  237. for official_language in babel.languages.get_official_languages(locale.territory, de_facto=True):
  238. searxng_locale = official_language + '-' + locale.territory
  239. engine_locale = engine_locales.get(searxng_locale)
  240. if engine_locale is not None:
  241. return engine_locale
  242. # Engine does not support one of the offical languages in the territory or
  243. # there is only a language selected without a territory.
  244. # Now lets have a look if the searxng_lang (the language selected by the
  245. # user) is a offical language in other territories. If so, check if
  246. # engine does support the searxng_lang in this other territory.
  247. if locale.language:
  248. terr_lang_dict = {}
  249. for territory, langs in babel.core.get_global("territory_languages").items():
  250. if not langs.get(searxng_lang, {}).get('official_status'):
  251. continue
  252. terr_lang_dict[territory] = langs.get(searxng_lang)
  253. # first: check fr-FR, de-DE .. is supported by the engine
  254. # exception: 'en' --> 'en-US'
  255. territory = locale.language.upper()
  256. if territory == 'EN':
  257. territory = 'US'
  258. if terr_lang_dict.get(territory):
  259. searxng_locale = locale.language + '-' + territory
  260. engine_locale = engine_locales.get(searxng_locale)
  261. if engine_locale is not None:
  262. return engine_locale
  263. # second: sort by population_percent and take first match
  264. # drawback of "population percent": if there is a terrirtory with a
  265. # small number of people (e.g 100) but the majority speaks the
  266. # language, then the percentage migth be 100% (--> 100 people) but in
  267. # a different terrirtory with more people (e.g. 10.000) where only 10%
  268. # speak the language the total amount of speaker is higher (--> 200
  269. # people).
  270. #
  271. # By example: The population of Saint-Martin is 33.000, of which 100%
  272. # speak French, but this is less than the 30% of the approximately 2.5
  273. # million Belgian citizens
  274. #
  275. # - 'fr-MF', 'population_percent': 100.0, 'official_status': 'official'
  276. # - 'fr-BE', 'population_percent': 38.0, 'official_status': 'official'
  277. terr_lang_list = []
  278. for k, v in terr_lang_dict.items():
  279. terr_lang_list.append((k, v))
  280. for territory, _lang in sorted(terr_lang_list, key=lambda item: item[1]['population_percent'], reverse=True):
  281. searxng_locale = locale.language + '-' + territory
  282. engine_locale = engine_locales.get(searxng_locale)
  283. if engine_locale is not None:
  284. return engine_locale
  285. # No luck: narrow by "language from territory" and "territory from language"
  286. # does not fit to a locale supported by the engine.
  287. if engine_locale is None:
  288. engine_locale = default
  289. return default
  290. def match_locale(searxng_locale: str, locale_tag_list: List[str], fallback: Optional[str] = None) -> Optional[str]:
  291. """Return tag from ``locale_tag_list`` that best fits to ``searxng_locale``.
  292. :param str searxng_locale: SearXNG's internal representation of locale (de,
  293. de-DE, fr-BE, zh, zh-CN, zh-TW ..).
  294. :param list locale_tag_list: The list of locale tags to select from
  295. :param str fallback: fallback locale tag (if unset --> ``None``)
  296. The rules to find a match are implemented in :py:obj:`get_engine_locale`,
  297. the ``engine_locales`` is build up by :py:obj:`build_engine_locales`.
  298. .. hint::
  299. The *SearXNG locale* string and the members of ``locale_tag_list`` has to
  300. be known by babel! The :py:obj:`ADDITIONAL_TRANSLATIONS` are used in the
  301. UI and are not known by babel --> will be ignored.
  302. """
  303. # searxng_locale = 'es'
  304. # locale_tag_list = ['es-AR', 'es-ES', 'es-MX']
  305. if not searxng_locale:
  306. return fallback
  307. locale = get_locale(searxng_locale)
  308. if locale is None:
  309. return fallback
  310. # normalize to a SearXNG locale that can be passed to get_engine_locale
  311. searxng_locale = language_tag(locale)
  312. if locale.territory:
  313. searxng_locale = region_tag(locale)
  314. # clean up locale_tag_list
  315. tag_list = []
  316. for tag in locale_tag_list:
  317. if tag in ('all', 'auto') or tag in ADDITIONAL_TRANSLATIONS:
  318. continue
  319. tag_list.append(tag)
  320. # emulate fetch_traits
  321. engine_locales = build_engine_locales(tag_list)
  322. return get_engine_locale(searxng_locale, engine_locales, default=fallback)
  323. def build_engine_locales(tag_list: List[str]):
  324. """From a list of locale tags a dictionary is build that can be passed by
  325. argument ``engine_locales`` to :py:obj:`get_engine_locale`. This function
  326. is mainly used by :py:obj:`match_locale` and is similar to what the
  327. ``fetch_traits(..)`` function of engines do.
  328. If there are territory codes in the ``tag_list`` that have a *script code*
  329. additional keys are added to the returned dictionary.
  330. .. code:: python
  331. >>> import locales
  332. >>> engine_locales = locales.build_engine_locales(['en', 'en-US', 'zh', 'zh-CN', 'zh-TW'])
  333. >>> engine_locales
  334. {
  335. 'en': 'en', 'en-US': 'en-US',
  336. 'zh': 'zh', 'zh-CN': 'zh-CN', 'zh_Hans': 'zh-CN',
  337. 'zh-TW': 'zh-TW', 'zh_Hant': 'zh-TW'
  338. }
  339. >>> get_engine_locale('zh-Hans', engine_locales)
  340. 'zh-CN'
  341. This function is a good example to understand the language/region model
  342. of SearXNG:
  343. SearXNG only distinguishes between **search languages** and **search
  344. regions**, by adding the *script-tags*, languages with *script-tags* can
  345. be assigned to the **regions** that SearXNG supports.
  346. """
  347. engine_locales = {}
  348. for tag in tag_list:
  349. locale = get_locale(tag)
  350. if locale is None:
  351. logger.warning("build_engine_locales: skip locale tag %s / unknown by babel", tag)
  352. continue
  353. if locale.territory:
  354. engine_locales[region_tag(locale)] = tag
  355. if locale.script:
  356. engine_locales[language_tag(locale)] = tag
  357. else:
  358. engine_locales[language_tag(locale)] = tag
  359. return engine_locales