1. 简介
构建内容
在本 Codelab 中,您将学习如何使用 Vertex AI 生成图片,并将其发送到 Google Ads,以便这些素材资源可用作广告系列中的图片素材资源。
学习内容
- 如何通过 GCP、Vertex AI 生成图片
- 如何将图片上传到 Google Ads
- 如何在 Google Ads 中使用图片
所需条件
- Google Ads 账号
- GCP 账号
2. 获取 Google Ads 凭据
此部分用于从 Google Ads 获取图片素材资源。如需通过 Colab 访问 Google Ads,您需要正确的凭据。
创建凭据 -> 创建“OAuth 客户端 ID”-> Web 应用
如需获取正确的凭据以关联 Google Ads,您需要访问 Cloud 凭据。
如果您尚未配置权限请求页面,请先设置权限请求页面。
- 用户类型:外部
- 发布状态:已投入生产

将以下 URI 添加到“已获授权的重定向 URI”
将以下 URI 放置在以下屏幕截图中所示的位置。
https://developers.google.com/oauthplayground

复制客户端 ID 和客户端密钥
您可以获取客户端 ID 和客户端密钥。

3. 生成刷新令牌
访问 OAuth Playground
您可以在 OAuth Playground 中轻松颁发临时刷新令牌。
前往“设置”,然后选中“使用您自己的 OAuth 凭据”。从上一章获取 OAuth 客户端 ID 和客户端密钥后,您可以将它们放入相应的文本框中。 

添加范围
您可以将范围 https://www.googleapis.com/auth/adwords 添加到以下区域。

点击“授权 API”,您将看到下一个界面。
生成刷新令牌
点击“将授权代码转换为令牌”,您将看到刷新令牌。

4. 准备 Colab 以执行代码
Colab 是一个方便的代码笔记本,随 Python 一起提供。默认选项提供了相当多的计算能力。您还可以使用任何平台调用 Google Cloud Vertex AI 的 REST API。
请前往 https://colab.research.google.com/ 使用。
依次前往 [File → New note],然后开始编写新代码。

如果您点击“新建笔记本”,您将看到已准备就绪的新工作表。
5. 通过 Google Cloud Vertex AI 生成图片
导入库
!pip install requests google-ads
首先,安装 Google Ads 和 API 请求的库。安装库后,您需要重启运行时。
您还可以加载必要的库。
import requests
import json
import base64
from google.ads import googleads
from google.colab import auth
from IPython.display import display, Image
获取身份验证
系统会要求您授权您的 Google 账号。
auth.authenticate_user()
access_token = !gcloud auth print-access-token
access_token = access_token[0]
授权自己后,您就可以调用 Google Cloud API 了。
6. 通过 Vertex AI 生成图片
准备提示和 POST 请求
首先,您应该拥有 Google Cloud 项目 ID。您可以从 Google Cloud 获取该 ID。您需要一个文本提示,还可以设置所需的图片数量。如需了解更多选项,请参阅官方 文档。
PROJECT_ID = 'abcdefg' # Your GCP project ID
TEXT_PROMPT = 'cat computer' # Your prompt goes here.
IMAGE_COUNT = 4 # You will get 4 images as a result.
您可以在文本提示中写入任何内容。在这里,我们希望生成一张图片,其中同时包含猫和电脑。
url = f"https://us-central1-aiplatform.googleapis.com/v1/projects/{PROJECT_ID}/locations/us-central1/publishers/google/models/imagegeneration:predict"
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json; charset=utf-8"
}
data = {
"instances": [
{
"prompt": TEXT_PROMPT
}
],
"parameters": {
"sampleCount": IMAGE_COUNT
}
}
请求生成图片
准备好 JSON 后,您现在可以请求生成图片了。以下是典型的 HTTP 请求。
response = requests.post(url, headers=headers, data=json.dumps(data))
if response.status_code == 200:
response_data = response.json()
for prediction in response_data.get('predictions', []):
image_data = base64.b64decode(prediction['bytesBase64Encoded'])
display(Image(data=image_data))
else:
print("Request failed:", response.status_code, response.text)
如果您等待几秒钟,您将获得结果。非常简单!

7. 与 Google Ads 相关联
关联您的 Google Ads 账号
您需要 Google Ads 提供的开发者令牌。您可以申请基本或标准开发者令牌,但出于测试目的,您也可以使用测试令牌。前往您的 MCC 账号。在“工具和设置”标签页中,您将看到 API 中心。在“API”部分,您可以在其中找到您的令牌。
客户端 ID、客户端密钥和刷新令牌应在上一章中准备就绪。
credentials = {
"developer_token": "ABCDEFG",
"client_id": "123456789012-abcd1234.apps.googleusercontent.com",
"client_secret": "GOCSPX-abcd1234-abcd1234-abcd1234",
"refresh_token": "1//abcdefghijklmnopqrstuvwxyz",
"use_proto_plus": True
}
设置凭据后,您可以加载 GoogleAdsService API。客户 ID 通常采用 xxx-xxxx-xxx 格式,但您应移除“-”。
client = googleads.client.GoogleAdsClient.load_from_dict(credentials, version='v13')
googleads_service = client.get_service("GoogleAdsService")
customer_id = "1234567890"
查询 Google Ads 账号
现在,您可以使用 googleads_service 进行测试。让我们查询广告账号中包含哪些类型的素材资源。
query = (
'''
SELECT
ad_group_ad.ad.id,
ad_group_ad.ad.app_ad.headlines,
ad_group_ad.ad.app_ad.descriptions,
ad_group_ad.ad.app_ad.images
FROM ad_group_ad
''')
response = googleads_service.search(customer_id=customer_id, query=query)
for googleads_row in response:
print(googleads_row)
您将看到 Google Ads 账号中的素材资源列表,采用 JSON 格式。如果您看到类似以下内容,
ad_group_ad {
`images { asset: "customers/1234567890/assets/09876543210" }`
}
8. 将图片素材资源上传到 Google Ads
上传
在最后一步中,我们将生成的素材资源上传到 Google Ads。
for prediction in response_data.get('predictions', []):
image_base64 = prediction['bytesBase64Encoded']
image_bytes = base64.b64decode(image_base64)
asset_service = client.get_service('AssetService')
asset_operation = client.get_type('AssetOperation')
asset = asset_operation.create
asset.type_ = client.enums.AssetTypeEnum.IMAGE
asset.image_asset.data = image_bytes
asset.name = "cats"
asset_service.mutate_assets(customer_id=customer_id, operations=[asset_operation])
几秒钟后,您将能够通过 Google Ads 前端查看上传的素材资源。以下是示例屏幕截图。

9. 恭喜
恭喜,您已成功通过现有图片生成精美的图片素材资源!
您学到的内容
- 如何通过生成式 AI (Vertex AI) 生成图片素材资源
- 如何将图片上传到 Google Ads 并将其用作图片素材资源