This topic describes how to integrate the text moderation 2.0 SDK.
Step 1: Activate the service
Activate the text moderation 2.0 service on the Activate Service page.
After you activate the text 2.0 service, the default billing method is pay-as-you-go. You are charged daily based on your actual usage. You are not charged if you do not use the service. The system automatically generates bills based on your usage of API operations.
Step 2: Grant permissions to a RAM user
Before you integrate an SDK or call an API operation, you must grant permissions to a RAM user. You can create an AccessKey pair for an Alibaba Cloud account or a RAM user. When you call an Alibaba Cloud API operation, you must use an AccessKey pair to complete identity verification. For more 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
AliyunYundunGreenWebFullAccesssystem policy to the RAM user.For more information, see Grant permissions to a RAM user.
After completing the preceding operations, you can call the Content Moderation API as the RAM user.
Step 3: Install and integrate the SDK
The following regions are supported:
Region | Public endpoint | VPC endpoint |
Singapore | green-cip.ap-southeast-1.aliyuncs.com | green-cip-vpc.ap-southeast-1.aliyuncs.com |
US (Virginia) | green-cip.us-east-1.aliyuncs.com | green-cip-vpc.us-east-1.aliyuncs.com |
US (Silicon Valley) | green-cip.us-west-1.aliyuncs.com | N/A |
UK (London) | green-cip.eu-west-1.aliyuncs.com | N/A |
If you need SDK sample code in other languages, you can use the OpenAPI Explorer online tool to debug API operations and automatically generate the corresponding SDK sample code.
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 enhanced version general service
This SDK corresponds to the Text moderation enhanced version 2.0 multilingual service.
Java SDK
Java 1.8 or later is supported.
For the source code, see Java SDK source code or Java SDK source code (OSS path).
Add the following dependency to the pom.xml file to use the SDK in your Maven project.
Add the following dependency to the dependencies section:
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>2.2.11</version> </dependency>Integrate the Java SDK.
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(); // Leaking your source code may cause your AccessKey pair to be leaked and threaten the security of all your resources. The following sample code is for reference only. Use a Security Token Service (STS) token for authorization. For more information, see the related documentation. // Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are set. config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")); config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")); // Modify the region and endpoint as needed. config.setRegionId("ap-southeast-1"); config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com"); // Set the read and connection timeout periods in milliseconds. config.setReadTimeout(6000); config.setConnectTimeout(3000); // To improve performance, reuse the client instance to avoid creating multiple connections. Client client = new Client(config); // Create a 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(); // Set the service as needed. textModerationRequest.setService("text moderation service"); textModerationRequest.setServiceParameters(serviceParameters.toJSONString()); try { // Obtain the detection result. TextModerationResponse response = client.textModerationWithOptions(textModerationRequest, runtime); // Print the 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(); } } }
Python SDK
Python 3.6 or later is supported.
For the source code, see Python SDK source code.
Python 3.6 or later is supported.
Run the following command to install the dependencies:
pip install alibabacloud_green20220302==2.2.11You can integrate the Python SDK.
Examples
# 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( # Set the service as needed. service = 'text moderation service', service_parameters = json.dumps(service_parameters) ) # Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are set. config = Config( # Leaking your source code may cause your AccessKey pair to be leaked and threaten the security of all your resources. The following sample code is for reference only. Use an STS token for authorization. For more information, see the related documentation. access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], # Set the read and connection timeout periods in milliseconds. connect_timeout=3000, read_timeout=6000, # Modify the region and endpoint as needed. region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) # To improve performance, reuse the client instance to avoid creating multiple connections. client = Client(config) # Create a 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 the 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()
PHP SDK
The SDK supports PHP 5.6 or later.
For the source code, see PHP SDK source code.
Run the following command to import the dependencies:
composer require alibabacloud/green-20220302 2.2.10Integrate the PHP SDK.
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(); // Set the service as needed. $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([ // Leaking your source code may cause your AccessKey pair to be leaked and threaten the security of all your resources. The following sample code is for reference only. Use an STS token for authorization. For more information, see the related documentation. // Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are set. "accessKeyId" => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'), "accessKeySecret" => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'), // Modify the region and endpoint as needed. "endpoint" => "green-cip.ap-southeast-1.aliyuncs.com", "regionId" => "ap-southeast-1" ]); // To improve performance, reuse the client instance to avoid creating multiple connections. $client = new Green($config); // Create a RuntimeObject instance and set runtime parameters. $runtime = new RuntimeOptions([]); $runtime->readTimeout = 10000; $runtime->connectTimeout = 10000; try { // Obtain the detection result. $response = $client->textModerationWithOptions($request, $runtime); // Print the 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()); }
Go SDK
Run the following command to import the dependencies:
go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2Integrate the Go SDK.
Sample code
package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green "github.com/alibabacloud-go/green-20220302/v2/client" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { config := &openapi.Config{ // Your AccessKey ID. AccessKeyId: tea.String("Obtain the AccessKey ID of a RAM user from an environment variable"), // Your AccessKey secret. AccessKeySecret: tea.String("Obtain the AccessKey secret of a RAM user from an environment variable"), // The endpoint to access. Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"), /** * Set the timeout period. The server-side end-to-end processing timeout period is 10 seconds. Configure the timeout period accordingly. * If you set the ReadTimeout parameter to a value less than the time required for server-side processing, your program receives a ReadTimeout exception. */ ConnectTimeout: tea.Int(3000), ReadTimeout: tea.Int(6000), } client, _err := green.NewClient(config) if _err != nil { panic(_err) } serviceParameters, _ := json.Marshal( map[string]interface{}{ "content": "text to be moderated", }, ) request := green.TextModerationRequest{ Service: tea.String("text moderation service"), ServiceParameters: tea.String(string(serviceParameters)), } result, _err := client.TextModeration(&request) if _err != nil { panic(_err) } statusCode := tea.IntValue(tea.ToInt(result.StatusCode)) if statusCode == http.StatusOK { textModerationResponse := result.Body fmt.Println("response success. response:" + textModerationResponse.String()) if tea.IntValue(tea.ToInt(textModerationResponse.Code)) == 200 { textModerationResponseData := textModerationResponse.Data fmt.Println("response reason:" + tea.StringValue(textModerationResponseData.Reason)) fmt.Println("response labels:" + tea.StringValue(textModerationResponseData.Labels)) } } else { fmt.Println("response not success. status:" + tea.ToString(statusCode)) } }
Node.js SDK
Run the following command to install the dependencies:
npm install @alicloud/green20220302@2.2.10Integrate the Node.js SDK.
Sample code
const RPCClient = require("@alicloud/pop-core"); async function main() { // To improve performance, reuse the client instance to avoid creating multiple connections. var client = new RPCClient({ // Leaking your source code may cause your AccessKey pair to be leaked and threaten the security of all your resources. The following sample code is for reference only. Use an STS token for authorization. For more information, see the related documentation. // Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are set. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], // Modify the region and endpoint as needed. endpoint: "https://green-cip.ap-southeast-1.aliyuncs.com", apiVersion: '2022-03-02' }); // Create a RuntimeObject instance and set runtime parameters. var params = { // Set the service as needed. "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 { // Obtain the detection result. var response = await client.request('TextModeration', params, requestOption) // Print the detection result. console.log(JSON.stringify(response)) } catch (err) { console.log(err); } } main().then(function (response) { });
C# SDK
You can run the following command to import the dependencies:
dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10You can integrate the C# SDK.
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 a text moderation request. AlibabaCloud.SDK.Green20220302.Models.TextModerationRequest textModerationRequest = new AlibabaCloud.SDK.Green20220302.Models.TextModerationRequest(); // Set the service as needed. 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); // Leaking your source code may cause your AccessKey pair to be leaked and threaten the security of all your resources. The following sample code is for reference only. Use an STS token for authorization. For more information, see the related documentation. // Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables 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 the region and endpoint as needed. Endpoint = "green-cip.ap-southeast-1.aliyuncs.com", }; // To improve performance, reuse the client instance to avoid creating multiple connections. AlibabaCloud.SDK.Green20220302.Client client = new AlibabaCloud.SDK.Green20220302.Client(config); // 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 { // Obtain the detection result. AlibabaCloud.SDK.Green20220302.Models.TextModerationResponse response = client.TextModerationWithOptions(textModerationRequest, runtime); // Print the detection result. Console.WriteLine(response.Body.RequestId); Console.WriteLine(JsonConvert.SerializeObject(response.Body)); } catch (Exception _err) { Console.WriteLine(_err); } } } }