%%writefile requirements.txt
joblib~=1.0
numpy~=1.20
scikit-learn~=0.24
google-cloud-storage>=1.26.0,<2.0.0dev

# Required in Docker serving container
%pip install -U -r requirements.txt

# For local FastAPI development and running
%pip install -U "uvicorn[standard]>=0.12.0,<0.14.0" fastapi~=0.63

# AI Platform (Classic) client library
%pip install -U google-api-python-client

"""
Explanation: <table align="left">
  <td>
    <a href="https://github.com/GoogleCloudPlatform/ai-platform-samples/blob/main/ai-platform/notebooks/unofficial/AI_Platform_Custom_Container_Prediction_sklearn.ipynb">
      <img src="https://cloud.google.com/ml-engine/images/github-logo-32px.png" alt="GitHub logo">
      View on GitHub
    </a>
  </td>
</table>

Overview
This tutorial walks through building a custom container to serve a scikit-learn model on AI Platform Predictions. You will use the FastAPI Python web server framework to create a prediction and health endpoint.
You will also cover incorporating a pre-processor from training into your online serving.
Dataset
This tutorial uses R.A. Fisher's Iris dataset, a small dataset that is popular for trying out machine learning techniques. Each instance has four numerical features, which are different measurements of a flower, and a target label that
marks it as one of three types of iris: Iris setosa, Iris versicolour, or Iris virginica.
This tutorial uses the copy of the Iris dataset included in the
scikit-learn library.
Objective
The goal is to:
- Train a model that uses a flower's measurements as input to predict what type of iris it is.
- Save the model and its serialized pre-processor
- Build a FastAPI server to handle predictions and health checks
- Build a custom container with model artifacts
- Upload and deploy custom container to AI Platform Prediction
This tutorial focuses more on deploying this model with AI Platform than on
the design of the model itself.
Costs
This tutorial uses billable components of Google Cloud:

AI Platform 

Learn about AI Platform (Classic)
pricing, and use the Pricing
Calculator
to generate a cost estimate based on your projected usage.
Set up your local development environment
If you are using Colab or AI Platform Notebooks, your environment already meets
all the requirements to run this notebook. You can skip this step.
Otherwise, make sure your environment meets this notebook's requirements.
You need the following:

Docker
Git
Google Cloud SDK (gcloud)
Python 3
virtualenv
Jupyter notebook running in a virtual environment with Python 3

The Google Cloud guide to Setting up a Python development
environment and the Jupyter
installation guide provide detailed instructions
for meeting these requirements. The following steps provide a condensed set of
instructions:


Install and initialize the Cloud SDK.


Install Python 3.


Install
   virtualenv
   and create a virtual environment that uses Python 3. Activate the virtual environment.


To install Jupyter, run pip install jupyter on the
command-line in a terminal shell.


To launch Jupyter, run jupyter notebook on the command-line in a terminal shell.


Open this notebook in the Jupyter Notebook Dashboard.


Install additional packages
Install additional package dependencies not installed in your notebook environment, such as NumPy, Scikit-learn, FastAPI, Uvicorn, and joblib. Use the latest major GA version of each package.
End of explanation
"""


# Automatically restart kernel after installs
import os

if not os.getenv("IS_TESTING"):
    # Automatically restart kernel after installs
    import IPython

    app = IPython.Application.instance()
    app.kernel.do_shutdown(True)

"""
Explanation: Restart the kernel
After you install the additional packages, you need to restart the notebook kernel so it can find the packages.
End of explanation
"""


# Get your Google Cloud project ID from gcloud
shell_output=!gcloud config list --format 'value(core.project)' 2>/dev/null

try:
    PROJECT_ID = shell_output[0]
except IndexError:
    PROJECT_ID = None

print("Project ID:", PROJECT_ID)

"""
Explanation: Before you begin
Set up your Google Cloud project
The following steps are required, regardless of your notebook environment.


Select or create a Google Cloud project. When you first create an account, you get a $300 free credit towards your compute/storage costs.


Make sure that billing is enabled for your project.


Enable the AI Platform (Classic) API and Compute Engine API.


If you are running this notebook locally, you will need to install the Cloud SDK.


Enter your project ID in the cell below. Then run the cell to make sure the
Cloud SDK uses the right project for all the commands in this notebook.


Note: Jupyter runs lines prefixed with ! or % as shell commands, and it interpolates Python variables with $ or {} into these commands.
Set your project ID
If you don't know your project ID, you may be able to get your project ID using gcloud.
End of explanation
"""


if PROJECT_ID == "" or PROJECT_ID is None:
    PROJECT_ID = "[your-project-id]"  # @param {type:"string"}

"""
Explanation: Otherwise, set your project ID here.
End of explanation
"""


import os
import sys

# If you are running this notebook in Colab, run this cell and follow the
# instructions to authenticate your GCP account. This provides access to your
# Cloud Storage bucket and lets you submit training jobs and prediction
# requests.

# If on AI Platform, then don't execute this code
if not os.path.exists("/opt/deeplearning/metadata/env_version"):
    if "google.colab" in sys.modules:
        from google.colab import auth as google_auth

        google_auth.authenticate_user()

    # If you are running this notebook locally, replace the string below with the
    # path to your service account key and run this cell to authenticate your GCP
    # account.
    elif not os.getenv("IS_TESTING") and not os.getenv(
        "GOOGLE_APPLICATION_CREDENTIALS"
    ):
        %env GOOGLE_APPLICATION_CREDENTIALS ''

"""
Explanation: Authenticate your Google Cloud account
If you are using AI Platform Notebooks, your environment is already
authenticated. Skip this step.
If you are using Colab, run the cell below and follow the instructions
when prompted to authenticate your account via oAuth.
Otherwise, follow these steps:


In the Cloud Console, go to the Create service account key
   page.


Click Create service account.


In the Service account name field, enter a name, and
   click Create.


In the Grant this service account access to project section, click the Role drop-down list. Type "AI Platform"
into the filter box, and select
   AI Platform Administrator. Type "Storage Object Admin" into the filter box, and select Storage Object Admin.


Click Create. A JSON file that contains your key downloads to your
local environment.


Enter the path to your service account key as the
GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell.
End of explanation
"""


REGION = "us-central1"  # @param {type:"string"}
MODEL_ARTIFACT_DIR = "custom-container-prediction-model"  # @param {type:"string"}
REPOSITORY = "custom-container-prediction-sklearn"  # @param {type:"string"}
IMAGE = "sklearn-fastapi-server"  # @param {type:"string"}
MODEL_NAME = "sklearn_custom_container"  # @param {type:"string"}
VERSION_NAME = "v1"  # @param {type:"string"}

"""
Explanation: Configure project and resource names
End of explanation
"""


BUCKET_NAME = "gs://[your-bucket-name]"  # @param {type:"string"}

"""
Explanation: REGION - Used for operations
throughout the rest of this notebook. Make sure to choose a region where Cloud
AI Platform services are
available. You may
not use a Multi-Regional Storage bucket for training with AI Platform.
MODEL_ARTIFACT_DIR - Folder directory path to your model artifacts within a Cloud Storage bucket, for example: "my-models/fraud-detection/trial-4"
REPOSITORY - Name of the Artifact Repository to create or use.
IMAGE - Name of the container image that will be pushed.
MODEL_NAME - Name of AI Platform Model.
VERSION_NAME - Name of AI Platform Model version.
Create a Cloud Storage bucket
The following steps are required, regardless of your notebook environment.
To update your model artifacts without re-building the container, you must upload your model
artifacts and any custom code to Cloud Storage.
Set the name of your Cloud Storage bucket below. It must be unique across all
Cloud Storage buckets.
End of explanation
"""


! gsutil mb -l $REGION $BUCKET_NAME

"""
Explanation: Only if your bucket doesn't already exist: Run the following cell to create your Cloud Storage bucket.
End of explanation
"""


! gsutil ls -al $BUCKET_NAME

"""
Explanation: Finally, validate access to your Cloud Storage bucket by examining its contents:
End of explanation
"""


%mkdir app

%%writefile app/preprocess.py
import numpy as np

class MySimpleScaler(object):
    def __init__(self):
        self._means = None
        self._stds = None

    def preprocess(self, data):
        if self._means is None:  # during training only
            self._means = np.mean(data, axis=0)

        if self._stds is None:  # during training only
            self._stds = np.std(data, axis=0)
            if not self._stds.all():
                raise ValueError("At least one column has standard deviation of 0.")

        return (data - self._means) / self._stds


"""
Explanation: Write your pre-processor
Scaling training data so each numerical feature column has a mean of 0 and a standard deviation of 1 can improve your model.
Create preprocess.py, which contains a class to do this scaling:
End of explanation
"""


%cd app/

import pickle

import joblib
from preprocess import MySimpleScaler
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier

iris = load_iris()
scaler = MySimpleScaler()

X = scaler.preprocess(iris.data)
y = iris.target

model = RandomForestClassifier()
model.fit(X, y)

joblib.dump(model, "model.joblib")
with open("preprocessor.pkl", "wb") as f:
    pickle.dump(scaler, f)

"""
Explanation: Train and store model with pre-processor
Next, use preprocess.MySimpleScaler to preprocess the iris data, then train a model using scikit-learn.
At the end, export your trained model as a joblib (.joblib) file and export your MySimpleScaler instance as a pickle (.pkl) file:
End of explanation
"""


!gsutil cp model.joblib preprocessor.pkl {BUCKET_NAME}/{MODEL_ARTIFACT_DIR}/
%cd ..

"""
Explanation: Upload model artifacts and custom code to Cloud Storage
Before you can deploy your model for serving, AI Platform needs access to the following files in Cloud Storage:

model.joblib (model artifact)
preprocessor.pkl (model artifact)

Run the following commands to upload your files:
End of explanation
"""


%%writefile app/main.py
from fastapi import FastAPI, Request

import joblib
import json
import numpy as np
import pickle
import os

from google.cloud import storage
from preprocess import MySimpleScaler
from sklearn.datasets import load_iris


app = FastAPI()
gcs_client = storage.Client()

with open("preprocessor.pkl", 'wb') as preprocessor_f, open("model.joblib", 'wb') as model_f:
    gcs_client.download_blob_to_file(
        f"{os.environ['AIP_STORAGE_URI']}/preprocessor.pkl", preprocessor_f
    )
    gcs_client.download_blob_to_file(
        f"{os.environ['AIP_STORAGE_URI']}/model.joblib", model_f
    )

with open("preprocessor.pkl", "rb") as f:
    preprocessor = pickle.load(f)

_class_names = load_iris().target_names
_model = joblib.load("model.joblib")
_preprocessor = preprocessor


@app.get(os.environ['AIP_HEALTH_ROUTE'], status_code=200)
def health():
    return {}


@app.post(os.environ['AIP_PREDICT_ROUTE'])
async def predict(request: Request):
    body = await request.json()

    instances = body["instances"]
    inputs = np.asarray(instances)
    preprocessed_inputs = _preprocessor.preprocess(inputs)
    outputs = _model.predict(preprocessed_inputs)

    return {"predictions": [_class_names[class_num] for class_num in outputs]}


"""
Explanation: Build a FastAPI server
End of explanation
"""


%%writefile app/prestart.sh
#!/bin/bash
export PORT=$AIP_HTTP_PORT

"""
Explanation: Add pre-start script
FastAPI will execute this script before starting up the server. The PORT environment variable is set to equal AIP_HTTP_PORT in order to run FastAPI on same the port expected by AI Platform Prediction.
End of explanation
"""


%%writefile instances.json
{
    "instances": [
        [6.7, 3.1, 4.7, 1.5],
        [4.6, 3.1, 1.5, 0.2]
    ]
}

"""
Explanation: Store test instances to use later
To learn more about formatting input instances in JSON, read the documentation.
End of explanation
"""


# NOTE: Copy in credentials to run locally, this step can be skipped for deployment
%cp $GOOGLE_APPLICATION_CREDENTIALS app/credentials.json

"""
Explanation: Build and push container to Artifact Registry
Build your container
Optionally copy in your credentials to run the container locally.
End of explanation
"""


%%writefile Dockerfile

FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7

COPY ./app /app
COPY requirements.txt requirements.txt

RUN pip install -r requirements.txt

"""
Explanation: Write the Dockerfile, using tiangolo/uvicorn-gunicorn-fastapi as a base image. This will automatically run FastAPI for you using Gunicorn and Uvicorn. Visit the FastAPI docs to read more about deploying FastAPI with Docker.
End of explanation
"""


!docker build \
    --tag={REGION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY}/{IMAGE} \
    .

"""
Explanation: Build the image and tag the Artifact Registry path that you will push to.
End of explanation
"""


!docker rm local-iris
!docker run -d -p 80:8080 \
    --name=local-iris \
    -e AIP_HTTP_PORT=8080 \
    -e AIP_HEALTH_ROUTE=/health \
    -e AIP_PREDICT_ROUTE=/predict \
    -e AIP_STORAGE_URI={BUCKET_NAME}/{MODEL_ARTIFACT_DIR} \
    -e GOOGLE_APPLICATION_CREDENTIALS=credentials.json \
    {REGION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY}/{IMAGE}

!curl localhost/health

!curl -X POST \
  -d @instances.json \
  -H "Content-Type: application/json; charset=utf-8" \
  localhost/predict

!docker stop local-iris

"""
Explanation: Run and test the container locally (optional)
Run the container locally in detached mode and provide the environment variables that the container requires. These env vars will be provided to the container by AI Platform Prediction once deployed. Test the /health and /predict routes, then stop the running image.
End of explanation
"""


!gcloud beta artifacts repositories create {REPOSITORY} \
 --repository-format=docker \
 --location=$REGION

!gcloud auth configure-docker {REGION}-docker.pkg.dev

!docker push {REGION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY}/{IMAGE}

"""
Explanation: Push the container to artifact registry
Configure Docker to access Artifact Registry. Then push your container image to your Artifact Registry repository.
End of explanation
"""


!gcloud beta ai-platform models create $MODEL_NAME \
    --region=$REGION \
    --enable-logging \
    --enable-console-logging

"""
Explanation: Deploy to AI Platform (Classic)
Use gcloud CLI to create your model and model version.
Create the model
End of explanation
"""


!echo "deploymentUri: {BUCKET_NAME}/{MODEL_ARTIFACT_DIR}" > config.yaml

!gcloud beta ai-platform versions create $VERSION_NAME \
    --region=$REGION \
    --model=$MODEL_NAME \
    --machine-type=n1-standard-4 \
    --config=config.yaml \
    --image={REGION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY}/{IMAGE}

"""
Explanation: Create the model version
After this step completes, the model is deployed and ready for online prediction.
End of explanation
"""


!curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @instances.json \
    https://{REGION}-ml.googleapis.com/v1/projects/{PROJECT_ID}/models/{MODEL_NAME}/versions/{VERSION_NAME}:predict

"""
Explanation: Send predictions
Using REST
End of explanation
"""


from google.api_core.client_options import ClientOptions
from googleapiclient import discovery

client_options = ClientOptions(api_endpoint=f"https://{REGION}-ml.googleapis.com")

service = discovery.build("ml", "v1", client_options=client_options)

response = (
    service.projects()
    .predict(
        name=f"projects/{PROJECT_ID}/models/{MODEL_NAME}/versions/{VERSION_NAME}",
        body={"instances": [[6.7, 3.1, 4.7, 1.5], [4.6, 3.1, 1.5, 0.2]]},
    )
    .execute()
)

if "error" in response:
    raise RuntimeError(response["error"])
else:
    print(response)

"""
Explanation: Using Python SDK
End of explanation
"""


!gcloud beta ai-platform predict \
  --region=$REGION \
  --model=$MODEL_NAME \
  --json-request=instances.json

"""
Explanation: Using gcloud CLI
End of explanation
"""


# Delete the model version
!gcloud ai-platform versions delete $VERSION_NAME \
    --region=$REGION \
    --model=$MODEL_NAME \
    --quiet

# Delete the model
!gcloud ai-platform models delete $MODEL_NAME \
    --region=$REGION \
    --quiet

# Delete the container image from Artifact Registry
!gcloud artifacts docker images delete \
    --quiet \
    --delete-tags \
    {REGION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY}/{IMAGE}

"""
Explanation: Cleaning up
To clean up all Google Cloud resources used in this project, you can delete the Google Cloud
project you used for the tutorial.
Otherwise, you can delete the individual resources you created in this tutorial:
End of explanation
"""


