YAMLLoader.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import logging
  2. import os
  3. import yaml
  4. logging.basicConfig()
  5. logger = logging.getLogger("kalliope")
  6. class YAMLFileNotFound(Exception):
  7. pass
  8. class YAMLLoader:
  9. def __init__(self):
  10. pass
  11. @classmethod
  12. def get_config(cls, yaml_file):
  13. """
  14. Load settings file
  15. :return: cfg : the configuration file
  16. """
  17. current_dir = os.path.dirname(os.path.abspath(__file__))
  18. logger.debug("Current dir: %s " % current_dir)
  19. root_dir = os.path.join(current_dir, "../../")
  20. root_dir = os.path.normpath(root_dir)
  21. logger.debug("Root dir: %s " % root_dir)
  22. cls.file_path_to_load = os.path.join(root_dir, yaml_file)
  23. logger.debug("File path to load: %s " % cls.file_path_to_load)
  24. if os.path.isfile(cls.file_path_to_load):
  25. inc_import = IncludeImport(cls.file_path_to_load)
  26. data = inc_import.get_data()
  27. return data
  28. else:
  29. raise YAMLFileNotFound("File %s not found" % cls.file_path_to_load)
  30. class IncludeImport(object):
  31. def __init__(self, file_path):
  32. """
  33. Load yaml file, with includes statement
  34. :param file_path: path to the yaml file to load
  35. """
  36. # get the parent dir. will be used in case of relative path
  37. parent_dir = os.path.normpath(file_path + os.sep + os.pardir)
  38. # load the yaml file
  39. self.data = yaml.load(open(file_path, 'r'))
  40. # add included brain
  41. if isinstance(self.data, list):
  42. for el in self.data:
  43. if "includes" in el:
  44. for inc in el["includes"]:
  45. # if the path is relative, we add the root path
  46. if not os.path.isabs(inc): # os.path.isabs returns True if the path is absolute
  47. # logger.debug("File path %s is relative, adding the root path" % inc)
  48. inc = os.path.join(parent_dir, inc)
  49. # logger.debug("New path: %s" % inc)
  50. self.update(yaml.load(open(inc)))
  51. def get_data(self):
  52. return self.data
  53. def update(self, data_to_add):
  54. # print "cur_data: %s" % self.data
  55. # print "data to add %s" % data_to_add
  56. # we add each synapse inside the extended brain into the main brain data
  57. if data_to_add is not None:
  58. for el in data_to_add:
  59. self.data.append(el)
  60. # print "final data: %s" % self.data