mirror of
https://github.com/GoogleCloudPlatform/vertex-ai-samples.git
synced 2026-09-26 14:42:04 +00:00
* Migrate gsutil usage to gcloud storage * changes for 4304 * Apply automated linter fixes * remove unused import --------- Co-authored-by: gurusai-voleti <gvoleti@google.com>
33 KiB
33 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 [ ]:
# Install the packages
%pip install --upgrade google-cloud-aiplatform \
google-cloud-storage \
kfp \
google-cloud-pipeline-componentsIn [ ]:
! python3 -c "import kfp; print('KFP SDK version: {}'.format(kfp.__version__))"In [ ]:
import sys
if "google.colab" in sys.modules:
from google.colab import auth
auth.authenticate_user()In [ ]:
PROJECT_ID = "[your-project-id]" # @param {type:"string"}
LOCATION = "us-central1" # @param {type:"string"}In [ ]:
BUCKET_URI = f"gs://your-bucket-name-{PROJECT_ID}-unique" # @param {type:"string"}In [ ]:
! gcloud storage buckets create --location={LOCATION} --project={PROJECT_ID} {BUCKET_URI}In [ ]:
SERVICE_ACCOUNT = "[your-service-account]" # @param {type:"string"}In [ ]:
import sys
IS_COLAB = "google.colab" in sys.modules
if (
SERVICE_ACCOUNT == ""
or SERVICE_ACCOUNT is None
or SERVICE_ACCOUNT == "[your-service-account]"
):
# Get your service account from gcloud
if not IS_COLAB:
shell_output = !gcloud auth list 2>/dev/null
SERVICE_ACCOUNT = shell_output[2].replace("*", "").strip()
else: # IS_COLAB:
shell_output = ! gcloud projects describe $PROJECT_ID
project_number = shell_output[-1].split(":")[1].strip().replace("'", "")
SERVICE_ACCOUNT = f"{project_number}-compute@developer.gserviceaccount.com"
print("Service Account:", SERVICE_ACCOUNT)In [ ]:
! gcloud storage buckets add-iam-policy-binding $BUCKET_URI --member=serviceAccount:{SERVICE_ACCOUNT} --role=roles/storage.objectCreator
! gcloud storage buckets add-iam-policy-binding $BUCKET_URI --member=serviceAccount:{SERVICE_ACCOUNT} --role=roles/storage.objectViewerIn [ ]:
import json
from typing import NamedTuple
from google.cloud import aiplatform
from kfp import compiler, dsl
from kfp.dsl import componentIn [ ]:
aiplatform.init(project=PROJECT_ID, location=LOCATION, staging_bucket=BUCKET_URI)In [ ]:
# API service endpoint
API_ENDPOINT = f"{LOCATION}-aiplatform.googleapis.com"
# Pipelne root dir
PIPELINE_ROOT = f"{BUCKET_URI}/pipeline_root/intro"In [ ]:
@component(base_image="python:3.9")
def hello_world(text: str) -> str:
print(text)
return text
compiler.Compiler().compile(hello_world, "hw.yaml")In [ ]:
@component(packages_to_install=["google-cloud-storage"])
def two_outputs(
text: str,
) -> NamedTuple(
"Outputs",
[
("output_one", str), # Return parameters
("output_two", str),
],
):
# the import is not actually used for this simple example, but the import
# is successful, as it was included in the `packages_to_install` list.
from google.cloud import storage # noqa: F401
o1 = f"output one from text: {text}"
o2 = f"output two from text: {text}"
print("output one: {}; output_two: {}".format(o1, o2))
return (o1, o2)In [ ]:
@component
def consumer(text1: str, text2: str, text3: str) -> str:
print(f"text1: {text1}; text2: {text2}; text3: {text3}")
return f"text1: {text1}; text2: {text2}; text3: {text3}"In [ ]:
@dsl.pipeline(
name="intro-pipeline-unique",
description="A simple intro pipeline",
pipeline_root=PIPELINE_ROOT,
)
def pipeline(text: str = "hi there"):
hw_task = hello_world(text=text)
two_outputs_task = two_outputs(text=text)
consumer_task = consumer( # noqa: F841
text1=hw_task.output,
text2=two_outputs_task.outputs["output_one"],
text3=two_outputs_task.outputs["output_two"],
)In [ ]:
compiler.Compiler().compile(pipeline_func=pipeline, package_path="intro_pipeline.json")In [ ]:
DISPLAY_NAME = "intro_pipeline_job_unique"
job = aiplatform.PipelineJob(
display_name=DISPLAY_NAME,
template_path="intro_pipeline.json",
pipeline_root=PIPELINE_ROOT,
)
job.run()In [ ]:
job.delete()In [ ]:
DISPLAY_NAME = "intro_pipeline_job_svc_acc"
job = aiplatform.PipelineJob(
display_name=DISPLAY_NAME,
template_path="intro_pipeline.json",
pipeline_root=PIPELINE_ROOT,
)
job.run(
service_account=SERVICE_ACCOUNT
) # <-- CHANGE to use non-default service accountIn [ ]:
job.delete()In [ ]:
job = aiplatform.PipelineJob(
display_name="intro_pipeline_job_cached_unique",
template_path="intro_pipeline.json",
enable_caching=False,
)
job.run()In [ ]:
job.delete()In [ ]:
! curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" https://{API_ENDPOINT}/v1beta1/projects/{PROJECT_ID}/locations/{LOCATION}/pipelineJobsIn [ ]:
# Load the pipeline specification
with open("intro_pipeline.json") as fp:
pipeline_job_spec = json.load(fp)In [ ]:
# Specify the pipeline configuration details
pipeline_config = {
"displayName": "intro-pipeline-rest-api",
"runtimeConfig": {
"gcsOutputDirectory": PIPELINE_ROOT,
},
"pipelineSpec": pipeline_job_spec,
}
# Save the configuration to a json file
with open("pipeline_config.json", "w") as fp:
json.dump(pipeline_config, fp)In [ ]:
# Set a job ID (optional)
PIPELINE_RUN_ID = "intro-pipeline-job-unique"
# Send the job creation request using the configuration payload
output = ! curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "Content-Type: application/json; charset=utf-8" https://{API_ENDPOINT}/v1beta1/projects/{PROJECT_ID}/locations/{LOCATION}/pipelineJobs?pipelineJobId={PIPELINE_RUN_ID} --data "@pipeline_config.json"
# In case you didn't use a pre-defined PipelineJobId, Vertex AI
# generates one automatically. In such a case, use the following
# commented code to retrieve the generated job id.
# output_json = json.loads(" ".join(output))
# PIPELINE_RUN_ID = output_json['name'].split("/")[-1]
# print(PIPELINE_RUN_ID)In [ ]:
! curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" https://{API_ENDPOINT}/v1beta1/projects/{PROJECT_ID}/locations/{LOCATION}/pipelineJobs/{PIPELINE_RUN_ID}In [ ]:
! curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" https://{API_ENDPOINT}/v1beta1/projects/{PROJECT_ID}/locations/{LOCATION}/pipelineJobs/{PIPELINE_RUN_ID}:cancelIn [ ]:
! curl -X DELETE -H "Authorization: Bearer $(gcloud auth print-access-token)" https://{API_ENDPOINT}/v1beta1/projects/{PROJECT_ID}/locations/{LOCATION}/pipelineJobs/{PIPELINE_RUN_ID}In [ ]:
# Delete the Cloud Storage bucket
delete_bucket = False # Set True for deletion
if delete_bucket:
! gcloud storage rm --recursive $BUCKET_URI
# Delete the locally generated files
! rm intro_pipeline.json
! rm pipeline_config.json
