동영상 동작 인식 모델에서 예측 가져오기

이 페이지에서는 Google Cloud 콘솔 또는 Vertex AI API를 사용하여 동영상 동작 인식 모델에서 일괄 예측을 얻는 방법을 보여줍니다. 일괄 예측은 비동기식 요청입니다. 모델을 엔드포인트에 배포할 필요 없이 모델 리소스에서 직접 일괄 예측을 요청합니다.

AutoML 동영상 모델은 온라인 예측을 지원하지 않습니다.

일괄 예측 가져오기

일괄 예측 요청을 수행하려면 Vertex AI가 예측 결과를 저장하는 입력 소스출력 형식을 지정합니다.

입력 데이터 요구사항

일괄 요청의 입력은 예측을 위해 모델에 보낼 항목을 지정합니다. AutoML 동영상 모델 유형의 일괄 예측은 JSON Lines 파일을 사용하여 예측할 동영상 목록을 지정한 다음 JSON Lines 파일을 Cloud Storage 버킷에 저장합니다. timeSegmentEnd 필드에 Infinity를 지정하여 동영상 종료 지점을 지정할 수 있습니다. 다음 샘플에서는 입력 JSON Lines 파일의 단일 줄을 보여줍니다.

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

배치 예측 요청

일괄 예측 요청의 경우 Google Cloud 콘솔 또는 Vertex AI API를 사용할 수 있습니다. 제출한 입력 항목 수에 따라 일괄 예측 태스크를 완료하는 데 다소 시간이 걸릴 수 있습니다.

Google Cloud 콘솔

Google Cloud 콘솔을 사용하여 일괄 예측을 요청합니다.

  1. Google Cloud 콘솔의 Vertex AI 섹션에서 일괄 예측 페이지로 이동합니다.

    일괄 예측 페이지로 이동

  2. 만들기를 클릭하여 새 일괄 예측 창을 열고 다음 단계를 완료합니다.

    1. 일괄 예측의 이름을 입력합니다.
    2. 모델 이름에서 이 일괄 예측에 사용할 모델의 이름을 선택합니다.
    3. 소스 경로에서 JSON Lines 입력 파일이 있는 Cloud Storage 위치를 지정합니다.
    4. 대상 경로에서 일괄 예측 결과가 저장되는 Cloud Storage 위치를 지정합니다. 출력 형식은 모델의 목표에 따라 결정됩니다. 이미지 목표의 AutoML 모델은 JSON Lines 파일을 출력합니다.

API

Vertex AI API를 사용하여 일괄 예측 요청을 전송합니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • LOCATION_ID: 모델이 저장되고 일괄 예측 작업이 실행되는 리전. 예를 들면 us-central1입니다.
  • PROJECT_ID: 프로젝트 ID
  • BATCH_JOB_NAME: 일괄 작업의 표시 이름
  • MODEL_ID: 예측을 수행하는 데 사용할 모델의 ID입니다.
  • THRESHOLD_VALUE(선택사항): 모델은 신뢰도가 이 값 이상인 예측만 반환합니다.
  • URI: 입력 JSON Lines 파일이 있는 Cloud Storage URI입니다.
  • BUCKET: Cloud Storage 버킷
  • PROJECT_NUMBER: 프로젝트의 자동으로 생성된 프로젝트 번호

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
    "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",
        },
    },
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

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

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

다음과 비슷한 JSON 응답이 표시됩니다.

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

작업 stateJOB_STATE_SUCCEEDED가 될 때까지 BATCH_JOB_ID를 사용하여 일괄 작업의 상태를 폴링할 수 있습니다.

Java

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용Java 설정 안내를 따르세요. 자세한 내용은 Vertex AI Java API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

Python을 설치하거나 업데이트하는 방법은 Python용 Vertex AI SDK 설치를 참조하세요. 자세한 내용은 Python API 참고 문서를 참조하세요.

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

일괄 예측 결과 검색

Vertex AI는 지정된 대상에 일괄 예측 출력을 보냅니다.

일괄 예측 작업이 완료되면 요청에 지정한 Cloud Storage 버킷에 예측 결과가 저장됩니다.

일괄 예측 결과 예시

다음은 동작 인식 모델의 일괄 예측 결과 예시입니다.

{
  "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
  }]
}