|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""PyMilo Chain Module.""" |
| 3 | + |
| 4 | +from traceback import format_exc |
| 5 | +from abc import ABC, abstractmethod |
| 6 | + |
| 7 | +from ..utils.util import get_sklearn_type |
| 8 | +from ..transporters.transporter import Command |
| 9 | +from ..exceptions.serialize_exception import PymiloSerializationException, SerializationErrorTypes |
| 10 | +from ..exceptions.deserialize_exception import PymiloDeserializationException, DeserializationErrorTypes |
| 11 | + |
| 12 | + |
| 13 | +class Chain(ABC): |
| 14 | + """ |
| 15 | + Chain Interface. |
| 16 | +
|
| 17 | + Each Chain serializes/deserializes the given model. |
| 18 | + """ |
| 19 | + |
| 20 | + @abstractmethod |
| 21 | + def is_supported(self, model): |
| 22 | + """ |
| 23 | + Check if the given model is a sklearn's ML model supported by this chain. |
| 24 | +
|
| 25 | + :param model: a string name of an ML model or a sklearn object of it |
| 26 | + :type model: any object |
| 27 | + :return: check result as bool |
| 28 | + """ |
| 29 | + |
| 30 | + @abstractmethod |
| 31 | + def transport(self, request, command, is_inner_model=False): |
| 32 | + """ |
| 33 | + Return the transported (serialized or deserialized) model. |
| 34 | +
|
| 35 | + :param request: given ML model to be transported |
| 36 | + :type request: any object |
| 37 | + :param command: command to specify whether the request should be serialized or deserialized |
| 38 | + :type command: transporter.Command |
| 39 | + :param is_inner_model: determines whether it is an inner model of a super ML model |
| 40 | + :type is_inner_model: boolean |
| 41 | + :return: the transported request as a json string or sklearn ML model |
| 42 | + """ |
| 43 | + |
| 44 | + @abstractmethod |
| 45 | + def serialize(self, model): |
| 46 | + """ |
| 47 | + Return the serialized json string of the given model. |
| 48 | +
|
| 49 | + :param model: given ML model to be get serialized |
| 50 | + :type model: sklearn ML model |
| 51 | + :return: the serialized json string of the given ML model |
| 52 | + """ |
| 53 | + |
| 54 | + @abstractmethod |
| 55 | + def deserialize(self, serialized_model, is_inner_model=False): |
| 56 | + """ |
| 57 | + Return the associated sklearn ML model of the given previously serialized ML model. |
| 58 | +
|
| 59 | + :param serialized_model: given json string of a ML model to get deserialized to associated sklearn ML model |
| 60 | + :type serialized_model: obj |
| 61 | + :param is_inner_model: determines whether it is an inner ML model of a super ML model |
| 62 | + :type is_inner_model: boolean |
| 63 | + :return: associated sklearn ML model |
| 64 | + """ |
| 65 | + |
| 66 | + @abstractmethod |
| 67 | + def validate(self, model, command): |
| 68 | + """ |
| 69 | + Check if the provided inputs are valid in relation to each other. |
| 70 | +
|
| 71 | + :param model: a sklearn ML model or a json string of it, serialized through the pymilo export |
| 72 | + :type model: obj |
| 73 | + :param command: command to specify whether the request should be serialized or deserialized |
| 74 | + :type command: transporter.Command |
| 75 | + :return: None |
| 76 | + """ |
| 77 | + |
| 78 | + |
| 79 | +class AbstractChain(Chain): |
| 80 | + """Abstract Chain with the general implementation of the Chain interface.""" |
| 81 | + |
| 82 | + def __init__(self, transporters, supported_models): |
| 83 | + """ |
| 84 | + Initialize the AbstractChain instance. |
| 85 | +
|
| 86 | + :param transporters: worker transporters dedicated to this chain |
| 87 | + :type transporters: transporter.AbstractTransporter[] |
| 88 | + :param supported_models: supported sklearn ML models belong to this chain |
| 89 | + :type supported_models: dict |
| 90 | + :return: an instance of the AbstractChain class |
| 91 | + """ |
| 92 | + self._transporters = transporters |
| 93 | + self._supported_models = supported_models |
| 94 | + |
| 95 | + def is_supported(self, model): |
| 96 | + """ |
| 97 | + Check if the given model is a sklearn's ML model supported by this chain. |
| 98 | +
|
| 99 | + :param model: a string name of an ML model or a sklearn object of it |
| 100 | + :type model: any object |
| 101 | + :return: check result as bool |
| 102 | + """ |
| 103 | + model_name = model if isinstance(model, str) else get_sklearn_type(model) |
| 104 | + return model_name in self._supported_models |
| 105 | + |
| 106 | + def transport(self, request, command, is_inner_model=False): |
| 107 | + """ |
| 108 | + Return the transported (serialized or deserialized) model. |
| 109 | +
|
| 110 | + :param request: given ML model to be transported |
| 111 | + :type request: any object |
| 112 | + :param command: command to specify whether the request should be serialized or deserialized |
| 113 | + :type command: transporter.Command |
| 114 | + :param is_inner_model: determines whether it is an inner model of a super ML model |
| 115 | + :type is_inner_model: boolean |
| 116 | + :return: the transported request as a json string or sklearn ML model |
| 117 | + """ |
| 118 | + if not is_inner_model: |
| 119 | + self.validate(request, command) |
| 120 | + |
| 121 | + if command == Command.SERIALIZE: |
| 122 | + try: |
| 123 | + return self.serialize(request) |
| 124 | + except Exception as e: |
| 125 | + raise PymiloSerializationException( |
| 126 | + { |
| 127 | + 'error_type': SerializationErrorTypes.VALID_MODEL_INVALID_INTERNAL_STRUCTURE, |
| 128 | + 'error': { |
| 129 | + 'Exception': repr(e), |
| 130 | + 'Traceback': format_exc(), |
| 131 | + }, |
| 132 | + 'object': request, |
| 133 | + }) |
| 134 | + |
| 135 | + elif command == Command.DESERIALIZE: |
| 136 | + try: |
| 137 | + return self.deserialize(request, is_inner_model) |
| 138 | + except Exception as e: |
| 139 | + raise PymiloDeserializationException( |
| 140 | + { |
| 141 | + 'error_type': DeserializationErrorTypes.VALID_MODEL_INVALID_INTERNAL_STRUCTURE, |
| 142 | + 'error': { |
| 143 | + 'Exception': repr(e), |
| 144 | + 'Traceback': format_exc()}, |
| 145 | + 'object': request |
| 146 | + }) |
| 147 | + |
| 148 | + def serialize(self, model): |
| 149 | + """ |
| 150 | + Return the serialized json string of the given model. |
| 151 | +
|
| 152 | + :param model: given ML model to be get serialized |
| 153 | + :type model: sklearn ML model |
| 154 | + :return: the serialized json string of the given ML model |
| 155 | + """ |
| 156 | + for transporter in self._transporters: |
| 157 | + self._transporters[transporter].transport(model, Command.SERIALIZE) |
| 158 | + return model.__dict__ |
| 159 | + |
| 160 | + def deserialize(self, serialized_model, is_inner_model=False): |
| 161 | + """ |
| 162 | + Return the associated sklearn ML model of the given previously serialized ML model. |
| 163 | +
|
| 164 | + :param serialized_model: given json string of a ML model to get deserialized to associated sklearn ML model |
| 165 | + :type serialized_model: obj |
| 166 | + :param is_inner_model: determines whether it is an inner ML model of a super ML model |
| 167 | + :type is_inner_model: boolean |
| 168 | + :return: associated sklearn ML model |
| 169 | + """ |
| 170 | + raw_model = None |
| 171 | + data = None |
| 172 | + if is_inner_model: |
| 173 | + raw_model = self._supported_models[serialized_model["type"]]() |
| 174 | + data = serialized_model["data"] |
| 175 | + else: |
| 176 | + raw_model = self._supported_models[serialized_model.type]() |
| 177 | + data = serialized_model.data |
| 178 | + for transporter in self._transporters: |
| 179 | + self._transporters[transporter].transport( |
| 180 | + serialized_model, Command.DESERIALIZE, is_inner_model) |
| 181 | + for item in data: |
| 182 | + setattr(raw_model, item, data[item]) |
| 183 | + return raw_model |
| 184 | + |
| 185 | + def validate(self, model, command): |
| 186 | + """ |
| 187 | + Check if the provided inputs are valid in relation to each other. |
| 188 | +
|
| 189 | + :param model: a sklearn ML model or a json string of it, serialized through the pymilo export |
| 190 | + :type model: obj |
| 191 | + :param command: command to specify whether the request should be serialized or deserialized |
| 192 | + :type command: transporter.Command |
| 193 | + :return: None |
| 194 | + """ |
| 195 | + if command == Command.SERIALIZE: |
| 196 | + if self.is_supported(model): |
| 197 | + return |
| 198 | + else: |
| 199 | + raise PymiloSerializationException( |
| 200 | + { |
| 201 | + 'error_type': SerializationErrorTypes.INVALID_MODEL, |
| 202 | + 'object': model |
| 203 | + } |
| 204 | + ) |
| 205 | + elif command == Command.DESERIALIZE: |
| 206 | + if self.is_supported(model.type): |
| 207 | + return |
| 208 | + else: |
| 209 | + raise PymiloDeserializationException( |
| 210 | + { |
| 211 | + 'error_type': DeserializationErrorTypes.INVALID_MODEL, |
| 212 | + 'object': model |
| 213 | + } |
| 214 | + ) |
0 commit comments