Skip to content

API documentation

Base Classes

Base class for building ML models that are easy to deploy and integrate.

MLModel

Bases: ABC

Base class for ML model prediction code.

Source code in ml_base/ml_model.py
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
class MLModel(ABC):
    """Base class for ML model prediction code."""

    def __repr__(self) -> str:
        """Return a string representing the model object."""
        return self.__class__.__name__

    @property
    @abstractmethod
    def display_name(self) -> str:
        """Abstract property that returns a display name for the model.

        Returns:
            str: The display name of the model.

        !!! note
            This is a name for the model that looks good in user interfaces.

        """
        raise NotImplementedError()  # pragma: no cover

    @property
    @abstractmethod
    def qualified_name(self) -> str:
        """Abstract property that returns the qualified name of the model.

        Returns:
            str: The qualified name of the model.

        !!! warning
            A qualified name is an unambiguous identifier for the model.

        """
        raise NotImplementedError()  # pragma: no cover

    @property
    @abstractmethod
    def description(self) -> str:
        """Abstract property that returns a description of the model.

        Returns:
            str: The description of the model.

        """
        raise NotImplementedError()  # pragma: no cover

    @property
    @abstractmethod
    def version(self) -> str:
        """Abstract property that returns the model's version as a string.

        Returns:
            str: The version of the model.

        """
        raise NotImplementedError()  # pragma: no cover

    @property
    @abstractmethod
    def input_schema(self) -> BaseModel:
        """Property that returns the schema that is accepted by the predict() method.

        Returns:
            pydantic.BaseModel: The input schema of the model.

        !!! note
            This property must return a subtype of pydantic.BaseModel.

        """
        raise NotImplementedError()  # pragma: no cover

    @property
    @abstractmethod
    def output_schema(self) -> BaseModel:
        """Property returns the schema that is returned by the predict() method.

        Returns:
            pydantic.BaseModel: The output schema of the model.

        !!! note
            This property must return a subtype of pydantic.BaseModel.

        """
        raise NotImplementedError()  # pragma: no cover

    @abstractmethod
    def __init__(self) -> None:
        """Create an MLModel instance by adding any deserialization and initialization code for the model."""
        raise NotImplementedError()  # pragma: no cover

    @abstractmethod
    def predict(self, data: BaseModel) -> BaseModel:
        """Prediction with the model.

        Args:
            data: data used by the model for making a prediction

        Returns:
            object: can be any python type

        """
        raise NotImplementedError()  # pragma: no cover

description: str property abstractmethod

Abstract property that returns a description of the model.

Returns:

Name Type Description
str str

The description of the model.

display_name: str property abstractmethod

Abstract property that returns a display name for the model.

Returns:

Name Type Description
str str

The display name of the model.

Note

This is a name for the model that looks good in user interfaces.

input_schema: BaseModel property abstractmethod

Property that returns the schema that is accepted by the predict() method.

Returns:

Type Description
BaseModel

pydantic.BaseModel: The input schema of the model.

Note

This property must return a subtype of pydantic.BaseModel.

output_schema: BaseModel property abstractmethod

Property returns the schema that is returned by the predict() method.

Returns:

Type Description
BaseModel

pydantic.BaseModel: The output schema of the model.

Note

This property must return a subtype of pydantic.BaseModel.

qualified_name: str property abstractmethod

Abstract property that returns the qualified name of the model.

Returns:

Name Type Description
str str

The qualified name of the model.

Warning

A qualified name is an unambiguous identifier for the model.

version: str property abstractmethod

Abstract property that returns the model's version as a string.

Returns:

Name Type Description
str str

The version of the model.

__init__() abstractmethod

Create an MLModel instance by adding any deserialization and initialization code for the model.

Source code in ml_base/ml_model.py
91
92
93
94
@abstractmethod
def __init__(self) -> None:
    """Create an MLModel instance by adding any deserialization and initialization code for the model."""
    raise NotImplementedError()  # pragma: no cover

__repr__()

Return a string representing the model object.

Source code in ml_base/ml_model.py
 9
10
11
def __repr__(self) -> str:
    """Return a string representing the model object."""
    return self.__class__.__name__

predict(data) abstractmethod

Prediction with the model.

Parameters:

Name Type Description Default
data BaseModel

data used by the model for making a prediction

required

Returns:

Name Type Description
object BaseModel

can be any python type

Source code in ml_base/ml_model.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
@abstractmethod
def predict(self, data: BaseModel) -> BaseModel:
    """Prediction with the model.

    Args:
        data: data used by the model for making a prediction

    Returns:
        object: can be any python type

    """
    raise NotImplementedError()  # pragma: no cover

MLModelException

Bases: Exception

Exception base class used to raise exceptions within MLModel derived classes.

Source code in ml_base/ml_model.py
110
111
112
113
114
115
class MLModelException(Exception):
    """Exception base class used to raise exceptions within MLModel derived classes."""

    def __init__(self, *args: tuple) -> None:
        """Initialize MLModelException instance."""
        Exception.__init__(self, *args)

__init__(*args)

Initialize MLModelException instance.

Source code in ml_base/ml_model.py
113
114
115
def __init__(self, *args: tuple) -> None:
    """Initialize MLModelException instance."""
    Exception.__init__(self, *args)

MLModelSchemaValidationException

Bases: MLModelException

Exception type used to raise schema validation exceptions within MLModel derived classes.

Source code in ml_base/ml_model.py
118
119
120
121
122
123
class MLModelSchemaValidationException(MLModelException):
    """Exception type used to raise schema validation exceptions within MLModel derived classes."""

    def __init__(self, *args: tuple) -> None:
        """Initialize MLModelSchemaValidationException instance."""
        MLModelException.__init__(self, *args)

__init__(*args)

Initialize MLModelSchemaValidationException instance.

Source code in ml_base/ml_model.py
121
122
123
def __init__(self, *args: tuple) -> None:
    """Initialize MLModelSchemaValidationException instance."""
    MLModelException.__init__(self, *args)

Base class for building decorators for MLModel objects.

MLModelDecorator

Bases: MLModel

Base class for ML model decorator code.

Note

The default behavior of the MLModelDecorator base class is to do nothing and to forward the method call to the model that is is wrapping. Any subtypes of MLModelDecorator that would like to add on to the behavior of the model needs to override the default implementations in the MLModelDecorator base class.

Source code in ml_base/decorator.py
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
class MLModelDecorator(MLModel):
    """Base class for ML model decorator code.

    !!! note
        The default behavior of the MLModelDecorator base class is to do nothing and to forward the method call to
        the model that is is wrapping. Any subtypes of MLModelDecorator that would like to add on to the behavior
        of the model needs to override the default implementations in the MLModelDecorator base class.

    """

    _decorator_attributes = ["_model", "_configuration"]

    def __init__(self, model: Optional[MLModel] = None, **kwargs: dict) -> None:
        """Initialize MLModelDecorator instance.

        !!! note
            The MLModel parameter is optional and does not need to be provided at initialization of the decorator
            instance.

        !!! note
            This method receives the model instance and stores the reference.

        """
        if model is not None and not isinstance(model, MLModel):
            raise ValueError("Only objects of type MLModel can be wrapped with MLModelDecorator instances.")

        self.__dict__["_model"] = model
        self.__dict__["_configuration"] = kwargs

    def __repr__(self) -> str:
        """Return a string describing the decorator and the model that it is decorating."""
        return "{}({})".format(self.__class__.__name__, str(self.__dict__["_model"]))

    def set_model(self, model: MLModel) -> "MLModelDecorator":
        """Set a model in the decorator instance."""
        if not isinstance(model, MLModel):
            raise ValueError("Only objects of type MLModel can be wrapped with MLModelDecorator instances.")

        self.__dict__["_model"] = model
        return self

    def __getattr__(self, name: str) -> Any:
        """Get an attribute."""
        if name in MLModelDecorator._decorator_attributes:
            return self.__dict__[name]
        else:
            return getattr(self.__dict__["_model"], name)

    def __setattr__(self, name: str, value: Any) -> None:
        """Set an attribute."""
        if name in MLModelDecorator._decorator_attributes:
            setattr(self, name, value)
        else:
            setattr(self.__dict__["_model"], name, value)

    def __delattr__(self, name: str) -> None:
        """Delete an attribute."""
        delattr(self.__dict__["_model"], name)

    @property
    def display_name(self) -> str:
        """Property that returns a display name for the model.

        !!! note
            Unless this method is overridden, the implementation just returns the display_name property of the
            model that is being decorated.

        """
        return getattr(self, "_model").display_name

    @property
    def qualified_name(self) -> str:
        """Property that returns the qualified name of the model.

        !!! note
            Unless this method is overridden, the implementation just returns the qualified_name property of the
            model that is being decorated.

        """
        return getattr(self, "_model").qualified_name

    @property
    def description(self) -> str:
        """Property that returns a description of the model.

        !!! note
            Unless this method is overridden, the implementation just returns the description property of the
            model that is being decorated.

        """
        return getattr(self, "_model").description

    @property
    def version(self) -> str:
        """Property that returns the model's version as a string.

        !!! note
            Unless this method is overridden, the implementation just returns the version property of the
            model that is being decorated.


        """
        return getattr(self, "_model").version

    @property
    def input_schema(self) -> BaseModel:
        """Property that returns the schema that is accepted by the predict() method.

        !!! note
            Unless this method is overridden, the implementation just returns the input_schema property of the
            model that is being decorated.

        """
        return getattr(self, "_model").input_schema

    @property
    def output_schema(self) -> BaseModel:
        """Property returns the schema that is returned by the predict() method.

        !!! note
            Unless this method is overridden, the implementation just returns the output_schema property of the
            model that is being decorated.

        """
        return getattr(self, "_model").output_schema

    def predict(self, data: BaseModel) -> BaseModel:
        """Predict with the model.

        Params:
            data: Data used by the model for making a prediction.

        Returns:
            python object -- can be any python type

        !!! note
            Unless this method is overridden, the implementation just calls the predict method of the
            model that is being decorated and returns the result.

        """
        return getattr(self, "_model").predict(data=data)

description: str property

Property that returns a description of the model.

Note

Unless this method is overridden, the implementation just returns the description property of the model that is being decorated.

display_name: str property

Property that returns a display name for the model.

Note

Unless this method is overridden, the implementation just returns the display_name property of the model that is being decorated.

input_schema: BaseModel property

Property that returns the schema that is accepted by the predict() method.

Note

Unless this method is overridden, the implementation just returns the input_schema property of the model that is being decorated.

output_schema: BaseModel property

Property returns the schema that is returned by the predict() method.

Note

Unless this method is overridden, the implementation just returns the output_schema property of the model that is being decorated.

qualified_name: str property

Property that returns the qualified name of the model.

Note

Unless this method is overridden, the implementation just returns the qualified_name property of the model that is being decorated.

version: str property

Property that returns the model's version as a string.

Note

Unless this method is overridden, the implementation just returns the version property of the model that is being decorated.

__delattr__(name)

Delete an attribute.

Source code in ml_base/decorator.py
62
63
64
def __delattr__(self, name: str) -> None:
    """Delete an attribute."""
    delattr(self.__dict__["_model"], name)

__getattr__(name)

Get an attribute.

Source code in ml_base/decorator.py
48
49
50
51
52
53
def __getattr__(self, name: str) -> Any:
    """Get an attribute."""
    if name in MLModelDecorator._decorator_attributes:
        return self.__dict__[name]
    else:
        return getattr(self.__dict__["_model"], name)

__init__(model=None, **kwargs)

Initialize MLModelDecorator instance.

Note

The MLModel parameter is optional and does not need to be provided at initialization of the decorator instance.

Note

This method receives the model instance and stores the reference.

Source code in ml_base/decorator.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def __init__(self, model: Optional[MLModel] = None, **kwargs: dict) -> None:
    """Initialize MLModelDecorator instance.

    !!! note
        The MLModel parameter is optional and does not need to be provided at initialization of the decorator
        instance.

    !!! note
        This method receives the model instance and stores the reference.

    """
    if model is not None and not isinstance(model, MLModel):
        raise ValueError("Only objects of type MLModel can be wrapped with MLModelDecorator instances.")

    self.__dict__["_model"] = model
    self.__dict__["_configuration"] = kwargs

__repr__()

Return a string describing the decorator and the model that it is decorating.

Source code in ml_base/decorator.py
36
37
38
def __repr__(self) -> str:
    """Return a string describing the decorator and the model that it is decorating."""
    return "{}({})".format(self.__class__.__name__, str(self.__dict__["_model"]))

__setattr__(name, value)

Set an attribute.

Source code in ml_base/decorator.py
55
56
57
58
59
60
def __setattr__(self, name: str, value: Any) -> None:
    """Set an attribute."""
    if name in MLModelDecorator._decorator_attributes:
        setattr(self, name, value)
    else:
        setattr(self.__dict__["_model"], name, value)

predict(data)

Predict with the model.

Parameters:

Name Type Description Default
data BaseModel

Data used by the model for making a prediction.

required

Returns:

Type Description
BaseModel

python object -- can be any python type

Note

Unless this method is overridden, the implementation just calls the predict method of the model that is being decorated and returns the result.

Source code in ml_base/decorator.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def predict(self, data: BaseModel) -> BaseModel:
    """Predict with the model.

    Params:
        data: Data used by the model for making a prediction.

    Returns:
        python object -- can be any python type

    !!! note
        Unless this method is overridden, the implementation just calls the predict method of the
        model that is being decorated and returns the result.

    """
    return getattr(self, "_model").predict(data=data)

set_model(model)

Set a model in the decorator instance.

Source code in ml_base/decorator.py
40
41
42
43
44
45
46
def set_model(self, model: MLModel) -> "MLModelDecorator":
    """Set a model in the decorator instance."""
    if not isinstance(model, MLModel):
        raise ValueError("Only objects of type MLModel can be wrapped with MLModelDecorator instances.")

    self.__dict__["_model"] = model
    return self

Utilities

Bases: object

Singleton class that instantiates and manages model objects.

Source code in ml_base/utilities/model_manager.py
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
class ModelManager(object):
    """Singleton class that instantiates and manages model objects."""

    _lock = Lock()

    def __new__(cls) -> "ModelManager":  # noqa: D102
        """Create and return a new ModelManager instance, after instance is first created it will always be returned."""
        if not hasattr(cls, "_instance"):
            with cls._lock:
                cls._instance = super(ModelManager, cls).__new__(cls)
                cls._instance._is_initialized = False
        return cls._instance

    def __init__(self) -> None:
        """Construct ModelManager object."""
        if self._is_initialized is False:  # pytype: disable=attribute-error
            self._models = []
            self._is_initialized = True

    @classmethod
    def clear_instance(cls) -> None:
        """Clear singleton instance from class."""
        del cls._instance

    def load_model(self, class_path: str) -> None:
        """Import and instantiate an MLModel object from a class path.

        Args:
            class_path: Class path to the model's MLModel class.

        Raises:
            ValueError: Raised if the model is not a subtype of MLModel, or if a model with the same qualified name
                      is already loaded in the ModelManager.

        """
        # splitting the class_path into module path and class name
        module_path = ".".join(class_path.split(".")[:-1])
        class_name = class_path.split(".")[-1]

        # importing the model class
        model_module = importlib.import_module(module_path)
        model_class = getattr(model_module, class_name)

        # instantiating the model object from the class
        model_object = model_class()

        self.add_model(model_object)

    def add_model(self, model: MLModel) -> None:
        """Add a model to the ModelManager.

        Args:
            model: instance of MLModel

        """
        if not isinstance(model, MLModel):
            raise ValueError("ModelManager instance can only hold references to objects of type MLModel.")

        if model.qualified_name in [model.qualified_name for model in self._models]:
            raise ValueError("A model with the same qualified name is already in the ModelManager singleton.")

        # saving the model reference to the models list
        self._models.append(model)

    def remove_model(self, qualified_name: str) -> None:
        """Remove an MLModel object from the ModelManager singleton.

        Args:
            qualified_name: The qualified name of the model to be returned.

        Raises:
            ValueError: Raised if a model with the qualified name can't be found in the ModelManager singleton.

        """
        # searching the list of model objects to find the one with the right qualified name
        model = next((model for model in self._models if model.qualified_name == qualified_name), None)

        if model is None:
            raise ValueError("Instance of model '{}' not found in ModelManager.".format(qualified_name))
        else:
            self._models.remove(model)

    def get_models(self) -> List[dict]:
        """Get a list of models in the model manager singleton.

        Returns:
            List of dictionaries containing information about the model instances in the ModelManager singleton.

        !!! note
            The dictionaries in the list returned by this method contain these keys:

            - display_name
            - qualified_name
            - description
            - version

        """
        model_objects = [{"display_name": model.display_name,
                          "qualified_name": model.qualified_name,
                          "description": model.description,
                          "version": model.version} for model in self._models]
        return model_objects

    def get_model_metadata(self, qualified_name: str) -> dict:
        """Get model metadata by qualified name.

        Args:
            qualified_name: Qualified name of the model for which to get metadata

        Returns:
            Dictionary containing information about a model in the ModelManager singleton.

        !!! note
            The dictionaries in the list returned by this method contain these keys:

            - display_name
            - qualified_name
            - description
            - version
            - input_schema
            - output_schema

        """
        # searching the list of model objects to find the one with the right qualified name
        model = next((model for model in self._models if model.qualified_name == qualified_name), None)

        if model is None:
            raise ValueError("Instance of model '{}' not found in ModelManager.".format(qualified_name))
        else:
            return {
                "display_name": model.display_name,
                "qualified_name": model.qualified_name,
                "description": model.description,
                "version": model.version,
                "input_schema": model.input_schema.schema(),
                "output_schema": model.output_schema.schema()
            }

    def get_model(self, qualified_name: str) -> MLModel:
        """Get a model object by qualified name.

        Args:
            qualified_name: The qualified name of the model to be returned.

        Returns:
            Model object

        Raises:
            ValueError: Raised if a model with the qualified name can't be found in the ModelManager singleton.

        """
        # searching the list of model objects to find the one with the right qualified name
        model = next((model for model in self._models if model.qualified_name == qualified_name), None)

        if model is None:
            raise ValueError("Instance of model '{}' not found in ModelManager.".format(qualified_name))
        else:
            return model

    def add_decorator(self, qualified_name: str, decorator: MLModelDecorator) -> None:
        """Add a decorator to a model object by qualified name.

        Args:
            qualified_name: The qualified name of the model to add decorator to.
            decorator: MLModelDecorator instance to apply to model instance.

        Returns:
            None

        Raises:
            ValueError: Raised if a model with the qualified name can't be found in the ModelManager singleton.

        """
        # searching the list of model objects to find the one with the right qualified name
        model = next((model for model in self._models if model.qualified_name == qualified_name), None)

        if model is None:
            raise ValueError("Instance of model '{}' not found in ModelManager.".format(qualified_name))

        # removing old model reference
        self.remove_model(qualified_name)

        # adding the decorator to the model object
        decorated_model = decorator.set_model(model)

        # adding the decorated model to the collection
        self.add_model(decorated_model)

__init__()

Construct ModelManager object.

Source code in ml_base/utilities/model_manager.py
22
23
24
25
26
def __init__(self) -> None:
    """Construct ModelManager object."""
    if self._is_initialized is False:  # pytype: disable=attribute-error
        self._models = []
        self._is_initialized = True

__new__()

Create and return a new ModelManager instance, after instance is first created it will always be returned.

Source code in ml_base/utilities/model_manager.py
14
15
16
17
18
19
20
def __new__(cls) -> "ModelManager":  # noqa: D102
    """Create and return a new ModelManager instance, after instance is first created it will always be returned."""
    if not hasattr(cls, "_instance"):
        with cls._lock:
            cls._instance = super(ModelManager, cls).__new__(cls)
            cls._instance._is_initialized = False
    return cls._instance

add_decorator(qualified_name, decorator)

Add a decorator to a model object by qualified name.

Parameters:

Name Type Description Default
qualified_name str

The qualified name of the model to add decorator to.

required
decorator MLModelDecorator

MLModelDecorator instance to apply to model instance.

required

Returns:

Type Description
None

None

Raises:

Type Description
ValueError

Raised if a model with the qualified name can't be found in the ModelManager singleton.

Source code in ml_base/utilities/model_manager.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def add_decorator(self, qualified_name: str, decorator: MLModelDecorator) -> None:
    """Add a decorator to a model object by qualified name.

    Args:
        qualified_name: The qualified name of the model to add decorator to.
        decorator: MLModelDecorator instance to apply to model instance.

    Returns:
        None

    Raises:
        ValueError: Raised if a model with the qualified name can't be found in the ModelManager singleton.

    """
    # searching the list of model objects to find the one with the right qualified name
    model = next((model for model in self._models if model.qualified_name == qualified_name), None)

    if model is None:
        raise ValueError("Instance of model '{}' not found in ModelManager.".format(qualified_name))

    # removing old model reference
    self.remove_model(qualified_name)

    # adding the decorator to the model object
    decorated_model = decorator.set_model(model)

    # adding the decorated model to the collection
    self.add_model(decorated_model)

add_model(model)

Add a model to the ModelManager.

Parameters:

Name Type Description Default
model MLModel

instance of MLModel

required
Source code in ml_base/utilities/model_manager.py
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def add_model(self, model: MLModel) -> None:
    """Add a model to the ModelManager.

    Args:
        model: instance of MLModel

    """
    if not isinstance(model, MLModel):
        raise ValueError("ModelManager instance can only hold references to objects of type MLModel.")

    if model.qualified_name in [model.qualified_name for model in self._models]:
        raise ValueError("A model with the same qualified name is already in the ModelManager singleton.")

    # saving the model reference to the models list
    self._models.append(model)

clear_instance() classmethod

Clear singleton instance from class.

Source code in ml_base/utilities/model_manager.py
28
29
30
31
@classmethod
def clear_instance(cls) -> None:
    """Clear singleton instance from class."""
    del cls._instance

get_model(qualified_name)

Get a model object by qualified name.

Parameters:

Name Type Description Default
qualified_name str

The qualified name of the model to be returned.

required

Returns:

Type Description
MLModel

Model object

Raises:

Type Description
ValueError

Raised if a model with the qualified name can't be found in the ModelManager singleton.

Source code in ml_base/utilities/model_manager.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def get_model(self, qualified_name: str) -> MLModel:
    """Get a model object by qualified name.

    Args:
        qualified_name: The qualified name of the model to be returned.

    Returns:
        Model object

    Raises:
        ValueError: Raised if a model with the qualified name can't be found in the ModelManager singleton.

    """
    # searching the list of model objects to find the one with the right qualified name
    model = next((model for model in self._models if model.qualified_name == qualified_name), None)

    if model is None:
        raise ValueError("Instance of model '{}' not found in ModelManager.".format(qualified_name))
    else:
        return model

get_model_metadata(qualified_name)

Get model metadata by qualified name.

Parameters:

Name Type Description Default
qualified_name str

Qualified name of the model for which to get metadata

required

Returns:

Type Description
dict

Dictionary containing information about a model in the ModelManager singleton.

Note

The dictionaries in the list returned by this method contain these keys:

  • display_name
  • qualified_name
  • description
  • version
  • input_schema
  • output_schema
Source code in ml_base/utilities/model_manager.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def get_model_metadata(self, qualified_name: str) -> dict:
    """Get model metadata by qualified name.

    Args:
        qualified_name: Qualified name of the model for which to get metadata

    Returns:
        Dictionary containing information about a model in the ModelManager singleton.

    !!! note
        The dictionaries in the list returned by this method contain these keys:

        - display_name
        - qualified_name
        - description
        - version
        - input_schema
        - output_schema

    """
    # searching the list of model objects to find the one with the right qualified name
    model = next((model for model in self._models if model.qualified_name == qualified_name), None)

    if model is None:
        raise ValueError("Instance of model '{}' not found in ModelManager.".format(qualified_name))
    else:
        return {
            "display_name": model.display_name,
            "qualified_name": model.qualified_name,
            "description": model.description,
            "version": model.version,
            "input_schema": model.input_schema.schema(),
            "output_schema": model.output_schema.schema()
        }

get_models()

Get a list of models in the model manager singleton.

Returns:

Type Description
List[dict]

List of dictionaries containing information about the model instances in the ModelManager singleton.

Note

The dictionaries in the list returned by this method contain these keys:

  • display_name
  • qualified_name
  • description
  • version
Source code in ml_base/utilities/model_manager.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def get_models(self) -> List[dict]:
    """Get a list of models in the model manager singleton.

    Returns:
        List of dictionaries containing information about the model instances in the ModelManager singleton.

    !!! note
        The dictionaries in the list returned by this method contain these keys:

        - display_name
        - qualified_name
        - description
        - version

    """
    model_objects = [{"display_name": model.display_name,
                      "qualified_name": model.qualified_name,
                      "description": model.description,
                      "version": model.version} for model in self._models]
    return model_objects

load_model(class_path)

Import and instantiate an MLModel object from a class path.

Parameters:

Name Type Description Default
class_path str

Class path to the model's MLModel class.

required

Raises:

Type Description
ValueError

Raised if the model is not a subtype of MLModel, or if a model with the same qualified name is already loaded in the ModelManager.

Source code in ml_base/utilities/model_manager.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def load_model(self, class_path: str) -> None:
    """Import and instantiate an MLModel object from a class path.

    Args:
        class_path: Class path to the model's MLModel class.

    Raises:
        ValueError: Raised if the model is not a subtype of MLModel, or if a model with the same qualified name
                  is already loaded in the ModelManager.

    """
    # splitting the class_path into module path and class name
    module_path = ".".join(class_path.split(".")[:-1])
    class_name = class_path.split(".")[-1]

    # importing the model class
    model_module = importlib.import_module(module_path)
    model_class = getattr(model_module, class_name)

    # instantiating the model object from the class
    model_object = model_class()

    self.add_model(model_object)

remove_model(qualified_name)

Remove an MLModel object from the ModelManager singleton.

Parameters:

Name Type Description Default
qualified_name str

The qualified name of the model to be returned.

required

Raises:

Type Description
ValueError

Raised if a model with the qualified name can't be found in the ModelManager singleton.

Source code in ml_base/utilities/model_manager.py
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def remove_model(self, qualified_name: str) -> None:
    """Remove an MLModel object from the ModelManager singleton.

    Args:
        qualified_name: The qualified name of the model to be returned.

    Raises:
        ValueError: Raised if a model with the qualified name can't be found in the ModelManager singleton.

    """
    # searching the list of model objects to find the one with the right qualified name
    model = next((model for model in self._models if model.qualified_name == qualified_name), None)

    if model is None:
        raise ValueError("Instance of model '{}' not found in ModelManager.".format(qualified_name))
    else:
        self._models.remove(model)