動画内の不適切なコンテンツを検出する

不適切なコンテンツの検出は、動画内のアダルト コンテンツを検出します。通常、アダルト コンテンツは 18 歳未満には不適切なもので、ヌード、性的描写、ポルノなどを指します(ただし、これらに限定されません)。このようなコンテンツは、漫画やアニメでも検出されます。

レスポンスには、バケット化された可能性の値(VERY_UNLIKELY から VERY_LIKELY まで)が含まれます。

不適切なコンテンツの検出で動画を評価すると、フレーム単位で分析が実行されます。評価されるのはビジュアル コンテンツのみです。動画の音声部分は、不適切なコンテンツのレベルが評価されません。

Cloud Storage にあるファイルに対して、不適切なコンテンツの検出機能について動画分析を行う例を次に示します。

REST

動画アノテーションリクエストを送信する

POST リクエストを videos:annotate メソッドに送信する方法を以下に示します。この例では、Google Cloud CLI を使用してアクセス トークンを作成します。gcloud CLI のインストール手順については、Video Intelligence API のクイックスタートをご覧ください。

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

  • INPUT_URI: アノテーションを付けるファイルを含む Cloud Storage バケット(ファイル名を含む)。gs:// で始まる必要があります。
    例: "inputUri": "gs://cloud-videointelligence-demo/assistant.mp4",
  • PROJECT_NUMBER: Google Cloud プロジェクトの数値識別子。

HTTP メソッドと URL:

POST https://videointelligence.googleapis.com/v1/videos:annotate

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

{
  "inputUri": "INPUT_URI",
  "features": ["EXPLICIT_CONTENT_DETECTION"]
}

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

次のような JSON レスポンスが返されます。

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/operations/OPERATION_ID"
}

レスポンスが成功すると、Video Intelligence API はオペレーションの name を返します。上記は、このようなレスポンスの例です。

  • PROJECT_NUMBER: プロジェクトの数
  • LOCATION_ID: アノテーションを実行する Cloud リージョン。サポート対象のクラウド リージョンは us-east1us-west1europe-west1asia-east1 です。リージョンを指定しないと、動画ファイルの場所に基づいてリージョンが決まります。
  • OPERATION_ID: リクエストに対して作成され、オペレーション開始時にレスポンスで指定された長時間実行オペレーションの ID(例: 12345...

アノテーション結果を取得する

オペレーションの結果を取得するには、次の例のように、videos:annotate の呼び出しから返されたオペレーション名を使用して GET リクエストを行います。

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

  • OPERATION_NAME: Video Intelligence API によって返されるオペレーションの名前。オペレーション名の形式は projects/PROJECT_NUMBER/locations/LOCATION_ID/operations/OPERATION_ID です。
  • PROJECT_NUMBER: Google Cloud プロジェクトの数値識別子。

HTTP メソッドと URL:

GET https://videointelligence.googleapis.com/v1/OPERATION_NAME

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

次のような JSON レスポンスが返されます。

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION_ID/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.videointelligence.v1.AnnotateVideoProgress",
    "annotationProgress": [
     {
      "inputUri": "/demomaker/gbikes_dinosaur.mp4",
      "progressPercent": 100,
      "startTime": "2020-03-26T00:16:35.112404Z",
      "updateTime": "2020-03-26T00:16:55.937889Z"
     }
    ]
   },
   "done": true,
   "response": {
    "@type": "type.googleapis.com/google.cloud.videointelligence.v1.AnnotateVideoResponse",
    "annotationResults": [
     {
      "inputUri": "/demomaker/gbikes_dinosaur.mp4",
      "explicitAnnotation": {
       "frames": [
        {
         "timeOffset": "0.056149s",
         "pornographyLikelihood": "VERY_UNLIKELY"
        },
        {
         "timeOffset": "1.166841s",
         "pornographyLikelihood": "VERY_UNLIKELY"
        },
            ...
        {
         "timeOffset": "41.678209s",
         "pornographyLikelihood": "VERY_UNLIKELY"
        },
        {
         "timeOffset": "42.596413s",
         "pornographyLikelihood": "VERY_UNLIKELY"
        }
       ]
      }
     }
    ]
   }
  }
ショット検出のアノテーションは shotAnnotations リストとして返されます。注: doneフィールドは、値が True の場合にのみ返されます。オペレーションが完了していない場合、レスポンスには含まれません。

アノテーションの結果をダウンロードする

アノテーションを、送信元バケットから送信先バケットにコピーします(ファイルとオブジェクトのコピーをご覧ください)。

gsutil cp gcs_uri gs://my-bucket

注: 出力 GCS URI がユーザーによって指定された場合、アノテーションはその GCS URI に格納されます。

Go


func explicitContentURI(w io.Writer, file string) error {
	ctx := context.Background()
	client, err := video.NewClient(ctx)
	if err != nil {
		return err
	}
	defer client.Close()

	op, err := client.AnnotateVideo(ctx, &videopb.AnnotateVideoRequest{
		Features: []videopb.Feature{
			videopb.Feature_EXPLICIT_CONTENT_DETECTION,
		},
		InputUri: file,
	})
	if err != nil {
		return err
	}
	resp, err := op.Wait(ctx)
	if err != nil {
		return err
	}

	// A single video was processed. Get the first result.
	result := resp.AnnotationResults[0].ExplicitAnnotation

	for _, frame := range result.Frames {
		offset, _ := ptypes.Duration(frame.TimeOffset)
		fmt.Fprintf(w, "%s - %s\n", offset, frame.PornographyLikelihood.String())
	}

	return nil
}

Java

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

// Instantiate a com.google.cloud.videointelligence.v1.VideoIntelligenceServiceClient
try (VideoIntelligenceServiceClient client = VideoIntelligenceServiceClient.create()) {
  // Create an operation that will contain the response when the operation completes.
  AnnotateVideoRequest request =
      AnnotateVideoRequest.newBuilder()
          .setInputUri(gcsUri)
          .addFeatures(Feature.EXPLICIT_CONTENT_DETECTION)
          .build();

  OperationFuture<AnnotateVideoResponse, AnnotateVideoProgress> response =
      client.annotateVideoAsync(request);

  System.out.println("Waiting for operation to complete...");
  // Print detected annotations and their positions in the analyzed video.
  for (VideoAnnotationResults result : response.get().getAnnotationResultsList()) {
    for (ExplicitContentFrame frame : result.getExplicitAnnotation().getFramesList()) {
      double frameTime =
          frame.getTimeOffset().getSeconds() + frame.getTimeOffset().getNanos() / 1e9;
      System.out.printf("Location: %.3fs\n", frameTime);
      System.out.println("Adult: " + frame.getPornographyLikelihood());
    }
  }

Node.js

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

// Imports the Google Cloud Video Intelligence library
const video = require('@google-cloud/video-intelligence').v1;

// Creates a client
const client = new video.VideoIntelligenceServiceClient();

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const gcsUri = 'GCS URI of video to analyze, e.g. gs://my-bucket/my-video.mp4';

const request = {
  inputUri: gcsUri,
  features: ['EXPLICIT_CONTENT_DETECTION'],
};

// Human-readable likelihoods
const likelihoods = [
  'UNKNOWN',
  'VERY_UNLIKELY',
  'UNLIKELY',
  'POSSIBLE',
  'LIKELY',
  'VERY_LIKELY',
];

// Detects unsafe content
const [operation] = await client.annotateVideo(request);
console.log('Waiting for operation to complete...');
const [operationResult] = await operation.promise();
// Gets unsafe content
const explicitContentResults =
  operationResult.annotationResults[0].explicitAnnotation;
console.log('Explicit annotation results:');
explicitContentResults.frames.forEach(result => {
  if (result.timeOffset === undefined) {
    result.timeOffset = {};
  }
  if (result.timeOffset.seconds === undefined) {
    result.timeOffset.seconds = 0;
  }
  if (result.timeOffset.nanos === undefined) {
    result.timeOffset.nanos = 0;
  }
  console.log(
    `\tTime: ${result.timeOffset.seconds}` +
      `.${(result.timeOffset.nanos / 1e6).toFixed(0)}s`
  );
  console.log(
    `\t\tPornography likelihood: ${likelihoods[result.pornographyLikelihood]}`
  );
});

Python

Python 用の Cloud Video Intelligence API クライアント ライブラリのインストールと使用方法については、Cloud Video Intelligence API クライアント ライブラリをご覧ください。
"""Detects explicit content from the GCS path to a video."""
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.Feature.EXPLICIT_CONTENT_DETECTION]

operation = video_client.annotate_video(
    request={"features": features, "input_uri": path}
)
print("\nProcessing video for explicit content annotations:")

result = operation.result(timeout=90)
print("\nFinished processing.")

# Retrieve first result because a single video was processed
for frame in result.annotation_results[0].explicit_annotation.frames:
    likelihood = videointelligence.Likelihood(frame.pornography_likelihood)
    frame_time = frame.time_offset.seconds + frame.time_offset.microseconds / 1e6
    print("Time: {}s".format(frame_time))
    print("\tpornography: {}".format(likelihood.name))

その他の言語

C#: クライアント ライブラリ ページの C# の設定手順を実行してから、.NET の Video Intelligence のリファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページのPHP の設定手順を実行してから、PHP の Video Intelligence のリファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を実行してから、Ruby の Video Intelligence のリファレンス ドキュメントをご覧ください。