import datetime
import os
import shutil

import numpy as np
import pandas as pd
import tensorflow as tf
from matplotlib import pyplot as plt
from tensorflow import keras
from tensorflow.keras.callbacks import TensorBoard
from tensorflow.keras.layers import Dense, DenseFeatures
from tensorflow.keras.models import Sequential

print(tf.__version__)
%matplotlib inline

"""
Explanation: Introducing the Keras Sequential API
Learning Objectives
  1. Build a DNN model using the Keras Sequential API
  1. Learn how to use feature columns in a Keras model
  1. Learn how to train a model with Keras
  1. Learn how to save/load, and deploy a Keras model on GCP
  1. Learn how to deploy and make predictions with the Keras model
Introduction
The Keras sequential API allows you to create Tensorflow models layer-by-layer. This is useful for building most kinds of machine learning models but it does not allow you to create models that share layers, re-use layers or have multiple inputs or outputs. 
In this lab, we'll see how to build a simple deep neural network model using the Keras sequential api and feature columns. Once we have trained our model, we will deploy it using AI Platform and see how to call our model for online prediciton.
Start by importing the necessary libraries for this lab.
End of explanation
"""


!ls -l ../data/*.csv

!head ../data/taxi*.csv

"""
Explanation: Load raw data
We will use the taxifare dataset, using the CSV files that we created in the first notebook of this sequence. Those files have been saved into ../data.
End of explanation
"""


CSV_COLUMNS = [
    "fare_amount",
    "pickup_datetime",
    "pickup_longitude",
    "pickup_latitude",
    "dropoff_longitude",
    "dropoff_latitude",
    "passenger_count",
    "key",
]
LABEL_COLUMN = "fare_amount"
DEFAULTS = [[0.0], ["na"], [0.0], [0.0], [0.0], [0.0], [0.0], ["na"]]
UNWANTED_COLS = ["pickup_datetime", "key"]


def features_and_labels(row_data):
    label = row_data.pop(LABEL_COLUMN)
    features = row_data

    for unwanted_col in UNWANTED_COLS:
        features.pop(unwanted_col)

    return features, label


def create_dataset(pattern, batch_size=1, mode="eval"):
    dataset = tf.data.experimental.make_csv_dataset(
        pattern, batch_size, CSV_COLUMNS, DEFAULTS
    )

    dataset = dataset.map(features_and_labels)

    if mode == "train":
        dataset = dataset.shuffle(buffer_size=1000).repeat()

    # take advantage of multi-threading; 1=AUTOTUNE
    dataset = dataset.prefetch(1)
    return dataset

"""
Explanation: Use tf.data to read the CSV files
We wrote these functions for reading data from the csv files above in the previous notebook.
End of explanation
"""


INPUT_COLS = [
    "pickup_longitude",
    "pickup_latitude",
    "dropoff_longitude",
    "dropoff_latitude",
    "passenger_count",
]

# Create input layer of feature columns
feature_columns =  # TODO: Your code here

"""
Explanation: Build a simple keras DNN model
We will use feature columns to connect our raw data to our keras DNN model. Feature columns make it easy to perform common types of feature engineering on your raw data. For example, you can one-hot encode categorical data, create feature crosses, embeddings and more. We'll cover these in more detail later in the course, but if you want to a sneak peak browse the official TensorFlow feature columns guide.
In our case we won't do any feature engineering. However, we still need to create a list of feature columns to specify the numeric values which will be passed on to our model. To do this, we use tf.feature_column.numeric_column()
We use a python dictionary comprehension to create the feature columns for our model, which is just an elegant alternative to a for loop.
Exercise. Create a feature column dictionary that we will use when building our deep neural network below. The keys should be the element of the INPUT_COLS list, while the values should be numeric feature columns.
End of explanation
"""


# Build a keras DNN model using Sequential API
model =  # TODO: Your code here

"""
Explanation: Next, we create the DNN model. The Sequential model is a linear stack of layers and when building a model using the Sequential API, you configure each layer of the model in turn. Once all the layers have been added, you compile the model. 
Exercise. Create a deep neural network using Keras's Sequential API. In the cell below, use the tf.keras.layers library to create all the layers for your deep neural network.
End of explanation
"""


# Create a custom evalution metric
def rmse(y_true, y_pred):
    return  # TODO: Your code here


# Compile the keras model
# TODO: Your code here

"""
Explanation: Next, to prepare the model for training, you must configure the learning process. This is done using the compile method. The compile method takes three arguments:

An optimizer. This could be the string identifier of an existing optimizer (such as rmsprop or adagrad), or an instance of the Optimizer class.
A loss function. This is the objective that the model will try to minimize. It can be the string identifier of an existing loss function from the Losses class (such as categorical_crossentropy or mse), or it can be a custom objective function.
A list of metrics. For any machine learning problem you will want a set of metrics to evaluate your model. A metric could be the string identifier of an existing metric or a custom metric function.

We will add an additional custom metric called rmse to our list of metrics which will return the root mean square error. 
Exercise. Compile the model you created above. Create a custom loss function called rmse which computes the root mean squared error between y_true and y_pred. Pass this function to the model as an evaluation metric.
End of explanation
"""


TRAIN_BATCH_SIZE = 1000
NUM_TRAIN_EXAMPLES = 10000 * 5  # training dataset will repeat, wrap around
NUM_EVALS = 50  # how many times to evaluate
NUM_EVAL_EXAMPLES = 10000  # enough to get a reasonable sample

trainds = create_dataset(
    pattern="../data/taxi-train*", batch_size=TRAIN_BATCH_SIZE, mode="train"
)

evalds = create_dataset(
    pattern="../data/taxi-valid*", batch_size=1000, mode="eval"
).take(NUM_EVAL_EXAMPLES // 1000)

"""
Explanation: Train the model
To train your model, Keras provides two functions that can be used:
 1. .fit() for training a model for a fixed number of epochs (iterations on a dataset).
 2. .train_on_batch() runs a single gradient update on a single batch of data. 
The .fit() function works for various formats of data such as Numpy array, list of Tensors tf.data and Python generators. The .train_on_batch() method is for more fine-grained control over training and accepts only a single batch of data.
Our create_dataset function above generates batches of training examples, so we can use .fit. 
We start by setting up some parameters for our training job and create the data generators for the training and validation data.
We refer you the the blog post ML Design Pattern #3: Virtual Epochs for further details on why express the training in terms of NUM_TRAIN_EXAMPLES and NUM_EVALS and why, in this training code, the number of epochs is really equal to the number of evaluations we perform.
End of explanation
"""


%%time
steps_per_epoch =  # TODO: Your code here

LOGDIR = "./taxi_trained"
history =  # TODO: Your code here

"""
Explanation: There are various arguments you can set when calling the .fit method. Here x specifies the input data which in our case is a tf.data dataset returning a tuple of (inputs, targets). The steps_per_epoch parameter is used to mark the end of training for a single epoch. Here we are training for NUM_EVALS epochs. Lastly, for the callback argument we specify a Tensorboard callback so we can inspect Tensorboard after training. 
Exercise. In the cell below, you will train your model. First, define the steps_per_epoch then train your model using .fit(), saving the model training output to a variable called history.
End of explanation
"""


model.summary()

"""
Explanation: High-level model evaluation
Once we've run data through the model, we can call .summary() on the model to get a high-level summary of our network. We can also plot the training and evaluation curves for the metrics we computed above.
End of explanation
"""


RMSE_COLS = ["rmse", "val_rmse"]

pd.DataFrame(history.history)[RMSE_COLS].plot()

LOSS_COLS = ["loss", "val_loss"]

pd.DataFrame(history.history)[LOSS_COLS].plot()

"""
Explanation: Running .fit (or .fit_generator) returns a History object which collects all the events recorded during training. Similar to Tensorboard, we can plot the training and validation curves for the model loss and rmse by accessing these elements of the History object.
End of explanation
"""


model.predict(
    x={
        "pickup_longitude": tf.convert_to_tensor([-73.982683]),
        "pickup_latitude": tf.convert_to_tensor([40.742104]),
        "dropoff_longitude": tf.convert_to_tensor([-73.983766]),
        "dropoff_latitude": tf.convert_to_tensor([40.755174]),
        "passenger_count": tf.convert_to_tensor([3.0]),
    },
    steps=1,
)

"""
Explanation: Making predictions with our model
To make predictions with our trained model, we can call the predict method, passing to it a dictionary of values. The steps parameter determines the total number of steps before declaring the prediction round finished. Here since we have just one example, we set steps=1 (setting steps=None would also work). Note, however, that if x is a tf.data dataset or a dataset iterator, and steps is set to None, predict will run until the input dataset is exhausted.
End of explanation
"""


OUTPUT_DIR = "./export/savedmodel"
shutil.rmtree(OUTPUT_DIR, ignore_errors=True)
TIMESTAMP = datetime.datetime.now().strftime("%Y%m%d%H%M%S")

EXPORT_PATH = os.path.join(OUTPUT_DIR, TIMESTAMP)

tf.saved_model.save(
    # TODO: Your code here
)

!saved_model_cli show \
    --tag_set # TODO: Your code here
    --signature_def # TODO: Your code here
    --dir # TODO: Your code here

!find {EXPORT_PATH}
os.environ['EXPORT_PATH'] = EXPORT_PATH

"""
Explanation: Export and deploy our model
Of course, making individual predictions is not realistic, because we can't expect client code to have a model object in memory. For others to use our trained model, we'll have to export our model to a file, and expect client code to instantiate the model from that exported file. 
We'll export the model to a TensorFlow SavedModel format. Once we have a model in this format, we have lots of ways to "serve" the model, from a web application, from JavaScript, from mobile applications, etc.
Exercise. Use tf.saved_model.save to export the trained model to a Tensorflow SavedModel format. Reference the documentation for tf.saved_model.save as you fill in the code for the cell below.
Next, print the signature of your saved model using the SavedModel Command Line Interface command saved_model_cli. You can read more about the command line interface and the show and run commands it supports in the documentation here.
End of explanation
"""


PROJECT = !gcloud config list --format 'value(core.project)' 2>/dev/null
PROJECT = PROJECT[0]
BUCKET = PROJECT
REGION = "us-east1"
MODEL_NAME = f"taxifare_{TIMESTAMP}"
VERSION_NAME = "dnn"

os.environ["PROJECT"] = PROJECT
os.environ["BUCKET"] = BUCKET
os.environ["REGION"] = REGION
os.environ["MODEL_NAME"] = MODEL_NAME
os.environ["VERSION_NAME"] = VERSION_NAME

%%bash
gcloud config set project $PROJECT
gcloud config set ai_platform/region $REGION

%%bash
# Create GCS bucket if it doesn't exist already...
exists=$(gsutil ls -d | grep -w gs://${BUCKET}/)

if [ -n "$exists" ]; then
    echo -e "Bucket exists, let's not recreate it."
else
    echo "Creating a new GCS bucket."
    gsutil mb -l ${REGION} gs://${BUCKET}
    echo "\nHere are your current buckets:"
    gsutil ls
fi

echo "Creating $MODEL_NAME"
gcloud ai-platform models create --region=$REGION $MODEL_NAME

"""
Explanation: Deploy our model to AI Platform
Finally, we will deploy our trained model to AI Platform and see how we can make online predicitons.
End of explanation
"""


!echo "Creating $MODEL_NAME:$VERSION_NAME"
!gcloud ai-platform versions create # TODO: Your code here \
    --model=  # TODO: Your code here \
    --framework=  # TODO: Your code here \
    --python-version=  # TODO: Your code here \
    --runtime-version=  # TODO: Your code here \
    --origin=  # TODO: Your code here \
    --staging-bucket=  # TODO: Your code here

%%writefile input.json
{"pickup_longitude": -73.982683, "pickup_latitude": 40.742104,"dropoff_longitude": -73.983766,"dropoff_latitude": 40.755174,"passenger_count": 3.0}  

"""
Explanation: Exercise. Complete the code in the cell below to deploy your trained model to AI Platform using the gcloud ai-platform versions create command. Have a look at the documentation for how to create model version with gcloud.
End of explanation
"""


%%bash
gcloud ai-platform predict \
    --model  # TODO: Your code here \
    --json-instances   # TODO: Your code here \
    --version  # TODO: Your code here

"""
Explanation: Exercise. Complete the code in the cell below to call prediction on your deployed model for the example you just created in the input.json file above.
End of explanation
"""


