Moderation Agent service SDK integration

Updated at:

The Moderation Agent supports SDK-based calls and native HTTPS calls. We recommend that you use an SDK to connect to the service, which spares you the details of signature verification and request body construction. This topic describes the SDKs for the Moderation Agent service and how to connect to the service by using an SDK.

Step 1: Activate the service

Go to the Activate the service page to activate the Content Moderation Enhanced Edition service.

After you activate the Content Moderation Enhanced Edition service, the pay-as-you-go billing method is used by default. Fees incurred on the current day are settled based on your actual usage, and no fee is charged if you do not call the service. After the service is connected and used, the system automatically generates bills based on your usage. For more information, see Billing.

Step 2: Create a RAM user and grant permissions

To integrate an SDK, you must create a user identity, obtain its AccessKey, and grant it permissions to access cloud resources. This topic describes how to create a RAM user, obtain an AccessKey, and grant permissions to call the image detection service of Content Moderation 2.0. For more information, see Integrate an SDK.

  1. Log in to the RAM console with your Alibaba Cloud account (root account) or a RAM user that has administrative permissions.

  2. Create a RAM user, select OpenAPI Call Access, and record the AccessKey generated for the RAM user. For more information, see Create a RAM user.

  3. Grant the AliyunYundunGreenWebFullAccess system policy to the RAM user. For more information, see Manage RAM user permissions.

Step 3: Install and integrate the SDK

The following regions are supported:

Region

Public endpoint

Internal endpoint

China (Shanghai)

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

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

Note

If you need SDK sample code in other programming languages, you can use the online debugging tool of the OpenAPI Developer Portal to debug API operations. The tool automatically generates SDK sample code for the corresponding API operations.

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

For more information about the fields of the API operations, see Moderation Agent synchronous detection API.

Java SDK

Usage notes

  • Environment requirements: Java 1.8 or later.

  • Source code: See Java SDK source code.

  • Features: Currently, only images that are accessible over the public network can be moderated.

Moderate images that are accessible over the public network

Scenarios

When the images that you want to moderate can be accessed over the public network by using URLs, the Image Moderation Enhanced Edition service can retrieve the image files from the URLs and then moderate the images.

  1. Add the following dependency to the pom.xml file to install the Java SDK. Then, you can use the SDK in your Maven project.

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

    • Integration example

    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import com.aliyun.green20220302.Client;
    import com.aliyun.green20220302.models.*;
    import com.aliyun.teaopenapi.models.Config;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.UUID;
    
    public class MultiModalAgentDemo {
    
        public static void main(String[] args) throws Exception {
            Config config = new Config();
            /**
             * An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M.
             * Common methods to obtain environment variables:
             * Method 1:
             *     Obtain the AccessKey ID of a RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Obtain the AccessKey secret of a RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             * Method 2:
             *     Obtain the AccessKey ID of a RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
             *     Obtain the AccessKey secret of a RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             */
            config.setAccessKeyId("We recommend that you obtain the AccessKey ID of your RAM user from environment variables");
            config.setAccessKeySecret("We recommend that you obtain the AccessKey secret of your RAM user from environment variables");
    
            // Configure the region and endpoint based on the region that you actually use.
            config.setRegionId("cn-shanghai");
            config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
            // The read timeout period. Unit: milliseconds (ms).
            config.setReadTimeout(20000);
            // The connection timeout period. Unit: milliseconds (ms).
            config.setConnectTimeout(10000);
            // Set the HTTP proxy.
            //config.setHttpProxy("http://xx.xx.xx.xx:xxxx");
            // Set the HTTPS proxy.
            //config.setHttpsProxy("https://xx.xx.xx.xx:xxxx");
            Client client = new Client(config);
            // Process input parameters.
            JSONObject serviceParameters = new JSONObject();
            // The image to be moderated. A maximum of one image is supported.
            List<JSONObject> images = new ArrayList<>();
            JSONObject image = new JSONObject();
            image.put("imageUrl","https://img.alicdn.com/tfs/xxxxxxxxxx001.png");
            images.add(image);
            serviceParameters.put("images", images);
            // The text to be moderated. The maximum length is 2,000 characters.
            serviceParameters.put("content", "Sample text content");
            // The business ID.
            serviceParameters.put("dataId", UUID.randomUUID());
            MultiModalAgentRequest multiModalAgentRequest = new MultiModalAgentRequest();
            // The moderation type.
            // Text moderation: txt_check_agent_01
            // Image moderation: img_check_agent_01
            // Multimodal moderation: img_txt_check_agent_01
            multiModalAgentRequest.setAppID("img_txt_check_agent_01");
            multiModalAgentRequest.setServiceParameters(serviceParameters.toJSONString());
    
            try {
                MultiModalAgentResponse response = client.multiModalAgent(multiModalAgentRequest);
                if (response.getStatusCode() == 200) {
                    MultiModalAgentResponseBody result = response.getBody();
                    System.out.println(JSON.toJSONString(result));
                } else {
                    System.out.println("response not success. status:" + response.getStatusCode());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    In the sample code, replace the region ID (RegionId) and endpoint based on the region that you actually use. For the endpoints of different regions, see the preceding table of supported regions.

Python SDK

Usage notes

  • Environment requirements: Python 3.6 or later.

  • Source code: For the source code, see Python SDK source code.

  • Features: Currently, only images that are accessible over the public network can be moderated.

Moderate images that are accessible over the public network

Scenarios

When the images that you want to moderate can be accessed over the public network by using URLs, the Image Moderation Enhanced Edition service can retrieve the image files from the URLs and then moderate the images.

  1. Run the following command to install the dependencies.

    python3
    pip install alibabacloud_green20220302==3.6.8
  2. Connect to the Python SDK.

  3. # 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
    import uuid
    
    config = Config(
        # An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M.
        # We strongly recommend that you do not save the AccessKey ID and AccessKey secret of your RAM user in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all resources under your account.
        # Common methods to obtain environment variables:
        # Obtain the AccessKey ID of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
        # Obtain the AccessKey secret of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        access_key_id='We recommend that you obtain the AccessKey ID of your RAM user from environment variables',
        access_key_secret='We recommend that you obtain the AccessKey secret of your RAM user from environment variables',
        # The connection timeout period. Unit: milliseconds (ms)
        connect_timeout=10000,
        # The read timeout period. Unit: milliseconds (ms)
        read_timeout=20000,
        region_id='cn-shanghai',
        endpoint='green-cip.cn-shanghai.aliyuncs.com'
    )
    
    clt = Client(config)
    
    serviceParameters = {
        # The text to be moderated. The maximum length is 2,000 characters.
        'content': 'Sample text content',
        # The image to be moderated. A maximum of one image is supported.
        'images': {'imageUrl':'https://img.alicdn.com/tfs/xxxxxxxxxx001.png'},
        # The business ID.
        'dataId':uuid.uuid4().hex
    }
    multiModalAgentRequest = models.MultiModalAgentRequest(
        # The moderation type.
        # Text moderation: txt_check_agent_01
        # Image moderation: img_check_agent_01
        # Multimodal moderation: img_txt_check_agent_01
        app_id='img_txt_check_agent_01',
        service_parameters=json.dumps(serviceParameters)
    )
    
    try:
        response = clt.multi_modal_agent(multiModalAgentRequest)
        if response.status_code == 200:
            # The call is successful.
            result = response.body
            print('response success. result:{}'.format(result))
        else:
            print('response not success. status:{} ,result:{}'.format(response.status_code, response))
    except Exception as err:
        print(err)

    In the sample code, replace the region ID (region_id) and endpoint based on the region that you actually use. For the endpoints of different regions, see the preceding table of supported regions.

If you encounter any problems when you use the service, Please join the DingTalk group (group ID: 35573806), to contact product technical experts for consultation.