Пример #1
0
    def from_file(filepath: str = None, parent_filepath: str = None):
        """Load a Collection from a file.

        Args:
            filepath (str): File from which to load the collection
            parent_filepath (str): Parent filename (if file is imported from another file)
        """
        fullpath = full_filepath(filepath, parent_filepath)
        raw, md_path = load_any_file(filepath, parent_filepath)
        d = raw
        if isinstance(raw, dict):
            lc_keys = lowercase_keys(raw)
            if "collection" in lc_keys:
                d = raw[lc_keys["collection"]]
            elif "collections" in lc_keys:
                # called Collection.from_file() on a collection list, fallback to CollectionList
                d = raw[lc_keys["collections"]]
                if isinstance(d, list):
                    from modelindex.models.CollectionList import CollectionList
                    return CollectionList(d, fullpath)

            return Collection.from_dict(d, fullpath, md_path)
        else:
            raise ValueError(f"Expected a collection dict, but got "
                             f"something else in file '{fullpath}'")
Пример #2
0
    def from_file(filepath: str = None, parent_filepath: str = None):
        """Load a Metadata from a file.

        Args:
            filepath (str): File from which to load the metadata
            parent_filepath (str): Parent filename (if file is imported from another file)
        """
        fullpath = full_filepath(filepath, parent_filepath)
        raw, md_path = load_any_file(filepath, parent_filepath)

        d = raw
        if isinstance(d, dict):
            return Metadata.from_dict(d, fullpath)

        raise ValueError(f"Expected a dictionary with metadata, "
                         f"but got something else in file at"
                         f"'{fullpath}'")
Пример #3
0
def load(path: str = "model-index.yml"):
    """Load the model index.

       Args:
            path (str): Path to the file to load, or a directory containing model-index.yml.

       Returns:
            ModelIndex instance that has been loaded from the disk.
    """

    if os.path.isdir(path):
        new_path = os.path.join(path, MODEL_INDEX_ROOT_FILE)
        # if model-index.yml doesn't exist try model-index.yaml
        if not os.path.exists(new_path):
            yaml_ext = os.path.join(path, "model-index.yaml")
            if os.path.exists(yaml_ext):
                new_path = yaml_ext
        path = new_path

    raw, md_path = load_any_file(path)

    # make sure the input is a dict
    if not isinstance(raw, dict) and not isinstance(raw, list):
        raise ValueError(
            f"Expected the file '{path}' to contain a dict or a list, but it doesn't."
        )

    # Guess the type based on dict entries
    obj = None
    if isinstance(raw, dict) and raw:
        obj = load_based_on_dict_field_guess(raw, path, md_path, is_root=True)
    elif isinstance(raw, list) and raw:
        obj_guess = load_based_on_dict_field_guess(raw[0],
                                                   path,
                                                   md_path,
                                                   is_root=True)
        if isinstance(obj_guess, Result):
            return ResultList(raw, path)
        elif isinstance(obj_guess, Model):
            return ModelList(raw, path)

    if obj is None:
        raise ValueError(f"Unrecognized format in file '{path}'")

    return obj
Пример #4
0
    def from_file(filepath: str = None, parent_filepath: str = None):
        """Load a Library from a file.

        Args:
            filepath (str): File from which to load the library
            parent_filepath (str): Parent filename (if file is imported from another file)
        """
        fullpath = full_filepath(filepath, parent_filepath)
        raw, md_path = load_any_file(filepath, parent_filepath)
        d = raw
        if isinstance(raw, dict):
            lc_keys = lowercase_keys(raw)
            if "library" in lc_keys:
                d = raw[lc_keys["library"]]

            return Library.from_dict(d, fullpath, md_path)
        else:
            raise ValueError(f"Expected a library dict, but got "
                             f"something else in file '{fullpath}'")
Пример #5
0
    def from_file(filepath: str = None, parent_filepath: str = None):
        """Load a ModelList from a file.

        Args:
            filepath (str): File from which to load the list of models.
            parent_filepath (str): Parent filename (if file is imported from another file)

        """
        fullpath = full_filepath(filepath, parent_filepath)
        raw, md_path = load_any_file(filepath, parent_filepath)
        d = raw

        if isinstance(d, list):
            return ModelList(d, fullpath)
        elif isinstance(d, dict):
            lc_keys = lowercase_keys(raw)
            if "models" in lc_keys:
                return ModelList(d[lc_keys["models"]], fullpath)

        raise ValueError(f"Expected a list of models, but got something else"
                         f"in file {fullpath}")
Пример #6
0
    def __init__(self,
                 data: dict = None,
                 filepath: str = None,
                 _path_to_readme: str = None,
                 is_root: bool = False,
                 ):
        """
        Args:
            data (dict): The root model index as a dictionary
            filepath (str): The path from which it was loaded
            _path_to_readme (str): The path to the readme file (if loaded from there)
            is_root (bool): If this is the root ModelIndex instance for the whole project
        """

        check_errors = OrderedSet()

        if data is None:
            data = {}

        d = {
            "Models": ModelList(_filepath=filepath),
            "Collections": CollectionList(_filepath=filepath),
            "Library": None,
        }
        lc_keys = lowercase_keys(data)
        if "models" in lc_keys:
            models = data[lc_keys["models"]]
            # Syntax: Models: <path to file(s)>
            if models is not None and isinstance(models, str):
                models_list = []
                for model_file in expand_wildcard_path(models, filepath):
                    try:
                        models_list.append(ModelList.from_file(model_file, filepath))
                    except (IOError, ValueError) as e:
                        check_errors.add(str(e))
                models = merge_lists_data(models_list)
            # Syntax: Models: list[ model dict ]
            elif models is not None and not isinstance(models, ModelList):
                models = ModelList(models, filepath, _path_to_readme)

            d["Models"] = models

        if "collections" in lc_keys:
            collections = data[lc_keys["collections"]]
            # Syntax: Collections: <path to file(s)>
            if collections is not None and isinstance(collections, str):
                collections_list = []
                for model_file in expand_wildcard_path(collections, filepath):
                    try:
                        collections_list.append(CollectionList.from_file(model_file, filepath))
                    except (IOError, ValueError) as e:
                        check_errors.add(str(e))
                collections = merge_lists_data(collections_list)
            # Syntax: Collections: list[ model dict ]
            elif collections is not None and not isinstance(collections, CollectionList):
                collections = CollectionList(collections, filepath, _path_to_readme)

            d["Collections"] = collections

        if "library" in lc_keys:
            lib = data[lc_keys["library"]]
            if isinstance(lib, dict):
                d["Library"] = Library.from_dict(lib, filepath)
            elif isinstance(lib, str):
                d["Library"] = Library.from_file(lib, filepath)
            else:
                check_errors.add("Mis-formatted `Library` entry: expected a dict or a filepath but got something else.")

        if "import" in lc_keys:
            imp = data[lc_keys["import"]]

            if not isinstance(imp, list):
                imp = list(imp)

            for import_file in imp:
                try:
                    for relpath in expand_wildcard_path(import_file, filepath):
                        raw, md_name = load_any_file(relpath, filepath)
                        fullpath = full_filepath(relpath, filepath)
                        mi = ModelIndex.from_dict(raw, fullpath, md_name)
                        if mi.models:
                            for model in mi.models:
                                d["Models"].add(model)

                        if mi.collections:
                            for col in mi.collections:
                                d["Collections"].add(col)

                        if mi.library:
                            d["Library"] = mi.library
                except (IOError, ValueError) as e:
                    check_errors.add(str(e))

        super().__init__(
            data=d,
            filepath=filepath,
            check_errors=check_errors,
        )

        self.lc_keys = lowercase_keys(data)
        self.is_root = is_root
        if is_root:
            self.build_models_with_collections()