Vertex AI에서 이미지를 생성하여 Google Ads에 업로드하는 방법

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' 만들기 -> 웹 애플리케이션

Google Ads를 연결하는 데 필요한 사용자 인증 정보를 얻으려면 Cloud 사용자 인증 정보에 액세스해야 합니다.

동의 화면을 구성하지 않은 경우 먼저 동의 화면을 설정합니다.

  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 승인'을 클릭하면 다음 화면이 표시됩니다.

갱신 토큰 생성

'승인 코드를 토큰으로 교환'을 클릭하면 갱신 토큰이 표시됩니다.

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로 테스트할 수 있습니다. Google Ads 계정에 어떤 확장 소재가 있는지 쿼리해 보겠습니다.

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에 이미지를 업로드하고 이미지 확장 소재로 사용하는 방법