-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathserialization.py
More file actions
378 lines (278 loc) · 8.96 KB
/
serialization.py
File metadata and controls
378 lines (278 loc) · 8.96 KB
1
2
3
4
5
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
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
import json
from typing import Any, Union
import numpy as np
from pydantic.json import pydantic_encoder
from .importing import which_import
try:
import msgpack
except ModuleNotFoundError:
pass
_msgpack_which_msg = "Please install via `conda install msgpack-python`."
## MSGPackExt
def msgpackext_encode(obj: Any) -> Any:
r"""
Encodes an object using pydantic and NumPy array serialization techniques suitable for msgpack.
Parameters
----------
obj : Any
Any object that can be serialized with pydantic and NumPy encoding techniques.
Returns
-------
Any
A msgpack compatible form of the object.
"""
# First try pydantic base objects
try:
return pydantic_encoder(obj)
except TypeError:
pass
if isinstance(obj, np.ndarray):
if obj.shape:
data = {b"_nd_": True, b"dtype": obj.dtype.str, b"data": np.ascontiguousarray(obj).tobytes()}
if len(obj.shape) > 1:
data[b"shape"] = obj.shape
return data
else:
# Converts np.array(5) -> 5
return obj.tolist()
return obj
def msgpackext_decode(obj: Any) -> Any:
r"""
Decodes a msgpack objects from a dictionary representation.
Parameters
----------
obj : Any
An encoded object, likely a dictionary.
Returns
-------
Any
The decoded form of the object.
"""
if b"_nd_" in obj:
arr = np.frombuffer(obj[b"data"], dtype=obj[b"dtype"])
if b"shape" in obj:
arr.shape = obj[b"shape"]
return arr
return obj
def msgpackext_dumps(data: Any) -> bytes:
r"""Safe serialization of a Python object to msgpack binary representation using all known encoders.
For NumPy, encodes a specialized object format to encode all shape and type data.
Parameters
----------
data : Any
A encodable python object.
Returns
-------
bytes
A msgpack representation of the data in bytes.
"""
which_import("msgpack", raise_error=True, raise_msg=_msgpack_which_msg)
return msgpack.dumps(data, default=msgpackext_encode, use_bin_type=True)
def msgpackext_loads(data: bytes) -> Any:
r"""Deserializes a msgpack byte representation of known objects into those objects.
Parameters
----------
data : bytes
The serialized msgpack byte array.
Returns
-------
Any
The deserialized Python objects.
"""
which_import("msgpack", raise_error=True, raise_msg=_msgpack_which_msg)
return msgpack.loads(data, object_hook=msgpackext_decode, raw=False)
## JSON Ext
class JSONExtArrayEncoder(json.JSONEncoder):
def default(self, obj: Any) -> Any:
try:
return pydantic_encoder(obj)
except TypeError:
pass
if isinstance(obj, np.ndarray):
if obj.shape:
data = {"_nd_": True, "dtype": obj.dtype.str, "data": np.ascontiguousarray(obj).tobytes().hex()}
if len(obj.shape) > 1:
data["shape"] = obj.shape
return data
else:
# Converts np.array(5) -> 5
return obj.tolist()
return json.JSONEncoder.default(self, obj)
def jsonext_decode(obj: Any) -> Any:
if "_nd_" in obj:
arr = np.frombuffer(bytes.fromhex(obj["data"]), dtype=obj["dtype"])
if "shape" in obj:
arr.shape = obj["shape"]
return arr
return obj
def jsonext_dumps(data: Any) -> str:
r"""Safe serialization of Python objects to JSON string representation using all known encoders.
The JSON serializer uses a custom array syntax rather than flat JSON lists.
Parameters
----------
data : Any
A encodable python object.
Returns
-------
str
A JSON representation of the data.
"""
return json.dumps(data, cls=JSONExtArrayEncoder)
def jsonext_loads(data: Union[str, bytes]) -> Any:
r"""Deserializes a json representation of known objects into those objects.
Parameters
----------
data : str or bytes
The byte-serialized JSON blob.
Returns
-------
Any
The deserialized Python objects.
"""
return json.loads(data, object_hook=jsonext_decode)
## JSON
class JSONArrayEncoder(json.JSONEncoder):
def default(self, obj: Any) -> Any:
try:
return pydantic_encoder(obj)
except TypeError:
pass
if isinstance(obj, np.ndarray):
if obj.shape:
return obj.ravel().tolist()
else:
return obj.tolist()
return json.JSONEncoder.default(self, obj)
def json_dumps(data: Any, **kwargs) -> str:
r"""Safe serialization of a Python dictionary to JSON string representation using all known encoders.
Parameters
----------
data : Any
A encodable python object.
kwargs : Any
Keyword arguments for json.dumps()
Returns
-------
str
A JSON representation of the data.
"""
return json.dumps(data, cls=JSONArrayEncoder, **kwargs)
def json_loads(data: str) -> Any:
r"""Deserializes a json representation of known objects into those objects.
Parameters
----------
data : str
The serialized JSON blob.
Returns
-------
Any
The deserialized Python objects.
"""
# Doesn't hurt anything to try to load JSONext as well
return json.loads(data, object_hook=jsonext_decode)
## MSGPack
def msgpack_encode(obj: Any) -> Any:
r"""
Encodes an object using pydantic. Converts numpy arrays to plain python lists
Parameters
----------
obj : Any
Any object that can be serialized with pydantic and NumPy encoding techniques.
Returns
-------
Any
A msgpack compatible form of the object.
"""
try:
return pydantic_encoder(obj)
except TypeError:
pass
if isinstance(obj, np.ndarray):
if obj.shape:
return obj.ravel().tolist()
else:
return obj.tolist()
return obj
def msgpack_dumps(data: Any) -> str:
r"""Safe serialization of a Python object to msgpack binary representation using all known encoders.
For NumPy, converts to lists.
Parameters
----------
data : Any
A encodable python object.
Returns
-------
str
A msgpack representation of the data in bytes.
"""
which_import("msgpack", raise_error=True, raise_msg=_msgpack_which_msg)
return msgpack.dumps(data, default=msgpack_encode, use_bin_type=True)
def msgpack_loads(data: str) -> Any:
r"""Deserializes a msgpack byte representation of known objects into those objects.
Parameters
----------
data : bytes
The serialized msgpack byte array.
Returns
-------
Any
The deserialized Python objects.
"""
which_import("msgpack", raise_error=True, raise_msg=_msgpack_which_msg)
# Doesn't hurt anything to try to load msgpack-ext as well
return msgpack.loads(data, object_hook=msgpackext_decode, raw=False)
## Helper functions
def serialize(data: Any, encoding: str, **kwargs) -> Union[str, bytes]:
r"""Encoding Python objects using the provided encoder.
Parameters
----------
data : Any
A encodable python object.
encoding : str
The type of encoding to perform: {'json', 'json-ext', 'msgpack-ext'}
kwargs: Any
For passing additional kwargs to serialization functions, such as indent
Returns
-------
Union[str, bytes]
A serialized representation of the data.
"""
if encoding.lower() == "json":
return json_dumps(data, **kwargs)
elif encoding.lower() == "json-ext":
return jsonext_dumps(data)
elif encoding.lower() == "msgpack":
return msgpack_dumps(data)
elif encoding.lower() == "msgpack-ext":
return msgpackext_dumps(data)
else:
raise KeyError(f"Encoding '{encoding}' not understood, valid options: 'json', 'json-ext', 'msgpack-ext'")
def deserialize(blob: Union[str, bytes], encoding: str) -> Any:
r"""Encoding Python objects using .
Parameters
----------
blob : Union[str, bytes]
The serialized data.
encoding : str
The type of encoding of the blob: {'json', 'json-ext', 'msgpack'}
Returns
-------
Any
The deserialized Python objects.
"""
if encoding.lower() == "json":
assert isinstance(blob, str)
return json_loads(blob)
elif encoding.lower() == "json-ext":
assert isinstance(blob, (str, bytes))
return jsonext_loads(blob)
elif encoding.lower() in ["msgpack"]:
assert isinstance(blob, bytes)
return msgpack_loads(blob)
elif encoding.lower() in ["msgpack-ext"]:
assert isinstance(blob, bytes)
return msgpackext_loads(blob)
else:
raise KeyError(
f"Encoding '{encoding}' not understood, valid options: 'json', 'json-ext', 'msgpack', 'msgpack-ext'"
)