동영상 주석 추가

모델을 학습시킨 후 동영상을 나열하는 batchPredict 메서드에 CSV 파일을 제공하여 예측을 요청할 수 있습니다. batchPredict 메서드는 모델에서 수행한 예측을 기반으로 라벨을 적용합니다.

모델의 최대 수명은 2년입니다. 그런 다음 새 모델을 학습시켜야 합니다.

예측 예시

AutoML Video에서 일괄 예측을 요청하려면 주석을 추가할 동영상에 대한 Cloud Storage 경로를 나열하는 CSV 파일을 만듭니다. 또한 시작 및 종료 시간을 지정하여 AutoML Video가 동영상의 세그먼트(세그먼트 수준)에만 주석을 추가하도록 지시할 수 있습니다. 시작 시간은 0 이상이고 종료 시간보다 이전이어야 합니다. 종료 시간은 시작 시간보다 커야 하고 동영상의 재생 시간보다 작거나 같아야 합니다. inf를 사용하여 동영상의 종료를 나타낼 수도 있습니다.

gs://my-videos-vcm/short_video_1.avi,0.0,5.566667
gs://my-videos-vcm/car_chase.avi,0.0,3.933333
gs://my-videos-vcm/northwest_wildlife_01.avi,0.0,3.7
gs://my-videos-vcm/northwest_wildlife_02.avi,0.0,1.666667
gs://my-videos-vcm/motorcycles_and_cars.avi,0.0,2.633333
gs://my-videos-vcm/drying_paint.avi,0.0,inf

또한 AutoML Video에서 모델의 예측 결과를 기록할 출력 파일 경로를 지정해야 합니다. 이 경로는 쓰기 권한이 있는 Cloud Storage 버킷 및 객체여야 합니다.

각 동영상의 최대 재생 시간은 3시간이며 최대 파일 크기는 50GB입니다. AutoML Video는 12시간의 처리 시간 안에 약 100시간의 동영상에 대한 예측을 생성할 수 있습니다

동영상의 예측을 요청하는 경우 params 섹션에서 다음 옵션을 설정할 수 있습니다. 이러한 옵션을 지정하지 않으면 기본 점수 임곗값이 적용되고 segment_classification이 사용됩니다.

  • score_threshold - 0.0(신뢰도 없음)~1.0(신뢰도 매우 높음) 사이의 값입니다. 모델이 동영상의 예측을 수행하면 최소한 지정한 신뢰도 점수가 있는 결과만 생성됩니다. API 기본값은 0.5입니다.

  • segment_classification - 세그먼트 수준의 분류를 사용하려면 true로 설정합니다. AutoML Video는 요청 구성에 지정한 동영상의 전체 세그먼트에 대한 라벨과 신뢰도 점수를 반환합니다. 기본값은 true입니다.

  • shot_classification - 장면 수준의 분류를 사용하려면 true로 설정합니다. AutoML Video는 요청 구성에 지정한 동영상의 전체 세그먼트에서 각 카메라 장면의 경계를 결정합니다. 그런 다음 AutoML Video Intelligence는 감지된 각 장면의 라벨과 신뢰도 점수를 장면의 시작 및 종료 시간과 함께 반환합니다. 기본값은 false입니다.

  • 1s_interval_classification - 동영상을 1초 간격으로 분류할 수 있게 하려면 true로 설정합니다. AutoML Video는 요청 구성에 지정한 동영상의 전체 세그먼트에서 초당 라벨과 신뢰도 점수를 반환합니다. 기본값은 false입니다.

웹 UI

  1. AutoML Video UI를 엽니다.
  2. 표시된 목록에서 사용할 모델을 클릭합니다. Cloud Console의 AutoML Video Intelligence 모델 목록
  3. 모델의 테스트 및 사용 탭에서 다음을 수행합니다.
    • 모델 테스트에서 예측에 사용할 CSV 파일을 선택합니다. CSV 파일은 주석을 추가하려는 동영상의 목록을 제공해야 합니다.
    • 또한 모델 테스트에서 주석 처리 결과를 수신할 Cloud Storage 버킷 안의 디렉토리를 선택합니다.

      실제로 Cloud Storage 버킷에 주석 결과를 보관할 특정 'results' 폴더를 만드는 것이 좋습니다. 이렇게 하면 결과 디렉터리에 포함된 video_classification.csv 파일을 로드하여 이전 예측에 더 쉽게 액세스할 수 있습니다.

    • 예측 가져오기를 클릭합니다.
    AutoML Video Intelligence의 예측 요청 구성

예측 가져오기 과정은 주석을 달고자 하는 동영상의 수에 따라 다소 시간이 걸릴 수 있습니다.

이 과정이 완료되면 최근 예측 아래 모델 페이지에 결과가 나타납니다. 결과를 보려면 다음 안내를 따르세요.

  1. 최근 예측 아래의 예측 열에서 확인하려는 예측 옆에 있는 보기를 클릭합니다.
  2. 동영상에서 결과를 보려는 동영상의 이름을 선택합니다.

AutoML Video Intelligence 예측 결과

REST

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

  • input-uri: 파일 이름을 포함하여 주석을 추가하고자 하는 파일을 포함한 Cloud Storage 버킷입니다. gs://로 시작해야 합니다. 예시:
    "inputUris": ["gs://automl-video-demo-data/hmdb_split1_test_gs_predict.csv"]
  • output-bucket을 Cloud Storage 버킷 이름으로 바꿉니다. 예를 들면 my-project-vcm입니다.
  • object-id: 데이터 가져오기 작업의 작업 ID로 바꿉니다.
  • 참고:
    • project-number: 프로젝트 수입니다.
    • location-id: 주석이 있어야 하는 Cloud 리전입니다. 지원되는 클라우드 리전은 us-east1, us-west1, europe-west1, asia-east1입니다. 리전을 지정하지 않으면 동영상 파일 위치를 기준으로 리전이 결정됩니다.

HTTP 메서드 및 URL:

POST https://automl.googleapis.com/v1beta1/projects/project-number/locations/location-id/models/model-id:batchPredict

JSON 요청 본문:

{
  "inputConfig": {
    "gcsSource": {
      "inputUris": [input-uri]
    }
  },
  "outputConfig": {
    "gcsDestination": {
      "outputUriPrefix": "gs://output-bucket/object-id"
    }
  }
}

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

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-number" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://automl.googleapis.com/v1beta1/projects/project-number/locations/location-id/models/model-id:batchPredict "

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-number" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://automl.googleapis.com/v1beta1/projects/project-number/locations/location-id/models/model-id:batchPredict " | Select-Object -Expand Content

일괄 예측 요청의 작업 ID를 받아야 합니다. 예시: VCN926615623331479552

CSV 파일에서 지정한 동영상의 수에 따라 일괄 예측 작업을 완료하는 데 다소 시간이 걸릴 수 있습니다. 작업이 완료되면 다음 예시와 같이 오류가 없는 작업의 상태에 done: true가 표시됩니다.

{
  "name": "projects/project-number/locations/location-id/operations/VCN926615623331479552",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1beta1.OperationMetadata",
    "createTime": "2020-02-11T21:39:19.832131Z",
    "updateTime": "2020-02-11T21:43:43.908318Z",
    "done": true,
    "batchPredictDetails": {
      "inputConfig": {
        "gcsSource": {
          "inputUris": [
            "gs://bucket-name/input-file.csv"
          ]
        }
      },
      "outputInfo": {
        "gcsOutputDirectory": "output-storage-path/prediction-test_model_01-2019-01-11T21:39:19.684Z"
      }
    }
  }
}

일괄 예측 작업이 완료되면 명령어에 지정된 Cloud Storage 버킷에 예측 출력이 저장됩니다. 각 동영상 세그먼트에 대한 JSON 파일이 있습니다. 예를 들면 다음과 같습니다.

my-video-01.avi.json

{
  "input_uri": "automl-video-sample/sample_video.avi",
  "segment_classification_annotations": [ {
    "annotation_spec": {
      "display_name": "ApplyLipstick",
      "description": "ApplyLipstick"
    },
    "segments": [ {
      "segment": {
        "start_time_offset": {
        },
        "end_time_offset": {
          "seconds": 4,
          "nanos": 960000000
        }
      },
      "confidence": 0.43253016
    }, {
      "segment": {
        "start_time_offset": {
        },
        "end_time_offset": {
          "seconds": 4,
          "nanos": 960000000
        }
      },
      "confidence": 0.56746984
    } ],
    "frames": [ ]
  } ],
  "shot_classification_annotations": [ {
    "annotation_spec": {
      "display_name": "ApplyLipstick",
      "description": "ApplyLipstick"
    },
    "segments": [ {
      "segment": {
        "start_time_offset": {
        },
        "end_time_offset": {
          "seconds": 5
        }
      },
      "confidence": 0.43253016
    }, {
      "segment": {
        "start_time_offset": {
        },
        "end_time_offset": {
          "seconds": 5
        }
      },
      "confidence": 0.56746984
    } ],
    "frames": [ ]
  } ],
  "one_second_sliding_window_classification_annotations": [ {
    "annotation_spec": {
      "display_name": "ApplyLipstick",
      "description": "ApplyLipstick"
    },
    "segments": [ ],
    "frames": [ {
      "time_offset": {
        "nanos": 800000000
      },
      "confidence": 0.54533803
    }, {
      "time_offset": {
        "nanos": 800000000
      },
      ...
      "confidence": 0.57945728
    }, {
      "time_offset": {
        "seconds": 4,
        "nanos": 300000000
      },
      "confidence": 0.42054281
    } ]
  } ],
  "object_annotations": [ ],
  "error": {
    "details": [ ]
  }
}

Java

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

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1beta1.BatchPredictInputConfig;
import com.google.cloud.automl.v1beta1.BatchPredictOutputConfig;
import com.google.cloud.automl.v1beta1.BatchPredictRequest;
import com.google.cloud.automl.v1beta1.BatchPredictResult;
import com.google.cloud.automl.v1beta1.GcsDestination;
import com.google.cloud.automl.v1beta1.GcsSource;
import com.google.cloud.automl.v1beta1.ModelName;
import com.google.cloud.automl.v1beta1.OperationMetadata;
import com.google.cloud.automl.v1beta1.PredictionServiceClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

abstract class BatchPredict {

  static void batchPredict() throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    String inputUri = "gs://YOUR_BUCKET_ID/path_to_your_input_csv_or_jsonl";
    String outputUri = "gs://YOUR_BUCKET_ID/path_to_save_results/";
    batchPredict(projectId, modelId, inputUri, outputUri);
  }

  static void batchPredict(String projectId, String modelId, String inputUri, String outputUri)
      throws IOException, ExecutionException, InterruptedException {
    // 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 (PredictionServiceClient client = PredictionServiceClient.create()) {
      // Get the full path of the model.
      ModelName name = ModelName.of(projectId, "us-central1", modelId);

      // Configure the source of the file from a GCS bucket
      GcsSource gcsSource = GcsSource.newBuilder().addInputUris(inputUri).build();
      BatchPredictInputConfig inputConfig =
          BatchPredictInputConfig.newBuilder().setGcsSource(gcsSource).build();

      // Configure where to store the output in a GCS bucket
      GcsDestination gcsDestination =
          GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build();
      BatchPredictOutputConfig outputConfig =
          BatchPredictOutputConfig.newBuilder().setGcsDestination(gcsDestination).build();

      // Build the request that will be sent to the API
      BatchPredictRequest request =
          BatchPredictRequest.newBuilder()
              .setName(name.toString())
              .setInputConfig(inputConfig)
              .setOutputConfig(outputConfig)
              .build();

      // Start an asynchronous request
      OperationFuture<BatchPredictResult, OperationMetadata> future =
          client.batchPredictAsync(request);

      System.out.println("Waiting for operation to complete...");
      future.get();
      System.out.println("Batch Prediction results saved to specified Cloud Storage bucket.");
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const modelId = 'YOUR_MODEL_ID';
// const inputUri = 'gs://YOUR_BUCKET_ID/path_to_your_input_csv_or_jsonl';
// const outputUri = 'gs://YOUR_BUCKET_ID/path_to_save_results/';

// Imports the Google Cloud AutoML library
const {PredictionServiceClient} = require('@google-cloud/automl').v1beta1;

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

async function batchPredict() {
  // Construct request
  const request = {
    name: client.modelPath(projectId, location, modelId),
    inputConfig: {
      gcsSource: {
        inputUris: [inputUri],
      },
    },
    outputConfig: {
      gcsDestination: {
        outputUriPrefix: outputUri,
      },
    },
  };

  const [operation] = await client.batchPredict(request);

  console.log('Waiting for operation to complete...');
  // Wait for operation to complete.
  const [response] = await operation.promise();
  console.log(
    `Batch Prediction results saved to Cloud Storage bucket. ${response}`
  );
}

batchPredict();

Python

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

from google.cloud import automl_v1beta1 as automl

def batch_predict(
    project_id="YOUR_PROJECT_ID",
    model_id="YOUR_MODEL_ID",
    input_uri="gs://YOUR_BUCKET_ID/path/to/your/input/csv_or_jsonl",
    output_uri="gs://YOUR_BUCKET_ID/path/to/save/results/",
):
    """Batch predict"""
    prediction_client = automl.PredictionServiceClient()

    # Get the full path of the model.
    model_full_id = automl.AutoMlClient.model_path(project_id, "us-central1", model_id)

    gcs_source = automl.GcsSource(input_uris=[input_uri])

    input_config = automl.BatchPredictInputConfig(gcs_source=gcs_source)
    gcs_destination = automl.GcsDestination(output_uri_prefix=output_uri)
    output_config = automl.BatchPredictOutputConfig(gcs_destination=gcs_destination)
    params = {}

    request = automl.BatchPredictRequest(
        name=model_full_id,
        input_config=input_config,
        output_config=output_config,
        params=params,
    )
    response = prediction_client.batch_predict(request=request)

    print("Waiting for operation to complete...")
    print(
        "Batch Prediction results saved to Cloud Storage bucket. {}".format(
            response.result()
        )
    )