locales.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. LOCALE_NAMES = {
  11. "oc": "Occitan",
  12. "nl-BE": "Vlaams (Dutch, Belgium)",
  13. }
  14. """Mapping of locales and their description. Locales e.g. 'fr' or 'pt-BR'
  15. (delimiter is *underline* '-')"""
  16. RTL_LOCALES: Set[str] = set()
  17. """List of *Right-To-Left* locales e.g. 'he' or 'fa-IR' (delimiter is
  18. *underline* '-')"""
  19. def _get_name(locale, language_code):
  20. language_name = locale.get_language_name(language_code).capitalize()
  21. if language_name and ('a' <= language_name[0] <= 'z'):
  22. language_name = language_name.capitalize()
  23. terrirtory_name = locale.get_territory_name(language_code)
  24. return language_name, terrirtory_name
  25. def _get_locale_name(locale, locale_name):
  26. """Get locale name e.g. 'Français - fr' or 'Português (Brasil) - pt-BR'
  27. :param locale: instance of :py:class:`Locale`
  28. :param locale_name: name e.g. 'fr' or 'pt_BR' (delimiter is *underscore*)
  29. """
  30. native_language, native_territory = _get_name(locale, locale_name)
  31. english_language, english_territory = _get_name(locale, 'en')
  32. if native_territory == english_territory:
  33. english_territory = None
  34. if not native_territory and not english_territory:
  35. if native_language == english_language:
  36. return native_language
  37. return native_language + ' (' + english_language + ')'
  38. result = native_language + ', ' + native_territory + ' (' + english_language
  39. if english_territory:
  40. return result + ', ' + english_territory + ')'
  41. return result + ')'
  42. def initialize_locales(directory):
  43. """Initialize global names :py:obj:`LOCALE_NAMES`, :py:obj:`RTL_LOCALES`."""
  44. for dirname in sorted(os.listdir(directory)):
  45. # Based on https://flask-babel.tkte.ch/_modules/flask_babel.html#Babel.list_translations
  46. if not os.path.isdir(os.path.join(directory, dirname, 'LC_MESSAGES')):
  47. continue
  48. locale_name = dirname.replace('_', '-')
  49. info = LOCALE_NAMES.get(locale_name)
  50. if not info:
  51. locale = Locale.parse(dirname)
  52. LOCALE_NAMES[locale_name] = _get_locale_name(locale, dirname)
  53. if locale.text_direction == 'rtl':
  54. RTL_LOCALES.add(locale_name)
  55. initialize_locales(pathlib.Path(__file__).parent / 'translations')