<jupyter_start><jupyter_text>E2E ML on GCP: MLOps stage 1 : formalization: get started with Vertex AI Data Labeling                  View on GitHub                  Open in Vertex AI Workbench        OverviewThis tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 1 : data management: get started with Vertex AI Data Labeling service.  DatasetThe dataset used for this tutorial is the [Flowers dataset](https://www.tensorflow.org/datasets/catalog/tf_flowers) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). The version of the dataset you will use in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the type of flower an image is from a class of five flowers: daisy, dandelion, rose, sunflower, or tulip.  ObjectiveIn this tutorial, you learn how to use the `Vertex AI Data Labeling` service/This tutorial uses the following Google Cloud ML services:- `Vertex AI Data Labeling`- `Vertex AI Dataset`The steps performed include:- Create a Specialist Pool for data labelers.- Create a data labeling job.- Submit the data labeling job.- List data labeling jobs.- Cancel a data labeling job.Learn more about [Request a Vertex AI Data Labeling job](https://cloud.google.com/vertex-ai/docs/datasets/data-labeling-job).  InstallationInstall the following packages to execute this notebook.<jupyter_code>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"

# Install the packages
! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG
! pip3 install --upgrade google-cloud-storage<jupyter_output><empty_output><jupyter_text>Restart the KernelOnce you've installed the Vertex SDK and Google *cloud-storage*, you need to restart the notebook kernel so it can find the packages.<jupyter_code>import os

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

    app = IPython.Application.instance()
    app.kernel.do_shutdown(True)<jupyter_output><empty_output><jupyter_text>Before you begin GPU run-time*Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select* **Runtime > Change Runtime Type > GPU** Set up your GCP project**The following steps are required, regardless of your notebook environment.**1. [Select or create a GCP project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.2. [Make sure that billing is enabled for your project.](https://cloud.google.com/billing/docs/how-to/modify-project)3. [Enable the Vertex APIs and Compute Engine APIs.](https://console.cloud.google.com/flows/enableapi?apiid=ml.googleapis.com,compute_component)4. [Google Cloud SDK](https://cloud.google.com/sdk) is already installed in Google Cloud Notebooks.5. Enter your project ID in the cell below. Then run the  cell to make sure theCloud 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.<jupyter_code>PROJECT_ID = "[your-project-id]"  # @param {type:"string"}
if PROJECT_ID == "" or PROJECT_ID is None or PROJECT_ID == "[your-project-id]":
    # Get your GCP project id from gcloud
    shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null
    PROJECT_ID = shell_output[0]
    print("Project ID:", PROJECT_ID)
! gcloud config set project $PROJECT_ID<jupyter_output><empty_output><jupyter_text>RegionYou can also change the `REGION` variable, which is used for operationsthroughout the rest of this notebook.  Below are regions supported for Vertex AI. We recommend that you choose the region closest to you.- Americas: `us-central1`- Europe: `europe-west4`- Asia Pacific: `asia-east1`You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services.Learn more about [Vertex AI regions](https://cloud.google.com/vertex-ai/docs/general/locations).<jupyter_code>REGION = "[your-region]"  # @param {type: "string"}

if REGION == "[your-region]":
    REGION = "us-central1"<jupyter_output><empty_output><jupyter_text>TimestampIf 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 onto the name of resources which will be created in this tutorial.<jupyter_code>from datetime import datetime

TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")<jupyter_output><empty_output><jupyter_text>EmailYou need an email address to send labeling job request to. This is the email address will be the manager of the data labeling specialist pool.In this tutorial, if you don't specify an email address, the email address associated with your project ID will be used.<jupyter_code>EMAIL = "[your-email-address]"  # @param {type: "string"}
if EMAIL == "[your-email-address]":
    shell_output = ! gcloud auth list 2>/dev/null
    EMAIL = shell_output[3].replace("*", "").strip()

print(EMAIL)<jupyter_output><empty_output><jupyter_text>Authenticate your GCP account**If you are using Google Cloud Notebooks**, your environment is alreadyauthenticated. Skip this step.*Note: If you are on an Vertex AI Workbench notebook and run the cell, the cell knows to skip executing the authentication steps.*<jupyter_code>import os
import sys

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

# If on Vertex, 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 tutorial in a notebook locally, replace the string
    # below with the path to your service account key and run this cell to
    # authenticate your Google Cloud account.
    else:
        %env GOOGLE_APPLICATION_CREDENTIALS your_path_to_credentials.json

    # Log in to your account on Google Cloud
    ! gcloud auth login<jupyter_output><empty_output><jupyter_text>Create a Cloud Storage bucket**The following steps are required, regardless of your notebook environment.**This tutorial is designed to use training data that is in a public Cloud Storage bucket and a local Cloud Storage bucket for your batch predictions. You may alternatively use your own training data that you have stored in a local Cloud Storage bucket.Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets.<jupyter_code>BUCKET_NAME = "[your-bucket-name]"  # @param {type:"string"}
BUCKET_URI = f"gs://{BUCKET_NAME}"
if BUCKET_URI == "" or BUCKET_URI is None or BUCKET_URI == "gs://[your-bucket-name]":
    BUCKET_URI = "gs://" + PROJECT_ID + "aip-" + TIMESTAMP<jupyter_output><empty_output><jupyter_text>**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket.<jupyter_code>! gsutil mb -l $REGION $BUCKET_URI<jupyter_output><empty_output><jupyter_text>Finally, validate access to your Cloud Storage bucket by examining its contents:<jupyter_code>! gsutil ls -al $BUCKET_URI<jupyter_output><empty_output><jupyter_text>Set up variablesNext, set up some variables used throughout the tutorial. Import libraries and define constants  Import Vertex AI SDKImport the Vertex AI SDK into our Python environment.<jupyter_code>import os
import sys
import time

import google.cloud.aiplatform as aip
from google.cloud.aiplatform import gapic
from google.protobuf.json_format import ParseDict
from google.protobuf.struct_pb2 import Value<jupyter_output><empty_output><jupyter_text>Vertex AI constantsSetup up the following constants for Vertex AI:- `API_ENDPOINT`: The Vertex AI API service endpoint for dataset, model, job, pipeline and endpoint services.- `PARENT`: The Vertex AI location root path for dataset, model and endpoint resources.<jupyter_code># API Endpoint
API_ENDPOINT = "{}-aiplatform.googleapis.com".format(REGION)

# Vertex AI location root path for your dataset, model and endpoint resources
PARENT = "projects/" + PROJECT_ID + "/locations/" + REGION<jupyter_output><empty_output><jupyter_text>Schema constantsNext, setup constants for schemas related image classification datasets:- Data Labeling (Annotations) Schemas: Tells the managed dataset service how the data is labeled (annotated).<jupyter_code># Image labeling task
LABELING_SCHEMA_IMAGE = "gs://google-cloud-aiplatform/schema/datalabelingjob/inputs/image_classification_1.0.0.yaml"<jupyter_output><empty_output><jupyter_text>Create clientsThe Vertex AI SDK works as a client/server model. On your side (the Python script) you create a client that sends requests and receives responses from the server (Vertex AI).You use several clients in this tutorial, so set them all up upfront.- Specialist pool service for specialist pools- Job Service for data labeling<jupyter_code># client options same for all services
client_options = {"api_endpoint": API_ENDPOINT}

clients = {}
clients["job"] = gapic.JobServiceClient(client_options=client_options)

# add client for specialist pool
clients["specialist_pool"] = gapic.SpecialistPoolServiceClient(
    client_options=client_options
)

for client in clients.items():
    print(client)<jupyter_output><empty_output><jupyter_text>Create a CSV file for examples to labelNext, you will create a CSV file for the examples you are requesting to be labeled. In this example, the examples to label are images. For each row in the CSV file, you specify the Cloud Storage location of the image to label.<jupyter_code>import tensorflow as tf

LABELING_FILES = [
    "gs://cloud-samples-data/vision/automl_classification/flowers/daisy/100080576_f52e8ee070_n.jpg",
    "gs://cloud-samples-data/vision/automl_classification/flowers/daisy/102841525_bd6628ae3c.jpg",
]

IMPORT_FILE = BUCKET_URI + "/labeling.csv"
with tf.io.gfile.GFile(IMPORT_FILE, "w") as f:
    for lf in LABELING_FILES:
        f.write(lf + "\n")

! gsutil cat $IMPORT_FILE<jupyter_output><empty_output><jupyter_text>Create a unlabeled datasetNext, you create a dataset for the data to be labeled.<jupyter_code>dataset = aip.ImageDataset.create("labeling_" + TIMESTAMP)
print(dataset)<jupyter_output><empty_output><jupyter_text>Import the unlabeled dataNow, import the unlabeled data to the dataset, i.e., the examples to be labeled.<jupyter_code>dataset.import_data(
    gcs_source=[IMPORT_FILE],
    import_schema_uri=aip.schema.dataset.ioformat.image.single_label_classification,
)<jupyter_output><empty_output><jupyter_text>Create a new data specialist poolYou data labeling job will be sent to a data specialist pool. You may have one or more multiple specialist pools. In this next step, you create a new specialist pool with the method `create_specialist_pool()`. The request includes the parameters:- `name`: The resource name of the specialist pool.- `display_name`: A human readable name for the specialist pool.- `specialist_manager_emails`: A list of the email addresses of the manager(s) for the specialist pool.*Note:* You can use an existing specialist pool if one already existed.<jupyter_code>specialist_pool = {
    "name": "labeling_" + TIMESTAMP,
    "display_name": "labeling_" + TIMESTAMP,
    "specialist_manager_emails": [EMAIL],
}

request = clients["specialist_pool"].create_specialist_pool(
    parent=PARENT, specialist_pool=specialist_pool
)

result = request.result()
print(result)

specialist_name = result.name

specialist_id = specialist_name.split("/")[-1]

print(specialist_name)<jupyter_output><empty_output><jupyter_text>Create data labeling jobNow that you have a specialist pool, you can send a data labeling request using the `create_data_labeling_job()` method.Your request will consist of the following:- The Vertex AI Dataset with the unlabeled data.- Instructions for labeling.<jupyter_code># create placeholder file for instructions for data labeling
! echo "this is instruction" >> instruction.txt | gsutil cp instruction.txt $BUCKET_URI
LABLEING_SCHEMA = LABELING_SCHEMA_IMAGE
INSTRUCTION_FILE = BUCKET_URI + "/instruction.txt"

inputs = ParseDict({"annotation_specs": ["rose"]}, Value())

data_labeling_job = {
    "display_name": "labeling_" + TIMESTAMP,
    "datasets": [dataset.resource_name],
    "labeler_count": 1,
    "instruction_uri": INSTRUCTION_FILE,
    "inputs_schema_uri": LABLEING_SCHEMA,
    "inputs": inputs,
    "annotation_labels": {
        "aiplatform.googleapis.com/annotation_set_name": "data_labeling_job_specialist_pool"
    },
    "specialist_pools": [specialist_name],
}

print(data_labeling_job)

request = clients["job"].create_data_labeling_job(
    parent=PARENT, data_labeling_job=data_labeling_job
)

print(request)

labeling_task_name = request.name

print(labeling_task_name)<jupyter_output><empty_output><jupyter_text>Get a data labeling jobYou can get information on your data labeling job using the `get_data_labeling_job()` method, with the following parameters:- `name`: The name of the labeling task.<jupyter_code>request = clients["job"].get_data_labeling_job(name=labeling_task_name)
print(request)<jupyter_output><empty_output><jupyter_text>Cancel a data labeling taskYou can cancel a data labeling request using the `cancel_data_labeling_job()` method, with the following parameters:- `name`: The name of the labeling task.<jupyter_code>request = clients["job"].cancel_data_labeling_job(name=labeling_task_name)
print(request)<jupyter_output><empty_output><jupyter_text>Wait for labeling job to be canceledThe cancel request is asyncrhonous. The code below polls on the labeling job status until the status is CANCELED.<jupyter_code>while True:
    response = clients["job"].get_data_labeling_job(name=labeling_task_name)
    if response.state == gapic.JobState.JOB_STATE_CANCELLED:
        print("Labeling job CANCELED")
        break
    else:
        print("Canceling labeling job:", response.state)
        time.sleep(60)<jupyter_output><empty_output><jupyter_text>Cleaning upTo clean up all GCP resources used in this project, you can [delete the GCPproject](https://cloud.google.com/resource-manager/docs/creating-managing-projectsshutting_down_projects) you used for the tutorial.Otherwise, you can delete the individual resources you created in this tutorial.<jupyter_code>delete_dataset = True
delete_job = True
delete_specialist_pool = True
delete_bucket = True

# Delete the dataset using the Vertex AI fully qualified identifier for the dataset
try:
    if delete_dataset:
        dataset.delete()
except Exception as e:
    print(e)

# Delete the labeling job using the Vertex AI fully qualified identifier for the dataset
try:
    if delete_job:
        request = clients["job"].delete_data_labeling_job(name=labeling_task_name)
except Exception as e:
    print(e)

# Delete the specialist pool using the Vertex AI fully qualified identifier for the dataset
try:
    if delete_specialist_pool:
        clients["specialist_pool"].delete_specialist_pool(name=specialist_name)
except Exception as e:
    print(e)


if delete_bucket and "BUCKET_URI" in globals():
    ! gsutil rm -r $BUCKET_URI<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08250364639482528, 'fraction_numerical': 0.0037415181685585643, 'mean_word_length': 5.35118807893677, 'pattern_counts': {'":': 18, '<': 93, '<?xml version=': 0, '>': 99, 'https://': 9, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '23', 'dir': 'jupyter-structured-clean-dedup', 'id': '264394', 'license': 'Apache-2.0', 'n_tokens_mistral': 4623, 'n_tokens_neox': 4480, 'n_words': 1625, 'path': 'notebooks/community/ml_ops/stage1/get_started_with_data_labeling.ipynb', 'repo_name': 'jwlee98/vertex-ai-samples', 'size': '15769'}