import os

# The Google Cloud Notebook product has specific requirements
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")

# Google Cloud Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_GOOGLE_CLOUD_NOTEBOOK:
    USER_FLAG = "--user"

"""
Explanation: <table align="left">

  <td>
    <a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/official/ml_metadata/vertex-pipelines-ml-metadata.ipynb">
      <img src="https://cloud.google.com/ml-engine/images/colab-logo-32px.png" alt="Colab logo"> Run in Colab
    </a>
  </td>
  <td>
    <a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/official/ml_metadata/vertex-pipelines-ml-metadata.ipynb">
      <img src="https://cloud.google.com/ml-engine/images/github-logo-32px.png" alt="GitHub logo">
      View on GitHub
    </a>
  </td>
</table>

Vertex AI: Track artifacts and metrics across Vertex Pipelines runs using Vertex ML Metadata
Overview
This notebook demonstrates how to track metrics and artifacts across Vertex Pipelines runs, and analyze this metadata using the Vertex AI SDK. If you'd prefer to follow a step-by-step tutorial, check out the codelab version of this notebook.
Dataset
In this notebook, we will train a model using scikit-learn to classify bean types using the Dry Beans Dataset from UCI Machine Learning. This is a tabular dataset that includes measurements and characteristics of seven different types of beans taken from images.
Objective
In this notebook, you will learn how to:

Use the Kubeflow Pipelines SDK to build an ML pipeline that runs on Vertex AI
The pipeline will create a dataset, train a scikit-learn model, and deploy the model to an endpoint
Write custom pipeline components that generate artifacts and metadata
Compare Vertex Pipelines runs, both in the Cloud console and programmatically
Trace the lineage for pipeline-generated artifacts
Query your pipeline run metadata

Costs
This tutorial uses billable components of Google Cloud:

Vertex AI
Cloud Storage

Learn about Vertex AI
pricing and Cloud Storage
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:

The Google Cloud SDK
Git
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
Run the following commands to install the Vertex AI SDK and packages used in this notebook.
End of explanation
"""


!pip3 install {USER_FLAG} google-cloud-aiplatform==1.7.0
!pip3 install {USER_FLAG} kfp==1.8.9

"""
Explanation: Install Vertex AI and Kubeflow Pipelines SDKs.
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
"""


import os

PROJECT_ID = ""

# Get your Google Cloud project ID from gcloud
if not os.getenv("IS_TESTING"):
    shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null
    PROJECT_ID = shell_output[0]
    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 services we'll be using throughout this notebook by running the cell below.


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


Enter your project ID in the project ID 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 ! as shell commands, and it interpolates Python variables prefixed with $ into these commands.
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.


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"}

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 Google Cloud Notebooks, then don't execute this code
IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists("/opt/deeplearning/metadata/env_version")

if not IS_GOOGLE_CLOUD_NOTEBOOK:
    if "google.colab" in sys.modules:
        from google.colab import auth as google_auth

        google_auth.authenticate_user()
        !gcloud config set project $PROJECT_ID

    # 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"):
        %env GOOGLE_APPLICATION_CREDENTIALS ''

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


!gcloud services enable compute.googleapis.com         \
                       containerregistry.googleapis.com  \
                       aiplatform.googleapis.com

"""
Explanation: Enable Cloud services used throughout this notebook.
Run the cell below to the enable Compute Engine, Container Registry, and Vertex AI services.
End of explanation
"""


from datetime import datetime

TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")

"""
Explanation: Timestamp
If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append it onto the name of resources you create in this tutorial.
End of explanation
"""


BUCKET_NAME = "gs://{}-bucket".format(PROJECT_ID)
!gsutil mb -l us-central1 $BUCKET_NAME # You only need to run this once

"""
Explanation: Create a Cloud Storage Bucket
To run our Vertex Pipeline, we'll need a storage bucket to store artifacts generated by our pipeline. This bucket needs to be regional. We're using the us-central1 region here, but you are welcome to use another region (just replace it throughout this lab). If you already have a bucket you can replace the BUCKET_NAME variable with the name of your bucket and skip the gsutil mb step.
End of explanation
"""


import matplotlib.pyplot as plt
import pandas as pd
# We'll use this beta library for metadata querying
from google.cloud import aiplatform, aiplatform_v1beta1
from google.cloud.aiplatform import pipeline_jobs
from kfp.v2 import compiler, dsl
from kfp.v2.dsl import (Artifact, Dataset, Input, Metrics, Model, Output,
                        OutputPath, component)

"""
Explanation: Next, make sure your compute service account has store.objectAdmin access to this bucket. Your compute service account will look something like YOUR_PROJECT_NUMBER-compute@developer.gserviceaccount.com.
Import libraries and define constants
Import required libraries.
End of explanation
"""


PATH = get_ipython().run_line_magic("env", "PATH")
%env PATH={PATH}:/home/jupyter/.local/bin
REGION = "us-central1"

PIPELINE_ROOT = f"{BUCKET_NAME}/pipeline_root/"
PIPELINE_ROOT

"""
Explanation: Define some constants
End of explanation
"""


aiplatform.init(project=PROJECT_ID, location=REGION)

"""
Explanation: Initialize the Vertex AI SDK
End of explanation
"""


@component(
    packages_to_install=["google-cloud-bigquery", "pandas", "pyarrow"],
    base_image="python:3.9",
    output_component_file="create_dataset.yaml",
)
def get_dataframe(bq_table: str, output_data_path: OutputPath("Dataset")):
    from google.cloud import bigquery

    bqclient = bigquery.Client(project=PROJECT_ID)
    table = bigquery.TableReference.from_string(bq_table)
    rows = bqclient.list_rows(table)
    dataframe = rows.to_dataframe(
        create_bqstorage_client=True,
    )
    dataframe = dataframe.sample(frac=1, random_state=2)
    dataframe.to_csv(output_data_path)

"""
Explanation: Concepts
To better understand Vertex Pipelines and ML Metadata, we'd like to introduce the following concepts:
Pipeline Run
When we use the term run, we're referring to a single execution of your pipeline in Vertex Pipelines. Each run generates artifacts, metrics, and associated metadata.
Artifact
An artifact is a resource generated by your pipeline. Artifacts could include datasets, models, endpoints, or custom resources defined in your pipeline.
Metric
A metric is a way to measure the performance of your pipeline runs and artifacts. For example, a metric could be the accuracy of a classification model artifact created in your pipeline, or the size of the dataset used to train your model.
Metadata
Metadata describes the artifacts and metrics generated by your pipeline runs. Metadata on a model, for example, could include the URL of the model artifacts, its name, and the time it was created.
Creating a 3-step pipeline with custom components
The focus of this lab is on understanding metadata from pipeline runs. In order to do that, we'll need a pipeline to run on Vertex Pipelines, which is where we'll start. Here we'll define a 3-step pipeline with the following custom components:

get_dataframe: Retrieve data from a BigQuery table and convert it into a pandas DataFrame
train_sklearn_model: Use the pandas DataFrame to train and export a scikit-learn model, along with some metrics
deploy_model: Deploy the exported scikit-learn model to an endpoint in Vertex AI

Create and define Python function based components
First, define the get_dataframe component with the code below. This component does the following:
* Creates a reference to a BigQuery table using the BigQuery client library
* Downloads the BigQuery table and converts it to a shuffled pandas DataFrame
* Exports the DataFrame to a CSV file
End of explanation
"""


@component(
    packages_to_install=["sklearn", "pandas", "joblib"],
    base_image="python:3.9",
    output_component_file="beans_model_component.yaml",
)
def sklearn_train(
    dataset: Input[Dataset], metrics: Output[Metrics], model: Output[Model]
):
    import pandas as pd
    from joblib import dump
    from sklearn.model_selection import train_test_split
    from sklearn.tree import DecisionTreeClassifier

    df = pd.read_csv(dataset.path)
    labels = df.pop("Class").tolist()
    data = df.values.tolist()
    x_train, x_test, y_train, y_test = train_test_split(data, labels)

    skmodel = DecisionTreeClassifier()
    skmodel.fit(x_train, y_train)
    score = skmodel.score(x_test, y_test)
    print("accuracy is:", score)

    metrics.log_metric("accuracy", (score * 100.0))
    metrics.log_metric("framework", "Scikit Learn")
    metrics.log_metric("dataset_size", len(df))
    dump(skmodel, model.path + ".joblib")

"""
Explanation: Next, create a component to train a scikit-learn model. This component does the following:
* Imports a CSV as a pandas DataFrame
* Splits the DataFrame into train and test sets
* Trains a scikit-learn model
* Logs metrics from the model
* Saves the model artifacts as a local model.joblib file
End of explanation
"""


@component(
    packages_to_install=["google-cloud-aiplatform"],
    base_image="python:3.9",
    output_component_file="beans_deploy_component.yaml",
)
def deploy_model(
    model: Input[Model],
    project: str,
    region: str,
    vertex_endpoint: Output[Artifact],
    vertex_model: Output[Model],
):
    from google.cloud import aiplatform

    aiplatform.init(project=project, location=region)

    deployed_model = aiplatform.Model.upload(
        display_name="beans-model-pipeline",
        artifact_uri=model.uri.replace("model", ""),
        serving_container_image_uri="us-docker.pkg.dev/vertex-ai/prediction/sklearn-cpu.0-24:latest",
    )
    endpoint = deployed_model.deploy(machine_type="n1-standard-4")

    # Save data to the output params
    vertex_endpoint.uri = endpoint.resource_name
    vertex_model.uri = deployed_model.resource_name

"""
Explanation: Finally, our last component will take the trained model from the previous step, upload it to Vertex AI, and deploy it to an endpoint:
End of explanation
"""


@dsl.pipeline(
    # Default pipeline root. You can override it when submitting the pipeline.
    pipeline_root=PIPELINE_ROOT,
    # A name for the pipeline.
    name="mlmd-pipeline",
)
def pipeline(
    bq_table: str = "",
    output_data_path: str = "data.csv",
    project: str = PROJECT_ID,
    region: str = REGION,
):
    dataset_task = get_dataframe(bq_table)

    model_task = sklearn_train(dataset_task.output)

    deploy_model(model=model_task.outputs["model"], project=project, region=region)

"""
Explanation: Define and compile the pipeline
End of explanation
"""


compiler.Compiler().compile(pipeline_func=pipeline, package_path="mlmd_pipeline.json")

"""
Explanation: The following will generate a JSON file that you'll use to run the pipeline:
End of explanation
"""


from datetime import datetime

TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")

"""
Explanation: Start two pipeline runs
Next we'll kick off two runs of our pipeline. First let's define a timestamp to use for our pipeline job IDs:
End of explanation
"""


run1 = pipeline_jobs.PipelineJob(
    display_name="mlmd-pipeline",
    template_path="mlmd_pipeline.json",
    job_id="mlmd-pipeline-small-{}".format(TIMESTAMP),
    parameter_values={"bq_table": "sara-vertex-demos.beans_demo.small_dataset"},
    enable_caching=True,
)

"""
Explanation: Our pipeline takes one parameter when we run it: the bq_table we want to use for training data. This pipeline run will use a smaller version of the beans dataset:
End of explanation
"""


run2 = pipeline_jobs.PipelineJob(
    display_name="mlmd-pipeline",
    template_path="mlmd_pipeline.json",
    job_id="mlmd-pipeline-large-{}".format(TIMESTAMP),
    parameter_values={"bq_table": "sara-vertex-demos.beans_demo.large_dataset"},
    enable_caching=True,
)

"""
Explanation: Next, create another pipeline run using a larger version of the same dataset.
End of explanation
"""


run1.submit()

"""
Explanation: Finally, kick off pipeline executions for both runs. It's best to do this in two separate notebook cells so you can see the output for each run.
End of explanation
"""


run2.submit()

"""
Explanation: Then, kick off the second run:
End of explanation
"""


df = aiplatform.get_pipeline_df(pipeline="mlmd-pipeline")
print(df)

"""
Explanation: After running this cell, you'll see a link to view each pipeline in the Vertex AI console. Open that link to see more details on your pipeline.
These pipeline runs will take 10-15 minutes to complete.
Comparing pipeline runs
Now that you have two pipeline completed pipeline runs, we're ready to take a closer look at pipeline metrics using the Vertex AI SDK.
For guidance on inspecting pipeline artifacts and metadata in the Vertex AI Console, see this codelab.
You can use the aiplatform.get_pipeline_df() method to access run metadata. Here, we'll get metadata for the last two runs of the same pipeline and load it into a Pandas DataFrame. The mlmd-pipeline parameter here refers to the name we gave our pipeline in our pipeline definition:
End of explanation
"""


plt.plot(df["metric.dataset_size"], df["metric.accuracy"], label="Accuracy")
plt.title("Accuracy and dataset size")
plt.legend(loc=4)
plt.show()

"""
Explanation: We've only executed our pipeline twice here, but you can imagine how many metrics you'd have with more executions. Next, we'll create a custom visualization with matplotlib to see the relationship between our model's accuracy and the amount of data used for training. Run the following to generate a graph:
End of explanation
"""


API_ENDPOINT = "{}-aiplatform.googleapis.com".format(REGION)
metadata_client = aiplatform_v1beta1.MetadataServiceClient(
    client_options={"api_endpoint": API_ENDPOINT}
)

"""
Explanation: Querying pipeline metrics
In addition to getting a DataFrame of all pipeline metrics, you may want to programmatically query artifacts created in your ML system. From there you could create a custom dashboard or let others in your organizaiton get details on specific artifacts.
Getting all Model artifacts
To query artifacts in this way, we'll create a MetadataServiceClient:
End of explanation
"""


MODEL_FILTER = 'schema_title = "system.Model"'
artifact_request = aiplatform_v1beta1.ListArtifactsRequest(
    parent="projects/{}/locations/{}/metadataStores/default".format(PROJECT_ID, REGION),
    filter=MODEL_FILTER,
)
model_artifacts = metadata_client.list_artifacts(artifact_request)

"""
Explanation: Next, we'll make a list_artifacts request to that endpoint and pass a filter indicating which artifacts we'd like in our response. First, let's get all the artifacts in our project that are models. To do that, run the following in your notebook:
End of explanation
"""


LIVE_FILTER = 'create_time > "2021-08-10T00:00:00-00:00" AND state = LIVE'
artifact_req = {
    "parent": "projects/{}/locations/{}/metadataStores/default".format(
        PROJECT_ID, REGION
    ),
    "filter": LIVE_FILTER,
}
live_artifacts = metadata_client.list_artifacts(artifact_req)

"""
Explanation: The resulting model_artifacts response contains an iterable object for each model artifact in your project, along with associated metadata for each model.
Filtering objects and displaying in a DataFrame
It would be handy if we could more easily visualize the resulting artifact query. Next, let's get all artifacts created after August 10, 2021 with a LIVE state. After we run this request, we'll display the results in a pandas DataFrame. First, execute the request:
End of explanation
"""


data = {"uri": [], "createTime": [], "type": []}

for i in live_artifacts:
    data["uri"].append(i.uri)
    data["createTime"].append(i.create_time)
    data["type"].append(i.schema_title)

df = pd.DataFrame.from_dict(data)
print(df)

"""
Explanation: Then, display the results in a DataFrame:
End of explanation
"""


