Mendapatkan inferensi dari model pengenalan tindakan video

Halaman ini menunjukkan cara mendapatkan inferensi batch dari model pengenalan tindakan video menggunakan konsol Google Cloud atau Vertex AI API. Inferensi batch adalah permintaan asinkron. Anda meminta inferensi batch langsung dari resource model tanpa perlu men-deploy model ke endpoint.

Model video AutoML tidak mendukung inferensi online.

Mendapatkan inferensi batch

Untuk membuat permintaan inferensi batch, tentukan sumber input dan format output tempat Vertex AI menyimpan hasil inferensi.

Persyaratan data input

Input untuk permintaan batch menentukan item yang akan dikirim ke model Anda untuk inferensi. Inferensi batch untuk jenis model video AutoML menggunakan file JSON Lines untuk menentukan daftar video yang akan dibuat inferensinya, lalu menyimpan file JSON Lines tersebut di bucket Cloud Storage. Anda dapat menentukan Infinity untuk kolom timeSegmentEnd guna menentukan akhir video. Contoh berikut menunjukkan satu baris dalam file JSON Lines input.

{'content': 'gs://sourcebucket/datasets/videos/source_video.mp4', 'mimeType': 'video/mp4', 'timeSegmentStart': '0.0s', 'timeSegmentEnd': '2.366667s'}

Meminta inferensi batch

Untuk permintaan inferensi batch, Anda dapat menggunakan konsol Google Cloud atau Vertex AI API. Bergantung pada jumlah item input yang Anda kirimkan, tugas inferensi batch dapat memerlukan waktu beberapa saat untuk diselesaikan.

Google Cloud console

Gunakan konsol Google Cloud untuk meminta inferensi batch.

  1. Di konsol Google Cloud , di bagian Vertex AI, buka halaman Prediksi batch.

    Buka halaman Prediksi batch

  2. Klik Create untuk membuka jendela New batch predictions dan selesaikan langkah-langkah berikut:

    1. Masukkan nama untuk inferensi batch.
    2. Untuk Model name, pilih nama model yang akan digunakan untuk inferensi batch ini.
    3. Untuk Source path, tentukan lokasi Cloud Storage tempat file input JSON Lines Anda berada.
    4. Untuk Destination path, tentukan lokasi Cloud Storage tempat hasil inferensi batch disimpan. Format Output ditentukan oleh tujuan model Anda. Model AutoML untuk tujuan gambar menghasilkan file JSON Lines.

API

Gunakan Vertex AI API untuk mengirim permintaan inferensi batch.

REST

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • LOCATION_ID: Region tempat Model disimpan dan tugas inferensi batch dijalankan. Misalnya, us-central1.
  • PROJECT_ID: Project ID Anda
  • BATCH_JOB_NAME: Nama tampilan untuk tugas batch
  • MODEL_ID: ID yang digunakan oleh model untuk membuat inferensi
  • THRESHOLD_VALUE (opsional): Model hanya menampilkan inferensi yang memiliki skor keyakinan dengan minimal nilai ini
  • URI: Cloud Storage URI tempat file JSON Lines input Anda berada.
  • BUCKET: Bucket Cloud Storage Anda
  • PROJECT_NUMBER: Nomor project yang dibuat secara otomatis untuk project Anda

Metode HTTP dan URL:

POST https://LOCATION_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/batchPredictionJobs

Isi JSON permintaan:

{
    "displayName": "BATCH_JOB_NAME",
    "model": "projects/PROJECT_ID/locations/LOCATION_ID/models/MODEL_ID",
    "modelParameters": {
      "confidenceThreshold": THRESHOLD_VALUE,
    },
    "inputConfig": {
        "instancesFormat": "jsonl",
        "gcsSource": {
            "uris": ["URI"],
        },
    },
    "outputConfig": {
        "predictionsFormat": "jsonl",
        "gcsDestination": {
            "outputUriPrefix": "OUTPUT_BUCKET",
        },
    },
}

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

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

PowerShell

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

$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_ID-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/batchPredictionJobs" | Select-Object -Expand Content

Anda akan menerima respons JSON yang mirip seperti berikut:

{
  "name": "projects/PROJECT_NUMBER/locations/us-central1/batchPredictionJobs/BATCH_JOB_ID",
  "displayName": "BATCH_JOB_NAME",
  "model": "projects/PROJECT_NUMBER/locations/us-central1/models/MODEL_ID",
  "inputConfig": {
    "instancesFormat": "jsonl",
    "gcsSource": {
      "uris": [
        "CONTENT"
      ]
    }
  },
  "outputConfig": {
    "predictionsFormat": "jsonl",
    "gcsDestination": {
      "outputUriPrefix": "BUCKET"
    }
  },
  "state": "JOB_STATE_PENDING",
  "createTime": "2020-05-30T02:58:44.341643Z",
  "updateTime": "2020-05-30T02:58:44.341643Z",
  "modelDisplayName": "MODEL_NAME",
  "modelObjective": "MODEL_OBJECTIVE"
}

Anda dapat melakukan polling untuk status tugas batch menggunakan BATCH_JOB_ID hingga state tugas menjadi JOB_STATE_SUCCEEDED.

Java

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di Panduan memulai Vertex AI menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Java Vertex AI.

Untuk melakukan autentikasi ke Vertex AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import com.google.cloud.aiplatform.util.ValueConverter;
import com.google.cloud.aiplatform.v1.BatchPredictionJob;
import com.google.cloud.aiplatform.v1.GcsDestination;
import com.google.cloud.aiplatform.v1.GcsSource;
import com.google.cloud.aiplatform.v1.JobServiceClient;
import com.google.cloud.aiplatform.v1.JobServiceSettings;
import com.google.cloud.aiplatform.v1.LocationName;
import com.google.cloud.aiplatform.v1.ModelName;
import com.google.protobuf.Value;
import java.io.IOException;

public class CreateBatchPredictionJobVideoActionRecognitionSample {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String project = "PROJECT";
    String displayName = "DISPLAY_NAME";
    String model = "MODEL";
    String gcsSourceUri = "GCS_SOURCE_URI";
    String gcsDestinationOutputUriPrefix = "GCS_DESTINATION_OUTPUT_URI_PREFIX";
    createBatchPredictionJobVideoActionRecognitionSample(
        project, displayName, model, gcsSourceUri, gcsDestinationOutputUriPrefix);
  }

  static void createBatchPredictionJobVideoActionRecognitionSample(
      String project,
      String displayName,
      String model,
      String gcsSourceUri,
      String gcsDestinationOutputUriPrefix)
      throws IOException {
    JobServiceSettings settings =
        JobServiceSettings.newBuilder()
            .setEndpoint("us-central1-aiplatform.googleapis.com:443")
            .build();
    String location = "us-central1";

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (JobServiceClient client = JobServiceClient.create(settings)) {
      Value modelParameters = ValueConverter.EMPTY_VALUE;
      GcsSource gcsSource = GcsSource.newBuilder().addUris(gcsSourceUri).build();
      BatchPredictionJob.InputConfig inputConfig =
          BatchPredictionJob.InputConfig.newBuilder()
              .setInstancesFormat("jsonl")
              .setGcsSource(gcsSource)
              .build();
      GcsDestination gcsDestination =
          GcsDestination.newBuilder().setOutputUriPrefix(gcsDestinationOutputUriPrefix).build();
      BatchPredictionJob.OutputConfig outputConfig =
          BatchPredictionJob.OutputConfig.newBuilder()
              .setPredictionsFormat("jsonl")
              .setGcsDestination(gcsDestination)
              .build();

      String modelName = ModelName.of(project, location, model).toString();

      BatchPredictionJob batchPredictionJob =
          BatchPredictionJob.newBuilder()
              .setDisplayName(displayName)
              .setModel(modelName)
              .setModelParameters(modelParameters)
              .setInputConfig(inputConfig)
              .setOutputConfig(outputConfig)
              .build();
      LocationName parent = LocationName.of(project, location);
      BatchPredictionJob response = client.createBatchPredictionJob(parent, batchPredictionJob);
      System.out.format("response: %s\n", response);
      System.out.format("\tName: %s\n", response.getName());
    }
  }
}

Python

Untuk mempelajari cara menginstal atau mengupdate Vertex AI SDK untuk Python, lihat Menginstal Vertex AI SDK untuk Python. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi API Python.

def create_batch_prediction_job_sample(
    project: str,
    location: str,
    model_resource_name: str,
    job_display_name: str,
    gcs_source: Union[str, Sequence[str]],
    gcs_destination: str,
    sync: bool = True,
):
    aiplatform.init(project=project, location=location)

    my_model = aiplatform.Model(model_resource_name)

    batch_prediction_job = my_model.batch_predict(
        job_display_name=job_display_name,
        gcs_source=gcs_source,
        gcs_destination_prefix=gcs_destination,
        sync=sync,
    )

    batch_prediction_job.wait()

    print(batch_prediction_job.display_name)
    print(batch_prediction_job.resource_name)
    print(batch_prediction_job.state)
    return batch_prediction_job

Mengambil hasil inferensi batch

Vertex AI mengirimkan output inferensi batch ke tujuan yang Anda tentukan.

Setelah tugas inferensi batch selesai, output inferensi akan disimpan di bucket Cloud Storage yang Anda tentukan dalam permintaan Anda.

Contoh hasil inferensi batch

Berikut ini contoh hasil inferensi batch dari model pengenalan tindakan video.

{
  "instance": {
   "content": "gs://bucket/video.mp4",
    "mimeType": "video/mp4",
    "timeSegmentStart": "1s",
    "timeSegmentEnd": "5s"
  }
  "prediction": [{
    "id": "1",
    "displayName": "swing",
    "timeSegmentStart": "1.2s",
    "timeSegmentEnd": "1.2s",
    "confidence": 0.7
  }, {
    "id": "2",
    "displayName": "jump",
    "timeSegmentStart": "3.4s",
    "timeSegmentEnd": "3.4s",
    "confidence": 0.5
  }]
}