This topic describes how to call the Text Moderation 2.0 service by using SDKs.
Step 1: Activate Text Moderation 2.0
Open the service activation page to activate the Text Moderation 2.0 service.
After you activate the Text Moderation 2.0 service, the default billing method is pay-as-you-go. Daily fees are calculated based on the actual usage. If the service is not called, no charge is made. After you call an API operation, the billing system automatically charges you based on your usage.
Step 2: Grant permissions to a RAM user
Before you call API operations or use SDKs as a Resource Access Management (RAM) user, you must grant permissions to the RAM user. You can create an AccessKey pair for your Alibaba Cloud account and the RAM user. When you call an API operation, you must use the AccessKey pair to complete identity verification. For information about how to obtain an AccessKey pair, see Obtain an AccessKey pair.
Procedure
Log on to the RAM console as a RAM administrator.
- Create a RAM user.
For more information, see Create a RAM user.
- 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 use SDKs
The following table provides the supported regions.
Region | Public endpoint | Internal endpoint | Supported service |
Singapore | green-cip.ap-southeast-1.aliyuncs.com | green-cip-vpc.ap-southeast-1.aliyuncs.com | Text Moderation 2.0 service |
If you need SDK sample code in other programming languages, you can call an operation in OpenAPI Explorer. OpenAPI Explorer dynamically generates the sample code of the operation for different SDKs.
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.
Text Moderation 2.0 service
The API operation for this service is described in Multi-language services provided by Text Moderation 2.0.
SDK for Java
The Java version must be 1.8 or later.
For more information about the source code, see SDK source code for Java or SDK source code for Java in Open Source Software (OSS).
After you add the related dependencies to the pom.xml file, you can use the SDK in Maven projects.
Add the following dependencies to the dependencies field:
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>2.2.15</version> </dependency>
Use the SDK for Java.
Sample code:
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.TextModerationRequest; import com.aliyun.green20220302.models.TextModerationResponse; import com.aliyun.green20220302.models.TextModerationResponseBody; import com.aliyun.teaopenapi.models.Config; import com.aliyun.teautil.models.RuntimeOptions; public class TextAutoRoute { public static void main(String[] args) throws Exception { Config config = new Config(); // The leakage of code may lead to the leakage of AccessKey and security breakage of your account. The following examples are for reference only. It is recommended to use STS tokens for authorization, please refer to related documentation. // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set. config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")); config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); // Modify region and endpoint according to your requirement. config.setRegionId("ap-southeast-1"); config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com"); // Setup read and connection timeout by ms. config.setReadTimeout(6000); config.setConnectTimeout(3000); // To improve performance, we strongly recommend you reuse client instance to avoid establishing duplicate connections. Client client = new Client(config); // Create RuntimeObject instance and set runtime parameters. RuntimeOptions runtime = new RuntimeOptions(); runtime.readTimeout = 10000; runtime.connectTimeout = 10000; // Construct service parameters. JSONObject serviceParameters = new JSONObject(); serviceParameters.put("content", "text to be detected"); if (serviceParameters.get("content") == null || serviceParameters.getString("content").trim().length() == 0) { System.out.println("text moderation content is empty"); return; } TextModerationRequest textModerationRequest = new TextModerationRequest(); // Setup service according to your requirement. textModerationRequest.setService("text moderation service"); textModerationRequest.setServiceParameters(serviceParameters.toJSONString()); try { // Method to obtain detection result. TextModerationResponse response = client.textModerationWithOptions(textModerationRequest, runtime); // Print detection result. if (response != null) { if (response.getStatusCode() == 200) { TextModerationResponseBody result = response.getBody(); System.out.println(JSON.toJSONString(result)); Integer code = result.getCode(); if (code != null && code == 200) { TextModerationResponseBody.TextModerationResponseBodyData data = result.getData(); System.out.println("labels = [" + data.getLabels() + "]"); System.out.println("reason = [" + data.getReason() + "]"); } else { System.out.println("text moderation not success. code:" + code); } } else { System.out.println("response not success. status:" + response.getStatusCode()); } } } catch (Exception e) { e.printStackTrace(); } } }
SDK for Python
The Python version must be 3.6 or later.
For more information about the source code, see SDK source code for Python.
The Python version must be 3.6 or later.
Run the following command to install the related dependencies:
pip install alibabacloud_green20220302==2.2.15
Use the SDK for Python.
Sample code:
# coding=utf-8 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 class TextAutoRoute: @staticmethod def main() -> None: service_parameters = { 'content': 'text to be detected', 'dataId': str(uuid.uuid1()) } if service_parameters.get("content") is None or len(service_parameters.get("content").strip()) == 0: print("text moderation content is empty") return text_moderation_request = models.TextModerationRequest( # Setup service according to your requirement. service = 'text moderation service', service_parameters = json.dumps(service_parameters) ) # Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set. config = Config( # The leakage of code may lead to the leakage of AccessKey and security breakage of your account. The following examples are for reference only. It is recommended to use STS tokens for authorization, please refer to related documentation. access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], # Setup read and connection timeout by ms. connect_timeout=3000, read_timeout=6000, # Modify region and endpoint according to your requirement. region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) # To improve performance, we strongly recommend you reuse client instance to avoid establishing duplicate connections. client = Client(config) # Create RuntimeObject instance and set runtime parameters. runtime = util_models.RuntimeOptions() runtime.read_timeout = 10000 runtime.connect_timeout = 10000 try: response = client.text_moderation_with_options(text_moderation_request, runtime) if response.status_code == 200: # Print detection result. result = response.body print('response success. result:{}'.format(result)) if result.code == 200: resultData = result.data print('labels:{}, reason:{}'.format(resultData.labels, resultData.reason)) else: print('response not success. status:{} ,result:{}'.format(response.status_code, response)) except Exception as err: print(err) if __name__ == '__main__': TextAutoRoute.main()
SDK for PHP
The PHP version must be 5.6 or later.
For more information about the source code, see SDK source code for PHP.
Run the following command to install the related dependencies:
composer require alibabacloud/green-20220302 2.2.15
Use the SDK for PHP.
Sample code:
<?php require('vendor/autoload.php'); use AlibabaCloud\Tea\Utils\Utils; use Darabonba\OpenApi\Models\Config; use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions; use AlibabaCloud\SDK\Green\V20220302\Green; use AlibabaCloud\SDK\Green\V20220302\Models\TextModerationRequest; $request = new TextModerationRequest(); // Setup service according to your requirement. $request->service = "text moderation service"; $arr = array('content' => 'text to be detected'); $request->serviceParameters = json_encode($arr); if (empty($arr) || empty(trim($arr["content"]))) { echo "text moderation content is empty"; return; } $config = new Config([ // The leakage of code may lead to the leakage of AccessKey and security breakage of your account. The following examples are for reference only. It is recommended to use STS tokens for authorization, please refer to related documentation. // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set. "accessKeyId" => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'), "accessKeySecret" => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'), // Modify region and endpoint according to your requirement. "endpoint" => "green-cip.ap-southeast-1.aliyuncs.com", "regionId" => "ap-southeast-1" ]); // To improve performance, we strongly recommend you reuse client instance to avoid establishing duplicate connections. $client = new Green($config); // Create RuntimeObject instance and set runtime parameters. $runtime = new RuntimeOptions([]); $runtime->readTimeout = 10000; $runtime->connectTimeout = 10000; try { // Method to obtain detection result. $response = $client->textModerationWithOptions($request, $runtime); // Print detection result. print_r($response->body); } catch (Exception $e) { var_dump($e->getMessage()); var_dump($e->getErrorInfo()); var_dump($e->getLastException()); var_dump($e->getLastRequest()); }
SDK for Go
Run the following command to install the related dependencies:
go git clone --branch v2.2.16 github.com/alibabacloud-go/green-20220302/v2
Use the SDK for Go.
Sample code:
// This file is auto-generated, don't edit it. Thanks. package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green20220302 "github.com/alibabacloud-go/green-20220302/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "net/http" "strings" ) func _main() (_err error) { serviceParameters, _ := json.Marshal( map[string]interface{}{ "content": "text to be detected", }, ) var contentMap map[string]interface{} _err = json.Unmarshal(serviceParameters, &contentMap) if contentMap["content"] == "" || len(strings.TrimSpace(fmt.Sprint(contentMap["content"]))) == 0 { fmt.Println("text moderation content is empty") return } textModerationRequest := &green20220302.TextModerationRequest{ // Setup service according to your requirement. Service: tea.String("text moderation service"), ServiceParameters: tea.String(string(serviceParameters)), } // The leakage of code may lead to the leakage of AccessKey and security breakage of your account. The following examples are for reference only. It is recommended to use STS tokens for authorization, please refer to related documentation. config := &openapi.Config{ // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set. AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")), AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")), // Modify region and endpoint according to your requirement. RegionId: tea.String("ap-southeast-1"), Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"), // Setup read and connection timeout by ms. ConnectTimeout: tea.Int(3000), ReadTimeout: tea.Int(6000), } // To improve performance, we strongly recommend you reuse client instance to avoid establishing duplicate connections. client, _err := green20220302.NewClient(config) if _err != nil { return _err } // Create RuntimeObject instance and set runtime parameters. runtime := &util.RuntimeOptions{} runtime.ReadTimeout = tea.Int(10000) runtime.ConnectTimeout = tea.Int(10000) response, _err := client.TextModerationWithOptions(textModerationRequest,runtime) // Print detection result. if response != nil{ statusCode := tea.IntValue(tea.ToInt(response.StatusCode)) body := response.Body textModerationResponseData := body.Data fmt.Println("requestId:" + tea.StringValue(body.RequestId)) if statusCode == http.StatusOK { fmt.Println("response success. response:" + body.String()) if tea.IntValue(tea.ToInt(body.Code)) == 200 { fmt.Println("response reason:" + tea.StringValue(textModerationResponseData.Reason)) fmt.Println("response labels:" + tea.StringValue(textModerationResponseData.Labels)) } else { fmt.Println("text moderation not success. status" + tea.ToString(body.Code)) } } else { fmt.Print("response not success. status:" + tea.ToString(statusCode)) } } return nil } func main() { err := _main() if err != nil { panic(err) } }
SDK for Node.js
Run the following command to install the related dependencies:
npm install @alicloud/green20220302@2.2.15
Use the SDK for Node.js.
Sample code:
const RPCClient = require("@alicloud/pop-core"); async function main() { // To improve performance, we strongly recommend you reuse client instance to avoid establishing duplicate connections. var client = new RPCClient({ // The leakage of code may lead to the leakage of AccessKey and security breakage of your account. The following examples are for reference only. It is recommended to use STS tokens for authorization, please refer to related documentation. // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], // Modify region and endpoint according to your requirement. endpoint: "https://green-cip.ap-southeast-1.aliyuncs.com", apiVersion: '2022-03-02' }); // Create RuntimeObject instance and set runtime parameters. var params = { // Setup service according to your requirement. "Service": "text moderation service", "ServiceParameters": JSON.stringify({ "content": "text to be detected", }) } var serviceParameters = JSON.parse(params.ServiceParameters); if (!serviceParameters.hasOwnProperty("content") || serviceParameters.content.trim().length === 0) { console.log("text moderation content is empty") return; } var requestOption = { method: 'POST', formatParams: false, }; try { // Method to obtain detection result. var response = await client.request('TextModeration', params, requestOption) // Print detection result. console.log(JSON.stringify(response)) } catch (err) { console.log(err); } } main().then(function (response) { });
SDK for C#
Run the following command to install the related dependencies:
dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.15
Use the SDK for C#.
Sample code:
// This file is auto-generated, don't edit it. Thanks. using Newtonsoft.Json; namespace AlibabaCloud.SDK.Green20220302 { public class TextModerationAutoRoute { public static void Main(string[] args) { // Construct text moderation request. AlibabaCloud.SDK.Green20220302.Models.TextModerationRequest textModerationRequest = new AlibabaCloud.SDK.Green20220302.Models.TextModerationRequest(); // Setup service according to your requirement. textModerationRequest.Service = "text moderation service"; Dictionary<string, object> task = new Dictionary<string, object>(); task.Add("content", "text to be detected"); if (!task.ContainsKey("content") || Convert.ToString(task["content"]).Trim() == string.Empty) { Console.WriteLine("text moderation content is empty"); return; } textModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task); // The leakage of code may lead to the leakage of AccessKey and security breakage of your account. The following examples are for reference only. It is recommended to use STS tokens for authorization, please refer to related documentation. // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set. AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"), AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), // Modify region and endpoint according to your requirement. Endpoint = "green-cip.ap-southeast-1.aliyuncs.com", }; // To improve performance, we strongly recommend you reuse client instance to avoid establishing duplicate connections. AlibabaCloud.SDK.Green20220302.Client client = new AlibabaCloud.SDK.Green20220302.Client(config); // Create RuntimeObject instance and set runtime parameters. AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); runtime.ReadTimeout = 10000; runtime.ConnectTimeout = 10000; try { // Method to obtain detection result. AlibabaCloud.SDK.Green20220302.Models.TextModerationResponse response = client.TextModerationWithOptions(textModerationRequest, runtime); // Print detection result. Console.WriteLine(response.Body.RequestId); Console.WriteLine(JsonConvert.SerializeObject(response.Body)); } catch (Exception _err) { Console.WriteLine(_err); } } } }