Video Moderation 2.0 SDK and integration

更新时间:
复制 MD 格式

Video Moderation 2.0 supports integration through SDKs or native HTTPS requests. We recommend using an SDK because it automatically handles details such as signature verification and request formatting. This topic describes how to integrate Video Moderation 2.0.

Step 1: Activate the service

Go to the Activate Content Moderation 2.0 service page to activate the Content Moderation 2.0 service. After you integrate and use the API, you are automatically charged based on your usage. For more information, see billing. You can also purchase a resource plan. Resource plans offer tiered discounts compared to the pay-as-you-go method and are suitable for users with predictable and high usage.

After you activate the Content Moderation 2.0 service, the default billing method is pay-as-you-go. Fees are settled daily based on actual usage. If you do not call the service, you are not charged.

Step 2: Grant permissions to a RAM user

Before you use the SDK or API, you must grant permissions to a RAM user. You also need to create an AccessKey pair for the RAM user to authenticate your Alibaba Cloud API calls. For more information, see Obtain an AccessKey pair.

Grant permissions to a RAM user

  1. Log on to the RAM console using your Alibaba Cloud account.

  2. Create a RAM user. For details, see Create a RAM user.

  3. Grant the AliyunYundunGreenWebFullAccess system policy to the RAM user. This policy grants full access to Content Moderation. For details, see Manage RAM user permissions.

    The RAM user can now call the Content Moderation API.

Step 3: Integrate video moderation

The video moderation service is available in the following regions:

Region

Public endpoint

Internal endpoint

Supported services

China (Shanghai)

https://green-cip.cn-shanghai.aliyuncs.com

https://green-cip-vpc.cn-shanghai.aliyuncs.com

videoDetection, liveStreamDetection, videoDetectionByVL, liveStreamDetectionByVL, videoAigcDetector

China (Beijing)

https://green-cip.cn-beijing.aliyuncs.com

https://green-cip-vpc.cn-beijing.aliyuncs.com

China (Hangzhou)

https://green-cip.cn-hangzhou.aliyuncs.com

https://green-cip-vpc.cn-hangzhou.aliyuncs.com

videoDetection, liveStreamDetection

China (Shenzhen)

https://green-cip.cn-shenzhen.aliyuncs.com

https://green-cip-vpc.cn-shenzhen.aliyuncs.com

Asia Pacific SE 1 (Singapore)

https://green-cip.ap-southeast-1.aliyuncs.com

https://green-cip-vpc.ap-southeast-1.aliyuncs.com

videoDetection_cb, videoDetectionByVL_cb, liveStreamDetection_cb, liveStreamDetectionByVL_cb

US East 1 (Virginia)

https://green-cip.us-east-1.aliyuncs.com

https://green-cip-vpc.us-east-1.aliyuncs.com

videoDetection_cb, liveStreamDetection_cb

US West 1 (Silicon Valley)

https://green-cip.us-west-1.aliyuncs.com

Not available

EU Central 1 (Frankfurt)

https://green-cip.eu-central-1.aliyuncs.com

Not available

Note

To get SDK sample code in other languages, use the online debugging tool in the OpenAPI Developer Portal to debug API operations. The tool automatically generates the SDK sample code. The following API operations are available for online debugging:

Alibaba Cloud SDKs create default credentials by reading the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. When you call an API operation, the program reads your AccessKey from these variables and automatically completes authentication. Before you use SDK sample code, you must configure the environment variables. For more information, see Configure authentication credentials.

For details on API fields, see Video File Moderation 2.0 API and Live Stream Moderation 2.0 API.

Java SDK

This feature requires Java 1.8 or later.

For the source code, see Java SDK source code or Java SDK source code (OSS path).

This service supports three types of video detection.

Moderate public videos

Scenarios

The Video Moderation Enhanced service can fetch and moderate videos that are accessible from a public URL.

  1. Add the following dependency to the pom.xml file to use the SDK in your Maven project.

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>green20220302</artifactId>
      <version>3.3.3</version>
    </dependency>
  2. Integrate the Java SDK.

    • Submitting a video detection task

      import com.alibaba.fastjson.JSON;
      import com.alibaba.fastjson.JSONObject;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.VideoModerationRequest;
      import com.aliyun.green20220302.models.VideoModerationResponse;
      import com.aliyun.green20220302.models.VideoModerationResponseBody;
      import com.aliyun.teaopenapi.models.Config;
      
      
      public class VideoModerationDemo {
      
          public static void main(String[] args) throws Exception {
              Config config = new Config();
             /**
               * An AccessKey pair from an Alibaba Cloud account grants full API access. For security, we recommend using a RAM user for API calls and daily O&M.
               * Common methods to obtain credentials from environment variables:
               * Method 1:
               *     Get the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Get the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Get the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Get the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              config.setAccessKeyId("YOUR_ACCESS_KEY_ID");
              config.setAccessKeySecret("YOUR_ACCESS_KEY_SECRET");
              // Configure your region and endpoint.
              config.setRegionId("cn-shanghai");
              config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
              // Read timeout in milliseconds.
              config.setReadTimeout(6000);
              // Connection timeout in milliseconds.
              config.setConnectTimeout(3000);
              // Set the HTTP proxy.
              //config.setHttpProxy("http://10.10.xx.xx:xxxx");
              // Set the HTTPS proxy.
              //config.setHttpsProxy("https://10.10.xx.xx:xxxx");
              Client client = new Client(config);
      
              JSONObject serviceParameters = new JSONObject();
              serviceParameters.put("url", "https://xxx.oss.aliyuncs.com/xxx.mp4");
      
              VideoModerationRequest videoModerationRequest = new VideoModerationRequest();
              // Specify the service type. For regions in the Chinese mainland, use "videoDetection".
              videoModerationRequest.setService("videoDetection");
              videoModerationRequest.setServiceParameters(serviceParameters.toJSONString());
      
              try {
                  VideoModerationResponse response = client.videoModeration(videoModerationRequest);
                  if (response.getStatusCode() == 200) {
                      VideoModerationResponseBody result = response.getBody();
                      System.out.println(JSON.toJSONString(result));
                      System.out.println("requestId = " + result.getRequestId());
                      System.out.println("code = " + result.getCode());
                      System.out.println("msg = " + result.getMessage());
                      Integer code = result.getCode();
                      if (200 == code) {
                          VideoModerationResponseBody.VideoModerationResponseBodyData data = result.getData();
                          System.out.println("taskId = [" + data.getTaskId() + "]");
                      } else {
                          System.out.println("Video moderation failed. Code: " + code);
                      }
                  } else {
                      System.out.println("Request failed. Status: " + response.getStatusCode());
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }
    • Retrieving video detection task results

      import com.alibaba.fastjson.JSON;
      import com.alibaba.fastjson.JSONObject;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.VideoModerationResultRequest;
      import com.aliyun.green20220302.models.VideoModerationResultResponse;
      import com.aliyun.green20220302.models.VideoModerationResultResponseBody;
      import com.aliyun.teaopenapi.models.Config;
      
      public class VideoModerationResultDemo {
      
          public static void main(String[] args) throws Exception {
              Config config = new Config();
              /**
               * An AccessKey pair from an Alibaba Cloud account grants full API access. For security, we recommend using a RAM user for API calls and daily O&M.
               * Common methods to obtain credentials from environment variables:
               * Method 1:
               *     Get the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Get the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Get the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Get the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              config.setAccessKeyId("YOUR_ACCESS_KEY_ID");
              config.setAccessKeySecret("YOUR_ACCESS_KEY_SECRET");
              // Configure your region and endpoint.
              config.setRegionId("cn-shanghai");
              config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
              // Read timeout in milliseconds.
              config.setReadTimeout(6000);
              // Connection timeout in milliseconds.
              config.setConnectTimeout(3000);
              // Set the HTTP proxy.
              //config.setHttpProxy("http://10.10.xx.xx:xxxx");
              // Set the HTTPS proxy.
              //config.setHttpsProxy("https://10.10.xx.xx:xxxx");
              Client client = new Client(config);
      
              JSONObject serviceParameters = new JSONObject();
              // Specify the taskId returned from the submission request.
              serviceParameters.put("taskId", "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****");
      
      
              VideoModerationResultRequest videoModerationResultRequest = new VideoModerationResultRequest();
              // Specify the service type. For regions in the Chinese mainland, use "videoDetection".
              videoModerationResultRequest.setService("videoDetection");
              videoModerationResultRequest.setServiceParameters(serviceParameters.toJSONString());
      
              try {
                  VideoModerationResultResponse response = client.videoModerationResult(videoModerationResultRequest);
                  if (response.getStatusCode() == 200) {
                      VideoModerationResultResponseBody result = response.getBody();
                      System.out.println("requestId=" + result.getRequestId());
                      System.out.println("code=" + result.getCode());
                      System.out.println("msg=" + result.getMessage());
                      if (200 == result.getCode()) {
                          VideoModerationResultResponseBody.VideoModerationResultResponseBodyData data = result.getData();
                          System.out.println("dataId = " + data.getDataId());
                          System.out.println("riskLevel = " + data.getRiskLevel());
                          System.out.println("audioResult = " + JSON.toJSONString(data.getAudioResult()));
                          System.out.println("frameResult = " + JSON.toJSONString(data.getFrameResult()));
                      } else {
                          System.out.println("Failed to retrieve video moderation results. Code: " + result.getCode());
                      }
                  } else {
                      System.out.println("Request failed. Status: " + response.getStatusCode());
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }
    • Canceling a video detection task

      import com.alibaba.fastjson.JSONObject;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.VideoModerationCancelRequest;
      import com.aliyun.green20220302.models.VideoModerationCancelResponse;
      import com.aliyun.green20220302.models.VideoModerationCancelResponseBody;
      import com.aliyun.teaopenapi.models.Config;
      
      
      public class VideoModerationCancelDemo {
      
          public static void main(String[] args) throws Exception {
              Config config = new Config();
          		/**
               * An AccessKey pair from an Alibaba Cloud account grants full API access. For security, we recommend using a RAM user for API calls and daily O&M.
               * Common methods to obtain credentials from environment variables:
               * Method 1:
               *     Get the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Get the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Get the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Get the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              config.setAccessKeyId("YOUR_ACCESS_KEY_ID");
              config.setAccessKeySecret("YOUR_ACCESS_KEY_SECRET");
              // Configure your region and endpoint.
              config.setRegionId("cn-shanghai");
              config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
              // Read timeout in milliseconds.
              config.setReadTimeout(6000);
              // Connection timeout in milliseconds.
              config.setConnectTimeout(3000);
              // Set the HTTP proxy.
              //config.setHttpProxy("http://xx.xx.xx.xx:xxxx");
              // Set the HTTPS proxy.
              //config.setHttpsProxy("https://xx.xx.xx.xx:xxxx");
              Client client = new Client(config);
      
              JSONObject serviceParameters = new JSONObject();
              // Specify the taskId of the task to cancel.
              serviceParameters.put("taskId", "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****");
      
              VideoModerationCancelRequest videoModerationCancelRequest = new VideoModerationCancelRequest();
              
              videoModerationCancelRequest.setService("videoDetection");
              videoModerationCancelRequest.setServiceParameters(serviceParameters.toJSONString());
      
              try {
                  VideoModerationCancelResponse response = client.videoModerationCancel(videoModerationCancelRequest);
                  if (response.getStatusCode() == 200) {
                      VideoModerationCancelResponseBody result = response.getBody();
                      System.out.println("requestId=" + result.getRequestId());
                      System.out.println("code=" + result.getCode());
                      System.out.println("msg=" + result.getMessage());
                      if (200 != result.getCode()) {
                          System.out.println("Failed to cancel video moderation task. Code: " + result.getCode());
                      }
                  } else {
                      System.out.println("Request failed. Status: " + response.getStatusCode());
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }

Local video moderation

Use cases

If you need to moderate a video that is stored on your local machine and lacks a public URL, you can upload it to an OSS bucket provided by Content Moderation. The video moderation Enhanced Edition service can then directly access OSS to retrieve the video for moderation.

  1. Add the following dependency to pom.xml to use the SDK in a Maven project.

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>green20220302</artifactId>
      <version>3.3.3</version>
    </dependency>

    Install the OSS SDK:

    <dependency>
      <groupId>com.aliyun.oss</groupId>
      <artifactId>aliyun-sdk-oss</artifactId>
      <version>3.16.3</version>
    </dependency>
  2. Integrate the Java SDK.

    • Sample code for submitting a video moderation task

      import com.alibaba.fastjson.JSON;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.DescribeUploadTokenResponse;
      import com.aliyun.green20220302.models.DescribeUploadTokenResponseBody;
      import com.aliyun.green20220302.models.VideoModerationRequest;
      import com.aliyun.green20220302.models.VideoModerationResponse;
      import com.aliyun.green20220302.models.VideoModerationResponseBody;
      import com.aliyun.oss.OSS;
      import com.aliyun.oss.OSSClientBuilder;
      import com.aliyun.oss.model.PutObjectRequest;
      import com.aliyun.teaopenapi.models.Config;
      import com.aliyun.teautil.models.RuntimeOptions;
      
      import java.io.File;
      import java.util.HashMap;
      import java.util.Map;
      import java.util.UUID;
      
      public class LocalVideoModeration {
      
          // Specifies whether the service is deployed in a VPC.
          public static boolean isVPC = false;
      
          // A map of endpoints to file upload tokens.
          public static Map<String, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData> tokenMap = new HashMap<>();
      
          // The client for file upload requests.
          public static OSS ossClient = null;
      
          /**
           * Creates a client for sending requests.
           *
           * @param accessKeyId
           * @param accessKeySecret
           * @param endpoint
           * @return
           * @throws Exception
           */
          public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              Config config = new Config();
              config.setAccessKeyId(accessKeyId);
              config.setAccessKeySecret(accessKeySecret);
              // Change the region and endpoint based on your actual requirements.
              config.setEndpoint(endpoint);
              return new Client(config);
          }
      
          /**
           * Creates a client for file upload requests.
           *
           * @param tokenData
           * @param isVPC
           */
          public static void getOssClient(DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData, boolean isVPC) {
              // Note: To improve moderation performance, reuse the instantiated client to avoid repeatedly establishing connections.
              if (isVPC) {
                  ossClient = new OSSClientBuilder().build(tokenData.ossInternalEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken());
              } else {
                  ossClient = new OSSClientBuilder().build(tokenData.ossInternetEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken());
              }
          }
      
          /**
           * Uploads a file.
           *
           * @param filePath
           * @param tokenData
           * @return
           * @throws Exception
           */
          public static String uploadFile(String filePath, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData) throws Exception {
              String[] split = filePath.split("\\.");
              String objectName;
              if (split.length > 1) {
                  objectName = tokenData.getFileNamePrefix() + UUID.randomUUID() + "." + split[split.length - 1];
              } else {
                  objectName = tokenData.getFileNamePrefix() + UUID.randomUUID();
              }
              PutObjectRequest putObjectRequest = new PutObjectRequest(tokenData.getBucketName(), objectName, new File(filePath));
              ossClient.putObject(putObjectRequest);
              return objectName;
          }
      
          public static VideoModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              // Note: To improve moderation performance, reuse the instantiated client to avoid repeatedly establishing connections.
              Client client = createClient(accessKeyId, accessKeySecret, endpoint);
              RuntimeOptions runtime = new RuntimeOptions();
      
              // The full path to the local file, for example, D:\\localPath\\exampleFile.mp4.
              String filePath = "D:\\localPath\\exampleFile.mp4";
              // Obtain the file upload token.
              if (tokenMap.get(endpoint) == null || tokenMap.get(endpoint).expiration <= System.currentTimeMillis() / 1000) {
                  DescribeUploadTokenResponse tokenResponse = client.describeUploadToken();
                  tokenMap.put(endpoint, tokenResponse.getBody().getData());
              }
              // The client for file upload requests.
              getOssClient(tokenMap.get(endpoint), isVPC);
      
              // Upload the file.
              String objectName = uploadFile(filePath, tokenMap.get(endpoint));
      
              // Construct the moderation parameters.
              Map<String, String> serviceParameters = new HashMap<>();
              // File upload information.
              serviceParameters.put("ossBucketName", tokenMap.get(endpoint).getBucketName());
              serviceParameters.put("ossObjectName", objectName);
              serviceParameters.put("dataId", UUID.randomUUID().toString());
      
              VideoModerationRequest request = new VideoModerationRequest();
              // The moderation service. Set the value to videoDetection.
              request.setService("videoDetection");
              request.setServiceParameters(JSON.toJSONString(serviceParameters));
      
              VideoModerationResponse response = null;
              try {
                  response = client.videoModerationWithOptions(request, runtime);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return response;
          }
      
          public static void main(String[] args) throws Exception {
              /**
               * An AccessKey pair for an Alibaba Cloud account has permissions for all API operations. We recommend that you use a RAM user for API access and daily O&M.
               * Common methods for obtaining environment variables:
               * Method 1:
               *     Obtain the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Obtain the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              String accessKeyId = "We recommend that you obtain the AccessKey ID of your RAM user from environment variables.";
              String accessKeySecret = "We recommend that you obtain the AccessKey secret of your RAM user from environment variables.";
              // Change the region and endpoint based on your actual requirements.
              VideoModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-shanghai.aliyuncs.com");
              try {
                  // The following code implements a manual failover.
                  if (response != null) {
                      // Switch the region to China (Beijing).
                      if (500 == response.getStatusCode() || (response.getBody() != null && 500 == (response.getBody().getCode()))) {
                          // Change the region and endpoint based on your actual requirements.
                          response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-beijing.aliyuncs.com");
                      }
                  }
                  // Print the moderation result.
                  if (response != null) {
                      if (response.getStatusCode() == 200) {
                          VideoModerationResponseBody body = response.getBody();
                          System.out.println(JSON.toJSONString(body));
                          System.out.println("requestId = " + body.getRequestId());
                          System.out.println("code = " + body.getCode());
                          System.out.println("msg = " + body.getMessage());
                          Integer code = body.getCode();
                          if (200 == code) {
                              VideoModerationResponseBody.VideoModerationResponseBodyData data = body.getData();
                              System.out.println("taskId = [" + data.getTaskId() + "]");
                          } else {
                              System.out.println("video moderation not success. code:" + code);
                          }
                      } else {
                          System.out.println("response not success. status:" + response.getStatusCode());
                      }
                  }
                  } catch (Exception e) {
                      e.printStackTrace();
                  }
              } }
    • Sample code for retrieving the result of a video moderation task

      import com.alibaba.fastjson.JSON;
      import com.alibaba.fastjson.JSONObject;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.VideoModerationResultRequest;
      import com.aliyun.green20220302.models.VideoModerationResultResponse;
      import com.aliyun.green20220302.models.VideoModerationResultResponseBody;
      import com.aliyun.teaopenapi.models.Config;
      
      public class VideoModerationResultDemo {
      
          public static void main(String[] args) throws Exception {
              Config config = new Config();
              /**
               * An AccessKey pair for an Alibaba Cloud account has permissions for all API operations. We recommend that you use a RAM user for API access and daily O&M.
               * Common methods for obtaining environment variables:
               * Method 1:
               *     Obtain the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Obtain the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              config.setAccessKeyId("We recommend that you obtain the AccessKey ID of your RAM user from environment variables.");
              config.setAccessKeySecret("We recommend that you obtain the AccessKey secret of your RAM user from environment variables.");
              // Change the region and endpoint based on your actual requirements.
              config.setRegionId("cn-shanghai");
              config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
              // The read timeout in milliseconds (ms).
              config.setReadTimeout(6000);
              // The connection timeout in milliseconds (ms).
              config.setConnectTimeout(3000);
              // Sets the HTTP proxy.
              //config.setHttpProxy("http://10.10.xx.xx:xxxx");
              // Sets the HTTPS proxy.
              //config.setHttpsProxy("https://10.10.xx.xx:xxxx");
              Client client = new Client(config);
      
              JSONObject serviceParameters = new JSONObject();
              // The ID of the task returned upon submission.
              serviceParameters.put("taskId", "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****");
      
      
              VideoModerationResultRequest videoModerationResultRequest = new VideoModerationResultRequest();
              // The moderation service. Set the value to videoDetection.
              videoModerationResultRequest.setService("videoDetection");
              videoModerationResultRequest.setServiceParameters(serviceParameters.toJSONString());
      
              try {
                  VideoModerationResultResponse response = client.videoModerationResult(videoModerationResultRequest);
                  if (response.getStatusCode() == 200) {
                      VideoModerationResultResponseBody result = response.getBody();
                      System.out.println("requestId=" + result.getRequestId());
                      System.out.println("code=" + result.getCode());
                      System.out.println("msg=" + result.getMessage());
                      if (200 == result.getCode()) {
                          VideoModerationResultResponseBody.VideoModerationResultResponseBodyData data = result.getData();
                          System.out.println("dataId = " + data.getDataId());
                          System.out.println("riskLevel = " + data.getRiskLevel());
                          System.out.println("audioResult = " + JSON.toJSONString(data.getAudioResult()));
                          System.out.println("frameResult = " + JSON.toJSONString(data.getFrameResult()));
                      } else {
                          System.out.println("video moderation result not success. code:" + result.getCode());
                      }
                  } else {
                      System.out.println("response not success. status:" + response.getStatusCode());
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }
    • Sample code for canceling a video moderation task

      import com.alibaba.fastjson.JSONObject;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.VideoModerationCancelRequest;
      import com.aliyun.green20220302.models.VideoModerationCancelResponse;
      import com.aliyun.green20220302.models.VideoModerationCancelResponseBody;
      import com.aliyun.teaopenapi.models.Config;
      
      
      public class VideoModerationCancelDemo {
      
          public static void main(String[] args) throws Exception {
              Config config = new Config();
          		/**
               * An AccessKey pair for an Alibaba Cloud account has permissions for all API operations. We recommend that you use a RAM user for API access and daily O&M.
               * Common methods for obtaining environment variables:
               * Method 1:
               *     Obtain the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Obtain the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              config.setAccessKeyId("We recommend that you obtain the AccessKey ID of your RAM user from environment variables.");
              config.setAccessKeySecret("We recommend that you obtain the AccessKey secret of your RAM user from environment variables.");
              // Change the region and endpoint based on your actual requirements.
              config.setRegionId("cn-shanghai");
              config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
              // The read timeout in milliseconds (ms).
              config.setReadTimeout(6000);
              // The connection timeout in milliseconds (ms).
              config.setConnectTimeout(3000);
              // Sets the HTTP proxy.
              //config.setHttpProxy("http://xx.xx.xx.xx:xxxx");
              // Sets the HTTPS proxy.
              //config.setHttpsProxy("https://xx.xx.xx.xx:xxxx");
              Client client = new Client(config);
      
              JSONObject serviceParameters = new JSONObject();
              // The ID of the task returned upon submission.
              serviceParameters.put("taskId", "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****");
      
              VideoModerationCancelRequest videoModerationCancelRequest = new VideoModerationCancelRequest();
              
              videoModerationCancelRequest.setService("videoDetection");
              videoModerationCancelRequest.setServiceParameters(serviceParameters.toJSONString());
      
              try {
                  VideoModerationCancelResponse response = client.videoModerationCancel(videoModerationCancelRequest);
                  if (response.getStatusCode() == 200) {
                      VideoModerationCancelResponseBody result = response.getBody();
                      System.out.println("requestId=" + result.getRequestId());
                      System.out.println("code=" + result.getCode());
                      System.out.println("msg=" + result.getMessage());
                      if (200 != result.getCode()) {
                          System.out.println("video moderation cancel not success. code:" + result.getCode());
                      }
                  } else {
                      System.out.println("response not success. status:" + response.getStatusCode());
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }

Moderate videos in OSS

Use cases

To moderate video files already stored in OSS, create a service role to grant the Content Moderation service access to the files. The Video Moderation Enhanced service uses this role to retrieve and moderate the files. Visit the Cloud Resource Access Authorization page to create the service role.

  1. Add the following dependency to your project's pom.xml file to use the SDK.

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>green20220302</artifactId>
      <version>3.3.3</version>
    </dependency>
  2. Integrate the Java SDK.

    • Submit a video moderation task

      import com.alibaba.fastjson.JSON;
      import com.alibaba.fastjson.JSONObject;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.VideoModerationRequest;
      import com.aliyun.green20220302.models.VideoModerationResponse;
      import com.aliyun.green20220302.models.VideoModerationResponseBody;
      import com.aliyun.teaopenapi.models.Config;
      
      
      public class VideoModerationDemo {
      
          public static void main(String[] args) throws Exception {
              Config config = new Config();
             /**
               * An AccessKey pair for an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user for API calls or routine O&M.
               * Common methods to obtain environment variables:
               * Method 1:
               *     Obtain the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Obtain the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              config.setAccessKeyId("We recommend that you obtain the AccessKey ID of a RAM user from environment variables.");
              config.setAccessKeySecret("We recommend that you obtain the AccessKey secret of a RAM user from environment variables.");
              // Modify the region and endpoint based on your actual deployment.
              config.setRegionId("cn-shanghai");
              config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
              // Connection timeout in milliseconds (ms).
              config.setReadTimeout(6000);
              // Read timeout in milliseconds (ms).
              config.setConnectTimeout(3000);
              // Set the HTTP proxy.
              //config.setHttpProxy("http://10.10.xx.xx:xxxx");
              // Set the HTTPS proxy.
              //config.setHttpsProxy("https://10.10.xx.xx:xxxx");
              Client client = new Client(config);
      
              JSONObject serviceParameters = new JSONObject();
              serviceParameters.put("ossBucketName", "bucket_01");
              serviceParameters.put("ossObjectName", "20240307/07/28/test.flv");
              serviceParameters.put("ossRegionId", "cn-shanghai");
      
              VideoModerationRequest videoModerationRequest = new VideoModerationRequest();
              // Specify the moderation service. Set the value to videoDetection.
              videoModerationRequest.setService("videoDetection");
              videoModerationRequest.setServiceParameters(serviceParameters.toJSONString());
      
              try {
                  VideoModerationResponse response = client.videoModeration(videoModerationRequest);
                  if (response.getStatusCode() == 200) {
                      VideoModerationResponseBody result = response.getBody();
                      System.out.println(JSON.toJSONString(result));
                      System.out.println("requestId = " + result.getRequestId());
                      System.out.println("code = " + result.getCode());
                      System.out.println("msg = " + result.getMessage());
                      Integer code = result.getCode();
                      if (200 == code) {
                          VideoModerationResponseBody.VideoModerationResponseBodyData data = result.getData();
                          System.out.println("taskId = [" + data.getTaskId() + "]");
                      } else {
                          System.out.println("video moderation failed. code:" + code);
                      }
                  } else {
                      System.out.println("request failed. status:" + response.getStatusCode());
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }
    • Retrieve moderation results

      import com.alibaba.fastjson.JSON;
      import com.alibaba.fastjson.JSONObject;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.VideoModerationResultRequest;
      import com.aliyun.green20220302.models.VideoModerationResultResponse;
      import com.aliyun.green20220302.models.VideoModerationResultResponseBody;
      import com.aliyun.teaopenapi.models.Config;
      
      public class VideoModerationResultDemo {
      
          public static void main(String[] args) throws Exception {
              Config config = new Config();
              /**
               * An AccessKey pair for an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user for API calls or routine O&M.
               * Common methods to obtain environment variables:
               * Method 1:
               *     Obtain the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Obtain the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              config.setAccessKeyId("We recommend that you obtain the AccessKey ID of a RAM user from environment variables.");
              config.setAccessKeySecret("We recommend that you obtain the AccessKey secret of a RAM user from environment variables.");
              // Modify the region and endpoint based on your actual deployment.
              config.setRegionId("cn-shanghai");
              config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
              // Connection timeout in milliseconds (ms).
              config.setReadTimeout(6000);
              // Read timeout in milliseconds (ms).
              config.setConnectTimeout(3000);
              // Set the HTTP proxy.
              //config.setHttpProxy("http://10.10.xx.xx:xxxx");
              // Set the HTTPS proxy.
              //config.setHttpsProxy("https://10.10.xx.xx:xxxx");
              Client client = new Client(config);
      
              JSONObject serviceParameters = new JSONObject();
              // The ID of the task to query. This ID is returned when you submit a moderation task.
              serviceParameters.put("taskId", "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****");
      
      
              VideoModerationResultRequest videoModerationResultRequest = new VideoModerationResultRequest();
              // The moderation service that you want to use. Set the value to videoDetection.
              videoModerationResultRequest.setService("videoDetection");
              videoModerationResultRequest.setServiceParameters(serviceParameters.toJSONString());
      
              try {
                  VideoModerationResultResponse response = client.videoModerationResult(videoModerationResultRequest);
                  if (response.getStatusCode() == 200) {
                      VideoModerationResultResponseBody result = response.getBody();
                      System.out.println("requestId=" + result.getRequestId());
                      System.out.println("code=" + result.getCode());
                      System.out.println("msg=" + result.getMessage());
                      if (200 == result.getCode()) {
                          VideoModerationResultResponseBody.VideoModerationResultResponseBodyData data = result.getData();
                          System.out.println("dataId = " + data.getDataId());
                          System.out.println("riskLevel = " + data.getRiskLevel());
                          System.out.println("audioResult = " + JSON.toJSONString(data.getAudioResult()));
                          System.out.println("frameResult = " + JSON.toJSONString(data.getFrameResult()));
                      } else {
                          System.out.println("getting video moderation result failed. code:" + result.getCode());
                      }
                  } else {
                      System.out.println("request failed. status:" + response.getStatusCode());
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }
    • Cancel a video moderation task

      import com.alibaba.fastjson.JSONObject;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.VideoModerationCancelRequest;
      import com.aliyun.green20220302.models.VideoModerationCancelResponse;
      import com.aliyun.green20220302.models.VideoModerationCancelResponseBody;
      import com.aliyun.teaopenapi.models.Config;
      
      
      public class VideoModerationCancelDemo {
      
          public static void main(String[] args) throws Exception {
              Config config = new Config();
          		/**
               * An AccessKey pair for an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user for API calls or routine O&M.
               * Common methods to obtain environment variables:
               * Method 1:
               *     Obtain the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Obtain the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              config.setAccessKeyId("We recommend that you obtain the AccessKey ID of a RAM user from environment variables.");
              config.setAccessKeySecret("We recommend that you obtain the AccessKey secret of a RAM user from environment variables.");
              // Modify the region and endpoint based on your actual deployment.
              config.setRegionId("cn-shanghai");
              config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
              // Connection timeout in milliseconds (ms).
              config.setReadTimeout(6000);
              // Read timeout in milliseconds (ms).
              config.setConnectTimeout(3000);
              // Set the HTTP proxy.
              //config.setHttpProxy("http://xx.xx.xx.xx:xxxx");
              // Set the HTTPS proxy.
              //config.setHttpsProxy("https://xx.xx.xx.xx:xxxx");
              Client client = new Client(config);
      
              JSONObject serviceParameters = new JSONObject();
              // The ID of the task to cancel. This ID is returned when you submit a moderation task.
              serviceParameters.put("taskId", "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****");
      
              VideoModerationCancelRequest videoModerationCancelRequest = new VideoModerationCancelRequest();
              
              videoModerationCancelRequest.setService("videoDetection");
              videoModerationCancelRequest.setServiceParameters(serviceParameters.toJSONString());
      
              try {
                  VideoModerationCancelResponse response = client.videoModerationCancel(videoModerationCancelRequest);
                  if (response.getStatusCode() == 200) {
                      VideoModerationCancelResponseBody result = response.getBody();
                      System.out.println("requestId=" + result.getRequestId());
                      System.out.println("code=" + result.getCode());
                      System.out.println("msg=" + result.getMessage());
                      if (200 != result.getCode()) {
                          System.out.println("video moderation cancellation failed. code:" + result.getCode());
                      }
                  } else {
                      System.out.println("request failed. status:" + response.getStatusCode());
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }

Python SDK

Python 3.6 or later is required.

For the source code, see Python SDK source code.

This service supports the following three types of video moderation.

Publicly accessible videos

Use cases

If the video you want to moderate is accessible via a public URL, the video moderationEnhanced Edition service can fetch the file and moderate it.

  1. Run the following command to install the package:

    pip install alibabacloud_green20220302==3.2.4
  2. Integrate the Python SDK.

    • Sample code for submitting a video moderation task

      # -*- encoding: utf-8 -*-
      # Python 3.6 or later is required.
      import os
      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      import json
      
      config = Config(
                  # We recommend that you use a RAM user for API access and routine O&M.
                  # For security, do not hardcode your AccessKey ID and AccessKey Secret. This practice can lead to leaks, compromising the security of all resources in your account.
                  # Store your credentials in environment variables, as shown in this example.
                  access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
                  access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
                  # Connection timeout in milliseconds.
                  connect_timeout=3000,
                  # Read timeout in milliseconds.
                  read_timeout=6000,
                  # The service region and endpoint. Specify them based on your business requirements.
                  region_id='cn-shanghai',
                  endpoint='green-cip.cn-shanghai.aliyuncs.com'
      )
      
      clt = Client(config)
      
      serviceParameters = {
          'url': 'https://xxx.oss.aliyuncs.com/xxx.mp4'
      }
      videoModerationRequest = models.VideoModerationRequest(
          # The moderation service. Set the value to 'videoDetection'.
          service='videoDetection',
          service_parameters=json.dumps(serviceParameters)
      )
      
      try:
          response = clt.video_moderation(videoModerationRequest)
          if response.status_code == 200:
              # The API call is successful.
              # Obtain the moderation result.
              result = response.body
              print('response success. result:{}'.format(result))
          else:
              print('response not success. status:{} ,result:{}'.format(response.status_code, response))
      except Exception as err:
          print(err)
    • Retrieve video moderation results

      # -*- encoding: utf-8 -*-
      # Python 3.6 or later is required.
      import os
      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      import json
      
      config = Config(
                  # We recommend that you use a RAM user for API access and routine O&M.
                  # For security, do not hardcode your AccessKey ID and AccessKey Secret. This practice can lead to leaks, compromising the security of all resources in your account.
                  # Store your credentials in environment variables, as shown in this example.
                  access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
                  access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
                  # Connection timeout in milliseconds.
                  connect_timeout=3000,
                  # Read timeout in milliseconds.
                  read_timeout=6000,
                  # The service region and endpoint. Specify them based on your business requirements.
                  region_id='cn-shanghai',
                  endpoint='green-cip.cn-shanghai.aliyuncs.com'
      )
      
      clt = Client(config)
      
      # The ID of the video moderation task, returned upon submission.
      serviceParameters = {
          "taskId": 'vi_f_11w5THcbVYctjdxz2C0Afa-1x****'
      }
      videoModerationResultRequest = models.VideoModerationResultRequest(
          # The moderation service. Set the value to 'videoDetection'.
          service='videoDetection',
          service_parameters=json.dumps(serviceParameters)
      )
      
      try:
          response = clt.video_moderation_result(videoModerationResultRequest)
          if response.status_code == 200:
              # The API call is successful.
              # Obtain the moderation result.
              result = response.body
              print('response success. result:{}'.format(result))
          else:
              print('response not success. status:{} ,result:{}'.format(response.status_code, response))
      except Exception as err:
          print(err)
    • Sample code for canceling a live video stream moderation task

      # -*- encoding: utf-8 -*-
      # Python 3.6 or later is required.
      import os
      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      import json
      
      config = Config(
          # We recommend that you use a RAM user for API access and routine O&M.
          # For security, do not hardcode your AccessKey ID and AccessKey Secret. This practice can lead to leaks, compromising the security of all resources in your account.
          # Store your credentials in environment variables, as shown in this example.
          access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
          access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
          # Connection timeout in milliseconds.
          connect_timeout=10000,
          # Read timeout in milliseconds.
          read_timeout=3000,
          region_id='cn-shanghai',
          endpoint='green-cip.cn-shanghai.aliyuncs.com'
      )
      
      clt = Client(config)
      
      # The ID of the task returned upon submission.
      serviceParameters = {
          "taskId": 'vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****'
      }
      videoModerationCancelRequest = models.VideoModerationCancelRequest(
          # The moderation service.
          service='videoDetection',
          service_parameters=json.dumps(serviceParameters)
      )
      
      try:
          response = clt.video_moderation_cancel(videoModerationCancelRequest)
          if response.status_code == 200:
              # The API call is successful.
              result = response.body
              print('response success. result:{}'.format(result))
          else:
              print('response not success. status:{} ,result:{}'.format(response.status_code, response))
      except Exception as err:
          print(err)

Local videos

Use cases

If the video that you want to moderate is on your local machine and does not have a public URL, you can upload it to an Object Storage Service (OSS) bucket provided by Content Moderation. The Video Moderation Enhanced Edition service can directly access OSS to retrieve and moderate the video.

  1. Run the following command to install the package:

    pip install alibabacloud_green20220302==3.2.4

    Install the OSS SDK:

    pip install oss2
  2. Integrate the Python SDK.

    • Sample code for submitting a video moderation task

      import os
      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      from alibabacloud_tea_util.client import Client as UtilClient
      from alibabacloud_tea_util import models as util_models
      import json
      import uuid
      
      import oss2
      import time
      
      config = Config(
          # We recommend that you use a RAM user for API access and routine O&M.
          # For security, do not hardcode your AccessKey ID and AccessKey Secret. This practice can lead to leaks, compromising the security of all resources in your account.
          # Store your credentials in environment variables, as shown in this example.
          access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
          access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
          # Connection timeout in milliseconds.
          connect_timeout=10000,
          # Read timeout in milliseconds.
          read_timeout=10000,
          # The service region and endpoint. Specify them based on your business requirements.
          region_id='cn-shanghai',
          endpoint='green-cip.cn-shanghai.aliyuncs.com'
      )
      # For better performance, reuse the client instance to avoid creating new connections for each request.
      client = Client(config)
      
      bucket = None
      upload_token = None
      
      
      def get_oss_client(is_vpc):
          global upload_token
          global bucket
          if (upload_token is None) or int(upload_token.expiration) <= int(time.time()):
              response = client.describe_upload_token()
      
              upload_token = response.body.data
              auth = oss2.StsAuth(upload_token.access_key_id, upload_token.access_key_secret, upload_token.security_token)
      
              end_point = upload_token.oss_internet_end_point
              if is_vpc:
                  end_point = upload_token.oss_internal_end_point
              bucket = oss2.Bucket(auth, end_point, upload_token.bucket_name)
      
      
      def upload_file(file_name, is_vpc):
          get_oss_client(is_vpc)
          object_name = upload_token.file_name_prefix + str(uuid.uuid4()) + '.' + file_name.split('.')[-1]
          bucket.put_object_from_file(object_name, file_name)
          return object_name
      
      
      def video_moderation_by_local_file(file_path, is_vpc):
          # 1. Upload the file.
          object_name = upload_file(file_path, is_vpc)
      
          # 2. Submit the video for moderation.
          service_parameters = {
              'dataId': str(uuid.uuid4()),
              'ossBucketName': upload_token.bucket_name,
              'ossObjectName': object_name
          }
      
          video_moderation_request = models.VideoModerationRequest(
              # The moderation service. Set the value to 'videoDetection'.
              service='videoDetection',
              service_parameters=json.dumps(service_parameters)
          )
      
          # Create a RuntimeOptions instance and configure its parameters.
          runtime = util_models.RuntimeOptions()
          runtime.read_timeout = 10000
          runtime.connect_timeout = 10000
          try:
              global client
              response = client.video_moderation_with_options(video_moderation_request, runtime)
              # Automatic routing.
              if UtilClient.equal_number(500,
                                         response.status_code) or not response or not response.body or 200 != response.body.code:
                  # If a server error occurs, the code switches to the cn-beijing region.
                  config.region_id = 'cn-beijing'
                  config.endpoint = 'green-cip.cn-beijing.aliyuncs.com'
                  client = Client(config)
                  response = client.video_moderation_with_options(video_moderation_request, runtime)
      
              if response.status_code == 200:
                  # The API call is successful.
                  # Obtain the moderation result.
                  result = response.body
                  print('response success. result:{}'.format(result))
                  if result.code == 200:
                      result_data = result.data
                      print('result: {}'.format(result_data))
              else:
                  print('response not success. status:{} ,result:{}'.format(response.status_code, response))
          except Exception as err:
              print(err)
      
      
      if __name__ == '__main__':
          # The path to the local file.
          file_path = '/path/to/your/video.mp4'
          # Indicates if the service is deployed in a virtual private cloud (VPC).
          is_vpc = False  # True
          video_moderation_by_local_file(file_path, is_vpc)
    • Retrieve video moderation results

      # -*- encoding: utf-8 -*-
      # Python 3.6 or later is required.
      import os
      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      import json
      
      config = Config(
                  # We recommend that you use a RAM user for API access and routine O&M.
                  # For security, do not hardcode your AccessKey ID and AccessKey Secret. This practice can lead to leaks, compromising the security of all resources in your account.
                  # Store your credentials in environment variables, as shown in this example.
                  access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
                  access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
                  # Connection timeout in milliseconds.
                  connect_timeout=3000,
                  # Read timeout in milliseconds.
                  read_timeout=6000,
                  # The service region and endpoint. Specify them based on your business requirements.
                  region_id='cn-shanghai',
                  endpoint='green-cip.cn-shanghai.aliyuncs.com'
      )
      
      clt = Client(config)
      
      # The ID of the video moderation task, returned upon submission.
      serviceParameters = {
          "taskId": 'vi_f_11w5THcbVYctjdxz2C0Afa-1x****'
      }
      videoModerationResultRequest = models.VideoModerationResultRequest(
          # The moderation service. Set the value to 'videoDetection'.
          service='videoDetection',
          service_parameters=json.dumps(serviceParameters)
      )
      
      try:
          response = clt.video_moderation_result(videoModerationResultRequest)
          if response.status_code == 200:
              # The API call is successful.
              # Obtain the moderation result.
              result = response.body
              print('response success. result:{}'.format(result))
          else:
              print('response not success. status:{} ,result:{}'.format(response.status_code, response))
      except Exception as err:
          print(err)
    • Sample code for canceling a live video stream moderation task

      # -*- encoding: utf-8 -*-
      # Python 3.6 or later is required.
      import os
      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      import json
      
      config = Config(
          # We recommend that you use a RAM user for API access and routine O&M.
          # For security, do not hardcode your AccessKey ID and AccessKey Secret. This practice can lead to leaks, compromising the security of all resources in your account.
          # Store your credentials in environment variables, as shown in this example.
          access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
          access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
          # Connection timeout in milliseconds.
          connect_timeout=10000,
          # Read timeout in milliseconds.
          read_timeout=3000,
          region_id='cn-shanghai',
          endpoint='green-cip.cn-shanghai.aliyuncs.com'
      )
      
      clt = Client(config)
      
      # The ID of the task returned upon submission.
      serviceParameters = {
          "taskId": 'vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****'
      }
      videoModerationCancelRequest = models.VideoModerationCancelRequest(
          # The moderation service.
          service='videoDetection',
          service_parameters=json.dumps(serviceParameters)
      )
      
      try:
          response = clt.video_moderation_cancel(videoModerationCancelRequest)
          if response.status_code == 200:
              # The API call is successful.
              result = response.body
              print('response success. result:{}'.format(result))
          else:
              print('response not success. status:{} ,result:{}'.format(response.status_code, response))
      except Exception as err:
          print(err)

OSS videos

Use cases

If the video you want to moderate is already in Object Storage Service (OSS), you must create a service role that grants the Content Moderation service access to your OSS resources. The video moderationEnhanced Edition service then uses this role to retrieve and moderate the file. To create the role, visit the Cloud Resource Access Authorization page.

  1. Run the following command to install the package:

    pip install alibabacloud_green20220302==3.2.4
  2. Integrate the Python SDK.

    • Sample code for submitting a video moderation task

      # -*- encoding: utf-8 -*-
      # Python 3.6 or later is required.
      import os
      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      import json
      
      config = Config(
                  # We recommend that you use a RAM user for API access and routine O&M.
                  # For security, do not hardcode your AccessKey ID and AccessKey Secret. This practice can lead to leaks, compromising the security of all resources in your account.
                  # Store your credentials in environment variables, as shown in this example.
                  access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
                  access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
                  # Connection timeout in milliseconds.
                  connect_timeout=3000,
                  # Read timeout in milliseconds.
                  read_timeout=6000,
                  # The service region and endpoint. Specify them based on your business requirements.
                  region_id='cn-shanghai',
                  endpoint='green-cip.cn-shanghai.aliyuncs.com'
      )
      
      clt = Client(config)
      
      serviceParameters = {
          'ossBucketName': 'your-bucket-name',
          'ossObjectName': 'path/to/your/video.flv',
          'ossRegionId': 'cn-shanghai'
      }
      videoModerationRequest = models.VideoModerationRequest(
          # The moderation service. Set the value to 'videoDetection'.
          service='videoDetection',
          service_parameters=json.dumps(serviceParameters)
      )
      
      try:
          response = clt.video_moderation(videoModerationRequest)
          if response.status_code == 200:
              # The API call is successful.
              # Obtain the moderation result.
              result = response.body
              print('response success. result:{}'.format(result))
          else:
              print('response not success. status:{} ,result:{}'.format(response.status_code, response))
      except Exception as err:
          print(err)
    • Retrieve video moderation results

      # -*- encoding: utf-8 -*-
      # Python 3.6 or later is required.
      import os
      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      import json
      
      config = Config(
                  # We recommend that you use a RAM user for API access and routine O&M.
                  # For security, do not hardcode your AccessKey ID and AccessKey Secret. This practice can lead to leaks, compromising the security of all resources in your account.
                  # Store your credentials in environment variables, as shown in this example.
                  access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
                  access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
                  # Connection timeout in milliseconds.
                  connect_timeout=3000,
                  # Read timeout in milliseconds.
                  read_timeout=6000,
                  # The service region and endpoint. Specify them based on your business requirements.
                  region_id='cn-shanghai',
                  endpoint='green-cip.cn-shanghai.aliyuncs.com'
      )
      
      clt = Client(config)
      
      # The ID of the video moderation task, returned upon submission.
      serviceParameters = {
          "taskId": 'vi_f_11w5THcbVYctjdxz2C0Afa-1x****'
      }
      videoModerationResultRequest = models.VideoModerationResultRequest(
          # The moderation service. Set the value to 'videoDetection'.
          service='videoDetection',
          service_parameters=json.dumps(serviceParameters)
      )
      
      try:
          response = clt.video_moderation_result(videoModerationResultRequest)
          if response.status_code == 200:
              # The API call is successful.
              # Obtain the moderation result.
              result = response.body
              print('response success. result:{}'.format(result))
          else:
              print('response not success. status:{} ,result:{}'.format(response.status_code, response))
      except Exception as err:
          print(err)
    • Sample code for canceling a live video stream moderation task

      # -*- encoding: utf-8 -*-
      # Python 3.6 or later is required.
      import os
      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      import json
      
      config = Config(
          # We recommend that you use a RAM user for API access and routine O&M.
          # For security, do not hardcode your AccessKey ID and AccessKey Secret. This practice can lead to leaks, compromising the security of all resources in your account.
          # Store your credentials in environment variables, as shown in this example.
          access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
          access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
          # Connection timeout in milliseconds.
          connect_timeout=10000,
          # Read timeout in milliseconds.
          read_timeout=3000,
          region_id='cn-shanghai',
          endpoint='green-cip.cn-shanghai.aliyuncs.com'
      )
      
      clt = Client(config)
      
      # The ID of the task returned upon submission.
      serviceParameters = {
          "taskId": 'vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****'
      }
      videoModerationCancelRequest = models.VideoModerationCancelRequest(
          # The moderation service.
          service='videoDetection',
          service_parameters=json.dumps(serviceParameters)
      )
      
      try:
          response = clt.video_moderation_cancel(videoModerationCancelRequest)
          if response.status_code == 200:
              # The API call is successful.
              result = response.body
              print('response success. result:{}'.format(result))
          else:
              print('response not success. status:{} ,result:{}'.format(response.status_code, response))
      except Exception as err:
          print(err)

PHP SDK

Requires PHP 5.6 or later.

For the source code, see the PHP SDK source code.

The following three types of video detection are supported.

Moderate public videos

Scenarios

The video moderation Enhanced service can fetch and moderate any video that is accessible from a public URL.

  1. Run the following command to install the dependency.

    composer require alibabacloud/green-20220302 3.2.4
  2. Integrate the PHP SDK.

    • Submit a video moderation task

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationRequest;
      use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      
      $config = new Config([
          /**
           * An AccessKey pair of an Alibaba Cloud account has permissions for all APIs. We recommend that you use a RAM user for API access and daily O&M.
           * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code. This may compromise the security of all resources in your account.
           * We recommend that you retrieve the credentials from environment variables. Examples:
           * Obtain the AccessKey ID of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
           * Obtain the AccessKey Secret of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
           */
          "accessKeyId" => 'We recommend that you obtain the AccessKey ID of your RAM user from environment variables.',
          "accessKeySecret" => 'We recommend that you obtain the AccessKey Secret of your RAM user from environment variables.',
          // Set an HTTP proxy.
          // "httpProxy" => "http://10.10.xx.xx:xxxx",
          // Set an HTTPS proxy.
          // "httpsProxy" => "https://10.10.xx.xx:xxxx",
          "endpoint" => "green-cip.cn-shanghai.aliyuncs.com",
          "regionId" => "cn-shanghai"
      
      ]);
      // Note: To improve detection performance, reuse the client instance to avoid repeatedly establishing connections.
      $client = new Green($config);
      
      $request = new VideoModerationRequest();
      // Detection type: `videoDetection` for video file detection, and `liveStreamDetection` for live stream detection.
      $request->service = "videoDetection";
      $serviceParameters = array("url" => "https://xxx.oss.aliyuncs.com/xxx.mp4");
      
      $request->serviceParameters = json_encode($serviceParameters);
      
      $runtime = new RuntimeOptions();
      $runtime->readTimeout = 6000;
      $runtime->connectTimeout = 3000;
      
      try {
          $response = $client->videoModerationWithOptions($request, $runtime);
          print_r($response->body);
          if (200 != $response->statusCode) {
              print_r("Response not successful. Code:" . $response->statusCode);
              return;
          }
          $body = $response->body;
          print_r("requestId = " . $body->requestId . "\n");
          print_r("code = " . $body->code . "\n");
          print_r("message = " . $body->message . "\n");
          if (200 != $body->code) {
              print_r("Video moderation not successful. Code:" . $body->code);
          }
          $data = $body->data;
          print_r("taskId = " . $data->taskId);
      } catch (TeaUnableRetryError $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }
    • Retrieve a video moderation task result

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationResultRequest;
      use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      
      $config = new Config([
          /**
           * An AccessKey pair of an Alibaba Cloud account has permissions for all APIs. We recommend that you use a RAM user for API access and daily O&M.
           * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code. This may compromise the security of all resources in your account.
           * We recommend that you retrieve the credentials from environment variables. Examples:
           * Obtain the AccessKey ID of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
           * Obtain the AccessKey Secret of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
           */
          "accessKeyId" => 'We recommend that you obtain the AccessKey ID of your RAM user from environment variables.',
          "accessKeySecret" => 'We recommend that you obtain the AccessKey Secret of your RAM user from environment variables.',
          // Set an HTTP proxy.
          // "httpProxy" => "http://10.10.xx.xx:xxxx",
          // Set an HTTPS proxy.
          // "httpsProxy" => "https://10.10.xx.xx:xxxx",
          "endpoint" => "green-cip.cn-shanghai.aliyuncs.com",
          "regionId" => "cn-shanghai"
      
      ]);
      // Note: To improve detection performance, reuse the client instance to avoid repeatedly establishing connections.
      $client = new Green($config);
      
      $request = new VideoModerationResultRequest();
      // Detection type: `videoDetection` for video file detection, and `liveStreamDetection` for live stream detection.
      $request->service = "videoDetection";
      $serviceParameters = array("taskId" => "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****");
      
      $request->serviceParameters = json_encode($serviceParameters);
      
      $runtime = new RuntimeOptions();
      $runtime->readTimeout = 6000;
      $runtime->connectTimeout = 3000;
      
      try {
          $response = $client->videoModerationResultWithOptions($request, $runtime);
          if (200 != $response->statusCode) {
              print_r("Response not successful. Code:" . $response->statusCode);
              return;
          }
          $body = $response->body;
          print_r("requestId = " . $body->requestId . "\n");
          print_r("code = " . $body->code . "\n");
          print_r("message = " . $body->message . "\n");
          if (280 == $body->code) {
              print_r("The video moderation task is being processed. Code:" . $body->code);
              return;
          }
          if (200 != $body->code) {
              print_r("The video moderation result was not retrieved. Code:" . $body->code);
              return;
          }
          $data = $body->data;
          print_r("liveId = " . $data->liveId . "\n");
          print_r("dataId = " . $data->dataId . "\n");
          print_r("riskLevel = " . $data->RiskLevel . "\n");
          print_r("audioResult = " . json_encode($data->audioResult) . "\n");
          print_r("frameResult = " . json_encode($data->frameResult) . "\n");
      } catch (TeaUnableRetryError $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }
    • Cancel a video moderation task

      <?php
        require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationCancelRequest;
      use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      
      $config = new Config([
          /**
           * An AccessKey pair of an Alibaba Cloud account has permissions for all APIs. We recommend that you use a RAM user for API access and daily O&M.
           * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code. This may compromise the security of all resources in your account.
           * We recommend that you retrieve the credentials from environment variables. Examples:
           * Obtain the AccessKey ID of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
           * Obtain the AccessKey Secret of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
           */
          "accessKeyId" => 'We recommend that you obtain the AccessKey ID of your RAM user from environment variables.',
          "accessKeySecret" => 'We recommend that you obtain the AccessKey Secret of your RAM user from environment variables.',
          // Set an HTTP proxy.
          // "httpProxy" => "http://10.10.xx.xx:xxxx",
          // Set an HTTPS proxy.
          // "httpsProxy" => "https://10.10.xx.xx:xxxx",
          "endpoint" => "green-cip.cn-shanghai.aliyuncs.com",
          "regionId" => "cn-shanghai"
      
      ]);
      // Note: To improve detection performance, reuse the client instance to avoid repeatedly establishing connections.
      $client = new Green($config);
      
      $request = new VideoModerationCancelRequest();
      // Detection type: `videoDetection` for video file detection, and `liveStreamDetection` for live stream detection.
      $request->service = "videoDetection";
      $serviceParameters = array('taskId' => 'vi_s_lyxBXzWhSsxuJjiNHcpQ0N-*****');
      
      $request->serviceParameters = json_encode($serviceParameters);
      
      $runtime = new RuntimeOptions();
      $runtime->readTimeout = 6000;
      $runtime->connectTimeout = 3000;
      
      try {
        $response = $client->videoModerationCancel($request, $runtime);
        print_r($response->body);
        if (200 == $response->statusCode) {
          $body = $response->body;
          print_r("requestId = " . $body->requestId);
          print_r("code = " . $body->code);
          print_r("message = " . $body->message);
          if (200 != $body->code) {
            print_r("The video moderation task was not canceled. Code:" . $body->code);
          }
        } else {
          print_r("Response not successful. Code:" . $response->statusCode);
        }
      } catch (TeaUnableRetryError $e) {
        var_dump($e->getMessage());
        var_dump($e->getErrorInfo());
        var_dump($e->getLastException());
        var_dump($e->getLastRequest());
      }

Moderate local videos

Use cases

To moderate a local video that does not have a public URL, you can upload it to an OSS bucket provided by Content Moderation. The video moderation Enhanced Edition service can then directly access OSS to moderate the video.

  1. Run the following commands to install the required dependencies.

    composer require alibabacloud/green-20220302 3.2.4

    Install the OSS SDK:

    composer require aliyuncs/oss-sdk-php
  2. Integrate the PHP SDK.

    • Submit a video moderation task

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationResponse;
      use AlibabaCloud\Tea\Utils\Utils;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationRequest;
      use OSS\OssClient;
      
      // Specifies whether the service is deployed in a VPC.
      $isVPC = false;
      // The file upload token.
      $tokenArray = array();
      // The client for file upload requests.
      $ossClient = null;
      
      /**
       * Creates a request client.
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return Green
       */
      function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
      {
          $config = new Config([
              "accessKeyId" => $accessKeyId,
              "accessKeySecret" => $accessKeySecret,
              // Set an HTTP proxy.
              // "httpProxy" => "http://10.10.xx.xx:xxxx",
              // Set an HTTPS proxy.
              // "httpsProxy" => "https://10.10.xx.xx:xxxx",
              "endpoint" => $endpoint,
          ]);
          return new Green($config);
      }
      
      /**
       * Creates a file upload client.
       * @param $tokenData
       * @return void
       */
      function create_upload_client($tokenData): void
      {
      
          global $isVPC;
          global $ossClient;
          // Note: For better performance, reuse the client to avoid repeated connections.
          if ($isVPC) {
              $ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternalEndPoint, false, $tokenData->securityToken);
          } else {
              $ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternetEndPoint, false, $tokenData->securityToken);
          }
      }
      
      /**
       * Uploads a file.
       * @param $filePath
       * @param $tokenData
       * @return string
       * @throws \OSS\Core\OssException
       */
      function upload_file($filePath, $tokenData): string
      {
          global $ossClient;
          // Initializes the OssClient.
          create_upload_client($tokenData);
          $split = explode(".", $filePath);
          if (count($split) > 1) {
              $objectName = $tokenData->fileNamePrefix . uniqid() . "." . explode(".", $filePath)[count($split) - 1];
          } else {
              $objectName = $tokenData->fileNamePrefix . uniqid();
          }
          // Uploads the file.
          $ossClient->uploadFile($tokenData->bucketName, $objectName, $filePath);
          return $objectName;
      }
      
      /**
       * Submits a moderation task.
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return VideoModerationResponse
       * @throws \OSS\Core\OssException
       */
      function invoke($accessKeyId, $accessKeySecret, $endpoint): VideoModerationResponse
      {
          global $tokenArray;
          // Note: For better performance, reuse the client to avoid repeated connections.
          $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
          // Sets runtime parameters.
          $runtime = new RuntimeOptions([]);
          // The full path of the local file, for example, D:\\localPath\\exampleFile.mp4.
          $filePath = "D:\\test\\video\\b652.mp4";
      
          // Get the file upload token.
          if (!isset($tokenArray[$endpoint]) || $tokenArray[$endpoint]->expiration <= time()) {
              $token = $client->describeUploadToken();
              $tokenArray[$endpoint] = $token->body->data;
          }
      
          // Uploads the file.
          $objectName = upload_file($filePath, $tokenArray[$endpoint]);
      
          // Set the moderation parameters.
          $request = new VideoModerationRequest();
          // Example: videoDetection
            $request->service = "videoDetection";
          // The OSS information for the file to be moderated.
          $serviceParameters = array(
              'ossObjectName' => $objectName,
              'ossBucketName' => $tokenArray[$endpoint]->bucketName,
              'dataId' => uniqid());
          $request->serviceParameters = json_encode($serviceParameters);
          // Submit the moderation task.
          return $client->videoModerationWithOptions($request, $runtime);
      }
      
      /**
       * An AccessKey pair for an Alibaba Cloud account has full permissions on all APIs. For better security, we recommend using a RAM user for API access and daily operations.
       * Do not hard-code your AccessKey ID and AccessKey Secret in your code. This can lead to credential leakage and compromise the security of all your resources.
       * We recommend obtaining your credentials from environment variables.
       * Obtain the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
       * Obtain the AccessKey secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
       */
      $accessKeyId = getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      $accessKeySecret = getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
      // Modify the region and endpoint as required.
      $endpoint = "green-cip.cn-shanghai.aliyuncs.com";
      
      try {
          $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          // Automatic routing.
          if (Utils::equalNumber(500, $response->statusCode) || Utils::equalNumber(500, $response->body->code)) {
              // Switch the region to China (Beijing).
              $endpoint = "green-cip.cn-beijing.aliyuncs.com";
              $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          }
          print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
      } catch (Exception $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }
    • Retrieve video moderation results

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationResultRequest;
      use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      
      $config = new Config([
          /**
           * An AccessKey pair for an Alibaba Cloud account has full permissions on all APIs. For better security, we recommend using a RAM user for API access and daily operations.
           * Do not hard-code your AccessKey ID and AccessKey Secret in your code. This can lead to credential leakage and compromise the security of all your resources.
           * We recommend obtaining your credentials from environment variables.
           * Obtain the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
           * Obtain the AccessKey secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
           */
          "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
          "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
          // Set an HTTP proxy.
          // "httpProxy" => "http://10.10.xx.xx:xxxx",
          // Set an HTTPS proxy.
          // "httpsProxy" => "https://10.10.xx.xx:xxxx",
          "endpoint" => "green-cip.cn-shanghai.aliyuncs.com",
          "regionId" => "cn-shanghai"
      
      ]);
      // Note: For better performance, reuse the client to avoid repeated connections.
      $client = new Green($config);
      
      $request = new VideoModerationResultRequest();
      // Service type: `videoDetection` for video file moderation, `liveStreamDetection` for live stream moderation.
      $request->service = "videoDetection";
      $serviceParameters = array("taskId" => "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****");
      
      $request->serviceParameters = json_encode($serviceParameters);
      
      $runtime = new RuntimeOptions();
      $runtime->readTimeout = 6000;
      $runtime->connectTimeout = 3000;
      
      try {
          $response = $client->videoModerationResultWithOptions($request, $runtime);
          if (200 != $response->statusCode) {
              print_r("Response not successful. code:" . $response->statusCode);
              return;
          }
          $body = $response->body;
          print_r("requestId = " . $body->requestId . "\n");
          print_r("code = " . $body->code . "\n");
          print_r("message = " . $body->message . "\n");
          if (280 == $body->code) {
              print_r("The video moderation task is in progress. code:" . $body->code);
              return;
          }
          if (200 != $body->code) {
              print_r("Failed to retrieve the video moderation results. code:" . $body->code);
              return;
          }
          $data = $body->data;
          print_r("liveId = " . $data->liveId . "\n");
          print_r("dataId = " . $data->dataId . "\n");
          print_r("riskLevel = " . $data->RiskLevel . "\n");
          print_r("audioResult = " . json_encode($data->audioResult) . "\n");
          print_r("frameResult = " . json_encode($data->frameResult) . "\n");
      } catch (TeaUnableRetryError $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }
    • Cancel a video moderation task

      <?php
        require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationCancelRequest;
      use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      
      $config = new Config([
          /**
           * An AccessKey pair for an Alibaba Cloud account has full permissions on all APIs. For better security, we recommend using a RAM user for API access and daily operations.
           * Do not hard-code your AccessKey ID and AccessKey Secret in your code. This can lead to credential leakage and compromise the security of all your resources.
           * We recommend obtaining your credentials from environment variables.
           * Obtain the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
           * Obtain the AccessKey secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
           */
          "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
          "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
          // Set an HTTP proxy.
          // "httpProxy" => "http://10.10.xx.xx:xxxx",
          // Set an HTTPS proxy.
          // "httpsProxy" => "https://10.10.xx.xx:xxxx",
          "endpoint" => "green-cip.cn-shanghai.aliyuncs.com",
          "regionId" => "cn-shanghai"
      
      ]);
      // Note: For better performance, reuse the client to avoid repeated connections.
      $client = new Green($config);
      
      $request = new VideoModerationCancelRequest();
      // Service type: `videoDetection` for video file moderation, `liveStreamDetection` for live stream moderation.
      $request->service = "videoDetection";
      $serviceParameters = array('taskId' => 'vi_s_lyxBXzWhSsxuJjiNHcpQ0N-*****');
      
      $request->serviceParameters = json_encode($serviceParameters);
      
      $runtime = new RuntimeOptions();
      $runtime->readTimeout = 6000;
      $runtime->connectTimeout = 3000;
      
      try {
        $response = $client->videoModerationCancel($request, $runtime);
        print_r($response->body);
        if (200 == $response->statusCode) {
          $body = $response->body;
          print_r("requestId = " . $body->requestId);
          print_r("code = " . $body->code);
          print_r("message = " . $body->message);
          if (200 != $body->code) {
            print_r("Failed to cancel the video moderation task. code:" . $body->code);
          }
        } else {
          print_r("Response not successful. code:" . $response->statusCode);
        }
      } catch (TeaUnableRetryError $e) {
        var_dump($e->getMessage());
        var_dump($e->getErrorInfo());
        var_dump($e->getLastException());
        var_dump($e->getLastRequest());
      }

OSS video detection

use case

If the video file you need to moderate is already stored in OSS, you can authorize the Content Moderation service to access OSS by creating a service role. The Video Moderation Enhanced service uses this service role to retrieve and moderate the file from OSS. Go to the Cloud Resource Access Authorization page to create a service role.

  1. Run the following command to install the required dependencies.

    composer require alibabacloud/green-20220302 3.2.4
  2. Integrate the PHP SDK.

    • Sample code for submitting a video detection task

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationRequest;
      use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      
      $config = new Config([
          /**
           * An AccessKey pair for an Alibaba Cloud account grants access to all APIs. We recommend using a RAM user for API access and daily O&M.
           * For security reasons, we strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your code.
           * Hard-coding credentials can lead to leakage and compromise the security of all resources in your account.
           * We recommend retrieving credentials from environment variables:
           * Get the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
           * Get the AccessKey Secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
           */
          "accessKeyId" => 'We recommend that you retrieve the RAM user AccessKey ID from an environment variable',
          "accessKeySecret" => 'We recommend that you retrieve the RAM user AccessKey Secret from an environment variable',
          // Set an HTTP proxy.
          // "httpProxy" => "http://10.10.xx.xx:xxxx",
          // Set an HTTPS proxy.
          // "httpsProxy" => "https://10.10.xx.xx:xxxx",
          "endpoint" => "green-cip.cn-shanghai.aliyuncs.com",
          "regionId" => "cn-shanghai"
      
      ]);
      // Note: Reuse the client whenever possible to avoid reconnecting and to improve detection performance.
      $client = new Green($config);
      
      $request = new VideoModerationRequest();
      // Detection type: `videoDetection` for video file detection, `liveStreamDetection` for live stream detection.
      $request->service = "videoDetection";
      $serviceParameters = array(
                // The file to be detected. Example: video/001.mp4
              'ossObjectName' => 'video/001.mp4',
              // The region of the bucket where the file is stored. Example: cn-shanghai
              'ossRegionId' => 'cn-shanghai',
                // The name of the bucket where the file is stored. Example: bucket001
              'ossBucketName' => 'bucket001',
              // A unique identifier for the data.
              'dataId' => uniqid());
      
      $request->serviceParameters = json_encode($serviceParameters);
      
      $runtime = new RuntimeOptions();
      $runtime->readTimeout = 6000;
      $runtime->connectTimeout = 3000;
      
      try {
          $response = $client->videoModerationWithOptions($request, $runtime);
          print_r($response->body);
          if (200 != $response->statusCode) {
              print_r("Response not successful. code:" . $response->statusCode);
              return;
          }
          $body = $response->body;
          print_r("requestId = " . $body->requestId . "\n");
          print_r("code = " . $body->code . "\n");
          print_r("message = " . $body->message . "\n");
          if (200 != $body->code) {
              print_r("Video moderation failed. code:" . $body->code);
          }
          $data = $body->data;
          print_r("taskId = " . $data->taskId);
      } catch (TeaUnableRetryError $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }
    • Sample code for querying a video detection task

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationResultRequest;
      use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      
      $config = new Config([
          /**
           * An AccessKey pair for an Alibaba Cloud account grants access to all APIs. We recommend using a RAM user for API access and daily O&M.
           * For security reasons, we strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your code.
           * Hard-coding credentials can lead to leakage and compromise the security of all resources in your account.
           * We recommend retrieving credentials from environment variables:
           * Get the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
           * Get the AccessKey Secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
           */
          "accessKeyId" => 'We recommend that you retrieve the RAM user AccessKey ID from an environment variable',
          "accessKeySecret" => 'We recommend that you retrieve the RAM user AccessKey Secret from an environment variable',
          // Set an HTTP proxy.
          // "httpProxy" => "http://10.10.xx.xx:xxxx",
          // Set an HTTPS proxy.
          // "httpsProxy" => "https://10.10.xx.xx:xxxx",
          "endpoint" => "green-cip.cn-shanghai.aliyuncs.com",
          "regionId" => "cn-shanghai"
      
      ]);
      // Note: Reuse the client whenever possible to avoid reconnecting and to improve detection performance.
      $client = new Green($config);
      
      $request = new VideoModerationResultRequest();
      // Detection type: `videoDetection` for video file detection, `liveStreamDetection` for live stream detection.
      $request->service = "videoDetection";
      $serviceParameters = array("taskId" => "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****");
      
      $request->serviceParameters = json_encode($serviceParameters);
      
      $runtime = new RuntimeOptions();
      $runtime->readTimeout = 6000;
      $runtime->connectTimeout = 3000;
      
      try {
          $response = $client->videoModerationResultWithOptions($request, $runtime);
          if (200 != $response->statusCode) {
              print_r("Response not successful. code:" . $response->statusCode);
              return;
          }
          $body = $response->body;
          print_r("requestId = " . $body->requestId . "\n");
          print_r("code = " . $body->code . "\n");
          print_r("message = " . $body->message . "\n");
          if (280 == $body->code) {
              print_r("The video moderation task is being processed. code:" . $body->code);
              return;
          }
          if (200 != $body->code) {
              print_r("The video moderation result was not successfully retrieved. code:" . $body->code);
              return;
          }
          $data = $body->data;
          print_r("liveId = " . $data->liveId . "\n");
          print_r("dataId = " . $data->dataId . "\n");
          print_r("riskLevel = " . $data->RiskLevel . "\n");
          print_r("audioResult = " . json_encode($data->audioResult) . "\n");
          print_r("frameResult = " . json_encode($data->frameResult) . "\n");
      } catch (TeaUnableRetryError $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }
    • Sample code for canceling a video detection task

      <?php
        require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationCancelRequest;
      use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      
      $config = new Config([
          /**
           * An AccessKey pair for an Alibaba Cloud account grants access to all APIs. We recommend using a RAM user for API access and daily O&M.
           * For security reasons, we strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your code.
           * Hard-coding credentials can lead to leakage and compromise the security of all resources in your account.
           * We recommend retrieving credentials from environment variables:
           * Get the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
           * Get the AccessKey Secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
           */
          "accessKeyId" => 'We recommend that you retrieve the RAM user AccessKey ID from an environment variable',
          "accessKeySecret" => 'We recommend that you retrieve the RAM user AccessKey Secret from an environment variable',
          // Set an HTTP proxy.
          // "httpProxy" => "http://10.10.xx.xx:xxxx",
          // Set an HTTPS proxy.
          // "httpsProxy" => "https://10.10.xx.xx:xxxx",
          "endpoint" => "green-cip.cn-shanghai.aliyuncs.com",
          "regionId" => "cn-shanghai"
      
      ]);
      // Note: Reuse the client whenever possible to avoid reconnecting and to improve detection performance.
      $client = new Green($config);
      
      $request = new VideoModerationCancelRequest();
      // Detection type: `videoDetection` for video file detection, `liveStreamDetection` for live stream detection.
      $request->service = "videoDetection";
      $serviceParameters = array('taskId' => 'vi_s_lyxBXzWhSsxuJjiNHcpQ0N-*****');
      
      $request->serviceParameters = json_encode($serviceParameters);
      
      $runtime = new RuntimeOptions();
      $runtime->readTimeout = 6000;
      $runtime->connectTimeout = 3000;
      
      try {
        $response = $client->videoModerationCancel($request, $runtime);
        print_r($response->body);
        if (200 == $response->statusCode) {
          $body = $response->body;
          print_r("requestId = " . $body->requestId);
          print_r("code = " . $body->code);
          print_r("message = " . $body->message);
          if (200 != $body->code) {
            print_r("The video moderation task was not successfully canceled. code:" . $body->code);
          }
        } else {
          print_r("Response not successful. code:" . $response->statusCode);
        }
      } catch (TeaUnableRetryError $e) {
        var_dump($e->getMessage());
        var_dump($e->getErrorInfo());
        var_dump($e->getLastException());
        var_dump($e->getLastRequest());
      }

Go SDK

This service supports three types of video detection.

Moderate videos from a public URL

Scenarios

If the video you want to moderate is available at a public URL, the video moderation Enhanced service can download and moderate it.

  1. Run the following command to install the required dependency.

    go get github.com/alibabacloud-go/green-20220302/v3@v3.2.4
  2. Integrate the SDK for Go.

    • Submit a video moderation task

      package main
      
      import (
      	"encoding/json"
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
      	util "github.com/alibabacloud-go/tea-utils/v2/service"
      	"github.comcom/alibabacloud-go/tea/tea"
      	"net/http"
      	"os"
      )
      
      func main() {
      	// For security reasons, we recommend that you do not hard-code your credentials in your code.
      	// Instead, load them from environment variables or use a more secure method like STS.
      	config := &openapi.Config{
      		// An AccessKey pair for an Alibaba Cloud account has permissions on all APIs.
      		// We recommend that you use a RAM user for API access or daily O&M.
      		// To secure your credentials, we recommend that you save them as environment variables.
      		AccessKeyId:     tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
      		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
      		// Set the HTTP proxy.
      		// HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"),
      		// Set the HTTPS proxy.
      		// HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
      		RegionId: tea.String("cn-shanghai"),
      		Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"),
      		/**
      		 * Set a timeout period. The server-side timeout for an end-to-end request is 10 seconds. Make sure that the settings are appropriate.
      		 * If the ReadTimeout that you set is shorter than the server's processing time, a ReadTimeout exception is thrown.
      		 */
      		ConnectTimeout: tea.Int(3000),
      		ReadTimeout:    tea.Int(6000),
      	}
      	client, _err := green20220302.NewClient(config)
      	if _err != nil {
      		panic(_err)
      	}
      
      	// Create a RuntimeObject instance and set runtime parameters.
      	runtime := &util.RuntimeOptions{}
      	runtime.ReadTimeout = tea.Int(10000)
      	runtime.ConnectTimeout = tea.Int(10000)
      
      	serviceParameters, _ := json.Marshal(
      		map[string]interface{}{
      			"url": "https://your-video-url.mp4",
      		},
      	)
      	request := green20220302.VideoModerationRequest{
      		Service:           tea.String("videoDetection"),
      		ServiceParameters: tea.String(string(serviceParameters)),
      	}
      
      	result, _err := client.VideoModerationWithOptions(&request, runtime)
      	if _err != nil {
      		panic(_err)
      	}
      
      	if *result.StatusCode != http.StatusOK {
      		fmt.Printf("response not success. status:%d\n", *result.StatusCode)
      		return
      	}
      	body := result.Body
      	fmt.Printf("response success. requestId:%s, code:%d, msg:%s\n", *body.RequestId, *body.Code, *body.Message)
      	if *body.Code != http.StatusOK {
      		fmt.Printf("video moderation not success. code:%d\n", *body.Code)
      		return
      	}
      
      	data := body.Data
      	fmt.Printf("video moderation taskId:%s\n", *data.TaskId)
      }
    • Get the results of a video moderation task

      package main
      
      import (
      	"encoding/json"
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
      	util "github.com/alibabacloud-go/tea-utils/v2/service"
      	"github.com/alibabacloud-go/tea/tea"
      	"net/http"
      	"os"
      )
      
      func main() {
      	// For security reasons, we recommend that you do not hard-code your credentials in your code.
      	// Instead, load them from environment variables or use a more secure method like STS.
      	config := &openapi.Config{
      		// An AccessKey pair for an Alibaba Cloud account has permissions on all APIs.
      		// We recommend that you use a RAM user for API access or daily O&M.
      		// To secure your credentials, we recommend that you save them as environment variables.
      		AccessKeyId:     tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
      		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
      		// Set the HTTP proxy.
      		// HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"),
      		// Set the HTTPS proxy.
      		// HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
      		RegionId: tea.String("cn-shanghai"),
      		Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"),
      		/**
      		 * Set a timeout period. The server-side timeout for an end-to-end request is 10 seconds. Make sure that the settings are appropriate.
      		 * If the ReadTimeout that you set is shorter than the server's processing time, a ReadTimeout exception is thrown.
      		 */
      		ConnectTimeout: tea.Int(3000),
      		ReadTimeout:    tea.Int(6000),
      	}
      	client, _err := green20220302.NewClient(config)
      	if _err != nil {
      		panic(_err)
      	}
      
      	// Create a RuntimeObject instance and set runtime parameters.
      	runtime := &util.RuntimeOptions{}
      	runtime.ReadTimeout = tea.Int(10000)
      	runtime.ConnectTimeout = tea.Int(10000)
      
      	serviceParameters, _ := json.Marshal(
      		map[string]interface{}{
      			"taskId": "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****",
      		},
      	)
      	request := green20220302.VideoModerationResultRequest{
      		Service:           tea.String("videoDetection"),
      		ServiceParameters: tea.String(string(serviceParameters)),
      	}
      
      	result, _err := client.VideoModerationResultWithOptions(&request, runtime)
      	if _err != nil {
      		panic(_err)
      	}
      
      	if *result.StatusCode != http.StatusOK {
      		fmt.Printf("response not success. status:%d\n", *result.StatusCode)
      		return
      	}
      	body := result.Body
      	fmt.Printf("response success. requestId:%s, code:%d, msg:%s\n", *body.RequestId, *body.Code, *body.Message)
      	if *body.Code == 280 {
      		fmt.Printf("The video moderation task is being processed. code:%d\n", *body.Code)
      		return
      	}
      	if *body.Code != http.StatusOK {
      		fmt.Printf("Failed to get the video moderation result. code:%d\n", *body.Code)
      		return
      	}
      
      	data := body.Data
          fmt.Printf("Video moderation result: %+v\n", data)
      	fmt.Printf("Audio result: %+v\n", data.AudioResult)
      	fmt.Printf("Frame result: %+v\n", data.FrameResult)
      }
    • Cancel a live stream moderation task

      package main
      
      import (
      	"encoding/json"
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
      	util "github.com/alibabacloud-go/tea-utils/v2/service"
      	"github.com/alibabacloud-go/tea/tea"
      	"net/http"
      	"os"
      )
      
      func main() {
      	// For security reasons, we recommend that you do not hard-code your credentials in your code.
      	// Instead, load them from environment variables or use a more secure method like STS.
      	config := &openapi.Config{
      		// An AccessKey pair for an Alibaba Cloud account has permissions on all APIs.
      		// We recommend that you use a RAM user for API access or daily O&M.
      		// To secure your credentials, we recommend that you save them as environment variables.
      		AccessKeyId:     tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
      		AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
      		// Set the HTTP proxy.
      		// HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"),
      		// Set the HTTPS proxy.
      		// HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
      		RegionId: tea.String("cn-shanghai"),
      		Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"),
      		/**
      		 * Set a timeout period. The server-side timeout for an end-to-end request is 10 seconds. Make sure that the settings are appropriate.
      		 * If the ReadTimeout that you set is shorter than the server's processing time, a ReadTimeout exception is thrown.
      		 */
      		ConnectTimeout: tea.Int(3000),
      		ReadTimeout:    tea.Int(6000),
      	}
      	client, _err := green20220302.NewClient(config)
      	if _err != nil {
      		panic(_err)
      	}
      
      	// Create a RuntimeObject instance and set runtime parameters.
      	runtime := &util.RuntimeOptions{}
      	runtime.ReadTimeout = tea.Int(10000)
      	runtime.ConnectTimeout = tea.Int(10000)
      
      	serviceParameters, _ := json.Marshal(
      		map[string]interface{}{
      			"taskId": "vi_s_lyxBXzWhSsxuJjiNHcpQ0N-*****",
      		},
      	)
      	request := green20220302.VideoModerationCancelRequest{
      		Service:           tea.String("videoDetection"),
      		ServiceParameters: tea.String(string(serviceParameters)),
      	}
      
      	result, _err := client.VideoModerationCancelWithOptions(&request, runtime)
      	if _err != nil {
      		panic(_err)
      	}
      
      	if *result.StatusCode != http.StatusOK {
      		fmt.Printf("response not success. status:%d\n", *result.StatusCode)
      		return
      	}
      	body := result.Body
      	fmt.Printf("response success. requestId:%s, code:%d, msg:%s\n", *body.RequestId, *body.Code, *body.Message)
      	if *body.Code != http.StatusOK {
      		fmt.Printf("Failed to cancel the video moderation task. code:%d\n", *body.Code)
      	}
      }

Moderate local videos

Use cases

When the video you need to moderate is on a local machine and does not have a public URL, you can upload the video to an Object Storage Service (OSS) bucket provided by Content Moderation. The Video Moderation Enhanced Edition service can directly access OSS to retrieve the video content for moderation.

  1. Run the following command to install the required dependency.

    go get github.com/alibabacloud-go/green-20220302/v3@v3.2.4

    Install the OSS SDK:

    go get github.com/aliyun/aliyun-oss-go-sdk/oss
  2. Integrate the Go SDK.

    • Sample code for submitting a video moderation task

      package main
      
      import (
          "encoding/json"
          "fmt"
          openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
          green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
          util "github.com/alibabacloud-go/tea-utils/v2/service"
          "github.com/alibabacloud-go/tea/tea"
          "github.com/aliyun/aliyun-oss-go-sdk/oss"
          "github.com/google/uuid"
          "net/http"
          "os"
          "strings"
          "time"
      )
      // The token for file upload.
      var TokenMap =make(map[string]*green20220302.DescribeUploadTokenResponseBodyData)
      // The client for file uploads.
      var Bucket *oss.Bucket
      // Specifies whether the service is deployed in a VPC.
      var isVPC = false
      // Creates a request client.
      func createClient(accessKeyId string, accessKeySecret string, endpoint string) (*green20220302.Client, error) {
          config := &openapi.Config{
              AccessKeyId: tea.String(accessKeyId),
              AccessKeySecret: tea.String(accessKeySecret),
              // Set the HTTP proxy.
              // HttpProxy: tea.String("http://10.10.xx.xx:xxxx"),
              // Set the HTTPS proxy.
              // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
              Endpoint: tea.String(endpoint),
          }
          // Note: To improve performance, reuse the instantiated client to avoid repeatedly establishing connections.
          return green20220302.NewClient(config);
      }
      
      // Creates a client for file uploads.
      func createOssClient(tokenData *green20220302.DescribeUploadTokenResponseBodyData) {
          if isVPC{
              ossClient, err := oss.New(tea.StringValue(tokenData.OssInternalEndPoint), tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken)))
              if err != nil {
                  fmt.Println("Error:", err)
                  os.Exit(-1)
              }
              Bucket, _ =ossClient.Bucket(tea.StringValue(tokenData.BucketName));
          }else {
              ossClient, err := oss.New(tea.StringValue(tokenData.OssInternetEndPoint), tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken)))
              if err != nil {
                  fmt.Println("Error:", err)
                  os.Exit(-1)
              }
              Bucket, _ =ossClient.Bucket(tea.StringValue(tokenData.BucketName));
          }
      }
      
      // Uploads a file.
      func uploadFile(filePath string,tokenData *green20220302.DescribeUploadTokenResponseBodyData) (string,error) {
          createOssClient(tokenData)
          objectName := tea.StringValue(tokenData.FileNamePrefix) + uuid.New().String() + "." + strings.Split(filePath, ".")[1]
              // Uploads the file.
              _err := Bucket.PutObjectFromFile(objectName, filePath)
              if _err != nil {
                  fmt.Println("Error:", _err)
                  os.Exit(-1)
              }
          return objectName,_err
      }
      
      func invoke(accessKeyId string, accessKeySecret string, endpoint string) (_result *green20220302.VideoModerationResponse, _err error) {
          // Note: To improve performance, reuse the instantiated client to avoid repeatedly establishing connections.
          client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
          if _err != nil {
              return nil,_err
          }
          // Set runtime options, which apply only to requests made with this runtime instance.
          runtime := &util.RuntimeOptions{}
          // The full path to the local file. Example: /path/to/your/video.mp4.
          var filePath = "/path/to/your/video.mp4"
          // Get a temporary token for file upload.
              tokenData,ok:=TokenMap[endpoint];
              if !ok || tea.Int32Value(tokenData.Expiration) <= int32(time.Now().Unix()) {
                  // Get a temporary token for file upload.
                  uploadTokenResponse, _err := client.DescribeUploadToken()
                  if _err != nil {
                      return nil,_err
                  }
                  tokenData = uploadTokenResponse.Body.Data
                  TokenMap[endpoint] = tokenData
              }
               var objectName, _ = uploadFile(filePath,TokenMap[endpoint])
      
          // Build the moderation request.
              serviceParameters, _ := json.Marshal(
                  map[string]interface{}{
                      "ossBucketName": tea.StringValue(TokenMap[endpoint].BucketName),
                      "ossObjectName": objectName,
                      "dataId":   uuid.New().String(),
                  },
              )
              videoModerationRequest := &green20220302.VideoModerationRequest{
                  // Example: videoDetection
            Service:           tea.String("videoDetection"),
                  ServiceParameters: tea.String(string(serviceParameters)),
              }
      
          return client.VideoModerationWithOptions(videoModerationRequest, runtime)
      
      }
      
      func main() {
          // An AccessKey pair from an Alibaba Cloud account has permissions for all API operations. For better security, we recommend using a RAM user for API access and routine O&M.
          // Do not hardcode your AccessKey ID or AccessKey Secret. This practice can lead to credential leaks and compromise the security of your account resources.
          // Instead, store credentials in environment variables.
          // Obtain the AccessKey ID of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
          // Obtain the AccessKey secret of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
          var accessKeyId= os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
          var accessKeySecret= os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
          // Modify the region and endpoint based on your actual requirements.
          var endpoint = "green-cip.cn-shanghai.aliyuncs.com";
          response,_err := invoke(accessKeyId,accessKeySecret,endpoint)
          
          flag := false
          if _err != nil {
              var err = &tea.SDKError{}
              if _t, ok := _err.(*tea.SDKError); ok {
                  err = _t
                  if *err.StatusCode == 500 {
                      flag = true
                  }
              }
          }
          if response == nil || *response.StatusCode == 500 || *response.Body.Code == 500 {
              flag = true
          }
          // Automatic failover. If the request fails, the region is switched to China (Beijing).
          if flag {
              endpoint = "green-cip.cn-beijing.aliyuncs.com";
              response, _err = invoke(accessKeyId,accessKeySecret,endpoint)
          }
      
          if response != nil {
              statusCode := tea.IntValue(tea.ToInt(response.StatusCode))
              body := response.Body
              videoModerationResponseData := body.Data
              fmt.Println("requestId:" + tea.StringValue(body.RequestId))
              if statusCode == http.StatusOK {
                  fmt.Println("Request successful. response:" + body.String())
                  if tea.IntValue(tea.ToInt(body.Code)) == 200 {
                      result := videoModerationResponseData.Result
                      fmt.Println("response dataId:" + tea.StringValue(videoModerationResponseData.DataId))
                      for i := 0; i < len(result); i++ {
                          fmt.Println("response label:" + tea.StringValue(result[i].Label))
                          fmt.Println("response confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence)))
                      }
                  } else {
                      fmt.Println("Video moderation failed. status" + tea.ToString(body.Code))
                  }
              } else {
                  fmt.Print("Request failed. status:" + tea.ToString(statusCode))
              }
          }
      }
    • Retrieve the results of a video moderation task

      package main
      
      import (
      	"encoding/json"
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
      	util "github.com/alibabacloud-go/tea-utils/v2/service"
      	"github.com/alibabacloud-go/tea/tea"
      	"net/http"
          "os"
      )
      
      func main() {
      	// For enhanced security, we recommend using a method such as STS and avoiding hardcoding your credentials.
          config := &openapi.Config{
              // An AccessKey pair from an Alibaba Cloud account has permissions for all API operations. For better security, we recommend using a RAM user for API access and routine O&M.
              // Do not hardcode your AccessKey ID or AccessKey Secret. This practice can lead to credential leaks and compromise the security of your account resources.
              // Instead, store credentials in environment variables.
              // Obtain the AccessKey ID of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
              // Obtain the AccessKey secret of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
              AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
              AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
              // Set the HTTP proxy.
              // HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"),
              // Set the HTTPS proxy.
              // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
              RegionId: tea.String("cn-shanghai"),
              Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"),
              // The server-side timeout for this operation is 10 seconds. Ensure your client-side timeout is set appropriately.
      		// If your `ReadTimeout` is shorter than the server's processing time, a `ReadTimeout` exception will occur.
              ConnectTimeout: tea.Int(3000),
              ReadTimeout:    tea.Int(6000),
          }
      	client, _err := green20220302.NewClient(config)
      	if _err != nil {
      		panic(_err)
      	}
      
      	// Create a RuntimeOptions instance and set runtime parameters.
      	runtime := &util.RuntimeOptions{}
      	runtime.ReadTimeout = tea.Int(10000)
      	runtime.ConnectTimeout = tea.Int(10000)
      
      	serviceParameters, _ := json.Marshal(
      		map[string]interface{}{
      			"taskId": "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****",
      		},
      	)
      	request := green20220302.VideoModerationResultRequest{
      		Service:           tea.String("videoDetection"),
      		ServiceParameters: tea.String(string(serviceParameters)),
      	}
      
      	result, _err := client.VideoModerationResultWithOptions(&request, runtime)
      	if _err != nil {
      		panic(_err)
      	}
      
      	if *result.StatusCode != http.StatusOK {
      		fmt.Printf("Request failed. status:%d\n", *result.StatusCode)
      		return
      	}
      	body := result.Body
      	fmt.Printf("Request successful. requestId:%s, code:%d, msg:%s\n", *body.RequestId, *body.Code, *body.Message)
      	if *body.Code == 280 {
      		fmt.Printf("The video moderation task is being processed. code:%d\n", *body.Code)
      		return
      	}
      	if *body.Code != http.StatusOK {
      		fmt.Printf("Failed to get video moderation result. code:%d\n", *body.Code)
      		return
      	}
      
      	data := body.Data
          fmt.Printf("Video moderation result:%+v\n", data)
      	fmt.Printf("Video moderation audio result:%+v\n", data.AudioResult)
      	fmt.Printf("Video moderation frame result:%+v\n", data.FrameResult)
      }
    • Sample code for canceling a live video stream moderation task

      package main
      
      import (
          "encoding/json"
          "fmt"
          openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
          green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
          util "github.com/alibabacloud-go/tea-utils/v2/service"
          "github.com/alibabacloud-go/tea/tea"
          "net/http"
          "os"
      )
      
      func main() {
      	// For enhanced security, we recommend using a method such as STS and avoiding hardcoding your credentials.
          config := &openapi.Config{
              // An AccessKey pair from an Alibaba Cloud account has permissions for all API operations. For better security, we recommend using a RAM user for API access and routine O&M.
              // Do not hardcode your AccessKey ID or AccessKey Secret. This practice can lead to credential leaks and compromise the security of your account resources.
              // Instead, store credentials in environment variables.
              // Obtain the AccessKey ID of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
              // Obtain the AccessKey secret of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
              AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
              AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
              // Set the HTTP proxy.
              // HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"),
              // Set the HTTPS proxy.
              // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
              RegionId: tea.String("cn-shanghai"),
              Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"),
              // The server-side timeout for this operation is 10 seconds. Ensure your client-side timeout is set appropriately.
      		// If your `ReadTimeout` is shorter than the server's processing time, a `ReadTimeout` exception will occur.
              ConnectTimeout: tea.Int(3000),
              ReadTimeout:    tea.Int(6000),
          }
      	client, _err := green20220302.NewClient(config)
      	if _err != nil {
      		panic(_err)
      	}
      
          // Create a RuntimeOptions instance and set runtime parameters.
          runtime := &util.RuntimeOptions{}
          runtime.ReadTimeout = tea.Int(10000)
          runtime.ConnectTimeout = tea.Int(10000)
      
          serviceParameters, _ := json.Marshal(
              map[string]interface{}{
                  "taskId": "vi_s_lyxBXzWhSsxuJjiNHcpQ0N-*****",
              },
          )
          request := green20220302.VideoModerationCancelRequest{
              Service:           tea.String("videoDetection"),
              ServiceParameters: tea.String(string(serviceParameters)),
          }
      
          result, _err := client.VideoModerationCancelWithOptions(&request, runtime)
          if _err != nil {
              panic(_err)
          }
      
          if *result.StatusCode != http.StatusOK {
              fmt.Printf("Request failed. status:%d\n", *result.StatusCode)
              return
          }
          body := result.Body
          fmt.Printf("Request successful. requestId:%s, code:%d, msg:%s\n", *body.RequestId, *body.Code, *body.Message)
          if *body.Code != http.StatusOK {
              fmt.Printf("Failed to cancel video moderation task. code:%d\n", *body.Code)
          }
      }

Moderate OSS videos

Scenarios

If your video files for moderation are stored in Alibaba Cloud Object Storage Service (OSS), you can create a service role to grant the Content Moderation service access to your OSS resources. The video moderation Enhanced service uses this service role to retrieve files from OSS and moderate them. Visit the Cloud Resource Access Authorization page to create a service role.

  1. Run the following command to import the required dependency.

    go get github.com/alibabacloud-go/green-20220302/v3@v3.2.4
  2. Integrate the Go SDK.

    • Submit a video moderation task

      package main
      
      import (
          "encoding/json"
          "fmt"
          openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
          green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
          util "github.com/alibabacloud-go/tea-utils/v2/service"
          "github.com/alibabacloud-go/tea/tea"
          "net/http"
      )
      
      func main() {
          // Storing AccessKeys in your project code may lead to security risks. We recommend that you use a more secure method, such as STS, for authentication. The following code is for reference only.
          config := &openapi.Config{
              /**
               * The AccessKey of an Alibaba Cloud account has permissions to all APIs. We recommend that you use a RAM user for API access and routine O&M.
               * We strongly recommend that you do not hardcode your AccessKey ID and AccessKey Secret in your project code. This can expose your credentials and compromise all resources in your account.
               * Common methods for obtaining environment variables:
               * Obtain the AccessKey ID of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
               * Obtain the AccessKey Secret of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
               */
              AccessKeyId: tea.String(""),
    • Retrieve video moderation results

      package main
      
      import (
      	"encoding/json"
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
      	util "github.com/alibabacloud-go/tea-utils/v2/service"
      	"github.com/alibabacloud-go/tea/tea"
      	"net/http"
      )
      
      func main() {
      	// Storing AccessKeys in your project code may lead to security risks. We recommend that you use a more secure method, such as STS, for authentication. The following code is for reference only.
          config := &openapi.Config{
              /**
               * The AccessKey of an Alibaba Cloud account has permissions to all APIs. We recommend that you use a RAM user for API access and routine O&M.
               * We strongly recommend that you do not hardcode your AccessKey ID and AccessKey Secret in your project code. This can expose your credentials and compromise all resources in your account.
               * Common methods for obtaining environment variables:
               * Obtain the AccessKey ID of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
               * Obtain the AccessKey Secret of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
               */
              AccessKeyId: tea.String(""),
    • Cancel a video moderation task

      package main
      
      import (
          "encoding/json"
          "fmt"
          openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
          green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
          util "github.com/alibabacloud-go/tea-utils/v2/service"
          "github.com/alibabacloud-go/tea/tea"
          "net/http"
      )
      
      func main() {
      	// Storing AccessKeys in your project code may lead to security risks. We recommend that you use a more secure method, such as STS, for authentication. The following code is for reference only.
          config := &openapi.Config{
              /**
               * The AccessKey of an Alibaba Cloud account has permissions to all APIs. We recommend that you use a RAM user for API access and routine O&M.
               * We strongly recommend that you do not hardcode your AccessKey ID and AccessKey Secret in your project code. This can expose your credentials and compromise all resources in your account.
               * Common methods for obtaining environment variables:
               * Obtain the AccessKey ID of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
               * Obtain the AccessKey Secret of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
               */
              AccessKeyId: tea.String(""),

C# SDK

See the SDK source code.

The following three types of video detection are supported.

Moderate publicly accessible videos

Scenario

If a video is accessible over the public network, the video moderation Enhanced service fetches the file from its URL to moderate it.

  1. Run the following command to install the required dependency.

    dotnet add package AlibabaCloud.SDK.Green20220302 --version 3.2.4
  2. Integrate the C# SDK.

    • Code example for submitting a video moderation task

      using System;
      using System.Collections.Generic;
      using Newtonsoft.Json;
      using Tea;
      
      namespace AlibabaCloud.SDK.Sample
      {
          public class Sample
          {
              /**
               * Initialize the client with an AccessKey pair.
               * @param accessKeyId
               * @param accessKeySecret
               * @return Client
               * @throws Exception
               */
              public static AlibabaCloud.SDK.Green20220302.Client CreateClient(string accessKeyId, string accessKeySecret)
              {
                  AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
                  {
                      AccessKeyId = accessKeyId,
                      AccessKeySecret = accessKeySecret,
                  };
                  // The endpoint of the service.
                  config.Endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  return new AlibabaCloud.SDK.Green20220302.Client(config);
              }
      
              public static void Main(string[] args)
              {
                  // For security reasons, do not hard-code your AccessKey pair in the code.
                  // We recommend that you use a more secure method, such as Security Token Service (STS), or load credentials from environment variables.
                  /**
                  * An AccessKey pair for an Alibaba Cloud account has permissions on all APIs. We recommend that you use a RAM user for API access or daily O&M.
                  * We strongly recommend that you do not store an AccessKey ID and an AccessKey secret in your code. Otherwise, the AccessKey pair may be compromised, which threatens the security of all your resources.
                  * A common practice is to read credentials from environment variables:
                  * Get the AccessKey ID of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
                  string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
                  
                  // Note: To improve performance, reuse the client instance to avoid establishing a new connection for each request.
                  AlibabaCloud.SDK.Green20220302.Client client = CreateClient(accessKeyId, accessKeySecret);
                  // Build the moderation request.
                  AlibabaCloud.SDK.Green20220302.Models.VideoModerationRequest videoModerationRequest = new AlibabaCloud.SDK.Green20220302.Models.VideoModerationRequest();
                  // The moderation service to use.
                  videoModerationRequest.Service = "videoDetection";
                  Dictionary<string, object> serviceParameters = new Dictionary<string, object>();
                  // The URL of the video to be moderated. The URL must be publicly accessible.
                  serviceParameters.Add("url", "https://your-video-url.mp4");
                  videoModerationRequest.ServiceParameters = JsonConvert.SerializeObject(serviceParameters);
                  // Create a RuntimeOptions instance and set runtime parameters.
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
                  runtime.ReadTimeout = 10000;
                  runtime.ConnectTimeout = 10000;
                  try
                  {
                      // Submit the moderation task.
                      AlibabaCloud.SDK.Green20220302.Models.VideoModerationResponse response = client.VideoModerationWithOptions(videoModerationRequest, runtime);
                      if (response != null)
                      {
                          Console.WriteLine("Response StatusCode: " + response.StatusCode);
                          if (response.Body != null)
                          {
                              Console.WriteLine("RequestId: " + response.Body.RequestId);
                              Console.WriteLine("Code: " + response.Body.Code);
                              Console.WriteLine("Message: " + response.Body.Message);
                              if (response.Body.Data != null)
                              {
                                  Console.WriteLine("TaskId: " + response.Body.Data.TaskId);
                              }
                          }
                      }
                  }
                  catch (TeaException error)
                  {
                      // If an error occurs, print the error details.
                      AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
                      Console.WriteLine("Error: " + error);
                  }
                  catch (Exception _error)
                  {
                      TeaException error = new TeaException(new Dictionary<string, object>
                      {
                          { "message", _error.Message }
                      });
                      // If an error occurs, print the error details.
                      AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
                      Console.WriteLine("Error: " + error);
                  }
              }
          }
      }
    • Code example for querying the results of a video moderation task

      using System;
      using System.Collections.Generic;
      using Newtonsoft.Json;
      using Tea;
      
      namespace AlibabaCloud.SDK.Sample
      {
          public class Sample
          {
              /**
               * Initialize the client with an AccessKey pair.
               * @param accessKeyId
               * @param accessKeySecret
               * @return Client
               * @throws Exception
               */
              public static AlibabaCloud.SDK.Green20220302.Client CreateClient(string accessKeyId, string accessKeySecret)
              {
                  AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
                  {
                      AccessKeyId = accessKeyId,
                      AccessKeySecret = accessKeySecret,
                  };
                  // The endpoint of the service.
                  config.Endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  return new AlibabaCloud.SDK.Green20220302.Client(config);
              }
      
              public static void Main(string[] args)
              {
                  // For security reasons, do not hard-code your AccessKey pair in the code.
                  // We recommend that you use a more secure method, such as Security Token Service (STS), or load credentials from environment variables.
                  /**
                  * An AccessKey pair for an Alibaba Cloud account has permissions on all APIs. We recommend that you use a RAM user for API access or daily O&M.
                  * We strongly recommend that you do not store an AccessKey ID and an AccessKey secret in your code. Otherwise, the AccessKey pair may be compromised, which threatens the security of all your resources.
                  * A common practice is to read credentials from environment variables:
                  * Get the AccessKey ID of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
                  string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
                  
                  // Note: To improve performance, reuse the client instance to avoid establishing a new connection for each request.
                  AlibabaCloud.SDK.Green20220302.Client client = CreateClient(accessKeyId, accessKeySecret);
                  // Build the moderation request.
                  AlibabaCloud.SDK.Green20220302.Models.VideoModerationResultRequest videoModerationResultRequest = new AlibabaCloud.SDK.Green20220302.Models.VideoModerationResultRequest();
                  // The moderation service to use.
                  videoModerationResultRequest.Service = "videoDetection";
                  Dictionary<string, object> serviceParameters = new Dictionary<string, object>();
                  // The ID of the task to query.
                  serviceParameters.Add("taskId", "");
                  videoModerationResultRequest.ServiceParameters = JsonConvert.SerializeObject(serviceParameters);
                  // Create a RuntimeOptions instance and set runtime parameters.
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
                  runtime.ReadTimeout = 10000;
                  runtime.ConnectTimeout = 10000;
                  try
                  {
                      // Submit the query request.
                      AlibabaCloud.SDK.Green20220302.Models.VideoModerationResultResponse response = client.VideoModerationResultWithOptions(videoModerationResultRequest, runtime);
                      if (response != null)
                      {
                          Console.WriteLine("Response StatusCode: " + response.StatusCode);
                          if (response.Body != null)
                          {
                              Console.WriteLine("RequestId: " + response.Body.RequestId);
                              Console.WriteLine("Code: " + response.Body.Code);
                              Console.WriteLine("Message: " + response.Body.Message);
                              if (response.Body.Data != null)
                              {
                                  Console.WriteLine("TaskId: " + response.Body.Data.TaskId);
                                  Console.WriteLine("RiskLevel: " + response.Body.Data.RiskLevel);
                                  Console.WriteLine("LiveId: " + response.Body.Data.LiveId);
                                  Console.WriteLine("Url: " + response.Body.Data.Url);
                                  Console.WriteLine("SliceDetails: " + JsonConvert.SerializeObject(response.Body.Data.SliceDetails));
                              }
                          }
                      }
                  }
                  catch (TeaException error)
                  {
                      // If an error occurs, print the error details.
                      AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
                      Console.WriteLine("Error: " + error);
                  }
                  catch (Exception _error)
                  {
                      TeaException error = new TeaException(new Dictionary<string, object>
                      {
                          { "message", _error.Message }
                      });
                      // If an error occurs, print the error details.
                      AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
                      Console.WriteLine("Error: " + error);
                  }
              }
          }
      }
    • Code example for canceling a video moderation task

      using System;
      using System.Collections.Generic;
      using Tea;
      using Newtonsoft.Json;
      
      namespace AlibabaCloud.SDK.Sample
      {
          public class Sample
          {
              /**
               * Initialize the client with an AccessKey pair.
               * @param accessKeyId
               * @param accessKeySecret
               * @return Client
               * @throws Exception
               */
              public static AlibabaCloud.SDK.Green20220302.Client CreateClient(string accessKeyId, string accessKeySecret)
              {
                  AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
                  {
                      AccessKeyId = accessKeyId,
                      AccessKeySecret = accessKeySecret,
                  };
                  // The endpoint of the service.
                  config.Endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  return new AlibabaCloud.SDK.Green20220302.Client(config);
              }
      
              public static void Main(string[] args)
              {
                  // For security reasons, do not hard-code your AccessKey pair in your code.
                  // We recommend that you use a more secure method, such as Security Token Service (STS), or load credentials from environment variables.
                  /**
                  * An AccessKey pair for an Alibaba Cloud account has permissions on all APIs. We recommend that you use a RAM user for API access or daily O&M.
                  * We strongly recommend that you do not store an AccessKey ID and an AccessKey secret in your code. Otherwise, the AccessKey pair may be compromised, which threatens the security of all your resources.
                  * A common practice is to read credentials from environment variables:
                  * Get the AccessKey ID of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
                  string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
                  
                  // Note: To improve performance, reuse the client instance to avoid establishing a new connection for each request.
                  AlibabaCloud.SDK.Green20220302.Client client = CreateClient(accessKeyId, accessKeySecret);
                  // Build the request to cancel the video moderation task.
                  AlibabaCloud.SDK.Green20220302.Models.VideoModerationCancelRequest videoModerationCancelRequest = new AlibabaCloud.SDK.Green20220302.Models.VideoModerationCancelRequest();
                  // The moderation service to use.
                  videoModerationCancelRequest.Service = "videoDetection";
                  Dictionary<string, object> serviceParameters = new Dictionary<string, object>();
                  // The ID of the video moderation task to cancel.
                  serviceParameters.Add("taskId", "");
                  videoModerationCancelRequest.ServiceParameters = JsonConvert.SerializeObject(serviceParameters);
                  // Create a RuntimeOptions instance and set runtime parameters.
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
                  runtime.ReadTimeout = 10000;
                  runtime.ConnectTimeout = 10000;
                  try
                  {
                      // Submit the cancellation request.
                      AlibabaCloud.SDK.Green20220302.Models.VideoModerationCancelResponse response = client.VideoModerationCancelWithOptions(videoModerationCancelRequest, runtime);
                      if (response != null)
                      {
                          Console.WriteLine("Response StatusCode: " + response.StatusCode);
                          if (response.Body != null)
                          {
                              Console.WriteLine("RequestId: " + response.Body.RequestId);
                              Console.WriteLine("Code: " + response.Body.Code);
                              Console.WriteLine("Message: " + response.Body.Message);
                          }
                      }
                  }
                  catch (TeaException error)
                  {
                      // If an error occurs, print the error details.
                      AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
                      Console.WriteLine("Error: " + error);
                  }
                  catch (Exception _error)
                  {
                      TeaException error = new TeaException(new Dictionary<string, object>
                      {
                          { "message", _error.Message }
                      });
                      // If an error occurs, print the error details.
                      AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
                      Console.WriteLine("Error: " + error);
                  }
              }
          }
      }

Moderate a local video

Scenarios

If a video is on your local machine and lacks a public URL, upload it to an Object Storage Service (OSS) bucket provided by Content Moderation. The Video Moderation Enhanced Edition service can then directly access OSS to retrieve the video for moderation.

  1. Run the following command to add the required dependency.

    dotnet add package AlibabaCloud.SDK.Green20220302 --version 3.2.4

    Install the OSS SDK:

    Install using NuGet 
    1. If NuGet is not installed in your Visual Studio, install NuGet first.
    2. In Visual Studio, create a project or open an existing one, and then choose Tools > NuGet Package Manager > Manage NuGet Packages for Solution.
    3. Search for aliyun.oss.sdk. In the search results, find Aliyun.OSS.SDK (for .NET Framework) or Aliyun.OSS.SDK.NetCore.
  2. Integrate the C# SDK.

    • Submit a video moderation task

      // This file is auto-generated, don't edit it. Thanks.
      
      using System;
      using Newtonsoft.Json;
      using Aliyun.OSS;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class VideoModerationAutoRoute
          {
              // The token for file uploads.
              public static Dictionary<String, Models.DescribeUploadTokenResponse> tokenDic =
                  new Dictionary<String, Models.DescribeUploadTokenResponse>();
      
              // The client for file uploads.
              public static OssClient ossClient = null;
      
              // Specifies whether the service is deployed in a VPC.
              public static Boolean isVPC = false;
      
              public static void Main(string[] args)
              {
                  /**
                  * An AccessKey pair grants full permissions to your Alibaba Cloud account. We recommend using a RAM user for API access and routine O&M.
                  * We strongly recommend that you do not save the AccessKey ID and AccessKey Secret in your code. This can lead to credential leaks and compromise your account security.
                  * A common practice is to read credentials from environment variables:
                  * To retrieve the AccessKey ID of the RAM user, call Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID").
                  * To retrieve the AccessKey secret of the RAM user, call Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET").
                  */
                  String accessKeyId = "We recommend that you retrieve the AccessKey ID from an environment variable.";
                  String accessKeySecret = "We recommend that you retrieve the AccessKey secret from an environment variable.";
                  // Modify the region and endpoint based on your actual requirements.
                  String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  Models.VideoModerationResponse response = invoke(
                      accessKeyId,
                      accessKeySecret,
                      endpoint
                  );
                  // Automatic routing. Switches to the China (Beijing) region.
                  if (
                      response is null
                      || response.Body is null
                      || AlibabaCloud.TeaUtil.Common.EqualNumber(
                          500,
                          AlibabaCloud.TeaUtil.Common.AssertAsNumber(response.StatusCode)
                      )
                      || AlibabaCloud.TeaUtil.Common.EqualString(
                          "500",
                          Convert.ToString(response.Body.Code)
                      )
                  )
                  {
                      endpoint = "green-cip.cn-beijing.aliyuncs.com";
                      response = invoke(accessKeyId, accessKeySecret, endpoint);
                      ;
                  }
      
                  Console.WriteLine(response.Body.RequestId);
                  Console.WriteLine(JsonConvert.SerializeObject(response.Body));
              }
      
              // Creates a client.
              public static Client createClient(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  AlibabaCloud.OpenApiClient.Models.Config config =
                      new AlibabaCloud.OpenApiClient.Models.Config
                      {
                          AccessKeyId = accessKeyId,
                          AccessKeySecret = accessKeySecret,
                          // Specify an HTTP proxy.
                          //HttpProxy = "http://10.10.xx.xx:xxxx",
                          // Specify an HTTPS proxy.
                          //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          // The endpoint of the service.
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
      
              // Creates a client for file uploads.
              private static OssClient getOssClient(
                  Models.DescribeUploadTokenResponse tokenResponse,
                  Boolean isVPC
              )
              {
                  var tokenData = tokenResponse.Body.Data;
                  if (isVPC)
                  {
                      return new OssClient(
                          tokenData.OssInternalEndPoint,
                          tokenData.AccessKeyId,
                          tokenData.AccessKeySecret,
                          tokenData.SecurityToken
                      );
                  }
                  else
                  {
                      return new OssClient(
                          tokenData.OssInternetEndPoint,
                          tokenData.AccessKeyId,
                          tokenData.AccessKeySecret,
                          tokenData.SecurityToken
                      );
                  }
              }
      
              // Uploads a file.
              public static String uploadFile(
                  String filePath,
                  Models.DescribeUploadTokenResponse tokenResponse
              )
              {
                  // Create an OssClient instance.
                  ossClient = getOssClient(tokenResponse, isVPC);
                  var tokenData = tokenResponse.Body.Data;
      
                  String objectName =
                      tokenData.FileNamePrefix
                      + Guid.NewGuid().ToString()
                      + "."
                      + filePath.Split(".").GetValue(1);
                  // Upload the file.
                  ossClient.PutObject(tokenData.BucketName, objectName, filePath);
                  return objectName;
              }
      
              // Submits a moderation request.
              public static Models.VideoModerationResponse invoke(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  // Note: To improve performance, reuse the client instance to avoid establishing a new connection for each request.
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  // Set runtime options. The settings are valid only for requests that use this RuntimeOptions instance.
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
                  // The full path of the local file. Example: D:\\localPath\\exampleFile.mp4.
                  String filePath = "D:\\localPath\\exampleFile.mp4";
                  try
                  {
                      // Obtain a temporary token for file uploads.
                      if (
                          !tokenDic.ContainsKey(endpoint)
                          || tokenDic[endpoint].Body.Data.Expiration
                              <= DateTimeOffset.Now.ToUnixTimeSeconds()
                      )
                      {
                          var tokenResponse = client.DescribeUploadToken();
                          tokenDic[endpoint] = tokenResponse;
                      }
                      // Upload the file.
                      String objectName = uploadFile(filePath, tokenDic[endpoint]);
                      // Construct a moderation request.
                      Models.VideoModerationRequest videoModerationRequest =
                          new Models.VideoModerationRequest();
                      // The service. Example: videoDetection.
                        videoModerationRequest.Service = "videoDetection";
                      Dictionary<string, object> task = new Dictionary<string, object>();
                      // The file to be moderated.
                      task.Add("ossBucketName", tokenDic[endpoint].Body.Data.BucketName);
                      task.Add("ossObjectName", objectName);
                      // The data ID.
                      task.Add("dataId", Guid.NewGuid().ToString());
                      videoModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
                      // Call the API to get the moderation results.
                      Models.VideoModerationResponse response = client.VideoModerationWithOptions(
                          videoModerationRequest,
                          runtimeOptions
                      );
                      return response;
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                      return null;
                  }
              }
          }
      }
    • Retrieve the result of a video moderation task

      using Newtonsoft.Json;
      using Tea;
      
      namespace AlibabaCloud.SDK.Sample
      {
          public class Sample
          {
      
              /**
               * Use an AccessKey pair to initialize a client.
               * @param accessKeyId
               * @param accessKeySecret
               * @return Client
               * @throws Exception
               */
              public static AlibabaCloud.SDK.Green20220302.Client CreateClient(string accessKeyId, string accessKeySecret)
              {
                  AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
                  {
                      AccessKeyId = accessKeyId,
                      AccessKeySecret = accessKeySecret,
                  };
                  // The endpoint of the service.
                  config.Endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  return new AlibabaCloud.SDK.Green20220302.Client(config);
              }
      
              public static void Main(string[] args)
              {
                  // We recommend using a more secure method, such as STS credentials. If you use an AccessKey pair to call API operations, your AccessKey pair may be leaked.
                  /**
                  * An AccessKey pair grants full permissions to your Alibaba Cloud account. We recommend using a RAM user for API access and routine O&M.
                  * We strongly recommend that you do not save the AccessKey ID and AccessKey Secret in your code. This can lead to credential leaks and compromise your account security.
                  * A common practice is to read credentials from environment variables:
                  * To retrieve the AccessKey ID of the RAM user, call Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID").
                  * To retrieve the AccessKey secret of the RAM user, call Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET").
                  */
                  string accessKeyId = "We recommend that you retrieve the AccessKey ID from an environment variable.";
                  string accessKeySecret = "We recommend that you retrieve the AccessKey secret from an environment variable.";
                  // Note: To improve performance, reuse the client instance to avoid establishing a new connection for each request.
                  AlibabaCloud.SDK.Green20220302.Client client = CreateClient(accessKeyId, accessKeySecret);
                  // Construct a moderation request.
                  AlibabaCloud.SDK.Green20220302.Models.VideoModerationResultRequest videoModerationResultRequest = new AlibabaCloud.SDK.Green20220302.Models.VideoModerationResultRequest();
                  // The moderation service.
                  videoModerationResultRequest.Service="videoDetection";
                  Dictionary<String,Object> task=new Dictionary<string, object>();
                  // The ID of the task to query.
                  task.Add("taskId","");
                  videoModerationResultRequest.ServiceParameters=JsonConvert.SerializeObject(task);
                  // Create a RuntimeOptions instance and set runtime parameters.
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
                  runtime.ReadTimeout = 10000;
                  runtime.ConnectTimeout = 10000;
                  try
                  {
                      // Retrieve the moderation results.
                    AlibabaCloud.SDK.Green20220302.Models.VideoModerationResultResponse response= client.VideoModerationResultWithOptions(videoModerationResultRequest, runtime);
                  if(response is not null){
                      Console.WriteLine("response statusCode : "+response.StatusCode);
                      if (response.Body is not null){
                      Console.WriteLine("requestId : " + response.Body.RequestId);
                      Console.WriteLine("code : " + response.Body.Code);
                      Console.WriteLine("message : " + response.Body.Message);
                          if(response.Body.Data is not null){
                              Console.WriteLine("taskId : " + response.Body.Data.TaskId);
                              Console.WriteLine("riskLevel : " + response.Body.Data.RiskLevel);
                              Console.WriteLine("liveId : " + response.Body.Data.LiveId);
                              Console.WriteLine("url : " + response.Body.Data.Url);
                              Console.WriteLine("sliceDetails : " + JsonConvert.SerializeObject(response.Body.Data.SliceDetails));
                          }
                      }
                  }
                  }
                  catch (TeaException error)
                  {
                      // Print the error if required.
                      AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
                      Console.WriteLine("error : " + error);
                  }
                  catch (Exception _error)
                  {
                      TeaException error = new TeaException(new Dictionary<string, object>
                      {
                          { "message", _error.Message }
                      });
                      // Print the error if required.
                      AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
                      Console.WriteLine("error : " + error);
                  }
              }
          }
      }
    • Cancel a live stream moderation task

      using Tea;
      using Newtonsoft.Json;
      
      namespace AlibabaCloud.SDK.Sample
      {
          public class Sample
          {
      
              /**
               * Use an AccessKey pair to initialize a client.
               * @param accessKeyId
               * @param accessKeySecret
               * @return Client
               * @throws Exception
               */
              public static AlibabaCloud.SDK.Green20220302.Client CreateClient(string accessKeyId, string accessKeySecret)
              {
                  AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
                  {
                      AccessKeyId = accessKeyId,
                      AccessKeySecret = accessKeySecret,
                  };
                  // The endpoint of the service.
                  config.Endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  return new AlibabaCloud.SDK.Green20220302.Client(config);
              }
      
              public static void Main(string[] args)
              {
                  // We recommend using a more secure method, such as STS credentials. If you use an AccessKey pair to call API operations, your AccessKey pair may be leaked.
                  /**
                  * An AccessKey pair grants full permissions to your Alibaba Cloud account. We recommend using a RAM user for API access and routine O&M.
                  * We strongly recommend that you do not save the AccessKey ID and AccessKey Secret in your code. This can lead to credential leaks and compromise your account security.
                  * A common practice is to read credentials from environment variables:
                  * To retrieve the AccessKey ID of the RAM user, call Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID").
                  * To retrieve the AccessKey secret of the RAM user, call Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET").
                  */
                  string accessKeyId = "We recommend that you retrieve the AccessKey ID from an environment variable.";
                  string accessKeySecret = "We recommend that you retrieve the AccessKey secret from an environment variable.";
                    // Note: To improve performance, reuse the client instance to avoid establishing a new connection for each request.
                  AlibabaCloud.SDK.Green20220302.Client client = CreateClient(accessKeyId, accessKeySecret);
                  // Construct a request to cancel the live stream moderation task.
                  AlibabaCloud.SDK.Green20220302.Models.VideoModerationCancelRequest videoModerationCancelRequest = new AlibabaCloud.SDK.Green20220302.Models.VideoModerationCancelRequest();
                  // The moderation service.
                  videoModerationCancelRequest.Service="videoDetection";
                  Dictionary<String,Object> task=new Dictionary<string, object>();
                  // The ID of the task to cancel.
                  task.Add("taskId","");
                  videoModerationCancelRequest.ServiceParameters=JsonConvert.SerializeObject(task);
                  // Create a RuntimeOptions instance and set runtime parameters.
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
                  runtime.ReadTimeout = 10000;
                  runtime.ConnectTimeout = 10000;
                  try
                  {
                      // Cancel the moderation task.
                      AlibabaCloud.SDK.Green20220302.Models.VideoModerationCancelResponse response = client.VideoModerationCancelWithOptions(videoModerationCancelRequest, runtime);
                      if(response is not null){
                      Console.WriteLine("response statusCode : "+response.StatusCode);
                          if (response.Body is not null){
                          Console.WriteLine("requestId : " + response.Body.RequestId);
                          Console.WriteLine("code : " + response.Body.Code);
                          Console.WriteLine("message : " + response.Body.Message);
                          }
                      }
                  }
                  catch (TeaException error)
                  {
                      // Print the error if required.
                      AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
                      Console.WriteLine("error : " + error);
                  }
                  catch (Exception _error)
                  {
                      TeaException error = new TeaException(new Dictionary<string, object>
                      {
                          { "message", _error.Message }
                      });
                      // Print the error if required.
                      AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
                      Console.WriteLine("error : " + error);
                  }
              }
          }
      }

Moderate videos in OSS

Use cases

To moderate a video file stored in Alibaba Cloud Object Storage Service (OSS), create a service role that grants the Content Moderation service access to OSS. The Video Moderation Enhanced Edition service uses this role to retrieve and moderate the file. You can create the service role on the Cloud Resource Access Authorization page.

  1. Run the following command to import the required dependency.

    dotnet add package AlibabaCloud.SDK.Green20220302 --version 3.2.4
  2. Integrate the C# SDK.

    • Code example for submitting a video moderation task

      using System;
      using System.Collections.Generic;
      using Newtonsoft.Json;
      using Tea;
      
      namespace AlibabaCloud.SDK.Sample
      {
          public class Sample
          {
      
              /**
               * Initialize the client with an AccessKey pair.
               * @param accessKeyId
               * @param accessKeySecret
               * @return Client
               * @throws Exception
               */
              public static AlibabaCloud.SDK.Green20220302.Client CreateClient(string accessKeyId, string accessKeySecret)
              {
                  AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
                  {
                      AccessKeyId = accessKeyId,
                      AccessKeySecret = accessKeySecret,
                  };
                  // The endpoint of the service.
                  config.Endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  return new AlibabaCloud.SDK.Green20220302.Client(config);
              }
      
              public static void Main(string[] args)
              {
                  // Leaking your AccessKey pair in the project code may compromise the security of all resources in your account.
                  // The following code is for reference only. We recommend that you use a more secure method, such as Security Token Service (STS), to manage your credentials.
                  /**
                  * An AccessKey pair for an Alibaba Cloud account has permissions on all APIs. We recommend that you use a RAM user for API access or daily O&M.
                  * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code.
                  * Otherwise, your AccessKey pair may be leaked, which threatens the security of all resources in your account.
                  * A common practice is to read credentials from environment variables:
                  * Get the AccessKey ID of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
                  string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
                  // Note: To improve performance, reuse the client instance and avoid establishing a new connection for each request.
                  AlibabaCloud.SDK.Green20220302.Client client = CreateClient(accessKeyId, accessKeySecret);
                  // Build the moderation request.
                  AlibabaCloud.SDK.Green20220302.Models.VideoModerationRequest videoModerationRequest = new AlibabaCloud.SDK.Green20220302.Models.VideoModerationRequest();
                  // Specify the moderation service.
                  videoModerationRequest.Service="videoDetection";
                  Dictionary<String,Object> serviceParameters=new Dictionary<string, object>();
                  // Example of passing parameters for an OSS file.
                  serviceParameters.Add("ossBucketName","your-bucket-name");
                  serviceParameters.Add("ossObjectName","test/sample.mp4");
                  serviceParameters.Add("ossRegionId","cn-shanghai");
                  videoModerationRequest.ServiceParameters=JsonConvert.SerializeObject(serviceParameters);
                  // Create a RuntimeOptions instance and set runtime parameters.
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
                  runtime.ReadTimeout = 10000;
                  runtime.ConnectTimeout = 10000;
                  try
                  {
                      // Submit the moderation task.
                    AlibabaCloud.SDK.Green20220302.Models.VideoModerationResponse response= client.VideoModerationWithOptions(videoModerationRequest, runtime);
                  if(response is not null){
                      Console.WriteLine("response statusCode: "+response.StatusCode);
                      if (response.Body is not null){
                      Console.WriteLine("requestId: " + response.Body.RequestId);
                      Console.WriteLine("code: " + response.Body.Code);
                      Console.WriteLine("message: " + response.Body.Message);
                          if(response.Body.Data is not null){
                              Console.WriteLine("taskId: " + response.Body.Data.TaskId);
                          }
                      }
                  }
                  }
                  catch (TeaException error)
                  {
                      // If an error occurs, print the error details.
                      AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
                      Console.WriteLine("error: " + error);
                  }
                  catch (Exception _error)
                  {
                      TeaException error = new TeaException(new Dictionary<string, object>
                      {
                          { "message", _error.Message }
                      });
                      // If an error occurs, print the error details.
                      AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
                      Console.WriteLine("error: " + error);
                  }
              }
          }
      }
    • Code example for retrieving video moderation results

      using System;
      using System.Collections.Generic;
      using Newtonsoft.Json;
      using Tea;
      
      namespace AlibabaCloud.SDK.Sample
      {
          public class Sample
          {
      
              /**
               * Initialize the client with an AccessKey pair.
               * @param accessKeyId
               * @param accessKeySecret
               * @return Client
               * @throws Exception
               */
              public static AlibabaCloud.SDK.Green20220302.Client CreateClient(string accessKeyId, string accessKeySecret)
              {
                  AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
                  {
                      AccessKeyId = accessKeyId,
                      AccessKeySecret = accessKeySecret,
                  };
                  // The endpoint of the service.
                  config.Endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  return new AlibabaCloud.SDK.Green20220302.Client(config);
              }
      
              public static void Main(string[] args)
              {
                  // Leaking your AccessKey pair in the project code may compromise the security of all resources in your account.
                  // The following code is for reference only. We recommend that you use a more secure method, such as Security Token Service (STS), to manage your credentials.
                  /**
                  * An AccessKey pair for an Alibaba Cloud account has permissions on all APIs. We recommend that you use a RAM user for API access or daily O&M.
                  * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code.
                  * Otherwise, your AccessKey pair may be leaked, which threatens the security of all resources in your account.
                  * A common practice is to read credentials from environment variables:
                  * Get the AccessKey ID of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
                  string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
                  // Note: To improve performance, reuse the client instance and avoid establishing a new connection for each request.
                  AlibabaCloud.SDK.Green20220302.Client client = CreateClient(accessKeyId, accessKeySecret);
                  // Build the query request.
                  AlibabaCloud.SDK.Green20220302.Models.VideoModerationResultRequest videoModerationResultRequest = new AlibabaCloud.SDK.Green20220302.Models.VideoModerationResultRequest();
                  // Specify the moderation service.
                  videoModerationResultRequest.Service="videoDetection";
                  Dictionary<String,Object> serviceParameters=new Dictionary<string, object>();
                  // The ID of the task to query.
                  serviceParameters.Add("taskId","<your_task_id>");
                  videoModerationResultRequest.ServiceParameters=JsonConvert.SerializeObject(serviceParameters);
                  // Create a RuntimeOptions instance and set runtime parameters.
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
                  runtime.ReadTimeout = 10000;
                  runtime.ConnectTimeout = 10000;
                  try
                  {
                      // Submit the query request.
                    AlibabaCloud.SDK.Green20220302.Models.VideoModerationResultResponse response= client.VideoModerationResultWithOptions(videoModerationResultRequest, runtime);
                  if(response is not null){
                      Console.WriteLine("response statusCode: "+response.StatusCode);
                      if (response.Body is not null){
                      Console.WriteLine("requestId: " + response.Body.RequestId);
                      Console.WriteLine("code: " + response.Body.Code);
                      Console.WriteLine("message: " + response.Body.Message);
                          if(response.Body.Data is not null){
                              Console.WriteLine("taskId: " + response.Body.Data.TaskId);
                              Console.WriteLine("liveId: " + response.Body.Data.LiveId);
                              Console.WriteLine("riskLevel: " + response.Body.Data.RiskLevel);
                              Console.WriteLine("url: " + response.Body.Data.Url);
                              Console.WriteLine("sliceDetails: " + JsonConvert.SerializeObject(response.Body.Data.SliceDetails));
                          }
                      }
                  }
                  }
                  catch (TeaException error)
                  {
                      // If an error occurs, print the error details.
                      AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
                      Console.WriteLine("error: " + error);
                  }
                  catch (Exception _error)
                  {
                      TeaException error = new TeaException(new Dictionary<string, object>
                      {
                          { "message", _error.Message }
                      });
                      // If an error occurs, print the error details.
                      AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
                      Console.WriteLine("error: " + error);
                  }
              }
          }
      }
    • Code example for canceling a video moderation task

      using System;
      using System.Collections.Generic;
      using Newtonsoft.Json;
      using Tea;
      
      namespace AlibabaCloud.SDK.Sample
      {
          public class Sample
          {
      
              /**
               * Initialize the client with an AccessKey pair.
               * @param accessKeyId
               * @param accessKeySecret
               * @return Client
               * @throws Exception
               */
              public static AlibabaCloud.SDK.Green20220302.Client CreateClient(string accessKeyId, string accessKeySecret)
              {
                  AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
                  {
                      AccessKeyId = accessKeyId,
                      AccessKeySecret = accessKeySecret,
                  };
                  // The endpoint of the service.
                  config.Endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  return new AlibabaCloud.SDK.Green20220302.Client(config);
              }
      
              public static void Main(string[] args)
              {
                  // Leaking your AccessKey pair in the project code may compromise the security of all resources in your account.
                  // The following code is for reference only. We recommend that you use a more secure method, such as Security Token Service (STS), to manage your credentials.
                  /**
                  * An AccessKey pair for an Alibaba Cloud account has permissions on all APIs. We recommend that you use a RAM user for API access or daily O&M.
                  * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your project code.
                  * Otherwise, your AccessKey pair may be leaked, which threatens the security of all resources in your account.
                  * A common practice is to read credentials from environment variables:
                  * Get the AccessKey ID of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
                  string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
                  // Note: To improve performance, reuse the client instance and avoid establishing a new connection for each request.
                  AlibabaCloud.SDK.Green20220302.Client client = CreateClient(accessKeyId, accessKeySecret);
                  // Build the request to cancel the video moderation task.
                  AlibabaCloud.SDK.Green20220302.Models.VideoModerationCancelRequest videoModerationCancelRequest = new AlibabaCloud.SDK.Green20220302.Models.VideoModerationCancelRequest();
                  // Specify the moderation service.
                  videoModerationCancelRequest.Service="videoDetection";
                  Dictionary<String,Object> serviceParameters=new Dictionary<string, object>();
                  // The ID of the video moderation task to cancel.
                  serviceParameters.Add("taskId","<your_task_id>");
                  videoModerationCancelRequest.ServiceParameters=JsonConvert.SerializeObject(serviceParameters);
                  // Create a RuntimeOptions instance and set runtime parameters.
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
                  runtime.ReadTimeout = 10000;
                  runtime.ConnectTimeout = 10000;
                  try
                  {
                      // Submit the cancellation request.
                      AlibabaCloud.SDK.Green20220302.Models.VideoModerationCancelResponse response = client.VideoModerationCancelWithOptions(videoModerationCancelRequest, runtime);
                      if(response is not null){
                      Console.WriteLine("response statusCode: "+response.StatusCode);
                          if (response.Body is not null){
                          Console.WriteLine("requestId: " + response.Body.RequestId);
                          Console.WriteLine("code: " + response.Body.Code);
                          Console.WriteLine("message: " + response.Body.Message);
                          }
                      }
                  }
                  catch (TeaException error)
                  {
                      // If an error occurs, print the error details.
                      AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
                      Console.WriteLine("error: " + error);
                  }
                  catch (Exception _error)
                  {
                      TeaException error = new TeaException(new Dictionary<string, object>
                      {
                          { "message", _error.Message }
                      });
                      // If an error occurs, print the error details.
                      AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
                      Console.WriteLine("error: " + error);
                  }
              }
          }
      }

Node.js SDK

See the source code for the Node.js SDK.

This service supports three video detection methods.

Publicly accessible videos

Use cases

If a video is accessible via a public URL, the Video Moderation Enhanced Edition service can fetch it by its URL to perform moderation.

  1. Run the following command to install the dependency.

    npm install @alicloud/green20220302@3.2.4
  2. Integrate the Node.js SDK.

    • Sample code for submitting a video moderation task

      const Green20220302 = require('@alicloud/green20220302');
      const OpenApi = require('@alicloud/openapi-client');
      const Util = require('@alicloud/tea-util');
      // Note: To improve performance, reuse the client instance to avoid establishing a new connection for each request.
      // For security reasons, do not hard-code your AccessKey pair in your code. Hard-coding your credentials can lead to leakage and compromise the security of all your resources. The following sample code is for reference only.
      class Client {
          static createClient() {
              const config = new OpenApi.Config({
                  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in your runtime environment.
                  accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in your runtime environment.
                  accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                  endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
              });
              return new Green20220302.default(config);
          }
      
          static async main() {
              const client = Client.createClient();
              // Construct the request object.
              const videoModerationRequest = new Green20220302.VideoModerationRequest({
                  "service": "videoDetection",
                  "serviceParameters": JSON.stringify({"url":"http://aliyundoc.com/test.flv"})
              });
              // Create a runtime options object.
              const runtime = new Util.RuntimeOptions();
              try {
                  // Send the request and get the response.
                  const response = await client.videoModerationWithOptions(videoModerationRequest, runtime);
                  console.log(JSON.stringify(response.body));
              } catch (error) {
                  // This is for demonstration purposes only. Handle exceptions with caution in your projects and do not ignore them.
                  // The error message.
                  console.log('Error occurred:', error.message);
              }
          }
      }
      
      Client.main();
    • Sample code for querying the result of a video moderation task

      const Green20220302 = require('@alicloud/green20220302');
      const OpenApi = require('@alicloud/openapi-client');
      const Util = require('@alicloud/tea-util');
      // Note: To improve performance, reuse the client instance to avoid establishing a new connection for each request.
      // For security reasons, do not hard-code your AccessKey pair in your code. Hard-coding your credentials can lead to leakage and compromise the security of all your resources. The following sample code is for reference only.
      class Client {
          static createClient() {
              const config = new OpenApi.Config({
                  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in your runtime environment.
                  accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in your runtime environment.
                  accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                  endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
              });
              return new Green20220302.default(config);
          }
      
          static async main() {
              const client = Client.createClient();
              // Construct the request object.
              const videoModerationResultRequest = new Green20220302.VideoModerationResultRequest({
                  // The video moderation service.
                  "service": "videoDetection",
                  "serviceParameters": JSON.stringify({"taskId":"<The ID of the video moderation task whose result you want to query>"})
              });
              // Create a runtime options object.
              const runtime = new Util.RuntimeOptions();
              try {
                  // Send the request and get the response.
                  const response = await client.videoModerationResultWithOptions(videoModerationResultRequest, runtime);
                  console.log(JSON.stringify(response.body));
              } catch (error) {
                  // This is for demonstration purposes only. Handle exceptions with caution in your projects and do not ignore them.
                  // The error message.
                  console.log('Error occurred:', error.message);
              }
          }
      }
      
      Client.main();
    • Sample code for canceling a video moderation task

      const Green20220302 = require('@alicloud/green20220302');
      const OpenApi = require('@alicloud/openapi-client');
      const Util = require('@alicloud/tea-util');
      // Note: To improve performance, reuse the client instance to avoid establishing a new connection for each request.
      // For security reasons, do not hard-code your AccessKey pair in your code. Hard-coding your credentials can lead to leakage and compromise the security of all your resources. The following sample code is for reference only.
      class Client {
          static createClient() {
              const config = new OpenApi.Config({
                  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in your runtime environment.
                  accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in your runtime environment.
                  accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                  endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
              });
              return new Green20220302.default(config);
          }
      
          static async main() {
              const client = Client.createClient();
              // Construct the request object.
              const videoModerationCancelRequest = new Green20220302.VideoModerationCancelRequest({
                  // The video moderation service.
                  "service": "videoDetection",
                  // The ID of the video moderation task to cancel.
                  "serviceParameters": JSON.stringify({"taskId":"<The ID of the video moderation task to cancel>"})
              });
              // Create a runtime options object.
              const runtime = new Util.RuntimeOptions();
              try {
                  // Send the request and get the response.
                  const response = await client.videoModerationCancelWithOptions(videoModerationCancelRequest, runtime);
                  console.log(JSON.stringify(response.body));
              } catch (error) {
                  // This is for demonstration purposes only. Handle exceptions with caution in your projects and do not ignore them.
                  // The error message.
                  console.log('Error occurred:', error.message);
              }
          }
      }
      
      Client.main();

Local videos

Use cases

To moderate a local video that does not have a public URL, upload it to an Object Storage Service (OSS) bucket provided by Content Moderation. The Video Moderation Enhanced Edition service then retrieves the video directly from OSS for moderation.

  1. Run the following command to install the dependency.

    npm install @alicloud/green20220302@3.2.4
  2. Integrate the Node.js SDK.

    • Sample code for submitting a video moderation task

      const RPCClient = require("@alicloud/pop-core");
      const OSS = require('ali-oss');
      const { v4: uuidv4 } = require('uuid');
      const path = require("path");
      
      // Specifies whether the service is deployed in a VPC.
      var isVPC = false;
      // The token for file upload.
      var tokenDic = new Array();
      // The client for file upload.
      var ossClient;
      
      // Create a client for file upload.
      function createClient(accessKeyId, accessKeySecret, endpoint) {
          return new RPCClient({
              accessKeyId: accessKeyId,
              accessKeySecret: accessKeySecret,
              endpoint: endpoint,
              apiVersion: '2022-03-02',
              // Set an HTTP proxy.
              //httpProxy: "http://xx.xx.xx.xx:xxxx",
              // Set an HTTPS proxy.
              //httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999",
          });
      }
      
      // Create a client for file upload.
      function getOssClient(tokenData, isVPC) {
          if (isVPC) {
              ossClient = new OSS({
                  accessKeyId: tokenData['AccessKeyId'],
                  accessKeySecret: tokenData['AccessKeySecret'],
                  stsToken: tokenData['SecurityToken'],
                  endpoint: tokenData['OssInternalEndPoint'],
                  bucket: tokenData['BucketName'],
              });
          } else {
              ossClient = new OSS({
                  accessKeyId: tokenData['AccessKeyId'],
                  accessKeySecret: tokenData['AccessKeySecret'],
                  stsToken: tokenData['SecurityToken'],
                  endpoint: tokenData['OssInternetEndPoint'],
                  bucket: tokenData['BucketName'],
              });
          }
      }
      
      // Submit a moderation task.
      async function invoke(accessKeyId, accessKeySecret, endpoint) {
          // Note: To improve performance, reuse the client instance to avoid establishing a new connection for each request.
          var client = createClient(accessKeyId, accessKeySecret, endpoint);
          var requestOption = {
              method: 'POST',
              formatParams: false,
          };
          // The full path of the local file. Example: D:\\localPath\\exampleFile.mp4.
          var filePath = 'D:\\localPath\\exampleFile.mp4';
      
          // Get the token for file upload.
          if (tokenDic[endpoint] == null || tokenDic[endpoint]['Expiration'] <= Date.parse(new Date() / 1000)) {
              var tokenResponse = await client.request('DescribeUploadToken', '', requestOption)
              tokenDic[endpoint] = tokenResponse.Data;
          }
      
          // Get the client for file upload.
          getOssClient(tokenDic[endpoint], isVPC)
          var split = filePath.split(".");
          var objectName;
          if (split.length > 1) {
              objectName = tokenDic[endpoint].FileNamePrefix + uuidv4() + "." + split[split.length - 1];
          } else {
              objectName = tokenDic[endpoint].FileNamePrefix + uuidv4();
          }
          // Upload the file.
          const result = await ossClient.put(objectName, path.normalize(filePath));
      
          // Create a moderation API request and set the parameters.
          var params = {
              // The video moderation service. Example: videoDetection
              "Service": "videoDetection",
              // Information about the uploaded local video.
              "ServiceParameters": JSON.stringify({
                  "ossBucketName": tokenDic[endpoint].BucketName,
                  "ossObjectName": objectName
              })
          }
          // Call the API to get the moderation result.
          return await client.request('VideoModeration', params, requestOption);
      }
      
      function main() {
          /**
          * An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M.
          * We strongly recommend that you do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised.
          * Common methods to obtain environment variables:
          * Obtain the AccessKey ID of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID']
          * Obtain the AccessKey secret of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          */
          const accessKeyId = 'We recommend that you obtain the AccessKey ID of a RAM user from an environment variable.'
          const accessKeySecret = 'We recommend that you obtain the AccessKey secret of a RAM user from an environment variable.'
          // Modify the region and endpoint based on your actual requirements.
          var endpoint = "https://green-cip.cn-shanghai.aliyuncs.com"
      
          try {
              var response;
              // Call the API to get the moderation result.
              invoke(accessKeyId, accessKeySecret, endpoint).then(function (response) {
                  // Automatic routing.
                  if (response.Code == 500) {
                      // Switch the region to China (Beijing).
                      endpoint = "https://green-cip.cn-beijing.aliyuncs.com"
                      invoke(accessKeyId, accessKeySecret, endpoint).then(function (response){
                          console.log(JSON.stringify(response))
                      })
                  }else{
                      console.log(JSON.stringify(response))
                  }
              })
          } catch (err) {
              console.log(err);
          }
      }
      
      main();
    • Sample code for querying the result of a video moderation task

      const Green20220302 = require('@alicloud/green20220302');
      const OpenApi = require('@alicloud/openapi-client');
      const Util = require('@alicloud/tea-util');
      // Note: To improve performance, reuse the client instance to avoid establishing a new connection for each request.
      // For security reasons, do not hard-code your AccessKey pair in your code. Hard-coding your credentials can lead to leakage and compromise the security of all your resources. The following sample code is for reference only.
      class Client {
          static createClient() {
              const config = new OpenApi.Config({
                  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in your runtime environment.
                  accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in your runtime environment.
                  accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                  endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
              });
              return new Green20220302.default(config);
          }
      
          static async main() {
              const client = Client.createClient();
              // Construct the request object.
              const videoModerationResultRequest = new Green20220302.VideoModerationResultRequest({
                  // The video moderation service.
                  "service": "videoDetection",
                  "serviceParameters": JSON.stringify({"taskId":"<The ID of the video moderation task whose result you want to query>"})
              });
              // Create a runtime options object.
              const runtime = new Util.RuntimeOptions();
              try {
                  // Send the request and get the response.
                  const response = await client.videoModerationResultWithOptions(videoModerationResultRequest, runtime);
                  console.log(JSON.stringify(response.body));
              } catch (error) {
                  // This is for demonstration purposes only. Handle exceptions with caution in your projects and do not ignore them.
                  // The error message.
                  console.log('Error occurred:', error.message);
              }
          }
      }
      
      Client.main();
    • Sample code for canceling a video moderation task

      const Green20220302 = require('@alicloud/green20220302');
      const OpenApi = require('@alicloud/openapi-client');
      const Util = require('@alicloud/tea-util');
      // Note: To improve performance, reuse the client instance to avoid establishing a new connection for each request.
      // For security reasons, do not hard-code your AccessKey pair in your code. Hard-coding your credentials can lead to leakage and compromise the security of all your resources. The following sample code is for reference only.
      class Client {
          static createClient() {
              const config = new OpenApi.Config({
                  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in your runtime environment.
                  accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in your runtime environment.
                  accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                  endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
              });
              return new Green20220302.default(config);
          }
      
          static async main() {
              const client = Client.createClient();
              // Construct the request object.
              const videoModerationCancelRequest = new Green20220302.VideoModerationCancelRequest({
                  // The video moderation service.
                  "service": "videoDetection_global",
                  // The ID of the video moderation task to cancel.
                  "serviceParameters": JSON.stringify({"taskId":"<The ID of the video moderation task to cancel>"})
              });
              // Create a runtime options object.
              const runtime = new Util.RuntimeOptions();
              try {
                  // Send the request and get the response.
                  const response = await client.videoModerationCancelWithOptions(videoModerationCancelRequest, runtime);
                  console.log(JSON.stringify(response.body));
              } catch (error) {
                  // This is for demonstration purposes only. Handle exceptions with caution in your projects and do not ignore them.
                  // The error message.
                  console.log('Error occurred:', error.message);
              }
          }
      }
      
      Client.main();

OSS videos

Use cases

If the video files that you need to moderate are stored in Alibaba Cloud Object Storage Service (OSS), you can create a service role to allow the Content Moderation service to access OSS. The Video Moderation Enhanced Edition service uses the service role to retrieve files from OSS for moderation. Go to the Cloud Resource Access Authorization page to create the service role.

  1. Run the following command to install the dependency.

    npm install @alicloud/green20220302@3.2.4
  2. Integrate the Node.js SDK.

    • Sample code for submitting a video moderation task

      const Green20220302 = require('@alicloud/green20220302');
      const OpenApi = require('@alicloud/openapi-client');
      const Util = require('@alicloud/tea-util');
      // Note: To improve performance, reuse the client instance to avoid establishing a new connection for each request.
      // For security reasons, do not hard-code your AccessKey pair in your code. Hard-coding your credentials can lead to leakage and compromise the security of all your resources. The following sample code is for reference only.
      class Client {
          static createClient() {
              const config = new OpenApi.Config({
                  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in your runtime environment.
                  accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in your runtime environment.
                  accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                  endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
              });
              return new Green20220302.default(config);
          }
      
          static async main() {
              const client = Client.createClient();
              // Construct the request object.
              const videoModerationRequest = new Green20220302.VideoModerationRequest({
                  "service": "videoDetection",
                  "serviceParameters": JSON.stringify({
                  // The region where the bucket that stores the file is located. Example: cn-shanghai
                  "ossRegionId": "cn-shanghai",
                  // The name of the bucket that stores the file. Example: bucket001
                  "ossBucketName": "bucket001",
                  // The file to be moderated. Example: video/001.mp4
                  "ossObjectName": "video/001.mp4",})
              });
              // Create a runtime options object.
              const runtime = new Util.RuntimeOptions();
              try {
                  // Send the request and get the response.
                  const response = await client.videoModerationWithOptions(videoModerationRequest, runtime);
                  console.log(JSON.stringify(response.body));
              } catch (error) {
                  // This is for demonstration purposes only. Handle exceptions with caution in your projects and do not ignore them.
                  // The error message.
                  console.log('Error occurred:', error.message);
              }
          }
      }
      
      Client.main();
    • Sample code for querying the result of a video moderation task

      const Green20220302 = require('@alicloud/green20220302');
      const OpenApi = require('@alicloud/openapi-client');
      const Util = require('@alicloud/tea-util');
      // Note: To improve performance, reuse the client instance to avoid establishing a new connection for each request.
      // For security reasons, do not hard-code your AccessKey pair in your code. Hard-coding your credentials can lead to leakage and compromise the security of all your resources. The following sample code is for reference only.
      class Client {
          static createClient() {
              const config = new OpenApi.Config({
                  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in your runtime environment.
                  accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in your runtime environment.
                  accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                  endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
              });
              return new Green20220302.default(config);
          }
      
          static async main() {
              const client = Client.createClient();
              // Construct the request object.
              const videoModerationResultRequest = new Green20220302.VideoModerationResultRequest({
                  // The video moderation service.
                  "service": "videoDetection",
                  "serviceParameters": JSON.stringify({"taskId":"<The ID of the video moderation task whose result you want to query>"})
              });
              // Create a runtime options object.
              const runtime = new Util.RuntimeOptions();
              try {
                  // Send the request and get the response.
                  const response = await client.videoModerationResultWithOptions(videoModerationResultRequest, runtime);
                  console.log(JSON.stringify(response.body));
              } catch (error) {
                  // This is for demonstration purposes only. Handle exceptions with caution in your projects and do not ignore them.
                  // The error message.
                  console.log('Error occurred:', error.message);
              }
          }
      }
      
      Client.main();
    • Sample code for canceling a video moderation task

      const Green20220302 = require('@alicloud/green20220302');
      const OpenApi = require('@alicloud/openapi-client');
      const Util = require('@alicloud/tea-util');
      // Note: To improve performance, reuse the client instance to avoid establishing a new connection for each request.
      // For security reasons, do not hard-code your AccessKey pair in your code. Hard-coding your credentials can lead to leakage and compromise the security of all your resources. The following sample code is for reference only.
      class Client {
          static createClient() {
              const config = new OpenApi.Config({
                  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in your runtime environment.
                  accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in your runtime environment.
                  accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
                  endpoint: `green-cip.cn-shanghai.aliyuncs.com`,
              });
              return new Green20220302.default(config);
          }
      
          static async main() {
              const client = Client.createClient();
              // Construct the request object.
              const videoModerationCancelRequest = new Green20220302.VideoModerationCancelRequest({
                  // The video moderation service.
                  "service": "videoDetection_global",
                  // The ID of the video moderation task to cancel.
                  "serviceParameters": JSON.stringify({"taskId":"<The ID of the video moderation task to cancel>"})
              });
              // Create a runtime options object.
              const runtime = new Util.RuntimeOptions();
              try {
                  // Send the request and get the response.
                  const response = await client.videoModerationCancelWithOptions(videoModerationCancelRequest, runtime);
                  console.log(JSON.stringify(response.body));
              } catch (error) {
                  // This is for demonstration purposes only. Handle exceptions with caution in your projects and do not ignore them.
                  // The error message.
                  console.log('Error occurred:', error.message);
              }
          }
      }
      
      Client.main();

Direct HTTPS requests

  • Invocation Method

    Service endpoint: https://green-cip.{region}.aliyuncs.com

    Protocol: HTTPS

    Method: POST

  • Common request parameters

    API calls for enhanced audio moderation consist of common and operation-specific request parameters. All API calls must include the common request parameters that are listed in the table below.

    Parameter

    Type

    Required

    Description

    Format

    String

    Yes

    The format of the response. Valid values:

    • JSON (default)

    • XML

    Version

    String

    Yes

    The API version, in YYYY-MM-DD format. The current version is 2022-03-02.

    AccessKeyId

    String

    Yes

    Your Alibaba Cloud access key ID.

    Signature

    String

    Yes

    The signature string. For calculation details, see the "Signing mechanism" section.

    SignatureMethod

    String

    Yes

    The signature method. The only supported value is HMAC-SHA1.

    Timestamp

    String

    Yes

    The request timestamp in UTC, formatted according to the ISO 8601 standard.

    Format: yyyy-MM-ddTHH:mm:ssZ.

    For example, 09:13:14 on December 12, 2022 (UTC+8) is represented as 2022-12-12T01:13:14Z.

    SignatureVersion

    String

    Yes

    The signature algorithm version. Set the value to 1.0.

    SignatureNonce

    String

    Yes

    A unique random number (nonce) that must be unique for each request to prevent network replay attacks.

    Action

    String

    Yes

    Valid values:

    • VideoModeration

    • VideoModerationResult

    • VideoModerationCancel

  • Common response parameters

    The system returns a unique request ID (RequestId) for every API call, regardless of its outcome. Other response parameters vary by the specific API called.

    {
        "RequestId":"20B935A9-XXXXXXXX-XXXXXXXX0C2",
        "Message":"SUCCESS",
        "Data":{
            "TaskId":"vi_f_O5xxxxxxxxxxxxxxqa-1****"
        },
        "Code":200
    }
  • Code examples

    The following examples are formatted for readability. Actual API responses are not formatted with line breaks or indentation.

    • Submitting a moderation task

      Sample Request

      http://green-cip.cn-shanghai.aliyuncs.com/
      ?Format=JSON
      &Version=2022-03-02
      &Signature=vpEEL0zFHfxXYzSFV0n7%2FZiFL9o%3D
      &SignatureMethod=Hmac-SHA1
      &SignatureNonce=15215528852396
      &SignatureVersion=1.0
      &Action=VideoModeration
      &AccessKeyId=123****cip
      &Timestamp=2023-02-03T12:00:00Z
      &Service=videoDetection
      &ServiceParameters={"url": "https://xxxxxx.aliyuncs.com/sample/****.mp4"}

      Sample Response

      {
          "RequestId":"20B935A9-XXXXXXXX-XXXXXXXX0C2",
          "Message":"SUCCESS",
          "Data":{
              "TaskId":"vi_f_O5xxxxxxxxxxxxxxqa-1x****"
          },
          "Code":200
      }
    • Querying a task result

      Sample Request

      http://green-cip.cn-shanghai.aliyuncs.com/
      ?Format=JSON
      &Version=2022-03-02
      &Signature=vpEEL0zFHfxXYzSFV0n7%2FZiFL9o%3D
      &SignatureMethod=Hmac-SHA1
      &SignatureNonce=15215528852396
      &SignatureVersion=1.0
      &Action=VideoModerationResult
      &AccessKeyId=123****cip
      &Timestamp=2023-02-03T12:00:00Z
      &Service=videoDetection
      &ServiceParameters={"taskId": "vi_f_O5zxxxxxxxxxxxxxxxx-1x****"}

      Sample Response

      {
          "Code": 200,
          "RequestId": "25106421-XXXX-XXXX-XXXX-15DA5AAAC546",
          "Message": "success finished",
          "Data": {
              "DataId": "ABCDEF-TESTDATAID",
              "TaskId": "vi_f_VnI6BO74NXFIZm7XXXXXXXXXXXXXX",
              "RiskLevel": "medium",
              "FrameResult": {
                  "FrameNum": 2,
                  "FrameSummarys": [
                      {
                          "Label": "violent_explosion",
                          "Description": "Suspected fireworks-related elements",
                          "LabelSum": 8
                      },
                      {
                          "Label": "sexual_cleavage",
                          "Description": "Suspected content with partial nudity or sexually suggestive elements",
                          "LabelSum": 8
                      }
                  ],
                  "RiskLevel": "medium",
                  "Frames": [
                      {
                          "Offset": 1,
                          "RiskLevel": "none",
                          "Results": [
                              {
                                  "Result": [
                                      {
                                          "Label": "nonLabel",
                                          "Description": "No risks detected"
                                      }
                                  ],
                                  "Service": "baselineCheck"
                              },
                              {
                                  "Result": [
                                      {
                                          "Label": "nonLabel"
                                      }
                                  ],
                                  "Service": "baselineCheck_pro"
                              }
                          ],
                          "TempUrl": "http://abc.oss-cn-shanghai.aliyuncs.com/test1.jpg"
                      },
                      {
                          "Offset": 2,
                          "RiskLevel": "medium",
                          "Results": [
                              {
                                  "Result": [
                                      {
                                          "Confidence": 74.1,
                                          "Label": "violent_explosion",
                                          "Description": "Suspected fireworks-related elements"
                                      }
                                  ],
                                  "Service": "baselineCheck"
                              },
                              {
                                  "Result": [
                                      {
                                          "Confidence": 1,
                                          "Label": "sexual_cleavage",
                                          "Description": "Suspected content with partial nudity or sexually suggestive elements"
                                      }
                                  ],
                                  "Service": "baselineCheck_pro"
                              }
                          ],
                          "TempUrl": "http://abc.oss-cn-shanghai.aliyuncs.com/test2.jpg"
                      }
                  ]
              }
          }
      }
  • Signing mechanism

    The enhanced audio moderation service authenticates each request by using a signature. The service uses a symmetric encryption method with an access key ID and an access key secret to verify the sender's identity.

    Alibaba Cloud issues your access key ID and access key secret, which you can manage on its website. The access key secret is used to encrypt the signature string for server-side verification. Keep your access key secret confidential.

    To sign a request, follow these steps:

    1. Create a canonicalized query string from the request parameters.

      1. Sort all request parameters (including common and operation-specific parameters, but excluding the Signature parameter) by parameter name in lexicographical order.

      2. Encode the names and values of the sorted parameters using UTF-8 URL encoding.

        Note

        Most URL encoding libraries, such as java.net.URLEncoder in Java, follow the rules for the application/x-www-form-urlencoded MIME type. You can use such a library for encoding, but you must then replace plus signs (+) with %20, asterisks (*) with %2A, and %7E with tildes (~).

        The URL encoding rules are as follows:

        • Do not encode the following characters: uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), hyphens (-), underscores (_), periods (.), and tildes (~).

        • Other characters are encoded in the %XY format, where XY is the hexadecimal representation of the character's ASCII code. For example, the English double quotation mark (") is encoded as %22.

        • Extended UTF-8 characters are encoded in the %XY%ZA… format.

        • Note that a space character is encoded as %20, and not a plus sign (+).

      3. Join each encoded parameter name and its value with an equal sign (=).

      4. Concatenate these 'name=value' pairs in their original sorted order, using ampersands (&), to create the canonicalized query string.

    2. Construct the string-to-sign from the canonicalized query string as follows:

      StringToSign=
      HTTPMethod + "&" +
      percentEncode("/") + "&" +
      percentEncode(CanonicalizedQueryString)
      Note

      HTTPMethod is the HTTP method used to submit the request, such as POST. percentEncode(/) is the value that is obtained by URL-encoding the forward slash (/) character as described in section a.ii. The value is %2F. percentEncode(CanonicalQueryString) is the string that is obtained by URL-encoding the canonicalized query string from section a.i as described in section a.ii.

    3. Calculate the HMAC value of the string to be signed as defined in RFC2104.

      Note

      Note that the Key used to calculate the signature is your AccessKey Secret followed by an& character (ASCII: 38). The hash algorithm used is SHA1.

    4. Base64-encode the HMAC value to get the signature string.

    5. Add the signature string to the request as the Signature parameter.

      Note

      Remember to URL-encode the signature string according to RFC 3986 before you add it to the request.