mirror of
https://github.com/GoogleCloudPlatform/vertex-ai-samples.git
synced 2026-09-26 14:42:04 +00:00
35 KiB
35 KiB
In [ ]:
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.In [ ]:
import os
# The Vertex AI Workbench Notebook product has specific requirements
IS_WORKBENCH_NOTEBOOK = os.getenv("DL_ANACONDA_HOME") and not os.getenv("VIRTUAL_ENV")
IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists(
"/opt/deeplearning/metadata/env_version"
)
# Vertex AI Notebook requires dependencies to be installed with '--user'
USER_FLAG = ""
if IS_WORKBENCH_NOTEBOOK:
USER_FLAG = "--user"
# Install the packages
! pip3 install --upgrade google-cloud-aiplatform \
google-cloud-storage $USER_FLAG -q
if os.getenv("IS_TESTING"):
! pip3 install --upgrade google-api-core==2.10 $USER_FLAG -qIn [ ]:
import os
if not os.getenv("IS_TESTING"):
# Automatically restart kernel after installs
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)In [ ]:
PROJECT_ID = "[your-project-id]" # @param {type:"string"}In [ ]:
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)In [ ]:
! gcloud config set project $PROJECT_IDIn [ ]:
REGION = "[your-region]" # @param {type: "string"}
if REGION == "[your-region]":
REGION = "us-central1"In [ ]:
from datetime import datetime
TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")In [ ]:
EMAIL = "[your-email-address]" # @param {type: "string"}In [ ]:
if EMAIL == "[your-email-address]":
shell_output = ! gcloud auth list 2>/dev/null
EMAIL = shell_output[2].replace("*", "").strip()
print(EMAIL)In [ ]:
# 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.
import os
import sys
# If on Vertex AI Workbench, then don't execute this code
IS_COLAB = False
if not os.path.exists("/opt/deeplearning/metadata/env_version") and not os.getenv(
"DL_ANACONDA_HOME"
):
if "google.colab" in sys.modules:
IS_COLAB = True
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"):
%env GOOGLE_APPLICATION_CREDENTIALS ''In [ ]:
BUCKET_NAME = "[your-bucket-name]" # @param {type:"string"}
BUCKET_URI = f"gs://{BUCKET_NAME}"In [ ]:
if BUCKET_URI == "" or BUCKET_URI is None or BUCKET_URI == "gs://[your-bucket-name]":
BUCKET_NAME = PROJECT_ID + "aip-" + TIMESTAMP
BUCKET_URI = "gs://" + BUCKET_NAMEIn [ ]:
! gsutil mb -l $REGION $BUCKET_URIIn [ ]:
! gsutil ls -al $BUCKET_URIIn [ ]:
import os
import sys
import time
import google.cloud.aiplatform as aip
from google.cloud import storage
from google.cloud.aiplatform import gapic
from google.protobuf.json_format import ParseDict
from google.protobuf.struct_pb2 import ValueIn [ ]:
aip.init(project=PROJECT_ID, location=REGION)In [ ]:
# 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/" + REGIONIn [ ]:
# Image labeling task
LABELING_SCHEMA_IMAGE = "gs://google-cloud-aiplatform/schema/datalabelingjob/inputs/image_classification_1.0.0.yaml"In [ ]:
# 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)In [ ]:
test_filename = "labeling.csv"
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"
bucket = storage.Client(project=PROJECT_ID).bucket(BUCKET_URI.replace("gs://", ""))
# creating a blob
blob = bucket.blob(blob_name=test_filename)
# creating data variable
data = LABELING_FILES[0] + "\n" + LABELING_FILES[1] + "\n"
# uploading data variable content to bucket
blob.upload_from_string(data, content_type="text/csv")
# printing path of uploaded file
print(IMPORT_FILE)
# printing content of uploaded file
! gsutil cat $IMPORT_FILEIn [ ]:
dataset = aip.ImageDataset.create("labeling_" + TIMESTAMP)
print(dataset)In [ ]:
dataset.import_data(
gcs_source=[IMPORT_FILE],
import_schema_uri=aip.schema.dataset.ioformat.image.single_label_classification,
)In [ ]:
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)In [ ]:
# create placeholder file for instructions for data labeling
! echo "this is instruction" >> instruction.txt | gsutil cp instruction.txt $BUCKET_URIIn [ ]:
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)In [ ]:
request = clients["job"].get_data_labeling_job(name=labeling_task_name)
print(request)In [ ]:
request = clients["job"].cancel_data_labeling_job(name=labeling_task_name)
print(request)In [ ]:
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)In [ ]:
# Set this to true only if you'd like to delete your bucket
delete_bucket = False
# Delete the dataset using the Vertex AI fully qualified identifier for the dataset
dataset.delete()
# Delete the labeling job using the Vertex AI fully qualified identifier for the dataset
request = clients["job"].delete_data_labeling_job(name=labeling_task_name)
# Delete the specialist pool using the Vertex AI fully qualified identifier for the dataset
clients["specialist_pool"].delete_specialist_pool(name=specialist_name)
# Delete the bucket created
if delete_bucket or os.getenv("IS_TESTING"):
! gsutil rm -r $BUCKET_URI
Run in Colab
View on GitHub