openmodels 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
openmodels/__init__.py ADDED
@@ -0,0 +1,50 @@
1
+ """
2
+ OpenModels: A flexible library for serializing and deserializing machine learning models.
3
+
4
+ This package provides tools for converting machine learning models to various
5
+ formats and back. It supports different model types and serialization formats
6
+ through a plugin-based system.
7
+
8
+ Main components:
9
+ - SerializationManager: Coordinates the serialization and deserialization process.
10
+ - SklearnSerializer: Handles serialization for scikit-learn models.
11
+ - JSONConverter, PickleConverter: Convert between dict and specific formats.
12
+ - FormatRegistry: Manages available format converters.
13
+
14
+ Example usage:
15
+ from openmodels import SerializationManager, SklearnSerializer
16
+ from sklearn.linear_model import LogisticRegression
17
+
18
+ # Create and train a scikit-learn model
19
+ model = LogisticRegression()
20
+ model.fit(X_train, y_train)
21
+
22
+ # Create a SerializationManager
23
+ manager = SerializationManager(SklearnSerializer())
24
+
25
+ # Serialize the model to JSON
26
+ serialized_model = manager.serialize(model, format="json")
27
+
28
+ # Deserialize the model from JSON
29
+ deserialized_model = manager.deserialize(serialized_model, format="json")
30
+
31
+ # Use the deserialized model
32
+ predictions = deserialized_model.predict(X_test)
33
+
34
+ For more advanced usage and custom serializers or converters, refer to the documentation.
35
+ """
36
+
37
+ from .core import SerializationManager
38
+ from .serializers import SklearnSerializer
39
+ from .converters import JSONConverter, PickleConverter
40
+ from .format_registry import FormatRegistry
41
+
42
+ # Register the JSONConverter
43
+ FormatRegistry.register("json", JSONConverter)
44
+ FormatRegistry.register("pickle", PickleConverter)
45
+
46
+ __all__ = [
47
+ "FormatRegistry",
48
+ "SerializationManager",
49
+ "SklearnSerializer",
50
+ ]
@@ -0,0 +1,11 @@
1
+ """
2
+ Converters module for the OpenModels library.
3
+
4
+ This module provides converters for different serialization formats.
5
+ Currently, it includes converters for JSON and pickle formats.
6
+ """
7
+
8
+ from .json_converter import JSONConverter
9
+ from .pickle_converter import PickleConverter
10
+
11
+ __all__ = ["JSONConverter", "PickleConverter"]
@@ -0,0 +1,61 @@
1
+ """
2
+ JSON converter for the OpenModels library.
3
+
4
+ This module provides a converter for serializing to and from JSON format.
5
+ """
6
+
7
+ import json
8
+ from typing import Any, Dict
9
+
10
+ from openmodels.protocols import FormatConverter
11
+
12
+
13
+ class JSONConverter(FormatConverter):
14
+ """
15
+ Converter for JSON format.
16
+
17
+ This class provides static methods to convert between dictionary
18
+ representations and JSON strings.
19
+ """
20
+
21
+ @staticmethod
22
+ def serialize_to_format(data: Dict[str, Any]) -> str:
23
+ """
24
+ Convert a dictionary to a JSON string.
25
+
26
+ Parameters
27
+ ----------
28
+ data : Dict[str, Any]
29
+ The dictionary to convert.
30
+
31
+ Returns
32
+ -------
33
+ str
34
+ The JSON string representation of the data.
35
+ """
36
+
37
+ if not isinstance(data, dict):
38
+ raise TypeError("Data must be a dictionary.")
39
+ return json.dumps(data)
40
+
41
+ @staticmethod
42
+ def deserialize_from_format(formatted_data: str) -> Dict[str, Any]:
43
+ """
44
+ Convert a JSON string to a dictionary.
45
+
46
+ Parameters
47
+ ----------
48
+ formatted_data : str
49
+ The JSON string to convert.
50
+
51
+ Returns
52
+ -------
53
+ Dict[str, Any]
54
+ The dictionary representation of the JSON data.
55
+
56
+ Raises
57
+ ------
58
+ json.JSONDecodeError
59
+ If the input string is not valid JSON.
60
+ """
61
+ return json.loads(formatted_data)
@@ -0,0 +1,72 @@
1
+ """
2
+ Pickle converter for the OpenModels library.
3
+
4
+ This module provides a converter for serializing to and from pickle format.
5
+
6
+ .. warning::
7
+ Unpickling can execute arbitrary code. Only deserialize pickle data from sources you
8
+ trust - see SECURITY.md. Prefer the JSON format for data from untrusted sources.
9
+ """
10
+
11
+ import pickle
12
+ from typing import Any, Dict
13
+
14
+ from openmodels.protocols import FormatConverter
15
+
16
+
17
+ class PickleConverter(FormatConverter):
18
+ """
19
+ Converter for pickle format.
20
+
21
+ This class provides static methods to convert between dictionary
22
+ representations and pickle byte strings.
23
+
24
+ .. warning::
25
+ ``deserialize_from_format`` calls ``pickle.loads()``, which can execute arbitrary
26
+ code as part of deserialization. Only use this converter with pickle data from
27
+ sources you trust.
28
+ """
29
+
30
+ @staticmethod
31
+ def serialize_to_format(data: Dict[str, Any]) -> bytes:
32
+ """
33
+ Convert a dictionary to a pickle byte string.
34
+
35
+ Parameters
36
+ ----------
37
+ data : Dict[str, Any]
38
+ The dictionary to convert.
39
+
40
+ Returns
41
+ -------
42
+ bytes
43
+ The pickle byte string representation of the data.
44
+ """
45
+ return pickle.dumps(data)
46
+
47
+ @staticmethod
48
+ def deserialize_from_format(formatted_data: bytes) -> Dict[str, Any]:
49
+ """
50
+ Convert a pickle byte string to a dictionary.
51
+
52
+ Parameters
53
+ ----------
54
+ formatted_data : bytes
55
+ The pickle byte string to convert.
56
+
57
+ Returns
58
+ -------
59
+ Dict[str, Any]
60
+ The dictionary representation of the pickle data.
61
+
62
+ Raises
63
+ ------
64
+ pickle.UnpicklingError
65
+ If the input bytes cannot be unpickled.
66
+
67
+ Warns
68
+ -----
69
+ Unpickling can execute arbitrary code. Only call this with pickle data from a
70
+ source you trust.
71
+ """
72
+ return pickle.loads(formatted_data)
openmodels/core.py ADDED
@@ -0,0 +1,205 @@
1
+ """
2
+ Core API module for the OpenModels library.
3
+
4
+ This module contains the SerializationManager class, which is the main interface
5
+ for serializing and deserializing machine learning models using various formats.
6
+ """
7
+
8
+ from typing import Any, Union
9
+ from pathlib import Path
10
+ from .protocols import ModelSerializer
11
+ from .format_registry import FormatRegistry
12
+ from .exceptions import SerializationError, DeserializationError
13
+
14
+
15
+ class SerializationManager:
16
+ """
17
+ Manage the serialization and deserialization of machine learning models.
18
+
19
+ This class coordinates the process of converting models to various formats
20
+ and back, using specified model serializers and format converters.
21
+
22
+ Attributes
23
+ ----------
24
+ model_serializer : ModelSerializer
25
+ The serializer used to convert models to and from dictionary representations.
26
+ """
27
+
28
+ def __init__(self, model_serializer: ModelSerializer):
29
+ """
30
+ Initialize the SerializationManager with a model serializer.
31
+
32
+ Parameters
33
+ ----------
34
+ model_serializer : ModelSerializer
35
+ The serializer to use for converting models to and from dictionary representations.
36
+ """
37
+ self.model_serializer = model_serializer
38
+
39
+ def serialize(self, model: Any, format_name: str = "json") -> Any:
40
+ """
41
+ Serialize a model to the specified format.
42
+
43
+ Parameters
44
+ ----------
45
+ model : Any
46
+ The machine learning model to serialize.
47
+ format_name : str, optional
48
+ The target format (default is "json").
49
+
50
+ Returns
51
+ -------
52
+ Any
53
+ The serialized model in the specified format.
54
+
55
+ Raises
56
+ ------
57
+ SerializationError
58
+ If the model serializer doesn't return a dictionary or if there's an error during
59
+ serialization.
60
+ UnsupportedFormatError
61
+ If the specified format is not supported.
62
+
63
+ Examples
64
+ --------
65
+ >>> manager = SerializationManager(SklearnSerializer())
66
+ >>> model = LogisticRegression()
67
+ >>> serialized_model = manager.serialize(model, format_name="json")
68
+ """
69
+ converter = FormatRegistry.get_converter(format_name)
70
+ serialized_dict = self.model_serializer.serialize(model)
71
+ if not isinstance(serialized_dict, dict):
72
+ raise SerializationError(
73
+ f"Model serializer must return a dict, got {type(serialized_dict)}"
74
+ )
75
+ return converter.serialize_to_format(serialized_dict)
76
+
77
+ def deserialize(self, serialized_model: Any, format_name: str = "json") -> Any:
78
+ """
79
+ Deserialize a model from the specified format.
80
+
81
+ Parameters
82
+ ----------
83
+ serialized_model : Any
84
+ The serialized model data.
85
+ format_name : str, optional
86
+ The format of the serialized data (default is "json").
87
+
88
+ Returns
89
+ -------
90
+ Any
91
+ The deserialized machine learning model.
92
+
93
+ Raises
94
+ ------
95
+ DeserializationError
96
+ If the format converter doesn't return a dictionary or if there's an error during
97
+ deserialization.
98
+ UnsupportedFormatError
99
+ If the specified format_name is not supported.
100
+
101
+ Examples
102
+ --------
103
+ >>> manager = SerializationManager(SklearnSerializer())
104
+ >>> deserialized_model = manager.deserialize(serialized_model, format_name="json")
105
+ >>> predictions = deserialized_model.predict(X_test)
106
+ """
107
+ converter = FormatRegistry.get_converter(format_name)
108
+ try:
109
+ deserialized_dict = converter.deserialize_from_format(serialized_model)
110
+ except Exception as e:
111
+ raise DeserializationError(f"Error during deserialization: {e}")
112
+ if not isinstance(deserialized_dict, dict):
113
+ raise DeserializationError(
114
+ f"Format converter must return a dict, got {type(deserialized_dict)}"
115
+ )
116
+ return self.model_serializer.deserialize(deserialized_dict)
117
+
118
+ def save(
119
+ self,
120
+ model: Any,
121
+ file_path: Union[str, Path],
122
+ format_name: str = "json",
123
+ ) -> None:
124
+ """
125
+ Save a model to a file in the specified format.
126
+
127
+ Parameters
128
+ ----------
129
+ model : Any
130
+ The machine learning model to serialize and save.
131
+ file_path : Union[str, Path]
132
+ The path to the file where the model will be saved.
133
+ format_name : str, optional
134
+ The target format (default is "json").
135
+
136
+ Raises
137
+ ------
138
+ SerializationError
139
+ If there's an error during serialization or file I/O.
140
+ UnsupportedFormatError
141
+ If the specified format is not supported.
142
+
143
+ Examples
144
+ --------
145
+ >>> manager = SerializationManager(SklearnSerializer())
146
+ >>> model = LogisticRegression()
147
+ >>> manager.save(model, "model.json", format_name="json")
148
+ """
149
+ serialized_data = self.serialize(model, format_name)
150
+ file_path = Path(file_path)
151
+
152
+ try:
153
+ # Determine write mode based on type of serialized_data
154
+ if isinstance(serialized_data, bytes):
155
+ with open(file_path, "wb") as f:
156
+ f.write(serialized_data)
157
+ else:
158
+ with open(file_path, "w", encoding="utf-8") as f:
159
+ f.write(serialized_data)
160
+
161
+ except Exception as e:
162
+ raise SerializationError(f"Failed to save model: {e}")
163
+
164
+ def load(self, file_path: Union[str, Path], format_name: str = "json") -> Any:
165
+ """
166
+ Load and deserialize a model from a file.
167
+
168
+ Parameters
169
+ ----------
170
+ file_path : Union[str, Path]
171
+ The path to the file containing the serialized model.
172
+ format_name : str, optional
173
+ The format of the serialized data (default is "json").
174
+
175
+ Returns
176
+ -------
177
+ Any
178
+ The deserialized machine learning model.
179
+
180
+ Raises
181
+ ------
182
+ DeserializationError
183
+ If deserialization or file I/O fails.
184
+ UnsupportedFormatError
185
+ If the specified format is not supported.
186
+
187
+ Examples
188
+ --------
189
+ >>> manager = SerializationManager(SklearnSerializer())
190
+ >>> loaded_model = manager.load("model.json", format_name="json")
191
+ """
192
+ file_path = Path(file_path)
193
+ # Determine read mode based on format
194
+ try:
195
+ serialized_data: Union[str, bytes]
196
+ if format_name == "pickle":
197
+ with open(file_path, "rb") as f:
198
+ serialized_data = f.read()
199
+ else:
200
+ with open(file_path, "r", encoding="utf-8") as f:
201
+ serialized_data = f.read()
202
+ except Exception as e:
203
+ raise DeserializationError(f"Failed to load model: {e}")
204
+
205
+ return self.deserialize(serialized_data, format_name)
@@ -0,0 +1,26 @@
1
+ """
2
+ Custom exceptions for the OpenModels library.
3
+
4
+ This module defines custom exception classes used throughout the OpenModels
5
+ library to provide more specific error handling and improve debuggability.
6
+ """
7
+
8
+
9
+ class OpenModelsError(Exception):
10
+ """Base exception class for all OpenModels library errors."""
11
+
12
+
13
+ class SerializationError(OpenModelsError):
14
+ """Exception raised when there's an error during model serialization."""
15
+
16
+
17
+ class DeserializationError(OpenModelsError):
18
+ """Exception raised when there's an error during model deserialization."""
19
+
20
+
21
+ class UnsupportedFormatError(OpenModelsError):
22
+ """Exception raised when an unsupported serialization format is requested."""
23
+
24
+
25
+ class UnsupportedEstimatorError(OpenModelsError):
26
+ """Exception raised when an unsupported estimator is encountered."""
@@ -0,0 +1,73 @@
1
+ """
2
+ Format registry module for the OpenModels library.
3
+
4
+ This module provides a registry for format converters, allowing dynamic
5
+ registration and retrieval of converters for different serialization formats.
6
+ """
7
+
8
+ from typing import Dict, Type
9
+ from .protocols import FormatConverter
10
+ from .exceptions import UnsupportedFormatError
11
+
12
+
13
+ class FormatRegistry:
14
+ """
15
+ A registry for format converters.
16
+
17
+ This class manages the registration and retrieval of format converters,
18
+ allowing the SerializationManager to support multiple serialization formats.
19
+
20
+ Attributes
21
+ ----------
22
+ _converters : Dict[str, Type[FormatConverter]]
23
+ A dictionary mapping format names to their respective converter classes.
24
+ """
25
+
26
+ _converters: Dict[str, Type[FormatConverter]] = {}
27
+
28
+ @classmethod
29
+ def register(cls, format_name: str, converter: Type[FormatConverter]) -> None:
30
+ """
31
+ Register a new format converter.
32
+
33
+ Parameters
34
+ ----------
35
+ format_name : str
36
+ The name of the format (e.g., "json", "pickle").
37
+ converter : Type[FormatConverter]
38
+ The converter class for the format.
39
+
40
+ Examples
41
+ --------
42
+ >>> FormatRegistry.register("json", JSONConverter)
43
+ """
44
+ cls._converters[format_name] = converter
45
+
46
+ @classmethod
47
+ def get_converter(cls, format_name: str) -> Type[FormatConverter]:
48
+ """
49
+ Retrieve a format converter by name.
50
+
51
+ Parameters
52
+ ----------
53
+ format_name : str
54
+ The name of the format to retrieve.
55
+
56
+ Returns
57
+ -------
58
+ Type[FormatConverter]
59
+ The converter class for the specified format.
60
+
61
+ Raises
62
+ ------
63
+ UnsupportedFormatError
64
+ If the specified format is not supported.
65
+
66
+ Examples
67
+ --------
68
+ >>> json_converter = FormatRegistry.get_converter("json")
69
+ >>> serialized_data = json_converter.serialize_to_format(data_dict)
70
+ """
71
+ if format_name not in cls._converters:
72
+ raise UnsupportedFormatError(f"Unsupported format: {format_name}")
73
+ return cls._converters[format_name]
@@ -0,0 +1,83 @@
1
+ """
2
+ Protocol definitions for the OpenModels library.
3
+
4
+ This module defines the protocols (interfaces) that model serializers and
5
+ format converters must implement to be compatible with the SerializationManager.
6
+ """
7
+
8
+ from abc import abstractmethod
9
+ from typing import Any, Dict, Protocol
10
+
11
+
12
+ class ModelSerializer(Protocol):
13
+ """Protocol for model serializers."""
14
+
15
+ @abstractmethod
16
+ def serialize(self, model: Any) -> Dict[str, Any]:
17
+ """
18
+ Serialize a model to a dictionary representation.
19
+
20
+ Parameters
21
+ ----------
22
+ model : Any
23
+ The model to serialize.
24
+
25
+ Returns
26
+ -------
27
+ Dict[str, Any]
28
+ A dictionary representation of the model.
29
+ """
30
+
31
+ @abstractmethod
32
+ def deserialize(self, data: Dict[str, Any]) -> Any:
33
+ """
34
+ Deserialize a model from a dictionary representation.
35
+
36
+ Parameters
37
+ ----------
38
+ data : Dict[str, Any]
39
+ The dictionary representation of the model.
40
+
41
+ Returns
42
+ -------
43
+ Any
44
+ The deserialized model.
45
+ """
46
+
47
+
48
+ class FormatConverter(Protocol):
49
+ """Protocol for format converters."""
50
+
51
+ @staticmethod
52
+ @abstractmethod
53
+ def serialize_to_format(data: Dict[str, Any]) -> Any:
54
+ """
55
+ Convert a dictionary to a specific format.
56
+
57
+ Parameters
58
+ ----------
59
+ data : Dict[str, Any]
60
+ The dictionary to convert.
61
+
62
+ Returns
63
+ -------
64
+ Any
65
+ The data in the specific format.
66
+ """
67
+
68
+ @staticmethod
69
+ @abstractmethod
70
+ def deserialize_from_format(formatted_data: Any) -> Dict[str, Any]:
71
+ """
72
+ Convert data from a specific format to a dictionary.
73
+
74
+ Parameters
75
+ ----------
76
+ formatted_data : Any
77
+ The data in the specific format.
78
+
79
+ Returns
80
+ -------
81
+ Dict[str, Any]
82
+ The dictionary representation of the data.
83
+ """
@@ -0,0 +1,10 @@
1
+ """
2
+ Serializers module for the OpenModels library.
3
+
4
+ This module provides serializers for different types of machine learning models.
5
+ Currently, it includes a serializer for scikit-learn models.
6
+ """
7
+
8
+ from .sklearn.sklearn_serializer import SklearnSerializer
9
+
10
+ __all__ = ["SklearnSerializer"]