如何透過 Vertex AI 產生圖片並上傳至 Google Ads

1. 簡介

建構項目

在本程式碼研究室中,您將瞭解如何使用 Vertex AI 生成圖片,並傳送至 Google Ads,以便在廣告活動中將這些素材資源做為圖片素材資源。

課程內容

  • 如何透過 GCP、Vertex AI 生成圖片
  • 如何將圖片上傳至 Google Ads
  • 如何在 Google Ads 中使用

軟硬體需求

  • Google Ads 帳戶
  • GCP 帳戶

2. 取得 Google Ads 憑證

這是從 Google Ads 取得圖片素材資源的必要部分。如要從 Colab 存取 Google Ads,您必須具備適當的憑證。

建立憑證 -> 建立「OAuth 用戶端 ID」-> 網頁應用程式

如要取得連結 Google Ads 的適當憑證,請存取雲端憑證

如果尚未設定同意畫面,請先設定同意畫面。

  1. 使用者類型:外部
  2. 發布狀態:實際運作中

6ecf963c5957379d.png

將下列 URI 新增至「已授權的重新導向 URI」

將下列 URI 設為下方螢幕截圖所示。

https://developers.google.com/oauthplayground

b5d054a6cac40869.png

複製用戶端 ID 和用戶端密鑰

您可以取得用戶端 ID 和用戶端密鑰。

c8578bf54ade7cee.png

3. 產生更新權杖

OAuth Playground 存取權

您可以在 OAuth Playground 輕鬆核發臨時更新權杖。

前往設定,然後勾選「使用自己的 OAuth 憑證」。從前一章取得 OAuth 用戶端 ID 和用戶端密鑰後,即可將這些資訊輸入對應的文字方塊。ace79f71603a922.png

ad82eca7a99c446c.png

新增範圍

您可以在下方區域新增 https://www.googleapis.com/auth/adwords 範圍。

eff5408ba160aad1.png

按一下「授權 API」,即可查看下一個畫面。

產生更新權杖

按一下「Exchange authorization code for tokens」,即可看到更新權杖。

e8c6860d61ad73fd.png

4. 準備 Colab 來執行程式碼

Colab 是隨附於 Python 的實用程式碼筆記本。預設選項提供的運算能力相當充足。您也可以使用任何平台呼叫 Google Cloud Vertex AI 的 REST API。

如要使用,請前往 https://colab.research.google.com/

前往「檔案」→「新記事」,開始撰寫新程式碼。

6b95020b3d3369ae.png

按一下「新筆記本」後,系統會顯示新的工作表。

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 取得這項服務。你需要提供文字提示,也可以設定所需圖片數量。如需更多選項,請參閱官方說明文件

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)

等待幾秒鐘後,系統就會顯示結果。非常簡單!

dec38d2d3f7faab8.png

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 前端查看上傳的資產。螢幕截圖範例如下。

7f2fb6063e5ae675.png

9. 恭喜

恭喜!您已成功從現有圖片生成精美圖片素材資源!

您已學習以下內容

  • 如何透過生成式 AI (Vertex AI) 生成圖片素材
  • 如何將圖片上傳至 Google Ads 並做為圖片素材資源使用