! pip3 install -U google-cloud-aiplatform --user

"""
Explanation: Vertex SDK: Data Labeling
Installation
Install the latest (preview) version of Vertex SDK.
End of explanation
"""


! pip3 install google-cloud-storage

"""
Explanation: Install the Google cloud-storage library as well.
End of explanation
"""


import os

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

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

"""
Explanation: Restart the Kernel
Once you've installed the Vertex SDK and Google cloud-storage, you need to restart the notebook kernel so it can find the packages.
End of explanation
"""


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

"""
Explanation: 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.


Select or create a GCP 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 Vertex APIs and Compute Engine APIs.


Google Cloud SDK is already installed in Google Cloud Notebooks.


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 ! as shell commands, and it interpolates Python variables prefixed with $ into these commands.
End of explanation
"""


REGION = "us-central1"  # @param {type: "string"}

"""
Explanation: Region
You can also change the REGION variable, which is used for operations
throughout the rest of this notebook.  Below are regions supported for Vertex AI. We recommend when possible, to choose the region closest to you.

Americas: us-central1
Europe: europe-west4
Asia Pacific: asia-east1

You cannot use a Multi-Regional Storage bucket for training with Vertex. Not all regions provide support for all Vertex services. For the latest support per region, see Region support for 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 onto the name of resources which will be created in this tutorial.
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 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

"""
Explanation: Authenticate your GCP account
If you are using Google Cloud Notebooks, your environment is already
authenticated. Skip this step.
Note: If you are on an Vertex notebook and run the cell, the cell knows to skip executing the authentication steps.
End of explanation
"""


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

if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "[your-bucket-name]":
    BUCKET_NAME = PROJECT_ID + "aip-" + TIMESTAMP

"""
Explanation: 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.
End of explanation
"""


! gsutil mb -l $REGION gs://$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 gs://$BUCKET_NAME

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


import os
import sys
import time

from google.cloud.aiplatform import gapic as aip
from google.protobuf import json_format
from google.protobuf.json_format import MessageToJson, ParseDict
from google.protobuf.struct_pb2 import Struct, Value

"""
Explanation: Set up variables
Next, set up some variables used throughout the tutorial.
Import libraries and define constants
Import Vertex SDK
Import the Vertex SDK into our Python environment.
End of explanation
"""


# 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

"""
Explanation: Vertex AI constants
Setup up the following constants for Vertex AI:

API_ENDPOINT: The Vertex AI API service endpoint for dataset, model, job, pipeline and endpoint services.
API_PREDICT_ENDPOINT: The Vertex AI API service endpoint for prediction.
PARENT: The Vertex AI location root path for dataset, model and endpoint resources.
End of explanation
"""


# Image Dataset type
IMAGE_SCHEMA = "google-cloud-aiplatform/schema/dataset/metadata/image_1.0.0.yaml"
# Image Labeling type
IMPORT_SCHEMA_IMAGE_CLASSIFICATION = "gs://google-cloud-aiplatform/schema/dataset/ioformat/image_classification_single_label_io_format_1.0.0.yaml"
# Image labeling task
LABELING_SCHEMA_IMAGE = "gs://google-cloud-aiplatform/schema/datalabelingjob/inputs/image_classification_1.0.0.yaml"

"""
Explanation: AutoML constants
Next, setup constants unique to AutoML image classification datasets and training:

Dataset Schemas: Tells the managed dataset service which type of dataset it is.
Data Labeling (Annotations) Schemas: Tells the managed dataset service how the data is labeled (annotated).
Dataset Training Schemas: Tells the Vertex AI Pipelines service the task (e.g., classification) to train the model for.
End of explanation
"""


# client options same for all services
client_options = {"api_endpoint": API_ENDPOINT}


def create_dataset_client():
    client = aip.DatasetServiceClient(client_options=client_options)
    return client


def create_job_client():
    client = aip.JobServiceClient(client_options=client_options)
    return client


clients = {}
clients["dataset"] = create_dataset_client()
clients["job"] = create_job_client()

for client in clients.items():
    print(client)

import tensorflow as tf

LABELING_FILES = [
    "https://raw.githubusercontent.com/googleapis/python-aiplatform/master/samples/snippets/resources/daisy.jpg"
]

IMPORT_FILE = "gs://" + BUCKET_NAME + "/labeling.csv"
with tf.io.gfile.GFile(IMPORT_FILE, "w") as f:
    for lf in LABELING_FILES:
        ! wget {lf} | gsutil cp {lf.split("/")[-1]} gs://{BUCKET_NAME}
        f.write("gs://" + BUCKET_NAME + "/" + lf.split("/")[-1] + "\n")

! gsutil cat $IMPORT_FILE

"""
Explanation: Clients
The Vertex SDK works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the server (Vertex).
You will use several clients in this tutorial, so set them all up upfront.

Dataset Service for managed datasets.
Job Service for batch jobs and custom training.
End of explanation
"""


DATA_SCHEMA = IMAGE_SCHEMA

dataset = {
    "display_name": "labeling_" + TIMESTAMP,
    "metadata_schema_uri": "gs://" + DATA_SCHEMA,
}

print(
    MessageToJson(
        aip.CreateDatasetRequest(parent=PARENT, dataset=dataset).__dict__["_pb"]
    )
)

"""
Explanation: Example output:
gs://migration-ucaip-trainingaip-20210303215432/daisy.jpg
Create a dataset
projects.locations.datasets.create
Request
End of explanation
"""


request = clients["dataset"].create_dataset(parent=PARENT, dataset=dataset)

"""
Explanation: Example output:
{
  "parent": "projects/migration-ucaip-training/locations/us-central1",
  "dataset": {
    "displayName": "labeling_20210303215432",
    "metadataSchemaUri": "gs://google-cloud-aiplatform/schema/dataset/metadata/image_1.0.0.yaml"
  }
}
Call
End of explanation
"""


result = request.result()

print(MessageToJson(result.__dict__["_pb"]))

"""
Explanation: Response
End of explanation
"""


# The full unique ID for the dataset
dataset_id = result.name
# The short numeric ID for the dataset
dataset_short_id = dataset_id.split("/")[-1]

print(dataset_id)

"""
Explanation: Example output:
{
  "name": "projects/116273516712/locations/us-central1/datasets/1165112889535627264",
  "displayName": "labeling_20210303215432",
  "metadataSchemaUri": "gs://google-cloud-aiplatform/schema/dataset/metadata/image_1.0.0.yaml",
  "labels": {
    "aiplatform.googleapis.com/dataset_metadata_schema": "IMAGE"
  },
  "metadata": {
    "dataItemSchemaUri": "gs://google-cloud-aiplatform/schema/dataset/dataitem/image_1.0.0.yaml"
  }
}
End of explanation
"""


LABEL_SCHEMA = IMPORT_SCHEMA_IMAGE_CLASSIFICATION

import_config = {
    "gcs_source": {"uris": [IMPORT_FILE]},
    "import_schema_uri": LABEL_SCHEMA,
}

print(
    MessageToJson(
        aip.ImportDataRequest(
            name=dataset_short_id, import_configs=[import_config]
        ).__dict__["_pb"]
    )
)

"""
Explanation: projects.locations.datasets.import
Request
End of explanation
"""


request = clients["dataset"].import_data(
    name=dataset_id, import_configs=[import_config]
)

"""
Explanation: Example output:
{
  "name": "1165112889535627264",
  "importConfigs": [
    {
      "gcsSource": {
        "uris": [
          "gs://migration-ucaip-trainingaip-20210303215432/labeling.csv"
        ]
      },
      "importSchemaUri": "gs://google-cloud-aiplatform/schema/dataset/ioformat/image_classification_single_label_io_format_1.0.0.yaml"
    }
  ]
}
Call
End of explanation
"""


result = request.result()

print(MessageToJson(result.__dict__["_pb"]))

"""
Explanation: Response
End of explanation
"""


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

"""
Explanation: Example output:
{}
Create data labeling specialist pool
In case you do not have access to labeling services execute this section.
End of explanation
"""


EMAIL = "[your-email-address]"

specialist_pool = {
    "name": "labeling_" + TIMESTAMP,  # he resource name of the SpecialistPool.
    "display_name": "labeling_" + TIMESTAMP,  # user-defined name of the SpecialistPool
    "specialist_manager_emails": [EMAIL],
}

print(
    MessageToJson(
        aip.CreateSpecialistPoolRequest(
            parent=PARENT, specialist_pool=specialist_pool
        ).__dict__["_pb"]
    )
)

"""
Explanation: projects.locations.specialistPools.create
Request
In this part, you will replace [your-email-address] with your email address. This makes you the specialist and recipient of the labeling request.
End of explanation
"""


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

"""
Explanation: Example output:
{
  "parent": "projects/migration-ucaip-training/locations/us-central1",
  "specialistPool": {
    "name": "labeling_20210303215432",
    "displayName": "labeling_20210303215432",
    "specialistManagerEmails": [
      "dev@fourteen33.com"
    ]
  }
}
Call
End of explanation
"""


result = request.result()

print(MessageToJson(result.__dict__["_pb"]))

"""
Explanation: Response
End of explanation
"""


specialist_name = result.name

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

print(specialist_name)

"""
Explanation: Example output:
{
  "name": "projects/116273516712/locations/us-central1/specialistPools/1167839678372511744"
}
End of explanation
"""


# create placeholder file for valid PDF file with instruction for data labeling
! echo "this is instruction" >> instruction.txt | gsutil cp instruction.txt gs://$BUCKET_NAME

"""
Explanation: Create data labeling job
projects.locations.dataLabelingJobs.create
End of explanation
"""


LABLEING_SCHEMA = LABELING_SCHEMA_IMAGE
INSTRUCTION_FILE = "gs://" + BUCKET_NAME + "/instruction.txt"

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

data_labeling_job = {
    "display_name": "labeling_" + TIMESTAMP,
    "datasets": [dataset_id],
    "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(
    MessageToJson(
        aip.CreateDataLabelingJobRequest(
            parent=PARENT, data_labeling_job=data_labeling_job
        ).__dict__["_pb"]
    )
)

"""
Explanation: Request
End of explanation
"""


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

"""
Explanation: Example output:
```
{
  "parent": "projects/migration-ucaip-training/locations/us-central1",
  "dataLabelingJob": {
    "displayName": "labeling_20210303215432",
    "datasets": [
      "projects/116273516712/locations/us-central1/datasets/1165112889535627264"
    ],
    "labelerCount": 1,
    "instructionUri": "gs://migration-ucaip-trainingaip-20210303215432/instruction.txt",
    "inputsSchemaUri": "gs://google-cloud-aiplatform/schema/datalabelingjob/inputs/image_classification_1.0.0.yaml",
    "inputs": {
      "annotation_specs": [
        "rose"
      ]
    },
    "annotationLabels": {
      "aiplatform.googleapis.com/annotation_set_name": "data_labeling_job_specialist_pool"
    },
    "specialistPools": [
      "projects/116273516712/locations/us-central1/specialistPools/1167839678372511744"
    ]
  }
```
Call
End of explanation
"""


print(MessageToJson(request.__dict__["_pb"]))

"""
Explanation: Response
End of explanation
"""


labeling_task_name = request.name

print(labeling_task_name)

"""
Explanation: Example output:
{
  "name": "projects/116273516712/locations/us-central1/dataLabelingJobs/3830883229125050368",
  "displayName": "labeling_20210303215432",
  "datasets": [
    "projects/116273516712/locations/us-central1/datasets/1165112889535627264"
  ],
  "labelerCount": 1,
  "instructionUri": "gs://migration-ucaip-trainingaip-20210303215432/instruction.txt",
  "inputsSchemaUri": "gs://google-cloud-aiplatform/schema/datalabelingjob/inputs/image_classification_1.0.0.yaml",
  "inputs": {
    "annotationSpecs": [
      "rose"
    ]
  },
  "state": "JOB_STATE_PENDING",
  "createTime": "2021-03-03T21:55:31.239049Z",
  "updateTime": "2021-03-03T21:55:31.239049Z"
}
End of explanation
"""


request = clients["job"].get_data_labeling_job(name=labeling_task_name)

"""
Explanation: projects.locations.dataLabelingJobs.get
Call
End of explanation
"""


print(MessageToJson(request.__dict__["_pb"]))

"""
Explanation: Response
End of explanation
"""


request = clients["job"].cancel_data_labeling_job(name=labeling_task_name)

"""
Explanation: Example output:
{
  "name": "projects/116273516712/locations/us-central1/dataLabelingJobs/3830883229125050368",
  "displayName": "labeling_20210303215432",
  "datasets": [
    "projects/116273516712/locations/us-central1/datasets/1165112889535627264"
  ],
  "labelerCount": 1,
  "instructionUri": "gs://migration-ucaip-trainingaip-20210303215432/instruction.txt",
  "inputsSchemaUri": "gs://google-cloud-aiplatform/schema/datalabelingjob/inputs/image_classification_1.0.0.yaml",
  "inputs": {
    "annotationSpecs": [
      "rose"
    ]
  },
  "state": "JOB_STATE_PENDING",
  "createTime": "2021-03-03T21:55:31.239049Z",
  "updateTime": "2021-03-03T21:55:31.239049Z",
  "specialistPools": [
    "projects/116273516712/locations/us-central1/specialistPools/1167839678372511744"
  ]
}
projects.locations.dataLabelingJobs.cancel
Call
End of explanation
"""


print(request)

"""
Explanation: Response
End of explanation
"""


while True:
    response = clients["job"].get_data_labeling_job(name=labeling_task_name)
    if response.state == aip.JobState.JOB_STATE_CANCELLED:
        print("Labeling job CANCELED")
        break
    else:
        print("Canceling labeling job:", response.state)
        time.sleep(60)

"""
Explanation: Example output:
None
End of explanation
"""


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:
        clients["dataset"].delete_dataset(name=dataset_id)
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_NAME" in globals():
    ! gsutil rm -r gs://$BUCKET_NAME

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


