__init__.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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(default_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: {}'
  45. .format(default_config_file))
  46. # 2. config from yaml file
  47. if config_file is None:
  48. config_file = default_config_file
  49. if osp.exists(config_file):
  50. with open(config_file) as f:
  51. user_config = yaml.load(f) or {}
  52. update_dict(config, user_config, validate_item=validate_config_item)
  53. # 3. command line argument
  54. if config_from_args is not None:
  55. update_dict(config, config_from_args,
  56. validate_item=validate_config_item)
  57. return config