로컬 동영상 파일에서 유해성 콘텐츠 감지

로컬에 저장된 동영상 파일에서 유해성 콘텐츠를 감지합니다.

더 살펴보기

이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.

코드 샘플

Go

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


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]}`
  );
});

PHP

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

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

/**
 * @param string $uri The cloud storage object to analyze (gs://your-bucket-name/your-object-name)
 * @param int $pollingIntervalSeconds
 */
function analyze_explicit_content(string $uri, int $pollingIntervalSeconds = 0)
{
    $video = new VideoIntelligenceServiceClient();

    # Execute a request.
    $features = [Feature::EXPLICIT_CONTENT_DETECTION];
    $request = (new AnnotateVideoRequest())
        ->setInputUri($uri)
        ->setFeatures($features);
    $operation = $video->annotateVideo($request);

    # Wait for the request to complete.
    $operation->pollUntilComplete([
        'pollingIntervalSeconds' => $pollingIntervalSeconds
    ]);

    # 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());
    }
}

Python

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

"""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))

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참고하세요.