# Set your output and project. !!!Must Do before you can proceed!!!
project =  'Your-Gcp-Project-ID'                          #'Your-GCP-Project-ID'
model_name = 'model-name'                                      # Model name matching TF_serve naming requirements       
import time
ts = int(time.time())
model_version = str(ts)                                            # Here we use timestamp as version to avoid conflict 
output = 'Your-Gcs-Path'     # A GCS bucket for asset outputs
KUBEFLOW_DEPLOYER_IMAGE = 'gcr.io/ml-pipeline/ml-pipeline-kubeflow-deployer:1.8.0-alpha.0'

model_path = '%s/%s' % (output,model_name)               
model_version_path = '%s/%s/%s' % (output,model_name,model_version)

"""
Explanation: KubeFlow Pipelines Serving Component
In this notebook, we will demo:

Saving a Keras model in a format compatible with TF Serving
Creating a pipeline to serve a trained model within a KubeFlow cluster

Reference documentation:
* https://www.tensorflow.org/tfx/serving/architecture
* https://www.tensorflow.org/beta/guide/keras/saving_and_serializing
* https://www.kubeflow.org/docs/components/serving/tfserving_new/
Setup
End of explanation
"""


import tensorflow as tf

model = tf.keras.applications.NASNetMobile(input_shape=None,
                                   include_top=True,
                                   weights='imagenet',
                                   input_tensor=None,
                                   pooling=None,
                                   classes=1000)

"""
Explanation: Load a Keras Model
Loading a pretrained Keras model to use as an example.
End of explanation
"""


tf.keras.experimental.export_saved_model(model, model_version_path)

"""
Explanation: Saved the Model for TF-Serve
Save the model using keras export_saved_model function. Note that specifically for TF-Serve the output directory should be structure as model_name/model_version/saved_model.
End of explanation
"""


def kubeflow_deploy_op():
    return dsl.ContainerOp(
        name = 'deploy',
        image = KUBEFLOW_DEPLOYER_IMAGE,
        arguments = [
            '--model-export-path', model_path,
            '--server-name', model_name,
        ]
    )

from kfp.deprecated import dsl, Client

# The pipeline definition
@dsl.pipeline(
    name='sample-model-deployer',
    description='Sample for deploying models using KFP model serving component'
)
def model_server():
    deploy = kubeflow_deploy_op()

"""
Explanation: Create a pipeline using KFP TF-Serve component
End of explanation
"""


Client().create_run_from_pipeline_func(model_server, arguments={})

#vvvvvvvvv This link leads to the run information page. (Note: There is a bug in JupyterLab that modifies the URL and makes the link stop working)

"""
Explanation: Submit pipeline for execution on Kubeflow Pipelines cluster
End of explanation
"""


