Ejemplo n.º 1
0
 def find_relative_file(original_file, relative_import_path, level):
     cur_file = os.path.dirname(original_file)
     for _ in range(level - 1):
         cur_file = os.path.dirname(cur_file)
     cur_name = relative_import_path.lstrip(".")
     for part in cur_name.split("."):
         cur_file = os.path.join(cur_file, part)
     # NOTE: directory import is not handled. Because then it's unclear
     # if such import should produce python module or DictConfig. This can
     # be discussed further if needed.
     if not cur_file.endswith(".py"):
         cur_file += ".py"
     if not PathManager.isfile(cur_file):
         raise ImportError(
             f"Cannot import name {relative_import_path} from "
             f"{original_file}: {cur_file} has to exist.")
     return cur_file
Ejemplo n.º 2
0
    def merge_from_file(self,
                        cfg_filename: str,
                        allow_unsafe: bool = True) -> None:
        assert PathManager.isfile(
            cfg_filename), f"Config file '{cfg_filename}' does not exist!"
        loaded_cfg = self.load_yaml_with_base(cfg_filename,
                                              allow_unsafe=allow_unsafe)
        loaded_cfg = type(self)(loaded_cfg)

        # defaults.py needs to import CfgNode
        from .defaults import _C

        latest_ver = _C.VERSION
        assert (
            latest_ver == self.VERSION
        ), "CfgNode.merge_from_file is only allowed on a config object of latest version!"

        logger = logging.getLogger(__name__)

        loaded_ver = loaded_cfg.get("VERSION", None)
        if loaded_ver is None:
            from .compat import guess_version

            loaded_ver = guess_version(loaded_cfg, cfg_filename)
        assert loaded_ver <= self.VERSION, "Cannot merge a v{} config into a v{} config.".format(
            loaded_ver, self.VERSION)

        if loaded_ver == self.VERSION:
            self.merge_from_other_cfg(loaded_cfg)
        else:
            # compat.py needs to import CfgNode
            from .compat import upgrade_config, downgrade_config

            logger.warning(
                "Loading an old v{} config file '{}' by automatically upgrading to v{}. "
                "See docs/CHANGELOG.md for instructions to update your files.".
                format(loaded_ver, cfg_filename, self.VERSION))
            # To convert, first obtain a full config at an old version
            old_self = downgrade_config(self, to_version=loaded_ver)
            old_self.merge_from_other_cfg(loaded_cfg)
            new_config = upgrade_config(old_self)
            self.clear()
            self.update(new_config)