All Products
Search
Document Center

Content Moderation:Video moderation

Last Updated:Jul 31, 2023

This topic describes how to use Content Moderation SDK for Java to moderate videos for risky content.

Description

Content Moderation SDK for PHP supports both synchronous and asynchronous video moderation.

  • If you use synchronous video moderation, you can submit only a sequence of frames captured from a video for moderation. For more information about the related parameters, see /green/video/syncscan.

  • (Recommended) If you use asynchronous video moderation, you can submit a video or a sequence of frames captured from the video for moderation. For more information about the related parameters, see /green/video/asyncscan and /green/video/results.

Prerequisites

  • Java dependencies are installed. For more information, see Installation.

    Note

    You must use the Java version described in the Installation topic to install the dependencies. Otherwise, subsequent operation calls fail.

  • The Extension.Uploader utility class is downloaded and imported into your project if you submit a local image or a binary image stream for image moderation.

(Recommended) Submit asynchronous video moderation tasks

Operation

Description

Supported region

VideoAsyncScanRequest

Sends asynchronous requests to moderate videos for risky content across multiple moderation scenarios, including pornography, terrorist content, ad, undesirable scene, and logo detection.

  • cn-shanghai: China (Shanghai)

  • cn-beijing: China (Beijing)

  • cn-shenzhen: China (Shenzhen)

  • ap-southeast-1: Singapore

Sample code

  • Submit the URL of an online video for video moderation

    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONObject;
    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.IAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.exceptions.ServerException;
    import com.aliyuncs.green.model.v20180509.VideoAsyncScanRequest;
    import com.aliyuncs.http.FormatType;
    import com.aliyuncs.http.HttpResponse;
    import com.aliyuncs.profile.DefaultProfile;
    import com.aliyuncs.profile.IClientProfile;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.LinkedHashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.UUID;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
            /**
             * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M.  
             * Common ways to obtain environment variables:
             * Method 1:
             *     Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             * Method 2:
             *     Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             */
            DefaultProfile profile = DefaultProfile.getProfile(
                    "cn-shanghai",
                    "We recommend that you obtain the AccessKey ID of your RAM user from environment variables",
                    "We recommend that you obtain the AccessKey secret of your RAM user from environment variables");
            DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
            // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
            IAcsClient client = new DefaultAcsClient(profile);
    
            VideoAsyncScanRequest videoAsyncScanRequest = new VideoAsyncScanRequest();
            videoAsyncScanRequest.setAcceptFormat(FormatType.JSON); // Specify the response format of the operation. 
            videoAsyncScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // Specify the request method. 
    
            List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
            Map<String, Object> task = new LinkedHashMap<String, Object>();
            task.put("dataId", UUID.randomUUID().toString());
            task.put("url", "Enter the HTTP or HTTPS URL of the online video that is accessible from the Internet.");
    
            tasks.add(task);
            /**
             * Specify the moderation scenario. The system charges you based on the moderation scenario that you specify. 
             * By default, a frame is captured from the video per second. You can specify the frequency at which sequential frames are captured. The system charges you based on the number of frames that are captured from the video and the moderation scenarios for each frame. 
             * For example, if 60 frames are captured from a 1-minute video and you want to moderate the video for both pornography and terrorist content, you are charged for moderating 60 frames for pornography and 60 frames for terrorist content. 
             */
            JSONObject data = new JSONObject();
            data.put("scenes", Arrays.asList("porn", "terrorism"));
            data.put("tasks", tasks);
            data.put("callback", "http://www.aliyundoc.com/xxx.json");
            data.put("seed", "yourPersonalSeed");
    
            videoAsyncScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
    
            /**
             * Specify the connection timeout period and read timeout period. 
             */
            videoAsyncScanRequest.setConnectTimeout(3000);
            videoAsyncScanRequest.setReadTimeout(6000);
            try {
                HttpResponse httpResponse = client.doAction(videoAsyncScanRequest);
    
                if (httpResponse.isSuccess()) {
                    JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                    System.out.println(JSON.toJSONString(scrResponse, true));
                    int requestCode = scrResponse.getIntValue("code");
                    // The moderation results of all videos. 
                    JSONArray taskResults = scrResponse.getJSONArray("data");
                    if (200 == requestCode) {
                        for (Object taskResult : taskResults) {
                            // The moderation result of a single video. 
                            int taskCode = ((JSONObject) taskResult).getIntValue("code");
                            if (200 == taskCode) {
                                // Save the task ID, which is used to poll the moderation results. 
                                System.out.println(((JSONObject) taskResult).getString("taskId"));
                            } else {
                                // A single video failed to be moderated. Analyze the failure based on the actual situation. 
                                System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                            }
                        }
                    } else {
                        /**
                         * The request failed to be processed. Analyze the failure based on the actual situation. 
                         */
                        System.out.println("the whole scan request failed. response:" + JSON.toJSONString(scrResponse));
                    }
                } else {
                    System.out.println("response not success. status:" + httpResponse.getStatus());
                }
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                e.printStackTrace();
            }
        }
    }
  • Submit the URL of a local video for video moderation

    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONObject;
    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.IAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.exceptions.ServerException;
    import com.aliyuncs.green.extension.uploader.ClientUploader;
    import com.aliyuncs.green.model.v20180509.VideoAsyncScanRequest;
    import com.aliyuncs.http.FormatType;
    import com.aliyuncs.http.HttpResponse;
    import com.aliyuncs.profile.DefaultProfile;
    import com.aliyuncs.profile.IClientProfile;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.LinkedHashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.UUID;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
            /**
             * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M.  
             * Common ways to obtain environment variables:
             * Method 1:
             *     Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             * Method 2:
             *     Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             */
            DefaultProfile profile = DefaultProfile.getProfile(
                    "cn-shanghai",
                    "We recommend that you obtain the AccessKey ID of your RAM user from environment variables",
                    "We recommend that you obtain the AccessKey secret of your RAM user from environment variables");
            DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
            // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
            IAcsClient client = new DefaultAcsClient(profile);
    
            VideoAsyncScanRequest videoAsyncScanRequest = new VideoAsyncScanRequest();
            videoAsyncScanRequest.setAcceptFormat(FormatType.JSON); // Specify the response format of the operation. 
            videoAsyncScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // Specify the request method. 
    
            /**
             * If you want to moderate a local video, use the following code to generate a URL based on the storage path of the video. Then, submit the generated URL of the video to the server. 
             */
            String url = null;
            ClientUploader uploader = ClientUploader.getVideoClientUploader(profile, false);
            try {
                url = uploader.uploadFile("Absolute path of the local video");
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
            Map<String, Object> task = new LinkedHashMap<String, Object>();
            task.put("dataId", UUID.randomUUID().toString());
            task.put("url", url);
    
            tasks.add(task);
            /**
             * Specify the moderation scenario. The system charges you based on the moderation scenario that you specify. 
             * By default, a frame is captured from the video per second. You can specify the frequency at which sequential frames are captured. The system charges you based on the number of frames that are captured from the video and the moderation scenarios for each frame. 
             * For example, if 60 frames are captured from a 1-minute video and you want to moderate the video for both pornography and terrorist content, you are charged for moderating 60 frames for pornography and 60 frames for terrorist content. 
             */
            JSONObject data = new JSONObject();
            data.put("scenes", Arrays.asList("porn", "terrorism"));
            data.put("tasks", tasks);
            data.put("callback", "http://www.aliyundoc.com/xxx.json");
            data.put("seed", "yourPersonalSeed");
    
            videoAsyncScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
    
            /**
             * Specify the connection timeout period and read timeout period. 
             */
            videoAsyncScanRequest.setConnectTimeout(3000);
            videoAsyncScanRequest.setReadTimeout(10000);
            try {
                HttpResponse httpResponse = client.doAction(videoAsyncScanRequest);
    
                if (httpResponse.isSuccess()) {
                    JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                    System.out.println(JSON.toJSONString(scrResponse, true));
                    int requestCode = scrResponse.getIntValue("code");
                    // The moderation results of all videos. 
                    JSONArray taskResults = scrResponse.getJSONArray("data");
                    if (200 == requestCode) {
                        for (Object taskResult : taskResults) {
                            // The moderation result of a single video. 
                            int taskCode = ((JSONObject) taskResult).getIntValue("code");
                            if (200 == taskCode) {
                                // Save the task ID, which is used to poll the moderation results. 
                                System.out.println(((JSONObject) taskResult).getString("taskId"));
                            } else {
                                // A single video failed to be moderated. Analyze the failure based on the actual situation. 
                                System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                            }
                        }
                    } else {
                        /**
                         * The request failed to be processed. Analyze the failure based on the actual situation. 
                         */
                        System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
                    }
                } else {
                    System.out.println("response not success. status:" + httpResponse.getStatus());
                }
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                e.printStackTrace();
            }
        }
    }
  • Submit a binary video stream for video moderation

    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONObject;
    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.IAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.exceptions.ServerException;
    import com.aliyuncs.green.extension.uploader.ClientUploader;
    import com.aliyuncs.green.model.v20180509.VideoAsyncScanRequest;
    import com.aliyuncs.http.FormatType;
    import com.aliyuncs.http.HttpResponse;
    import com.aliyuncs.profile.DefaultProfile;
    import com.aliyuncs.profile.IClientProfile;
    import org.apache.commons.io.FileUtils;
    
    import java.io.File;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.LinkedHashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.UUID;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
            /**
             * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M.  
             * Common ways to obtain environment variables:
             * Method 1:
             *     Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             * Method 2:
             *     Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             */
            DefaultProfile profile = DefaultProfile.getProfile(
                    "cn-shanghai",
                    "We recommend that you obtain the AccessKey ID of your RAM user from environment variables",
                    "We recommend that you obtain the AccessKey secret of your RAM user from environment variables");
            DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
            // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
            IAcsClient client = new DefaultAcsClient(profile);
    
            VideoAsyncScanRequest videoAsyncScanRequest = new VideoAsyncScanRequest();
            videoAsyncScanRequest.setAcceptFormat(FormatType.JSON); // Specify the response format of the operation. 
            videoAsyncScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // Specify the request method. 
    
            /**
             * If you want to moderate a local video, use the following code to generate a URL based on the storage path of the video. Then, submit the generated URL of the video to the server. 
             */
            ClientUploader uploader = ClientUploader.getVideoClientUploader(profile, false);
            byte[] videoBytes = null;
            String url = null;
            try {
                // Read and convert a local video to binary data and submit the binary data for moderation. In the actual code, directly use the binary data of your video. 
                videoBytes = FileUtils.readFileToByteArray (new File("Path of the local video"));
                // Upload the binary stream to the server. 
                url = uploader.uploadBytes(videoBytes);
            } catch (Exception e) {
                System.out.println("upload file to server fail." + e.toString());
            }
    
            List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
            Map<String, Object> task = new LinkedHashMap<String, Object>();
            task.put("dataId", UUID.randomUUID().toString());
            task.put("url", url);
    
            tasks.add(task);
            /**
             * Specify the moderation scenario. The system charges you based on the moderation scenario that you specify. 
             * By default, a frame is captured from the video per second. You can specify the frequency at which sequential frames are captured. The system charges you based on the number of frames that are captured from the video and the moderation scenarios for each frame. 
             * For example, if 60 frames are captured from a 1-minute video and you want to moderate the video for both pornography and terrorist content, you are charged for moderating 60 frames for pornography and 60 frames for terrorist content. 
             */
            JSONObject data = new JSONObject();
            data.put("scenes", Arrays.asList("porn", "terrorism"));
            data.put("tasks", tasks);
            data.put("callback", "http://www.aliyundoc.com/xxx.json");
            data.put("seed", "yourPersonalSeed");
    
            videoAsyncScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
    
            /**
             * Specify the connection timeout period and read timeout period. 
             */
            videoAsyncScanRequest.setConnectTimeout(3000);
            videoAsyncScanRequest.setReadTimeout(10000);
            try {
                HttpResponse httpResponse = client.doAction(videoAsyncScanRequest);
    
                if (httpResponse.isSuccess()) {
                    JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                    System.out.println(JSON.toJSONString(scrResponse, true));
                    int requestCode = scrResponse.getIntValue("code");
                    // The moderation results of all videos. 
                    JSONArray taskResults = scrResponse.getJSONArray("data");
                    if (200 == requestCode) {
                        for (Object taskResult : taskResults) {
                            // The moderation result of a single video. 
                            int taskCode = ((JSONObject) taskResult).getIntValue("code");
                            if (200 == taskCode) {
                                // Save the task ID, which is used to poll the moderation results. 
                                System.out.println(((JSONObject) taskResult).getString("taskId"));
                            } else {
                                // A single video failed to be moderated. Analyze the failure based on the actual situation. 
                                System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                            }
                        }
                    } else {
                        /**
                         * The request failed to be processed. Analyze the failure based on the actual situation. 
                         */
                        System.out.println("the whole scan request failed. response:" + JSON.toJSONString(scrResponse));
                    }
                } else {
                    System.out.println("response not success. status:" + httpResponse.getStatus());
                }
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                e.printStackTrace();
            }
        }
    }
  • Submit a video live stream for video moderation

    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONObject;
    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.IAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.exceptions.ServerException;
    import com.aliyuncs.green.model.v20180509.VideoAsyncScanRequest;
    import com.aliyuncs.http.FormatType;
    import com.aliyuncs.http.HttpResponse;
    import com.aliyuncs.profile.DefaultProfile;
    import com.aliyuncs.profile.IClientProfile;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.LinkedHashMap;
    import java.util.List;
    import java.util.Map;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
            /**
             * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M.  
             * Common ways to obtain environment variables:
             * Method 1:
             *     Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             * Method 2:
             *     Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             */
            DefaultProfile profile = DefaultProfile.getProfile(
                    "cn-shanghai",
                    "We recommend that you obtain the AccessKey ID of your RAM user from environment variables",
                    "We recommend that you obtain the AccessKey secret of your RAM user from environment variables");
            DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
            // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
            IAcsClient client = new DefaultAcsClient(profile);
    
            VideoAsyncScanRequest videoAsyncScanRequest = new VideoAsyncScanRequest();
            videoAsyncScanRequest.setAcceptFormat(FormatType.JSON); // Specify the response format of the operation. 
            videoAsyncScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // Specify the request method. 
    
            List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
            Map<String, Object> task = new LinkedHashMap<String, Object>();
            task.put("dataId", "ID of the video to be moderated");
            // Set the url parameter to the URL of your live stream. 
            task.put("url", "URL of the video to be moderated");
    
            tasks.add(task);
            /**
             * Specify the moderation scenario. The system charges you based on the moderation scenario that you specify. 
             * By default, a frame is captured from the video per second. You can specify the frequency at which sequential frames are captured. The system charges you based on the number of frames that are captured from the video and the moderation scenarios for each frame. 
             * For example, if 60 frames are captured from a 1-minute video and you want to moderate the video for both pornography and terrorist content, you are charged for moderating 60 frames for pornography and 60 frames for terrorist content. 
             */
            JSONObject data = new JSONObject();
            data.put("scenes", Arrays.asList("porn", "terrorism"));
            data.put("live", true);
            data.put("tasks", tasks);
            data.put("callback", "Your callback URL");
            data.put("seed", "yourPersonalSeed");
    
            videoAsyncScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
    
            /**
             * Specify the connection timeout period and read timeout period. 
             */
            videoAsyncScanRequest.setConnectTimeout(3000);
            videoAsyncScanRequest.setReadTimeout(10000);
            try {
                HttpResponse httpResponse = client.doAction(videoAsyncScanRequest);
    
                if (httpResponse.isSuccess()) {
                    JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                    System.out.println(JSON.toJSONString(scrResponse, true));
                    int requestCode = scrResponse.getIntValue("code");
                    // The moderation results of all videos. 
                    JSONArray taskResults = scrResponse.getJSONArray("data");
                    if (200 == requestCode) {
                        for (Object taskResult : taskResults) {
                            // The moderation result of a single video. 
                            int taskCode = ((JSONObject) taskResult).getIntValue("code");
                            if (200 == taskCode) {
                                // Save the task ID, which is used to poll the moderation results. 
                                System.out.println(((JSONObject) taskResult).getString("taskId"));
                            } else {
                                // A single video failed to be moderated. Analyze the failure based on the actual situation. 
                                System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                            }
                        }
                    } else {
                        /**
                         * The request failed to be processed. Analyze the failure based on the actual situation. 
                         */
                        System.out.println("the whole scan request failed. response:" + JSON.toJSONString(scrResponse));
                    }
                } else {
                    System.out.println("response not success. status:" + httpResponse.getStatus());
                }
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                e.printStackTrace();
            }
        }
    }
  • Submit a video live stream to moderate both the video images and audio

    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONObject;
    import com.aliyuncs.DefaultAcsClient;
    import com.aliyuncs.IAcsClient;
    import com.aliyuncs.exceptions.ClientException;
    import com.aliyuncs.exceptions.ServerException;
    import com.aliyuncs.green.model.v20180509.VideoAsyncScanRequest;
    import com.aliyuncs.http.FormatType;
    import com.aliyuncs.http.HttpResponse;
    import com.aliyuncs.profile.DefaultProfile;
    import com.aliyuncs.profile.IClientProfile;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.LinkedHashMap;
    import java.util.List;
    import java.util.Map;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
            /**
             * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M.  
             * Common ways to obtain environment variables:
             * Method 1:
             *     Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             * Method 2:
             *     Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             */
            DefaultProfile profile = DefaultProfile.getProfile(
                    "cn-shanghai",
                    "We recommend that you obtain the AccessKey ID of your RAM user from environment variables",
                    "We recommend that you obtain the AccessKey secret of your RAM user from environment variables");
            DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
            // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
            IAcsClient client = new DefaultAcsClient(profile);
    
            VideoAsyncScanRequest videoAsyncScanRequest = new VideoAsyncScanRequest();
            videoAsyncScanRequest.setAcceptFormat(FormatType.JSON); // Specify the response format of the operation. 
            videoAsyncScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // Specify the request method. 
    
            List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
            Map<String, Object> task = new LinkedHashMap<String, Object>();
            task.put("dataId", "ID of the video to be moderated");
            // Set the url parameter to the URL of your live stream. 
            task.put("url", "URL of the video to be moderated");
    
            tasks.add(task);
            /**
             * Specify the moderation scenario. The system charges you based on the moderation scenario that you specify. 
             * By default, a frame is captured from the video per second. You can specify the frequency at which sequential frames are captured. The system charges you based on the number of frames that are captured from the video and the moderation scenarios for each frame. 
             * For example, if 60 frames are captured from a 1-minute video and you want to moderate the video for both pornography and terrorist content, you are charged for moderating 60 frames for pornography and 60 frames for terrorist content. 
             */
            JSONObject data = new JSONObject();
            data.put("scenes", Arrays.asList("porn", "terrorism"));
            data.put("live", true);
            data.put("tasks", tasks);
            data.put("callback", "Your callback URL");
            data.put("seed", "yourPersonalSeed");
            /**
             * In addition to moderating video images, if you want to moderate the audio in the video for risky content, set the audioScenes parameter to antispam. 
             * The expense of audio moderation equals the product of the video duration and the unit price of audio anti-spam. 
             */
            data.put("audioScenes", Arrays.asList("antispam"));
    
            videoAsyncScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
    
            /**
             * Specify the connection timeout period and read timeout period. 
             */
            videoAsyncScanRequest.setConnectTimeout(3000);
            videoAsyncScanRequest.setReadTimeout(10000);
            try {
                HttpResponse httpResponse = client.doAction(videoAsyncScanRequest);
    
                if (httpResponse.isSuccess()) {
                    JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                    System.out.println(JSON.toJSONString(scrResponse, true));
                    int requestCode = scrResponse.getIntValue("code");
                    // The moderation results of all videos. 
                    JSONArray taskResults = scrResponse.getJSONArray("data");
                    if (200 == requestCode) {
                        for (Object taskResult : taskResults) {
                            // The moderation result of a single video. 
                            int taskCode = ((JSONObject) taskResult).getIntValue("code");
                            if (200 == taskCode) {
                                // Save the task ID, which is used to poll the moderation results. 
                                System.out.println(((JSONObject) taskResult).getString("taskId"));
                            } else {
                                // A single video failed to be moderated. Analyze the failure based on the actual situation. 
                                System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                            }
                        }
                    } else {
                        /**
                         * The request failed to be processed. Analyze the failure based on the actual situation. 
                         */
                        System.out.println("the whole scan request failed. response:" + JSON.toJSONString(scrResponse));
                    }
                } else {
                    System.out.println("response not success. status:" + httpResponse.getStatus());
                }
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                e.printStackTrace();
            }
        }
    }

Query the results of asynchronous video moderation

Operation

Description

Supported region

VideoAsyncScanResultsRequest

Queries the results of asynchronous video moderation.

Note

Instead of calling this operation to poll the moderation results, we recommend that you set the callback parameter when you submit asynchronous video moderation tasks to receive the moderation results.

  • cn-shanghai: China (Shanghai)

  • cn-beijing: China (Beijing)

  • cn-shenzhen: China (Shenzhen)

  • ap-southeast-1: Singapore

Sample code

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.green.model.v20180509.VideoAsyncScanResultsRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) throws Exception {
        /**
         * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M.  
         * Common ways to obtain environment variables:
         * Method 1:
         *     Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         * Method 2:
         *     Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         */
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-shanghai",
                "We recommend that you obtain the AccessKey ID of your RAM user from environment variables",
                "We recommend that you obtain the AccessKey secret of your RAM user from environment variables");
        DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
        IAcsClient client = new DefaultAcsClient(profile);

        VideoAsyncScanResultsRequest videoAsyncScanResultsRequest = new VideoAsyncScanResultsRequest();
        videoAsyncScanResultsRequest.setAcceptFormat(FormatType.JSON);

        List<String> taskList = new ArrayList<String>();
        // Specify the ID of the asynchronous video moderation task that you want to query. Save the task ID that is returned after you submit a task. 
        taskList.add("ID of the asynchronous video moderation task");

        videoAsyncScanResultsRequest.setHttpContent(JSON.toJSONString(taskList).getBytes("UTF-8"), "UTF-8", FormatType.JSON);

        /**
         * Specify the connection timeout period and read timeout period. 
         */
        videoAsyncScanResultsRequest.setConnectTimeout(3000);
        videoAsyncScanResultsRequest.setReadTimeout(6000);
        try {
            HttpResponse httpResponse = client.doAction(videoAsyncScanResultsRequest);
            if (httpResponse.isSuccess()) {
                JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                System.out.println(JSON.toJSONString(scrResponse, true));
                int requestCode = scrResponse.getIntValue("code");
                // The moderation results of all videos. 
                JSONArray taskResults = scrResponse.getJSONArray("data");
                if (200 == requestCode) {
                    for (Object taskResult : taskResults) {
                        // The moderation result of a single video. 
                        int taskCode = ((JSONObject) taskResult).getIntValue("code");
                        if (280 == taskCode) {
                            // Moderating. 
                            // The task ID. 
                            System.out.println(((JSONObject) taskResult).getString("taskId"));
                        } else if (200 == taskCode) {
                            // The task ID. 
                            System.out.println(((JSONObject) taskResult).getString("taskId"));
                            // The moderation result. 
                            JSONArray results = ((JSONObject) taskResult).getJSONArray("results");
                            for (Object result : results) {
                                // The category of the moderation result of the moderated video. 
                                System.out.println(((JSONObject) result).getString("label"));
                                // The score of the confidence level. Valid values: 0 to 100. A greater value indicates a higher confidence level. 
                                System.out.println(((JSONObject) result).getString("rate"));
                                // The moderation scenario of the moderated video, which you specify in the moderation request. 
                                System.out.println(((JSONObject) result).getString("scene"));
                                // The recommended subsequent operation. Valid values:
                                // pass: The moderated object does not require further actions. 
                                // review: The moderated object contains suspected violations and requires manual review. 
                                // block: The moderated object contains violations. We recommend that you delete or block the object. 
                                System.out.println(((JSONObject) result).getString("suggestion"));
                            }
                        } else {
                            // A single video failed to be moderated. Analyze the failure based on the actual situation. 
                            System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                        }
                    }
                } else {
                    /**
                     * The request failed to be processed. Analyze the failure based on the actual situation. 
                     */
                    System.out.println("the whole scan request failed. response:" + JSON.toJSONString(scrResponse));
                }
            } else {
                System.out.println("response not success. status:" + httpResponse.getStatus());
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}

Submit synchronous video moderation tasks

Operation

Description

Supported region

VideoSyncScanRequest

Sends synchronous requests to moderate videos for risky content.

Note

You can submit only a sequence of frames that are captured from a video for video moderation. To submit other types of videos, we recommend that you use the VideoAsyncScanRequest operation.

  • cn-shanghai: China (Shanghai)

  • cn-beijing: China (Beijing)

  • cn-shenzhen: China (Shenzhen)

  • ap-southeast-1: Singapore

Sample code

Note

In this example, a sequence of frames that are captured from a video is to be moderated.

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.green.model.v20180509.VideoSyncScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class Main {

    public static void main(String[] args) throws Exception {
        /**
         * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M.  
         * Common ways to obtain environment variables:
         * Method 1:
         *     Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         * Method 2:
         *     Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         */
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-shanghai",
                "We recommend that you obtain the AccessKey ID of your RAM user from environment variables",
                "We recommend that you obtain the AccessKey secret of your RAM user from environment variables");
        DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
        IAcsClient client = new DefaultAcsClient(profile);

        VideoSyncScanRequest videoSyncScanRequest = new VideoSyncScanRequest();
        videoSyncScanRequest.setAcceptFormat(FormatType.JSON); // Specify the response format of the operation. 
        videoSyncScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // Specify the request method. 

        List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
        Map<String, Object> task = new LinkedHashMap<String, Object>();
        task.put("dataId", UUID.randomUUID().toString());

        List<Map<String, Object>> frames = new ArrayList<Map<String, Object>>();
        Map<String, Object> frame1 = new LinkedHashMap<String, Object>();
        frame1.put("offset", 0);
        frame1.put("url", "URL of Video Frame 1");

        Map<String, Object> frame2 = new LinkedHashMap<String, Object>();
        frame2.put("offset", 5);
        frame2.put("url", "URL of Video Frame 2");

        Map<String, Object> frame3 = new LinkedHashMap<String, Object>();
        frame3.put("offset", 10);
        frame3.put("url", "URL of Video Frame 3");
        frames.addAll(Arrays.asList(frame1, frame2, frame3));

        task.put("frames", frames);
        tasks.add(task);
        /**
         * Specify the moderation scenario. The system charges you based on the moderation scenario that you specify. 
         * By default, a frame is captured from the video per second. You can specify the frequency at which sequential frames are captured. The system charges you based on the number of frames that are captured from the video and the moderation scenarios for each frame. 
         * For example, if 60 frames are captured from a 1-minute video and you want to moderate the video for both pornography and terrorist content, you are charged for moderating 60 frames for pornography and 60 frames for terrorist content. 
         */
        JSONObject data = new JSONObject();
        data.put("scenes", Arrays.asList("porn", "terrorism"));
        data.put("tasks", tasks);

        videoSyncScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);

        /**
         * Specify the connection timeout period and read timeout period. 
         */
        videoSyncScanRequest.setConnectTimeout(3000);
        videoSyncScanRequest.setReadTimeout(10000);
        try {
            HttpResponse httpResponse = client.doAction(videoSyncScanRequest);

            if (httpResponse.isSuccess()) {
                JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                System.out.println(JSON.toJSONString(scrResponse, true));
                int requestCode = scrResponse.getIntValue("code");
                // The moderation results of all videos. 
                JSONArray taskResults = scrResponse.getJSONArray("data");
                if (200 == requestCode) {
                    for (Object taskResult : taskResults) {
                        // The moderation result of a single video. 
                        int taskCode = ((JSONObject) taskResult).getIntValue("code");
                        if (200 == taskCode) {
                            // The task ID. 
                            System.out.println(((JSONObject) taskResult).getString("taskId"));
                            // The moderation result. 
                            JSONArray results = scrResponse.getJSONArray("results");
                            for (Object result : results) {
                                // The category of the moderation result of the moderated video. 
                                System.out.println(((JSONObject) result).getString("label"));
                                // The score of the confidence level. Valid values: 0 to 100. A greater value indicates a higher confidence level. 
                                System.out.println(((JSONObject) result).getString("rate"));
                                // The moderation scenario of the moderated video, which you specify in the moderation request. 
                                System.out.println(((JSONObject) result).getString("scene"));
                                // The recommended subsequent operation. Valid values:
                                // pass: The moderated object does not require further actions. 
                                // review: The moderated object contains suspected violations and requires manual review. 
                                // block: The moderated object contains violations. We recommend that you delete or block the object. 
                                System.out.println(((JSONObject) result).getString("suggestion"));
                            }
                        } else {
                            // A single video failed to be moderated. Analyze the failure based on the actual situation. 
                            System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
                        }
                    }
                } else {
                    /**
                     * The request failed to be processed. Analyze the failure based on the actual situation. 
                     */
                    System.out.println("the whole scan request failed. response:" + JSON.toJSONString(scrResponse));
                }
            } else {
                System.out.println("response not success. status:" + httpResponse.getStatus());
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}

Provide feedback on moderation results

If the moderation results do not meet your expectations, you can call the VideoFeedbackRequest operation to modify the results. Content Moderation adds the moderated video frames to the similar image blacklist or whitelist based on your feedback. When you submit a similar video frame for moderation, Content Moderation returns moderation results based on the label in your feedback.

For more information, see /green/video/feedback.

Operation

Description

Supported region

VideoFeedbackRequest

Provides feedback on video moderation results and modifies the machine-assisted moderation results based on the feedback.

  • cn-shanghai: China (Shanghai)

  • cn-beijing: China (Beijing)

  • cn-shenzhen: China (Shenzhen)

  • ap-southeast-1: Singapore

Sample code

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.green.model.v20180509.VideoFeedbackRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class VideoFeedbackSample {

    public static void main(String[] args) throws Exception {
        /**
         * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M.  
         * Common ways to obtain environment variables:
         * Method 1:
         *     Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         * Method 2:
         *     Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
         *     Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
         */
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-shanghai",
                "We recommend that you obtain the AccessKey ID of your RAM user from environment variables",
                "We recommend that you obtain the AccessKey secret of your RAM user from environment variables");
        DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        // Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
        IAcsClient client = new DefaultAcsClient(profile);

        VideoFeedbackRequest videoFeedbackRequest = new VideoFeedbackRequest();
        // Specify the response format of the operation. 
        videoFeedbackRequest.setAcceptFormat(FormatType.JSON);
        // Specify the request method. 
        videoFeedbackRequest.setMethod(MethodType.POST);
        videoFeedbackRequest.setEncoding("utf-8");
        // Both HTTP and HTTPS are supported. 
        videoFeedbackRequest.setProtocol(ProtocolType.HTTP);

        List<JSONObject> framesList = new ArrayList();
        JSONObject frame1 = new JSONObject();
        frame1.put("url", "URL of Video Frame 1");
        frame1.put("offset", 100);
        framesList.add(frame1);
        // scenes: the moderation scenarios. You can specify one or more moderation scenarios. 
        // suggestion: the moderation results that you expect to return. A value of pass indicates that the moderated video frame is normal. A value of block indicates that the moderated video frame contains violations. 
        JSONObject httpBody = new JSONObject();
        httpBody.put("dataId", "ID of the moderated data");
        httpBody.put("taskId", "ID of the video moderation task");
        httpBody.put("url", "URL of the moderated video");
        httpBody.put("suggestion", "block");
        httpBody.put("frames", framesList);
        httpBody.put("scenes", Arrays.asList("ad", "terrorism"));
        httpBody.put("note", "Remarks");

        videoFeedbackRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()),
                "UTF-8", FormatType.JSON);

        videoFeedbackRequest.setConnectTimeout(3000);
        videoFeedbackRequest.setReadTimeout(10000);
        try {
            HttpResponse httpResponse = client.doAction(videoFeedbackRequest);

            if (httpResponse.isSuccess()) {
                JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                System.out.println(JSON.toJSONString(scrResponse, true));
                int requestCode = scrResponse.getIntValue("code");
                if (200 == requestCode) {
                    // The call was successful.
                } else {
                    /**
                     * The request failed to be processed. Analyze the failure based on the actual situation. 
                     */
                    System.out.println("the whole request failed. response:" + JSON.toJSONString(scrResponse));
                }
            } else {
                System.out.println("response not success. status:" + httpResponse.getStatus());
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}