Document Moderation 2.0 supports both SDK-based and native HTTPS calls. SDK integration is recommended to simplify the signature verification and body format construction steps. This guide describes the integration methods for Document Moderation 2.0.
Step 1: Activate the service
Visit the Activate Content Moderation 2.0 Service page to activate the Document Moderation2.0 service. Usage-based billing will apply after integration. For more information, see Billing Description.
Upon activating the Document Moderation 2.0 service, the default billing method is pay-as-you-go, with daily charges based on actual usage. No fees are charged when the service is not in use.
Step 2: Grant permissions to the RAM user
Before using the SDK or API, grant the necessary permissions to the RAM user. Create an AccessKey pair for the RAM user to authenticate when calling the Alibaba Cloud API. For more information, see Obtain an AccessKey.
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 document moderation service
The service supports integration in the following regions.
Region | Public network access address | Internal network access address | Supported services |
Singapore | green-cip.ap-southeast-1.aliyuncs.com | green-cip-vpc.ap-southeast-1.aliyuncs.com | document_detection_global |
If you need SDK sample code in other languages, you can use the OpenAPI Developer Portal online debugging tool to test API operations. This tool automatically generates SDK sample code for the corresponding API.
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.
For details on the API interface fields, refer to the enhanced version 2.0 of the document review API.
Java SDK
Supports Java 1.8 and subsequent versions.
For the source code, refer to the Java SDK on GitHub or the Java SDK (OSS path).
Supports three types of document moderation.
Detecting Publicly Accessible Documents
Scenarios
When a document requiring review is available through a public network link, the 2.0 of the document review service can retrieve it using the document's URL for examination.
For documents that are publicly accessible via a URL, the Content Moderation enhanced version 2.0 service can retrieve the file for review. To use the SDK in a Maven project, add the necessary dependencies to your pom.xml file.
Include the following in dependencies:
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>2.2.11</version> </dependency>Integrate the Java SDK.
Sample code for submitting a document detection task:
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.FileModerationRequest; import com.aliyun.green20220302.models.FileModerationResponse; import com.aliyun.green20220302.models.FileModerationResponseBody; import com.aliyun.teaopenapi.models.Config; public class FileModerationDemo { public static void main(String[] args) throws Exception { Config config = new Config(); /** * The 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 RAM user AccessKey ID: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the RAM user AccessKey Secret: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Obtain the RAM user AccessKey ID: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the RAM user AccessKey Secret: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ config.setAccessKeyId("It is recommended to obtain the RAM user AccessKey ID from environment variables"); config.setAccessKeySecret("It is recommended to obtain the RAM user AccessKey Secret from environment variables"); // Modify the region and address based on actual conditions. config.setRegionId("ap-southeast-1"); config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com"); // Connection timeout in milliseconds (ms). config.setReadTimeout(6000); // Read timeout in milliseconds (ms). config.setConnectTimeout(3000); Client client = new Client(config); JSONObject serviceParameters = new JSONObject(); serviceParameters.put("url", "https://xxx.oss.aliyuncs.com/xxx.pdf"); // File URL FileModerationRequest fileModerationRequest = new FileModerationRequest(); // Detection type: document_detection_global general document detection fileModerationRequest.setService("document_detection_global"); fileModerationRequest.setServiceParameters(serviceParameters.toJSONString()); try { FileModerationResponse response = client.fileModeration(fileModerationRequest); if (response.getStatusCode() == 200) { FileModerationResponseBody 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) { FileModerationResponseBody.FileModerationResponseBodyData data = result.getData(); System.out.println("taskId = [" + data.getTaskId() + "]"); } else { System.out.println("file moderation not success. code:" + code); } } else { System.out.println("response not success. status:" + response.getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } } }Retrieve the results of the document detection task:
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.DescribeFileModerationResultRequest; import com.aliyun.green20220302.models.DescribeFileModerationResultResponse; import com.aliyun.green20220302.models.DescribeFileModerationResultResponseBody; import com.aliyun.teaopenapi.models.Config; public class DescribeFileModerationResultDemo { public static void main(String[] args) throws Exception { Config config = new Config(); /** * The 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 RAM user AccessKey ID: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the RAM user AccessKey Secret: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Obtain the RAM user AccessKey ID: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the RAM user AccessKey Secret: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ config.setAccessKeyId("It is recommended to obtain the RAM user AccessKey ID from environment variables"); config.setAccessKeySecret("It is recommended to obtain the RAM user AccessKey Secret from environment variables"); // Modify the region and address based on actual conditions config.setRegionId("ap-southeast-1"); config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com"); // Connection timeout in milliseconds (ms). config.setReadTimeout(6000); // Read timeout in milliseconds (ms). config.setConnectTimeout(3000); Client client = new Client(config); JSONObject serviceParameters = new JSONObject(); // taskId returned when the task is submitted serviceParameters.put("taskId", "fi_f_O5z5i*********-1xxp0V"); DescribeFileModerationResultRequest describeFileModerationResultRequest = new DescribeFileModerationResultRequest(); describeFileModerationResultRequest.setService("document_detection_global"); describeFileModerationResultRequest.setServiceParameters(serviceParameters.toJSONString()); try { DescribeFileModerationResultResponse response = client.describeFileModerationResult(describeFileModerationResultRequest); if (response.getStatusCode() == 200) { DescribeFileModerationResultResponseBody 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()) { DescribeFileModerationResultResponseBody.DescribeFileModerationResultResponseBodyData data = result.getData(); System.out.println("pageResult = " + JSON.toJSONString(data.getPageResult())); System.out.println("dataId = " + data.getDataId()); System.out.println("url = " + data.getUrl()); } else { System.out.println("file moderation result not success. code:" + result.getCode()); } } else { System.out.println("response not success. status:" + response.getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } } }
Detecting Local Documents
Scenarios
When the document requiring review is stored on a local machine without a public network access link, you can upload it to the Object Storage Service (OSS) Bucket provided by Content Moderation. The enhanced Version 2.0 service can directly retrieve the document content from OSS for review.
Include the following in dependencies:
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>2.2.11</version> </dependency>Install the OSS SDK:
<dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.16.3</version> </dependency>Integrate the Java SDK.
Sample code for submitting a document detection task:
import com.alibaba.fastjson.JSON; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.DescribeUploadTokenResponse; import com.aliyun.green20220302.models.DescribeUploadTokenResponseBody; import com.aliyun.green20220302.models.FileModerationRequest; import com.aliyun.green20220302.models.FileModerationResponse; import com.aliyun.green20220302.models.FileModerationResponseBody; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.model.PutObjectRequest; import com.aliyun.teaopenapi.models.Config; import com.aliyun.teautil.models.RuntimeOptions; import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class FileModerationFile { /**Whether the service is deployed on vpc*/ public static boolean isVPC = false; /**File upload token endpoint->token*/ public static Map<String, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData> tokenMap = new HashMap<>(); /**Client for uploading file requests*/ public static OSS ossClient = null; /** * Create a request client * * @param accessKeyId * @param accessKeySecret * @param endpoint * @return * @throws Exception */ public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception { Config config = new Config(); config.setAccessKeyId(accessKeyId); config.setAccessKeySecret(accessKeySecret); // Modify the region and address based on actual conditions config.setEndpoint(endpoint); return new Client(config); } /** * Create a client for uploading file requests * * @param tokenData * @param isVPC */ public static void getOssClient(DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData, boolean isVPC) { // Note that the instantiated client here should be reused as much as possible to avoid repeated connections and improve detection performance. if (isVPC) { ossClient = new OSSClientBuilder().build(tokenData.ossInternalEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken()); } else { ossClient = new OSSClientBuilder().build(tokenData.ossInternetEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken()); } } /** * Upload file * * @param filePath * @param tokenData * @return * @throws Exception */ public static String uploadFile(String filePath, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData) throws Exception { String[] split = filePath.split("\\."); String objectName; if (split.length > 1) { objectName = tokenData.getFileNamePrefix() + UUID.randomUUID() + "." + split[split.length - 1]; } else { objectName = tokenData.getFileNamePrefix() + UUID.randomUUID(); } PutObjectRequest putObjectRequest = new PutObjectRequest(tokenData.getBucketName(), objectName, new File(filePath)); ossClient.putObject(putObjectRequest); return objectName; } public static FileModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception { // Note that the instantiated client here should be reused as much as possible to avoid repeated connections and improve detection performance. Client client = createClient(accessKeyId, accessKeySecret, endpoint); RuntimeOptions runtime = new RuntimeOptions(); // The full path of the local file, such as D:\localPath\exampleFile.mp3. String filePath = "D:/test/1.pdf"; // Obtain the file upload token if (tokenMap.get(endpoint) == null || tokenMap.get(endpoint).expiration <= System.currentTimeMillis() / 1000) { DescribeUploadTokenResponse tokenResponse = client.describeUploadToken(); tokenMap.put(endpoint, tokenResponse.getBody().getData()); } // Client for uploading file requests getOssClient(tokenMap.get(endpoint), isVPC); // Upload file String objectName = uploadFile(filePath, tokenMap.get(endpoint)); // Construct detection parameters. Map<String, String> serviceParameters = new HashMap<>(); // File upload information serviceParameters.put("ossBucketName", tokenMap.get(endpoint).getBucketName()); serviceParameters.put("ossObjectName", objectName); serviceParameters.put("dataId", UUID.randomUUID().toString()); FileModerationRequest request = new FileModerationRequest(); // Detection type. request.setService("document_detection_global"); request.setServiceParameters(JSON.toJSONString(serviceParameters)); FileModerationResponse response = null; try { response = client.fileModerationWithOptions(request, runtime); } catch (Exception e) { e.printStackTrace(); } return response; } public static void main(String[] args) throws Exception { /** * The 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 RAM user AccessKey ID: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the RAM user AccessKey Secret: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Obtain the RAM user AccessKey ID: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the RAM user AccessKey Secret: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ config.setAccessKeyId("It is recommended to obtain the RAM user AccessKey ID from environment variables"); config.setAccessKeySecret("It is recommended to obtain the RAM user AccessKey Secret from environment variables"); // Modify the region and address based on actual conditions. FileModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com"); // Print the detection results. if (response != null) { if (response.getStatusCode() == 200) { FileModerationResponseBody body = response.getBody(); System.out.println(JSON.toJSONString(body)); System.out.println("requestId = " + body.getRequestId()); System.out.println("code = " + body.getCode()); System.out.println("msg = " + body.getMessage()); Integer code = body.getCode(); if (200 == code) { FileModerationResponseBody.FileModerationResponseBodyData data = body.getData(); System.out.println("taskId = [" + data.getTaskId() + "]"); } else { System.out.println("file moderation not success. code:" + code); } } else { System.out.println("response not success. status:" + response.getStatusCode()); } } } catch (Exception e) { e.printStackTrace(); } } }Sample code for retrieving document detection tasks:
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.DescribeFileModerationResultRequest; import com.aliyun.green20220302.models.DescribeFileModerationResultResponse; import com.aliyun.green20220302.models.DescribeFileModerationResultResponseBody; import com.aliyun.teaopenapi.models.Config; public class DescribeFileModerationResultDemo { public static void main(String[] args) throws Exception { Config config = new Config(); /** * The 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 RAM user AccessKey ID: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the RAM user AccessKey Secret: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Obtain the RAM user AccessKey ID: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the RAM user AccessKey Secret: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ config.setAccessKeyId("It is recommended to obtain the RAM user AccessKey ID from environment variables"); config.setAccessKeySecret("It is recommended to obtain the RAM user AccessKey Secret from environment variables"); // Modify the region and address based on actual conditions config.setRegionId("ap-southeast-1"); config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com"); // Connection timeout in milliseconds (ms). config.setReadTimeout(6000); // Read timeout in milliseconds (ms). config.setConnectTimeout(3000); Client client = new Client(config); JSONObject serviceParameters = new JSONObject(); // taskId returned when the task is submitted serviceParameters.put("taskId", "fi_f_O5z5i*********-1xxp0V"); DescribeFileModerationResultRequest describeFileModerationResultRequest = new DescribeFileModerationResultRequest(); describeFileModerationResultRequest.setService("document_detection_global"); describeFileModerationResultRequest.setServiceParameters(serviceParameters.toJSONString()); try { DescribeFileModerationResultResponse response = client.describeFileModerationResult(describeFileModerationResultRequest); if (response.getStatusCode() == 200) { DescribeFileModerationResultResponseBody 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()) { DescribeFileModerationResultResponseBody.DescribeFileModerationResultResponseBodyData data = result.getData(); System.out.println("pageResult = " + JSON.toJSONString(data.getPageResult())); System.out.println("dataId = " + data.getDataId()); System.out.println("url = " + data.getUrl()); } else { System.out.println("file moderation result not success. code:" + result.getCode()); } } else { System.out.println("response not success. status:" + response.getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } } }
Detecting OSS Documents
Scenarios
If your document for review is stored in Alibaba Cloud Object Storage Service (OSS), you can create a server role to grant Content Moderation access to OSS. The Content Moderation 2.0 will retrieve the document from OSS via this server role for analysis. To set up a server role, visit the cloud resource access authorization page.
Include the following in dependencies:
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>2.2.11</version> </dependency>Install the OSS SDK:
<dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.16.3</version> </dependency>Integrate the Java SDK.
Sample code for submitting a document detection task:
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.FileModerationRequest; import com.aliyun.green20220302.models.FileModerationResponse; import com.aliyun.green20220302.models.FileModerationResponseBody; import com.aliyun.teaopenapi.models.Config; public class FileModerationDemo { public static void main(String[] args) throws Exception { Config config = new Config(); /** * The 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 RAM user AccessKey ID: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the RAM user AccessKey Secret: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Obtain the RAM user AccessKey ID: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the RAM user AccessKey Secret: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ config.setAccessKeyId("It is recommended to obtain the RAM user AccessKey ID from environment variables"); config.setAccessKeySecret("It is recommended to obtain the RAM user AccessKey Secret from environment variables"); // Modify the region and address based on actual conditions. config.setRegionId("ap-southeast-1"); config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com"); // Connection timeout in milliseconds (ms). config.setReadTimeout(6000); // Read timeout in milliseconds (ms). config.setConnectTimeout(3000); Client client = new Client(config); JSONObject serviceParameters = new JSONObject(); serviceParameters.put("ossBucketName", "bucket_01"); serviceParameters.put("ossObjectName", "2022023/04/24/test.pdf"); serviceParameters.put("ossRegionId", "ap-southeast-1"); FileModerationRequest fileModerationRequest = new FileModerationRequest(); // Detection type: document_detection_global general document detection fileModerationRequest.setService("document_detection_global"); fileModerationRequest.setServiceParameters(serviceParameters.toJSONString()); try { FileModerationResponse response = client.fileModeration(fileModerationRequest); if (response.getStatusCode() == 200) { FileModerationResponseBody 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) { FileModerationResponseBody.FileModerationResponseBodyData data = result.getData(); System.out.println("taskId = [" + data.getTaskId() + "]"); } else { System.out.println("file moderation not success. code:" + code); } } else { System.out.println("response not success. status:" + response.getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } } }Sample code for retrieving document detection tasks:
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.DescribeFileModerationResultRequest; import com.aliyun.green20220302.models.DescribeFileModerationResultResponse; import com.aliyun.green20220302.models.DescribeFileModerationResultResponseBody; import com.aliyun.teaopenapi.models.Config; public class DescribeFileModerationResultDemo { public static void main(String[] args) throws Exception { Config config = new Config(); /** * The 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 RAM user AccessKey ID: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the RAM user AccessKey Secret: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Obtain the RAM user AccessKey ID: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the RAM user AccessKey Secret: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ config.setAccessKeyId("It is recommended to obtain the RAM user AccessKey ID from environment variables"); config.setAccessKeySecret("It is recommended to obtain the RAM user AccessKey Secret from environment variables"); // Modify the region and address based on actual conditions config.setRegionId("ap-southeast-1"); config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com"); // Connection timeout in milliseconds (ms). config.setReadTimeout(6000); // Read timeout in milliseconds (ms). config.setConnectTimeout(3000); Client client = new Client(config); JSONObject serviceParameters = new JSONObject(); // taskId returned when the task is submitted serviceParameters.put("taskId", "fi_f_O5z5i*********-1xxp0V"); DescribeFileModerationResultRequest describeFileModerationResultRequest = new DescribeFileModerationResultRequest(); describeFileModerationResultRequest.setService("document_detection_global"); describeFileModerationResultRequest.setServiceParameters(serviceParameters.toJSONString()); try { DescribeFileModerationResultResponse response = client.describeFileModerationResult(describeFileModerationResultRequest); if (response.getStatusCode() == 200) { DescribeFileModerationResultResponseBody 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()) { DescribeFileModerationResultResponseBody.DescribeFileModerationResultResponseBodyData data = result.getData(); System.out.println("pageResult = " + JSON.toJSONString(data.getPageResult())); System.out.println("dataId = " + data.getDataId()); System.out.println("url = " + data.getUrl()); } else { System.out.println("file moderation result not success. code:" + result.getCode()); } } else { System.out.println("response not success. status:" + response.getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } } }
Python SDK
Supports Python 3.6 and subsequent versions.
For the source code, refer to the Python SDK repository.
Supports three types of document detection:
Detect documents accessible via the public network
Scenarios
When the document awaiting review is accessible via a public network link, the version 2.0 of the document review service can retrieve the file using its URL for examination.
To install pip, execute the following command:
pip install alibabacloud_green20220302==2.2.11Integrate the Python SDK.
Sample code for submitting a document detection 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 has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. # We recommend that you do not save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, and this may compromise the security of all resources within your account. # Common methods to obtain environment variables: # Obtain RAM user AccessKey ID: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain RAM user AccessKey Secret: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='It is recommended to obtain the RAM user AccessKey ID from environment variables', access_key_secret='It is recommended to obtain the RAM user AccessKey Secret from environment variables', # Connection timeout in milliseconds (ms) connect_timeout=10000, # Read timeout in milliseconds (ms) read_timeout=3000, region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) clt = Client(config) serviceParameters = { 'url': 'https://detect-obj.oss-cn-hangzhou.aliyuncs.com/sample/xxxx.pdf', } fileModerationRequest = models.FileModerationRequest( # Detection type service='document_detection_global', service_parameters=json.dumps(serviceParameters) ) try: response = clt.file_moderation(fileModerationRequest) if response.status_code == 200: # Call 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)Retrieve the results of the document detection 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 has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. # We recommend that you do not save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, and this may compromise the security of all resources within your account. # Common methods to obtain environment variables: # Obtain RAM user AccessKey ID: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain RAM user AccessKey Secret: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='It is recommended to obtain the RAM user AccessKey ID from environment variables', access_key_secret='It is recommended to obtain the RAM user AccessKey Secret from environment variables', # Connection timeout in milliseconds (ms) connect_timeout=10000, # Read timeout in milliseconds (ms) read_timeout=3000, region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) clt = Client(config) # taskId returned when the task is submitted serviceParameters = { "taskId": 'fi_f_11w5THcb*******a-1xx7hH' } describeFileModerationResultRequest = models.DescribeFileModerationResultRequest( # Detection type service='document_detection_global', service_parameters=json.dumps(serviceParameters) ) try: response = clt.describe_file_moderation_result(describeFileModerationResultRequest) if response.status_code == 200: # Call successful # Obtain review results 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)
Detect local documents
Scenarios
When the document requiring review resides on a local machine without a public network access link, you can upload it to the Object Storage Service (OSS) Bucket provided by Content Moderation. The enhanced version 2.0 service can directly retrieve the document content from OSS for review.
To install pip, execute the following command:
pip install alibabacloud_green20220302==2.2.11Install the OSS SDK:
pip install oss2Integrate the Python SDK.
Sample code for submitting a document detection task:
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 import oss2 import time configs = Config( # The 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 recommend that you do not save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, and this may compromise the security of all resources within your account. # Common methods to obtain environment variables: # Obtain RAM user AccessKey ID: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain RAM user AccessKey Secret: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='It is recommended to obtain the RAM user AccessKey ID from environment variables', access_key_secret='It is recommended to obtain the RAM user AccessKey Secret from environment variables', # Connection timeout in milliseconds (ms). connect_timeout=10000, # Read timeout in milliseconds (ms). read_timeout=10000, # Modify the access region and address according to the actual situation. region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) # Note: The instantiated client here should be reused as much as possible to avoid repeated connections and improve detection performance. client = Client(configs) bucket = None upload_token = None def get_oss_client(is_vpc): global upload_token global bucket if (upload_token == None) or int(upload_token.expiration) <= int(time.time()): response = client.describe_upload_token() upload_token = response.body.data auth = oss2.StsAuth(upload_token.access_key_id, upload_token.access_key_secret, upload_token.security_token) end_point = upload_token.oss_internet_end_point if (is_vpc): end_point = upload_token.oss_internal_end_point bucket = oss2.Bucket(auth, end_point, upload_token.bucket_name) def upload_file(file_name, is_vpc): get_oss_client(is_vpc) object_name = upload_token.file_name_prefix + str(uuid.uuid4()) + '.' + file_name.split('.')[-1] bucket.put_object_from_file(object_name, file_name) return object_name def file_moderation_by_local_file(file_path, is_vpc): # 1. Upload file object_name = upload_file(file_path, is_vpc) # 2. Detection parameters service_parameters = { 'dataId': str(uuid.uuid4()), 'ossBucketName': upload_token.bucket_name, 'ossObjectName': object_name } file_moderation_request = models.FileModerationRequest( # Detection type. service='document_detection_global', service_parameters=json.dumps(service_parameters) ) # Create a RuntimeObject instance and set runtime parameters. runtime = util_models.RuntimeOptions() runtime.read_timeout = 10000 runtime.connect_timeout = 10000 try: global client response = client.file_moderation_with_options(file_moderation_request, runtime) if response.status_code == 200: # Call successful. # Obtain review results. result = response.body print('response success. result:{}'.format(result)) if result.code == 200: result_data = result.data print('result: {}'.format(result_data)) else: print('response not success. status:{} ,result:{}'.format(response.status_code, response)) except Exception as err: print(err) if __name__ == '__main__': # Local file path file_path = '/Users/test/MS.pdf' # Whether to deploy on VPC is_vpc = False # True file_moderation_by_local_file(file_path, is_vpc)Retrieve the results of the document detection 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 has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. # We recommend that you do not save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, and this may compromise the security of all resources within your account. # Common methods to obtain environment variables: # Obtain RAM user AccessKey ID: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain RAM user AccessKey Secret: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='It is recommended to obtain the RAM user AccessKey ID from environment variables', access_key_secret='It is recommended to obtain the RAM user AccessKey Secret from environment variables', # Connection timeout in milliseconds (ms) connect_timeout=10000, # Read timeout in milliseconds (ms) read_timeout=3000, region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) clt = Client(config) # taskId returned when the task is submitted serviceParameters = { "taskId": 'fi_f_11w5THcb*******a-1xx7hH' } describeFileModerationResultRequest = models.DescribeFileModerationResultRequest( # Detection type service='document_detection_global', service_parameters=json.dumps(serviceParameters) ) try: response = clt.describe_file_moderation_result(describeFileModerationResultRequest) if response.status_code == 200: # Call successful # Obtain review results 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)
Detect OSS documents
Scenarios
If you need to review a document stored in Alibaba Cloud Object Storage Service (OSS), you can create a server role to grant the Content Moderation service access to OSS. The document review service, 2.0, will retrieve the file from OSS via the server role for examination. To set up a server role, please visit the cloud resource access authorization page.
To install pip, execute the following command:
pip install alibabacloud_green20220302==2.2.11Integrate the Python SDK.
Sample code for submitting a document detection 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 has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. # We recommend that you do not save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, and this may compromise the security of all resources within your account. # Common methods to obtain environment variables: # Obtain RAM user AccessKey ID: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain RAM user AccessKey Secret: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='It is recommended to obtain the RAM user AccessKey ID from environment variables', access_key_secret='It is recommended to obtain the RAM user AccessKey Secret from environment variables', # Connection timeout in milliseconds (ms) connect_timeout=10000, # Read timeout in milliseconds (ms) read_timeout=3000, region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) clt = Client(config) serviceParameters = { 'ossRegionId': 'cn-hangzhou', 'ossBucketName': 'detect-obj', 'ossObjectName': 'sample/xxxx.pdf' } fileModerationRequest = models.FileModerationRequest( # Detection type service='document_detection_global', service_parameters=json.dumps(serviceParameters) ) try: response = clt.file_moderation(fileModerationRequest) if response.status_code == 200: # Call 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)Retrieve the results of the document detection 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 has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. # We recommend that you do not save the AccessKey ID and the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, and this may compromise the security of all resources within your account. # Common methods to obtain environment variables: # Obtain RAM user AccessKey ID: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain RAM user AccessKey Secret: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='It is recommended to obtain the RAM user AccessKey ID from environment variables', access_key_secret='It is recommended to obtain the RAM user AccessKey Secret from environment variables', # Connection timeout in milliseconds (ms) connect_timeout=10000, # Read timeout in milliseconds (ms) read_timeout=3000, region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) clt = Client(config) # taskId returned when the task is submitted serviceParameters = { "taskId": 'fi_f_11w5THcb*******a-1xx7hH' } describeFileModerationResultRequest = models.DescribeFileModerationResultRequest( # Detection type service='document_detection_global', service_parameters=json.dumps(serviceParameters) ) try: response = clt.describe_file_moderation_result(describeFileModerationResultRequest) if response.status_code == 200: # Call successful # Obtain review results 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
Supports PHP version 5.6 and newer.
For the source code, refer to the PHP SDK on Packagist.
Supports three types of document detection:
Detect documents accessible via the public network
Scenarios
When the document slated for review is accessible via a public network link, the Version 2.0 document review service can retrieve the file using the document's URL for examination.
Run the command below to add the necessary dependencies.
composer require alibabacloud/green-20220302 2.2.10Integrate the PHP SDK.
Sample code for submitting a document detection task:
<?php require('vendor/autoload.php'); use AlibabaCloud\SDK\Green\V20220302\Models\FileModerationRequest; 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 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 the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. * Common methods to obtain environment variables: * Obtain the RAM user AccessKey ID: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the RAM user AccessKey secret: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => 'It is recommended to obtain the RAM user AccessKey ID from environment variables', "accessKeySecret" => 'It is recommended to obtain the RAM user AccessKey secret from environment variables', "endpoint" => "green-cip.ap-southeast-1.aliyuncs.com", "regionId" => "ap-southeast-1" ]); // Note: Please reuse the instantiated client as much as possible to avoid repeated connections and improve detection performance. $client = new Green($config); $request = new FileModerationRequest(); $request->service = "document_detection_global"; $serviceParameters = array("url" => "https://xxx.oss.aliyuncs.com/xxx.pdf"); $request->serviceParameters = json_encode($serviceParameters); $runtime = new RuntimeOptions(); $runtime->readTimeout = 6000; $runtime->connectTimeout = 3000; try { $response = $client->fileModerationWithOptions($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("file 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()); }Retrieve the results of the document detection task:
<?php require('vendor/autoload.php'); use AlibabaCloud\SDK\Green\V20220302\Models\DescribeFileModerationResultRequest; 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 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 the AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. * Common methods to obtain environment variables: * Obtain the RAM user AccessKey ID: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the RAM user AccessKey secret: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => 'It is recommended to obtain the RAM user AccessKey ID from environment variables', "accessKeySecret" => 'It is recommended to obtain the RAM user AccessKey secret from environment variables', "endpoint" => "green-cip.ap-southeast-1.aliyuncs.com", "regionId" => "ap-southeast-1" ]); // Note: Please reuse the instantiated client as much as possible to avoid repeated connections and improve detection performance. $client = new Green($config); $request = new DescribeFileModerationResultRequest(); $request->service = "document_detection_global"; $serviceParameters = array("taskId" => "fi_f_O5z5iaIis*****NYj7qa-1x****"); $request->serviceParameters = json_encode($serviceParameters); $runtime = new RuntimeOptions(); $runtime->readTimeout = 6000; $runtime->connectTimeout = 3000; try { $response = $client->describeFileModerationResultWithOptions($request, $runtime); 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 (280 == $body->code) { print_r("processing file moderation. code:" . $body->code); return; } if (200 != $body->code) { print_r("file moderation result not success. code:" . $body->code); return; } $data = $body->data; print_r("data = " . json_encode($data) . "\n"); print_r("pageResult = " . json_encode($data->pageResult) . "\n"); } catch (TeaUnableRetryError $e) { var_dump($e->getMessage()); var_dump($e->getErrorInfo()); var_dump($e->getLastException()); var_dump($e->getLastRequest()); }
Detect local documents
Scenarios
If the document requiring review resides on a local machine without a public network access link, you can upload it to the Object Storage Service (OSS) Bucket provided by Content Moderation. The Content Moderation service's Version 2.0 can then directly access OSS to retrieve the document content for review.
Run the command below to add the necessary dependencies.
composer require alibabacloud/green-20220302 2.2.10Install the OSS SDK:
composer require aliyuncs/oss-sdk-phpIntegrate the PHP SDK.
Sample code for submitting a document detection task:
Retrieve the results of the document detection task:
Detect OSS documents
Scenarios
If you need to review a document file stored in Alibaba Cloud Object Storage Service (OSS), you can create a server role to grant the Content Moderation service access to OSS. The document review service Version 2.0 will retrieve the file from OSS via the server role for examination. To set up a server role, please visit the cloud resource access authorization page.
Run the command below to add the necessary dependencies.
composer require alibabacloud/green-20220302 2.2.10Integrate the PHP SDK.
Sample code for submitting a document detection task:
Retrieve the results of the document detection task:
Go SDK
Supports three types of document detection:
Detect documents accessible via the public network
Scenarios
When a document requiring review is accessible via a public network link, the Version 2.0 document review service can retrieve the file for review using the document's URL.
Go SDK
Introduce the necessary dependencies with the following command.
go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2Integrate the Go SDK.
Submit a document detection task with the following code example.
package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green20220302 "github.com/alibabacloud-go/green-20220302/v2/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { // Project code leakage may lead to AccessKey leakage and compromise the security of all resources in your account. The following code example is for reference only. It is recommended to use a more secure STS method. config := &openapi.Config{ /** * The 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 in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. * Common methods to obtain environment variables: * Obtain the AccessKey ID of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") * Obtain the AccessKey secret of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ AccessKeyId: tea.String("It is recommended to obtain the AccessKey ID of a RAM user from environment variables"), AccessKeySecret: tea.String("It is recommended to obtain the AccessKey secret of a RAM user from environment variables"), RegionId: tea.String("ap-southeast-1"), Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"), /** * Please set the timeout period. The server-side full-link processing timeout is 10 seconds. Please make the corresponding settings. * If you set the ReadTimeout to be less than the server-side processing time, the program will receive a ReadTimeout exception. */ 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) serviceParameters, _ := json.Marshal( map[string]interface{}{ "url": "https://xxx.oss.aliyuncs.com/xxx.pdf", }, ) request := green20220302.FileModerationRequest{ Service: tea.String("document_detection_global"), ServiceParameters: tea.String(string(serviceParameters)), } result, _err := client.FileModerationWithOptions(&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("file moderation not success. code:%d\n", *body.Code) return } data := body.Data fmt.Printf("file moderation taskId:%s\n", *data.TaskId) }Retrieve the results of the document detection task.
package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green20220302 "github.com/alibabacloud-go/green-20220302/v2/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { // Project code leakage may lead to AccessKey leakage and compromise the security of all resources in your account. The following code example is for reference only. It is recommended to use a more secure STS method. config := &openapi.Config{ /** * The 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 in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. * Common methods to obtain environment variables: * Obtain the AccessKey ID of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") * Obtain the AccessKey secret of a RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ AccessKeyId: tea.String("It is recommended to obtain the AccessKey ID of a RAM user from environment variables"), AccessKeySecret: tea.String("It is recommended to obtain the AccessKey secret of a RAM user from environment variables"), RegionId: tea.String("ap-southeast-1"), Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"), /** * Please set the timeout period. The server-side full-link processing timeout is 10 seconds. Please make the corresponding settings. * If you set the ReadTimeout to be less than the server-side processing time, the program will receive a ReadTimeout exception. */ 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) serviceParameters, _ := json.Marshal( map[string]interface{}{ "taskId": "fi_f_O5z5iaIi******-1x****", }, ) request := green20220302.DescribeFileModerationResultRequest{ Service: tea.String("document_detection_global"), ServiceParameters: tea.String(string(serviceParameters)), } result, _err := client.DescribeFileModerationResultWithOptions(&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 == 280 { fmt.Printf("processing file moderation. code:%d\n", *body.Code) return } if *body.Code != http.StatusOK { fmt.Printf("file moderation result not success. code:%d\n", *body.Code) return } data := body.Data fmt.Printf("file moderation result:%s\n", data) fmt.Printf("file moderation result pageResult:%s\n", data.PageResult) fmt.Printf("file moderation result dataId:%s\n", data.DataId) }
Detect local documents
Scenarios
When the document you need to review is stored on a local machine without a public network access link, you can upload it to the Object Storage Service (OSS) Bucket provided by Content Moderation. The Content Moderation service's Version 2.0 can then directly retrieve the document content from OSS for review.
Introduce the necessary dependencies with the following command.
go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2Install the OSS SDK with this command:
go get github.com/aliyun/aliyun-oss-go-sdk/ossIntegrate the Go SDK.
Submit a document detection task with the following code example.
Retrieve the results of the document detection task.
Detect OSS documents
Scenarios
If you need to review a document file stored in Alibaba Cloud Object Storage Service (OSS), you can grant permission for the Content Moderation service to access OSS by creating a service role. The Content Moderation Version 2.0 will retrieve the file through this service role for review. To set up a service role, please visit the cloud resource access authorization page.
Introduce the necessary dependencies with the following command.
go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2Integrate the Go SDK.
Submit a document detection task with the following code example.
Retrieve the results of the document detection task.
Node.js SDK
Original code. For more details, visit the Node.js SDK source code.
Supports three types of document detection:
Detecting documents accessible via the internet
Scenarios
For documents that are accessible through an internet link and require review, the Document Moderation 2.0 service can retrieve the file via the document URL for analysis.
Run the command below to add the necessary dependencies.
npm install @alicloud/green20220302@2.2.10Integrate the Node.js SDK.
Sample code for submitting a document moderation task
Sample code for retrieving document moderation task results
Detecting local documents
Scenarios
If the document you want to review is stored on a local machine without an internet link, upload it to the Object Storage Service (OSS) bucket provided by Content Moderation. The Document Moderation 2.0 service can then directly access the document in OSS for review.
Run the command below to add the necessary dependencies.
npm install @alicloud/green20220302@2.2.10Install the OSS dependency:
npm install ali-oss --saveIntegrate the Node.js SDK.
Sample code for submitting a document moderation task
Sample code for retrieving document moderation task results
Detecting OSS documents
Scenarios
For documents already stored in Alibaba Cloud Object Storage Service (OSS), authorize the creation of a server role to grant Content Moderation access to OSS. The Document Moderation 2.0 service will then retrieve the document through the server role for analysis. For server role creation, visit the cloud resource access authorization page.
Run the command below to add the necessary dependencies.
npm install @alicloud/green20220302@2.2.10Integrate the Node.js SDK.
Sample code for submitting a document moderation task
Sample code for retrieving document moderation task results
C# SDK
For the source code of the original C# SDK, please refer to this link.
Supports three types of document detection:
Detect documents accessible via the public network
Usage Scenarios
When the document awaiting review is accessible via a public network link, the 2.0 of the document review service can retrieve the file using the document's URL for examination.
Run the following command to add the necessary dependencies.
dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10Integrate the C# SDK.
Example code to submit a document detection task
Example code to retrieve a document detection task result
Detect local documents
Usage Scenarios
When you need to review a document that is stored on a local machine and lacks a public network access link, you can upload it to the Object Storage Service (OSS) Bucket provided by Content Moderation. The 2.0 of the document review service can then directly retrieve and review the content from OSS.
Run the following command to add the necessary dependencies.
dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10Install the OSS SDK:
Install via NuGet 1. If your Visual Studio does not have NuGet installed, please install NuGet first. 2. In Visual Studio, create a new project or open an existing project, and select Tools > NuGet Package Manager > Manage NuGet Packages for Solution. 3. Search for aliyun.oss.sdk, find Aliyun.OSS.SDK (for .NET Framework) or Aliyun.OSS.SDK.NetCore (for .Net Core) in the results, select the latest version, and click Install.Integrate the C# SDK.
Example code to submit a document detection task
Example code to retrieve a document detection task result
Detect OSS documents
Usage Scenarios
If you need to review a document already stored in Alibaba Cloud Object Storage Service (OSS), you can authorize the creation of a server role to grant the Content Moderation service access to OSS. The Document Review 2.0 will retrieve the file through the server role for analysis. To create a server role, please visit the cloud resource access authorization page.
Run the following command to add the necessary dependencies.
dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10Integrate the C# SDK.
Example code to submit a document detection task
Example code to retrieve a document detection task result
Native HTTPS calls
Call Method
Service request address: https://green-cip.{region}.aliyuncs.com
Protocol: HTTPS
Method: POST
Common Request Parameters
The input parameters for the enhanced document moderation API include both common and specific interface request parameters. Common request parameters are required by all interfaces. A detailed description of these parameters is provided in the following table.
Name
Type
Required
Description
Format
String
Yes
The response format. Valid values:
JSON (default)
XML
Version
String
Yes
The API version number in the YYYY-MM-DD date format. The current version is 2022-03-02.
AccessKeyId
String
Yes
The AccessKey ID provided by Alibaba Cloud for accessing services.
Signature
String
Yes
The signature string. For information about how to calculate the signature, see the signature method below.
SignatureMethod
String
Yes
The signature method. Currently, HMAC-SHA1 is supported.
Timestamp
String
Yes
The timestamp of the request. The date format follows the ISO 8601 standard and must use UTC time.
The format is: yyyy-MM-ddTHH:mm:ssZ.
For example, 09:13:14 on December 12, 2022, Beijing time is represented as 2022-12-12T01:13:14Z.
SignatureVersion
String
Yes
The signature algorithm version. The value is 1.0.
SignatureNonce
String
Yes
A unique random number used to prevent replay attacks. Different requests must use different random numbers.
Action
String
Yes
Valid values:
FileModeration
DescribeFileModerationResult
Common Response Parameters
Each interface call returns a unique access token (RequestId), regardless of success. Other response parameters will vary based on the service called.
{ "Msg": "OK", "Code": 200, "Data": { "TaskId": "AAAAA-BBBBB-CCCCCCCC" }, "RequestId": "ABCD1234-1234-1234-1234-123****" }Code Examples
The examples below are formatted for readability. Actual returns are not formatted with line breaks or indents.
Moderation task code example
Request example
Sample success response
{ "Msg": "OK", "Code": 200, "Data": { "TaskId": "AAAAA-BBBBB-CCCCCCCC" }, "RequestId": "ABCD1234-1234-1234-1234-123****" }Query task code example
Request example
Sample success response
{ "Code": 200, "Data": { "DataId": "fileId*****", "PageResult": [ { "ImageResult": [ { "Description": "Image content moderation of the document page", "LabelResult": [ { "label": "nonLabel" } ], "Service": "baselineCheck" } ], "ImageUrl": "http://oss.aliyundoc.com/a.png", "PageNum": 1, "TextResult": [ { "Description": "Text content moderation of the document page", "Labels": "", "RiskTips": "", "RiskWords": "", "Service": "pgc_detection", "Text": "Content moderation product test case a" } ] }, ... { "ImageResult": [ { "Description": "Image content moderation of the document page", "LabelResult": [ { "Confidence": 89.01, "Label": "pornographic_adultContent_tii" } ], "Service": "baselineCheck" } ], "ImageUrl": "http://oss.aliyundoc.com/b.png", "PageNum": 10, "TextResult": [ { "Description": "Text content moderation of the document page", "Labels": "contraband,sexual_content", "RiskTips": "prohibited_prohibited_goods,sexual_films,sexual_vulgar", "RiskWords": "risk word A,risk word B", "Service": "ad_compliance_detection", "Text": "Content moderation product test case b" } ] } ], "Url": "http://www.aliyundoc.com/a.docx" }, "Message": "SUCCESS", "RequestId": "1D0854A7-AAAAA-BBBBBBB-CC8292AE5" }
Signature Method
The enhanced document moderation service requires authentication for each access request, which includes signature information. Symmetric encryption with the AccessKey ID and AccessKey Secret is used to verify the requester's identity.
The AccessKey ID and AccessKey Secret are credentials provided by Alibaba Cloud to the user, which can be obtained and managed via the Alibaba Cloud official website. The AccessKey ID identifies the user, while the AccessKey Secret, which must be kept confidential, is used to encrypt and verify the signature string on the server side.
Users can sign their requests as follows:
Create a canonicalized query string using the request parameters.
Sort all request parameters alphabetically by name, excluding the Signature parameter.
URL-encode the parameter names and values based on the UTF-8 character set.
NoteUse libraries that support URL encoding, such as java.net.URLEncoder in Java, which encodes according to application/x-www-form-urlencoded MIME type rules. Replace plus signs (+) with %20, asterisks (*) with %2A, and %7E with a tilde (~).
The URL encoding rules are as follows:
Characters A-Z, a-z, 0-9, hyphen (-), underscore (_), period (.), and tilde (~) are not encoded.
Characters outside the standard range are encoded using the format
%XY, where XY represents the character's ASCII code in hexadecimal. For instance, the English double quotation mark (") is encoded as%22.Extended UTF-8 characters are encoded as
%XY%ZA….The space character is encoded as
%20, not a plus sign (+).
Connect the encoded names and values with equal signs (=).
Use the & symbol to connect the strings in alphabetical order to form the canonicalized query string.
Construct the string for signature calculation using the canonicalized string from the previous step.
StringToSign= HTTPMethod + "&" + percentEncode ("/") + "&" + percentEncode (CanonicalizedQueryString)NoteHTTPMethod is the method used for the request, such as POST. percentEncode(/) is the encoded value of the slash (/) character, which is
%2F. percentEncode(CanonicalQueryString) is the encoded canonicalized query string.Calculate the HMAC value of the signature string according to RFC2104.
NoteThe key for calculating the signature is the user's AccessKey Secret followed by an
&(ASCII:38). The SHA1 hash algorithm is used.Base64-encode the HMAC value to obtain the signature (Signature).
Add the signature value to the request parameters as the Signature parameter to complete the signing process.
NoteWhen submitting the signature value to the content moderation server, it must be URL encoded according to RFC3986, like other parameters.