__init__.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import os
  2. import os.path as osp
  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. config = yaml.load(open(config_file))
  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. # default config
  30. config = get_default_config()
  31. if config_from_args is not None:
  32. update_dict(config, config_from_args,
  33. validate_item=validate_config_item)
  34. save_config_file = False
  35. if config_file is None:
  36. home = os.path.expanduser('~')
  37. config_file = os.path.join(home, '.labelmerc')
  38. save_config_file = True
  39. if os.path.exists(config_file):
  40. user_config = yaml.load(open(config_file)) or {}
  41. update_dict(config, user_config, validate_item=validate_config_item)
  42. if save_config_file:
  43. try:
  44. yaml.safe_dump(config, open(config_file, 'w'),
  45. default_flow_style=False)
  46. except Exception:
  47. logger.warn('Failed to save config: {}'.format(config_file))
  48. return config