loader.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. import json
  2. import pathlib
  3. from .phrasebook import phrasebook
  4. class loader:
  5. """ It load phrasebook from JSNO file.
  6. Methods
  7. -------
  8. load() -> phrasebook
  9. This load phrasebook from path in constructor.
  10. """
  11. def __init__(self, path: pathlib.Path) -> None:
  12. """ This create new phrasebook loader from path to phrasebook.
  13. Parameters
  14. ----------
  15. path : pathlib.Path
  16. Path to the phrasebook to load.
  17. """
  18. self.__path = path
  19. def load(self) -> object:
  20. """ This load phrasebook given in constructor
  21. Raises
  22. ------
  23. RuntimeError
  24. When phrasebook file does not exists.
  25. SyntaxError
  26. When phrasebook file has invalid syntax.
  27. Returns
  28. -------
  29. phrasebook
  30. Loaded phrasebook
  31. """
  32. if not self.__path.is_file():
  33. raise RuntimeError(
  34. "Phrasebook file \"" + \
  35. str(self.__path) + \
  36. "\" not exists."
  37. )
  38. with self.__path.open() as handle:
  39. try:
  40. return self.__parse(json.loads(handle.read()))
  41. except Exception as error:
  42. raise SyntaxError(
  43. "Phrasebook file \"" + \
  44. str(self.__path) + \
  45. "\" has invalid syntax.\n" + \
  46. str(error)
  47. )
  48. def __parse(self, content: dict) -> phrasebook:
  49. """ This parse phrasebook file to phrasebook object.
  50. Parameters
  51. ----------
  52. content : dict
  53. Content of the JSON phrasebook file.
  54. Returns
  55. -------
  56. phrasebook
  57. Loaded phrasebook file.
  58. """
  59. has_objects = (
  60. "objects" in content and \
  61. type(content["objects"]) is dict
  62. )
  63. has_phrases = (
  64. "phrases" in content and \
  65. type(content["phrases"]) is dict
  66. )
  67. is_nested = (has_objects or has_phrases)
  68. if is_nested:
  69. phrases = content["phrases"] if has_phrases else dict()
  70. objects = content["objects"] if has_objects else dict()
  71. return phrasebook(self.__parse_phrases(phrases), objects)
  72. return phrasebook(self.__parse_phrases(content))
  73. def __parse_phrases(self, content: dict) -> dict:
  74. """ This parse phrases from phrasebook file to dict.
  75. Parameters
  76. ----------
  77. content : dict
  78. Content of the phrases part from file to parse.
  79. Returns
  80. -------
  81. dict
  82. Parsed phrases from file.
  83. """
  84. result = dict()
  85. for phrase, translation in content.items():
  86. result[phrasebook.prepare(phrase)] = translation
  87. return result