Image Moderation 2.0 supports SDK calls and native HTTPS calls. We recommend that you use an SDK to connect to the service. This lets you skip detailed steps, such as signature authentication and body format construction. This topic describes the methods for connecting to Image Moderation 2.0.
Step 1: Activate the service
Visit the Activate Service page and activate the Image Moderation Version 2.0 service.
After you activate the Image Moderation Version 2.0 service, the default billing method is pay-as-you-go, which settles charges daily based on your actual usage. You are not charged if you do not call the service. After you integrate and use the API, the system automatically generates bills based on your usage. For more information, see Billing details.
Step 2: Create a RAM user and grant permissions
Before you use SDKs to call the Content Moderation API, you must create a user, obtain the access credential associated with the user, and grant the user the permissions to access Alibaba Cloud resources. In this example, a Resource Access Management (RAM) user is created, an AccessKey pair is used as the access credential, and the RAM user is granted the permission to call the Content Moderation
Log on to the RAM console by using an Alibaba Cloud account or a RAM user that has administrative rights.
Create a RAM user, select OpenAPI Access, and record the AccessKey pair that is generated for the RAM user. For more information about how to create a RAM user, see Create a RAM user.
Grant the
AliyunYundunGreenWebFullAccesssystem policy to the RAM user. For more information, see Grant permissions to a RAM user.
Step 3: Install and integrate the SDK
The following regions are supported:
Region | Public endpoint | VPC endpoint | Support |
Singapore | green-cip.ap-southeast-1.aliyuncs.com | green-cip-vpc.ap-southeast-1.aliyuncs.com | postImageCheckByVL_global, baselineCheck_global, aigcDetector_global, faceDetect_global, faceDetect_pro_global |
UK (London) | green-cip.eu-west-1.aliyuncs.com | None | |
US (Virginia) | green-cip.us-east-1.aliyuncs.com | green-cip-vpc.us-east-1.aliyuncs.com | baselineCheck_global, aigcDetector_global |
US (Silicon Valley) | green-cip.us-west-1.aliyuncs.com | None | |
Germany (Frankfurt) | green-cip.eu-central-1.aliyuncs.com | green-cip-vpc.eu-central-1.aliyuncs.com |
If you need SDK sample code for other languages, you can use the online debugging tool on the OpenAPI Developer Portal to debug API operations. The tool automatically generates SDK call sample code for the corresponding API operation.
In Alibaba Cloud SDK code, you can create a default access credential by defining ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. When you call API operations of Alibaba Cloud services, the system directly accesses the credential, reads your AccessKey pair, and then automatically completes authentication. Before you use the SDK sample code, you must configure environment variables. For more information, see Configure credentials.
For descriptions of the API operation fields, see Image Moderation Enhanced 2.0 Synchronous Detection API.
Java SDK
Usage notes
Environment requirements: Java 1.8 or later.
Source code reference: For more information, see Java SDK source code or Java SDK source code (OSS path).
Supported features: The SDK supports the following three types of image detection.
For more information about the values and descriptions of the Label field returned by these API operations, see Risk label description table.
Detect publicly accessible images
Scenarios
If an image to be moderated is accessible using a public URL, the Image Moderation Version 2.0 service can retrieve the file from the URL to moderate it.
To install the Java SDK, add the following dependency to the pom.xml file. You can then use the SDK in your Maven project.
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>2.2.11</version> </dependency>Integrate the Java SDK.
Synchronous API integration example
import com.alibaba.fastjson.JSON; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.ImageModerationRequest; import com.aliyun.green20220302.models.ImageModerationResponse; import com.aliyun.green20220302.models.ImageModerationResponseBody; import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyData; import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyDataResult; import com.aliyun.teaopenapi.models.Config; import com.aliyun.teautil.models.RuntimeOptions; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; public class ImageUrlDemo { /** * Create a request client. * * @param accessKeyId * @param accessKeySecret * @param endpoint * @return * @throws Exception */ public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception { Config config = new Config(); config.setAccessKeyId(accessKeyId); config.setAccessKeySecret(accessKeySecret); // Set the HTTP proxy. // config.setHttpProxy("http://10.10.xx.xx:xxxx"); // Set the HTTPS proxy. // config.setHttpsProxy("https://10.10.xx.xx:xxxx"); // Modify the region and endpoint as needed. config.setEndpoint(endpoint); return new Client(config); } public static ImageModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception { // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. Client client = createClient(accessKeyId, accessKeySecret, endpoint); // Create a RuntimeObject instance and set runtime parameters. RuntimeOptions runtime = new RuntimeOptions(); // Construct detection parameters. Map<String, String> serviceParameters = new HashMap<>(); // A publicly accessible URL. serviceParameters.put("imageUrl", "https://img.alicdn.com/tfs/xxxxxxxxxx001.png"); // A unique identifier for the data to be detected. serviceParameters.put("dataId", UUID.randomUUID().toString()); ImageModerationRequest request = new ImageModerationRequest(); // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global request.setService("baselineCheck_global"); request.setServiceParameters(JSON.toJSONString(serviceParameters)); ImageModerationResponse response = null; try { response = client.imageModerationWithOptions(request, runtime); } catch (Exception e) { e.printStackTrace(); } return response; } public static void main(String[] args) throws Exception { /** * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M. * Common ways to get environment variables: * Method 1: * Get the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Get the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Get the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Get the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ String accessKeyId = "We recommend that you obtain the AccessKey ID of the RAM user from an environment variable"; String accessKeySecret = "We recommend that you obtain the AccessKey secret of the RAM user from an environment variable"; ImageModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com"); // Print the detection results. if (response != null) { if (response.getStatusCode() == 200) { ImageModerationResponseBody body = response.getBody(); System.out.println("requestId=" + body.getRequestId()); System.out.println("code=" + body.getCode()); System.out.println("msg=" + body.getMsg()); if (body.getCode() == 200) { ImageModerationResponseBodyData data = body.getData(); System.out.println("dataId=" + data.getDataId()); List<ImageModerationResponseBodyDataResult> results = data.getResult(); for (ImageModerationResponseBodyDataResult result : results) { System.out.println("label=" + result.getLabel()); System.out.println("confidence=" + result.getConfidence()); } } else { System.out.println("image moderation not success. code:" + body.getCode()); } } else { System.out.println("response not success. status:" + response.getStatusCode()); } } } }
Detect local images
Scenarios
To moderate images that are on your local machine and do not have a publicly accessible URL, you can upload the images to an Object Storage Service (OSS) bucket provided by Content Moderation. The Image Moderation Version 2.0 service can then directly access OSS to retrieve and moderate the image content.
Install the Java SDK.
Install the Content Moderation SDK:
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>2.2.11</version> </dependency>Install the OSS SDK:
<dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.16.3</version> </dependency>Integrate the Java SDK.
Synchronous API integration example
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.ImageModerationRequest; import com.aliyun.green20220302.models.ImageModerationResponse; import com.aliyun.green20220302.models.ImageModerationResponseBody; import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyData; import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyDataResult; 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.List; import java.util.Map; import java.util.UUID; public class ScanLocalImage { // Specifies whether the service is deployed in a VPC. public static boolean isVPC = false; // File upload token: endpoint->token public static Map<String, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData> tokenMap = new HashMap<>(); // Client for file upload requests. public static OSS ossClient = null; /** * Create a request client. * * @param accessKeyId * @param accessKeySecret * @param endpoint * @return * @throws Exception */ public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception { Config config = new Config(); config.setAccessKeyId(accessKeyId); config.setAccessKeySecret(accessKeySecret); // Modify the region and endpoint as needed. config.setEndpoint(endpoint); return new Client(config); } /** * Create a client for file upload requests. * * @param tokenData * @param isVPC */ public static void getOssClient(DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData, boolean isVPC) { // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. if (isVPC) { ossClient = new OSSClientBuilder().build(tokenData.ossInternalEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken()); } else { ossClient = new OSSClientBuilder().build(tokenData.ossInternetEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken()); } } /** * Upload 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 ImageModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception { // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. Client client = createClient(accessKeyId, accessKeySecret, endpoint); RuntimeOptions runtime = new RuntimeOptions(); // The full path of the local file, for example, D:\localPath\exampleFile.png. String filePath = "D:\\localPath\\exampleFile.png"; // Get the file upload token. if (tokenMap.get(endpoint) == null || tokenMap.get(endpoint).expiration <= System.currentTimeMillis() / 1000) { DescribeUploadTokenResponse tokenResponse = client.describeUploadToken(); tokenMap.put(endpoint,tokenResponse.getBody().getData()); } // Client for file upload requests. getOssClient(tokenMap.get(endpoint), isVPC); // Upload the file. String objectName = uploadFile(filePath, tokenMap.get(endpoint)); // Construct detection parameters. Map<String, String> serviceParameters = new HashMap<>(); // File upload information. serviceParameters.put("ossBucketName", tokenMap.get(endpoint).getBucketName()); serviceParameters.put("ossObjectName", objectName); serviceParameters.put("dataId", UUID.randomUUID().toString()); ImageModerationRequest request = new ImageModerationRequest(); // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck request.setService("baselineCheck_global"); request.setServiceParameters(JSON.toJSONString(serviceParameters)); ImageModerationResponse response = null; try { response = client.imageModerationWithOptions(request, runtime); } catch (Exception e) { e.printStackTrace(); } return response; } public static void main(String[] args) throws Exception { /** * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M. * Common ways to get environment variables: * Method 1: * Get the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Get the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Get the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Get the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ String accessKeyId = "We recommend that you obtain the AccessKey ID of the RAM user from an environment variable"; String accessKeySecret = "We recommend that you obtain the AccessKey secret of the RAM user from an environment variable"; // Modify the region and endpoint as needed. ImageModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com"); try { // Print the detection results. if (response != null) { if (response.getStatusCode() == 200) { ImageModerationResponseBody body = response.getBody(); System.out.println("requestId=" + body.getRequestId()); System.out.println("code=" + body.getCode()); System.out.println("msg=" + body.getMsg()); if (body.getCode() == 200) { ImageModerationResponseBodyData data = body.getData(); System.out.println("dataId=" + data.getDataId()); List<ImageModerationResponseBodyDataResult> results = data.getResult(); for (ImageModerationResponseBodyDataResult result : results) { System.out.println("label=" + result.getLabel()); System.out.println("confidence=" + result.getConfidence()); } } else { System.out.println("image moderation not success. code:" + body.getCode()); } } else { System.out.println("response not success. status:" + response.getStatusCode()); } } } catch (Exception e) { e.printStackTrace(); } } }
Detect OSS images
Scenarios
To moderate image files that are stored in Object Storage Service (OSS), you can create a service role to grant the Content Moderation service access to your OSS resources. The Image Moderation Version 2.0 service uses this service role to retrieve files from OSS for moderation. You can create the AliyunCIPScanOSSRole service role on the Cloud Resource Access Authorization page.
Use your Alibaba Cloud account (root account) to navigate to the Cloud Resource Access Authorization page to grant permissions.
To install the Java SDK, add the following dependency to the pom.xml file. You can then use the SDK in your Maven project.
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>2.2.11</version> </dependency>Integrate the Java SDK.
Synchronous API integration example
import com.alibaba.fastjson.JSON; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.ImageModerationRequest; import com.aliyun.green20220302.models.ImageModerationResponse; import com.aliyun.green20220302.models.ImageModerationResponseBody; import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyData; import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyDataResult; import com.aliyun.teaopenapi.models.Config; import com.aliyun.teautil.models.RuntimeOptions; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; public class OssScanDemo { /** * Create a request client. * * @param accessKeyId * @param accessKeySecret * @param endpoint * @return * @throws Exception */ public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception { Config config = new Config(); config.setAccessKeyId(accessKeyId); config.setAccessKeySecret(accessKeySecret); // Set the HTTP proxy. // config.setHttpProxy("http://10.10.xx.xx:xxxx"); // Set the HTTPS proxy. // config.setHttpsProxy("https://10.10.xx.xx:xxxx"); // Modify the region and endpoint as needed. config.setEndpoint(endpoint); return new Client(config); } public static ImageModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception { // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. Client client = createClient(accessKeyId, accessKeySecret, endpoint); // Create a RuntimeObject instance and set runtime parameters. RuntimeOptions runtime = new RuntimeOptions(); // Construct detection parameters. Map<String, String> serviceParameters = new HashMap<>(); // A unique identifier for the data to be detected. serviceParameters.put("dataId", UUID.randomUUID().toString()); // The region where the bucket of the file to be detected is located. Example: ap-southeast-1 serviceParameters.put("ossRegionId", "ap-southeast-1"); // The name of the bucket where the file to be detected is located. Example: bucket001 serviceParameters.put("ossBucketName", "bucket001"); // The file to be detected. Example: image/001.jpg serviceParameters.put("ossObjectName", "image/001.jpg"); ImageModerationRequest request = new ImageModerationRequest(); // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global request.setService("baselineCheck_global"); request.setServiceParameters(JSON.toJSONString(serviceParameters)); ImageModerationResponse response = null; try { response = client.imageModerationWithOptions(request, runtime); } catch (Exception e) { e.printStackTrace(); } return response; } public static void main(String[] args) throws Exception { /** * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M. * Common ways to get environment variables: * Method 1: * Get the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Get the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Get the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Get the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ String accessKeyId = "We recommend that you obtain the AccessKey ID of the RAM user from an environment variable"; String accessKeySecret = "We recommend that you obtain the AccessKey secret of the RAM user from an environment variable"; ImageModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com"); // Print the detection results. if (response != null) { if (response.getStatusCode() == 200) { ImageModerationResponseBody body = response.getBody(); System.out.println("requestId=" + body.getRequestId()); System.out.println("code=" + body.getCode()); System.out.println("msg=" + body.getMsg()); if (body.getCode() == 200) { ImageModerationResponseBodyData data = body.getData(); System.out.println("dataId=" + data.getDataId()); List<ImageModerationResponseBodyDataResult> results = data.getResult(); for (ImageModerationResponseBodyDataResult result : results) { System.out.println("label=" + result.getLabel()); System.out.println("confidence=" + result.getConfidence()); } } else { System.out.println("image moderation not success. code:" + body.getCode()); } } else { System.out.println("response not success. status:" + response.getStatusCode()); } } } }
Python SDK
Usage notes
Environment requirements: Python 3.6 or later.
Source code reference: For the source code, see Python SDK source code.
Supported features: The SDK supports the following three types of image detection.
For more information about the values and descriptions of the Label field returned by these API operations, see Risk label description table.
Detect publicly accessible images
Scenarios
If an image to be moderated is accessible using a public URL, the Image Moderation V2.0 service can retrieve the file from the URL to moderate it.
Run the following command to import the required dependencies.
pip install alibabacloud_green20220302==2.2.11Integrate the Python SDK.
Synchronous API integration example
# coding=utf-8 from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config from alibabacloud_tea_util import models as util_models import json import uuid # Create a request client. def create_client(access_key_id, access_key_secret, endpoint): config = Config( access_key_id=access_key_id, access_key_secret=access_key_secret, # Set the HTTP proxy. # http_proxy='http://10.10.xx.xx:xxxx', # Set the HTTPS proxy. # https_proxy='https://10.10.xx.xx:xxxx', # Modify the region and endpoint as needed. endpoint=endpoint ) return Client(config) def invoke_function(access_key_id, access_key_secret, endpoint): # Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. client = create_client(access_key_id, access_key_secret, endpoint) # Create a RuntimeObject instance and set runtime parameters. runtime = util_models.RuntimeOptions() # Construct detection parameters. service_parameters = { # A publicly accessible image URL. 'imageUrl': 'https://img.alicdn.com/tfs/xxxxxxxxxx001.png', # A unique identifier for the data. 'dataId': str(uuid.uuid1()) } image_moderation_request = models.ImageModerationRequest( # Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global service='baselineCheck_global', service_parameters=json.dumps(service_parameters) ) try: return client.image_moderation_with_options(image_moderation_request, runtime) except Exception as err: print(err) if __name__ == '__main__': # An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M. # We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account. # Common ways to get environment variables: # Get the AccessKey ID of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Get the AccessKey secret of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='We recommend that you obtain the AccessKey ID of the RAM user from an environment variable' access_key_secret='We recommend that you obtain the AccessKey secret of the RAM user from an environment variable' # Modify the region and endpoint as needed. response = invoke_function(access_key_id, access_key_secret, 'green-cip.ap-southeast-1.aliyuncs.com') # Print the results. if response is not None: if response.status_code == 200: # The call was successful. # Get the moderation results. result = response.body print('response success. result:{}'.format(result)) if result.code == 200: result_data = result.data print('result: {}'.format(result_data)) else: print('response not success. status:{} ,result:{}'.format(response.status_code, response))
Detect local images
Scenarios
To moderate images that are stored on a local machine and do not have a publicly accessible URL, you can upload the images to an Object Storage Service (OSS) bucket provided by Content Moderation. The Image Moderation Version 2.0 service can then directly access OSS to retrieve and moderate the image content.
Install the Python SDK.
Install the Content Moderation SDK:
pip install alibabacloud_green20220302==2.2.11Install the OSS SDK:
pip install oss2Integrate the Python SDK.
Synchronous API integration example
from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config from alibabacloud_tea_util import models as util_models import json import uuid import oss2 import time import os # Specifies whether the service is deployed in a VPC. is_vpc = False # File upload token: endpoint->token token_dict = dict() # Client for file uploads. bucket = None # Create a request client. def create_client(access_key_id, access_key_secret, endpoint): config = Config( access_key_id=access_key_id, access_key_secret=access_key_secret, # Set the HTTP proxy. # http_proxy='http://10.10.xx.xx:xxxx', # Set the HTTPS proxy. # https_proxy='https://10.10.xx.xx:xxxx', # Modify the region and endpoint as needed. endpoint=endpoint ) return Client(config) # Create a client for file uploads. def create_oss_bucket(is_vpc, upload_token): global token_dict global bucket auth = oss2.StsAuth(upload_token.access_key_id, upload_token.access_key_secret, upload_token.security_token) if (is_vpc): end_point = upload_token.oss_internal_end_point else: end_point = upload_token.oss_internet_end_point # Note: Reuse the instantiated bucket as much as possible to avoid repeated connection establishment and improve detection performance. bucket = oss2.Bucket(auth, end_point, upload_token.bucket_name) def upload_file(file_name, upload_token): create_oss_bucket(is_vpc, upload_token) object_name = upload_token.file_name_prefix + str(uuid.uuid1()) + '.' + file_name.split('.')[-1] bucket.put_object_from_file(object_name, file_name) return object_name def invoke_function(access_key_id, access_key_secret, endpoint): # Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. client = create_client(access_key_id, access_key_secret, endpoint) # Create a RuntimeObject instance and set runtime parameters. runtime = util_models.RuntimeOptions() # The full path of the local file, for example, D:\localPath\exampleFile.png. file_path = 'D:\\localPath\\exampleFile.png' # Get the file upload token. upload_token = token_dict.setdefault(endpoint, None) if (upload_token == None) or int(upload_token.expiration) <= int(time.time()): response = client.describe_upload_token() upload_token = response.body.data token_dict[endpoint] = upload_token # Upload the file. object_name = upload_file(file_path, upload_token) # Construct detection parameters. service_parameters = { # The name of the bucket where the file to be detected is located. 'ossBucketName': upload_token.bucket_name, # The file to be detected. 'ossObjectName': object_name, # A unique identifier for the data. 'dataId': str(uuid.uuid1()) } image_moderation_request = models.ImageModerationRequest( # Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global service='baselineCheck_global', service_parameters=json.dumps(service_parameters) ) try: return client.image_moderation_with_options(image_moderation_request, runtime) except Exception as err: print(err) if __name__ == '__main__': # An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M. # We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account. # Common ways to get environment variables: # Get the AccessKey ID of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Get the AccessKey secret of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='We recommend that you obtain the AccessKey ID of the RAM user from an environment variable' access_key_secret='We recommend that you obtain the AccessKey secret of the RAM user from an environment variable' # Modify the region and endpoint as needed. response = invoke_function(access_key_id, access_key_secret, 'green-cip.ap-southeast-1.aliyuncs.com') # Print the results. if response is not None: if response.status_code == 200: # The call was successful. # Get the moderation results. result = response.body print('response success. result:{}'.format(result)) if result.code == 200: result_data = result.data print('result: {}'.format(result_data)) else: print('response not success. status:{} ,result:{}'.format(response.status_code, response))
Using OSS images for detection
Scenarios
If the image files that you need to moderate are stored in Alibaba Cloud Object Storage Service (OSS), you can create a service role to grant the Content Moderation service access to your OSS resources. The Image Moderation Version 2.0 service uses this service role to retrieve files from OSS for moderation. You can create the AliyunCIPScanOSSRole service role on the Cloud Resource Access Authorization page.
Use your Alibaba Cloud account (root account) to navigate to the Cloud Resource Access Authorization page to grant permissions.
Run the following command to install the Python SDK.
pip install alibabacloud_green20220302==2.2.11Integrate the Python SDK.
Synchronous API integration example
from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config from alibabacloud_tea_util import models as util_models import json import os import uuid # Create a request client. def create_client(access_key_id, access_key_secret, endpoint): config = Config( access_key_id=access_key_id, access_key_secret=access_key_secret, # Set the HTTP proxy. # http_proxy='http://10.10.xx.xx:xxxx', # Set the HTTPS proxy. # https_proxy='https://10.10.xx.xx:xxxx', # Modify the region and endpoint as needed. endpoint=endpoint ) return Client(config) def invoke_function(access_key_id, access_key_secret, endpoint): # Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. client = create_client(access_key_id, access_key_secret, endpoint) # Create a RuntimeObject instance and set runtime parameters. runtime = util_models.RuntimeOptions() # Construct detection parameters. service_parameters = { # The region where the bucket of the file to be detected is located. Example: ap-southeast-1 'ossRegionId': 'ap-southeast-1', # The name of the bucket where the file to be detected is located. Example: bucket001 'ossBucketName': 'bucket001', # The file to be detected. Example: image/001.jpg 'ossObjectName': 'image/001.jpg', # A unique identifier for the data. 'dataId': str(uuid.uuid1()) } image_moderation_request = models.ImageModerationRequest( # Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global service='baselineCheck_global', service_parameters=json.dumps(service_parameters) ) try: return client.image_moderation_with_options(image_moderation_request, runtime) except Exception as err: print(err) if __name__ == '__main__': # An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M. # We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account. # Common ways to get environment variables: # Get the AccessKey ID of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Get the AccessKey secret of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='We recommend that you obtain the AccessKey ID of the RAM user from an environment variable' access_key_secret='We recommend that you obtain the AccessKey secret of the RAM user from an environment variable' # Modify the region and endpoint as needed. response = invoke_function(access_key_id, access_key_secret, 'green-cip.ap-southeast-1.aliyuncs.com') # Print the results. if response is not None: if response.status_code == 200: # The call was successful. # Get the moderation results. result = response.body print('response success. result:{}'.format(result)) if result.code == 200: result_data = result.data print('result: {}'.format(result_data)) else: print('response not success. status:{} ,result:{}'.format(response.status_code, response))
PHP SDK
Usage notes
Environment requirements: PHP 5.6 or later.
Source code reference: For more information, see PHP SDK source code.
Supported features: The SDK supports the following three types of image detection.
For more information about the values and descriptions of the Label field returned by these API operations, see Risk label description table.
Detect publicly accessible images
Scenarios
If an image to be moderated is accessible using a public URL, the Image Moderation Version 2.0 service can retrieve the file from its URL to moderate it.
Install the PHP SDK.
Run the following command to import the required dependencies.
composer require alibabacloud/green-20220302 2.2.10Integrate the PHP SDK.
Synchronous API integration example
<?php require('vendor/autoload.php'); use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationResponse; use Darabonba\OpenApi\Models\Config; use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions; use AlibabaCloud\SDK\Green\V20220302\Green; use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationRequest; /** * Create 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 the HTTP proxy. // "httpProxy" => "http://10.10.xx.xx:xxxx", // Set the HTTPS proxy. // "httpsProxy" => "https://10.10.xx.xx:xxxx", "endpoint" => $endpoint, ]); return new Green($config); } /** * Submit a detection task. * @param $accessKeyId * @param $accessKeySecret * @param $endpoint * @return ImageModerationResponse */ function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageModerationResponse { // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. $client = create_client($accessKeyId, $accessKeySecret, $endpoint); // Create a RuntimeObject instance and set runtime parameters. $runtime = new RuntimeOptions([]); // Construct detection parameters. $request = new ImageModerationRequest(); $serviceParameters = array( // The image to be detected, which is a publicly accessible URL. 'imageUrl' => 'https://img.alicdn.com/tfs/xxxxxxxxxx001.png', // A unique identifier for the detection data. 'dataId' => uniqid()); // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global $request->service = "baselineCheck_global"; $request->serviceParameters = json_encode($serviceParameters); // Submit for detection. return $client->imageModerationWithOptions($request, $runtime); } /** * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M. * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account. * Common ways to get environment variables: * Get the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Get the AccessKey secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ $accessKeyId = 'We recommend that you obtain the AccessKey ID of the RAM user from an environment variable'; $accessKeySecret = 'We recommend that you obtain the AccessKey secret of the RAM user from an environment variable'; // Modify the region and endpoint as needed. $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()); }
Detect local images
Scenarios
To moderate images that are on your local machine and do not have a publicly accessible URL, you can upload them to an Object Storage Service (OSS) bucket provided by Content Moderation. The Image Moderation Version 2.0 service can then directly access OSS to retrieve and moderate the image content.
Install the PHP SDK.
Install the Content Moderation SDK:
composer require alibabacloud/green-20220302 2.2.10Install the OSS SDK:
composer require aliyuncs/oss-sdk-phpIntegrate the PHP SDK.
Synchronous API integration example
<?php require('vendor/autoload.php'); use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationResponse; 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\ImageModerationRequest; use OSS\OssClient; // Specifies whether the service is deployed in a VPC. $isVPC = false; // File upload token. $tokenArray = array(); // Client for file upload requests. $ossClient = null; /** * Create 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 the HTTP proxy. // "httpProxy" => "http://10.10.xx.xx:xxxx", // Set the HTTPS proxy. // "httpsProxy" => "https://10.10.xx.xx:xxxx", "endpoint" => $endpoint, ]); return new Green($config); } /** * Create a client for file uploads. * @param $tokenData * @return void */ function create_upload_client($tokenData): void { global $isVPC; global $ossClient; // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. 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); } } /** * Upload a file. * @param $fileName * @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; } /** * Submit a detection task. * @param $accessKeyId * @param $accessKeySecret * @param $endpoint * @return ImageModerationResponse * @throws \OSS\Core\OssException */ function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageModerationResponse { global $tokenArray; // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. $client = create_client($accessKeyId, $accessKeySecret, $endpoint); // Create a RuntimeObject instance and set runtime parameters. $runtime = new RuntimeOptions([]); // The full path of the local file, for example, D:\\localPath\\exampleFile.png. $filePath = "D:\\localPath\\exampleFile.png"; // Get the 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 detection parameters. $request = new ImageModerationRequest(); // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global $request->service = "baselineCheck_global"; // The image to be detected, which is a publicly accessible URL. $serviceParameters = array( 'ossObjectName' => $objectName, 'ossBucketName' => $tokenArray[$endpoint]->bucketName, 'dataId' => uniqid()); $request->serviceParameters = json_encode($serviceParameters); // Submit for detection. return $client->imageModerationWithOptions($request, $runtime); } /** * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M. * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account. * Common ways to get environment variables: * Get the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Get the AccessKey secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ $accessKeyId = 'We recommend that you obtain the AccessKey ID of the RAM user from an environment variable'; $accessKeySecret = 'We recommend that you obtain the AccessKey secret of the RAM user from an environment variable'; // Modify the region and endpoint as needed. $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()); }
Detect OSS images
Scenarios
If the image files that you want to moderate are stored in Object Storage Service (OSS), you can create a service role to grant the Content Moderation service access to your OSS resources. The Image Moderation Version 2.0 service uses this service role to retrieve files from OSS for moderation. You can create the AliyunCIPScanOSSRole service role on the Cloud Resource Access Authorization page.
Use your Alibaba Cloud account (root account) to navigate to the Cloud Resource Access Authorization page to grant permissions.
Install the PHP SDK.
composer require alibabacloud/green-20220302 2.2.10Integrate the PHP SDK.
Synchronous API integration example
<?php require('vendor/autoload.php'); use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationResponse; use Darabonba\OpenApi\Models\Config; use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions; use AlibabaCloud\SDK\Green\V20220302\Green; use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationRequest; use AlibabaCloud\Tea\Utils\Utils; /** * Create 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 the HTTP proxy. // "httpProxy" => "http://10.10.xx.xx:xxxx", // Set the HTTPS proxy. // "httpsProxy" => "https://10.10.xx.xx:xxxx", "endpoint" => $endpoint, ]); return new Green($config); } /** * Submit a detection task. * @param $accessKeyId * @param $accessKeySecret * @param $endpoint * @return ImageModerationResponse */ function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageModerationResponse { // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. $client = create_client($accessKeyId, $accessKeySecret, $endpoint); // Create a RuntimeObject instance and set runtime parameters. $runtime = new RuntimeOptions([]); // Construct detection parameters. $request = new ImageModerationRequest(); $serviceParameters = array( // The file to be detected. Example: image/001.jpg 'ossObjectName' => 'image/001.jpg', // The region where the bucket of the file to be detected is located. Example: ap-southeast-1 'ossRegionId' => 'ap-southeast-1', // The name of the bucket where the file to be detected is located. Example: bucket001 'ossBucketName' => 'bucket001', // A unique identifier for the data to be detected. 'dataId' => uniqid()); // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global $request->service = "baselineCheck_global"; $request->serviceParameters = json_encode($serviceParameters); // Submit for detection. return $client->imageModerationWithOptions($request, $runtime); } /** * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M. * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account. * Common ways to get environment variables: * Get the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Get the AccessKey secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ $accessKeyId = 'We recommend that you obtain the AccessKey ID of the RAM user from an environment variable'; $accessKeySecret = 'We recommend that you obtain the AccessKey secret of the RAM user from an environment variable'; // Modify the region and endpoint as needed. $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()); }
Go SDK
Usage Notes
Source code reference: For more information, see Go SDK source code.
Supported features: The SDK supports the following three types of image detection.
For more information about the values and descriptions of the Label field returned by these API operations, see Risk label description table.
Detect publicly accessible images
Scenarios
If an image to be moderated is accessible using a public URL, the Image Moderation Version 2.0 service can retrieve the image file from the URL to moderate it.
Install the Go SDK.
go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2Integrate the Go SDK.
Synchronous API integration example
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/google/uuid" "net/http" "os" ) // Create a request client. func createClient(accessKeyId *string, accessKeySecret *string, endpoint *string) (*green20220302.Client, error) { config := &openapi.Config{ AccessKeyId: accessKeyId, AccessKeySecret: accessKeySecret, // Set the HTTP proxy. // HttpProxy: tea.String("http://10.10.xx.xx:xxxx"), // Set the HTTPS proxy. // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"), Endpoint: endpoint, } // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. return green20220302.NewClient(config); } func invoke(accessKeyId *string, accessKeySecret *string, endpoint *string) (_result *green20220302.ImageModerationResponse, _err error) { // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. client, _err := createClient(accessKeyId, accessKeySecret, endpoint) if _err != nil { return nil,_err } // Set runtime parameters. This is valid only for requests that use this runtime parameter instance. runtime := &util.RuntimeOptions{} // Construct an image detection request. serviceParameters, _ := json.Marshal( map[string]interface{}{ // The URL of the image to be detected, which must be publicly accessible. "imageUrl": "https://img.alicdn.com/tfs/xxxxxxxxxx001.png", // The ID of the data to be detected. "dataId":uuid.New(), }, ) imageModerationRequest := &green20220302.ImageModerationRequest{ // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global Service: tea.String("baselineCheck_global"), ServiceParameters: tea.String(string(serviceParameters)), } return client.ImageModerationWithOptions(imageModerationRequest, runtime) } func main() { /** * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M. * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account. * Common ways to get environment variables: * 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= tea.String("We recommend that you obtain the AccessKey ID of the RAM user from an environment variable"); var accessKeySecret= tea.String("We recommend that you obtain the AccessKey secret of the RAM user from an environment variable"); // Modify the region and endpoint as needed. var endpoint = tea.String("green-cip.ap-southeast-1.aliyuncs.com"); response,_err := invoke(accessKeyId,accessKeySecret,endpoint) if response != nil { statusCode := tea.IntValue(tea.ToInt(response.StatusCode)) body := response.Body imageModerationResponseData := 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 { result := imageModerationResponseData.Result fmt.Println("response dataId:" + tea.StringValue(imageModerationResponseData.DataId)) for i := 0; i < len(result); i++ { fmt.Println("response label:" + tea.StringValue(result[i].Label)) fmt.Println("response confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence))) } } else { fmt.Println("image moderation not success. status" + tea.ToString(body.Code)) } } else { fmt.Print("response not success. status:" + tea.ToString(statusCode)) fmt.Println("Error:", _err) } } }
Detect local images
Scenarios
To moderate an image that is stored on your local machine and does not have a public URL, you can upload the image to an Object Storage Service (OSS) bucket provided by Content Moderation. The Image Moderation Version 2.0 service can then directly access OSS to retrieve the image content for moderation.
Install the Go SDK.
Install the Content Moderation SDK:
go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2Install the OSS SDK:
go get github.com/aliyun/aliyun-oss-go-sdk/ossIntegrate the Go SDK.
Synchronous API integration example
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" ) // File upload token. var TokenMap =make(map[string]*green20220302.DescribeUploadTokenResponseBodyData) // Client for file uploads. var Bucket *oss.Bucket // Specifies whether the service is deployed in a VPC. var isVPC = false // Create 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 the HTTP proxy. // HttpProxy: tea.String("http://10.10.xx.xx:xxxx"), // Set the HTTPS proxy. // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"), Endpoint: tea.String(endpoint), } // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. return green20220302.NewClient(config); } // Create 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)); } } // Upload 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.ImageModerationResponse, _err error) { // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. client, _err := createClient(accessKeyId, accessKeySecret, endpoint) if _err != nil { return nil,_err } // Set runtime parameters. This is valid only for requests that use this runtime parameter instance. runtime := &util.RuntimeOptions{} // The full path of the local file, for example, D:\localPath\exampleFile.png. var filePath = "D:\\localPath\\exampleFile.png" // Get a temporary token for file upload. tokenData,ok:=TokenMap[endpoint]; if !ok || tea.Int32Value(tokenData.Expiration) <= int32(time.Now().Unix()) { // Get 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 an image detection request. serviceParameters, _ := json.Marshal( map[string]interface{}{ "ossBucketName": tea.StringValue(TokenMap[endpoint].BucketName), "ossObjectName": objectName, "dataId": uuid.New().String(), }, ) imageModerationRequest := &green20220302.ImageModerationRequest{ // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global Service: tea.String("baselineCheck_global"), ServiceParameters: tea.String(string(serviceParameters)), } return client.ImageModerationWithOptions(imageModerationRequest, runtime) } func main() { /** * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M. * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account. * Common ways to get environment variables: * 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= "We recommend that you obtain the AccessKey ID of the RAM user from an environment variable"; var accessKeySecret= "We recommend that you obtain the AccessKey secret of the RAM user from an environment variable"; // Modify the region and endpoint as needed. var endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; response,_err := invoke(accessKeyId,accessKeySecret,endpoint) if response != nil { statusCode := tea.IntValue(tea.ToInt(response.StatusCode)) body := response.Body imageModerationResponseData := 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 { result := imageModerationResponseData.Result fmt.Println("response dataId:" + tea.StringValue(imageModerationResponseData.DataId)) for i := 0; i < len(result); i++ { fmt.Println("response label:" + tea.StringValue(result[i].Label)) fmt.Println("response confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence))) } } else { fmt.Println("image moderation not success. status" + tea.ToString(body.Code)) } } else { fmt.Print("response not success. status:" + tea.ToString(statusCode)) fmt.Println("Error:", _err) } } }
Detect OSS images
Scenarios
If the image files that you need to moderate are stored in Alibaba Cloud Object Storage Service (OSS), you can create a service role to authorize the Content Moderation service to access your OSS resources. The Image Moderation V2.0 service uses this service role to retrieve files from OSS for moderation. You can create the AliyunCIPScanOSSRole service role on the Cloud Resource Access Authorization page.
Use your Alibaba Cloud account (root account) to navigate to the Cloud Resource Access Authorization page to grant permissions.
Run the following command to install the Go SDK.
go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2Integrate the Go SDK.
Synchronous API integration example
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/google/uuid" "net/http" "os" ) // Create a request client. func createClient(accessKeyId *string, accessKeySecret *string, endpoint *string) (*green20220302.Client, error) { config := &openapi.Config{ AccessKeyId: accessKeyId, AccessKeySecret: accessKeySecret, // Set the HTTP proxy. // HttpProxy: tea.String("http://10.10.xx.xx:xxxx"), // Set the HTTPS proxy. // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"), Endpoint: endpoint, } // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. return green20220302.NewClient(config); } func invoke(accessKeyId *string, accessKeySecret *string, endpoint *string) (_result *green20220302.ImageModerationResponse, _err error) { // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. client, _err := createClient(accessKeyId, accessKeySecret, endpoint) if _err != nil { return nil,_err } // Set runtime parameters. This is valid only for requests that use this runtime parameter instance. runtime := &util.RuntimeOptions{} // Construct an image detection request. serviceParameters, _ := json.Marshal( map[string]interface{}{ // The region where the bucket of the image to be detected is located. Example: ap-southeast-1 "ossRegionId": "ap-southeast-1", // The name of the bucket where the image to be detected is located. Example: bucket001 "ossBucketName":"bucket001", // The name of the object of the image to be detected. Example: image/001.jpg "ossObjectName":"image//001.jpg", // The ID of the data to be detected. "dataId": uuid.New().String(), }, ) imageModerationRequest := &green20220302.ImageModerationRequest{ // Image moderation service, the serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global Service: tea.String("baselineCheck_global"), ServiceParameters: tea.String(string(serviceParameters)), } return client.ImageModerationWithOptions(imageModerationRequest, runtime) } func main() { /** * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M. * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account. * Common ways to get environment variables: * 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") */ // Modify the region and endpoint as needed. var endpoint = tea.String("green-cip.ap-southeast-1.aliyuncs.com"); response,_err := invoke(accessKeyId,accessKeySecret,endpoint) if response != nil { statusCode := tea.IntValue(tea.ToInt(response.StatusCode)) body := response.Body imageModerationResponseData := 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 { result := imageModerationResponseData.Result fmt.Println("response dataId:" + tea.StringValue(imageModerationResponseData.DataId)) for i := 0; i < len(result); i++ { fmt.Println("response label:" + tea.StringValue(result[i].Label)) fmt.Println("response confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence))) } } else { fmt.Println("image moderation not success. status" + tea.ToString(body.Code)) } } else { fmt.Print("response not success. status:" + tea.ToString(statusCode)) fmt.Println("Error:", _err) } } }
Node.js SDK
Usage Notes
Source code reference: For more information, see Node.js SDK source code.
Supported features: The SDK supports the following three types of image detection.
For more information about the values and descriptions of the Label field returned by these API operations, see Risk label description table.
Detect publicly accessible images
Scenarios
If an image that requires moderation is accessible using a public URL, the Image Moderation V2.0 service can retrieve the file from the image URL for moderation.
Install the Node.js SDK.
Run the following command to import the relevant dependencies.
npm install @alicloud/green20220302@2.2.10Integrate the Node.js SDK.
Synchronous API integration example
const RPCClient = require("@alicloud/pop-core"); const { v4: uuidv4 } = require('uuid'); async function main() { // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. var client = new RPCClient({ /** * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M. * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account. * Common ways to get environment variables: * Get the AccessKey ID of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'] * Get the AccessKey secret of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] */ accessKeyId: 'We recommend that you obtain the AccessKey ID of the RAM user from an environment variable', accessKeySecret: 'We recommend that you obtain the AccessKey secret of the RAM user from an environment variable', // Modify the region and endpoint as needed. endpoint: "https://green-cip.ap-southeast-1.aliyuncs.com", apiVersion: '2022-03-02', // Set the HTTP proxy. // httpProxy: "http://xx.xx.xx.xx:xxxx", // Set the HTTPS proxy. // httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999", }); // Create an API request and set parameters. var params = { // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global "Service": "baselineCheck_global", "ServiceParameters": JSON.stringify({ // A unique identifier for the data. "dataId": uuidv4(), // The URL of the image to be detected, which must be publicly accessible. "imageUrl": "https://img.alicdn.com/tfs/xxxxxxxxxx001.png" }) } var requestOption = { method: 'POST', formatParams: false, }; try { // Call the API operation to get the detection results. var response = await client.request('ImageModeration', params, requestOption) } catch (err) { console.log(err); } return response; } main().then(function (response) { console.log(JSON.stringify(response)) });
Detect local images
Scenarios
To moderate images that are on your local machine and do not have a publicly accessible URL, you can upload them to an Object Storage Service (OSS) bucket provided by Content Moderation. The Image Moderation Version 2.0 service can then directly access OSS to retrieve and moderate the image content.
Install the Node.js SDK.
Install the Content Moderation SDK:
npm install @alicloud/green20220302@2.2.10Install the OSS dependency:
npm install ali-oss --saveIntegrate the Node.js SDK.
Synchronous API integration example
const RPCClient = require("@alicloud/pop-core"); const OSS = require('ali-oss'); const { v4: uuidv4 } = require('uuid'); const path = require("path"); // Specifies whether the service is deployed in a VPC. var isVPC = false; // File upload token. var tokenDic = new Array(); // Client for file uploads. var ossClient; // Create a client for file uploads. function createClient(accessKeyId, accessKeySecret, endpoint) { return new RPCClient({ accessKeyId: accessKeyId, accessKeySecret: accessKeySecret, endpoint: endpoint, apiVersion: '2022-03-02', // Set the HTTP proxy. // httpProxy: "http://xx.xx.xx.xx:xxxx", // Set the HTTPS proxy. // httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999", }); } // Create a client for file uploads. function 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'], }); } } async function invoke(accessKeyId, accessKeySecret, endpoint) { // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. var client = createClient(accessKeyId, accessKeySecret, endpoint); var requestOption = { method: 'POST', formatParams: false, }; // The full path of the local file, for example, D:\\localPath\\exampleFile.png. var filePath = 'D:\\localPath\\exampleFile.png'; // Get the file upload token. if (tokenDic[endpoint] == null || tokenDic[endpoint]['Expiration'] <= Date.parse(new Date() / 1000)) { var tokenResponse = await client.request('DescribeUploadToken', '', requestOption) tokenDic[endpoint] = tokenResponse.Data; } // Get the client for file uploads. 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)); // Create a detection API request and set parameters. var params = { // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global "Service": "baselineCheck_global", // Information about the uploaded local image. "ServiceParameters": JSON.stringify({ "ossBucketName": tokenDic[endpoint].BucketName, "ossObjectName": objectName }) } // Call the API operation to get the detection results. return await client.request('ImageModeration', params, requestOption); } function main() { /** * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M. * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account. * Common ways to get environment variables: * Get the AccessKey ID of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'] * Get the AccessKey secret of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] */ const accessKeyId: 'We recommend that you obtain the AccessKey ID of the RAM user from an environment variable' const accessKeySecret: 'We recommend that you obtain the AccessKey secret of the RAM user from an environment variable' // Modify the region and endpoint as needed. var endpoint = "https://green-cip.ap-southeast-1.aliyuncs.com" try { // Call the API operation to get the detection results. invoke(accessKeyId, accessKeySecret, endpoint).then(function (response) { console.log(JSON.stringify(response)) }) } catch (err) { console.log(err); } } main();
Detect OSS images
Scenarios
If the image files that you want to moderate are stored in Object Storage Service (OSS), you can create a service role to grant the Content Moderation service access to your OSS resources. The Image Moderation Version 2.0 service uses this service role to retrieve files from OSS for moderation. You can create the AliyunCIPScanOSSRole service role on the Cloud Resource Access Authorization page.
Use your Alibaba Cloud account (root account) to navigate to the Cloud Resource Access Authorization page to grant permissions.
Install the Node.js SDK.
npm install @alicloud/green20220302@2.2.10Integrate the Node.js SDK.
Synchronous API integration example
const RPCClient = require("@alicloud/pop-core"); const { v4: uuidv4 } = require('uuid'); async function main() { // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. var client = new RPCClient({ /** * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M. * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account. * Common ways to get environment variables: * Get the AccessKey ID of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'] * Get the AccessKey secret of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] */ accessKeyId: 'We recommend that you obtain the AccessKey ID of the RAM user from an environment variable', accessKeySecret: 'We recommend that you obtain the AccessKey secret of the RAM user from an environment variable', // Modify the region and endpoint as needed. endpoint: "https://green-cip.ap-southeast-1.aliyuncs.com", apiVersion: '2022-03-02', // Set the HTTP proxy. // httpProxy: "http://xx.xx.xx.xx:xxxx", // Set the HTTPS proxy. // httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999", }); // Create an API request and set parameters. var params = { // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global "Service": "baselineCheck_global", // OSS information of the image to be detected. "ServiceParameters": JSON.stringify({ // The region where the bucket of the file to be detected is located. Example: ap-southeast-1 "ossRegionId": "ap-southeast-1", // The name of the bucket where the file to be detected is located. Example: bucket001 "ossBucketName": "bucket001", // The file to be detected. Example: image/001.jpg "ossObjectName": "image/001.jpg", // A unique identifier for the data. "dataId": uuidv4() }) } var requestOption = { method: 'POST', formatParams: false, }; try { // Call the API operation to get the detection results. var response = await client.request('ImageModeration', params, requestOption) return response; } catch (err) { console.log(err); } } main().then(function (response) { console.log(JSON.stringify(response)) });
C# SDK
Precautions
Source code reference: For more information, see C# SDK source code.
Supported features: The SDK supports the following three types of image detection.
For more information about the values and descriptions of the Label field returned by these API operations, see Risk label description table.
Detect publicly accessible images
Scenarios
If an image to be moderated is accessible using a public URL, the Image Moderation Version 2.0 service can retrieve the file from the image URL to perform moderation.
You can install the C# SDK.
dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10Integrate the C# SDK.
Synchronous API integration example
// This file is auto-generated, don't edit it. Thanks. using Newtonsoft.Json; namespace AlibabaCloud.SDK.Green20220302 { public class ImageModerationAutoRoute { public static void Main(string[] args) { /** * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M. * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account. * Common ways to get 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 = "We recommend that you obtain the AccessKey ID of the RAM user from an environment variable"; String accessKeySecret = "We recommend that you obtain the AccessKey secret of the RAM user from an environment variable"; // Modify the region and endpoint as needed. String endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. Client client = createClient(accessKeyId, accessKeySecret, endpoint); // Set runtime parameters. This is valid only for requests that use this runtime parameter instance. AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); // Construct an image detection request. Models.ImageModerationRequest imageModerationRequest = new Models.ImageModerationRequest(); // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global imageModerationRequest.Service = "baselineCheck_global"; Dictionary<string, object> task = new Dictionary<string, object>(); // The URL of the image to be detected, which must be publicly accessible. task.Add( "imageUrl", "https://img.alicdn.com/tfs/xxxxxxxxxx001.png" ); // The ID of the data to be detected. task.Add("dataId", Guid.NewGuid().ToString()); imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task); try { // Call the API operation to get the detection results. Models.ImageModerationResponse response = client.ImageModerationWithOptions( imageModerationRequest, runtimeOptions ); Console.WriteLine(response.Body.RequestId); Console.WriteLine(JsonConvert.SerializeObject(response.Body)); } catch (Exception _err) { Console.WriteLine(_err); } } // Create 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 the HTTP proxy. // HttpProxy = "http://10.10.xx.xx:xxxx", // Set the HTTPS proxy. // HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999", // The domain name to access. Endpoint = endpoint, }; return new Client(config); } } }
Detect local images
Scenarios
To moderate images that are on your local machine and do not have a publicly accessible URL, you can upload them to an Object Storage Service (OSS) bucket provided by Content Moderation. The Image Moderation V2.0 service can then directly access OSS to retrieve the images and perform moderation.
Install the C# SDK.
Install the Content Moderation SDK:
dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10Install the OSS SDK:
//. dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.8 //. Install via NuGet 1. If your Visual Studio does not have NuGet installed, install it first. 2. In Visual Studio, create a new project or open an existing one. Choose 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.
Synchronous API integration example
// This file is auto-generated, don't edit it. Thanks. using System; using Newtonsoft.Json; using Aliyun.OSS; namespace AlibabaCloud.SDK.Green20220302 { public class ImageModerationAutoRoute { // File upload token. public static Dictionary<String, Models.DescribeUploadTokenResponse> tokenDic = new Dictionary<String, Models.DescribeUploadTokenResponse>(); // Client for file uploads. public static OssClient ossClient = null; // Specifies whether the service is deployed in a VPC. public static Boolean isVPC = false; public static void Main(string[] args) { /** * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M. * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account. * Common ways to get 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 = "We recommend that you obtain the AccessKey ID of the RAM user from an environment variable"; String accessKeySecret = "We recommend that you obtain the AccessKey secret of the RAM user from an environment variable"; // Modify the region and endpoint as needed. String endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; Models.ImageModerationResponse response = invoke( accessKeyId, accessKeySecret, endpoint ); Console.WriteLine(response.Body.RequestId); Console.WriteLine(JsonConvert.SerializeObject(response.Body)); } // Create 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 the HTTP proxy. // HttpProxy = "http://10.10.xx.xx:xxxx", // Set the HTTPS proxy. // HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999", // The domain name to access. Endpoint = endpoint, }; return new Client(config); } // Create a client for file uploads. private static OssClient getOssClient( Models.DescribeUploadTokenResponse tokenResponse, Boolean 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 ); } } // Upload a file. public static String uploadFile( String filePath, Models.DescribeUploadTokenResponse tokenResponse ) { // Construct an OssClient instance. ossClient = getOssClient(tokenResponse, isVPC); var tokenData = tokenResponse.Body.Data; String objectName = tokenData.FileNamePrefix + Guid.NewGuid().ToString() + "." + filePath.Split(".").GetValue(1); // Upload the file. ossClient.PutObject(tokenData.BucketName, objectName, filePath); return objectName; } // Submit a detection request. public static Models.ImageModerationResponse invoke( String accessKeyId, String accessKeySecret, String endpoint ) { // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. Client client = createClient(accessKeyId, accessKeySecret, endpoint); // Set runtime parameters. This is valid only for requests that use this runtime parameter instance. AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); // The full path of the local file, for example, D:\localPath\exampleFile.png. String filePath = "D:\\localPath\\exampleFile.png."; try { // Get 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; } // Upload the file. String objectName = uploadFile(filePath, tokenDic[endpoint]); // Construct an image detection request. Models.ImageModerationRequest imageModerationRequest = new Models.ImageModerationRequest(); // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global imageModerationRequest.Service = "baselineCheck_global"; Dictionary<string, object> task = new Dictionary<string, object>(); // Information about the image to be detected. task.Add("ossBucketName", tokenDic[endpoint].Body.Data.BucketName); task.Add("ossObjectName", objectName); // The ID of the data to be detected. task.Add("dataId", Guid.NewGuid().ToString()); imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task); // Call the API operation to get the detection results. Models.ImageModerationResponse response = client.ImageModerationWithOptions( imageModerationRequest, runtimeOptions ); return response; } catch (Exception _err) { Console.WriteLine(_err); return null; } } } }
Detect OSS images
Scenarios
If the image files that you need to moderate are stored in Alibaba Cloud Object Storage Service (OSS), you can create a service role to grant the Content Moderation service access to your OSS resources. The Image Moderation Version 2.0 service uses this service role to retrieve files from OSS for moderation. You can create the AliyunCIPScanOSSRole service role on the Cloud Resource Access Authorization page.
Use your Alibaba Cloud account (root account) to navigate to the Cloud Resource Access Authorization page to grant permissions.
Install the C# SDK.
dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10Integrate the C# SDK.
Synchronous API integration example
// This file is auto-generated, don't edit it. Thanks. using Newtonsoft.Json; namespace AlibabaCloud.SDK.Green20220302 { public class OssScanDemo { public static void Main(string[] args) { /** * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M. * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account. * Common ways to get 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 = "We recommend that you obtain the AccessKey ID of the RAM user from an environment variable"; String accessKeySecret = "We recommend that you obtain the AccessKey secret of the RAM user from an environment variable"; // Modify the region and endpoint as needed. String endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance. Client client = createClient(accessKeyId, accessKeySecret, endpoint); // Set runtime parameters. This is valid only for requests that use this runtime parameter instance. AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); // Construct an image detection request. Models.ImageModerationRequest imageModerationRequest = new Models.ImageModerationRequest(); // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global imageModerationRequest.Service = "baselineCheck_global"; Dictionary<string, object> task = new Dictionary<string, object>(); // The region where the bucket of the image to be detected is located. Example: ap-southeast-1 task.Add("ossRegionId", "ap-southeast-1"); // The name of the bucket where the image to be detected is located. Example: bucket001 task.Add("ossBucketName", "bucket001"); // The name of the object of the image to be detected. Example: image/001.jpg task.Add("ossObjectName", "image/001.jpg"); // The ID of the data to be detected. task.Add("dataId", Guid.NewGuid().ToString()); imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task); try { // Call the API operation to get the detection results. Models.ImageModerationResponse response = client.ImageModerationWithOptions( imageModerationRequest, runtimeOptions ); Console.WriteLine(response.Body.RequestId); Console.WriteLine(JsonConvert.SerializeObject(response.Body)); } catch (Exception _err) { Console.WriteLine(_err); } } // Create 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 the HTTP proxy. // HttpProxy = "http://10.10.xx.xx:xxxx", // Set the HTTPS proxy. // HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999", // The domain name to access. Endpoint = endpoint, }; return new Client(config); } } }
HTTPS native call
The Content Moderation Version 2.0 API service also supports native HTTPS calls. This method requires you to manually handle request signing and verification, and assemble the request, including the URL, body, header, and parameters. Native HTTPS calls are typically required in only two scenarios. If your use case is not one of these two scenarios, we recommend that you use an SDK to make calls.
Direct use in an app with high requirements for client size.
Specific dependency on certain library packages that are inconvenient to upgrade.
Calling method
Service request endpoint: https://green-cip.{region}.aliyuncs.com
Protocol: HTTPS
Method: POST
Common request parameters
The request parameters for Image Moderation V2.0 API operations consist of common request parameters and API-specific request parameters. Common request parameters are required for all API operations. The following table describes the common request parameters.
Name
Type
Required
Description
Format
String
Yes
The format of the response message. Valid values:
JSON (default)
XML
Version
String
Yes
The API version number, in YYYY-MM-DD format. This version is 2022-03-02.
AccessKeyId
String
Yes
The AccessKey ID issued by Alibaba Cloud for accessing the service.
Signature
String
Yes
The signature string. For information on how to calculate the signature, see the signature method below.
SignatureMethod
String
Yes
The signature method. HMAC-SHA1 is currently supported.
Timestamp
String
Yes
The timestamp of the request. The date format must follow the ISO 8601 standard and be in UTC. The format is yyyy-MM-ddTHH:mm:ssZ. For example, 09:13:14 on December 12, 2022 (UTC+8) is represented as 2022-12-12T01:13:14Z.
SignatureVersion
String
Yes
The signature algorithm version. The value is 1.0.
SignatureNonce
String
Yes
A unique random number used to prevent network replay attacks. Different requests must use different random values.
Action
String
Yes
Synchronous image API: ImageModeration
Asynchronous image API: ImageAsyncModeration
Get asynchronous image moderation result API: DescribeImageModerationResult
Multi-service synchronous image API: ImageBatchModeration
Common response parameters
For each API call that you send, the system returns a unique identifier, RequestId, regardless of whether the call is successful. Other response parameters include the label and confidence score. The returned parameters vary by service. For more information, see the documentation for the specific service.
NoteFor more information about the values and descriptions of the
Labelfield returned by these API operations, see Risk label description table.Code example
The following response examples are formatted for readability. The actual response is not formatted with line breaks or indentation.
The following is a request example for the Image Moderation V2.0 - General Baseline Detection Service Sync API. For other API operations, see the specific API documentation for the business request parameters:
https://green-cip.ap-southeast-1.aliyuncs.com/ ?Format=JSON &Version=2022-03-02 &Signature=vpEEL0zFHfxXYzSFV0n7%2FZiFL9o%3D &SignatureMethod=Hmac-SHA1 &SignatureNonce=15215528852396 &SignatureVersion=1.0 &Action=ImageModeration &AccessKeyId=123****cip &Timestamp=2022-12-12T12:00:00Z &Service=baselineCheck_global &ServiceParameters={"imageUrl": "https://img.alicdn.com/tfs/TB1U4r9AeH2gK0jSZJnXXaT1FXa-2880-480.png", "dataId": "img1234567"}The following is a JSON code example of the returned parameters for the Image Moderation Version 2.0 - General Baseline Detection Service synchronous API:
{ "Msg": "OK", "Code": 200, "Data": { "DataId": "uimg123****", "Result": [ { "Label": "pornographic_adultContent", "Confidence": 81.3 }, { "Label": "sexual_partialNudity", "Confidence": 98.9 } ] }, "RequestId": "ABCD1234-1234-1234-1234-1234XYZ" }Signature method
The Image Moderation V2.0 service authenticates every request. Therefore, each request must include a signature. The Image Moderation V2.0 service verifies the identity of the sender using symmetric encryption with an AccessKey ID and an AccessKey secret.
The AccessKey ID and AccessKey secret are issued by Alibaba Cloud. You can apply for and manage them on the Alibaba Cloud website. The AccessKey ID is used to identify you. The AccessKey secret is a key used to encrypt the signature string and for server-side verification of the signature string. It must be kept strictly confidential.
To access the service, sign the request using the following method:
Construct a canonicalized query string from the request parameters.
Sort all request parameters (including common request parameters and API-specific request parameters, but not the Signature parameter) in alphabetical order of their names.
Encode the names and values of the request parameters. The names and values must be URL-encoded using the UTF-8 character set.
NoteLibraries that support URL encoding, such as java.net.URLEncoder in Java, typically encode based on the rules of the application/x-www-form-urlencoded MIME type. You can use this method for encoding. Replace the plus sign (+) in the encoded string with %20, the asterisk (*) with %2A, and %7E with a tilde (~) to obtain the encoded string that is described by the preceding rules.
The URL encoding rules are as follows:
Characters A-Z, a-z, 0-9, and the characters hyphen (-), underscore (_), period (.), and tilde (~) are not encoded.
Other characters are encoded in the format
%XY, where XY is the hexadecimal representation of the character's ASCII code. For example, the English double quotation mark (") is encoded as%22.Extended UTF-8 characters are encoded in the format
%XY%ZA….Note that the English space ( ) must be encoded as
%20, not a plus sign (+).
Connect the encoded parameter name and value with an equal sign (=).
Connect the strings that are joined by the equal sign in the alphabetical order of the parameter names using an ampersand (&) to obtain the canonicalized query string.
Create the string to sign from the normalized string in step a.i based on the following rules.
StringToSign= HTTPMethod + "&" + percentEncode("/") + "&" + percentEncode(CanonicalizedQueryString)NoteIn this format, HTTPMethod is the HTTP method used to submit the request, such as POST. percentEncode(/) is the value that is obtained by encoding the character (/) based on the URL encoding rules described in the previous step, which is
%2F. percentEncode(CanonicalizedQueryString) is the string that is obtained by encoding the canonicalized query string from the previous step based on the same URL encoding rules.As defined in RFC 2104, use the string for signing to calculate the HMAC signature value.
NoteThe key used for signature calculation is your AccessKey secret appended with an ampersand (
&) character (ASCII code 38). The hash algorithm is SHA1.Encode the HMAC value into a string based on Base64 encoding rules to obtain the signature value (Signature).
Add the signature value as the Signature parameter to the request parameters.
NoteWhen the signature value is submitted to the Content Moderation server as the final request parameter, it must be URL-encoded based on the rules of RFC 3986, similar to other parameters.