All Products
Search
Document Center

Content Moderation:Document Moderation 2.0 SDK and integration guide

Last Updated:Jan 07, 2026

Document Moderation 2.0 supports both SDK-based and native HTTPS calls. You can use the SDK to skip the signature verification and body format construction steps. This guide describes how to integrate Document Moderation 2.0.

Step 1: Activate the service

Visit the Activate Content Moderation 2.0 Service page to activate the Document Moderation 2.0 service. After you integrate the service, you are automatically billed based on your usage. For more information, see Billing description.

After you activate the Document Moderation 2.0 service, the default billing method is pay-as-you-go. You are billed daily based on your actual usage. No fees are incurred when you do not use the service.

Step 2: Grant permissions to the RAM user

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

Procedure

  1. Log on to the RAM console as a RAM administrator.

  2. Create a RAM user.

    For more information, see Create a RAM user.

  3. Grant the AliyunYundunGreenWebFullAccess system policy to the RAM user.

    For more information, see Grant permissions to a RAM user.

    After completing the preceding operations, you can call the Content Moderation API as the RAM user.

Step 3: Install and integrate the document moderation service

The service can be integrated in the following regions.

Region

Public endpoint

VPC endpoint

Supported services

Singapore

green-cip.ap-southeast-1.aliyuncs.com

green-cip-vpc.ap-southeast-1.aliyuncs.com

document_detection_global

Note

If you require SDK sample code in other languages, you can use the OpenAPI Developer Portal online debugging tool to test API operations. This tool automatically generates SDK sample code for the corresponding API.

In Alibaba Cloud SDK code, you can create a default access credential by defining ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. When you call API operations of Alibaba Cloud services, the system directly accesses the credential, reads your AccessKey pair, and then automatically completes authentication. Before you use the SDK sample code, you must configure environment variables. For more information, see Configure credentials.

For more information about the API interface fields, see Document Moderation enhanced edition 2.0 API.

Java SDK

This SDK supports Java 1.8 and later.

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

The SDK supports the following three types of document detection.

Detect publicly accessible documents

Scenario

If the document that you want to moderate is accessible from the Internet, Document Moderation 2.0 retrieves the file using the document URL and then moderates the file.

To use the SDK in a Maven project, add the required dependencies to the pom.xml file.

  1. Add the following dependencies to the dependencies section:

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

    • Sample code for submitting a document detection task

      import com.alibaba.fastjson.JSON;
      import com.alibaba.fastjson.JSONObject;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.FileModerationRequest; 
      import com.aliyun.green20220302.models.FileModerationResponse; 
      import com.aliyun.green20220302.models.FileModerationResponseBody; 
      import com.aliyun.teaopenapi.models.Config;
      
      public class FileModerationDemo {
          public static void main(String[] args) throws Exception {
              Config config = new Config();
               /**
               * The 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.
               * Common methods to obtain environment variables:
               * Method 1:
               *     Obtain the RAM user AccessKey ID: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the RAM user AccessKey Secret: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Obtain the RAM user AccessKey ID: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the RAM user AccessKey Secret: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              config.setAccessKeyId("It is recommended to obtain the RAM user AccessKey ID from environment variables");
              config.setAccessKeySecret("It is recommended to obtain the RAM user AccessKey Secret from environment variables");
              // Modify the region and address based on actual conditions.
              config.setRegionId("ap-southeast-1");
              config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com");
              // Connection timeout in milliseconds (ms).
              config.setReadTimeout(6000);
              // Read timeout in milliseconds (ms).
              config.setConnectTimeout(3000);
      
              Client client = new Client(config);
              JSONObject serviceParameters = new JSONObject();
              serviceParameters.put("url", "https://xxx.oss.aliyuncs.com/xxx.pdf"); // File URL
      
              FileModerationRequest fileModerationRequest = new FileModerationRequest(); 
              // Detection type: document_detection_global general document detection
              fileModerationRequest.setService("document_detection_global");
              fileModerationRequest.setServiceParameters(serviceParameters.toJSONString());
      
              try {
                  FileModerationResponse response = client.fileModeration(fileModerationRequest); 
                  if (response.getStatusCode() == 200) {
                      FileModerationResponseBody 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) {
                          FileModerationResponseBody.FileModerationResponseBodyData data = result.getData();
                          System.out.println("taskId = [" + data.getTaskId() + "]");
                      } else {
                          System.out.println("file moderation not success. code:" + code);
                      }
                  } else {
                      System.out.println("response not success. status:" + response.getStatusCode());
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }
      
    • Retrieve document detection task results

      import com.alibaba.fastjson.JSON;
      import com.alibaba.fastjson.JSONObject;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.DescribeFileModerationResultRequest;
      import com.aliyun.green20220302.models.DescribeFileModerationResultResponse;
      import com.aliyun.green20220302.models.DescribeFileModerationResultResponseBody;
      import com.aliyun.teaopenapi.models.Config;
      
      
      public class DescribeFileModerationResultDemo {
      
          public static void main(String[] args) throws Exception {
              Config config = new Config();
              /**
               * The 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.
               * Common methods to obtain environment variables:
               * Method 1:
               *     Obtain the RAM user AccessKey ID: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the RAM user AccessKey Secret: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Obtain the RAM user AccessKey ID: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the RAM user AccessKey Secret: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              config.setAccessKeyId("It is recommended to obtain the RAM user AccessKey ID from environment variables");
              config.setAccessKeySecret("It is recommended to obtain the RAM user AccessKey Secret from environment variables");
              // Modify the region and address based on actual conditions
              config.setRegionId("ap-southeast-1");
              config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com");
              // Connection timeout in milliseconds (ms).
              config.setReadTimeout(6000);
              // Read timeout in milliseconds (ms).
              config.setConnectTimeout(3000);
            
              Client client = new Client(config);
      
              JSONObject serviceParameters = new JSONObject();
              // taskId returned when the task is submitted
              serviceParameters.put("taskId", "fi_f_O5z5i*********-1xxp0V");
      
      
              DescribeFileModerationResultRequest describeFileModerationResultRequest = new DescribeFileModerationResultRequest();
              
              describeFileModerationResultRequest.setService("document_detection_global");
              describeFileModerationResultRequest.setServiceParameters(serviceParameters.toJSONString());
      
              try {
                  DescribeFileModerationResultResponse response = client.describeFileModerationResult(describeFileModerationResultRequest);
                  if (response.getStatusCode() == 200) {
                      DescribeFileModerationResultResponseBody 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()) {
                          DescribeFileModerationResultResponseBody.DescribeFileModerationResultResponseBodyData data = result.getData();
                          System.out.println("pageResult = " + JSON.toJSONString(data.getPageResult()));
                          System.out.println("dataId = " + data.getDataId());
                          System.out.println("url = " + data.getUrl());
                      } else {
                          System.out.println("file moderation result not success. code:" + result.getCode());
                      }
                  } else {
                      System.out.println("response not success. status:" + response.getStatusCode());
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }

Detect local documents

Scenario

If the document that you want to moderate is stored locally and is not accessible from the Internet, you must upload it to an Object Storage Service (OSS) bucket that is provided by Content Moderation. Document Moderation 2.0 then directly accesses OSS to retrieve and moderate the document content.

  1. Add the following dependencies to the dependencies section:

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>green20220302</artifactId>
      <version>2.2.11</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 document detection 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.FileModerationRequest;
      import com.aliyun.green20220302.models.FileModerationResponse;
      import com.aliyun.green20220302.models.FileModerationResponseBody;
      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 FileModerationFile {
          /**Whether the service is deployed on vpc*/
          public static boolean isVPC = false;
      
          /**File upload token endpoint->token*/
          public static Map<String, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData> tokenMap = new HashMap<>();
      
          /**Client for uploading file requests*/
          public static OSS ossClient = null;
      
          /**
           * Create a request client
           *
           * @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);
              // Modify the region and address based on actual conditions
              config.setEndpoint(endpoint);
              return new Client(config);
          }
      
          /**
           * Create a client for uploading file requests
           *
           * @param tokenData
           * @param isVPC
           */
          public static void getOssClient(DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData, boolean isVPC) {
              // Note that the instantiated client here should be reused as much as possible to avoid repeated connections and improve detection performance.
              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());
              }
          }
      
          /**
           * Upload 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 FileModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              // Note that the instantiated client here should be reused as much as possible to avoid repeated connections and improve detection performance.
              Client client = createClient(accessKeyId, accessKeySecret, endpoint);
              RuntimeOptions runtime = new RuntimeOptions();
      
              // The full path of the local file, such as D:\localPath\exampleFile.mp3.
              String filePath = "D:/test/1.pdf";
              // 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());
              }
              // Client for uploading file requests
              getOssClient(tokenMap.get(endpoint), isVPC);
      
              // Upload file
              String objectName = uploadFile(filePath, tokenMap.get(endpoint));
      
              // Construct detection 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());
      
              FileModerationRequest request = new FileModerationRequest();
              // Detection type.
              request.setService("document_detection_global");
              request.setServiceParameters(JSON.toJSONString(serviceParameters));
      
              FileModerationResponse response = null;
              try {
                  response = client.fileModerationWithOptions(request, runtime);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return response;
          }
      
          public static void main(String[] args) throws Exception {
              /**
               * The 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.
               * Common methods to obtain environment variables:
               * Method 1:
               *     Obtain the RAM user AccessKey ID: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the RAM user AccessKey Secret: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Obtain the RAM user AccessKey ID: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the RAM user AccessKey Secret: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              config.setAccessKeyId("It is recommended to obtain the RAM user AccessKey ID from environment variables");
              config.setAccessKeySecret("It is recommended to obtain the RAM user AccessKey Secret from environment variables");
              // Modify the region and address based on actual conditions.
              FileModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com");
      
                  // Print the detection results.
                  if (response != null) {
                      if (response.getStatusCode() == 200) {
                          FileModerationResponseBody 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) {
                              FileModerationResponseBody.FileModerationResponseBodyData data = body.getData();
                              System.out.println("taskId = [" + data.getTaskId() + "]");
                          } else {
                              System.out.println("file moderation not success. code:" + code);
                          }
                      } else {
                          System.out.println("response not success. status:" + response.getStatusCode());
                      }
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }
      
    • Obtain a code sample for a document detection task

      import com.alibaba.fastjson.JSON;
      import com.alibaba.fastjson.JSONObject;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.DescribeFileModerationResultRequest;
      import com.aliyun.green20220302.models.DescribeFileModerationResultResponse;
      import com.aliyun.green20220302.models.DescribeFileModerationResultResponseBody;
      import com.aliyun.teaopenapi.models.Config;
      
      
      public class DescribeFileModerationResultDemo {
      
          public static void main(String[] args) throws Exception {
              Config config = new Config();
              /**
               * The 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.
               * Common methods to obtain environment variables:
               * Method 1:
               *     Obtain the RAM user AccessKey ID: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the RAM user AccessKey Secret: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Obtain the RAM user AccessKey ID: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the RAM user AccessKey Secret: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              config.setAccessKeyId("It is recommended to obtain the RAM user AccessKey ID from environment variables");
              config.setAccessKeySecret("It is recommended to obtain the RAM user AccessKey Secret from environment variables");
              // Modify the region and address based on actual conditions
              config.setRegionId("ap-southeast-1");
              config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com");
              // Connection timeout in milliseconds (ms).
              config.setReadTimeout(6000);
              // Read timeout in milliseconds (ms).
              config.setConnectTimeout(3000);
            
              Client client = new Client(config);
      
              JSONObject serviceParameters = new JSONObject();
              // taskId returned when the task is submitted
              serviceParameters.put("taskId", "fi_f_O5z5i*********-1xxp0V");
      
      
              DescribeFileModerationResultRequest describeFileModerationResultRequest = new DescribeFileModerationResultRequest();
              
              describeFileModerationResultRequest.setService("document_detection_global");
              describeFileModerationResultRequest.setServiceParameters(serviceParameters.toJSONString());
      
              try {
                  DescribeFileModerationResultResponse response = client.describeFileModerationResult(describeFileModerationResultRequest);
                  if (response.getStatusCode() == 200) {
                      DescribeFileModerationResultResponseBody 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()) {
                          DescribeFileModerationResultResponseBody.DescribeFileModerationResultResponseBodyData data = result.getData();
                          System.out.println("pageResult = " + JSON.toJSONString(data.getPageResult()));
                          System.out.println("dataId = " + data.getDataId());
                          System.out.println("url = " + data.getUrl());
                      } else {
                          System.out.println("file moderation result not success. code:" + result.getCode());
                      }
                  } else {
                      System.out.println("response not success. status:" + response.getStatusCode());
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }

Detect OSS documents

Scenarios

If the document that you want to moderate is stored in Alibaba Cloud Object Storage Service (OSS), you must create a server role to grant Content Moderation access to OSS. Document Moderation 2.0 retrieves the file from OSS for analysis using this server role. To create a server role, visit the Cloud resource access authorization page.

  1. Add the following dependencies to the dependencies section:

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>green20220302</artifactId>
      <version>2.2.11</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 document detection task

      import com.alibaba.fastjson.JSON;
      import com.alibaba.fastjson.JSONObject;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.FileModerationRequest; 
      import com.aliyun.green20220302.models.FileModerationResponse; 
      import com.aliyun.green20220302.models.FileModerationResponseBody; 
      import com.aliyun.teaopenapi.models.Config;
      
      public class FileModerationDemo {
          public static void main(String[] args) throws Exception {
              Config config = new Config();
               /**
               * The 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.
               * Common methods to obtain environment variables:
               * Method 1:
               *     Obtain the RAM user AccessKey ID: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the RAM user AccessKey Secret: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Obtain the RAM user AccessKey ID: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the RAM user AccessKey Secret: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              config.setAccessKeyId("It is recommended to obtain the RAM user AccessKey ID from environment variables");
              config.setAccessKeySecret("It is recommended to obtain the RAM user AccessKey Secret from environment variables");
              // Modify the region and address based on actual conditions.
              config.setRegionId("ap-southeast-1");
              config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com");
              // Connection timeout in milliseconds (ms).
              config.setReadTimeout(6000);
              // Read timeout in milliseconds (ms).
              config.setConnectTimeout(3000);
      
              Client client = new Client(config);
              JSONObject serviceParameters = new JSONObject();
              serviceParameters.put("ossBucketName", "bucket_01");
              serviceParameters.put("ossObjectName", "2022023/04/24/test.pdf");
              serviceParameters.put("ossRegionId", "ap-southeast-1"); 
      
              FileModerationRequest fileModerationRequest = new FileModerationRequest(); 
              // Detection type: document_detection_global general document detection
              fileModerationRequest.setService("document_detection_global");
              fileModerationRequest.setServiceParameters(serviceParameters.toJSONString());
      
              try {
                  FileModerationResponse response = client.fileModeration(fileModerationRequest); 
                  if (response.getStatusCode() == 200) {
                      FileModerationResponseBody 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) {
                          FileModerationResponseBody.FileModerationResponseBodyData data = result.getData();
                          System.out.println("taskId = [" + data.getTaskId() + "]");
                      } else {
                          System.out.println("file moderation not success. code:" + code);
                      }
                  } else {
                      System.out.println("response not success. status:" + response.getStatusCode());
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }
      
    • Sample code for retrieving document detection task results

      import com.alibaba.fastjson.JSON;
      import com.alibaba.fastjson.JSONObject;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.DescribeFileModerationResultRequest;
      import com.aliyun.green20220302.models.DescribeFileModerationResultResponse;
      import com.aliyun.green20220302.models.DescribeFileModerationResultResponseBody;
      import com.aliyun.teaopenapi.models.Config;
      
      
      public class DescribeFileModerationResultDemo {
      
          public static void main(String[] args) throws Exception {
              Config config = new Config();
              /**
               * The 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.
               * Common methods to obtain environment variables:
               * Method 1:
               *     Obtain the RAM user AccessKey ID: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the RAM user AccessKey Secret: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Obtain the RAM user AccessKey ID: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Obtain the RAM user AccessKey Secret: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              config.setAccessKeyId("It is recommended to obtain the RAM user AccessKey ID from environment variables");
              config.setAccessKeySecret("It is recommended to obtain the RAM user AccessKey Secret from environment variables");
              // Modify the region and address based on actual conditions
              config.setRegionId("ap-southeast-1");
              config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com");
              // Connection timeout in milliseconds (ms).
              config.setReadTimeout(6000);
              // Read timeout in milliseconds (ms).
              config.setConnectTimeout(3000);
            
              Client client = new Client(config);
      
              JSONObject serviceParameters = new JSONObject();
              // taskId returned when the task is submitted
              serviceParameters.put("taskId", "fi_f_O5z5i*********-1xxp0V");
      
      
              DescribeFileModerationResultRequest describeFileModerationResultRequest = new DescribeFileModerationResultRequest();
              
              describeFileModerationResultRequest.setService("document_detection_global");
              describeFileModerationResultRequest.setServiceParameters(serviceParameters.toJSONString());
      
              try {
                  DescribeFileModerationResultResponse response = client.describeFileModerationResult(describeFileModerationResultRequest);
                  if (response.getStatusCode() == 200) {
                      DescribeFileModerationResultResponseBody 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()) {
                          DescribeFileModerationResultResponseBody.DescribeFileModerationResultResponseBodyData data = result.getData();
                          System.out.println("pageResult = " + JSON.toJSONString(data.getPageResult()));
                          System.out.println("dataId = " + data.getDataId());
                          System.out.println("url = " + data.getUrl());
                      } else {
                          System.out.println("file moderation result not success. code:" + result.getCode());
                      }
                  } else {
                      System.out.println("response not success. status:" + response.getStatusCode());
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }

Python SDK

This SDK supports Python 3.6 and later.

For the source code, see Python SDK source code.

The SDK supports the following three types of document detection.

Detect publicly accessible documents

Scenarios

If the document that you want to moderate is accessible from the Internet, Document Moderation 2.0 retrieves the file using the document URL and then moderates the file.

  1. You can run the following command to install pip.

    pip install alibabacloud_green20220302==2.2.11

  2. Integrate the Python SDK.

    • Sample code for submitting a document detection task

      # coding=utf-8
      # python version >= 3.6
      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      import json
      
      config = Config(
          # The 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 save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, and this may compromise the security of all resources within your account.
          # Common methods to obtain environment variables:
          # Obtain RAM user AccessKey ID: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
          # Obtain RAM user AccessKey Secret: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          access_key_id='It is recommended to obtain the RAM user AccessKey ID from environment variables',
          access_key_secret='It is recommended to obtain the RAM user AccessKey Secret from environment variables',
          # Connection timeout in milliseconds (ms)
          connect_timeout=10000, 
          # Read timeout in milliseconds (ms) 
          read_timeout=3000,  
          region_id='ap-southeast-1',
          endpoint='green-cip.ap-southeast-1.aliyuncs.com'
      )
      
      clt = Client(config)
      
      serviceParameters = {
          'url': 'https://detect-obj.oss-cn-hangzhou.aliyuncs.com/sample/xxxx.pdf',
      }
      fileModerationRequest = models.FileModerationRequest(
          # Detection type
          service='document_detection_global',
          service_parameters=json.dumps(serviceParameters)
      )
      
      try:
          response = clt.file_moderation(fileModerationRequest)
          if response.status_code == 200:
              # Call 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)
    • Obtain the results of the document detection task

      # coding=utf-8
      # python version >= 3.6
      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      import json
      
      config = Config(
          # The 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 save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, and this may compromise the security of all resources within your account.
          # Common methods to obtain environment variables:
          # Obtain RAM user AccessKey ID: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
          # Obtain RAM user AccessKey Secret: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          access_key_id='It is recommended to obtain the RAM user AccessKey ID from environment variables',
          access_key_secret='It is recommended to obtain the RAM user AccessKey Secret from environment variables',
          # Connection timeout in milliseconds (ms)
          connect_timeout=10000, 
          # Read timeout in milliseconds (ms) 
          read_timeout=3000,  
          region_id='ap-southeast-1',
          endpoint='green-cip.ap-southeast-1.aliyuncs.com'
      )
      
      clt = Client(config)
      
      # taskId returned when the task is submitted
      serviceParameters = {
          "taskId": 'fi_f_11w5THcb*******a-1xx7hH'
      }
      describeFileModerationResultRequest = models.DescribeFileModerationResultRequest(
          # Detection type
          service='document_detection_global',
          service_parameters=json.dumps(serviceParameters)
      )
      
      try:
          response = clt.describe_file_moderation_result(describeFileModerationResultRequest)
          if response.status_code == 200:
              # Call successful
              # Obtain review results
              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)

Detect local documents

Scenarios

If the document that you want to moderate is stored locally and is not accessible from the Internet, you must upload it to an Object Storage Service (OSS) bucket that is provided by Content Moderation. Document Moderation 2.0 then directly accesses OSS to retrieve and moderate the document content.

  1. Run the following command to install pip.

    pip install alibabacloud_green20220302==2.2.11

    Install the OSS SDK:

    pip install oss2
  2. Integrate the Python SDK.

    • Sample code for submitting a document detection task

      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
      
      configs = Config(
          # The 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 save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, and this may compromise the security of all resources within your account.
          # Common methods to obtain environment variables:
          # Obtain RAM user AccessKey ID: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
          # Obtain RAM user AccessKey Secret: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          access_key_id='It is recommended to obtain the RAM user AccessKey ID from environment variables',
          access_key_secret='It is recommended to obtain the RAM user AccessKey Secret from environment variables',
          # Connection timeout in milliseconds (ms).
          connect_timeout=10000,
          # Read timeout in milliseconds (ms).
          read_timeout=10000,
          # Modify the access region and address according to the actual situation.
          region_id='ap-southeast-1',
          endpoint='green-cip.ap-southeast-1.aliyuncs.com'
      )
      # Note: The instantiated client here should be reused as much as possible to avoid repeated connections and improve detection performance.
      client = Client(configs)
      
      bucket = None
      upload_token = None
      
      
      def get_oss_client(is_vpc):
          global upload_token
          global bucket
          if (upload_token == 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 file_moderation_by_local_file(file_path, is_vpc):
          # 1. Upload file
          object_name = upload_file(file_path, is_vpc)
      
          # 2. Detection parameters
          service_parameters = {
              'dataId': str(uuid.uuid4()),
              'ossBucketName': upload_token.bucket_name,
              'ossObjectName': object_name
          }
      
          file_moderation_request = models.FileModerationRequest(
              # Detection type.
              service='document_detection_global',
              service_parameters=json.dumps(service_parameters)
          )
      
          # Create a RuntimeObject instance and set runtime parameters.
          runtime = util_models.RuntimeOptions()
          runtime.read_timeout = 10000
          runtime.connect_timeout = 10000
          try:
              global client
              response = client.file_moderation_with_options(file_moderation_request, runtime)
      
              if response.status_code == 200:
                  # Call successful.
                  # Obtain review results.
                  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__':
          # Local file path
          file_path = '/Users/test/MS.pdf'
          # Whether to deploy on VPC
          is_vpc = False  # True
          file_moderation_by_local_file(file_path, is_vpc)
           
    • Retrieve document detection task results

      # coding=utf-8
      # python version >= 3.6
      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      import json
      
      config = Config(
          # The 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 save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, and this may compromise the security of all resources within your account.
          # Common methods to obtain environment variables:
          # Obtain RAM user AccessKey ID: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
          # Obtain RAM user AccessKey Secret: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          access_key_id='It is recommended to obtain the RAM user AccessKey ID from environment variables',
          access_key_secret='It is recommended to obtain the RAM user AccessKey Secret from environment variables',
          # Connection timeout in milliseconds (ms)
          connect_timeout=10000, 
          # Read timeout in milliseconds (ms) 
          read_timeout=3000,  
          region_id='ap-southeast-1',
          endpoint='green-cip.ap-southeast-1.aliyuncs.com'
      )
      
      clt = Client(config)
      
      # taskId returned when the task is submitted
      serviceParameters = {
          "taskId": 'fi_f_11w5THcb*******a-1xx7hH'
      }
      describeFileModerationResultRequest = models.DescribeFileModerationResultRequest(
          # Detection type
          service='document_detection_global',
          service_parameters=json.dumps(serviceParameters)
      )
      
      try:
          response = clt.describe_file_moderation_result(describeFileModerationResultRequest)
          if response.status_code == 200:
              # Call successful
              # Obtain review results
              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)

Detect OSS documents

Scenario

If the document that you want to moderate is stored in Alibaba Cloud Object Storage Service (OSS), you must create a server role to grant Content Moderation access to OSS. Document Moderation 2.0 retrieves the file from OSS for analysis using this server role. To create a server role, visit the Cloud resource access authorization page.

  1. Run the following command to install pip.

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

    • Sample code for submitting a document detection task

      # coding=utf-8
      # python version >= 3.6
      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      import json
      
      config = Config(
          # The 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 save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, and this may compromise the security of all resources within your account.
          # Common methods to obtain environment variables:
          # Obtain RAM user AccessKey ID: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
          # Obtain RAM user AccessKey Secret: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          access_key_id='It is recommended to obtain the RAM user AccessKey ID from environment variables',
          access_key_secret='It is recommended to obtain the RAM user AccessKey Secret from environment variables',
          # Connection timeout in milliseconds (ms)
          connect_timeout=10000,
          # Read timeout in milliseconds (ms)
          read_timeout=3000,
          region_id='ap-southeast-1',
          endpoint='green-cip.ap-southeast-1.aliyuncs.com'
      )
      
      clt = Client(config)
      
      serviceParameters = {
          'ossRegionId': 'cn-hangzhou',
          'ossBucketName': 'detect-obj',
          'ossObjectName': 'sample/xxxx.pdf'
      }
      fileModerationRequest = models.FileModerationRequest(
          # Detection type
          service='document_detection_global',
          service_parameters=json.dumps(serviceParameters)
      )
      
      try:
          response = clt.file_moderation(fileModerationRequest)
          if response.status_code == 200:
              # Call 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)
          
    • Retrieve document detection task results

      # coding=utf-8
      # python version >= 3.6
      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      import json
      
      config = Config(
          # The 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 save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, and this may compromise the security of all resources within your account.
          # Common methods to obtain environment variables:
          # Obtain RAM user AccessKey ID: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
          # Obtain RAM user AccessKey Secret: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          access_key_id='It is recommended to obtain the RAM user AccessKey ID from environment variables',
          access_key_secret='It is recommended to obtain the RAM user AccessKey Secret from environment variables',
          # Connection timeout in milliseconds (ms)
          connect_timeout=10000, 
          # Read timeout in milliseconds (ms) 
          read_timeout=3000,  
          region_id='ap-southeast-1',
          endpoint='green-cip.ap-southeast-1.aliyuncs.com'
      )
      
      clt = Client(config)
      
      # taskId returned when the task is submitted
      serviceParameters = {
          "taskId": 'fi_f_11w5THcb*******a-1xx7hH'
      }
      describeFileModerationResultRequest = models.DescribeFileModerationResultRequest(
          # Detection type
          service='document_detection_global',
          service_parameters=json.dumps(serviceParameters)
      )
      
      try:
          response = clt.describe_file_moderation_result(describeFileModerationResultRequest)
          if response.status_code == 200:
              # Call successful
              # Obtain review results
              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

This SDK supports PHP 5.6 and later.

For the source code, see PHP SDK source code.

The SDK supports the following three types of document detection.

Detect publicly accessible documents

Scenario

If the document that you want to moderate is accessible from the Internet, Document Moderation 2.0 retrieves the file using the document URL and then moderates the file.

  1. Run the following command to add the dependencies:

    composer require alibabacloud/green-20220302 2.2.10

  2. Integrate the PHP SDK.

    • Sample code for submitting a document detection task

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\FileModerationRequest;
      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([
          /**
           * The 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 save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, and this may compromise the security of all resources within your account.
           * Common methods to obtain environment variables:
           * Obtain the RAM user AccessKey ID: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
           * Obtain the RAM user AccessKey secret: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
           */
          "accessKeyId" => 'It is recommended to obtain the RAM user AccessKey ID from environment variables',
          "accessKeySecret" => 'It is recommended to obtain the RAM user AccessKey secret from environment variables',
          "endpoint" => "green-cip.ap-southeast-1.aliyuncs.com",
          "regionId" => "ap-southeast-1"
      
      ]);
      // Note: Please reuse the instantiated client as much as possible to avoid repeated connections and improve detection performance.
      $client = new Green($config);
      
      $request = new FileModerationRequest();
      $request->service = "document_detection_global";
      $serviceParameters = array("url" => "https://xxx.oss.aliyuncs.com/xxx.pdf");
      
      $request->serviceParameters = json_encode($serviceParameters);
      
      $runtime = new RuntimeOptions();
      $runtime->readTimeout = 6000;
      $runtime->connectTimeout = 3000;
      
      try {
          $response = $client->fileModerationWithOptions($request, $runtime);
          print_r($response->body);
          if (200 != $response->statusCode) {
              print_r("response not success. 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("file moderation not success. 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 the results of a document detection task

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\DescribeFileModerationResultRequest;
      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([
          /**
           * The 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 save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, and this may compromise the security of all resources within your account.
           * Common methods to obtain environment variables:
           * Obtain the RAM user AccessKey ID: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
           * Obtain the RAM user AccessKey secret: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
           */
          "accessKeyId" => 'It is recommended to obtain the RAM user AccessKey ID from environment variables',
          "accessKeySecret" => 'It is recommended to obtain the RAM user AccessKey secret from environment variables',
          "endpoint" => "green-cip.ap-southeast-1.aliyuncs.com",
          "regionId" => "ap-southeast-1"
      
      ]);
      // Note: Please reuse the instantiated client as much as possible to avoid repeated connections and improve detection performance.
      $client = new Green($config);
      
      $request = new DescribeFileModerationResultRequest();
      $request->service = "document_detection_global";
      $serviceParameters = array("taskId" => "fi_f_O5z5iaIis*****NYj7qa-1x****");
      
      $request->serviceParameters = json_encode($serviceParameters);
      
      $runtime = new RuntimeOptions();
      $runtime->readTimeout = 6000;
      $runtime->connectTimeout = 3000;
      
      try {
          $response = $client->describeFileModerationResultWithOptions($request, $runtime);
          if (200 != $response->statusCode) {
              print_r("response not success. 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("processing file moderation. code:" . $body->code);
              return;
          }
          if (200 != $body->code) {
              print_r("file moderation result not success. code:" . $body->code);
              return;
          }
          $data = $body->data;
            print_r("data = " . json_encode($data) . "\n");
          print_r("pageResult = " . json_encode($data->pageResult) . "\n");
      } catch (TeaUnableRetryError $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }

Detect local documents

Scenario

If the document that you want to moderate is stored locally and is not accessible from the Internet, you must upload it to an Object Storage Service (OSS) bucket that is provided by Content Moderation. Document Moderation 2.0 then directly accesses OSS to retrieve and moderate the document content.

  1. Run the following command to add the dependencies:

    composer require alibabacloud/green-20220302 2.2.10

    Install the OSS SDK:

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

    • Sample code for submitting a document detection task

    • Retrieve the results of a document detection task

Detect OSS documents

Scenarios

If the document that you want to moderate is stored in Alibaba Cloud Object Storage Service (OSS), you must create a server role to grant Content Moderation access to OSS. Document Moderation 2.0 retrieves the file from OSS for analysis using this server role. To create a server role, visit the Cloud resource access authorization page.

  1. Run the following command to add the dependencies:

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

    • Sample code for submitting a document detection task

    • Retrieve the results of a document detection task

Go SDK

The SDK supports the following three types of document detection.

Detect publicly accessible documents

Scenario

If the document that you want to moderate is accessible from the Internet, Document Moderation 2.0 retrieves the file using the document URL and then moderates the file.

Go SDK

  1. Run the following command to add the dependencies:

    go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2

  2. Integrate the Go SDK.

    • Sample code for submitting a document detection 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() {
          // Project code leakage may lead to AccessKey leakage and threaten the security of all resources in your account. The following code example is for reference only. It is recommended to use a more secure STS method.
          config := &openapi.Config{
              /**
               * The 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 save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised.
               * Common methods to obtain environment variables:
               * Obtain the RAM user AccessKey ID: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
               * Obtain the RAM user AccessKey secret: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
               */
              AccessKeyId: tea.String("It is recommended to obtain the RAM user AccessKey ID from environment variables"),
              AccessKeySecret: tea.String("It is recommended to obtain the RAM user AccessKey secret from environment variables"),
              RegionId: tea.String("ap-southeast-1"),
              Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"),
              /**
           * Please set the timeout period. The server-side full-link processing timeout is 10 seconds. Please make the corresponding settings.
           * If you set the ReadTimeout to be less than the server-side processing time, the program will receive a ReadTimeout exception.
           */
              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://xxx.oss.aliyuncs.com/xxx.pdf",
              },
          )
          request := green20220302.FileModerationRequest{
              Service:           tea.String("document_detection_global"),
              ServiceParameters: tea.String(string(serviceParameters)),
          }
      
          result, _err := client.FileModerationWithOptions(&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("file moderation not success. code:%d\n", *body.Code)
              return
          }
          
          data := body.Data
          fmt.Printf("file moderation taskId:%s\n", *data.TaskId)
      }
    • Obtain the results of a document detection 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() {
          // Project code leakage may lead to AccessKey leakage and threaten the security of all resources in your account. The following code example is for reference only. It is recommended to use a more secure STS method.
          config := &openapi.Config{
              /**
               * The 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 save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised.
               * Common methods to obtain environment variables:
               * Obtain the RAM user AccessKey ID: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
               * Obtain the RAM user AccessKey secret: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
               */
              AccessKeyId: tea.String("It is recommended to obtain the RAM user AccessKey ID from environment variables"),
              AccessKeySecret: tea.String("It is recommended to obtain the RAM user AccessKey secret from environment variables"),
              RegionId: tea.String("ap-southeast-1"),
              Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"),
              /**
           * Please set the timeout period. The server-side full-link processing timeout is 10 seconds. Please make the corresponding settings.
           * If you set the ReadTimeout to be less than the server-side processing time, the program will receive a ReadTimeout exception.
           */
              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": "fi_f_O5z5iaIi******-1x****",
          },
          )
          request := green20220302.DescribeFileModerationResultRequest{
          Service:           tea.String("document_detection_global"),
          ServiceParameters: tea.String(string(serviceParameters)),
          }
      
          result, _err := client.DescribeFileModerationResultWithOptions(&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("processing file moderation. code:%d\n", *body.Code)
          return
          }
          if *body.Code != http.StatusOK {
          fmt.Printf("file moderation result not success. code:%d\n", *body.Code)
          return
          }
      
          data := body.Data
          fmt.Printf("file moderation result:%s\n", data)
          fmt.Printf("file moderation result pageResult:%s\n", data.PageResult)
          fmt.Printf("file moderation result dataId:%s\n", data.DataId)
      }

Detect local documents

Scenarios

If the document that you want to moderate is stored locally and is not accessible from the Internet, you must upload it to an Object Storage Service (OSS) bucket that is provided by Content Moderation. Document Moderation 2.0 then directly accesses OSS to retrieve and moderate the document content.

  1. Run the following command to add the dependencies:

    go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2

    Install the OSS SDK:

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

    • Sample code for submitting a document detection task

    • Retrieve the results of a document detection task

Detect OSS documents

Scenario

If the document that you want to moderate is stored in Alibaba Cloud Object Storage Service (OSS), you must create a server role to grant Content Moderation access to OSS. Document Moderation 2.0 retrieves the file from OSS for analysis using this server role. To create a server role, visit the Cloud resource access authorization page.

  1. Run the following command to add the dependencies:

    go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2

  2. Integrate the Go SDK.

    • Sample code for submitting a document detection task

    • Retrieve document detection task results

Node.js SDK

For the source code, see Node.js SDK source code.

The SDK supports the following three types of document detection.

Detect publicly accessible documents

Scenarios

If the document that you want to moderate is accessible from the Internet, Document Moderation 2.0 retrieves the file using the document URL and then moderates the file.

  1. Run the following command to add the dependencies:

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

    • Sample code for submitting a document detection task

      Sample code for retrieving document detection task results

Detect local documents

Scenario

If the document that you want to moderate is stored locally and is not accessible from the Internet, you must upload it to an Object Storage Service (OSS) bucket that is provided by Content Moderation. Document Moderation 2.0 then directly accesses OSS to retrieve and moderate the document content.

  1. Run the following command to add the dependencies:

    npm install @alicloud/green20220302@2.2.10

    Install the OSS SDK:

    npm install ali-oss --save
  2. Integrate the Node.js SDK.

    • Sample code for submitting a document detection task

      Sample code for retrieving document detection task results

Detect OSS documents

Scenarios

If the document that you want to moderate is stored in Alibaba Cloud Object Storage Service (OSS), you must create a server role to grant Content Moderation access to OSS. Document Moderation 2.0 retrieves the file from OSS for analysis using this server role. To create a server role, visit the Cloud resource access authorization page.

  1. Run the following command to add the dependencies:

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

    • Sample code for submitting a document detection task

      Sample code for retrieving document detection task results

C# SDK

For the source code, see C# SDK source code.

The SDK supports the following three types of document detection.

Detect publicly accessible documents

Scenarios

If the document that you want to moderate is accessible from the Internet, Document Moderation 2.0 retrieves the file using the document URL and then moderates the file.

  1. Run the following command to add the dependencies:

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

    • Sample code for submitting a document detection task

    • Sample code for retrieving document detection task results

Detect local documents

Scenario

If the document that you want to moderate is stored locally and is not accessible from the Internet, you must upload it to an Object Storage Service (OSS) bucket that is provided by Content Moderation. Document Moderation 2.0 then directly accesses OSS to retrieve and moderate the document content.

  1. Run the following command to add the dependencies:

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

    Install the OSS SDK:

    Install via NuGet 
    1. If your Visual Studio does not have NuGet installed, install NuGet first.
    2. In Visual Studio, create a new project or open an existing one, and select Tools > NuGet Package Manager > Manage NuGet Packages for Solution.
    3. Search for aliyun.oss.sdk, find Aliyun.OSS.SDK (for .NET Framework) or Aliyun.OSS.SDK.NetCore (for .Net Core) in the results, select the latest version, and click Install.
  2. Integrate the C# SDK.

    • Sample code for submitting a document detection task

    • Sample code for retrieving document detection task results

Detect OSS documents

Scenarios

If the document that you want to moderate is stored in Alibaba Cloud Object Storage Service (OSS), you must create a server role to grant Content Moderation access to OSS. Document Moderation 2.0 retrieves the file from OSS for analysis using this server role. To create a server role, visit the Cloud resource access authorization page.

  1. Run the following command to add the dependencies:

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

    • Sample code for submitting a document detection task

    • Sample code for retrieving document detection task results

Native HTTPS calls

  • Call method

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

    Protocol: HTTPS

    Method: POST

  • Common request parameters

    The input parameters for the Document Moderation enhanced edition API include common request parameters and API-specific operation parameters. Common request parameters are required for every API operation. The following table describes the common request parameters.

    Name

    Type

    Required

    Description

    Format

    String

    Yes

    The format of the response. Valid values:

    • JSON (default)

    • XML

    Version

    String

    Yes

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

    AccessKeyId

    String

    Yes

    The AccessKey ID issued by Alibaba Cloud to a user for service access.

    Signature

    String

    Yes

    The signature string. For information about how to calculate the signature, see the signature method below.

    SignatureMethod

    String

    Yes

    The signature method. HMAC-SHA1 is supported.

    Timestamp

    String

    Yes

    The timestamp of the request. The date format follows the ISO 8601 standard and must be in UTC.

    The timestamp of the request. The date format must follow the ISO 8601 standard and use UTC. The format is 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 used to prevent replay attacks. Use a different random number for each request.

    Action

    String

    Yes

    Valid values:

    • FileModeration

    • DescribeFileModerationResult

  • Common response parameters

    For each API call, the system returns a unique request ID (RequestId), regardless of whether the call is successful. Other response parameters vary based on the API operation that you call.

    {
        "Msg": "OK",
        "Code": 200,
        "Data":
        {
            "TaskId": "AAAAA-BBBBB-CCCCCCCC"
        },
        "RequestId": "ABCD1234-1234-1234-1234-123****"
    }
  • Code examples

    The following response examples are formatted for readability. The actual responses are not formatted with line breaks or indents.

    • Example of a moderation task

      Sample request

      Sample response

      {
          "Msg": "OK",
          "Code": 200,
          "Data":
          {
              "TaskId": "AAAAA-BBBBB-CCCCCCCC"
          },
          "RequestId": "ABCD1234-1234-1234-1234-123****"
      }
    • Example of a query task

      Sample request

      Sample response

      {
          "Code": 200,
          "Data": {
              "DataId": "fileId*****",
              "PageResult": [
                  {
                      "ImageResult": [
                          {
                              "Description": "Image content moderation of the document page",
                              "LabelResult": [
                                  {
                                      "label": "nonLabel"
                                  }
                              ],
                              "Service": "baselineCheck"
                          }
                      ],
                      "ImageUrl": "http://oss.aliyundoc.com/a.png",
                      "PageNum": 1,
                      "TextResult": [
                          {
                              "Description": "Text content moderation of the document page",
                              "Labels": "",
                              "RiskTips": "",
                              "RiskWords": "",
                              "Service": "pgc_detection",
                              "Text": "Content Moderation product test case a"
                          }
                      ]
                  },
                  ...
                  {
                      "ImageResult": [
                          {
                              "Description": "Image content moderation of the document page",
                              "LabelResult": [
                                  {
                                      "Confidence": 89.01,
                                      "Label": "pornographic_adultContent_tii"
                                  }
                              ],
                              "Service": "baselineCheck"
                          }
                      ],
                      "ImageUrl": "http://oss.aliyundoc.com/b.png",
                      "PageNum": 10,
                      "TextResult": [
                          {
                              "Description": "Text content moderation of the document page",
                              "Labels": "contraband,sexual_content",
                              "RiskTips": "prohibited_prohibited_goods,sexual_films,sexual_vulgar",
                              "RiskWords": "risk word A,risk word B",
                              "Service": "ad_compliance_detection",
                              "Text": "Content Moderation product test case b"
                          }
                      ]
                  }
              ],
              "Url": "http://www.aliyundoc.com/a.docx"
          },
          "Message": "SUCCESS",
          "RequestId": "1D0854A7-AAAAA-BBBBBBB-CC8292AE5"
      }
  • Signature method

    The Document Moderation enhanced edition service authenticates every request. Therefore, you must include signature information in each request. The service uses symmetric encryption with an AccessKey ID and an AccessKey secret to verify the identity of the request sender.

    The AccessKey ID and AccessKey secret are issued by Alibaba Cloud. You can apply for and manage them on the Alibaba Cloud website. The AccessKey ID identifies the user. The AccessKey secret is used to encrypt the signature string and verify the signature string on the server. The AccessKey secret must be kept confidential.

    To sign a request, perform the following steps:

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

      1. Sort all request parameters alphabetically by parameter name. The request parameters include common and API-specific parameters but exclude the Signature parameter.

      2. URL-encode the name and value of each request parameter in UTF-8.

        Note

        URL encoding libraries, such as java.net.URLEncoder in Java, typically follow the rules of the application/x-www-form-urlencoded MIME type. You can use these libraries for encoding. To obtain the required format, you must replace the plus sign (+) with %20, the asterisk (*) with %2A, and %7E with a tilde (~) in the encoded string.

        The URL encoding rules are as follows:

        • Do not encode uppercase letters, lowercase letters, digits, and the following characters: hyphen (-), underscore (_), period (.), and tilde (~).

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

        • Encode extended UTF-8 characters into the %XY%ZA… format.

        • Encode a space as %20, not a plus sign (+).

      3. Connect the encoded parameter name and its value with an equal sign (=).

      4. Connect the resulting strings with ampersands (&) in the sorted order to create the canonicalized query string.

    2. Use the normalized string from Step a.i to create the string to sign according to the following rules:

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

      HTTPMethod is the HTTP method used for the request, such as POST. percentEncode("/") is the URL-encoded value of a forward slash (/), which is %2F. percentEncode(CanonicalizedQueryString) is the URL-encoded canonicalized query string that you constructed in the previous step.

    3. Calculate the HMAC value of the string-to-sign as defined in RFC 2104.

      Note

      The key for calculating the signature is your AccessKey secret followed by an & character (ASCII code 38). The SHA1 hash algorithm is used.

    4. Encode the HMAC value in Base64 to obtain the signature.

    5. Add the signature as the Signature parameter to the request to complete the signing process.

      Note

      When you submit the signature to the Content Moderation server, it must be URL-encoded based on RFC 3986, similar to other parameters.