How to generate image from Vertex AI and Upload to Google Ads

1. Introduction

What you'll build

In this codelab, You will learn how to generate images using Vertex AI and send it to Google Ads so that the assets can be used as image assets in the campaigns.

What you'll learn

  • How to generate images from GCP, Vertex AI
  • How to upload images to the Google Ads
  • How to use it in Google Ads

What you'll need

  • Google Ads Account
  • GCP Account

2. Get Google Ads credentials

This part is needed to get image assets from Google Ads. To access Google Ads from Colab, you need proper credentials.

Create credentials -> Create ‘OAuth client ID' -> Web Application

To get proper credentials to connect Google Ads, you need to access Cloud credentials.

If you haven't configured consent screen, setup consent screen first.

  1. User type: External
  2. Publishing status: In production

6ecf963c5957379d.png

Add the following URI to ‘Authorized redirect URIs'

Put below URI as the below screenshot.

https://developers.google.com/oauthplayground

b5d054a6cac40869.png

Copy Client ID and client secret

You can get client ID and client secret.

c8578bf54ade7cee.png

3. Generate Refresh Token

Access to OAuth Playground

You can easily issue a temporary refresh token at OAuth Playground.

Go to the settings, and check on the ‘User your own OAuth credentials'. After you acquired OAuth client ID and client secret from the previous chapter, you can put them into the corresponding text boxes. ace79f71603a922.png

ad82eca7a99c446c.png

Add the scope

You can add the scope https://www.googleapis.com/auth/adwords into the below area.

eff5408ba160aad1.png

Click Authorize APIs, and you will see the next screen.

Generate Refresh Token

Click ‘Exchange authorization code for tokens', and you will see the refresh token.

e8c6860d61ad73fd.png

4. Prepare Colab for executing the code

Colab is the handy code notebook that comes with Python. The default option provides quite a generous amount of computing power. You can also use any platform to call the REST API of the Google Cloud Vertex AI.

Please go to https://colab.research.google.com/ to use it.

Go to [File → New note] and start writing new codes.

6b95020b3d3369ae.png

If you click New Notebook, you will see the new sheet ready for you.

5. Generate Image through Google Cloud Vertex AI

Import libraries

!pip install requests google-ads

First, Install libraries for Google Ads, and API requests. You need to restart runtime after installing the libraries.

You can also load essential libraries.

import requests
import json
import base64

from google.ads import googleads
from google.colab import auth
from IPython.display import display, Image

Get Authentication

You will be asked to authorize your google account.

auth.authenticate_user()

access_token = !gcloud auth print-access-token
access_token = access_token[0]

After authorizing yourself, you are ready to call Google Cloud APIs.

6. Generate image from Vertex AI

Prepare your prompt and POST request

First, you should have your Google cloud project ID. You can get it from Google Cloud. You need a text prompt, and you can also set how many images you need. For more options, please refer to the official documentation.

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.

You can write anything inside the text prompt. Here, we want to generate the images that have cat and computer together in a single picture.

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
    }
}

Request image generation

Once you are ready for the json, you can now request for the image generation. Below is the typical http request.

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)

If you wait several seconds, you will get the result. Very simple!

dec38d2d3f7faab8.png

7. Get Connected to Google Ads

Connect to your Google Ads Account

You need a developer token from Google Ads. You can apply for basic or standard dev token, but for the testing purpose, test token is also available. Go to your MCC account. In the tools and settings tab, you will see the API center. At the API section, you will find your token there.

Client id, client secret and refresh tokens should be ready at the previous chapter.

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
}

After setting credentials, you can load GoogleAdsService API. Customer id is usually in format of xxx-xxxx-xxx, but you should remove ‘-'.

client = googleads.client.GoogleAdsClient.load_from_dict(credentials, version='v13')
googleads_service = client.get_service("GoogleAdsService")
customer_id = "1234567890"

Querying Google Ads Account

Now, you can test with googleads_service. Let's query what kind of assets we have in the Ads account.

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)

You will see the list of assets in Google Ads account in json format. If you see something like

ad_group_ad {

`images { asset: "customers/1234567890/assets/09876543210" }` 

}

8. Upload Image Asset to Google Ads

Upload

For the last step, we are going to upload generated assets to 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])

After a few seconds, you will be able to check the uploaded asset through Google Ads Frontend. Here is the sample screenshot.

7f2fb6063e5ae675.png

9. Congratulations

Congratulations, you've successfully generated beautiful image assets from the existing image!

You've learned

  • How to generate image assets through generative AI (Vertex AI)
  • How to upload images to Google Ads and use it as image assets