1# Copyright 2020 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"""Ops for compressing and uncompressing dataset elements.""" 16from __future__ import absolute_import 17from __future__ import division 18from __future__ import print_function 19 20from tensorflow.python.data.util import structure 21from tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops 22 23 24def compress(element): 25 """Compress a dataset element. 26 27 Args: 28 element: A nested structure of types supported by Tensorflow. 29 30 Returns: 31 A variant tensor representing the compressed element. This variant can be 32 passed to `uncompress` to get back the original element. 33 """ 34 element_spec = structure.type_spec_from_value(element) 35 tensor_list = structure.to_tensor_list(element_spec, element) 36 return ged_ops.compress_element(tensor_list) 37 38 39def uncompress(element, output_spec): 40 """Uncompress a compressed dataset element. 41 42 Args: 43 element: A scalar variant tensor to uncompress. The element should have been 44 created by calling `compress`. 45 output_spec: A nested structure of `tf.TypeSpec` representing the type(s) of 46 the uncompressed element. 47 48 Returns: 49 The uncompressed element. 50 """ 51 flat_types = structure.get_flat_tensor_types(output_spec) 52 flat_shapes = structure.get_flat_tensor_shapes(output_spec) 53 tensor_list = ged_ops.uncompress_element( 54 element, output_types=flat_types, output_shapes=flat_shapes) 55 return structure.from_tensor_list(output_spec, tensor_list) 56