1# Copyright 2018 The TensorFlow Authors. All Rights Reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14# ============================================================================== 15"""Utilities for serializing Python objects.""" 16 17import numpy as np 18import wrapt 19 20from tensorflow.python.framework import dtypes 21from tensorflow.python.framework import tensor_shape 22from tensorflow.python.util.compat import collections_abc 23 24 25def get_json_type(obj): 26 """Serializes any object to a JSON-serializable structure. 27 28 Args: 29 obj: the object to serialize 30 31 Returns: 32 JSON-serializable structure representing `obj`. 33 34 Raises: 35 TypeError: if `obj` cannot be serialized. 36 """ 37 # if obj is a serializable Keras class instance 38 # e.g. optimizer, layer 39 if hasattr(obj, 'get_config'): 40 return {'class_name': obj.__class__.__name__, 'config': obj.get_config()} 41 42 # if obj is any numpy type 43 if type(obj).__module__ == np.__name__: 44 if isinstance(obj, np.ndarray): 45 return obj.tolist() 46 else: 47 return obj.item() 48 49 # misc functions (e.g. loss function) 50 if callable(obj): 51 return obj.__name__ 52 53 # if obj is a python 'type' 54 if type(obj).__name__ == type.__name__: 55 return obj.__name__ 56 57 if isinstance(obj, tensor_shape.Dimension): 58 return obj.value 59 60 if isinstance(obj, tensor_shape.TensorShape): 61 return obj.as_list() 62 63 if isinstance(obj, dtypes.DType): 64 return obj.name 65 66 if isinstance(obj, collections_abc.Mapping): 67 return dict(obj) 68 69 if obj is Ellipsis: 70 return {'class_name': '__ellipsis__'} 71 72 if isinstance(obj, wrapt.ObjectProxy): 73 return obj.__wrapped__ 74 75 raise TypeError(f'Object {obj} is not JSON-serializable. You may implement ' 76 'a `get_config()` method on the class ' 77 '(returning a JSON-serializable dictionary) to make it ' 78 'serializable.') 79