__init__.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import os.path as osp
  2. import yaml
  3. from labelme import logger
  4. here = osp.dirname(osp.abspath(__file__))
  5. def update_dict(target_dict, new_dict, validate_item=None):
  6. for key, value in new_dict.items():
  7. if validate_item:
  8. validate_item(key, value)
  9. if key not in target_dict:
  10. logger.warn('Skipping unexpected key in config: {}'
  11. .format(key))
  12. continue
  13. if isinstance(target_dict[key], dict) and \
  14. isinstance(value, dict):
  15. update_dict(target_dict[key], value, validate_item=validate_item)
  16. else:
  17. target_dict[key] = value
  18. # -----------------------------------------------------------------------------
  19. def get_default_config():
  20. config_file = osp.join(here, 'default_config.yaml')
  21. with open(config_file) as f:
  22. config = yaml.load(f)
  23. return config
  24. def validate_config_item(key, value):
  25. if key == 'validate_label' and value not in [None, 'exact', 'instance']:
  26. raise ValueError('Unexpected value `{}` for key `{}`'
  27. .format(value, key))
  28. def get_config(config_from_args=None, config_file=None):
  29. # Configuration load order:
  30. #
  31. # 1. default config (lowest priority)
  32. # 2. config file passed by command line argument or ~/.labelmerc
  33. # 3. command line argument (highest priority)
  34. # 1. default config
  35. config = get_default_config()
  36. # save default config to ~/.labelmerc
  37. home = osp.expanduser('~')
  38. default_config_file = osp.join(home, '.labelmerc')
  39. if not osp.exists(default_config_file):
  40. try:
  41. with open(config_file, 'w') as f:
  42. yaml.safe_dump(config, f, default_flow_style=False)
  43. except Exception:
  44. logger.warn('Failed to save config: {}'.format(config_file))
  45. # 2. config from yaml file
  46. if config_file is None:
  47. config_file = default_config_file
  48. if osp.exists(config_file):
  49. with open(config_file) as f:
  50. user_config = yaml.load(f) or {}
  51. update_dict(config, user_config, validate_item=validate_config_item)
  52. # 3. command line argument
  53. if config_from_args is not None:
  54. update_dict(config, config_from_args,
  55. validate_item=validate_config_item)
  56. return config