Enhanced manual review SDK

Updated at:

You can integrate with human review Enhanced Edition using an SDK or native HTTPS calls. We recommend using the SDK because it handles details such as signature verification and request body construction. This topic explains how to integrate with human review Enhanced Edition.

Step 1: Enable the service

Enable the human review service on the Enable Human Review 2.0 page. Billing starts automatically based on your usage after you begin making API calls. For more information, see pricing details.

After you enable the Human Review 2.0 service, the default billing method is pay-as-you-go. You are charged daily based on your actual usage. If you do not call the service, you are not charged.

Step 2: Authorize a RAM user

Before you integrate with an SDK or API, you need to grant permissions to a RAM user. You can create an AccessKey for the RAM user. You must use the AccessKey for authentication when you call Alibaba Cloud APIs. For instructions on how to obtain an AccessKey, see Obtain an AccessKey.

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 the manual review service

This service is available in the following region:

Region

Public endpoint

Internal endpoint

China (Shanghai)

green-cip.cn-shanghai.aliyuncs.com

green-cip-vpc.cn-shanghai.aliyuncs.com

Note

To get SDK sample code for other languages, use the OpenAPI Portal to debug APIs. The portal automatically generates the required sample code. The following APIs can be debugged online:

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.

See the Asynchronous Detection API for Enhanced Manual Review for API field descriptions.

Java SDK

This SDK supports Java 1.8 and later versions.

For the source code, see Java SDK source code.

Provide the URL of the image, audio, or video to be moderated. For text, provide the content directly.

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

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

    • Sample code to submit a manual moderation task

      import com.alibaba.fastjson.JSON;
      import com.alibaba.fastjson.JSONObject;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.ManualModerationRequest;
      import com.aliyun.green20220302.models.ManualModerationResponse;
      import com.aliyun.green20220302.models.ManualModerationResponseBody;
      import com.aliyun.teaopenapi.models.Config;
      
      
      public class ManualModerationDemo {
      
          public static void main(String[] args) throws Exception {
              Config config = new Config();
             /**
               * The AccessKey pair of an Alibaba Cloud account grants full access to all APIs. We recommend that you use a RAM user for API calls and routine O&M.
               * Common ways to obtain environment variables:
               * Method 1:
               *     Get RAM user's AccessKey ID: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Get RAM user's AccessKey Secret: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Get RAM user's AccessKey ID: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Get RAM user's AccessKey Secret: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              config.setAccessKeyId("We recommend that you retrieve the AccessKey ID of a RAM user from an environment variable.");
              config.setAccessKeySecret("We recommend that you retrieve the AccessKey Secret of a RAM user from an environment variable.");
              // Modify 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);
              // 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();
              // Use the 'url' parameter for images, audio, and video.
              serviceParameters.put("url", "https://img.alicdn.com/tfs/TB1U4r9AeH2gK0jSZJnXXaT1FXa-2880-480.png");
              // For text moderation, use the 'content' parameter.
              //serviceParameters.put("content", "Text content to be moderated.");
              ManualModerationRequest manualModerationRequest = new ManualModerationRequest();
              // Moderation type. Valid values: imageManualCheck, longTextManualCheck, voiceFileManualCheck, and videoFileManualCheck.
              manualModerationRequest.setService("imageManualCheck");
              manualModerationRequest.setServiceParameters(serviceParameters.toJSONString());
      
              try {
                  ManualModerationResponse response = client.manualModeration(manualModerationRequest);
                  if (response.getStatusCode() == 200) {
                      ManualModerationResponseBody 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) {
                          ManualModerationResponseBody.ManualModerationResponseBodyData data = result.getData();
                          System.out.println("taskId = [" + data.getTaskId() + "]");
                      } else {
                          System.out.println("manual moderation not success. code:" + code);
                      }
                  } else {
                      System.out.println("response not success. status:" + response.getStatusCode());
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }
    • Sample code to query a manual moderation task

      import com.alibaba.fastjson.JSON;
      import com.alibaba.fastjson.JSONObject;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.ManualModerationResultRequest;
      import com.aliyun.green20220302.models.ManualModerationResultResponse;
      import com.aliyun.green20220302.models.ManualModerationResultResponseBody;
      import com.aliyun.teaopenapi.models.Config;
      
      public class ManualModerationResultDemo {
      
          public static void main(String[] args) throws Exception {
              Config config = new Config();
              /**
               * The AccessKey pair of an Alibaba Cloud account grants full access to all APIs. We recommend that you use a RAM user for API calls and routine O&M.
               * Common ways to obtain environment variables:
               * Method 1:
               *     Get RAM user's AccessKey ID: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Get RAM user's AccessKey Secret: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Get RAM user's AccessKey ID: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Get RAM user's AccessKey Secret: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              config.setAccessKeyId("We recommend that you retrieve the AccessKey ID of a RAM user from an environment variable.");
              config.setAccessKeySecret("We recommend that you retrieve the AccessKey Secret of a RAM user from an environment variable.");
              // Modify 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);
              // 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 taskId returned when you submitted the task.
              serviceParameters.put("taskId", "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****");
      
      
              ManualModerationResultRequest manualModerationResultRequest = new ManualModerationResultRequest();
              manualModerationResultRequest.setServiceParameters(serviceParameters.toJSONString());
      
              try {
                  ManualModerationResultResponse response = client.manualModerationResult(manualModerationResultRequest);
                  if (response.getStatusCode() == 200) {
                      ManualModerationResultResponseBody 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()) {
                          ManualModerationResultResponseBody.ManualModerationResultResponseBodyData data = result.getData();
                          System.out.println(JSON.toJSONString(data));
                      } else {
                          System.out.println("manual 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 versions.

For the source code, see Python SDK source code.

Provide the URL of the image, audio, or video to be moderated. For text, provide the content directly.

  1. Run the following command to install the dependency.

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

    • Sample code to submit a manual moderation task

      #encoding: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 grants full access to all APIs. We recommend that you use a RAM user for API calls and routine O&M.
                  # We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your code. Otherwise, the AccessKey pair may be leaked, compromising the security of all your resources.
                  # Common ways to obtain environment variables:
                  # Get RAM user's AccessKey ID: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
                  # Get RAM user's AccessKey Secret: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
                  access_key_id='We recommend that you retrieve the AccessKey ID of a RAM user from an environment variable.',
                  access_key_secret='We recommend that you retrieve the AccessKey Secret of a RAM user from an environment variable.',
                  # The connection timeout in milliseconds (ms).
                  connect_timeout=3000,
                  # The read timeout in milliseconds (ms).
                  read_timeout=6000,
                  # Modify the region and endpoint based on your actual requirements.
                  region_id='cn-shanghai',
                  endpoint='green-cip.cn-shanghai.aliyuncs.com'
      )
      
      clt = Client(config)
      # For text moderation, replace the 'url' parameter with 'content'.
      serviceParameters = {
          'url': 'https://img.alicdn.com/tfs/TB1U4r9AeH2gK0jSZJnXXaT1FXa-2880-480.png'
      }
      ManualModerationRequest = models.ManualModerationRequest(
          # Moderation type. Valid values: imageManualCheck, longTextManualCheck, voiceFileManualCheck, and videoFileManualCheck.
          service='imageManualCheck',
          service_parameters=json.dumps(serviceParameters)
      )
      
      try:
          response = clt.manual_moderation_with_options(ManualModerationRequest)
          if response.status_code == 200:
              # The call was successful.
              # Get 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 to query the result of a manual moderation 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 grants full access to all APIs. We recommend that you use a RAM user for API calls and routine O&M.
                  # We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your code. Otherwise, the AccessKey pair may be leaked, compromising the security of all your resources.
                  # Common ways to obtain environment variables:
                  # Get RAM user's AccessKey ID: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
                  # Get RAM user's AccessKey Secret: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
                  access_key_id='We recommend that you retrieve the AccessKey ID of a RAM user from an environment variable.',
                  access_key_secret='We recommend that you retrieve the AccessKey Secret of a RAM user from an environment variable.',
                  # The connection timeout in milliseconds (ms).
                  connect_timeout=3000,
                  # The read timeout in milliseconds (ms).
                  read_timeout=6000,
                  # Modify the region and endpoint based on your actual requirements.
                  region_id='cn-shanghai',
                  endpoint='green-cip.cn-shanghai.aliyuncs.com'
      )
      
      clt = Client(config)
      
      # The taskId returned when you submitted the task.
      serviceParameters = {
          "taskId": 'vi_f_11w5THcbVYctjdxz2C0Afa-1x****'
      }
      ManualModerationResultRequest = models.ManualModerationResultRequest(
          service_parameters=json.dumps(serviceParameters)
      )
      
      try:
          response = clt.manual_moderation_result_with_options(ManualModerationResultRequest)
          if response.status_code == 200:
              # The call was successful.
              # Get 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)

PHP SDK

This SDK supports PHP 5.6 and later versions.

For the source code, see PHP SDK source code.

Provide the URL of the image, audio, or video to be moderated. For text, provide the content directly.

  1. Run the following command to install the dependency.

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

    • Sample code to submit a manual moderation task

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\ManualModerationRequest;
      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 grants full access to all APIs. We recommend that you use a RAM user for API calls and routine O&M.
           * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your code. Otherwise, the AccessKey pair may be leaked, compromising the security of all your resources.
           * Common ways to obtain environment variables:
           * Get RAM user's AccessKey ID: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
           * Get RAM user's AccessKey Secret: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
           */
          "accessKeyId" => 'We recommend that you retrieve the AccessKey ID of a RAM user from an environment variable.',
          "accessKeySecret" => 'We recommend that you retrieve the AccessKey Secret of a RAM user from an environment variable.',
          // Set the HTTP proxy.
          // "httpProxy" => "http://10.10.xx.xx:xxxx",
          // Set the HTTPS proxy.
          // "httpsProxy" => "https://10.10.xx.xx:xxxx",
          "endpoint" => "green-cip.cn-shanghai.aliyuncs.com",
          "regionId" => "cn-shanghai"
      
      ]);
      // Note: To improve performance, reuse the client instance whenever possible and avoid creating a new connection for each request.
      $client = new Green($config);
      
      $request = new ManualModerationRequest();
      // Moderation type. Valid values: imageManualCheck, longTextManualCheck, voiceFileManualCheck, and videoFileManualCheck.
      $request->service = "imageManualCheck";
      // For text moderation, replace the 'url' parameter with 'content'.
      $serviceParameters = array("url" => "https://img.alicdn.com/tfs/TB1U4r9AeH2gK0jSZJnXXaT1FXa-2880-480.png");
      
      $request->serviceParameters = json_encode($serviceParameters);
      
      $runtime = new RuntimeOptions();
      $runtime->readTimeout = 6000;
      $runtime->connectTimeout = 3000;
      
      try {
          $response = $client->ManualModerationWithOptions($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("manual 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());
      }
    • Sample code to query a manual moderation task

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\ManualModerationResultRequest;
      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 grants full access to all APIs. We recommend that you use a RAM user for API calls and routine O&M.
           * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your code. Otherwise, the AccessKey pair may be leaked, compromising the security of all your resources.
           * Common ways to obtain environment variables:
           * Get RAM user's AccessKey ID: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
           * Get RAM user's AccessKey Secret: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
           */
          "accessKeyId" => 'We recommend that you retrieve the AccessKey ID of a RAM user from an environment variable.',
          "accessKeySecret" => 'We recommend that you retrieve the AccessKey Secret of a RAM user from an environment variable.',
          // Set the HTTP proxy.
          // "httpProxy" => "http://10.10.xx.xx:xxxx",
          // Set the HTTPS proxy.
          // "httpsProxy" => "https://10.10.xx.xx:xxxx",
          "endpoint" => "green-cip.cn-shanghai.aliyuncs.com",
          "regionId" => "cn-shanghai"
      
      ]);
      // Note: To improve performance, reuse the client instance whenever possible and avoid creating a new connection for each request.
      $client = new Green($config);
      
      $request = new ManualModerationResultRequest();
      // The ID of the moderation task to query.
      $serviceParameters = array("taskId" => "m_tx_ykVhOxKfGbV12dwg1b4IBX-*******");
      
      $request->serviceParameters = json_encode($serviceParameters);
      
      $runtime = new RuntimeOptions();
      $runtime->readTimeout = 6000;
      $runtime->connectTimeout = 3000;
      
      try {
          $response = $client->ManualModerationResultWithOptions($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("manual moderation not success. code:" . $body->code);
          }
          print_r(json_encode($body->data, JSON_UNESCAPED_UNICODE));
      } catch (TeaUnableRetryError $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }

Go SDK

This SDK supports Go 1.12 and later versions.

Provide the URL of the image, audio, or video to be moderated. For text, provide the content directly.

  1. Run the following command to install the dependency.

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

    • Sample code to submit a manual 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() {
          // Hard-coding your AccessKey pair in your code can expose them, compromising the security of your resources. The following code is for reference only. We recommend using a more secure method, such as STS.
          config := &openapi.Config{
              /**
               * The AccessKey pair of an Alibaba Cloud account grants full access to all APIs. We recommend that you use a RAM user for API calls and routine O&M.
               * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your code.
               * Common ways to obtain environment variables:
               * Get RAM user's AccessKey ID: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
               * Get RAM user's AccessKey Secret: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
               */
              AccessKeyId: tea.String("We recommend that you retrieve the AccessKey ID of a RAM user from an environment variable."),
              AccessKeySecret: tea.String("We recommend that you retrieve the AccessKey Secret of a RAM user from an environment variable."),
              // 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. The server's end-to-end processing timeout is 10 seconds. Configure your settings accordingly.
      		 * If the ReadTimeout you set 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 RuntimeObject instance and set runtime parameters.
          runtime := &util.RuntimeOptions{}
          runtime.ReadTimeout = tea.Int(10000)
          runtime.ConnectTimeout = tea.Int(10000)
          // For text moderation, replace the 'url' parameter with 'content'.
          serviceParameters, _ := json.Marshal(
              map[string]interface{}{
                  "url": "https://img.alicdn.com/tfs/TB1U4r9AeH2gK0jSZJnXXaT1FXa-2880-480.png",
              },
          )
          request := green20220302.ManualModerationRequest{
              // Moderation type. Valid values: imageManualCheck, longTextManualCheck, voiceFileManualCheck, and videoFileManualCheck.
              Service:           tea.String("imageManualCheck"),
              ServiceParameters: tea.String(string(serviceParameters)),
          }
      
          result, _err := client.ManualModerationWithOptions(&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("manual moderation not success. code:%d\n", *body.Code)
              return
          }
          
          data := body.Data
          fmt.Printf("manual moderation taskId:%s\n", *data.TaskId)
      }
    • Sample code to query the result of a manual 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() {
      	// Hard-coding your AccessKey pair in your code can expose them, compromising the security of your resources. The following code is for reference only. We recommend using a more secure method, such as STS.
      	config := &openapi.Config{
      		/**
      		 * The AccessKey pair of an Alibaba Cloud account grants full access to all APIs. We recommend that you use a RAM user for API calls and routine O&M.
      		 * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your code.
      		 * Common ways to obtain environment variables:
      		 * Get RAM user's AccessKey ID: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
      		 * Get RAM user's AccessKey Secret: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
      		 */
      		AccessKeyId: tea.String("We recommend that you retrieve the AccessKey ID of a RAM user from an environment variable."),
      		AccessKeySecret: tea.String("We recommend that you retrieve the AccessKey Secret of a RAM user from an environment variable."),
      		// 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. The server's end-to-end processing timeout is 10 seconds. Configure your settings accordingly.
      		 * If the ReadTimeout you set 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 RuntimeObject instance and set runtime parameters.
      	runtime := &util.RuntimeOptions{}
      	runtime.ReadTimeout = tea.Int(10000)
      	runtime.ConnectTimeout = tea.Int(10000)
      	// The ID of the task to query.
      	serviceParameters, _ := json.Marshal(
      		map[string]interface{}{
      			"taskId": "<The ID of the task to query>",
      		},
      	)
      	request := green20220302.ManualModerationResultRequest{
      		ServiceParameters: tea.String(string(serviceParameters)),
      	}
      
      	result, _err := client.ManualModerationResultWithOptions(&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("manual moderation not success. code:%d\n", *body.Code)
      		return
      	}
      
      	data := body.Data
      	fmt.Printf("manual moderation result" + data.String())
      }

C# SDK

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

Provide the URL of the image, audio, or video to be moderated. For text, provide the content directly.

  1. Run the following command to install the dependency.

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

    • Sample code to submit a manual moderation task

      using Newtonsoft.Json;
      using Tea;
      
      namespace AlibabaCloud.SDK.Sample
      {
          public class Sample
          {
      
              /**
               * Initializes the client with an AccessKey ID and an AccessKey Secret.
               * @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)
              {
                  // Hard-coding your AccessKey pair in your code can expose them, compromising the security of your resources. The following code is for reference only. We recommend using a more secure method, such as STS.
                  /**
                  * The AccessKey pair of an Alibaba Cloud account grants full access to all APIs. We recommend that you use a RAM user for API calls and routine O&M.
                  * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your code.
                  * Common ways to obtain environment variables:
                  * Get RAM user's AccessKey ID: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * Get RAM user's AccessKey Secret: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  string accessKeyId = "We recommend that you retrieve the AccessKey ID of a RAM user from an environment variable.";
                  string accessKeySecret = "We recommend that you retrieve the AccessKey Secret of a RAM user from an environment variable.";
                  // Note: To improve performance, reuse the client instance whenever possible and avoid creating a new connection for each request.
                  AlibabaCloud.SDK.Green20220302.Client client = CreateClient(accessKeyId, accessKeySecret);
                  // Construct the moderation request.
                  AlibabaCloud.SDK.Green20220302.Models.ManualModerationRequest ManualModerationRequest = new AlibabaCloud.SDK.Green20220302.Models.ManualModerationRequest();
                  // Moderation type. Valid values: imageManualCheck, longTextManualCheck, voiceFileManualCheck, and videoFileManualCheck.
                  ManualModerationRequest.Service="imageManualCheck";
                  Dictionary<String,Object> task=new Dictionary<string, object>();
                  // For text moderation, replace the 'url' parameter with 'content'.
                  task.Add("url","https://img.alicdn.com/tfs/TB1U4r9AeH2gK0jSZJnXXaT1FXa-2880-480.png");
                  ManualModerationRequest.ServiceParameters=JsonConvert.SerializeObject(task);
                  // Create a RuntimeObject 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.ManualModerationResponse response= client.ManualModerationWithOptions(ManualModerationRequest, 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)
                  {
                      // Print the error if necessary.
                      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 necessary.
                      AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
                      Console.WriteLine("error : " + error);
                  }
              }
          }
      }
    • Sample code to query the result of a manual moderation task

      using Newtonsoft.Json;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class ManualModerationRequestDemo
          {
              public static void Main(string[] args)
              {
                  /**
                  * The AccessKey pair of an Alibaba Cloud account grants full access to all APIs. We recommend that you use a RAM user for API calls and routine O&M.
                  * We strongly recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your code. Otherwise, the AccessKey pair may be leaked, compromising the security of all your resources.
                  * Common ways to obtain environment variables:
                  * Get RAM user's AccessKey ID: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * Get RAM user's AccessKey Secret: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  String accessKeyId = "We recommend that you retrieve the AccessKey ID of a RAM user from an environment variable.";
                  String accessKeySecret = "We recommend that you retrieve the AccessKey Secret of a RAM user from an environment variable.";
                  // Modify the region and endpoint based on your actual requirements.
                  String endpoint = "green-cip.cn-shanghai.aliyuncs.com";
                  //Note: To improve performance, reuse the client instance whenever possible and avoid creating a new connection for each request.
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  // Runtime parameter settings are valid only for requests that use this RuntimeOptions instance.
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
      
                  Models.ManualModerationResultRequest manualModerationResultRequest =
                      new Models.ManualModerationResultRequest();
                  Dictionary<String,Object> task=new Dictionary<string, object>();
                  // The ID of the task to query.
                  task.Add("taskId","<The ID of the task to query>");
                  manualModerationResultRequest.ServiceParameters = JsonConvert.SerializeObject(task);
      
                  try
                  {
                      // Get the moderation result.
                      Models.ManualModerationResultResponse response = client.ManualModerationResultWithOptions(
                          manualModerationResultRequest,
                          runtimeOptions
                      );
      
                      Console.WriteLine(response.Body.RequestId);
                      Console.WriteLine(JsonConvert.SerializeObject(response.Body));
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                  }
              }
      
              //Create the request 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,
                          //Set the HTTP proxy.
                          //HttpProxy = "http://10.10.xx.xx:xxxx",
                          //Set the HTTPS proxy.
                          //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          //The endpoint of the service.
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
          }
      }

Node.js SDK

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

Provide the URL of the image, audio, or video to be moderated. For text, provide the content directly.

  1. Run the following command to install the dependency.

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

    • Sample code to submit a manual 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 whenever possible and avoid creating a new connection for each request.
      // Hard-coding your AccessKey pair in your code can expose them, compromising the security of your resources. The following 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 set.
                  accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
                  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 a request object.
              const ManualModerationRequest = new Green20220302.ManualModerationRequest({
                  // Moderation type. Valid values: imageManualCheck, longTextManualCheck, voiceFileManualCheck, and videoFileManualCheck.
                  "service": "imageManualCheck",
                  // For text moderation, replace the 'url' parameter with 'content'.
                  "serviceParameters": JSON.stringify({"url":"http://aliyundoc.com/test.flv"})
              });
              // Create a runtime configuration object.
              const runtime = new Util.RuntimeOptions();
              try {
                  // Send the request and get the response.
                  const response = await client.ManualModerationWithOptions(ManualModerationRequest, runtime);
                  console.log(JSON.stringify(response.body));
              } catch (error) {
                  // In a production environment, implement proper exception handling.
                  // Log the error message.
                  console.log('Error occurred:', error.message);
              }
          }
      }
      
      Client.main();
    • Sample code to query the result of a manual 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 whenever possible and avoid creating a new connection for each request.
      // Hard-coding your AccessKey pair in your code can expose them, compromising the security of your resources. The following 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 set.
                  accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
                  // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set.
                  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 a request object.
              const ManualModerationResultRequest = new Green20220302.ManualModerationResultRequest({
                  "serviceParameters": JSON.stringify({"taskId":"<The ID of the task to query>"})
              });
              // Create a runtime configuration object.
              const runtime = new Util.RuntimeOptions();
              try {
                  // Send the request and get the response.
                  const response = await client.ManualModerationResultWithOptions(ManualModerationResultRequest, runtime);
                  console.log(JSON.stringify(response.body));
              } catch (error) {
                  // In a production environment, implement proper exception handling.
                  // Log the error message.
                  console.log('Error occurred:', error.message);
              }
          }
      }
      
      Client.main();

Native HTTPS call

  • Request details

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

    Protocol: HTTPS

    Method: POST

  • Common request parameters

    The Enhanced Manual Moderation API requires both common request parameters and operation-specific parameters. The common request parameters, described in the table below, are required for every API call.

    Parameter

    Type

    Required

    Description

    Format

    String

    Yes

    The format of the response. Valid values:

    • JSON (default)

    • XML

    Version

    String

    Yes

    The API version. The value is in the YYYY-MM-DD format. Current version: 2022-03-02.

    AccessKeyId

    String

    Yes

    Your Alibaba Cloud AccessKey ID.

    Signature

    String

    Yes

    The signature string. For details on how to calculate it, see the Signature method section.

    SignatureMethod

    String

    Yes

    The signature method. Only HMAC-SHA1 is supported.

    Timestamp

    String

    Yes

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

    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 nonce to prevent replay attacks. You must use a different nonce for each request.

    Action

    String

    Yes

    Valid values:

    • ManualModeration

    • ManualModerationResult

    • ManualModerationCancel

  • Common response parameters

    Every API response, successful or not, includes a unique request ID (RequestId). Other response parameters depend on the specific API operation.

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

    The following samples are formatted for readability. Actual responses do not contain line breaks or indentation.

    • Example for submitting a moderation task

      Request example

      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=ManualModeration
      &AccessKeyId=123****cip
      &Timestamp=2023-02-03T12:00:00Z
      &Service=imageManualCheck
      &ServiceParameters={"url": "https://img.alicdn.com/tfs/TB1U4r9AeH2gK0jSZJnXXaT1FXa-2880-480.png"}

      Sample successful response

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

      Request example

      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=ManualModerationResult
      &AccessKeyId=123****cip
      &Timestamp=2023-02-03T12:00:00Z
      &ServiceParameters={"taskId": "vi_f_O5zxxxxxxxxxxxxxxxx-1x****"}

      Sample successful response

      {
          "Msg": "success",
          "Code": 200,
          "Data": {
              "DataId": "img123****",
              "TaskId": "TASK1234-1234-1234-1234-123***",
              "Result": [
                  {
                      "Label": "porn",
                      "Description": "pornographic content"
                  }
              ],
              "RiskLevel": "high"
          },
          "RequestId": "ABCD1234-1234-1234-1234-123****"
      }
  • Signature method

    The Enhanced Manual Moderation service authenticates every request. Therefore, each request must include a signature. The service uses an AccessKey ID and AccessKey Secret for symmetric encryption to verify the sender's identity.

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

    To sign a request, follow these steps:

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

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

      2. URL-encode the names and values of the request parameters using the UTF-8 character set.

        Note

        Most URL encoding libraries, such as java.net.URLEncoder, follow application/x-www-form-urlencoded rules. If you use one, you must manually replace plus signs (+) with %20, asterisks (*) with %2A, and %7E with tildes (~) to achieve the required encoding.

        The URL encoding rules are as follows:

        • Do not encode the following characters: A-Z, a-z, 0-9, hyphen (-), underscore (_), period (.), and tilde (~).

        • Other characters are encoded into the %XY format, where XY is the two-digit hexadecimal representation of the character's ASCII value. For example, a double quotation mark (") is encoded as %22.

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

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

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

      4. Connect the resulting key-value pair strings with ampersands (&) in the lexicographical order of the parameter names to form the canonicalized query string.

    2. Use the canonicalized query string from the previous step to create the string-to-sign according to the following rules:

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

      HTTPMethod is the HTTP method used to submit the request, such as POST. percentEncode(/) is the value obtained by encoding the / character according to the URL encoding rules described in section a.ii, which is %2F. percentEncode(CanonicalQueryString) is the string obtained by encoding the canonicalized query string constructed in section a.i according to the URL encoding rules described in section a.ii.

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

      Note

      Note: The key used for signature calculation is your AccessKey Secret with an & character (ASCII: 38) appended. The hashing 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

      When you submit the signature value to the Content Moderation server, it must be URL-encoded according to RFC 3986, just like any other parameter.