translations.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # -*- coding: utf-8 -*-
  2. import gettext
  3. import locale
  4. import os
  5. from time import strftime, localtime
  6. __SYSTEM_LOCALE_FOUND = False
  7. # List all available languages.
  8. Languages = [
  9. ('de_DE', 'Deutsch'),
  10. ('nl_NL', 'Nederlands'),
  11. ('es_ES', 'Español')
  12. ]
  13. # Set searx-qt default language
  14. Language = None
  15. # Find system default
  16. defaultLanguage, defaultEncoding = locale.getlocale()
  17. # Set current language to system default if found.
  18. index = 0
  19. for key, name in Languages:
  20. if defaultLanguage == key:
  21. Language = Languages[index]
  22. break
  23. index += 1
  24. def timeToString(time_):
  25. if __SYSTEM_LOCALE_FOUND:
  26. locale.setlocale(locale.LC_TIME, normalize(Language[0]))
  27. return strftime("%a %d %b %Y %H:%M:%S", localtime(time_))
  28. def normalize(localeName):
  29. str_ = locale.normalize(localeName)
  30. enc = locale.getpreferredencoding(do_setlocale=True)
  31. str_ = str_.split('.', 1)[0]
  32. return str_ + "." + enc
  33. def localeTest(normalizedLocaleName):
  34. try:
  35. locale.setlocale(locale.LC_TIME, normalizedLocaleName)
  36. except locale.Error:
  37. return False
  38. return True
  39. _ = gettext.gettext
  40. if Language:
  41. # Set LC_TIME if system locale found.
  42. __SYSTEM_LOCALE_FOUND = localeTest(
  43. normalize(Language[0])
  44. )
  45. if not __SYSTEM_LOCALE_FOUND:
  46. print("Warning! `{0}` not found. Cannot translate dates and time."
  47. .format(normalize(Language[0])))
  48. # Set local .mo file.
  49. lang = None
  50. try:
  51. # First try system locale directory
  52. lang = gettext.translation('searx-qt', languages=[Language[0]])
  53. except FileNotFoundError:
  54. xdgDataHome = os.getenv('XDG_DATA_HOME')
  55. if xdgDataHome is not None:
  56. localeDir = os.path.join(xdgDataHome, 'locale')
  57. try:
  58. lang = gettext.translation('searx-qt', localedir=localeDir,
  59. languages=[Language[0]])
  60. except FileNotFoundError:
  61. pass
  62. if lang:
  63. lang.install()
  64. _ = lang.gettext
  65. else:
  66. print("Warning! Locale file (.mo) for language `{0}` not found!"
  67. .format(Language[0]))