__init__.py 2.2 KB

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