Detecting explicit content in videos

Explicit Content Detection detects adult content within a video. Adult content is content generally appropriate for 18 years of age and older, including but not limited to nudity, sexual activities, and pornography (including cartoons or anime).

The response includes a bucketized likelihood value, from VERY_UNLIKELY to VERY_LIKELY.

When Explicit Content Detection evaluates a video, it does so on a per-frame basis and considers visual content only. The audio component of the video is not used to evaluate the explicit content level. Google does not guarantee the accuracy of its Explicit Content Detection predictions.

Here is an example of performing video analysis for Explicit Content Detection features on a file located in Google Cloud Storage.

REST API

The following shows how to send a POST request to the videos:annotate method. The example uses the access token for a service account set up for the project using the Google Cloud Platform Cloud SDK. For instructions on installing the Cloud SDK, setting up a project with a service account, and obtaining an access token, see the Video Intelligence API Quickstart.

curl -X POST \
     -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     --data '    {
      "inputUri": "gs://demomaker/gbikes_dinosaur.mp4",
      "features": ["EXPLICIT_CONTENT_DETECTION"]
    }' "https://videointelligence.googleapis.com/v1/videos:annotate"

If the request is successful, the Cloud Video Intelligence API returns the name for your operation. The following shows an example of such a response, where project-name is the name of your project and operation-id is the ID of the long running operation created for the request.

{
  "name": "projects/project-name/locations/us-west1/operations/operation-id"
}

To retrieve the result of the operation, make a GET request, using the operation name returned from the call to videos:annotate, as shown in the following example.

curl -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  https://videointelligence.googleapis.com/v1/operation-name

Label search annotations are returned as an explicitAnnotation list.

    {
      "name": "projects/PROJECT_NAME/locations/us-west1/operations/OPERATION_ID",
      "metadata": {
        "@type": "type.googleapis.com/google.cloud.videointelligence.v1.AnnotateVideoProgress",
        "annotationProgress": [
          {
            "inputUri": "/demomaker/gbikes_dinosaur.mp4",
            "progressPercent": 100,
            "startTime": "2017-08-26T00:16:35.112404Z",
            "updateTime": "2017-08-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"
                }
              ]
            }
          }
        ]
      }
    }

C#

public static object AnalyzeExplicitContentGcs(string uri)
{
    var client = VideoIntelligenceServiceClient.Create();
    var request = new AnnotateVideoRequest()
    {
        InputUri = uri,
        Features = { Feature.ExplicitContentDetection }
    };
    var op = client.AnnotateVideo(request).PollUntilCompleted();
    foreach (var result in op.Result.AnnotationResults)
    {
        foreach (var frame in result.ExplicitAnnotation.Frames)
        {
            Console.WriteLine("Time Offset: {0}", frame.TimeOffset);
            Console.WriteLine("Pornography Likelihood: {0}", frame.PornographyLikelihood);
            Console.WriteLine();
        }
    }
    return 0;
}

Go


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

	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

// 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

// 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 [opertaion] = await client.annotateVideo(request);
console.log('Waiting for operation to complete...');
const [operationResult] = await opertaion.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

For more information on installing and using the Cloud Video Intelligence API Client Library for Python, refer to Cloud Video Intelligence API Client Libraries.
""" Detects explicit content from the GCS path to a video. """
video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.EXPLICIT_CONTENT_DETECTION]

operation = video_client.annotate_video(path, features=features)
print('\nProcessing video for explicit content annotations:')

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

# first result is retrieved because a single video was processed
for frame in result.annotation_results[0].explicit_annotation.frames:
    likelihood = enums.Likelihood(frame.pornography_likelihood)
    frame_time = frame.time_offset.seconds + frame.time_offset.nanos / 1e9
    print('Time: {}s'.format(frame_time))
    print('\tpornography: {}'.format(likelihood.name))

PHP

use Google\Cloud\VideoIntelligence\V1\VideoIntelligenceServiceClient;
use Google\Cloud\VideoIntelligence\V1\Feature;
use Google\Cloud\VideoIntelligence\V1\Likelihood;

/** Uncomment and populate these variables in your code */
// $uri = 'The cloud storage object to analyze (gs://your-bucket-name/your-object-name)';
// $options = []; // Optional, can be used to increate "pollingIntervalSeconds"

$video = new VideoIntelligenceServiceClient();

# Execute a request.
$operation = $video->annotateVideo([
    'inputUri' => $uri,
    'features' => [Feature::EXPLICIT_CONTENT_DETECTION]
]);

# Wait for the request to complete.
$operation->pollUntilComplete($options);

# Print the result.
if ($operation->operationSucceeded()) {
    $results = $operation->getResult()->getAnnotationResults()[0];
    $explicitAnnotation = $results->getExplicitAnnotation();
    foreach ($explicitAnnotation->getFrames() as $frame) {
        $time = $frame->getTimeOffset();
        printf('At %ss:' . PHP_EOL, $time->getSeconds() + $time->getNanos()/1000000000.0);
        printf('  pornography: ' . Likelihood::name($frame->getPornographyLikelihood()) . PHP_EOL);
    }
} else {
    print_r($operation->getError());
}

Ruby

# path = "Path to a video file on Google Cloud Storage: gs://bucket/video.mp4"

require "google/cloud/video_intelligence"

video = Google::Cloud::VideoIntelligence.new

# Register a callback during the method call
operation = video.annotate_video input_uri: path, features: [:EXPLICIT_CONTENT_DETECTION] do |operation|
  raise operation.results.message? if operation.error?
  puts "Finished Processing."

  explicit_annotation = operation.results.annotation_results.first.explicit_annotation

  explicit_annotation.frames.each do |frame|
    frame_time = frame.time_offset.seconds + frame.time_offset.nanos / 1e9

    puts "Time: #{frame_time}"
    puts "pornography: #{frame.pornography_likelihood}"
  end
end

puts "Processing video for label annotations:"
operation.wait_until_done!

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Video Intelligence API Documentation