Content moderation - text

Updated at:

This document provides sample code for Content Moderation - Text in popular programming languages.

Note
  • For real-time assistance, start an online consultation.

  • If you have questions about API access or usage for the Alibaba Cloud Vision AI Platform, join our DingTalk group (ID: 23109592) to contact us.

Overview

For detailed features and parameters, see Content Moderation - Text.

SDK installation

For information about SDK dependencies for popular programming languages, see SDK overview.

Configure environment variables

Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.

Important
  • An Alibaba Cloud account has full access to all API operations. We recommend that you use a RAM user for API calls or routine O&M. For more information, see Create a RAM user.

  • Do not save your AccessKey ID or AccessKey Secret in project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised.

  • Configure environment variables on Linux and macOS

    1. Open a terminal in IntelliJ IDEA.

    2. Run the following commands to configure the environment variables.

      Replace <access_key_id> with the AccessKey ID of your RAM user and <access_key_secret> with the AccessKey Secret of your RAM user. If you need to configure more permissions, see Control access permissions using a RAM policy.

      export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id>
      export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>
  • Configure environment variables on Windows

    Create a new environment variable file, add the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, and set them to the AccessKey ID and AccessKey Secret that you have prepared. Then, restart the Windows operating system. The following example uses Windows 10.

    1. Open File Explorer, right-click This PC, and then select Properties.

    2. In the left-side navigation pane, click Advanced system settings.

    3. On the Advanced tab of the System Properties dialog box, click Environment Variables.

    4. In the Environment Variables dialog box, click New.

    5. In the New System Variable dialog box, add the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, and set them to the AccessKey ID and AccessKey Secret that you have prepared.

    6. Restart the Windows operating system for the configurations to take effect.

Sample code

/*
Add the required SDK dependency.
<!-- https://mvnrepository.com/artifact/com.aliyun/imageaudit20191230 -->
<dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>imageaudit20191230</artifactId>
      <version>${aliyun.imageaudit.version}</version>
</dependency>
*/

import com.aliyun.imageaudit20191230.models.ScanTextRequest;
import com.aliyun.imageaudit20191230.models.ScanTextResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaModel;

public class ScanText {

    public static com.aliyun.imageaudit20191230.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        /*
          Initializes the configuration object com.aliyun.teaopenapi.models.Config.
          This object stores configuration parameters such as your AccessKeyId, AccessKeySecret, and endpoint.
         */
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        // The service endpoint.
        config.endpoint = "imageaudit.cn-shanghai.aliyuncs.com";
        return new com.aliyun.imageaudit20191230.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        // To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
        // If you are using a RAM user's AccessKey, you must also grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
        // Read the AccessKey ID and AccessKey Secret from environment variables. You must configure the environment variables before running the sample code.      
        String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");     
        String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        com.aliyun.imageaudit20191230.Client client = ScanText.createClient(accessKeyId, accessKeySecret);
        ScanTextRequest.ScanTextRequestTasks tasks = new ScanTextRequest.ScanTextRequestTasks()
                .setContent("Plumbing repair, contact weixin");
        ScanTextRequest.ScanTextRequestLabels labels = new ScanTextRequest.ScanTextRequestLabels()
                .setLabel("ad");
        com.aliyun.imageaudit20191230.models.ScanTextRequest scanTextRequest = new com.aliyun.imageaudit20191230.models.ScanTextRequest()
                .setLabels(java.util.Arrays.asList(
                        labels
                ))
                .setTasks(java.util.Arrays.asList(
                        tasks
                ));
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            ScanTextResponse response = client.scanTextWithOptions(scanTextRequest, runtime);
            // Get the full result.
            System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response)));
        } catch (TeaException error) {
            // Get the full error message.
            System.out.println(com.aliyun.teautil.Common.toJSONString(error));
            // Get a specific field.
            System.out.println(error.getCode());
        }
    }
}
 # # -*- coding: utf-8 -*-
# Add the required SDK dependency.
# pip install alibabacloud_imageaudit20191230

import os
from alibabacloud_imageaudit20191230.client import Client
from alibabacloud_imageaudit20191230.models import ScanTextRequestLabels, ScanTextRequestTasks, ScanTextRequest
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions

config = Config(
    # To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
    # If you are using a RAM user's AccessKey, you must also grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
    # Read the AccessKey ID and AccessKey Secret from environment variables. You must configure the environment variables before running the sample code.
    access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
    access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
    # The service endpoint.
    endpoint='imageaudit.cn-shanghai.aliyuncs.com',
    # The ID of the region where the service is deployed.
    region_id='cn-shanghai'
)
labels_0 = ScanTextRequestLabels(
    label='spam'
)
labels_1 = ScanTextRequestLabels(
    label='politics'
)
tasks_0 = ScanTextRequestTasks(
    content='Plumbing repair, contact weixin'
)
tasks_1 = ScanTextRequestTasks(
    content='This topic provides the syntax and sample code for the ScanText operation of Content Moderation - Text.'
)
scan_text_request = ScanTextRequest(
    tasks=[
        tasks_0,
        tasks_1
    ],
    labels=[
        labels_0,
        labels_1
    ]
)
runtime_option = RuntimeOptions()
try:
    # Initialize the client.
    client = Client(config)
    response = client.scan_text_with_options(scan_text_request, runtime_option)
    # Get the full result.
    print(response.body)
except Exception as error:
    # Get the full error message.
    print(error)
    # Get a specific field.
    print(error.code)
<?php

// Add the required SDK dependency.
//composer require alibabacloud/imageaudit-20191230

use AlibabaCloud\SDK\Imageaudit\V20191230\Imageaudit;
use AlibabaCloud\Tea\Utils\Utils;
use \Exception;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Imageaudit\V20191230\Models\ScanTextRequest\labels;
use AlibabaCloud\SDK\Imageaudit\V20191230\Models\ScanTextRequest\tasks;
use AlibabaCloud\SDK\Imageaudit\V20191230\Models\ScanTextRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class ScanText {

    /**
     * Initializes a client by using an AccessKey ID and AccessKey Secret.
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Imageaudit Client
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        // Initializes the configuration object Darabonba\OpenApi\Models\Config.
        // This object stores configuration parameters such as your accessKeyId, accessKeySecret, and endpoint.
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        // The service endpoint.
        $config->endpoint = "imageaudit.cn-shanghai.aliyuncs.com";
        return new Imageaudit($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function main($args){
        // To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
        // If you are using a RAM user's AccessKey, you must also grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
        // Read the AccessKey ID and AccessKey Secret from environment variables. You must configure the environment variables before running the sample code.    
        $accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');      
        $accessKeySecret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');
        $client = self::createClient($accessKeyId, $accessKeySecret);
        $labels0 = new labels([
            "label" => "spam"
        ]);
        $labels1 = new labels([
            "label" => "politics"
        ]);
        $labels2 = new labels([
            "label" => "abuse"
        ]);
        $labels3 = new labels([
            "label" => "terrorism"
        ]);
        $labels4 = new labels([
            "label" => "porn"
        ]);
        $labels5 = new labels([
            "label" => "flood"
        ]);
        $labels6 = new labels([
            "label" => "contraband"
        ]);
        $labels7 = new labels([
            "label" => "ad"
        ]);
        $tasks0 = new tasks([
            "content" => "Plumbing repair, contact weixin"
        ]);
        $tasks1 = new tasks([
            "content" => "This topic provides the syntax and sample code for the ScanText operation of Content Moderation - Text."
        ]);
        $scanTextRequest = new ScanTextRequest([
            "tasks" => [
                $tasks0,
                $tasks1
            ],
            "labels" => [
                $labels0,
                $labels1,
                $labels2,
                $labels3,
                $labels4,
                $labels5,
                $labels6,
                $labels7
            ]
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $resp = $client->scanTextWithOptions($scanTextRequest, $runtime);
            # Get the full result.
            echo Utils::toJSONString($resp->body);
        } catch (Exception $exception) {
            # Get the full error message.
            echo Utils::toJSONString($exception);
            # Get a specific field.
            echo $exception->getCode();
        }
    }
}
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}
// The $argv parameter is a reserved array input and requires no modification.
ScanText::main(array_slice($argv, 1));
// Add the required SDK dependency.
// npm install @alicloud/imageaudit20191230
// Import the SDK.
const ImageauditClient = require('@alicloud/imageaudit20191230');
const OpenapiClient = require('@alicloud/openapi-client');
const TeaUtil = require('@alicloud/tea-util');

let config = new OpenapiClient.Config({
  // To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
  // If you are using a RAM user's AccessKey, you must also grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
  // Read the AccessKey ID and AccessKey Secret from environment variables. You must configure the environment variables before running the sample code. 
  accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,   
  accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
});
// The service endpoint.
config.endpoint = `imageaudit.cn-shanghai.aliyuncs.com`;
const client = new ImageauditClient.default(config);
let labels0 = new ImageauditClient.ScanTextRequestLabels({
  label: "test",
});
let tasks0 = new ImageauditClient.ScanTextRequestTasks({
  content: "content",
});
let scanTextRequest = new ImageauditClient.ScanTextRequest({
  tasks: [
    tasks0
  ],
  labels: [
    labels0
  ],
});
let runtime = new TeaUtil.RuntimeOptions({ });
client.scanTextWithOptions(scanTextRequest, runtime)
  .then(function(scanTextResponse) {
    // Get the full result.
    console.log(scanTextResponse);
    // Get a specific field.
    console.log(scanTextResponse.body.data);
  }, function(error) {
    // Get the full error message.
    console.log(error);
    // Get a specific field.
    console.log(error.data.Code);
  })
/**
The dependency is github.com/alibabacloud-go/imageaudit-20191230/v3.
We recommend that you use 'go mod tidy' to install the dependency.
*/
package main

import (
	"fmt"
	"os"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	imageaudit20191230 "github.com/alibabacloud-go/imageaudit-20191230/v3/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
)

func main() {
        // To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
        // If you are using a RAM user's AccessKey, you must also grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
        // Read the AccessKey ID and AccessKey Secret from environment variables. You must configure the environment variables before running the sample code.  
        accessKeyId := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")  
        accessKeySecret := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
        // Initializes the configuration object &openapi.Config. This object stores configuration parameters such as your AccessKeyId, AccessKeySecret, and endpoint.
	config := &openapi.Config{
		AccessKeyId: tea.String(accessKeyId),
		AccessKeySecret: tea.String(accessKeySecret),
	}
	// The service endpoint.
	config.Endpoint = tea.String("imageaudit.cn-shanghai.aliyuncs.com")
	client, err := imageaudit20191230.NewClient(config)
	if err != nil {
		fmt.Println(err.Error())
	}

	task0 := &imageaudit20191230.ScanTextRequestTasks{
		Content: tea.String("Plumbing repair, contact weixin"),
	}
	label0 := &imageaudit20191230.ScanTextRequestLabels{
		Label: tea.String("ad"),
	}
	scanTextRequest := &imageaudit20191230.ScanTextRequest{
		Tasks:  []*imageaudit20191230.ScanTextRequestTasks{task0},
		Labels: []*imageaudit20191230.ScanTextRequestLabels{label0},
	}
	runtime := &util.RuntimeOptions{}
	scanTextResponse, _err := client.ScanTextWithOptions(scanTextRequest, runtime)
	if _err != nil {
		fmt.Println(_err.Error())
	} else {
		// Get the full result.
		fmt.Println(scanTextResponse)
		// Get a specific field.
		fmt.Println(scanTextResponse.Body.Data)
	}
}
  // Add the required SDK dependency.
// dotnet add package AlibabaCloud.SDK.Imageaudit20191230
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using AlibabaCloud.SDK.Imageaudit20191230.Models;
using Tea;
using Tea.Utils;
 
namespace AlibabaCloud.SDK.Sample
{
    public class Sample
    {
        /**
            * Initializes a client by using an AccessKey ID and AccessKey Secret.
            * @param accessKeyId
            * @param accessKeySecret
            * @return Client
            * @throws Exception
        */
        public static AlibabaCloud.SDK.Imageaudit20191230.Client CreateClient(string accessKeyId, string accessKeySecret)
        {
            // Initializes the configuration object AlibabaCloud.OpenApiClient.Models.Config. This object stores configuration parameters such as your AccessKeyId, AccessKeySecret, and endpoint.
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
            {
                AccessKeyId = accessKeyId,
                AccessKeySecret = accessKeySecret,
            };
            // The service endpoint.
            config.Endpoint = "imageaudit.cn-shanghai.aliyuncs.com";
            return new AlibabaCloud.SDK.Imageaudit20191230.Client(config);
        }
        public static void Main(string[] args)
        {          
            // To create an AccessKey ID and AccessKey Secret, see https://help.aliyun.com/document_detail/175144.html.
            // If you are using a RAM user's AccessKey, you must also grant the RAM user the AliyunVIAPIFullAccess permission. For more information, see https://help.aliyun.com/document_detail/145025.html.
            // Read the AccessKey ID and AccessKey Secret from environment variables. You must configure the environment variables before running the sample code.
            string accessKeyId = System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
            string accessKeySecret = System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
            AlibabaCloud.SDK.Imageaudit20191230.Client client = CreateClient(accessKeyId, accessKeySecret);
            AlibabaCloud.SDK.Imageaudit20191230.Models.ScanTextRequest.ScanTextRequestLabels labels0 = new AlibabaCloud.SDK.Imageaudit20191230.Models.ScanTextRequest.ScanTextRequestLabels
            {
                Label = "test",
            };
            AlibabaCloud.SDK.Imageaudit20191230.Models.ScanTextRequest.ScanTextRequestTasks tasks0 = new AlibabaCloud.SDK.Imageaudit20191230.Models.ScanTextRequest.ScanTextRequestTasks
            {
                Content = "content",
            };
            AlibabaCloud.SDK.Imageaudit20191230.Models.ScanTextRequest scanTextRequest = new AlibabaCloud.SDK.Imageaudit20191230.Models.ScanTextRequest
            {
                Tasks = new List<AlibabaCloud.SDK.Imageaudit20191230.Models.ScanTextRequest.ScanTextRequestTasks>
                {
                    tasks0
                },
                Labels = new List<AlibabaCloud.SDK.Imageaudit20191230.Models.ScanTextRequest.ScanTextRequestLabels>
                {
                    labels0
                },
            };
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            try
            {
                AlibabaCloud.SDK.Imageaudit20191230.Models.ScanTextResponse scanTextWithResponse = client.ScanTextWithOptions(scanTextRequest, runtime);
                // Get the full result.
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(scanTextWithResponse.Body));
                // Get a specific field.
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.ToJSONString(scanTextWithResponse.Body.Data));
            }
            catch (TeaException error)
            {
                // Print the error.
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
            }
            catch (Exception _error)
            {
                TeaException error = new TeaException(new Dictionary<string, object>
              {
                { "message", _error.Message }
              });
                // Print the error.
                Console.WriteLine(AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message));
            }
        }
    }
}