マルチモーダル エンベディングを取得する

マルチモーダル エンベディング モデルは、提供された入力に基づいて 1,408 次元のベクトル* を生成します。これには、画像、テキスト、動画データの組み合わせが含まれます。エンベディング ベクトルは、画像分類や動画コンテンツのモデレーションなどの後続のタスクに使用できます。

画像エンベディング ベクトルとテキスト エンベディング ベクトルは、同じ次元を持つ同じセマンティック空間にあります。そのため、これらのベクトルは、テキストによる画像の検索や画像による動画の検索などのユースケースでも使用できます。

テキストのみのエンベディングでは、Vertex AI Text-embeddings API を使用することをおすすめします。たとえば、Text-embeddings API は、テキストベースのセマンティック検索、クラスタリング、長時間のドキュメント分析、その他のテキスト取得や質問応答のユースケースに適しています。詳細については、テキスト エンベディングを取得するをご覧ください。

* デフォルト値

ユースケース

画像とテキスト:

  • 画像分類: 画像を入力として受け取り、1 つ以上のクラス(ラベル)を予測します。
  • 画像検索: 関連する画像や類似の画像を検索できます。
  • レコメンデーション: 画像に基づいておすすめの製品や広告を生成します。

画像、テキスト、動画:

  • レコメンデーション: 動画に基づいて商品または広告のレコメンデーションを生成します(類似性検索)。
  • 動画コンテンツ検索
    • セマンティック検索の使用: テキストを入力として受け取り、クエリに一致するランク付けされたフレームのセットを返します。
    • 類似性検索の使用:
      • 動画を入力として受け取り、クエリに一致する動画のセットを返します。
      • 画像を入力として受け取り、クエリに一致する動画のセットを返します。
  • 動画分類: 動画を入力として受け取り、1 つ以上のクラスを予測します。

サポートされているモデル

次のモデルを使用して、マルチモーダル エンベディングを取得できます。

  • multimodalembedding

ベスト プラクティス

マルチモーダル エンベディング モデルを使用する場合は、入力時の次のことを考慮してください。

  • 画像内のテキスト - このモデルは、光学式文字認識(OCR)と同様に、画像内のテキストを認識できます。画像コンテンツの説明と画像内のテキストを区別する必要がある場合は、プロンプト エンジニアリングを使用してターゲット コンテンツを指定することを検討してください。たとえば、ユースケースに応じて単に「cat」ではなく「picture of a cat」または「the text 'cat'」と指定します。




    テキスト「cat」

    「cat」という単語が含まれるテキストの画像




    猫の写真

    猫の画像
    画像クレジット: Manja VitolicUnsplash
  • エンベディングの類似度 - エンベディングのドット積は、調整された確率ではありません。ドット積は類似度指標であり、ユースケースによってスコア分布が異なる場合があります。品質を測定するために固定値のしきい値を使用することは避けてください。代わりに、取得にランキング アプローチを使用するか、分類にシグモイドを使用します。

API の使用

API の上限

テキストと画像のエンベディングに multimodalembedding モデルを使用する場合は、次の上限が適用されます。

上限 値と説明
テキストと画像のデータ
各プロジェクト 1 分あたりの最大 API リクエスト数 120
テキストの最大長 32 トークン(約 32 ワード)

テキストの最大長は 32 トークン(約 32 ワード)です。入力が 32 トークンを超える場合、この長さになるまで内部で入力が短縮されます。
言語 英語
画像形式 BMP、GIF、JPG、PNG
イメージサイズ Base64 エンコード画像: 20 MB(PNG にコード変換する場合)
Cloud Storage 画像: 20 MB(元のファイル形式)

使用できる画像サイズは最大 20 MB です。ネットワークのレイテンシの増加を回避するには、より小さいイメージを使用してください。さらに、このモデルは画像を 512 x 512 ピクセルの解像度に変更します。そのため、より高い解像度の画像を用意する必要はありません。
動画データ
音声対応 なし - このモデルでは、動画エンベディングの生成時に音声コンテンツが考慮されません
動画フォーマット AVI、FLV、MKV、MOV、MP4、MPEG、MPG、WEBM、WMV
動画の最大長(Cloud Storage) 上限なし。ただし、一度に分析できるコンテンツは 2 分間のみです。

始める前に

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  3. Google Cloud プロジェクトで課金が有効になっていることを確認します

  4. Vertex AI API を有効にします。

    API を有効にする

  5. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  6. Google Cloud プロジェクトで課金が有効になっていることを確認します

  7. Vertex AI API を有効にします。

    API を有効にする

  8. 環境の認証を設定します。

    このページのサンプルをどのように使うかに応じて、タブを選択してください。

    Java

    このページの Java サンプルをローカル開発環境から使用するには、gcloud CLI をインストールして初期化し、自身のユーザー認証情報を使用してアプリケーションのデフォルト認証情報を設定してください。

    1. Google Cloud CLI をインストールします。
    2. gcloud CLI を初期化するには:

      gcloud init
    3. gcloud コンポーネントを更新してインストールします。
      gcloud components update
      gcloud components install beta
    4. Google アカウントのローカル認証情報を作成します。

      gcloud auth application-default login

    詳細については、Google Cloud の認証に関するドキュメントのローカル開発環境の認証の設定をご覧ください。

    Node.js

    このページの Node.js サンプルをローカル開発環境から使用するには、gcloud CLI をインストールして初期化し、自身のユーザー認証情報を使用してアプリケーションのデフォルト認証情報を設定してください。

    1. Google Cloud CLI をインストールします。
    2. gcloud CLI を初期化するには:

      gcloud init
    3. gcloud コンポーネントを更新してインストールします。
      gcloud components update
      gcloud components install beta
    4. Google アカウントのローカル認証情報を作成します。

      gcloud auth application-default login

    詳細については、Google Cloud の認証に関するドキュメントのローカル開発環境の認証の設定をご覧ください。

    Python

    このページの Python サンプルをローカル開発環境から使用するには、gcloud CLI をインストールして初期化し、自身のユーザー認証情報を使用してアプリケーションのデフォルト認証情報を設定してください。

    1. Google Cloud CLI をインストールします。
    2. gcloud CLI を初期化するには:

      gcloud init
    3. gcloud コンポーネントを更新してインストールします。
      gcloud components update
      gcloud components install beta
    4. Google アカウントのローカル認証情報を作成します。

      gcloud auth application-default login

    詳細については、Google Cloud の認証に関するドキュメントのローカル開発環境の認証の設定をご覧ください。

    REST

    このページの REST API サンプルをローカル開発環境で使用するには、gcloud CLI に指定した認証情報を使用します。

    1. Google Cloud CLI をインストールします。
    2. gcloud CLI を初期化するには:

      gcloud init
    3. gcloud コンポーネントを更新してインストールします。
      gcloud components update
      gcloud components install beta
  9. Python SDK を使用するには、Vertex AI SDK for Python をインストールするの手順に沿って操作します。詳細については、Vertex AI SDK for Python API のリファレンス ドキュメントをご覧ください。
  10. 省略可。この機能の料金を確認します。エンベディングの料金は、送信するデータの種類(画像やテキストなど)によって異なります。また、特定のデータタイプ(Video Plus、Video Standard、Video Essentials など)で使用するモードによっても異なります。

ロケーション

ロケーションは、データの保存場所を制御するためにリクエストで指定できるリージョンです。使用可能なリージョンの一覧については、Vertex AI の生成 AI のロケーションをご覧ください。

エラー メッセージ

割り当て超過エラー

google.api_core.exceptions.ResourceExhausted: 429 Quota exceeded for
aiplatform.googleapis.com/online_prediction_requests_per_base_model with base
model: multimodalembedding. Please submit a quota increase request.

このエラーが初めて表示された場合は、Google Cloud コンソールでプロジェクトの割り当ての増加をリクエストします。増加をリクエストする前に、次のフィルタを使用します。

  • Service ID: aiplatform.googleapis.com
  • metric: aiplatform.googleapis.com/online_prediction_requests_per_base_model
  • base_model:multimodalembedding

[割り当て] に移動

割り当て増加リクエストをすでに送信している場合は、しばらく待ってから次のリクエストを送信してください。さらに割り当てを増やす必要がある場合は、割り当てリクエストの正当性を示しながら、割り当て増加リクエストを繰り返します。

低ディメンションのエンベディングを指定する

デフォルトでは、エンベディング リクエストはデータ型の 1,408 浮動小数点ベクトルを返します。テキストデータと画像データには、低次元のエンベディング(128、256、512 の浮動小数点ベクトル)を指定することもできます。このオプションを使用すると、エンベディングの使用方法に基づいてレイテンシ、ストレージ、品質を最適化できます。低ディメンションのエンベディングでは、後続のエンベディング タスク(検索やレコメンデーションなど)でストレージ ニーズが減少し、レイテンシが低くなります。また、高ディメンションのエンベディングでは、同じタスクに対して高い精度が実現されます。

REST

低ディメンションにアクセスするには、parameters.dimension フィールドを追加します。このパラメータは、1282565121408 のいずれかの値を受け入れます。レスポンスには、そのディメンションのエンベディングが含まれます。

リクエストのデータを使用する前に、次のように置き換えます。

  • LOCATION: プロジェクトのリージョン。たとえば、us-central1europe-west2asia-northeast3 です。使用可能なリージョンの一覧については、Vertex AI の生成 AI のロケーションをご覧ください。
  • PROJECT_ID: Google Cloud プロジェクト ID
  • IMAGE_URI: エンベディングを取得するターゲット動画の Cloud Storage URI。例: gs://my-bucket/embeddings/supermarket-img.png

    また、画像を base64 エンコードのバイト文字列として指定することもできます。

    [...]
    "image": {
      "bytesBase64Encoded": "B64_ENCODED_IMAGE"
    }
    [...]
    
  • TEXT: エンベディングを取得するターゲット テキスト。例: a cat
  • EMBEDDING_DIMENSION: エンベディング ディメンションの数。値を小さくすると、後続のタスクでこれらのエンベディングを使用する際のレイテンシが低くなります。値が高いほど、精度が向上します。使用可能な値: 1282565121408(デフォルト)。

HTTP メソッドと URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/multimodalembedding@001:predict

リクエストの本文(JSON):

{
  "instances": [
    {
      "image": {
        "gcsUri": "IMAGE_URI"
      },
      "text": "TEXT"
    }
  ],
  "parameters": {
    "dimension": EMBEDDING_DIMENSION
  }
}

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/multimodalembedding@001:predict"

PowerShell

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/multimodalembedding@001:predict" | Select-Object -Expand Content
モデルのエンベディングは、指定したディメンションの浮動小数点ベクトルを返します。スペースの関係上、次のサンプル レスポンスは短縮されています。

128 ディメンション:

{
  "predictions": [
    {
      "imageEmbedding": [
        0.0279239565,
        [...128 dimension vector...]
        0.00403284049
      ],
      "textEmbedding": [
        0.202921599,
        [...128 dimension vector...]
        -0.0365431122
      ]
    }
  ],
  "deployedModelId": "DEPLOYED_MODEL_ID"
}

256 ディメンション:

{
  "predictions": [
    {
      "imageEmbedding": [
        0.248620048,
        [...256 dimension vector...]
        -0.0646447465
      ],
      "textEmbedding": [
        0.0757875815,
        [...256 dimension vector...]
        -0.02749932
      ]
    }
  ],
  "deployedModelId": "DEPLOYED_MODEL_ID"
}

512 ディメンション:

{
  "predictions": [
    {
      "imageEmbedding": [
        -0.0523675755,
        [...512 dimension vector...]
        -0.0444030389
      ],
      "textEmbedding": [
        -0.0592851527,
        [...512 dimension vector...]
        0.0350437127
      ]
    }
  ],
  "deployedModelId": "DEPLOYED_MODEL_ID"
}

エンベディング リクエストを送信する(画像とテキスト)

次のコードサンプルを使用して、画像データとテキストデータのエンベディング リクエストを送信します。サンプルでは、両方のデータ型でリクエストを送信する方法を示していますが、データ型別にサービスを使用することもできます。

テキストと画像のエンベディングを取得する

REST

multimodalembedding モデル リクエストの詳細については、multimodalembedding モデル API リファレンスをご覧ください。

リクエストのデータを使用する前に、次のように置き換えます。

  • LOCATION: プロジェクトのリージョン。たとえば、us-central1europe-west2asia-northeast3 です。使用可能なリージョンの一覧については、Vertex AI の生成 AI のロケーションをご覧ください。
  • PROJECT_ID: Google Cloud プロジェクト ID
  • TEXT: エンベディングを取得するターゲット テキスト。例: a cat
  • B64_ENCODED_IMG: エンベディングを取得するターゲット画像。画像は base64 でエンコードされたバイト文字列として指定する必要があります。

HTTP メソッドと URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/multimodalembedding@001:predict

リクエストの本文(JSON):

{
  "instances": [
    {
      "text": "TEXT",
      "image": {
        "bytesBase64Encoded": "B64_ENCODED_IMG"
      }
    }
  ]
}

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/multimodalembedding@001:predict"

PowerShell

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/multimodalembedding@001:predict" | Select-Object -Expand Content
モデルが返すエンベディングは、1,408 個の浮動小数点ベクトルです。スペースの関係上、次のサンプル レスポンスの一部は表示されていません。
{
  "predictions": [
    {
      "textEmbedding": [
        0.010477379,
        -0.00399621,
        0.00576670747,
        [...]
        -0.00823613815,
        -0.0169572588,
        -0.00472954148
      ],
      "imageEmbedding": [
        0.00262696808,
        -0.00198890246,
        0.0152047109,
        -0.0103145819,
        [...]
        0.0324628279,
        0.0284924973,
        0.011650892,
        -0.00452344026
      ]
    }
  ],
  "deployedModelId": "DEPLOYED_MODEL_ID"
}

Python

Python をインストールまたは更新する方法については、Vertex AI SDK for Python をインストールするをご覧ください。詳細については、Python API リファレンス ドキュメントをご覧ください。

from typing import Optional

import vertexai
from vertexai.vision_models import (
    Image,
    MultiModalEmbeddingModel,
    MultiModalEmbeddingResponse,
)

def get_image_embeddings(
    project_id: str,
    location: str,
    image_path: str,
    contextual_text: Optional[str] = None,
) -> MultiModalEmbeddingResponse:
    """Example of how to generate multimodal embeddings from image and text.

    Args:
        project_id: Google Cloud Project ID, used to initialize vertexai
        location: Google Cloud Region, used to initialize vertexai
        image_path: Path to image (local or Google Cloud Storage) to generate embeddings for.
        contextual_text: Text to generate embeddings for.
    """

    vertexai.init(project=project_id, location=location)

    model = MultiModalEmbeddingModel.from_pretrained("multimodalembedding")
    image = Image.load_from_file(image_path)

    embeddings = model.get_embeddings(
        image=image,
        contextual_text=contextual_text,
    )
    print(f"Image Embedding: {embeddings.image_embedding}")
    print(f"Text Embedding: {embeddings.text_embedding}")

Node.js

このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある Node.js の設定手順を完了してください。詳細については、Vertex AI Node.js API のリファレンス ドキュメントをご覧ください。

Vertex AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

/**
 * TODO(developer): Uncomment these variables before running the sample.\
 * (Not necessary if passing values as arguments)
 */
// const project = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION';
// const bastImagePath = "YOUR_BASED_IMAGE_PATH"
// const textPrompt = 'YOUR_TEXT_PROMPT';
const aiplatform = require('@google-cloud/aiplatform');

// Imports the Google Cloud Prediction service client
const {PredictionServiceClient} = aiplatform.v1;

// Import the helper module for converting arbitrary protobuf.Value objects.
const {helpers} = aiplatform;

// Specifies the location of the api endpoint
const clientOptions = {
  apiEndpoint: 'us-central1-aiplatform.googleapis.com',
};
const publisher = 'google';
const model = 'multimodalembedding@001';

// Instantiates a client
const predictionServiceClient = new PredictionServiceClient(clientOptions);

async function predictImageFromImageAndText() {
  // Configure the parent resource
  const endpoint = `projects/${project}/locations/${location}/publishers/${publisher}/models/${model}`;

  const fs = require('fs');
  const imageFile = fs.readFileSync(baseImagePath);

  // Convert the image data to a Buffer and base64 encode it.
  const encodedImage = Buffer.from(imageFile).toString('base64');

  const prompt = {
    text: textPrompt,
    image: {
      bytesBase64Encoded: encodedImage,
    },
  };
  const instanceValue = helpers.toValue(prompt);
  const instances = [instanceValue];

  const parameter = {
    sampleCount: 1,
  };
  const parameters = helpers.toValue(parameter);

  const request = {
    endpoint,
    instances,
    parameters,
  };

  // Predict request
  const [response] = await predictionServiceClient.predict(request);
  console.log('Get image embedding response');
  const predictions = response.predictions;
  console.log('\tPredictions :');
  for (const prediction of predictions) {
    console.log(`\t\tPrediction : ${JSON.stringify(prediction)}`);
  }
}

await predictImageFromImageAndText();

Java

このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある Java の設定手順を完了してください。詳細については、Vertex AI Java API のリファレンス ドキュメントをご覧ください。

Vertex AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。


import com.google.cloud.aiplatform.v1beta1.EndpointName;
import com.google.cloud.aiplatform.v1beta1.PredictResponse;
import com.google.cloud.aiplatform.v1beta1.PredictionServiceClient;
import com.google.cloud.aiplatform.v1beta1.PredictionServiceSettings;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Value;
import com.google.protobuf.util.JsonFormat;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PredictImageFromImageAndTextSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace this variable before running the sample.
    String project = "YOUR_PROJECT_ID";
    String textPrompt = "YOUR_TEXT_PROMPT";
    String baseImagePath = "YOUR_BASE_IMAGE_PATH";

    // Learn how to use text prompts to update an image:
    // https://cloud.google.com/vertex-ai/docs/generative-ai/image/edit-images
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("sampleCount", 1);

    String location = "us-central1";
    String publisher = "google";
    String model = "multimodalembedding@001";

    predictImageFromImageAndText(
        project, location, publisher, model, textPrompt, baseImagePath, parameters);
  }

  // Update images using text prompts
  public static void predictImageFromImageAndText(
      String project,
      String location,
      String publisher,
      String model,
      String textPrompt,
      String baseImagePath,
      Map<String, Object> parameters)
      throws IOException {
    final String endpoint = String.format("%s-aiplatform.googleapis.com:443", location);
    final PredictionServiceSettings predictionServiceSettings =
        PredictionServiceSettings.newBuilder().setEndpoint(endpoint).build();

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (PredictionServiceClient predictionServiceClient =
        PredictionServiceClient.create(predictionServiceSettings)) {
      final EndpointName endpointName =
          EndpointName.ofProjectLocationPublisherModelName(project, location, publisher, model);

      // Convert the image to Base64
      byte[] imageData = Base64.getEncoder().encode(Files.readAllBytes(Paths.get(baseImagePath)));
      String encodedImage = new String(imageData, StandardCharsets.UTF_8);

      JsonObject jsonInstance = new JsonObject();
      jsonInstance.addProperty("text", textPrompt);
      JsonObject jsonImage = new JsonObject();
      jsonImage.addProperty("bytesBase64Encoded", encodedImage);
      jsonInstance.add("image", jsonImage);

      Value instanceValue = stringToValue(jsonInstance.toString());
      List<Value> instances = new ArrayList<>();
      instances.add(instanceValue);

      Gson gson = new Gson();
      String gsonString = gson.toJson(parameters);
      Value parameterValue = stringToValue(gsonString);

      PredictResponse predictResponse =
          predictionServiceClient.predict(endpointName, instances, parameterValue);
      System.out.println("Predict Response");
      System.out.println(predictResponse);
      for (Value prediction : predictResponse.getPredictionsList()) {
        System.out.format("\tPrediction: %s\n", prediction);
      }
    }
  }

  // Convert a Json string to a protobuf.Value
  static Value stringToValue(String value) throws InvalidProtocolBufferException {
    Value.Builder builder = Value.newBuilder();
    JsonFormat.parser().merge(value, builder);
    return builder.build();
  }
}

エンベディング リクエストを送信する(動画、画像、テキスト)

エンベディング リクエストを送信するときに、入力動画のみを指定することも、動画、画像、テキストデータの組み合わせを指定することもできます。

動画エンベディング モード

動画エンベディングでは、Essentials、Standard、Plus の 3 つのモードを使用できます。モードは、生成されるエンベディングの密度に対応します。これは、リクエストの interval_sec 構成で指定できます。動画の間隔(interval_sec)ごとにエンベディングが生成されます。動画の最小間隔は 4 秒です。間隔が 120 秒を超えると、生成されたエンベディングの品質に悪影響を及ぼす可能性があります。

動画エンベディングの料金は、使用するモードによって異なります。詳細は、料金をご覧ください。

次の表に、動画のエンベディングに使用できる 3 つのモードをまとめます。

モード 1 分あたりの最大エンベディング数 動画のエンベディング間隔(最小値)
Essential 4 15

これは intervalSec >= 15 に対応します
Standard 8 8

これは 8 <= intervalSec < 15 に対応します
Plus 15 4

これは 4 <= intervalSec < 8 に対応します。

動画エンベディングのベスト プラクティス

動画エンベディングのリクエストを送信する場合は、次の点を考慮してください。

  • 任意の長さの入力動画の最初の 2 分間に単一のエンベディングを生成するには、次の videoSegmentConfig 設定を使用します。

    request.json:

    // other request body content
    "videoSegmentConfig": {
      "intervalSec": 120
    }
    // other request body content
    
  • 長さが 2 分を超える動画のエンベディングを生成するには、videoSegmentConfig で開始時間と終了時間を指定する複数のリクエストを送信します。

    request1.json:

    // other request body content
    "videoSegmentConfig": {
      "startOffsetSec": 0,
      "endOffsetSec": 120
    }
    // other request body content
    

    request2.json:

    // other request body content
    "videoSegmentConfig": {
      "startOffsetSec": 120,
      "endOffsetSec": 240
    }
    // other request body content
    

動画のエンベディングを取得する

動画コンテンツのみのエンベディングを取得するには、次のサンプルを使用します。

REST

multimodalembedding モデル リクエストの詳細については、multimodalembedding モデル API リファレンスをご覧ください。

次の例では、Cloud Storage にある動画を使用します。video.bytesBase64Encoded フィールドを使用して、動画の base64 エンコード文字列表現を指定することもできます。

リクエストのデータを使用する前に、次のように置き換えます。

  • LOCATION: プロジェクトのリージョン。たとえば、us-central1europe-west2asia-northeast3 です。使用可能なリージョンの一覧については、Vertex AI の生成 AI のロケーションをご覧ください。
  • PROJECT_ID: Google Cloud プロジェクト ID
  • VIDEO_URI: エンベディングを取得するターゲット動画の Cloud Storage URI。例: gs://my-bucket/embeddings/supermarket-video.mp4

    また、動画を base64 エンコードのバイト文字列として指定することもできます。

    [...]
    "video": {
      "bytesBase64Encoded": "B64_ENCODED_VIDEO"
    }
    [...]
    
  • videoSegmentConfig (START_SECOND, END_SECOND, INTERVAL_SECONDS)。省略可。エンベディングが生成される特定の動画セグメント(秒単位)。

    例:

    [...]
    "videoSegmentConfig": {
      "startOffsetSec": 10,
      "endOffsetSec": 60,
      "intervalSec": 10
    }
    [...]

    この構成を使用して、10 秒から 60 秒までの動画データを指定し、[10, 20), [20, 30), [30, 40), [40, 50), [50, 60) の 10 秒の動画間隔のエンベディングを生成します。この動画間隔("intervalSec": 10)は、Standard 動画エンベディング モードになり、ユーザーには Standard モードの料金レートで請求されます。

    videoSegmentConfig を省略すると、サービスはデフォルト値の "videoSegmentConfig": { "startOffsetSec": 0, "endOffsetSec": 120, "intervalSec": 16 } を使用します。この動画間隔("intervalSec": 16)は、Essential 動画エンベディング モードになり、ユーザーには Essential モードの料金レートで請求されます。

HTTP メソッドと URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/multimodalembedding@001:predict

リクエストの本文(JSON):

{
  "instances": [
    {
      "video": {
        "gcsUri": "VIDEO_URI",
        "videoSegmentConfig": {
          "startOffsetSec": START_SECOND,
          "endOffsetSec": END_SECOND,
          "intervalSec": INTERVAL_SECONDS
        }
      }
    }
  ]
}

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/multimodalembedding@001:predict"

PowerShell

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/multimodalembedding@001:predict" | Select-Object -Expand Content
モデルが返すエンベディングは、1,408 個の浮動小数点ベクトルです。スペースの関係上、次のサンプル レスポンスは短縮されています。

レスポンス(7 秒の動画、videoSegmentConfig の指定なし):

{
  "predictions": [
    {
      "videoEmbeddings": [
        {
          "endOffsetSec": 7,
          "embedding": [
            -0.0045467657,
            0.0258095954,
            0.0146885719,
            0.00945400633,
            [...]
            -0.0023291884,
            -0.00493789,
            0.00975185353,
            0.0168156829
          ],
          "startOffsetSec": 0
        }
      ]
    }
  ],
  "deployedModelId": "DEPLOYED_MODEL_ID"
}

レスポンス(59 秒の動画、動画セグメントの構成: "videoSegmentConfig": { "startOffsetSec": 0, "endOffsetSec": 60, "intervalSec": 10 }):

{
  "predictions": [
    {
      "videoEmbeddings": [
        {
          "endOffsetSec": 10,
          "startOffsetSec": 0,
          "embedding": [
            -0.00683252793,
            0.0390476175,
            [...]
            0.00657121744,
            0.013023301
          ]
        },
        {
          "startOffsetSec": 10,
          "endOffsetSec": 20,
          "embedding": [
            -0.0104404651,
            0.0357737206,
            [...]
            0.00509833824,
            0.0131902946
          ]
        },
        {
          "startOffsetSec": 20,
          "embedding": [
            -0.0113538112,
            0.0305239167,
            [...]
            -0.00195809244,
            0.00941874553
          ],
          "endOffsetSec": 30
        },
        {
          "embedding": [
            -0.00299320649,
            0.0322436653,
            [...]
            -0.00993082579,
            0.00968887936
          ],
          "startOffsetSec": 30,
          "endOffsetSec": 40
        },
        {
          "endOffsetSec": 50,
          "startOffsetSec": 40,
          "embedding": [
            -0.00591270532,
            0.0368893594,
            [...]
            -0.00219071587,
            0.0042470959
          ]
        },
        {
          "embedding": [
            -0.00458270218,
            0.0368121453,
            [...]
            -0.00317760976,
            0.00595594104
          ],
          "endOffsetSec": 59,
          "startOffsetSec": 50
        }
      ]
    }
  ],
  "deployedModelId": "DEPLOYED_MODEL_ID"
}

Python

Python をインストールまたは更新する方法については、Vertex AI SDK for Python をインストールするをご覧ください。詳細については、Python API リファレンス ドキュメントをご覧ください。

from typing import Optional

import vertexai
from vertexai.vision_models import (
    MultiModalEmbeddingModel,
    MultiModalEmbeddingResponse,
    Video,
    VideoSegmentConfig,
)

def get_video_embeddings(
    project_id: str,
    location: str,
    video_path: str,
    contextual_text: Optional[str] = None,
    dimension: Optional[int] = 1408,
    video_segment_config: Optional[VideoSegmentConfig] = None,
) -> MultiModalEmbeddingResponse:
    """Example of how to generate multimodal embeddings from video and text.

    Args:
        project_id: Google Cloud Project ID, used to initialize vertexai
        location: Google Cloud Region, used to initialize vertexai
        video_path: Path to video (local or Google Cloud Storage) to generate embeddings for.
        contextual_text: Text to generate embeddings for.
        dimension: Dimension for the returned embeddings.
            https://cloud.google.com/vertex-ai/docs/generative-ai/embeddings/get-multimodal-embeddings#low-dimension
        video_segment_config: Define specific segments to generate embeddings for.
            https://cloud.google.com/vertex-ai/docs/generative-ai/embeddings/get-multimodal-embeddings#video-best-practices
    """

    vertexai.init(project=project_id, location=location)

    model = MultiModalEmbeddingModel.from_pretrained("multimodalembedding")
    video = Video.load_from_file(video_path)

    embeddings = model.get_embeddings(
        video=video,
        video_segment_config=video_segment_config,
        contextual_text=contextual_text,
        dimension=dimension,
    )

    # Video Embeddings are segmented based on the video_segment_config.
    print("Video Embeddings:")
    for video_embedding in embeddings.video_embeddings:
        print(
            f"Video Segment: {video_embedding.start_offset_sec} - {video_embedding.end_offset_sec}"
        )
        print(f"Embedding: {video_embedding.embedding}")

    print(f"Text Embedding: {embeddings.text_embedding}")

画像、テキスト、動画のエンベディングを取得する

次のサンプルを使用して、動画、テキスト、画像コンテンツのエンベディングを取得します。

REST

multimodalembedding モデル リクエストの詳細については、multimodalembedding モデル API リファレンスをご覧ください。

次の例では、画像、テキスト、動画のデータを使用します。リクエストの本文で、これらのデータ型を任意に組み合わせて使用できます。

また、このサンプルでは Cloud Storage にある動画を使用しています。video.bytesBase64Encoded フィールドを使用して、動画の base64 エンコード文字列表現を指定することもできます。

リクエストのデータを使用する前に、次のように置き換えます。

  • LOCATION: プロジェクトのリージョン。たとえば、us-central1europe-west2asia-northeast3 です。使用可能なリージョンの一覧については、Vertex AI の生成 AI のロケーションをご覧ください。
  • PROJECT_ID: Google Cloud プロジェクト ID
  • TEXT: エンベディングを取得するターゲット テキスト。例: a cat
  • IMAGE_URI: エンベディングを取得するターゲット動画の Cloud Storage URI。例: gs://my-bucket/embeddings/supermarket-img.png

    また、画像を base64 エンコードのバイト文字列として指定することもできます。

    [...]
    "image": {
      "bytesBase64Encoded": "B64_ENCODED_IMAGE"
    }
    [...]
    
  • VIDEO_URI: エンベディングを取得するターゲット動画の Cloud Storage URI。例: gs://my-bucket/embeddings/supermarket-video.mp4

    また、動画を base64 エンコードのバイト文字列として指定することもできます。

    [...]
    "video": {
      "bytesBase64Encoded": "B64_ENCODED_VIDEO"
    }
    [...]
    
  • videoSegmentConfig (START_SECOND, END_SECOND, INTERVAL_SECONDS)。省略可。エンベディングが生成される特定の動画セグメント(秒単位)。

    例:

    [...]
    "videoSegmentConfig": {
      "startOffsetSec": 10,
      "endOffsetSec": 60,
      "intervalSec": 10
    }
    [...]

    この構成を使用して、10 秒から 60 秒までの動画データを指定し、[10, 20), [20, 30), [30, 40), [40, 50), [50, 60) の 10 秒の動画間隔のエンベディングを生成します。この動画間隔("intervalSec": 10)は、Standard 動画エンベディング モードになり、ユーザーには Standard モードの料金レートで請求されます。

    videoSegmentConfig を省略すると、サービスはデフォルト値の "videoSegmentConfig": { "startOffsetSec": 0, "endOffsetSec": 120, "intervalSec": 16 } を使用します。この動画間隔("intervalSec": 16)は、Essential 動画エンベディング モードになり、ユーザーには Essential モードの料金レートで請求されます。

HTTP メソッドと URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/multimodalembedding@001:predict

リクエストの本文(JSON):

{
  "instances": [
    {
      "text": "TEXT",
      "image": {
        "gcsUri": "IMAGE_URI"
      },
      "video": {
        "gcsUri": "VIDEO_URI",
        "videoSegmentConfig": {
          "startOffsetSec": START_SECOND,
          "endOffsetSec": END_SECOND,
          "intervalSec": INTERVAL_SECONDS
        }
      }
    }
  ]
}

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/multimodalembedding@001:predict"

PowerShell

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/multimodalembedding@001:predict" | Select-Object -Expand Content
モデルが返すエンベディングは、1,408 個の浮動小数点ベクトルです。スペースの関係上、次のサンプル レスポンスの一部は表示されていません。
{
  "predictions": [
    {
      "textEmbedding": [
        0.0105433334,
        -0.00302835181,
        0.00656806398,
        0.00603460241,
        [...]
        0.00445805816,
        0.0139605571,
        -0.00170318608,
        -0.00490092579
      ],
      "videoEmbeddings": [
        {
          "startOffsetSec": 0,
          "endOffsetSec": 7,
          "embedding": [
            -0.00673126569,
            0.0248149596,
            0.0128901172,
            0.0107588246,
            [...]
            -0.00180952181,
            -0.0054573305,
            0.0117037306,
            0.0169312079
          ]
        }
      ],
      "imageEmbedding": [
        -0.00728622358,
        0.031021487,
        -0.00206603738,
        0.0273937676,
        [...]
        -0.00204976718,
        0.00321615417,
        0.0121978866,
        0.0193375275
      ]
    }
  ],
  "deployedModelId": "DEPLOYED_MODEL_ID"
}

Python

Python をインストールまたは更新する方法については、Vertex AI SDK for Python をインストールするをご覧ください。詳細については、Python API リファレンス ドキュメントをご覧ください。

from typing import Optional

import vertexai
from vertexai.vision_models import (
    Image,
    MultiModalEmbeddingModel,
    MultiModalEmbeddingResponse,
    Video,
    VideoSegmentConfig,
)

def get_image_video_text_embeddings(
    project_id: str,
    location: str,
    image_path: str,
    video_path: str,
    contextual_text: Optional[str] = None,
    dimension: Optional[int] = 1408,
    video_segment_config: Optional[VideoSegmentConfig] = None,
) -> MultiModalEmbeddingResponse:
    """Example of how to generate multimodal embeddings from image, video, and text.

    Args:
        project_id: Google Cloud Project ID, used to initialize vertexai
        location: Google Cloud Region, used to initialize vertexai
        image_path: Path to image (local or Google Cloud Storage) to generate embeddings for.
        video_path: Path to video (local or Google Cloud Storage) to generate embeddings for.
        contextual_text: Text to generate embeddings for.
        dimension: Dimension for the returned embeddings.
            https://cloud.google.com/vertex-ai/docs/generative-ai/embeddings/get-multimodal-embeddings#low-dimension
        video_segment_config: Define specific segments to generate embeddings for.
            https://cloud.google.com/vertex-ai/docs/generative-ai/embeddings/get-multimodal-embeddings#video-best-practices
    """

    vertexai.init(project=project_id, location=location)

    model = MultiModalEmbeddingModel.from_pretrained("multimodalembedding")
    image = Image.load_from_file(image_path)
    video = Video.load_from_file(video_path)

    embeddings = model.get_embeddings(
        image=image,
        video=video,
        video_segment_config=video_segment_config,
        contextual_text=contextual_text,
        dimension=dimension,
    )

    print(f"Image Embedding: {embeddings.image_embedding}")

    # Video Embeddings are segmented based on the video_segment_config.
    print("Video Embeddings:")
    for video_embedding in embeddings.video_embeddings:
        print(
            f"Video Segment: {video_embedding.start_offset_sec} - {video_embedding.end_offset_sec}"
        )
        print(f"Embedding: {video_embedding.embedding}")

    print(f"Text Embedding: {embeddings.text_embedding}")

次のステップ