@@ -0,0 +1,2445 @@
+# Copyright 2021 The TensorFlow Authors. All Rights Reserved.%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A#     http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A# ==============================================================================%0A%22%22%22Saving utilities to support Python's Pickle protocol.%0A%22%22%22%0A%0Aimport os%0Aimport tarfile%0Afrom io import BytesIO%0Afrom uuid import uuid4%0A%0Afrom numpy import asarray%0Aimport tensorflow.compat.v2 as tf%0A%0Afrom keras.saving.save import load_model%0A%0A%0Adef unpack_model(packed_keras_model):%0A  %22%22%22Reconstruct a Model from the result of pack_model.%0A%0A  Args:%0A      packed_keras_model (np.array): return value from pack_model.%0A%0A  Returns:%0A      keras.Model: a Keras Model instance.%0A  %22%22%22%0A  temp_dir = f%22ram://%7Buuid4()%7D%22%0A  b = BytesIO(packed_keras_model)%0A  with tarfile.open(fileobj=b, mode=%22r%22) as archive:%0A    for fname in archive.getnames():%0A      dest_path = os.path.join(temp_dir, fname)%0A      tf.io.gfile.makedirs(os.path.dirname(dest_path))%0A      with tf.io.gfile.GFile(dest_path, %22wb%22) as f:%0A        f.write(archive.extractfile(fname).read())%0A  model = load_model(temp_dir)%0A  tf.io.gfile.rmtree(temp_dir)%0A  return model%0A%0A%0Adef pack_model(model):%0A  %22%22%22Pack a Keras Model into a numpy array for pickling.%0A%0A  Args:%0A      model (tf.keras.Model): a Keras Model instance.%0A%0A  Returns:%0A      tuple: an unpacking function (unpack_model) and it's arguments,%0A      as per Python's pickle protocol.%0A  %22%22%22%0A  temp_dir = f%22ram://%7Buuid4()%7D%22%0A  model.save(temp_dir)%0A  b = BytesIO()%0A  with tarfile.open(fileobj=b, mode=%22w%22) as archive:%0A    for root, _, filenames in tf.io.gfile.walk(temp_dir):%0A      for filename in filenames:%0A        dest_path = os.path.join(root, filename)%0A        with tf.io.gfile.GFile(dest_path, %22rb%22) as f:%0A          info = tarfile.TarInfo(name=os.path.relpath(dest_path, temp_dir))%0A          info.size = f.size()%0A          archive.addfile(tarinfo=info, fileobj=f)%0A  tf.io.gfile.rmtree(temp_dir)%0A  b.seek(0)%0A  return unpack_model, (asarray(memoryview(b.read())), )%0A

Add file