YAMLLoader.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import logging
  2. import os
  3. import yaml
  4. from core.Utils import Utils
  5. logging.basicConfig()
  6. logger = logging.getLogger("kalliope")
  7. class YAMLFileNotFound(Exception):
  8. pass
  9. class YAMLLoader:
  10. def __init__(self):
  11. pass
  12. @classmethod
  13. def get_config(cls, yaml_file):
  14. """
  15. Load settings file
  16. :return: cfg : the configuration file
  17. """
  18. current_dir = os.path.dirname(os.path.abspath(__file__))
  19. logger.debug("Current dir: %s " % current_dir)
  20. root_dir = os.path.join(current_dir, "../../")
  21. root_dir = os.path.normpath(root_dir)
  22. logger.debug("Root dir: %s " % root_dir)
  23. file_path_to_load = os.path.join(root_dir, yaml_file)
  24. logger.debug("File path to load: %s " % file_path_to_load)
  25. if os.path.isfile(yaml_file):
  26. # data = IncludeLoader(open(file_path_to_load, 'r')).get_data()
  27. # print Utils.print_yaml_nicely(data)
  28. data = IncludeImport(file_path_to_load).get_data()
  29. return data
  30. else:
  31. raise YAMLFileNotFound("File %s not found" % file_path_to_load)
  32. class IncludeLoader(yaml.Loader):
  33. def __init__(self, *args, **kwargs):
  34. super(IncludeLoader, self).__init__(*args, **kwargs)
  35. self.add_constructor('#include', self._include)
  36. if 'root' in kwargs:
  37. self.root = kwargs['root']
  38. elif isinstance(self.stream, file):
  39. self.root = os.path.dirname(self.stream.name)
  40. else:
  41. self.root = os.path.curdir
  42. def _include(self, loader, node):
  43. oldRoot = self.root
  44. filename = os.path.join(self.root, loader.construct_scalar(node))
  45. self.root = os.path.dirname(filename)
  46. data = yaml.load(open(filename, 'r'))
  47. self.root = oldRoot
  48. return data
  49. class IncludeImport(object):
  50. def __init__(self, file_path):
  51. """
  52. Load yaml file, with includes statement
  53. :param file_path: path to the yaml file to load
  54. """
  55. self.data = yaml.load(open(file_path, 'r'))
  56. # print "content: %s" % self.data
  57. if isinstance(self.data, list):
  58. for el in self.data:
  59. if "includes" in el:
  60. for inc in el["includes"]:
  61. self.update(yaml.load(open(inc)))
  62. def get_data(self):
  63. return self.data
  64. def update(self, data_to_add):
  65. # print "cur_data: %s" % self.data
  66. # print "data to add %s" % data_to_add
  67. # we add each synapse inside the extended brain into the main brain data
  68. for el in data_to_add:
  69. self.data.append(el)
  70. # print "final data: %s" % self.data