__init__.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import os.path as osp
  2. import shutil
  3. import yaml
  4. from labelme.logger 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.safe_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(
  35. "Unexpected value for config key 'validate_label': {}"
  36. .format(value)
  37. )
  38. if key == 'labels' and value is not None and len(value) != len(set(value)):
  39. raise ValueError(
  40. "Duplicates are detected for config key 'labels': {}".format(value)
  41. )
  42. def get_config(config_from_args=None, config_file=None):
  43. # Configuration load order:
  44. #
  45. # 1. default config (lowest priority)
  46. # 2. config file passed by command line argument or ~/.labelmerc
  47. # 3. command line argument (highest priority)
  48. # 1. default config
  49. config = get_default_config()
  50. # 2. config from yaml file
  51. if config_file is not None and osp.exists(config_file):
  52. with open(config_file) as f:
  53. user_config = yaml.safe_load(f) or {}
  54. update_dict(config, user_config, validate_item=validate_config_item)
  55. # 3. command line argument
  56. if config_from_args is not None:
  57. update_dict(config, config_from_args,
  58. validate_item=validate_config_item)
  59. return config