import warnings
warnings.filterwarnings('ignore')

%matplotlib inline
%pylab inline
import matplotlib.pyplot as plt

import pandas as pd
print(pd.__version__)

import tensorflow as tf
tf.logging.set_verbosity(tf.logging.ERROR)
print(tf.__version__)

# let's see what compute devices we have available, hopefully a GPU 
sess = tf.Session()
devices = sess.list_devices()
for d in devices:
    print(d.name)

# a small sane check, does tf seem to work ok?
hello = tf.constant('Hello TF!')
print(sess.run(hello))

"""
Explanation: Preparing a TensorFlow model
End of explanation
"""


!curl -O https://raw.githubusercontent.com/DJCordhose/ai/master/notebooks/manning/model/insurance.hdf5

model = tf.keras.models.load_model('insurance.hdf5')

"""
Explanation: Loading and validating our model
End of explanation
"""


# a little sane check, does it work at all?

# within this code, we expect Olli to be a green customer with a high prabability
# 0: red
# 1: green
# 2: yellow

olli_data = [100, 47, 10]

X = np.array([olli_data])
model.predict(X)

"""
Explanation: Descison Boundaries for 2 Dimensions
End of explanation
"""


# https://cloud.google.com/blog/products/gcp/new-in-tensorflow-14-converting-a-keras-model-to-a-tensorflow-estimator
estimator_model = tf.keras.estimator.model_to_estimator(keras_model=model)

# it still works the same, with a different style of API, though
x = {"hidden1_input": X}
list(estimator_model.predict(input_fn=tf.estimator.inputs.numpy_input_fn(x, shuffle=False)))

"""
Explanation: Converting our Keras Model to the Alternative High-Level Estimator Model
End of explanation
"""


!rm -rf tf

import os

export_path_base = 'tf'
version = 1
export_path = os.path.join(
      tf.compat.as_bytes(export_path_base),
      tf.compat.as_bytes(str(version)))

tf.keras.backend.set_learning_phase(0)
sess = tf.keras.backend.get_session()

classification_inputs = tf.saved_model.utils.build_tensor_info(model.input)
classification_outputs_scores = tf.saved_model.utils.build_tensor_info(model.output)

signature =  tf.saved_model.signature_def_utils.build_signature_def(
    inputs={'inputs': classification_inputs},
    outputs={'scores': classification_outputs_scores},
    method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME)

builder = tf.saved_model.builder.SavedModelBuilder(export_path)
builder.add_meta_graph_and_variables(
      sess, [tf.saved_model.tag_constants.SERVING],
      signature_def_map={
           tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: signature
      })
builder.save()

del model

del estimator_model

import gc
gc.collect()

tf.keras.backend.clear_session()

"""
Explanation: Preparing our model for serving

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md
https://www.tensorflow.org/serving/serving_basic
End of explanation
"""


