No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mlstring.py 4.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. #
  2. # This file is part of Lodel 2 (https://github.com/OpenEdition)
  3. #
  4. # Copyright (C) 2015-2017 Cléo UMS-3287
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU Affero General Public License as published
  8. # by the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU Affero General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Affero General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. import copy
  20. import hashlib
  21. import json
  22. ## @package lodel.utils.mlstring Lodel2 description of multilanguage string
  23. #
  24. # Display content of a string in different languages
  25. class MlString(object):
  26. __default_lang = 'eng'
  27. langs = [
  28. 'fre',
  29. 'eng',
  30. 'ger',
  31. 'esp',
  32. ]
  33. # @brief Create a new MlString instance
  34. # @param arg str | dict : Can be a json string, a string or a dict. It could also be a MlString object
  35. def __init__(self, arg):
  36. self.values = dict()
  37. if isinstance(arg, str):
  38. self.values[self.__default_lang] = arg
  39. elif isinstance(arg, dict):
  40. for lang, value in arg.items():
  41. if not self.lang_is_valid(lang):
  42. raise ValueError('Invalid lang found in argument : "%s"' % lang)
  43. self.values[lang] = value
  44. elif isinstance(arg, MlString):
  45. self.values = copy.copy(arg.values)
  46. else:
  47. raise ValueError(
  48. '<class str>, <class dict> or <class MlString> expected, but %s found' % type(arg))
  49. # @brief Return a translation given a lang
  50. # @param lang str | None : If None return default lang translation
  51. def get(self, lang=None):
  52. lang = self.__default_lang if lang is None else lang
  53. if not self.lang_is_valid(lang):
  54. raise ValueError("Invalid lang : '%s'" % lang)
  55. elif lang in self.values:
  56. return self.values[lang]
  57. else:
  58. return str(self)
  59. # @brief Set a translation
  60. # @param lang str : the lang
  61. # @param val str | None: the translation if None delete the translation
  62. def set(self, lang, val):
  63. if not self.lang_is_valid(lang):
  64. raise ValueError("Invalid lang : '%s'" % lang)
  65. if not isinstance(val, str) and val is not None:
  66. raise ValueError("Expected a <class str> as value but got %s" % type(val))
  67. if val is None:
  68. del(self.values[lang])
  69. else:
  70. self.values[lang] = val
  71. # @brief Checks that given lang is valid
  72. # @param lang str : the lang
  73. @classmethod
  74. def lang_is_valid(cls, lang):
  75. if not isinstance(lang, str):
  76. raise ValueError('Invalid value for lang. Str expected but %s found' % type(lang))
  77. return lang in cls.langs
  78. # @brief Get or set the default lang
  79. @classmethod
  80. def default_lang(cls, lang=None):
  81. if lang is None:
  82. return cls.__default_lang
  83. if not cls.lang_is_valid(lang):
  84. raise ValueError('lang "%s" is not valid"' % lang)
  85. cls.__default_lang = lang
  86. # @brief Return a mlstring loaded from a json string
  87. # @param json_str str : Json string
  88. @classmethod
  89. def from_json(cls, json_str):
  90. return MlString(json.loads(json_str))
  91. def __hash__(self):
  92. res = ''
  93. for lang in sorted(list(self.values.keys())):
  94. res = hash((res, lang, self.values[lang]))
  95. return res
  96. def d_hash(self):
  97. m = hashlib.md5()
  98. for lang in sorted(list(self.values.keys())):
  99. m.update(bytes(lang + ";" + self.values[lang], 'utf-8'))
  100. return int.from_bytes(m.digest(), byteorder='big')
  101. def __eq__(self, a):
  102. return hash(self) == hash(a)
  103. # @return The default langage translation or any available translation
  104. def __str__(self):
  105. if self.__default_lang in self.values:
  106. return self.values[self.__default_lang]
  107. else:
  108. return self.values[list(self.values.keys())[0]]
  109. def __repr__(self):
  110. return repr(self.values)