부적절한 저장된 동영상 탐지 - Amazon Rekognition

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

부적절한 저장된 동영상 탐지

Amazon Rekognition Video의 저장된 비디오 속 부적절하거나 불쾌감을 주는 콘텐츠 탐지는 비동기 작업입니다. 부적절하거나 불쾌한 콘텐츠를 감지하려면 전화하세요. StartContentModeration Amazon Rekognition Video는 비디오 분석의 완료 상태를 Amazon Simple Notification Service 주제에 게시합니다. 동영상 분석에 성공하면 전화를 GetContentModeration걸어 분석 결과를 받아보세요. 비디오 분석 시작 및 결과 가져오기에 대한 자세한 내용은 Amazon Rekognition Video 작업 직접 호출 단원을 참조하십시오. Amazon Rekognition의 조절 레이블 목록은 이미지 및 비디오 조절 API 사용을 참조하세요.

이 절차는 동영상 분석 요청의 완료 상태를 가져오기 위해 Amazon Simple Queue Service 대기열을 사용하는 Java 또는 Python으로 Amazon S3 버킷에 저장된 비디오 분석(SDK)의 코드를 확장합니다.

Amazon S3 버킷(SDK)에 저장된 비디오에서 부적절하거나 불쾌감을 주는 콘텐츠를 탐지하려면
  1. Java 또는 Python으로 Amazon S3 버킷에 저장된 비디오 분석(SDK)을 수행합니다.

  2. 1단계에서 만든 클래스 VideoDetect에 다음 코드를 추가합니다.

    Java
    //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.) //Content moderation ================================================================== private static void StartUnsafeContentDetection(String bucket, String video) throws Exception{ NotificationChannel channel= new NotificationChannel() .withSNSTopicArn(snsTopicArn) .withRoleArn(roleArn); StartContentModerationRequest req = new StartContentModerationRequest() .withVideo(new Video() .withS3Object(new S3Object() .withBucket(bucket) .withName(video))) .withNotificationChannel(channel); StartContentModerationResult startModerationLabelDetectionResult = rek.startContentModeration(req); startJobId=startModerationLabelDetectionResult.getJobId(); } private static void GetUnsafeContentDetectionResults() throws Exception{ int maxResults=10; String paginationToken=null; GetContentModerationResult moderationLabelDetectionResult =null; do{ if (moderationLabelDetectionResult !=null){ paginationToken = moderationLabelDetectionResult.getNextToken(); } moderationLabelDetectionResult = rek.getContentModeration( new GetContentModerationRequest() .withJobId(startJobId) .withNextToken(paginationToken) .withSortBy(ContentModerationSortBy.TIMESTAMP) .withMaxResults(maxResults)); VideoMetadata videoMetaData=moderationLabelDetectionResult.getVideoMetadata(); System.out.println("Format: " + videoMetaData.getFormat()); System.out.println("Codec: " + videoMetaData.getCodec()); System.out.println("Duration: " + videoMetaData.getDurationMillis()); System.out.println("FrameRate: " + videoMetaData.getFrameRate()); //Show moderated content labels, confidence and detection times List<ContentModerationDetection> moderationLabelsInFrames= moderationLabelDetectionResult.getModerationLabels(); for (ContentModerationDetection label: moderationLabelsInFrames) { long seconds=label.getTimestamp()/1000; System.out.print("Sec: " + Long.toString(seconds)); System.out.println(label.getModerationLabel().toString()); System.out.println(); } } while (moderationLabelDetectionResult !=null && moderationLabelDetectionResult.getNextToken() != null); }

    main 함수에서 다음 줄을 바꿉니다.

    StartLabelDetection(bucket, video); if (GetSQSMessageSuccess()==true) GetLabelDetectionResults();

    다음으로 바꿉니다.

    StartUnsafeContentDetection(bucket, video); if (GetSQSMessageSuccess()==true) GetUnsafeContentDetectionResults();
    Java V2

    이 코드는 AWS 문서 SDK 예제 GitHub 저장소에서 가져온 것입니다. 전체 예제는 여기에서 확인하세요.

    import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rekognition.RekognitionClient; import software.amazon.awssdk.services.rekognition.model.NotificationChannel; import software.amazon.awssdk.services.rekognition.model.S3Object; import software.amazon.awssdk.services.rekognition.model.Video; import software.amazon.awssdk.services.rekognition.model.StartContentModerationRequest; import software.amazon.awssdk.services.rekognition.model.StartContentModerationResponse; import software.amazon.awssdk.services.rekognition.model.RekognitionException; import software.amazon.awssdk.services.rekognition.model.GetContentModerationResponse; import software.amazon.awssdk.services.rekognition.model.GetContentModerationRequest; import software.amazon.awssdk.services.rekognition.model.VideoMetadata; import software.amazon.awssdk.services.rekognition.model.ContentModerationDetection; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class VideoDetectInappropriate { private static String startJobId = ""; public static void main(String[] args) { final String usage = """ Usage: <bucket> <video> <topicArn> <roleArn> Where: bucket - The name of the bucket in which the video is located (for example, (for example, myBucket).\s video - The name of video (for example, people.mp4).\s topicArn - The ARN of the Amazon Simple Notification Service (Amazon SNS) topic.\s roleArn - The ARN of the AWS Identity and Access Management (IAM) role to use.\s """; if (args.length != 4) { System.out.println(usage); System.exit(1); } String bucket = args[0]; String video = args[1]; String topicArn = args[2]; String roleArn = args[3]; Region region = Region.US_EAST_1; RekognitionClient rekClient = RekognitionClient.builder() .region(region) .build(); NotificationChannel channel = NotificationChannel.builder() .snsTopicArn(topicArn) .roleArn(roleArn) .build(); startModerationDetection(rekClient, channel, bucket, video); getModResults(rekClient); System.out.println("This example is done!"); rekClient.close(); } public static void startModerationDetection(RekognitionClient rekClient, NotificationChannel channel, String bucket, String video) { try { S3Object s3Obj = S3Object.builder() .bucket(bucket) .name(video) .build(); Video vidOb = Video.builder() .s3Object(s3Obj) .build(); StartContentModerationRequest modDetectionRequest = StartContentModerationRequest.builder() .jobTag("Moderation") .notificationChannel(channel) .video(vidOb) .build(); StartContentModerationResponse startModDetectionResult = rekClient .startContentModeration(modDetectionRequest); startJobId = startModDetectionResult.jobId(); } catch (RekognitionException e) { System.out.println(e.getMessage()); System.exit(1); } } public static void getModResults(RekognitionClient rekClient) { try { String paginationToken = null; GetContentModerationResponse modDetectionResponse = null; boolean finished = false; String status; int yy = 0; do { if (modDetectionResponse != null) paginationToken = modDetectionResponse.nextToken(); GetContentModerationRequest modRequest = GetContentModerationRequest.builder() .jobId(startJobId) .nextToken(paginationToken) .maxResults(10) .build(); // Wait until the job succeeds. while (!finished) { modDetectionResponse = rekClient.getContentModeration(modRequest); status = modDetectionResponse.jobStatusAsString(); if (status.compareTo("SUCCEEDED") == 0) finished = true; else { System.out.println(yy + " status is: " + status); Thread.sleep(1000); } yy++; } finished = false; // Proceed when the job is done - otherwise VideoMetadata is null. VideoMetadata videoMetaData = modDetectionResponse.videoMetadata(); System.out.println("Format: " + videoMetaData.format()); System.out.println("Codec: " + videoMetaData.codec()); System.out.println("Duration: " + videoMetaData.durationMillis()); System.out.println("FrameRate: " + videoMetaData.frameRate()); System.out.println("Job"); List<ContentModerationDetection> mods = modDetectionResponse.moderationLabels(); for (ContentModerationDetection mod : mods) { long seconds = mod.timestamp() / 1000; System.out.print("Mod label: " + seconds + " "); System.out.println(mod.moderationLabel().toString()); System.out.println(); } } while (modDetectionResponse != null && modDetectionResponse.nextToken() != null); } catch (RekognitionException | InterruptedException e) { System.out.println(e.getMessage()); System.exit(1); } } }
    Python
    #Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. #PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.) # ============== Unsafe content =============== def StartUnsafeContent(self): response=self.rek.start_content_moderation(Video={'S3Object': {'Bucket': self.bucket, 'Name': self.video}}, NotificationChannel={'RoleArn': self.roleArn, 'SNSTopicArn': self.snsTopicArn}) self.startJobId=response['JobId'] print('Start Job Id: ' + self.startJobId) def GetUnsafeContentResults(self): maxResults = 10 paginationToken = '' finished = False while finished == False: response = self.rek.get_content_moderation(JobId=self.startJobId, MaxResults=maxResults, NextToken=paginationToken, SortBy="NAME", AggregateBy="TIMESTAMPS") print('Codec: ' + response['VideoMetadata']['Codec']) print('Duration: ' + str(response['VideoMetadata']['DurationMillis'])) print('Format: ' + response['VideoMetadata']['Format']) print('Frame rate: ' + str(response['VideoMetadata']['FrameRate'])) print() for contentModerationDetection in response['ModerationLabels']: print('Label: ' + str(contentModerationDetection['ModerationLabel']['Name'])) print('Confidence: ' + str(contentModerationDetection['ModerationLabel']['Confidence'])) print('Parent category: ' + str(contentModerationDetection['ModerationLabel']['ParentName'])) print('Timestamp: ' + str(contentModerationDetection['Timestamp'])) print() if 'NextToken' in response: paginationToken = response['NextToken'] else: finished = True

    main 함수에서 다음 줄을 바꿉니다.

    analyzer.StartLabelDetection() if analyzer.GetSQSMessageSuccess()==True: analyzer.GetLabelDetectionResults()

    다음으로 바꿉니다.

    analyzer.StartUnsafeContent() if analyzer.GetSQSMessageSuccess()==True: analyzer.GetUnsafeContentResults()
    참고

    Java 또는 Python으로 Amazon S3 버킷에 저장된 비디오 분석(SDK) 이외에 비디오 예제를 이미 실행한 경우, 바꿀 코드가 다를 수 있습니다.

  3. 코드를 실행합니다. 비디오에서 감지된 부적절한 콘텐츠 레이블 목록이 표시됩니다.

GetContentModeration 작업 응답

GetContentModeration 응답은 ContentModerationDetection객체로 구성된 배열입니다. ModerationLabels 부적절한 콘텐츠 레이블이 감지될 때마다 배열에 요소가 포함됩니다. ContentModerationDetectionObject개체 ModerationLabel내에는 부적절하거나 불쾌한 콘텐츠의 탐지된 항목에 대한 정보가 들어 있습니다. Timestamp동영상 시작 시점부터 라벨이 감지된 시점의 시간 (밀리초) 입니다. 레이블은 부적절한 콘텐츠 이미지 분석을 통해 감지된 레이블과 동일한 방식의 계층적 구조로 구성됩니다. 자세한 정보는 콘텐츠 조절을 참조하세요.

다음은 NAME 기준으로 정렬하고 TIMESTAMPS 기준으로 집계한 GetContentModeration로부터의 예제 응답입니다.

{ "JobStatus": "SUCCEEDED", "ModerationModelVersion": "6.1", "ModerationLabels": [ { "Timestamp": 1500, "ModerationLabel": { "Confidence": 71.88196563720703, "Name": "Male Swimwear Or Underwear", "ParentName": "Suggestive" } }, { "Timestamp": 2000, "ModerationLabel": { "Confidence": 71.88196563720703, "Name": "Male Swimwear Or Underwear", "ParentName": "Suggestive" } }, { "Timestamp": 1500, "ModerationLabel": { "Confidence": 71.88196563720703, "Name": "Suggestive", "ParentName": "" } }, { "Timestamp": 2000, "ModerationLabel": { "Confidence": 71.88196563720703, "Name": "Suggestive", "ParentName": "" } }, { "Timestamp": 500, "ModerationLabel": { "Confidence": 90.84736633300781, "Name": "Tobacco", "ParentName": "", } } ], "VideoMetadata": { "ColorRange": "FULL", "DurationMillis": 5000, "Format": "MP4", "FrameWidth": 1280, "FrameHeight": 720, "FrameRate": 24 }, "JobId": "123", "Video": { "S3Object": { "Bucket": "s3Bucket", "Name": "s3bucketpath/testfile.mp4" } }, "JobTag": "ContentModerationSet1", "GetRequestMetadata": { "AggregatedBy": "TIMESTAMPS", "SortBy": "TIMESTAMP" } }