Detect explicit content in a local video file
Stay organized with collections
Save and categorize content based on your preferences.
Detect explicit content in a video file stored locally.
Explore further
For detailed documentation that includes this code sample, see the following:
Code sample
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],[],[],[],null,["# Detect explicit content in a local video file\n\nDetect explicit content in a video file stored locally.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Detect explicit content in videos](/video-intelligence/docs/analyze-safesearch)\n\nCode sample\n-----------\n\n### Go\n\n\nTo authenticate to Video Intelligence, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n func explicitContentURI(w io.Writer, file string) error {\n \tctx := context.Background()\n \tclient, err := video.NewClient(ctx)\n \tif err != nil {\n \t\treturn err\n \t}\n \tdefer client.Close()\n\n \top, err := client.AnnotateVideo(ctx, &videopb.AnnotateVideoRequest{\n \t\tFeatures: []videopb.Feature{\n \t\t\tvideopb.Feature_EXPLICIT_CONTENT_DETECTION,\n \t\t},\n \t\tInputUri: file,\n \t})\n \tif err != nil {\n \t\treturn err\n \t}\n \tresp, err := op.Wait(ctx)\n \tif err != nil {\n \t\treturn err\n \t}\n\n \t// A single video was processed. Get the first result.\n \tresult := resp.AnnotationResults[0].ExplicitAnnotation\n\n \tfor _, frame := range result.Frames {\n \t\toffset, _ := ptypes.Duration(frame.TimeOffset)\n \t\tfmt.Fprintf(w, \"%s - %s\\n\", offset, frame.PornographyLikelihood.String())\n \t}\n\n \treturn nil\n }\n\n### Java\n\n\nTo authenticate to Video Intelligence, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n // Instantiate a com.google.cloud.videointelligence.v1.VideoIntelligenceServiceClient\n try (VideoIntelligenceServiceClient client = VideoIntelligenceServiceClient.create()) {\n // Create an operation that will contain the response when the operation completes.\n AnnotateVideoRequest request =\n AnnotateVideoRequest.newBuilder()\n .setInputUri(gcsUri)\n .addFeatures(Feature.EXPLICIT_CONTENT_DETECTION)\n .build();\n\n OperationFuture\u003cAnnotateVideoResponse, AnnotateVideoProgress\u003e response =\n client.annotateVideoAsync(request);\n\n System.out.println(\"Waiting for operation to complete...\");\n // Print detected annotations and their positions in the analyzed video.\n for (VideoAnnotationResults result : response.get().getAnnotationResultsList()) {\n for (ExplicitContentFrame frame : result.getExplicitAnnotation().getFramesList()) {\n double frameTime =\n frame.getTimeOffset().getSeconds() + frame.getTimeOffset().getNanos() / 1e9;\n System.out.printf(\"Location: %.3fs\\n\", frameTime);\n System.out.println(\"Adult: \" + frame.getPornographyLikelihood());\n }\n }\n\n### Node.js\n\n\nTo authenticate to Video Intelligence, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n // Imports the Google Cloud Video Intelligence library\n const video = require('https://cloud.google.com/nodejs/docs/reference/video-intelligence/latest/overview.html').v1;\n\n // Creates a client\n const client = new video.https://cloud.google.com/nodejs/docs/reference/video-intelligence/latest/overview.html();\n\n /**\n * TODO(developer): Uncomment the following line before running the sample.\n */\n // const gcsUri = 'GCS URI of video to analyze, e.g. gs://my-bucket/my-video.mp4';\n\n const request = {\n inputUri: gcsUri,\n features: ['EXPLICIT_CONTENT_DETECTION'],\n };\n\n // Human-readable likelihoods\n const likelihoods = [\n 'UNKNOWN',\n 'VERY_UNLIKELY',\n 'UNLIKELY',\n 'POSSIBLE',\n 'LIKELY',\n 'VERY_LIKELY',\n ];\n\n // Detects unsafe content\n const [operation] = await client.annotateVideo(request);\n console.log('Waiting for operation to complete...');\n const [operationResult] = await operation.promise();\n // Gets unsafe content\n const explicitContentResults =\n operationResult.annotationResults[0].explicitAnnotation;\n console.log('Explicit annotation results:');\n explicitContentResults.frames.forEach(result =\u003e {\n if (result.timeOffset === undefined) {\n result.timeOffset = {};\n }\n if (result.timeOffset.seconds === undefined) {\n result.timeOffset.seconds = 0;\n }\n if (result.timeOffset.nanos === undefined) {\n result.timeOffset.nanos = 0;\n }\n console.log(\n `\\tTime: ${result.timeOffset.seconds}` +\n `.${(result.timeOffset.nanos / 1e6).toFixed(0)}s`\n );\n console.log(\n `\\t\\tPornography likelihood: ${likelihoods[result.pornographyLikelihood]}`\n );\n });\n\n### PHP\n\n\nTo authenticate to Video Intelligence, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n use Google\\Cloud\\VideoIntelligence\\V1\\AnnotateVideoRequest;\n use Google\\Cloud\\VideoIntelligence\\V1\\Client\\VideoIntelligenceServiceClient;\n use Google\\Cloud\\VideoIntelligence\\V1\\Feature;\n use Google\\Cloud\\VideoIntelligence\\V1\\Likelihood;\n\n /**\n * @param string $uri The cloud storage object to analyze (gs://your-bucket-name/your-object-name)\n * @param int $pollingIntervalSeconds\n */\n function analyze_explicit_content(string $uri, int $pollingIntervalSeconds = 0)\n {\n $video = new VideoIntelligenceServiceClient();\n\n # Execute a request.\n $features = [Feature::EXPLICIT_CONTENT_DETECTION];\n $request = (new AnnotateVideoRequest())\n -\u003esetInputUri($uri)\n -\u003esetFeatures($features);\n $operation = $video-\u003eannotateVideo($request);\n\n # Wait for the request to complete.\n $operation-\u003epollUntilComplete([\n 'pollingIntervalSeconds' =\u003e $pollingIntervalSeconds\n ]);\n\n # Print the result.\n if ($operation-\u003eoperationSucceeded()) {\n $results = $operation-\u003egetResult()-\u003egetAnnotationResults()[0];\n $explicitAnnotation = $results-\u003egetExplicitAnnotation();\n foreach ($explicitAnnotation-\u003egetFrames() as $frame) {\n $time = $frame-\u003egetTimeOffset();\n printf('At %ss:' . PHP_EOL, $time-\u003egetSeconds() + $time-\u003egetNanos() / 1000000000.0);\n printf(' pornography: ' . Likelihood::name($frame-\u003egetPornographyLikelihood()) . PHP_EOL);\n }\n } else {\n print_r($operation-\u003egetError());\n }\n }\n\n### Python\n\n\nTo authenticate to Video Intelligence, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n \"\"\"Detects explicit content from the GCS path to a video.\"\"\"\n video_client = videointelligence.VideoIntelligenceServiceClient()\n features = [videointelligence.Feature.EXPLICIT_CONTENT_DETECTION]\n\n operation = video_client.annotate_video(\n request={\"features\": features, \"input_uri\": path}\n )\n print(\"\\nProcessing video for explicit content annotations:\")\n\n result = operation.result(timeout=90)\n print(\"\\nFinished processing.\")\n\n # Retrieve first result because a single video was processed\n for frame in result.annotation_results[0].explicit_annotation.frames:\n likelihood = videointelligence.Likelihood(frame.pornography_likelihood)\n frame_time = frame.time_offset.seconds + frame.time_offset.microseconds / 1e6\n print(\"Time: {}s\".format(frame_time))\n print(\"\\tpornography: {}\".format(likelihood.name))\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=video)."]]