You can integrate with Document ModerationEnhanced Edition by using an SDK or native HTTPS calls. We recommend using an SDK because it handles technical details, such as signature verification and request body construction, for you. This topic describes how to integrate with Document ModerationEnhanced Edition.
Step 1: Activate the service
Go to the Activate Content Moderation Enhanced Edition page to activate Content Moderationenhanced edition. After you start using the API, you are billed for your usage. For more information, see billing details. You can also purchase a pay-as-you-go resource package. Resource packages offer tiered discounts and are ideal for users with predictable or high usage.
After you activate Content Moderationenhanced edition, pay-as-you-go is the default billing method. You are charged daily for your actual usage. You are charged only when you use the service.
Step 2: Grant permissions to a RAM user
Before you integrate with the SDK or API, you must grant permissions to a RAM user. You need an AccessKey pair to authenticate calls to Alibaba Cloud APIs. For instructions, see Obtain an AccessKey.
Grant permissions to a RAM user
Log on to the RAM console using your Alibaba Cloud account.
Create a RAM user. For details, see Create a RAM user.
Grant the
AliyunYundunGreenWebFullAccesssystem policy to the RAM user. This policy grants full access to Content Moderation. For details, see Manage RAM user permissions.The RAM user can now call the Content Moderation API.
Step 3: Set up the document moderation service
Supported regions:
|
Region |
Public endpoint |
VPC endpoint |
Supported services |
|
China (Shanghai) |
green-cip.cn-shanghai.aliyuncs.com |
green-cip-vpc.cn-shanghai.aliyuncs.com |
document_detection, document_detection_byvl |
|
China (Beijing) |
green-cip.cn-beijing.aliyuncs.com |
green-cip-vpc.cn-beijing.aliyuncs.com |
|
|
China (Hangzhou) |
green-cip.cn-hangzhou.aliyuncs.com |
green-cip-vpc.cn-hangzhou.aliyuncs.com |
|
|
China (Shenzhen) |
green-cip.cn-shenzhen.aliyuncs.com |
green-cip-vpc.cn-shenzhen.aliyuncs.com |
|
|
Singapore |
green-cip.ap-southeast-1.aliyuncs.com |
green-cip-vpc.ap-southeast-1.aliyuncs.com |
document_detection_cb, |
Use OpenAPI Explorer to debug an API and automatically generate SDK sample code in other programming languages.
Alibaba Cloud SDKs create default credentials by reading the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. When you call an API operation, the program reads your AccessKey from these variables and automatically completes authentication. Before you use SDK sample code, you must configure the environment variables. For more information, see Configure authentication credentials.
For API field descriptions, see Content Moderation - Enhanced 2.0 API.
Java SDK
Supports Java 1.8 or later.
See Java SDK source code or Java SDK source code (OSS path).
This feature supports the following three document detection types.
Public document moderation
Use cases
The file moderation Enhanced Edition service can moderate publicly accessible documents by fetching them from a URL.
To use the SDK in your Maven project, add the dependency to the pom.xml file.
-
Add the following dependency to the dependencies section:
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>3.3.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(); /** * An AccessKey pair for an Alibaba Cloud account has permissions on all API operations. We recommend using a RAM user to call API operations or perform routine O&M. * Common methods to obtain environment variables: * Method 1: * Obtain the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Obtain the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ config.setAccessKeyId("YOUR_ACCESS_KEY_ID"); config.setAccessKeySecret("YOUR_ACCESS_KEY_SECRET"); // Modify the region and endpoint as needed. config.setRegionId("cn-shanghai"); config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com"); // The read timeout. Unit: milliseconds (ms). config.setReadTimeout(6000); // The connection timeout. Unit: milliseconds (ms). config.setConnectTimeout(3000); Client client = new Client(config); JSONObject serviceParameters = new JSONObject(); serviceParameters.put("url", "https://xxx.oss.aliyuncs.com/xxx.pdf"); // The URL of the file. FileModerationRequest fileModerationRequest = new FileModerationRequest(); // Specify the detection service: document_detection for general document detection. fileModerationRequest.setService("document_detection"); 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 failed. Code: " + code); } } else { System.out.println("The response was unsuccessful. Status: " + response.getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } } } -
Sample code for retrieving a document detection result
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(); /** * An AccessKey pair for an Alibaba Cloud account has permissions on all API operations. We recommend using a RAM user to call API operations or perform routine O&M. * Common methods to obtain environment variables: * Method 1: * Obtain the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Obtain the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ config.setAccessKeyId("YOUR_ACCESS_KEY_ID"); config.setAccessKeySecret("YOUR_ACCESS_KEY_SECRET"); // Modify the region and endpoint as needed. config.setRegionId("cn-shanghai"); config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com"); // The read timeout. Unit: milliseconds (ms). config.setReadTimeout(6000); // The connection timeout. Unit: milliseconds (ms). config.setConnectTimeout(3000); Client client = new Client(config); JSONObject serviceParameters = new JSONObject(); // The task ID returned after submitting the moderation task. serviceParameters.put("taskId", "fi_f_O5z5i*********-1xxp0V"); DescribeFileModerationResultRequest describeFileModerationResultRequest = new DescribeFileModerationResultRequest(); describeFileModerationResultRequest.setService("document_detection"); 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("Querying the file moderation result failed. Code: " + result.getCode()); } } else { System.out.println("The response was unsuccessful. Status: " + response.getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } } }
-
Scan local documents
Scenarios
If you need to moderate a document stored on a local machine without a public URL, upload it to an Object Storage Service (OSS) bucket. The File Moderation Enhanced Edition service can then access the document from the OSS bucket to moderate it.
-
Add the following dependency to the dependencies section:
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>3.3.3</version> </dependency>Add the OSS SDK dependency:
<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 file moderation 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 { /** Specifies whether the service is deployed in a VPC. */ public static boolean isVPC = false; /** Caches upload tokens. This map maps endpoints to tokens. */ public static Map<String, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData> tokenMap = new HashMap<>(); /** The client used to upload files. */ public static OSS ossClient = null; /** * Creates a client to send requests. * * @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 endpoint based on your actual deployment. config.setEndpoint(endpoint); return new Client(config); } /** * Creates a client to upload files. * * @param tokenData * @param isVPC */ public static void getOssClient(DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData, boolean isVPC) { // For better performance, we recommend reusing the client instance. 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()); } } /** * Uploads a 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 { // For better performance, we recommend reusing the client instance. Client client = createClient(accessKeyId, accessKeySecret, endpoint); RuntimeOptions runtime = new RuntimeOptions(); // The absolute path of the local file. Example: D:\localPath\exampleFile.mp3. String filePath = "D:/test/1.pdf"; // Obtain a 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()); } // Create a client for file uploads. getOssClient(tokenMap.get(endpoint), isVPC); // Upload the file. String objectName = uploadFile(filePath, tokenMap.get(endpoint)); // Construct moderation parameters. Map<String, String> serviceParameters = new HashMap<>(); // Specify file upload information. serviceParameters.put("ossBucketName", tokenMap.get(endpoint).getBucketName()); serviceParameters.put("ossObjectName", objectName); serviceParameters.put("dataId", UUID.randomUUID().toString()); FileModerationRequest request = new FileModerationRequest(); // Specify the moderation service. request.setService("document_detection"); 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 { /** * An AccessKey pair for an Alibaba Cloud account grants full permissions to all API operations. For improved security, we recommend using a RAM user to make API calls or perform routine maintenance. * 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"); */ String accessKeyId = "YOUR_ACCESS_KEY_ID"; String accessKeySecret = "YOUR_ACCESS_KEY_SECRET"; // Modify the region and endpoint based on your actual deployment. FileModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-shanghai.aliyuncs.com"); try { // Automatic failover to a different region. if (response != null) { // If the request fails, try switching to the China (Beijing) region. if (500 == response.getStatusCode() || (response.getBody() != null && 500 == (response.getBody().getCode()))) { // Modify the region and endpoint based on your actual deployment. response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-beijing.aliyuncs.com"); } } // Print the moderation result. 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 { // File moderation failed. code: System.out.println("File moderation failed. code: " + code); } } else { // Request failed. status: System.out.println("Request failed. status: " + response.getStatusCode()); } } } catch (Exception e) { e.printStackTrace(); } } } -
Sample code for retrieving the file moderation result
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(); /** * An AccessKey pair for an Alibaba Cloud account grants full permissions to all API operations. For improved security, we recommend using a RAM user to make API calls or perform routine maintenance. * 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("YOUR_ACCESS_KEY_ID"); config.setAccessKeySecret("YOUR_ACCESS_KEY_SECRET"); // Modify the region and endpoint based on your actual deployment. config.setRegionId("cn-shanghai"); config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com"); // Read timeout in milliseconds (ms). config.setReadTimeout(6000); // Connection timeout in milliseconds (ms). config.setConnectTimeout(3000); Client client = new Client(config); JSONObject serviceParameters = new JSONObject(); // The ID of the task returned upon submission. serviceParameters.put("taskId", "fi_f_O5z5i*********-1xxp0V"); DescribeFileModerationResultRequest describeFileModerationResultRequest = new DescribeFileModerationResultRequest(); describeFileModerationResultRequest.setService("document_detection"); 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 { // Failed to retrieve file moderation result. code: System.out.println("Failed to retrieve file moderation result. code: " + result.getCode()); } } else { // Request failed. status: System.out.println("Request failed. status: " + response.getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } } }
-
Moderate documents in OSS
Scenarios
To moderate documents stored in OSS, create a service role to authorize Content Moderation. The File Moderation (Enhanced) service then uses this role to retrieve and moderate the documents. To create a service role, visit the Cloud Resource Access Authorization page.
-
Add the following dependencies:
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>3.3.3</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 file moderation 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(); /** * An AccessKey pair of an Alibaba Cloud account has permissions for all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Methods to obtain environment variables: * Method 1: * Obtain the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Obtain the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ config.setAccessKeyId("YOUR_ACCESS_KEY_ID"); config.setAccessKeySecret("YOUR_ACCESS_KEY_SECRET"); // Modify the region and endpoint based on your deployment. config.setRegionId("cn-shanghai"); config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com"); // The read timeout period. Unit: milliseconds (ms). config.setReadTimeout(6000); // The connection timeout period. Unit: milliseconds (ms). config.setConnectTimeout(3000); Client client = new Client(config); JSONObject serviceParameters = new JSONObject(); serviceParameters.put("ossBucketName", "your-bucket-name"); serviceParameters.put("ossObjectName", "path/to/your/document.pdf"); serviceParameters.put("ossRegionId", "cn-beijing"); FileModerationRequest fileModerationRequest = new FileModerationRequest(); // The moderation service. Set the value to document_detection for general document detection. fileModerationRequest.setService("document_detection"); 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 failed. code:" + code); } } else { System.out.println("The response was unsuccessful. status:" + response.getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } } } -
Sample code for retrieving the result of a file moderation 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(); /** * An AccessKey pair of an Alibaba Cloud account has permissions for all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Methods to obtain environment variables: * Method 1: * Obtain the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Obtain the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ config.setAccessKeyId("YOUR_ACCESS_KEY_ID"); config.setAccessKeySecret("YOUR_ACCESS_KEY_SECRET"); // Modify the region and endpoint based on your deployment. config.setRegionId("cn-shanghai"); config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com"); // The read timeout period. Unit: milliseconds (ms). config.setReadTimeout(6000); // The connection timeout period. Unit: milliseconds (ms). config.setConnectTimeout(3000); Client client = new Client(config); JSONObject serviceParameters = new JSONObject(); // The task ID returned by the submission request. serviceParameters.put("taskId", "fi_f_O5z5i*********-1xxp0V"); DescribeFileModerationResultRequest describeFileModerationResultRequest = new DescribeFileModerationResultRequest(); describeFileModerationResultRequest.setService("document_detection"); 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("Failed to retrieve the file moderation result. code:" + result.getCode()); } } else { System.out.println("The response was unsuccessful. status:" + response.getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } } }
-
Python SDK
Supports Python 3.6 and later.
For the source code, see Python SDK source code.
This SDK supports the following three types of document detection.
Publicly accessible documents
Scenarios
If a document you want to moderate is accessible via a public URL, the File Moderation enhanced edition service can fetch and moderate it.
-
Run the following command to install the SDK:
pip install alibabacloud_green20220302==3.2.4 -
Integrate the Python SDK.
-
Submit 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 import os config = Config( # For authentication, an AccessKey pair is required. # For security, we recommend that you use a RAM user to call API operations and store the AccessKey pair in environment variables. # Do not hard-code the AccessKey ID or AccessKey secret in your code. Otherwise, the AccessKey pair may be leaked. # Before running the code, set the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'), access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'), # The connection timeout. Unit: milliseconds. connect_timeout=10000, # The read timeout. Unit: milliseconds. read_timeout=3000, region_id='cn-shanghai', endpoint='green-cip.cn-shanghai.aliyuncs.com' ) clt = Client(config) serviceParameters = { 'url': 'https://detect-obj.oss-cn-hangzhou.aliyuncs.com/sample/xxxx.pdf', } fileModerationRequest = models.FileModerationRequest( # The type of the detection service. service='document_detection', service_parameters=json.dumps(serviceParameters) ) try: response = clt.file_moderation(fileModerationRequest) if response.status_code == 200: # The API call was 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) -
Get the document detection result
# coding=utf-8 # python version >= 3.6 from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config import json import os config = Config( # For authentication, an AccessKey pair is required. # For security, we recommend that you use a RAM user to call API operations and store the AccessKey pair in environment variables. # Do not hard-code the AccessKey ID or AccessKey secret in your code. Otherwise, the AccessKey pair may be leaked. # Before running the code, set the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'), access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'), # The connection timeout. Unit: milliseconds. connect_timeout=10000, # The read timeout. Unit: milliseconds. read_timeout=3000, region_id='cn-shanghai', endpoint='green-cip.cn-shanghai.aliyuncs.com' ) clt = Client(config) # The ID of the task to query, which is returned upon task submission. serviceParameters = { "taskId": 'fi_f_11w5THcb*******a-1xx7hH' } describeFileModerationResultRequest = models.DescribeFileModerationResultRequest( # The type of the detection service. service='document_detection', service_parameters=json.dumps(serviceParameters) ) try: response = clt.describe_file_moderation_result(describeFileModerationResultRequest) if response.status_code == 200: # The API call was successful. # Obtain the moderation result. 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)
-
Local documents
Scenarios
If the document you want to moderate is stored on a local machine and does not have a public URL, you can upload it to an Object Storage Service (OSS) bucket provided by Content Moderation. The File Moderation enhanced edition service then accesses the bucket to moderate the document.
-
Run the following command to install the SDK:
pip install alibabacloud_green20220302==3.2.4Install the OSS SDK:
pip install oss2 -
Integrate the Python SDK.
-
Submit 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 os import oss2 import time configs = Config( # For authentication, an AccessKey pair is required. # For security, we recommend that you use a RAM user to call API operations and store the AccessKey pair in environment variables. # Do not hard-code the AccessKey ID or AccessKey secret in your code. Otherwise, the AccessKey pair may be leaked. # Before running the code, set the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'), access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'), # The connection timeout. Unit: milliseconds. connect_timeout=10000, # The read timeout. Unit: milliseconds. read_timeout=10000, # Modify the region and endpoint based on your business requirements. region_id='cn-shanghai', endpoint='green-cip.cn-shanghai.aliyuncs.com' ) # Note: To improve performance, reuse the client instance to avoid repeated connections. 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 the file. object_name = upload_file(file_path, is_vpc) # 2. Configure the detection parameters. service_parameters = { 'dataId': str(uuid.uuid4()), 'ossBucketName': upload_token.bucket_name, 'ossObjectName': object_name } file_moderation_request = models.FileModerationRequest( # The type of the detection service. service='document_detection', service_parameters=json.dumps(service_parameters) ) # Create a RuntimeOptions instance and configure 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 a server-side error occurs, this code manually fails over to a different region. if UtilClient.equal_number(500, response.status_code) or not response or not response.body or 200 != response.body.code: # A server-side error occurred. Switch to the China (Beijing) region. configs.region_id = 'cn-beijing' configs.endpoint = 'green-cip.cn-beijing.aliyuncs.com' client = Client(configs) response = client.file_moderation_with_options(file_moderation_request, runtime) if response.status_code == 200: # The API call was successful. # Obtain the moderation result. 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__': # The path to the local file. file_path = '/Users/test/MS.pdf' # Specifies whether the service is deployed in a VPC. is_vpc = False # True file_moderation_by_local_file(file_path, is_vpc) -
Get the document detection result
# coding=utf-8 # python version >= 3.6 from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config import json import os config = Config( # For authentication, an AccessKey pair is required. # For security, we recommend that you use a RAM user to call API operations and store the AccessKey pair in environment variables. # Do not hard-code the AccessKey ID or AccessKey secret in your code. Otherwise, the AccessKey pair may be leaked. # Before running the code, set the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'), access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'), # The connection timeout. Unit: milliseconds. connect_timeout=10000, # The read timeout. Unit: milliseconds. read_timeout=3000, region_id='cn-shanghai', endpoint='green-cip.cn-shanghai.aliyuncs.com' ) clt = Client(config) # The ID of the task to query, which is returned upon task submission. serviceParameters = { "taskId": 'fi_f_11w5THcb*******a-1xx7hH' } describeFileModerationResultRequest = models.DescribeFileModerationResultRequest( # The type of the detection service. service='document_detection', service_parameters=json.dumps(serviceParameters) ) try: response = clt.describe_file_moderation_result(describeFileModerationResultRequest) if response.status_code == 200: # The API call was successful. # Obtain the moderation result. 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)
-
OSS documents
Scenarios
If your document is already in Object Storage Service (OSS), you can authorize Content Moderation to access it by creating a service role. This role allows the File Moderation enhanced edition service to read your OSS files for moderation. To create the service role, visit the Cloud Resource Access Authorization page.
-
Run the following command to install the SDK:
pip install alibabacloud_green20220302==3.2.4 -
Integrate the Python SDK.
-
Submit 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 import os config = Config( # For authentication, an AccessKey pair is required. # For security, we recommend that you use a RAM user to call API operations and store the AccessKey pair in environment variables. # Do not hard-code the AccessKey ID or AccessKey secret in your code. Otherwise, the AccessKey pair may be leaked. # Before running the code, set the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'), access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'), # The connection timeout. Unit: milliseconds. connect_timeout=10000, # The read timeout. Unit: milliseconds. read_timeout=3000, region_id='cn-shanghai', endpoint='green-cip.cn-shanghai.aliyuncs.com' ) clt = Client(config) serviceParameters = { 'ossRegionId': 'cn-hangzhou', 'ossBucketName': 'detect-obj', 'ossObjectName': 'sample/xxxx.pdf' } fileModerationRequest = models.FileModerationRequest( # The type of the detection service. service='document_detection', service_parameters=json.dumps(serviceParameters) ) try: response = clt.file_moderation(fileModerationRequest) if response.status_code == 200: # The API call was 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) -
Get the document detection result
# coding=utf-8 # python version >= 3.6 from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config import json import os config = Config( # For authentication, an AccessKey pair is required. # For security, we recommend that you use a RAM user to call API operations and store the AccessKey pair in environment variables. # Do not hard-code the AccessKey ID or AccessKey secret in your code. Otherwise, the AccessKey pair may be leaked. # Before running the code, set the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'), access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET'), # The connection timeout. Unit: milliseconds. connect_timeout=10000, # The read timeout. Unit: milliseconds. read_timeout=3000, region_id='cn-shanghai', endpoint='green-cip.cn-shanghai.aliyuncs.com' ) clt = Client(config) # The ID of the task to query, which is returned upon task submission. serviceParameters = { "taskId": 'fi_f_11w5THcb*******a-1xx7hH' } describeFileModerationResultRequest = models.DescribeFileModerationResultRequest( # The type of the detection service. service='document_detection', service_parameters=json.dumps(serviceParameters) ) try: response = clt.describe_file_moderation_result(describeFileModerationResultRequest) if response.status_code == 200: # The API call was successful. # Obtain the moderation result. 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 5.6 and later.
For the source code, see PHP SDK source code.
The following three types of document detection are supported.
Publicly accessible documents
Use cases
If the document you want to moderate is accessible via a public URL, the file moderation enhanced edition service can fetch the file and moderate it.
-
Run the following command to install the dependencies:
composer require alibabacloud/green-20220302 3.2.4 -
Integrate the PHP SDK.
-
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. * To enhance security, do not hard-code your AccessKey ID and AccessKey Secret in your code. * This practice can lead to credential leaks, compromising the security of all resources in your account. Instead, retrieve credentials from environment variables. * To obtain the AccessKey ID of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * To obtain the AccessKey Secret of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), "endpoint" => "green-cip.cn-shanghai.aliyuncs.com", "regionId" => "cn-shanghai" ]); // Note: We recommend that you reuse the client instance to improve performance by avoiding repeated connections. $client = new Green($config); $request = new FileModerationRequest(); $request->service = "document_detection"; $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 successful. 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 successful. 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()); } -
Retrieving the document detection task result
<?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. * To enhance security, do not hard-code your AccessKey ID and AccessKey Secret in your code. * This practice can lead to credential leaks, compromising the security of all resources in your account. Instead, retrieve credentials from environment variables. * To obtain the AccessKey ID of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * To obtain the AccessKey Secret of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), "endpoint" => "green-cip.cn-shanghai.aliyuncs.com", "regionId" => "cn-shanghai" ]); // Note: We recommend that you reuse the client instance to improve performance by avoiding repeated connections. $client = new Green($config); $request = new DescribeFileModerationResultRequest(); $request->service = "document_detection"; $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 successful. 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 successful. 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()); }
-
Local documents
Use cases
To moderate a local document that is not publicly accessible, upload it to an OSS bucket provided by Content Moderation. The file moderation enhanced edition service then accesses the file from the bucket and moderates it.
-
Run the following command to install the dependencies:
composer require alibabacloud/green-20220302 3.2.4Install the OSS SDK:
composer require aliyuncs/oss-sdk-php -
Integrate the PHP SDK.
-
Submitting a document detection task
<?php require('vendor/autoload.php'); use AlibabaCloud\SDK\Green\V20220302\Models\FileModerationResponse; 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\FileModerationRequest; use OSS\OssClient; // Specifies whether the service is deployed in a VPC. $isVPC = false; // Caches upload tokens. $tokenArray = array(); // The client for file upload requests. $ossClient = null; /** * Creates a request client. * @param $accessKeyId * @param $accessKeySecret * @param $endpoint * @return Green */ function create_client($accessKeyId, $accessKeySecret, $endpoint): Green { $config = new Config([ "accessKeyId" => $accessKeyId, "accessKeySecret" => $accessKeySecret, // Set an HTTP proxy. // "httpProxy" => "http://10.10.xx.xx:xxxx", // Set an HTTPS proxy. // "httpsProxy" => "https://10.10.xx.xx:xxxx", "endpoint" => $endpoint, ]); return new Green($config); } /** * Creates a client for file uploads. * @param $tokenData * @return void */ function create_upload_client($tokenData): void { global $isVPC; global $ossClient; // Note: We recommend that you reuse the client instance to improve performance by avoiding repeated connections. if ($isVPC) { $ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternalEndPoint, false, $tokenData->securityToken); } else { $ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternetEndPoint, false, $tokenData->securityToken); } } /** * Uploads a file. * @param $filePath * @param $tokenData * @return string * @throws \OSS\Core\OssException */ function upload_file($filePath, $tokenData): string { global $ossClient; // Initialize OssClient. create_upload_client($tokenData); $split = explode(".", $filePath); if (count($split) > 1) { $objectName = $tokenData->fileNamePrefix . uniqid() . "." . explode(".", $filePath)[count($split) - 1]; } else { $objectName = $tokenData->fileNamePrefix . uniqid(); } // Upload the file. $ossClient->uploadFile($tokenData->bucketName, $objectName, $filePath); return $objectName; } /** * Submits a detection task. * @param $accessKeyId * @param $accessKeySecret * @param $endpoint * @return FileModerationResponse * @throws \OSS\Core\OssException */ function invoke($accessKeyId, $accessKeySecret, $endpoint): FileModerationResponse { global $tokenArray; // Note: We recommend that you reuse the client instance to improve performance by avoiding repeated connections. $client = create_client($accessKeyId, $accessKeySecret, $endpoint); // Create a RuntimeOptions instance and configure the runtime parameters. $runtime = new RuntimeOptions([]); // The absolute path of the local file. Example: D:\\localPath\\exampleFile.mp3. $filePath = "/Users/test/pdf/MS.pdf"; // Obtain a file upload token. if (!isset($tokenArray[$endpoint]) || $tokenArray[$endpoint]->expiration <= time()) { $token = $client->describeUploadToken(); $tokenArray[$endpoint] = $token->body->data; } // Upload the file. $objectName = upload_file($filePath, $tokenArray[$endpoint]); // Construct the detection parameters. $request = new FileModerationRequest(); // Example: document_detection $request->service = "document_detection"; // Information about the OSS file to be moderated. $serviceParameters = array( 'ossObjectName' => $objectName, 'ossBucketName' => $tokenArray[$endpoint]->bucketName, 'dataId' => uniqid()); $request->serviceParameters = json_encode($serviceParameters); // Submit the detection task. return $client->fileModerationWithOptions($request, $runtime); } /** * 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. * To enhance security, do not hard-code your AccessKey ID and AccessKey Secret in your code. * This practice can lead to credential leaks, compromising the security of all resources in your account. Instead, retrieve credentials from environment variables. * To obtain the AccessKey ID of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * To obtain the AccessKey Secret of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ $accessKeyId = getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); $accessKeySecret = getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); // Replace the region and endpoint based on your actual deployment. $endpoint = "green-cip.cn-shanghai.aliyuncs.com"; try { $response = invoke($accessKeyId, $accessKeySecret, $endpoint); // Automatic routing. if (Utils::equalNumber(500, $response->statusCode) || Utils::equalNumber(500, $response->body->code)) { // Switch the region to cn-beijing. $endpoint = "green-cip.cn-beijing.aliyuncs.com"; $response = invoke($accessKeyId, $accessKeySecret, $endpoint); } print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE)); } catch (Exception $e) { var_dump($e->getMessage()); var_dump($e->getErrorInfo()); var_dump($e->getLastException()); var_dump($e->getLastRequest()); }<?php require('vendor/autoload.php'); use AlibabaCloud\SDK\Green\V20220302\Models\FileModerationResponse; 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\FileModerationRequest; use OSS\OssClient; // Specifies whether the service is deployed in a VPC. $isVPC = false; // Caches upload tokens. $tokenArray = array(); // The client for file upload requests. $ossClient = null; /** * Creates a request client. * @param $accessKeyId * @param $accessKeySecret * @param $endpoint * @return Green */ function create_client($accessKeyId, $accessKeySecret, $endpoint): Green { $config = new Config([ "accessKeyId" => $accessKeyId, "accessKeySecret" => $accessKeySecret, // Set an HTTP proxy. // "httpProxy" => "http://10.10.xx.xx:xxxx", // Set an HTTPS proxy. // "httpsProxy" => "https://10.10.xx.xx:xxxx", "endpoint" => $endpoint, ]); return new Green($config); } /** * Creates a client for file uploads. * @param $tokenData * @return void */ function create_upload_client($tokenData): void { global $isVPC; global $ossClient; // Note: We recommend that you reuse the client instance to improve performance by avoiding repeated connections. if ($isVPC) { $ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternalEndPoint, false, $tokenData->securityToken); } else { $ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternetEndPoint, false, $tokenData->securityToken); } } /** * Uploads a file. * @param $filePath * @param $tokenData * @return string * @throws \OSS\Core\OssException */ function upload_file($filePath, $tokenData): string { global $ossClient; // Initialize OssClient. create_upload_client($tokenData); $split = explode(".", $filePath); if (count($split) > 1) { $objectName = $tokenData->fileNamePrefix . uniqid() . "." . explode(".", $filePath)[count($split) - 1]; } else { $objectName = $tokenData->fileNamePrefix . uniqid(); } // Upload the file. $ossClient->uploadFile($tokenData->bucketName, $objectName, $filePath); return $objectName; } /** * Submits a detection task. * @param $accessKeyId * @param $accessKeySecret * @param $endpoint * @return FileModerationResponse * @throws \OSS\Core\OssException */ function invoke($accessKeyId, $accessKeySecret, $endpoint): FileModerationResponse { global $tokenArray; // Note: We recommend that you reuse the client instance to improve performance by avoiding repeated connections. $client = create_client($accessKeyId, $accessKeySecret, $endpoint); // Create a RuntimeOptions instance and configure the runtime parameters. $runtime = new RuntimeOptions([]); // The absolute path of the local file. Example: D:\\localPath\\exampleFile.mp3. $filePath = "/Users/test/pdf/MS.pdf"; // Obtain a file upload token. if (!isset($tokenArray[$endpoint]) || $tokenArray[$endpoint]->expiration <= time()) { $token = $client->describeUploadToken(); $tokenArray[$endpoint] = $token->body->data; } // Upload the file. $objectName = upload_file($filePath, $tokenArray[$endpoint]); // Construct the detection parameters. $request = new FileModerationRequest(); // Example: document_detection_global $request->service = "document_detection_global"; // Information about the OSS file to be moderated. $serviceParameters = array( 'ossObjectName' => $objectName, 'ossBucketName' => $tokenArray[$endpoint]->bucketName, 'dataId' => uniqid()); $request->serviceParameters = json_encode($serviceParameters); // Submit the detection task. return $client->fileModerationWithOptions($request, $runtime); } /** * 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. * To enhance security, do not hard-code your AccessKey ID and AccessKey Secret in your code. * This practice can lead to credential leaks, compromising the security of all resources in your account. Instead, retrieve credentials from environment variables. * To obtain the AccessKey ID of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * To obtain the AccessKey Secret of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ $accessKeyId = getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); $accessKeySecret = getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); // Replace the region and endpoint based on your actual deployment. $endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; try { $response = invoke($accessKeyId, $accessKeySecret, $endpoint); print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE)); } catch (Exception $e) { var_dump($e->getMessage()); var_dump($e->getErrorInfo()); var_dump($e->getLastException()); var_dump($e->getLastRequest()); } -
Retrieving the document detection task result
<?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. * To enhance security, do not hard-code your AccessKey ID and AccessKey Secret in your code. * This practice can lead to credential leaks, compromising the security of all resources in your account. Instead, retrieve credentials from environment variables. * To obtain the AccessKey ID of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * To obtain the AccessKey Secret of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), "endpoint" => "green-cip.cn-shanghai.aliyuncs.com", "regionId" => "cn-shanghai" ]); // Note: We recommend that you reuse the client instance to improve performance by avoiding repeated connections. $client = new Green($config); $request = new DescribeFileModerationResultRequest(); $request->service = "document_detection"; $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 successful. 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 successful. 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()); }<?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. * To enhance security, do not hard-code your AccessKey ID and AccessKey Secret in your code. * This practice can lead to credential leaks, compromising the security of all resources in your account. Instead, retrieve credentials from environment variables. * To obtain the AccessKey ID of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * To obtain the AccessKey Secret of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), "endpoint" => "green-cip.ap-southeast-1.aliyuncs.com", "regionId" => "ap-southeast-1" ]); // Note: We recommend that you reuse the client instance to improve performance by avoiding repeated connections. $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 successful. 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 successful. 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()); }
-
OSS documents
Use cases
If the document you need to moderate is already stored in OSS, you can authorize Content Moderation to access it directly. To do this, create a service role that grants the Content Moderation service read access to your OSS files. The file moderation enhanced edition service then uses this role to fetch and moderate the document. To create the service role, visit the Cloud Resource Access Authorization page.
-
Run the following command to install the dependencies:
composer require alibabacloud/green-20220302 3.2.4 -
Integrate the PHP SDK.
-
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. * To enhance security, do not hard-code your AccessKey ID and AccessKey Secret in your code. * This practice can lead to credential leaks, compromising the security of all resources in your account. Instead, retrieve credentials from environment variables. * To obtain the AccessKey ID of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * To obtain the AccessKey Secret of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), "endpoint" => "green-cip.cn-shanghai.aliyuncs.com", "regionId" => "cn-shanghai" ]); // Note: We recommend that you reuse the client instance to improve performance by avoiding repeated connections. $client = new Green($config); $request = new FileModerationRequest(); $request->service = "document_detection"; $serviceParameters = array( "ossBucketName" => "your-bucket-name", "ossObjectName" => "your-document.pdf", "ossRegionId" => "cn-shanghai"); $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 successful. 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 successful. 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()); }<?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. * To enhance security, do not hard-code your AccessKey ID and AccessKey Secret in your code. * This practice can lead to credential leaks, compromising the security of all resources in your account. Instead, retrieve credentials from environment variables. * To obtain the AccessKey ID of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * To obtain the AccessKey Secret of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), "endpoint" => "green-cip.ap-southeast-1.aliyuncs.com", "regionId" => "ap-southeast-1" ]); // Note: We recommend that you reuse the client instance to improve performance by avoiding repeated connections. $client = new Green($config); $request = new FileModerationRequest(); $request->service = "document_detection_global"; $serviceParameters = array( "ossBucketName" => "your-bucket-name", "ossObjectName" => "your-document.pdf", "ossRegionId" => "ap-southeast-1"); $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 successful. 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 successful. 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()); } -
Retrieving the document detection task result
<?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. * To enhance security, do not hard-code your AccessKey ID and AccessKey Secret in your code. * This practice can lead to credential leaks, compromising the security of all resources in your account. Instead, retrieve credentials from environment variables. * To obtain the AccessKey ID of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * To obtain the AccessKey Secret of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), "endpoint" => "green-cip.cn-shanghai.aliyuncs.com", "regionId" => "cn-shanghai" ]); // Note: We recommend that you reuse the client instance to improve performance by avoiding repeated connections. $client = new Green($config); $request = new DescribeFileModerationResultRequest(); $request->service = "document_detection"; $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 successful. 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 successful. 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()); }<?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. * To enhance security, do not hard-code your AccessKey ID and AccessKey Secret in your code. * This practice can lead to credential leaks, compromising the security of all resources in your account. Instead, retrieve credentials from environment variables. * To obtain the AccessKey ID of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * To obtain the AccessKey Secret of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), "accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), "endpoint" => "green-cip.ap-southeast-1.aliyuncs.com", "regionId" => "ap-southeast-1" ]); // Note: We recommend that you reuse the client instance to improve performance by avoiding repeated connections. $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 successful. 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 successful. 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()); }
-
Go SDK
The Go SDK supports the following three types of document detection.
Publicly accessible documents
Use cases
If your document is accessible via a public URL, the document detection Enhanced Edition service can fetch and moderate the file.
Go SDK
-
Run the following command to install the dependency.
go get github.com/alibabacloud-go/green-20220302/v3@v3.2.4 -
Integrate the Go SDK.
-
Sample code for submitting a 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/v3/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { // Leaking project code may expose your AccessKey pair and compromise the security of all resources in your account. This sample code is for reference only. We recommend that you use a more secure method, such as STS. config := &openapi.Config{ /** * An AccessKey pair of an Alibaba Cloud account has permissions to call all API operations. We recommend that you use a RAM user for API access or daily O&M. * We strongly recommend that you do not hard-code the AccessKey ID and AccessKey Secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all resources in your account. * You can obtain environment variables in the following ways: * Get the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey Secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ AccessKeyId: tea.String("Specify the AccessKey ID of the RAM user. We recommend that you obtain the AccessKey ID from an environment variable."), AccessKeySecret: tea.String("Specify the AccessKey secret of the RAM user. We recommend that you obtain the AccessKey secret from an environment variable."), RegionId: tea.String("cn-shanghai"), Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"), /** * Set the timeout period. The end-to-end processing timeout period on the server is 10 seconds. We recommend that you configure the timeout period based on this value. * If the ReadTimeout period that you set is shorter than the processing time on the server, a ReadTimeout error is returned. */ 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 options. 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"), 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("document detection not success. code:%d\n", *body.Code) return } data := body.Data fmt.Printf("document detection taskId:%s\n", *data.TaskId) } -
Retrieve the result of a 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/v3/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { // Leaking project code may expose your AccessKey pair and compromise the security of all resources in your account. This sample code is for reference only. We recommend that you use a more secure method, such as STS. config := &openapi.Config{ /** * An AccessKey pair of an Alibaba Cloud account has permissions to call all API operations. We recommend that you use a RAM user for API access or daily O&M. * We strongly recommend that you do not hard-code the AccessKey ID and AccessKey Secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all resources in your account. * You can obtain environment variables in the following ways: * Get the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey Secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ AccessKeyId: tea.String("Specify the AccessKey ID of the RAM user. We recommend that you obtain the AccessKey ID from an environment variable."), AccessKeySecret: tea.String("Specify the AccessKey secret of the RAM user. We recommend that you obtain the AccessKey secret from an environment variable."), RegionId: tea.String("cn-shanghai"), Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"), /** * Set the timeout period. The end-to-end processing timeout period on the server is 10 seconds. We recommend that you configure the timeout period based on this value. * If the ReadTimeout period that you set is shorter than the processing time on the server, a ReadTimeout error is returned. */ 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 options. 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"), 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 document detection. code:%d\n", *body.Code) return } if *body.Code != http.StatusOK { fmt.Printf("document detection result not success. code:%d\n", *body.Code) return } data := body.Data fmt.Printf("document detection result:%s\n", data) fmt.Printf("document detection result pageResult:%s\n", data.PageResult) fmt.Printf("document detection result dataId:%s\n", data.DataId) }
-
Local documents
Use cases
To moderate a local document that is not publicly accessible, upload it to an Object Storage Service (OSS) bucket provided by Content Moderation. The document detection Enhanced Edition service can then access the document from the OSS bucket to moderate it.
-
Run the following command to install the required dependency.
go get github.com/alibabacloud-go/green-20220302/v3@v3.2.4Install the OSS SDK:
go get github.com/aliyun/aliyun-oss-go-sdk/oss -
Integrate the Go SDK.
-
Sample code for submitting a 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/v3/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "github.com/aliyun/aliyun-oss-go-sdk/oss" "github.com/google/uuid" "net/http" "os" "strings" "time" ) // TokenMap caches temporary tokens for file uploads. var TokenMap =make(map[string]*green20220302.DescribeUploadTokenResponseBodyData) // Bucket is the client for file uploads. var Bucket *oss.Bucket // isVPC specifies whether the service is deployed in a VPC. var isVPC = false // createClient creates a request client. func createClient(accessKeyId string, accessKeySecret string, endpoint string) (*green20220302.Client, error) { config := &openapi.Config{ AccessKeyId: tea.String(accessKeyId), AccessKeySecret: tea.String(accessKeySecret), // Set an HTTP proxy. // HTTP proxy: tea.String("http://10.10.xx.xx:xxxx"), // Set an HTTPS proxy. // HTTPS proxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"), Endpoint: tea.String(endpoint), } // Note: Reuse the client instance to avoid creating new connections and improve performance. return green20220302.NewClient(config); } // createOssClient creates a client for file uploads. func createOssClient(tokenData *green20220302.DescribeUploadTokenResponseBodyData) { if isVPC{ ossClient, err := oss.New(tea.StringValue(tokenData.OssInternalEndPoint), tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken))) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } Bucket, _ =ossClient.Bucket(tea.StringValue(tokenData.BucketName)); }else { ossClient, err := oss.New(tea.StringValue(tokenData.OssInternetEndPoint), tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken))) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } Bucket, _ =ossClient.Bucket(tea.StringValue(tokenData.BucketName)); } } // uploadFile uploads a file. func uploadFile(filePath string,tokenData *green20220302.DescribeUploadTokenResponseBodyData) (string,error) { createOssClient(tokenData) objectName := tea.StringValue(tokenData.FileNamePrefix) + uuid.New().String() + "." + strings.Split(filePath, ".")[1] // Upload the file. _err := Bucket.PutObjectFromFile(objectName, filePath) if _err != nil { fmt.Println("Error:", _err) os.Exit(-1) } return objectName,_err } func invoke(accessKeyId string, accessKeySecret string, endpoint string) (_result *green20220302.FileModerationResponse, _err error) { // Note: Reuse the client instance to avoid creating new connections and improve performance. client, _err := createClient(accessKeyId, accessKeySecret, endpoint) if _err != nil { return nil,_err } // Runtime options apply only to requests made with this RuntimeOptions instance. runtime := &util.RuntimeOptions{} // The full path of the local file, for example, /path/to/example.pdf. var filePath = "/path/to/example.pdf" // Obtain a temporary token for file upload. tokenData,ok:=TokenMap[endpoint]; if !ok || tea.Int32Value(tokenData.Expiration) <= int32(time.Now().Unix()) { // Obtain a temporary token for file upload. uploadTokenResponse, _err := client.DescribeUploadToken() if _err != nil { return nil,_err } tokenData = uploadTokenResponse.Body.Data TokenMap[endpoint] = tokenData } var objectName, _ = uploadFile(filePath,TokenMap[endpoint]) // Construct the moderation request. serviceParameters, _ := json.Marshal( map[string]interface{}{ "ossBucketName": tea.StringValue(TokenMap[endpoint].BucketName), "ossObjectName": objectName, "dataId": uuid.New().String(), }, ) fileModerationRequest := &green20220302.FileModerationRequest{ // Example: document_detection Service: tea.String("document_detection"), ServiceParameters: tea.String(string(serviceParameters)), } return client.FileModerationWithOptions(fileModerationRequest, runtime) } func main() { /** * An AccessKey pair of an Alibaba Cloud account has permissions to call all API operations. We recommend that you use a RAM user for API access or daily O&M. * We strongly recommend that you do not hard-code the AccessKey ID and AccessKey Secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all resources in your account. * You can obtain environment variables in the following ways: * Get the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey Secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ var accessKeyId= "Specify the AccessKey ID of the RAM user. We recommend that you obtain the AccessKey ID from an environment variable."; var accessKeySecret= "Specify the AccessKey secret of the RAM user. We recommend that you obtain the AccessKey secret from an environment variable."; // Modify the region and endpoint based on your business requirements. var endpoint = "green-cip.cn-shanghai.aliyuncs.com"; response,_err := invoke(accessKeyId,accessKeySecret,endpoint) flag := false if _err != nil { var err = &tea.SDKError{} if _t, ok := _err.(*tea.SDKError); ok { err = _t if *err.StatusCode == 500 { flag = true } } } if response == nil || *response.StatusCode == 500 || *response.Body.Code == 500 { flag = true } // Failover: Switches the region to China (Beijing) on failure. if flag { endpoint = "green-cip.cn-beijing.aliyuncs.com"; response, _err = invoke(accessKeyId,accessKeySecret,endpoint) } if response != nil { statusCode := tea.IntValue(tea.ToInt(response.StatusCode)) body := response.Body fileModerationResponseData := 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 TaskId:" + tea.StringValue(fileModerationResponseData.TaskId)) } else { fmt.Println("document detection failed. status: " + tea.ToString(body.Code)) } } else { fmt.Print("response failed. status: " + tea.ToString(statusCode)) } } }package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green20220302 "github.com/alibabacloud-go/green-20220302/v3/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "github.com/aliyun/aliyun-oss-go-sdk/oss" "github.com/google/uuid" "net/http" "os" "strings" "time" ) // TokenMap caches temporary tokens for file uploads. var TokenMap =make(map[string]*green20220302.DescribeUploadTokenResponseBodyData) // Bucket is the client for file uploads. var Bucket *oss.Bucket // isVPC specifies whether the service is deployed in a VPC. var isVPC = false // createClient creates a request client. func createClient(accessKeyId string, accessKeySecret string, endpoint string) (*green20220302.Client, error) { config := &openapi.Config{ AccessKeyId: tea.String(accessKeyId), AccessKeySecret: tea.String(accessKeySecret), // Set an HTTP proxy. // HTTP proxy: tea.String("http://10.10.xx.xx:xxxx"), // Set an HTTPS proxy. // HTTPS proxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"), Endpoint: tea.String(endpoint), } // Note: Reuse the client instance to avoid creating new connections and improve performance. return green20220302.NewClient(config); } // createOssClient creates a client for file uploads. func createOssClient(tokenData *green20220302.DescribeUploadTokenResponseBodyData) { if isVPC{ ossClient, err := oss.New(tea.StringValue(tokenData.OssInternalEndPoint), tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken))) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } Bucket, _ =ossClient.Bucket(tea.StringValue(tokenData.BucketName)); }else { ossClient, err := oss.New(tea.StringValue(tokenData.OssInternetEndPoint), tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken))) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } Bucket, _ =ossClient.Bucket(tea.StringValue(tokenData.BucketName)); } } // uploadFile uploads a file. func uploadFile(filePath string,tokenData *green20220302.DescribeUploadTokenResponseBodyData) (string,error) { createOssClient(tokenData) objectName := tea.StringValue(tokenData.FileNamePrefix) + uuid.New().String() + "." + strings.Split(filePath, ".")[1] // Upload the file. _err := Bucket.PutObjectFromFile(objectName, filePath) if _err != nil { fmt.Println("Error:", _err) os.Exit(-1) } return objectName,_err } func invoke(accessKeyId string, accessKeySecret string, endpoint string) (_result *green20220302.FileModerationResponse, _err error) { // Note: Reuse the client instance to avoid creating new connections and improve performance. client, _err := createClient(accessKeyId, accessKeySecret, endpoint) if _err != nil { return nil,_err } // Runtime options apply only to requests made with this RuntimeOptions instance. runtime := &util.RuntimeOptions{} // The full path of the local file, for example, /path/to/example.pdf. var filePath = "/path/to/example.pdf" // Obtain a temporary token for file upload. tokenData,ok:=TokenMap[endpoint]; if !ok || tea.Int32Value(tokenData.Expiration) <= int32(time.Now().Unix()) { // Obtain a temporary token for file upload. uploadTokenResponse, _err := client.DescribeUploadToken() if _err != nil { return nil,_err } tokenData = uploadTokenResponse.Body.Data TokenMap[endpoint] = tokenData } var objectName, _ = uploadFile(filePath,TokenMap[endpoint]) // Construct the moderation request. serviceParameters, _ := json.Marshal( map[string]interface{}{ "ossBucketName": tea.StringValue(TokenMap[endpoint].BucketName), "ossObjectName": objectName, "dataId": uuid.New().String(), }, ) fileModerationRequest := &green20220302.FileModerationRequest{ // Example: document_detection_global Service: tea.String("document_detection_global"), ServiceParameters: tea.String(string(serviceParameters)), } return client.FileModerationWithOptions(fileModerationRequest, runtime) } func main() { /** * An AccessKey pair of an Alibaba Cloud account has permissions to call all API operations. We recommend that you use a RAM user for API access or daily O&M. * We strongly recommend that you do not hard-code the AccessKey ID and AccessKey Secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all resources in your account. * You can obtain environment variables in the following ways: * Get the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey Secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ var accessKeyId= "Specify the AccessKey ID of the RAM user. We recommend that you obtain the AccessKey ID from an environment variable."; var accessKeySecret= "Specify the AccessKey secret of the RAM user. We recommend that you obtain the AccessKey secret from an environment variable."; // Modify the region and endpoint based on your business requirements. var endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; response,_err := invoke(accessKeyId,accessKeySecret,endpoint) flag := false if _err != nil { var err = &tea.SDKError{} if _t, ok := _err.(*tea.SDKError); ok { err = _t if *err.StatusCode == 500 { flag = true } } } if response == nil || *response.StatusCode == 500 || *response.Body.Code == 500 { flag = true } if response != nil { statusCode := tea.IntValue(tea.ToInt(response.StatusCode)) body := response.Body fileModerationResponseData := 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 TaskId:" + tea.StringValue(fileModerationResponseData.TaskId)) } else { fmt.Println("document detection failed. status: " + tea.ToString(body.Code)) } } else { fmt.Print("response failed. status: " + tea.ToString(statusCode)) } } } -
Retrieve the result of a 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/v3/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { // Leaking project code may expose your AccessKey pair and compromise the security of all resources in your account. This sample code is for reference only. We recommend that you use a more secure method, such as STS. config := &openapi.Config{ /** * An AccessKey pair of an Alibaba Cloud account has permissions to call all API operations. We recommend that you use a RAM user for API access or daily O&M. * We strongly recommend that you do not hard-code the AccessKey ID and AccessKey Secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all resources in your account. * You can obtain environment variables in the following ways: * Get the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey Secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ AccessKeyId: tea.String("Specify the AccessKey ID of the RAM user. We recommend that you obtain the AccessKey ID from an environment variable."), AccessKeySecret: tea.String("Specify the AccessKey secret of the RAM user. We recommend that you obtain the AccessKey secret from an environment variable."), RegionId: tea.String("cn-shanghai"), Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"), /** * Set the timeout period. The end-to-end processing timeout period on the server is 10 seconds. We recommend that you configure the timeout period based on this value. * If the ReadTimeout period that you set is shorter than the processing time on the server, a ReadTimeout error is returned. */ 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 options. 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"), 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 document detection. code:%d\n", *body.Code) return } if *body.Code != http.StatusOK { fmt.Printf("document detection result not success. code:%d\n", *body.Code) return } data := body.Data fmt.Printf("document detection result:%s\n", data) fmt.Printf("document detection result pageResult:%s\n", data.PageResult) fmt.Printf("document detection result dataId:%s\n", data.DataId) }package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green20220302 "github.com/alibabacloud-go/green-20220302/v3/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { // Leaking project code may expose your AccessKey pair and compromise the security of all resources in your account. This sample code is for reference only. We recommend that you use a more secure method, such as STS. config := &openapi.Config{ /** * An AccessKey pair of an Alibaba Cloud account has permissions to call all API operations. We recommend that you use a RAM user for API access or daily O&M. * We strongly recommend that you do not hard-code the AccessKey ID and AccessKey Secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all resources in your account. * You can obtain environment variables in the following ways: * Get the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey Secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ AccessKeyId: tea.String("Specify the AccessKey ID of the RAM user. We recommend that you obtain the AccessKey ID from an environment variable."), AccessKeySecret: tea.String("Specify the AccessKey secret of the RAM user. We recommend that you obtain the AccessKey secret from an environment variable."), RegionId: tea.String("ap-southeast-1"), Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"), /** * Set the timeout period. The end-to-end processing timeout period on the server is 10 seconds. We recommend that you configure the timeout period based on this value. * If the ReadTimeout period that you set is shorter than the processing time on the server, a ReadTimeout error is returned. */ 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 options. 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 document detection. code:%d\n", *body.Code) return } if *body.Code != http.StatusOK { fmt.Printf("document detection result not success. code:%d\n", *body.Code) return } data := body.Data fmt.Printf("document detection result:%s\n", data) fmt.Printf("document detection result pageResult:%s\n", data.PageResult) fmt.Printf("document detection result dataId:%s\n", data.DataId) }
-
OSS documents
Use cases
To moderate documents stored in Object Storage Service (OSS), you must first create a service role to grant Content Moderation access to your OSS resources. The document detection Enhanced Edition service then uses this role to fetch and moderate the documents. To create the service role, visit the Cloud Resource Access Authorization page.
-
Run the following command to install the dependency.
go get github.com/alibabacloud-go/green-20220302/v3@v3.2.4 -
Integrate the Go SDK.
-
Sample code for submitting a 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/v3/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { // Leaking project code may expose your AccessKey pair and compromise the security of all resources in your account. This sample code is for reference only. We recommend that you use a more secure method, such as STS. config := &openapi.Config{ /** * An AccessKey pair of an Alibaba Cloud account has permissions to call all API operations. We recommend that you use a RAM user for API access or daily O&M. * We strongly recommend that you do not hard-code the AccessKey ID and AccessKey Secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all resources in your account. * You can obtain environment variables in the following ways: * Get the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey Secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ AccessKeyId: tea.String("Specify the AccessKey ID of the RAM user. We recommend that you obtain the AccessKey ID from an environment variable."), AccessKeySecret: tea.String("Specify the AccessKey secret of the RAM user. We recommend that you obtain the AccessKey secret from an environment variable."), RegionId: tea.String("cn-shanghai"), Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"), /** * Set the timeout period. The end-to-end processing timeout period on the server is 10 seconds. We recommend that you configure the timeout period based on this value. * If the ReadTimeout period that you set is shorter than the processing time on the server, a ReadTimeout error is returned. */ 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 options. runtime := &util.RuntimeOptions{} runtime.ReadTimeout = tea.Int(10000) runtime.ConnectTimeout = tea.Int(10000) serviceParameters, _ := json.Marshal( map[string]interface{}{ "ossRegionId": "cn-hangzhou", "ossBucketName": "your-bucket-name", "ossObjectName": "sample/your-document.pdf", }, ) request := green20220302.FileModerationRequest{ Service: tea.String("document_detection"), 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("document detection not success. code:%d\n", *body.Code) return } data := body.Data fmt.Printf("document detection taskId:%s\n", *data.TaskId) }package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green20220302 "github.com/alibabacloud-go/green-20220302/v3/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { // Leaking project code may expose your AccessKey pair and compromise the security of all resources in your account. This sample code is for reference only. We recommend that you use a more secure method, such as STS. config := &openapi.Config{ /** * An AccessKey pair of an Alibaba Cloud account has permissions to call all API operations. We recommend that you use a RAM user for API access or daily O&M. * We strongly recommend that you do not hard-code the AccessKey ID and AccessKey Secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all resources in your account. * You can obtain environment variables in the following ways: * Get the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey Secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ AccessKeyId: tea.String("Specify the AccessKey ID of the RAM user. We recommend that you obtain the AccessKey ID from an environment variable."), AccessKeySecret: tea.String("Specify the AccessKey secret of the RAM user. We recommend that you obtain the AccessKey secret from an environment variable."), RegionId: tea.String("ap-southeast-1"), Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"), /** * Set the timeout period. The end-to-end processing timeout period on the server is 10 seconds. We recommend that you configure the timeout period based on this value. * If the ReadTimeout period that you set is shorter than the processing time on the server, a ReadTimeout error is returned. */ 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 options. runtime := &util.RuntimeOptions{} runtime.ReadTimeout = tea.Int(10000) runtime.ConnectTimeout = tea.Int(10000) serviceParameters, _ := json.Marshal( map[string]interface{}{ "ossRegionId": "ap-southeast-1", "ossBucketName": "your-bucket-name", "ossObjectName": "sample/your-document.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("document detection not success. code:%d\n", *body.Code) return } data := body.Data fmt.Printf("document detection taskId:%s\n", *data.TaskId) } -
Retrieve the result of a 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/v3/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { // Leaking project code may expose your AccessKey pair and compromise the security of all resources in your account. This sample code is for reference only. We recommend that you use a more secure method, such as STS. config := &openapi.Config{ /** * An AccessKey pair of an Alibaba Cloud account has permissions to call all API operations. We recommend that you use a RAM user for API access or daily O&M. * We strongly recommend that you do not hard-code the AccessKey ID and AccessKey Secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all resources in your account. * You can obtain environment variables in the following ways: * Get the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey Secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ AccessKeyId: tea.String("Specify the AccessKey ID of the RAM user. We recommend that you obtain the AccessKey ID from an environment variable."), AccessKeySecret: tea.String("Specify the AccessKey secret of the RAM user. We recommend that you obtain the AccessKey secret from an environment variable."), RegionId: tea.String("cn-shanghai"), Endpoint: tea.String("green-cip.cn-shanghai.aliyuncs.com"), /** * Set the timeout period. The end-to-end processing timeout period on the server is 10 seconds. We recommend that you configure the timeout period based on this value. * If the ReadTimeout period that you set is shorter than the processing time on the server, a ReadTimeout error is returned. */ 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 options. 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"), 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 document detection. code:%d\n", *body.Code) return } if *body.Code != http.StatusOK { fmt.Printf("document detection result not success. code:%d\n", *body.Code) return } data := body.Data fmt.Printf("document detection result:%s\n", data) fmt.Printf("document detection result pageResult:%s\n", data.PageResult) fmt.Printf("document detection result dataId:%s\n", data.DataId) }package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green20220302 "github.com/alibabacloud-go/green-20220302/v3/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { // Leaking project code may expose your AccessKey pair and compromise the security of all resources in your account. This sample code is for reference only. We recommend that you use a more secure method, such as STS. config := &openapi.Config{ /** * An AccessKey pair of an Alibaba Cloud account has permissions to call all API operations. We recommend that you use a RAM user for API access or daily O&M. * We strongly recommend that you do not hard-code the AccessKey ID and AccessKey Secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all resources in your account. * You can obtain environment variables in the following ways: * Get the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey Secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ AccessKeyId: tea.String("Specify the AccessKey ID of the RAM user. We recommend that you obtain the AccessKey ID from an environment variable."), AccessKeySecret: tea.String("Specify the AccessKey secret of the RAM user. We recommend that you obtain the AccessKey secret from an environment variable."), RegionId: tea.String("ap-southeast-1"), Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"), /** * Set the timeout period. The end-to-end processing timeout period on the server is 10 seconds. We recommend that you configure the timeout period based on this value. * If the ReadTimeout period that you set is shorter than the processing time on the server, a ReadTimeout error is returned. */ 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 options. 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 document detection. code:%d\n", *body.Code) return } if *body.Code != http.StatusOK { fmt.Printf("document detection result not success. code:%d\n", *body.Code) return } data := body.Data fmt.Printf("document detection result:%s\n", data) fmt.Printf("document detection result pageResult:%s\n", data.PageResult) fmt.Printf("document detection result dataId:%s\n", data.DataId) }
-
Node.js SDK
Refer to the Node.js SDK source code.
The following three types of document moderation are supported.
Public URL documents
Scenarios
If a document is accessible via a public URL, the document moderation enhanced edition service can fetch the file from the URL and perform moderation.
-
Run the following command to install the required dependency:
npm install @alicloud/green20220302@3.2.4 -
Integrate the Node.js SDK.
-
Sample code for submitting a document moderation task
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve detection performance, reuse the client instance whenever possible and avoid creating new connections for each request. // Leaking your source code can expose your AccessKey and threaten the security of your account resources. This code is for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: `green-cip.cn-shanghai.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Construct a request object. const fileModerationRequest = new Green20220302.FileModerationRequest({ "service": "document_detection", "serviceParameters": JSON.stringify({"url":"http://example.com/test.pdf"}) }); // Create a runtime options object. const runtime = new Util.RuntimeOptions(); try { // Send the request and get the response. const response = await client.fileModerationWithOptions(fileModerationRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // The following code is for demonstration only. In a production environment, handle exceptions properly and do not ignore them. // error message console.log('Error occurred:', error.message); } } } Client.main();const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve detection performance, reuse the client instance whenever possible and avoid creating new connections for each request. // Leaking your source code can expose your AccessKey and threaten the security of your account resources. This code is for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: `green-cip.ap-southeast-1.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Construct a request object. const fileModerationRequest = new Green20220302.FileModerationRequest({ "service": "document_detection_global", "serviceParameters": JSON.stringify({"url":"http://example.com/test.pdf"}) }); // Create a runtime options object. const runtime = new Util.RuntimeOptions(); try { // Send the request and get the response. const response = await client.fileModerationWithOptions(fileModerationRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // The following code is for demonstration only. In a production environment, handle exceptions properly and do not ignore them. // error message console.log('Error occurred:', error.message); } } } Client.main();Sample code for retrieving the result of a document moderation task
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve detection performance, reuse the client instance whenever possible and avoid creating new connections for each request. // Leaking your source code can expose your AccessKey and threaten the security of your account resources. This code is for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: `green-cip.cn-shanghai.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Construct a request object. const describeFileModerationResultRequest = new Green20220302.DescribeFileModerationResultRequest({ // The document moderation service. "service": "document_detection", "serviceParameters": JSON.stringify({"taskId":"<The ID of the document detection task>"}) }); // Create a runtime options object. const runtime = new Util.RuntimeOptions(); try { // Send the request and get the response. const response = await client.describeFileModerationResultWithOptions(describeFileModerationResultRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // The following code is for demonstration only. In a production environment, handle exceptions properly and do not ignore them. // error message console.log('Error occurred:', error.message); } } } Client.main();const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve detection performance, reuse the client instance whenever possible and avoid creating new connections for each request. // Leaking your source code can expose your AccessKey and threaten the security of your account resources. This code is for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: `green-cip.ap-southeast-1.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Construct a request object. const describeFileModerationResultRequest = new Green20220302.DescribeFileModerationResultRequest({ // The document moderation service. "service": "document_detection_global", "serviceParameters": JSON.stringify({"taskId":"<The ID of the document detection task>"}) }); // Create a runtime options object. const runtime = new Util.RuntimeOptions(); try { // Send the request and get the response. const response = await client.describeFileModerationResultWithOptions(describeFileModerationResultRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // The following code is for demonstration only. In a production environment, handle exceptions properly and do not ignore them. // error message console.log('Error occurred:', error.message); } } } Client.main();
-
Local files
Scenarios
If a document is stored locally and lacks a public URL, you can upload it to an Object Storage Service (OSS) bucket provided by Content Moderation. The document moderation enhanced edition service then retrieves the file from OSS to perform moderation.
-
Run the following command to install the required dependency:
npm install @alicloud/green20220302@3.2.4Install the OSS SDK:
npm install ali-oss --save -
Integrate the Node.js SDK.
-
Sample code for submitting a document moderation task
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const { v4: uuidv4 } = require('uuid'); const OSS = require('ali-oss'); const Util = require('@alicloud/tea-util'); const path = require("path"); // Note: To improve detection performance, reuse the client instance whenever possible and avoid creating new connections for each request. // Leaking your source code can expose your AccessKey and threaten the security of your account resources. This code is for reference only. // Specifies whether the service is deployed in a VPC. var isVPC = false; // Caches the file upload token. var tokenDic = new Array(); // The OSS client for file uploads. var ossClient; var endpoint = 'green-cip.cn-shanghai.aliyuncs.com' var filePath = '/path/to/your/file.pdf' var service = 'document_detection' class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: endpoint, }); return new Green20220302.default(config); } // Creates the OSS client for file uploads. static getOssClient(tokenData, isVPC) { if (isVPC) { ossClient = new OSS({ accessKeyId: tokenData['accessKeyId'], accessKeySecret: tokenData['accessKeySecret'], stsToken: tokenData['securityToken'], endpoint: tokenData['ossInternalEndPoint'], bucket: tokenData['bucketName'], }); } else { ossClient = new OSS({ accessKeyId: tokenData['accessKeyId'], accessKeySecret: tokenData['accessKeySecret'], stsToken: tokenData['securityToken'], endpoint: tokenData['ossInternetEndPoint'], bucket: tokenData['bucketName'], }); } } static async main() { const client = Client.createClient(); // Create a runtime options object. const runtime = new Util.RuntimeOptions(); // Obtain the file upload token. if (tokenDic[endpoint] == null || tokenDic[endpoint]['expiration'] <= Date.parse(new Date() / 1000)) { var tokenResponse = await client.describeUploadTokenWithOptions(runtime) tokenDic[endpoint] = tokenResponse.body.data; } // Obtain the OSS client for file uploads. this.getOssClient(tokenDic[endpoint], isVPC) var split = filePath.split("."); var objectName; if (split.length > 1) { objectName = tokenDic[endpoint].fileNamePrefix + uuidv4() + "." + split[split.length - 1]; } else { objectName = tokenDic[endpoint].fileNamePrefix + uuidv4(); } // Upload the file. const result = await ossClient.put(objectName, path.normalize(filePath)); // Construct a request object. const fileModerationRequest = new Green20220302.FileModerationRequest({ // The moderation service. "service": service, // The location of the file in OSS. "serviceParameters": JSON.stringify({ "ossBucketName": tokenDic[endpoint].bucketName, "ossObjectName": objectName, }) }); try { // Send the request and get the response. const response = await client.fileModerationWithOptions(fileModerationRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // The following code is for demonstration only. In a production environment, handle exceptions properly and do not ignore them. // error message console.log('Error occurred:', error.message); } } } Client.main();const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const { v4: uuidv4 } = require('uuid'); const OSS = require('ali-oss'); const Util = require('@alicloud/tea-util'); const path = require("path"); // Note: To improve detection performance, reuse the client instance whenever possible and avoid creating new connections for each request. // Leaking your source code can expose your AccessKey and threaten the security of your account resources. This code is for reference only. // Specifies whether the service is deployed in a VPC. var isVPC = false; // Caches the file upload token. var tokenDic = new Array(); // The OSS client for file uploads. var ossClient; var endpoint = 'green-cip.ap-southeast-1.aliyuncs.com' var filePath = '/path/to/your/file.pdf' var service = 'document_detection_global' class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: endpoint, }); return new Green20220302.default(config); } // Creates the OSS client for file uploads. static getOssClient(tokenData, isVPC) { if (isVPC) { ossClient = new OSS({ accessKeyId: tokenData['accessKeyId'], accessKeySecret: tokenData['accessKeySecret'], stsToken: tokenData['securityToken'], endpoint: tokenData['ossInternalEndPoint'], bucket: tokenData['bucketName'], }); } else { ossClient = new OSS({ accessKeyId: tokenData['accessKeyId'], accessKeySecret: tokenData['accessKeySecret'], stsToken: tokenData['securityToken'], endpoint: tokenData['ossInternetEndPoint'], bucket: tokenData['bucketName'], }); } } static async main() { const client = Client.createClient(); // Create a runtime options object. const runtime = new Util.RuntimeOptions(); // Obtain the file upload token. if (tokenDic[endpoint] == null || tokenDic[endpoint]['expiration'] <= Date.parse(new Date() / 1000)) { var tokenResponse = await client.describeUploadTokenWithOptions(runtime) tokenDic[endpoint] = tokenResponse.body.data; } // Obtain the OSS client for file uploads. this.getOssClient(tokenDic[endpoint], isVPC) var split = filePath.split("."); var objectName; if (split.length > 1) { objectName = tokenDic[endpoint].fileNamePrefix + uuidv4() + "." + split[split.length - 1]; } else { objectName = tokenDic[endpoint].fileNamePrefix + uuidv4(); } // Upload the file. const result = await ossClient.put(objectName, path.normalize(filePath)); // Construct a request object. const fileModerationRequest = new Green20220302.FileModerationRequest({ // The moderation service. "service": service, // The location of the file in OSS. "serviceParameters": JSON.stringify({ "ossBucketName": tokenDic[endpoint].bucketName, "ossObjectName": objectName, }) }); try { // Send the request and get the response. const response = await client.fileModerationWithOptions(fileModerationRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // The following code is for demonstration only. In a production environment, handle exceptions properly and do not ignore them. // error message console.log('Error occurred:', error.message); } } } Client.main();Sample code for retrieving the result of a document moderation task
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve detection performance, reuse the client instance whenever possible and avoid creating new connections for each request. // Leaking your source code can expose your AccessKey and threaten the security of your account resources. This code is for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: `green-cip.cn-shanghai.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Construct a request object. const describeFileModerationResultRequest = new Green20220302.DescribeFileModerationResultRequest({ // The document moderation service. "service": "document_detection", "serviceParameters": JSON.stringify({"taskId":"<The ID of the document detection task>"}) }); // Create a runtime options object. const runtime = new Util.RuntimeOptions(); try { // Send the request and get the response. const response = await client.describeFileModerationResultWithOptions(describeFileModerationResultRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // The following code is for demonstration only. In a production environment, handle exceptions properly and do not ignore them. // error message console.log('Error occurred:', error.message); } } } Client.main();const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve detection performance, reuse the client instance whenever possible and avoid creating new connections for each request. // Leaking your source code can expose your AccessKey and threaten the security of your account resources. This code is for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: `green-cip.ap-southeast-1.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Construct a request object. const describeFileModerationResultRequest = new Green20220302.DescribeFileModerationResultRequest({ // The document moderation service. "service": "document_detection_global", "serviceParameters": JSON.stringify({"taskId":"<The ID of the document detection task>"}) }); // Create a runtime options object. const runtime = new Util.RuntimeOptions(); try { // Send the request and get the response. const response = await client.describeFileModerationResultWithOptions(describeFileModerationResultRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // The following code is for demonstration only. In a production environment, handle exceptions properly and do not ignore them. // error message console.log('Error occurred:', error.message); } } } Client.main();
-
OSS documents
Scenarios
If a document you want to moderate is already in Object Storage Service (OSS), you must create a service role to authorize Content Moderation to access your OSS resources. The document moderation enhanced edition service then uses this role to fetch and moderate the file. You can create the service role on the Cloud Resource Access Authorization page.
-
Run the following command to install the required dependency:
npm install @alicloud/green20220302@3.2.4 -
Integrate the Node.js SDK.
-
Sample code for submitting a document moderation task
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve detection performance, reuse the client instance whenever possible and avoid creating new connections for each request. // Leaking your source code can expose your AccessKey and threaten the security of your account resources. This code is for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: `green-cip.cn-shanghai.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Construct a request object. const fileModerationRequest = new Green20220302.FileModerationRequest({ "service": "document_detection", "serviceParameters": JSON.stringify({ "ossRegionId": "cn-hangzhou", "ossBucketName": "your-bucket-name", "ossObjectName": "your-object-name.pdf" }) }); // Create a runtime options object. const runtime = new Util.RuntimeOptions(); try { // Send the request and get the response. const response = await client.fileModerationWithOptions(fileModerationRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // The following code is for demonstration only. In a production environment, handle exceptions properly and do not ignore them. // error message console.log('Error occurred:', error.message); } } } Client.main();const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve detection performance, reuse the client instance whenever possible and avoid creating new connections for each request. // Leaking your source code can expose your AccessKey and threaten the security of your account resources. This code is for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: `green-cip.ap-southeast-1.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Construct a request object. const fileModerationRequest = new Green20220302.FileModerationRequest({ "service": "document_detection_global", "serviceParameters": JSON.stringify({ "ossRegionId": "ap-southeast-1", "ossBucketName": "your-bucket-name", "ossObjectName": "your-object-name.pdf" }) }); // Create a runtime options object. const runtime = new Util.RuntimeOptions(); try { // Send the request and get the response. const response = await client.fileModerationWithOptions(fileModerationRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // The following code is for demonstration only. In a production environment, handle exceptions properly and do not ignore them. // error message console.log('Error occurred:', error.message); } } } Client.main();Sample code for retrieving the result of a document moderation task
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve detection performance, reuse the client instance whenever possible and avoid creating new connections for each request. // Leaking your source code can expose your AccessKey and threaten the security of your account resources. This code is for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: `green-cip.cn-shanghai.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Construct a request object. const describeFileModerationResultRequest = new Green20220302.DescribeFileModerationResultRequest({ // The document moderation service. "service": "document_detection", "serviceParameters": JSON.stringify({"taskId":"<The ID of the document detection task>"}) }); // Create a runtime options object. const runtime = new Util.RuntimeOptions(); try { // Send the request and get the response. const response = await client.describeFileModerationResultWithOptions(describeFileModerationResultRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // The following code is for demonstration only. In a production environment, handle exceptions properly and do not ignore them. // error message console.log('Error occurred:', error.message); } } } Client.main();const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve detection performance, reuse the client instance whenever possible and avoid creating new connections for each request. // Leaking your source code can expose your AccessKey and threaten the security of your account resources. This code is for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set in your runtime environment. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set in your runtime environment. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: `green-cip.ap-southeast-1.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Construct a request object. const describeFileModerationResultRequest = new Green20220302.DescribeFileModerationResultRequest({ // The document moderation service. "service": "document_detection_global", "serviceParameters": JSON.stringify({"taskId":"<The ID of the document detection task>"}) }); // Create a runtime options object. const runtime = new Util.RuntimeOptions(); try { // Send the request and get the response. const response = await client.describeFileModerationResultWithOptions(describeFileModerationResultRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // The following code is for demonstration only. In a production environment, handle exceptions properly and do not ignore them. // error message console.log('Error occurred:', error.message); } } } Client.main();
-
C# SDK
For the source code, see C# SDK source code.
This service supports three types of document detection.
Detect documents from a public URL
Use cases
If the document that you want to moderate is accessible from a public URL, the document detection enhanced edition service can fetch the file from the URL and moderate it.
-
Run the following command to install the required dependency.
dotnet add package AlibabaCloud.SDK.Green20220302 --version 3.2.4 -
Integrate the C# SDK.
-
Sample code to submit a document detection task
using System; using System.Collections.Generic; using AlibabaCloud.SDK.Green20220302; using AlibabaCloud.SDK.Green20220302.Models; using AlibabaCloud.OpenApiClient.Models; using AlibabaCloud.TeaUtil.Models; using Newtonsoft.Json; using Tea; namespace AlibabaCloud.SDK.Sample { public class Sample { /** * Initializes the client using an AccessKey pair. * @param accessKeyId * @param accessKeySecret * @return Client * @throws Exception */ public static Client CreateClient(string accessKeyId, string accessKeySecret) { Config config = new Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, }; // The API endpoint. config.Endpoint = "green-cip.cn-shanghai.aliyuncs.com"; return new Client(config); } public static void Main(string[] args) { // Leaking project code may expose your AccessKey and compromise the security of all resources in your account. This sample code is for reference only. We recommend that you use the more secure STS method. /** * The AccessKey pair of an Alibaba Cloud account has permissions to call all API operations. We recommend that you use a RAM user for API access or daily O&M. * We strongly recommend that you do not save your AccessKey ID and AccessKey Secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all resources in your account. * Common methods to obtain environment variables: * Get the AccessKey ID of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey Secret of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"); string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); // Note: Reuse the client whenever possible to improve detection performance. Avoid creating connections repeatedly. Client client = CreateClient(accessKeyId, accessKeySecret); // Construct a document detection request. FileModerationRequest fileModerationRequest = new FileModerationRequest(); // Specify the document detection service. fileModerationRequest.Service = "document_detection"; Dictionary<string, object> task = new Dictionary<string, object>(); // The URL of the publicly accessible document to moderate. task.Add("url", "https://example.com/sample.pdf"); fileModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task); // Create a RuntimeOptions instance and set runtime parameters. RuntimeOptions runtime = new RuntimeOptions(); runtime.ReadTimeout = 10000; runtime.ConnectTimeout = 10000; try { // Submit the document detection task. FileModerationResponse response = client.FileModerationWithOptions(fileModerationRequest, runtime); if (response is not null) { Console.WriteLine("response statusCode : " + response.StatusCode); if (response.Body is not null) { Console.WriteLine("requestId : " + response.Body.RequestId); Console.WriteLine("code : " + response.Body.Code); Console.WriteLine("message : " + response.Body.Message); if (response.Body.Data is not null) { Console.WriteLine("taskId : " + response.Body.Data.TaskId); } } } } catch (TeaException error) { // Print the error if one occurs. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } catch (Exception _error) { TeaException error = new TeaException(new Dictionary<string, object> { { "message", _error.Message } }); // Print the error if one occurs. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } } } }using System; using System.Collections.Generic; using AlibabaCloud.SDK.Green20220302; using AlibabaCloud.SDK.Green20220302.Models; using AlibabaCloud.OpenApiClient.Models; using AlibabaCloud.TeaUtil.Models; using Newtonsoft.Json; using Tea; namespace AlibabaCloud.SDK.Sample { public class Sample { /** * Initializes the client using an AccessKey pair. * @param accessKeyId * @param accessKeySecret * @return Client * @throws Exception */ public static Client CreateClient(string accessKeyId, string accessKeySecret) { Config config = new Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, }; // The API endpoint. config.Endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; return new Client(config); } public static void Main(string[] args) { // Leaking project code may expose your AccessKey and compromise the security of all resources in your account. This sample code is for reference only. We recommend that you use the more secure STS method. /** * The AccessKey pair of an Alibaba Cloud account has permissions to call all API operations. We recommend that you use a RAM user for API access or daily O&M. * We strongly recommend that you do not save your AccessKey ID and AccessKey Secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all resources in your account. * Common methods to obtain environment variables: * Get the AccessKey ID of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey Secret of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"); string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); // Note: Reuse the client whenever possible to improve detection performance. Avoid creating connections repeatedly. Client client = CreateClient(accessKeyId, accessKeySecret); // Construct a document detection request. FileModerationRequest fileModerationRequest = new FileModerationRequest(); // Specify the global document detection service. fileModerationRequest.Service = "document_detection_global"; Dictionary<string, object> task = new Dictionary<string, object>(); // The URL of the publicly accessible document to moderate. task.Add("url", "https://example.com/sample.pdf"); fileModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task); // Create a RuntimeOptions instance and set runtime parameters. RuntimeOptions runtime = new RuntimeOptions(); runtime.ReadTimeout = 10000; runtime.ConnectTimeout = 10000; try { // Submit the document detection task. FileModerationResponse response = client.FileModerationWithOptions(fileModerationRequest, runtime); if (response is not null) { Console.WriteLine("response statusCode : " + response.StatusCode); if (response.Body is not null) { Console.WriteLine("requestId : " + response.Body.RequestId); Console.WriteLine("code : " + response.Body.Code); Console.WriteLine("message : " + response.Body.Message); if (response.Body.Data is not null) { Console.WriteLine("taskId : " + response.Body.Data.TaskId); } } } } catch (TeaException error) { // Print the error if one occurs. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } catch (Exception _error) { TeaException error = new TeaException(new Dictionary<string, object> { { "message", _error.Message } }); // Print the error if one occurs. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } } } } -
Sample code to retrieve the result of a document detection task
using System; using System.Collections.Generic; using AlibabaCloud.SDK.Green20220302; using AlibabaCloud.SDK.Green20220302.Models; using AlibabaCloud.OpenApiClient.Models; using AlibabaCloud.TeaUtil.Models; using Newtonsoft.Json; using Tea; namespace AlibabaCloud.SDK.Sample { public class Sample { /** * Initializes the client using an AccessKey pair. * @param accessKeyId * @param accessKeySecret * @return Client * @throws Exception */ public static Client CreateClient(string accessKeyId, string accessKeySecret) { Config config = new Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, }; // The API endpoint. config.Endpoint = "green-cip.cn-shanghai.aliyuncs.com"; return new Client(config); } public static void Main(string[] args) { // Leaking project code may expose your AccessKey and compromise the security of all resources in your account. This sample code is for reference only. We recommend that you use the more secure STS method. /** * The AccessKey pair of an Alibaba Cloud account has permissions to call all API operations. We recommend that you use a RAM user for API access or daily O&M. * We strongly recommend that you do not save your AccessKey ID and AccessKey Secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all resources in your account. * Common methods to obtain environment variables: * Get the AccessKey ID of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey Secret of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"); string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); // Note: Reuse the client whenever possible to improve detection performance. Avoid creating connections repeatedly. Client client = CreateClient(accessKeyId, accessKeySecret); // Construct a request to query the moderation result. DescribeFileModerationResultRequest describeFileModerationResultRequest = new DescribeFileModerationResultRequest(); // Specify the document detection service. describeFileModerationResultRequest.Service = "document_detection"; Dictionary<string, object> task = new Dictionary<string, object>(); // The ID of the task whose result you want to query. task.Add("taskId", "<YOUR_TASK_ID>"); describeFileModerationResultRequest.ServiceParameters = JsonConvert.SerializeObject(task); // Create a RuntimeOptions instance and set runtime parameters. RuntimeOptions runtime = new RuntimeOptions(); runtime.ReadTimeout = 10000; runtime.ConnectTimeout = 10000; try { // Submit the query request. DescribeFileModerationResultResponse response = client.DescribeFileModerationResultWithOptions(describeFileModerationResultRequest, runtime); if (response is not null) { Console.WriteLine("response statusCode : " + response.StatusCode); if (response.Body is not null) { Console.WriteLine("requestId : " + response.Body.RequestId); Console.WriteLine("code : " + response.Body.Code); Console.WriteLine("message : " + response.Body.Message); if (response.Body.Data is not null) { Console.WriteLine("taskId : " + response.Body.Data.TaskId); Console.WriteLine("url : " + response.Body.Data.Url); Console.WriteLine("pageResult : " + JsonConvert.SerializeObject(response.Body.Data.PageResult)); } } } } catch (TeaException error) { // Print the error if one occurs. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } catch (Exception _error) { TeaException error = new TeaException(new Dictionary<string, object> { { "message", _error.Message } }); // Print the error if one occurs. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } } } }using System; using System.Collections.Generic; using AlibabaCloud.SDK.Green20220302; using AlibabaCloud.SDK.Green20220302.Models; using AlibabaCloud.OpenApiClient.Models; using AlibabaCloud.TeaUtil.Models; using Newtonsoft.Json; using Tea; namespace AlibabaCloud.SDK.Sample { public class Sample { /** * Initializes the client using an AccessKey pair. * @param accessKeyId * @param accessKeySecret * @return Client * @throws Exception */ public static Client CreateClient(string accessKeyId, string accessKeySecret) { Config config = new Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, }; // The API endpoint. config.Endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; return new Client(config); } public static void Main(string[] args) { // Leaking project code may expose your AccessKey and compromise the security of all resources in your account. This sample code is for reference only. We recommend that you use the more secure STS method. /** * The AccessKey pair of an Alibaba Cloud account has permissions to call all API operations. We recommend that you use a RAM user for API access or daily O&M. * We strongly recommend that you do not save your AccessKey ID and AccessKey Secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all resources in your account. * Common methods to obtain environment variables: * Get the AccessKey ID of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey Secret of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"); string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); // Note: Reuse the client whenever possible to improve detection performance. Avoid creating connections repeatedly. Client client = CreateClient(accessKeyId, accessKeySecret); // Construct a request to query the moderation result. DescribeFileModerationResultRequest describeFileModerationResultRequest = new DescribeFileModerationResultRequest(); // Specify the global document detection service. describeFileModerationResultRequest.Service = "document_detection_global"; Dictionary<string, object> task = new Dictionary<string, object>(); // The ID of the task whose result you want to query. task.Add("taskId", "<YOUR_TASK_ID>"); describeFileModerationResultRequest.ServiceParameters = JsonConvert.SerializeObject(task); // Create a RuntimeOptions instance and set runtime parameters. RuntimeOptions runtime = new RuntimeOptions(); runtime.ReadTimeout = 10000; runtime.ConnectTimeout = 10000; try { // Submit the query request. DescribeFileModerationResultResponse response = client.DescribeFileModerationResultWithOptions(describeFileModerationResultRequest, runtime); if (response is not null) { Console.WriteLine("response statusCode : " + response.StatusCode); if (response.Body is not null) { Console.WriteLine("requestId : " + response.Body.RequestId); Console.WriteLine("code : " + response.Body.Code); Console.WriteLine("message : " + response.Body.Message); if (response.Body.Data is not null) { Console.WriteLine("taskId : " + response.Body.Data.TaskId); Console.WriteLine("url : " + response.Body.Data.Url); Console.WriteLine("pageResult : " + JsonConvert.SerializeObject(response.Body.Data.PageResult)); } } } } catch (TeaException error) { // Print the error if one occurs. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } catch (Exception _error) { TeaException error = new TeaException(new Dictionary<string, object> { { "message", _error.Message } }); // Print the error if one occurs. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } } } }
-
Detect local documents
Use cases
If you need to moderate a document that is stored locally and is not accessible via a public URL, you can upload it to an Object Storage Service (OSS) bucket provided by Content Moderation. The document moderation service can then directly access the file from OSS to moderate it.
-
Run the following command to add the dependency:
dotnet add package AlibabaCloud.SDK.Green20220302 --version 3.2.4Install the OSS SDK:
Install via NuGet 1. If NuGet is not installed in your Visual Studio, install it first. 2. In Visual Studio, create or open a project. Select Tools > NuGet Package Manager > Manage NuGet Packages for Solution. 3. Search for aliyun.oss.sdk. In the results, find Aliyun.OSS.SDK (for .NET Framework) or Aliyun.OSS.SDK.NetCore (for .NET Core), select the latest version, and click Install. -
Integrate the C# SDK.
-
Submit a document detection task
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using AlibabaCloud.SDK.Green20220302.Models; using Aliyun.OSS; using Newtonsoft.Json; namespace AlibabaCloud.SDK.Green20220302 { public class FileModerationAutoRoute { // Caches file upload tokens. public static Dictionary<string, DescribeUploadTokenResponse> tokenDic = new Dictionary<string, DescribeUploadTokenResponse>(); // The client for file uploads. public static OssClient ossClient = null; // Specifies whether the service is deployed in a VPC. public static bool isVPC = false; public static void Main(string[] args) { /** * For security, avoid hard-coding your AccessKey ID and AccessKey secret. * We recommend retrieving them from environment variables. * Get the AccessKey ID of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"); string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); // Replace with the endpoint for your deployment region. string endpoint = "green-cip.cn-shanghai.aliyuncs.com"; FileModerationResponse response = invoke( accessKeyId, accessKeySecret, endpoint ); // Automatic routing: Switch to the China (Beijing) region. if ( response is null || response.Body is null || AlibabaCloud.TeaUtil.Common.EqualNumber( 500, AlibabaCloud.TeaUtil.Common.AssertAsNumber(response.StatusCode) ) || AlibabaCloud.TeaUtil.Common.EqualString( "500", Convert.ToString(response.Body.Code) ) ) { endpoint = "green-cip.cn-beijing.aliyuncs.com"; response = invoke(accessKeyId, accessKeySecret, endpoint); ; } Console.WriteLine(response.Body.RequestId); Console.WriteLine(JsonConvert.SerializeObject(response.Body)); } // Creates a request client. public static Client createClient( string accessKeyId, string accessKeySecret, string endpoint ) { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, // Set an HTTP proxy. //HttpProxy = "http://10.10.xx.xx:xxxx", // Set an HTTPS proxy. //HttpsProxy = "https://user:password@host:port", // The API endpoint. Endpoint = endpoint, }; return new Client(config); } // Creates a client for file uploads. private static OssClient getOssClient( DescribeUploadTokenResponse tokenResponse, bool isVPC ) { var tokenData = tokenResponse.Body.Data; if (isVPC) { return new OssClient( tokenData.OssInternalEndPoint, tokenData.AccessKeyId, tokenData.AccessKeySecret, tokenData.SecurityToken ); } else { return new OssClient( tokenData.OssInternetEndPoint, tokenData.AccessKeyId, tokenData.AccessKeySecret, tokenData.SecurityToken ); } } // Uploads a file. public static string uploadFile( string filePath, DescribeUploadTokenResponse tokenResponse ) { // Constructs an OssClient instance. ossClient = getOssClient(tokenResponse, isVPC); var tokenData = tokenResponse.Body.Data; string objectName = tokenData.FileNamePrefix + Guid.NewGuid().ToString() + "." + filePath.Split('.')[1]; // Uploads the file. ossClient.PutObject(tokenData.BucketName, objectName, filePath); return objectName; } // Submits a moderation request. public static FileModerationResponse invoke( string accessKeyId, string accessKeySecret, string endpoint ) { // Important: Reuse the client instance to improve performance and avoid creating new connections. Client client = createClient(accessKeyId, accessKeySecret, endpoint); // Sets runtime options, which are effective only for requests that use this instance. AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); // The absolute path of the local file, for example, D:\\localPath\\exampleFile.pdf. string filePath = "D:\\localPath\\exampleFile.pdf"; try { // Gets a temporary token for file upload. if ( !tokenDic.ContainsKey(endpoint) || tokenDic[endpoint].Body.Data.Expiration <= DateTimeOffset.Now.ToUnixTimeSeconds() ) { var tokenResponse = client.DescribeUploadToken(); tokenDic[endpoint] = tokenResponse; } // Uploads the file. string objectName = uploadFile(filePath, tokenDic[endpoint]); // Constructs the moderation request. FileModerationRequest fileModerationRequest = new FileModerationRequest(); // Moderation service. Example: document_detection fileModerationRequest.Service = "document_detection"; Dictionary<string, object> task = new Dictionary<string, object>(); // Information about the content to be moderated. task.Add("ossBucketName", tokenDic[endpoint].Body.Data.BucketName); task.Add("ossObjectName", objectName); // The ID of the data to be moderated. task.Add("dataId", Guid.NewGuid().ToString()); fileModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task); // Sends the request. FileModerationResponse response = client.FileModerationWithOptions( fileModerationRequest, runtimeOptions ); return response; } catch (Exception _err) { Console.WriteLine(_err); return null; } } } }// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using AlibabaCloud.SDK.Green20220302.Models; using Aliyun.OSS; using Newtonsoft.Json; namespace AlibabaCloud.SDK.Green20220302 { public class FileModerationAutoRoute { // Caches file upload tokens. public static Dictionary<string, DescribeUploadTokenResponse> tokenDic = new Dictionary<string, DescribeUploadTokenResponse>(); // The client for file uploads. public static OssClient ossClient = null; // Specifies whether the service is deployed in a VPC. public static bool isVPC = false; public static void Main(string[] args) { /** * For security, avoid hard-coding your AccessKey ID and AccessKey secret. * We recommend retrieving them from environment variables. * Get the AccessKey ID of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"); string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); // Replace with the endpoint for your deployment region. string endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; FileModerationResponse response = invoke( accessKeyId, accessKeySecret, endpoint ); Console.WriteLine(response.Body.RequestId); Console.WriteLine(JsonConvert.SerializeObject(response.Body)); } // Creates a request client. public static Client createClient( string accessKeyId, string accessKeySecret, string endpoint ) { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, // Set an HTTP proxy. //HttpProxy = "http://10.10.xx.xx:xxxx", // Set an HTTPS proxy. //HttpsProxy = "https://user:password@host:port", // The API endpoint. Endpoint = endpoint, }; return new Client(config); } // Creates a client for file uploads. private static OssClient getOssClient( DescribeUploadTokenResponse tokenResponse, bool isVPC ) { var tokenData = tokenResponse.Body.Data; if (isVPC) { return new OssClient( tokenData.OssInternalEndPoint, tokenData.AccessKeyId, tokenData.AccessKeySecret, tokenData.SecurityToken ); } else { return new OssClient( tokenData.OssInternetEndPoint, tokenData.AccessKeyId, tokenData.AccessKeySecret, tokenData.SecurityToken ); } } // Uploads a file. public static string uploadFile( string filePath, DescribeUploadTokenResponse tokenResponse ) { // Constructs an OssClient instance. ossClient = getOssClient(tokenResponse, isVPC); var tokenData = tokenResponse.Body.Data; string objectName = tokenData.FileNamePrefix + Guid.NewGuid().ToString() + "." + filePath.Split('.')[1]; // Uploads the file. ossClient.PutObject(tokenData.BucketName, objectName, filePath); return objectName; } // Submits a moderation request. public static FileModerationResponse invoke( string accessKeyId, string accessKeySecret, string endpoint ) { // Important: Reuse the client instance to improve performance and avoid creating new connections. Client client = createClient(accessKeyId, accessKeySecret, endpoint); // Sets runtime options, which are effective only for requests that use this instance. AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); // The absolute path of the local file, for example, D:\\localPath\\exampleFile.pdf. string filePath = "D:\\localPath\\exampleFile.pdf"; try { // Gets a temporary token for file upload. if ( !tokenDic.ContainsKey(endpoint) || tokenDic[endpoint].Body.Data.Expiration <= DateTimeOffset.Now.ToUnixTimeSeconds() ) { var tokenResponse = client.DescribeUploadToken(); tokenDic[endpoint] = tokenResponse; } // Uploads the file. string objectName = uploadFile(filePath, tokenDic[endpoint]); // Constructs the moderation request. FileModerationRequest fileModerationRequest = new FileModerationRequest(); // Moderation service. Example: document_detection_global fileModerationRequest.Service = "document_detection_global"; Dictionary<string, object> task = new Dictionary<string, object>(); // Information about the content to be moderated. task.Add("ossBucketName", tokenDic[endpoint].Body.Data.BucketName); task.Add("ossObjectName", objectName); // The ID of the data to be moderated. task.Add("dataId", Guid.NewGuid().ToString()); fileModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task); // Sends the request. FileModerationResponse response = client.FileModerationWithOptions( fileModerationRequest, runtimeOptions ); return response; } catch (Exception _err) { Console.WriteLine(_err); return null; } } } } -
Get the result of a document detection task
using System; using System.Collections.Generic; using AlibabaCloud.SDK.Green20220302; using AlibabaCloud.SDK.Green20220302.Models; using AlibabaCloud.OpenApiClient.Models; using AlibabaCloud.TeaUtil.Models; using Newtonsoft.Json; using Tea; namespace AlibabaCloud.SDK.Sample { public class Sample { /** * Initializes the client by using an AccessKey pair. * @param accessKeyId * @param accessKeySecret * @return Client * @throws Exception */ public static Client CreateClient(string accessKeyId, string accessKeySecret) { Config config = new Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, }; // The API endpoint. config.Endpoint = "green-cip.cn-shanghai.aliyuncs.com"; return new Client(config); } public static void Main(string[] args) { /** * For security, avoid hard-coding your AccessKey ID and AccessKey secret. * We recommend retrieving them from environment variables. * Get the AccessKey ID of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"); string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); // Important: Reuse the client instance to improve performance and avoid creating new connections. Client client = CreateClient(accessKeyId, accessKeySecret); // Construct a request to query the moderation result. DescribeFileModerationResultRequest describeFileModerationResultRequest = new DescribeFileModerationResultRequest(); // The document detection service. describeFileModerationResultRequest.Service="document_detection"; Dictionary<string,object> task=new Dictionary<string, object>(); // The ID of the task to query. task.Add("taskId",""); describeFileModerationResultRequest.ServiceParameters=JsonConvert.SerializeObject(task); // Create a RuntimeOptions instance and configure runtime options. RuntimeOptions runtime = new RuntimeOptions(); runtime.ReadTimeout = 10000; runtime.ConnectTimeout = 10000; try { // Submit the query request. DescribeFileModerationResultResponse response= client.DescribeFileModerationResultWithOptions(describeFileModerationResultRequest, runtime); if(response is not null) { Console.WriteLine("response statusCode : "+response.StatusCode); if (response.Body is not null) { Console.WriteLine("requestId : " + response.Body.RequestId); Console.WriteLine("code : " + response.Body.Code); Console.WriteLine("message : " + response.Body.Message); if(response.Body.Data is not null) { Console.WriteLine("taskId : " + response.Body.Data.TaskId); Console.WriteLine("url : " + response.Body.Data.Url); Console.WriteLine("pageResult : " + JsonConvert.SerializeObject(response.Body.Data.PageResult)); } } } } catch (TeaException error) { // Print the error if one occurs. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } catch (Exception _error) { TeaException error = new TeaException(new Dictionary<string, object> { { "message", _error.Message } }); // Print the error if one occurs. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } } } }using System; using System.Collections.Generic; using AlibabaCloud.SDK.Green20220302; using AlibabaCloud.SDK.Green20220302.Models; using AlibabaCloud.OpenApiClient.Models; using AlibabaCloud.TeaUtil.Models; using Newtonsoft.Json; using Tea; namespace AlibabaCloud.SDK.Sample { public class Sample { /** * Initializes the client by using an AccessKey pair. * @param accessKeyId * @param accessKeySecret * @return Client * @throws Exception */ public static Client CreateClient(string accessKeyId, string accessKeySecret) { Config config = new Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, }; // The API endpoint. config.Endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; return new Client(config); } public static void Main(string[] args) { /** * For security, avoid hard-coding your AccessKey ID and AccessKey secret. * We recommend retrieving them from environment variables. * Get the AccessKey ID of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"); string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); // Important: Reuse the client instance to improve performance and avoid creating new connections. Client client = CreateClient(accessKeyId, accessKeySecret); // Construct a request to query the moderation result. DescribeFileModerationResultRequest describeFileModerationResultRequest = new DescribeFileModerationResultRequest(); // The document detection service. describeFileModerationResultRequest.Service="document_detection_global"; Dictionary<string,object> task=new Dictionary<string, object>(); // The ID of the task to query. task.Add("taskId",""); describeFileModerationResultRequest.ServiceParameters=JsonConvert.SerializeObject(task); // Create a RuntimeOptions instance and configure runtime options. RuntimeOptions runtime = new RuntimeOptions(); runtime.ReadTimeout = 10000; runtime.ConnectTimeout = 10000; try { // Submit the query request. DescribeFileModerationResultResponse response= client.DescribeFileModerationResultWithOptions(describeFileModerationResultRequest, runtime); if(response is not null) { Console.WriteLine("response statusCode : "+response.StatusCode); if (response.Body is not null) { Console.WriteLine("requestId : " + response.Body.RequestId); Console.WriteLine("code : " + response.Body.Code); Console.WriteLine("message : " + response.Body.Message); if(response.Body.Data is not null) { Console.WriteLine("taskId : " + response.Body.Data.TaskId); Console.WriteLine("url : " + response.Body.Data.Url); Console.WriteLine("pageResult : " + JsonConvert.SerializeObject(response.Body.Data.PageResult)); } } } } catch (TeaException error) { // Print the error if one occurs. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } catch (Exception _error) { TeaException error = new TeaException(new Dictionary<string, object> { { "message", _error.Message } }); // Print the error if one occurs. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } } } }
-
Moderate documents in OSS
Scenarios
If the document files that you need to moderate are already stored in Alibaba Cloud Object Storage Service (OSS), you can authorize the creation of a service role to allow the Content Moderation service to access OSS. The Document Moderation enhanced edition service uses the service role to obtain files from OSS for moderation. Visit the Cloud Resource Access Authorization page to create the service role.
-
Run the following command to add the required dependency.
dotnet add package AlibabaCloud.SDK.Green20220302 --version 3.2.4 -
Integrate the C# SDK.
-
Sample code to submit a document moderation task
using System; using System.Collections.Generic; using AlibabaCloud.SDK.Green20220302; using AlibabaCloud.SDK.Green20220302.Models; using AlibabaCloud.OpenApiClient.Models; using AlibabaCloud.TeaUtil.Models; using Newtonsoft.Json; using Tea; namespace AlibabaCloud.SDK.Sample { public class Sample { /** * Initializes the client by using an AccessKey pair. * @param accessKeyId * @param accessKeySecret * @return Client * @throws Exception */ public static Client CreateClient(string accessKeyId, string accessKeySecret) { Config config = new Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, }; // The service endpoint. config.Endpoint = "green-cip.cn-shanghai.aliyuncs.com"; return new Client(config); } public static void Main(string[] args) { /** * We recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your code. This may lead to security risks. * We recommend that you retrieve them from environment variables or use a more secure method, such as using RAM roles. * For more information, see the following topic: * Obtain the AccessKey ID of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * Obtain the AccessKey Secret of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"); string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); // Reuse the client instance to improve performance and prevent multiple connections. Client client = CreateClient(accessKeyId, accessKeySecret); // Construct a document moderation request. FileModerationRequest fileModerationRequest = new FileModerationRequest(); // Specifies the document moderation service. fileModerationRequest.Service="document_detection"; Dictionary<string,object> task=new Dictionary<string, object>(); // The OSS location of the document to moderate. task.Add("ossRegionId", "cn-hangzhou"); task.Add("ossBucketName", "your-bucket-name"); task.Add("ossObjectName", "path/to/your/document.pdf"); fileModerationRequest.ServiceParameters=JsonConvert.SerializeObject(task); // Create a RuntimeOptions instance and configure runtime parameters. RuntimeOptions runtime = new RuntimeOptions(); runtime.ReadTimeout = 10000; runtime.ConnectTimeout = 10000; try { // Submit the document moderation task. FileModerationResponse response= client.FileModerationWithOptions(fileModerationRequest, runtime); if(response is not null) { Console.WriteLine("response statusCode : "+response.StatusCode); if (response.Body is not null) { Console.WriteLine("requestId : " + response.Body.RequestId); Console.WriteLine("code : " + response.Body.Code); Console.WriteLine("message : " + response.Body.Message); if(response.Body.Data is not null) { Console.WriteLine("taskId : " + response.Body.Data.TaskId); } } } } catch (TeaException error) { // Print the error if needed. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } catch (Exception _error) { TeaException error = new TeaException(new Dictionary<string, object> { { "message", _error.Message } }); // Print the error if needed. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } } } }using System; using System.Collections.Generic; using AlibabaCloud.SDK.Green20220302; using AlibabaCloud.SDK.Green20220302.Models; using AlibabaCloud.OpenApiClient.Models; using AlibabaCloud.TeaUtil.Models; using Newtonsoft.Json; using Tea; namespace AlibabaCloud.SDK.Sample { public class Sample { /** * Initializes the client by using an AccessKey pair. * @param accessKeyId * @param accessKeySecret * @return Client * @throws Exception */ public static Client CreateClient(string accessKeyId, string accessKeySecret) { Config config = new Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, }; // The service endpoint. config.Endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; return new Client(config); } public static void Main(string[] args) { /** * We recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your code. This may lead to security risks. * We recommend that you retrieve them from environment variables or use a more secure method, such as using RAM roles. * For more information, see the following topic: * Obtain the AccessKey ID of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * Obtain the AccessKey Secret of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"); string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); // Reuse the client instance to improve performance and prevent multiple connections. Client client = CreateClient(accessKeyId, accessKeySecret); // Construct a document moderation request. FileModerationRequest fileModerationRequest = new FileModerationRequest(); // Specifies the document moderation service. fileModerationRequest.Service="document_detection_global"; Dictionary<string,object> task=new Dictionary<string, object>(); // The OSS location of the document to moderate. task.Add("ossRegionId", "ap-southeast-1"); task.Add("ossBucketName", "your-bucket-name"); task.Add("ossObjectName", "path/to/your/document.pdf"); fileModerationRequest.ServiceParameters=JsonConvert.SerializeObject(task); // Create a RuntimeOptions instance and configure runtime parameters. RuntimeOptions runtime = new RuntimeOptions(); runtime.ReadTimeout = 10000; runtime.ConnectTimeout = 10000; try { // Submit the document moderation task. FileModerationResponse response= client.FileModerationWithOptions(fileModerationRequest, runtime); if(response is not null) { Console.WriteLine("response statusCode : "+response.StatusCode); if (response.Body is not null) { Console.WriteLine("requestId : " + response.Body.RequestId); Console.WriteLine("code : " + response.Body.Code); Console.WriteLine("message : " + response.Body.Message); if(response.Body.Data is not null) { Console.WriteLine("taskId : " + response.Body.Data.TaskId); } } } } catch (TeaException error) { // Print the error if needed. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } catch (Exception _error) { TeaException error = new TeaException(new Dictionary<string, object> { { "message", _error.Message } }); // Print the error if needed. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } } } } -
Sample code to retrieve document moderation results
using System; using System.Collections.Generic; using AlibabaCloud.SDK.Green20220302; using AlibabaCloud.SDK.Green20220302.Models; using AlibabaCloud.OpenApiClient.Models; using AlibabaCloud.TeaUtil.Models; using Newtonsoft.Json; using Tea; namespace AlibabaCloud.SDK.Sample { public class Sample { /** * Initializes the client by using an AccessKey pair. * @param accessKeyId * @param accessKeySecret * @return Client * @throws Exception */ public static Client CreateClient(string accessKeyId, string accessKeySecret) { Config config = new Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, }; // The service endpoint. config.Endpoint = "green-cip.cn-shanghai.aliyuncs.com"; return new Client(config); } public static void Main(string[] args) { /** * We recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your code. This may lead to security risks. * We recommend that you retrieve them from environment variables or use a more secure method, such as using RAM roles. * For more information, see the following topic: * Obtain the AccessKey ID of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * Obtain the AccessKey Secret of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"); string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); // Reuse the client instance to improve performance and prevent multiple connections. Client client = CreateClient(accessKeyId, accessKeySecret); // Construct a request to query the moderation result. DescribeFileModerationResultRequest describeFileModerationResultRequest = new DescribeFileModerationResultRequest(); // The service required for document moderation. describeFileModerationResultRequest.Service="document_detection"; Dictionary<string,object> task=new Dictionary<string, object>(); // The ID of the task to query. task.Add("taskId",""); describeFileModerationResultRequest.ServiceParameters=JsonConvert.SerializeObject(task); // Create a RuntimeOptions instance and configure runtime parameters. RuntimeOptions runtime = new RuntimeOptions(); runtime.ReadTimeout = 10000; runtime.ConnectTimeout = 10000; try { // Submit the query request. DescribeFileModerationResultResponse response= client.DescribeFileModerationResultWithOptions(describeFileModerationResultRequest, runtime); if(response is not null) { Console.WriteLine("response statusCode : "+response.StatusCode); if (response.Body is not null) { Console.WriteLine("requestId : " + response.Body.RequestId); Console.WriteLine("code : " + response.Body.Code); Console.WriteLine("message : " + response.Body.Message); if(response.Body.Data is not null) { Console.WriteLine("taskId : " + response.Body.Data.TaskId); Console.WriteLine("url : " + response.Body.Data.Url); Console.WriteLine("pageResult : " + JsonConvert.SerializeObject(response.Body.Data.PageResult)); } } } } catch (TeaException error) { // Print the error if needed. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } catch (Exception _error) { TeaException error = new TeaException(new Dictionary<string, object> { { "message", _error.Message } }); // Print the error if needed. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } } } }using System; using System.Collections.Generic; using AlibabaCloud.SDK.Green20220302; using AlibabaCloud.SDK.Green20220302.Models; using AlibabaCloud.OpenApiClient.Models; using AlibabaCloud.TeaUtil.Models; using Newtonsoft.Json; using Tea; namespace AlibabaCloud.SDK.Sample { public class Sample { /** * Initializes the client by using an AccessKey pair. * @param accessKeyId * @param accessKeySecret * @return Client * @throws Exception */ public static Client CreateClient(string accessKeyId, string accessKeySecret) { Config config = new Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, }; // The service endpoint. config.Endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; return new Client(config); } public static void Main(string[] args) { /** * We recommend that you do not hard-code your AccessKey ID and AccessKey Secret in your code. This may lead to security risks. * We recommend that you retrieve them from environment variables or use a more secure method, such as using RAM roles. * For more information, see the following topic: * Obtain the AccessKey ID of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * Obtain the AccessKey Secret of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"); string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); // Reuse the client instance to improve performance and prevent multiple connections. Client client = CreateClient(accessKeyId, accessKeySecret); // Construct a request to query the moderation result. DescribeFileModerationResultRequest describeFileModerationResultRequest = new DescribeFileModerationResultRequest(); // The service required for document moderation. describeFileModerationResultRequest.Service="document_detection_global"; Dictionary<string,object> task=new Dictionary<string, object>(); // The ID of the task to query. task.Add("taskId",""); describeFileModerationResultRequest.ServiceParameters=JsonConvert.SerializeObject(task); // Create a RuntimeOptions instance and configure runtime parameters. RuntimeOptions runtime = new RuntimeOptions(); runtime.ReadTimeout = 10000; runtime.ConnectTimeout = 10000; try { // Submit the query request. DescribeFileModerationResultResponse response= client.DescribeFileModerationResultWithOptions(describeFileModerationResultRequest, runtime); if(response is not null) { Console.WriteLine("response statusCode : "+response.StatusCode); if (response.Body is not null) { Console.WriteLine("requestId : " + response.Body.RequestId); Console.WriteLine("code : " + response.Body.Code); Console.WriteLine("message : " + response.Body.Message); if(response.Body.Data is not null) { Console.WriteLine("taskId : " + response.Body.Data.TaskId); Console.WriteLine("url : " + response.Body.Data.Url); Console.WriteLine("pageResult : " + JsonConvert.SerializeObject(response.Body.Data.PageResult)); } } } } catch (TeaException error) { // Print the error if needed. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } catch (Exception _error) { TeaException error = new TeaException(new Dictionary<string, object> { { "message", _error.Message } }); // Print the error if needed. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } } } }
-
Native HTTPS calls
-
Invocation Method
Endpoint: https://green-cip.{region}.aliyuncs.com
Protocol: HTTPS
Method: POST
-
Common request parameters
Requests to the Document Moderation (Enhanced) API include common request parameters and API-specific parameters. Every API call must include common request parameters. The following table describes the common request parameters.
Parameter
Type
Required
Description
Actions
String
Yes
The format of the response. Valid values:
-
JSON (default)
-
XML
Version
String
Yes
The API version. The format is YYYY-MM-DD. For this release, use
2022-03-02.AccessKeyId
String
Yes
The AccessKey ID for service access.
Signature
String
Yes
The signature string. For calculation details, see the "Signature method" section below.
SignatureMethod
String
Yes
The signature method.
HMAC-SHA1is supported.Timestamp
String
Yes
The timestamp of the request. The timestamp must be in UTC and formatted according to the ISO 8601 standard.
Format:
yyyy-MM-ddTHH:mm:ssZ.For example,
2022-12-12T01:13:14Zrepresents 09:13:14 on December 12, 2022 (UTC+8).SignatureVersion
String
Yes
The signature algorithm version. Set this to
1.0.SignatureNonce
String
Yes
A nonce to prevent replay attacks. You must use a different value for each request.
action
String
Yes
Valid values:
-
FileModeration
-
DescribeFileModerationResult
-
-
Common response parameters
The system returns a unique
RequestIdfor every API request, whether it succeeds or fails. Other response parameters vary depending on the API operation.{ "Msg": "OK", "Code": 200, "Data": { "TaskId": "AAAAA-BBBBB-CCCCCCCC" }, "RequestId": "ABCD1234-1234-1234-1234-123****" } -
Examples
The following sample responses are formatted for readability. The actual response is not indented or line-wrapped.
-
Moderation task example
Sample request
http://green-cip.cn-shanghai.aliyuncs.com/ ?Format=JSON &Version=2022-03-02 &Signature=vpEEL0zFHfxXYzSFV0n7%2FZiFL9o%3D &SignatureMethod=Hmac-SHA1 &SignatureNonce=15215528852396 &SignatureVersion=1.0 &Action=FileModeration &AccessKeyId=YOUR_ACCESS_KEY_ID &Timestamp=2023-02-03T12:00:00Z &Service=document_detection &ServiceParameters={"url": "https://example.com/sample.pdf"}Sample success response
{ "Msg": "OK", "Code": 200, "Data": { "TaskId": "AAAAA-BBBBB-CCCCCCCC" }, "RequestId": "ABCD1234-1234-1234-1234-123****" } -
Query task example
Sample request
http://green-cip.cn-shanghai.aliyuncs.com/ ?Format=JSON &Version=2022-03-02 &Signature=vpEEL0zFHfxXYzSFV0n7%2FZiFL9o%3D &SignatureMethod=Hmac-SHA1 &SignatureNonce=15215528852396 &SignatureVersion=1.0 &Action=DescribeFileModerationResult &AccessKeyId=YOUR_ACCESS_KEY_ID &Timestamp=2023-02-03T12:00:00Z &Service=document_detection &ServiceParameters={"taskId": "fi_f_O5zxxxxxxxxxxxxxxxx-1x****"}Sample success response
{ "Code": 200, "Data": { "DataId": "fileId*****", "PageResult": [ { "ImageResult": [ { "Description": "Moderation for image content on the document page", "LabelResult": [ { "label": "nonLabel" } ], "Service": "baselineCheck" } ], "ImageUrl": "http://oss.aliyundoc.com/a.png", "PageNum": 1, "TextResult": [ { "Description": "Moderation for text content on the document page", "Labels": "", "RiskTips": "", "RiskWords": "", "Service": "pgc_detection", "Text": "Content Moderation product test case A" } ] }, ... { "ImageResult": [ { "Description": "Moderation for image content on the document page", "LabelResult": [ { "Confidence": 89.01, "Label": "pornographic_adultContent_tii" } ], "Service": "baselineCheck" } ], "ImageUrl": "http://oss.aliyundoc.com/b.png", "PageNum": 10, "TextResult": [ { "Description": "Moderation for text content on the document page", "Labels": "contraband,sexual_content", "RiskTips": "contraband_prohibited-items,sexual-content_film-tv,sexual-content_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 Document Moderation (Enhanced) service authenticates every request. You must include a signature in each request to verify your identity. The service uses symmetric encryption with an
AccessKeyIdandAccessKey Secretto authenticate the sender.The
AccessKeyIdandAccessKey Secretare issued by Alibaba Cloud. You can create and manage them on the Alibaba Cloud website. TheAccessKeyIdidentifies you, and theAccessKey Secretis a private key used to calculate the signature string. You must keep yourAccessKey Secretconfidential.To sign a request, follow these steps:
-
Create a
canonicalized query string.-
Sort all request parameters (including common request parameters and custom parameters for the specified API, but not the Signature parameter itself) in alphabetical order of the parameter names.
-
URL-encode the name and value of each parameter by using the UTF-8 character set.
NoteMost URL-encoding libraries, such as
java.net.URLEncoderin Java, follow theapplication/x-www-form-urlencodedMIME type rules. When using these libraries, you must replace plus signs (+) with%20, asterisks (*) with%2A, and%7Ewith tildes (~) to match the required encoding scheme.The
URL encodingrules are as follows:-
Do not encode uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), hyphens (
-), underscores (_), periods (.), or tildes (~). -
Encode all other characters in the
%XYformat, whereXYis the two-digit hexadecimal representation of the character's ASCII code. For example, a double quotation mark (") is encoded as%22. -
Encode extended UTF-8 characters in the
%XY%ZA…format. -
A space must be encoded as
%20, not a plus sign (+).
-
-
Connect the encoded parameter name and its encoded value with an equal sign (
=). -
Concatenate the name-value pairs with ampersands (
&) to form the canonicalized query string.
-
-
Use the
canonicalized query stringto create the string to sign.StringToSign= HTTPMethod + "&" + percentEncode("/") + "&" + percentEncode(CanonicalizedQueryString)NoteHTTPMethod is the HTTP method used to make the request, such as POST. percentEncode(/) is the value obtained by URL-encoding the forward slash character (/) based on the URL encoding rules described in section a.ii, which is
%2F. percentEncode(CanonicalQueryString) is the string obtained by URL-encoding the Canonical Query String from section a.i based on the URL encoding rules in section a.ii. -
Calculate the HMAC value of the string to sign, as defined in RFC 2104.
NoteNote that the key for signature calculation is your AccessKey Secret followed by an
&character (ASCII: 38), and the hashing algorithm is SHA1. -
Base64-encode the HMAC value to obtain the signature string. This value is used for the
Signatureparameter. -
Add the signature string to the request as the
Signatureparameter.NoteBefore the signature string is added to the final request, it must also be URL-encoded per RFC 3986.
-