You can call the Image Moderation 2.0 API by using SDKs or HTTPS requests. We recommend that you use SDKs to call the API so as to skip some operations such as signature verification and HTTPS request body construction. This topic describes how to use Image Moderation 2.0.
Step 1: Activate Image Moderation 2.0
Open the Content Moderation V2.0 page and activate the Image Moderation 2.0 service.
After you activate the Image Moderation 2.0 service, the default billing method is pay-as-you-go. Daily fees are calculated based on the actual usage. If the service is not called, no charge is made. After you call API operations, the billing system automatically charges you based on your usage. For more information, see Billing rules.
Step 2: Create a RAM user and grant permissions to the RAM user
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
AliyunYundunGreenWebFullAccess
system policy to the RAM user. For more information, see Grant permissions to a RAM user.
Step 3: Install and use SDKs
The following table provides the supported regions.
Region | Public endpoint | Internal endpoint |
Singapore | green-cip.ap-southeast-1.aliyuncs.com | green-cip-vpc.ap-southeast-1.aliyuncs.com |
If you need SDK sample code in other programming languages, you can call an API operation in OpenAPI Explorer. OpenAPI Explorer dynamically generates the sample code of the operation for different SDKs.
In Alibaba Cloud SDK code, you can create a default access credential by defining ALIBABA_CLOUD_ACCESS_KEY_ID
and ALIBABA_CLOUD_ACCESS_KEY_SECRET
environment variables. When you call API operations of Alibaba Cloud services, the system directly accesses the credential, reads your AccessKey pair, and then automatically completes authentication. Before you use the SDK sample code, you must configure environment variables. For more information, see Configure credentials.
Java SDK
The Java version must be 1.8 or later.
For more information about the source code, see SDK source code for Java or SDK source code for Java in Open Source Software (OSS).
The following three ways of image moderation are supported.
Moderate an image that can be accessed over the Internet
Scenario
If the image to be moderated can be accessed over the Internet, Image Moderation 2.0 can obtain the image from the image URL for moderation.
Add the following dependencies to the pom.xml file to install the SDK for Java. This way, you can use the SDK in Maven projects.
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>2.2.11</version> </dependency>
Use the Java SDK.
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 the client that initiates image moderation requests. * * @param accessKeyId * @param accessKeySecret * @param endpoint * @return * @throws Exception */ public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception { Config config = new Config(); config.setAccessKeyId(accessKeyId); config.setAccessKeySecret(accessKeySecret); // Configure an HTTP proxy. // config.setHttpProxy("http://10.10.xx.xx:xxxx"); // Configure an HTTPS proxy. // config.setHttpsProxy("https://10.10.xx.xx:xxxx"); // Change the region ID and endpoint based on your business requirements. config.setEndpoint(endpoint); return new Client(config); } public static ImageModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception { // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation performance. Client client = createClient(accessKeyId, accessKeySecret, endpoint); // Create a RuntimeObject instance and configure runtime parameters. RuntimeOptions runtime = new RuntimeOptions(); // Construct moderation parameters. Map<String, String> serviceParameters = new HashMap<>(); // The URL that can be accessed over the Internet. serviceParameters.put("imageUrl", "https://img.alicdn.com/tfs/xxxxxxxxxx001.png"); // The unique ID of the data to be moderated. serviceParameters.put("dataId", UUID.randomUUID().toString()); ImageModerationRequest request = new ImageModerationRequest(); // Image moderation service: The service code configured for Image Moderation 2.0 in the Content Moderation console. 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 { /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * Common ways to obtain environment variables: * Method 1: * Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ String accessKeyId = "We recommend that you obtain the AccessKey ID of your RAM user from environment variables"; String accessKeySecret = "We recommend that you obtain the AccessKey secret of your RAM user from environment variables"; ImageModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com"); // Print the moderation 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()); } } } }
Moderate a local image
Scenario
If the image that you want to moderate is stored on your local computer and cannot be accessed over the Internet, you can upload the image to an OSS bucket provided by the Content Moderation service. Image Moderation 2.0 can obtain the image from the OSS bucket for moderation.
Install the Java SDK.
Install the SDK for Content Moderation:
<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>
Use the Java SDK.
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; // The token used to upload the file. The key is the endpoint of Content Moderation and the value is the token. public static Map<String, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData> tokenMap = new HashMap<>(); // The client that uploads the file. public static OSS ossClient = null; /** * Create the client that initiates image moderation requests. * * @param accessKeyId * @param accessKeySecret * @param endpoint * @return * @throws Exception */ public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception { Config config = new Config(); config.setAccessKeyId(accessKeyId); config.setAccessKeySecret(accessKeySecret); // Change the region ID and endpoint based on your business requirements. config.setEndpoint(endpoint); return new Client(config); } /** * Create the client that uploads the file. * * @param tokenData * @param isVPC */ public static void getOssClient(DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData, boolean isVPC) { // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation 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 the 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: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation performance. Client client = createClient(accessKeyId, accessKeySecret, endpoint); RuntimeOptions runtime = new RuntimeOptions(); // The full path of the local file. Example: D:\localPath\exampleFile.png. String filePath = "D:\localPath\exampleFile.png"; // Obtain a temporary token for uploading the file. if (tokenMap.get(endpoint) == null || tokenMap.get(endpoint).expiration <= System.currentTimeMillis() / 1000) { DescribeUploadTokenResponse tokenResponse = client.describeUploadToken(); tokenMap.put(endpoint,tokenResponse.getBody().getData()); } // The client that uploads the file. getOssClient(tokenMap.get(endpoint), isVPC); // Upload the file. String objectName = uploadFile(filePath, tokenMap.get(endpoint)); // Construct moderation parameters. Map<String, String> serviceParameters = new HashMap<>(); // Information about uploading the file. 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 service code configured for Image Moderation 2.0 in the Content Moderation console. Example: baselineCheck. request.setService("baselineCheck"); 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 { /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * Common ways to obtain environment variables: * Method 1: * Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ String accessKeyId = "We recommend that you obtain the AccessKey ID of your RAM user from environment variables"; String accessKeySecret = "We recommend that you obtain the AccessKey secret of your RAM user from environment variables"; // Change the access region ID and endpoint based on your business requirements. ImageModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-shanghai.aliyuncs.com"); try { // Automatic routing. if (response != null) { // Switch the region to cn-beijing. if (500 == response.getStatusCode() || (response.getBody() != null && 500 == (response.getBody().getCode()))) { // Change the access region ID and endpoint based on your business requirements. response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.cn-beijing.aliyuncs.com"); } } // Print the moderation 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(); } } }
Moderate an image stored in OSS
Scenario
If the image that you want to moderate is stored in an Alibaba Cloud OSS bucket, you can grant the permissions to create a service-linked role (SLR) to allow the Content Moderation service to access the OSS bucket. Image Moderation 2.0 uses the SLR to obtain the image from the OSS bucket for moderation. Go to the Cloud Resource Access Authorization page to create an SLR.
Use your Alibaba Cloud account to access the Cloud Resource Access Authorization page to grant permissions.
Add the following dependencies to the pom.xml file to install the SDK for Java. This way, you can use the SDK in Maven projects.
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>2.2.11</version> </dependency>
Use the Java SDK.
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 the client that initiates image moderation requests. * * @param accessKeyId * @param accessKeySecret * @param endpoint * @return * @throws Exception */ public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception { Config config = new Config(); config.setAccessKeyId(accessKeyId); config.setAccessKeySecret(accessKeySecret); // Configure an HTTP proxy. // config.setHttpProxy("http://10.10.xx.xx:xxxx"); // Configure an HTTPS proxy. // config.setHttpsProxy("https://10.10.xx.xx:xxxx"); // Change the region ID and endpoint based on your business requirements. config.setEndpoint(endpoint); return new Client(config); } public static ImageModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception { // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation performance. Client client = createClient(accessKeyId, accessKeySecret, endpoint); // Create a RuntimeObject instance and configure runtime parameters. RuntimeOptions runtime = new RuntimeOptions(); // Construct moderation parameters. Map<String, String> serviceParameters = new HashMap<>(); // The unique ID of the data to be moderated. serviceParameters.put("dataId", UUID.randomUUID().toString()); // The region of the bucket where the image to be moderated is located. Example: ap-southeast-1. serviceParameters.put("ossRegionId", "ap-southeast-1"); // The name of the bucket where the image to be moderated is located. Example: bucket001. serviceParameters.put("ossBucketName", "bucket001"); // The image to be moderated. Example: image/001.jpg. serviceParameters.put("ossObjectName", "image/001.jpg"); ImageModerationRequest request = new ImageModerationRequest(); // Image moderation service: The service code configured for Image Moderation 2.0 in the Content Moderation console. 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 { /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * Common ways to obtain environment variables: * Method 1: * Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ String accessKeyId = "We recommend that you obtain the AccessKey ID of your RAM user from environment variables"; String accessKeySecret = "We recommend that you obtain the AccessKey secret of your RAM user from environment variables"; ImageModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com"); // Print the moderation 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
The Python version must be 3.6 or later.
For more information about the source code, see SDK source code for Python.
The following three ways of image moderation are supported.
Moderate an image that can be accessed over the Internet
Scenario
If the image to be moderated can be accessed over the Internet, Image Moderation 2.0 can obtain the image from the image URL for moderation.
Run the following command to install the related dependencies.
pip install alibabacloud_green20220302==2.2.11
Use the Python SDK.
# 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 os import uuid # Create the client that initiates image moderation requests. def create_client(access_key_id, access_key_secret, endpoint): config = Config( access_key_id=access_key_id, access_key_secret=access_key_secret, # Configure an HTTP proxy. # http_proxy='http://10.10.xx.xx:xxxx', # Configure an HTTPS proxy. # https_proxy='https://10.10.xx.xx:xxxx', # Change the region ID and endpoint based on your business requirements. endpoint=endpoint ) return Client(config) def invoke_function(access_key_id, access_key_secret, endpoint): # Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation performance. client = create_client(access_key_id, access_key_secret, endpoint) # Create a RuntimeObject instance and configure runtime parameters. runtime = util_models.RuntimeOptions() # Construct moderation parameters. service_parameters = { # The URL of the image that can be accessed over the Internet. 'imageUrl': 'https://img.alicdn.com/tfs/xxxxxxxxxx001.png', # The unique ID of the data. 'dataId': str(uuid.uuid1()) } image_moderation_request = models.ImageModerationRequest( # Image moderation service: The service code configured for Image Moderation 2.0 in the Content Moderation console. 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__': # The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. # We recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. # Common ways to obtain environment variables: # Obtain the AccessKey ID of your RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain the AccessKey secret of your RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='We recommend that you obtain the AccessKey ID of your RAM user from environment variables' access_key_secret='We recommend that you obtain the AccessKey secret of your RAM user from environment variables' # Change the region ID and endpoint based on your business requirements. 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 is successful. # Obtain 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))
Submit a local image for image moderation
Scenario
If the image that you want to moderate is stored on your local computer and cannot be accessed over the Internet, you can upload the image to an OSS bucket provided by the Content Moderation service. Image Moderation 2.0 can obtain the image from the OSS bucket for moderation.
Install the SDK for Python.
Install the SDK for Content Moderation:
pip install alibabacloud_green20220302==2.2.11
Install the OSS SDK:
pip install oss2
Use the Python SDK.
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 # The token used to upload the file. The key is the endpoint of Content Moderation and the value is the token. token_dict = dict() # The client that uploads the file. bucket = None # Create the client that initiates image moderation requests. def create_client(access_key_id, access_key_secret, endpoint): config = Config( access_key_id=access_key_id, access_key_secret=access_key_secret, # Configure an HTTP proxy. # http_proxy='http://10.10.xx.xx:xxxx', # Configure an HTTPS proxy. # https_proxy='https://10.10.xx.xx:xxxx', # Change the region ID and endpoint based on your business requirements. endpoint=endpoint ) return Client(config) # Create the client that uploads the file. 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: We recommend that you reuse the instantiated bucket as much as possible to avoid repeatedly establishing connections and improve the moderation 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: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation performance. client = create_client(access_key_id, access_key_secret, endpoint) # Create a RuntimeObject instance and configure runtime parameters. runtime = util_models.RuntimeOptions() # The full path of the local file. Example: D:\localPath\exampleFile.png. file_path = 'D:\localPath\exampleFile.png' # Obtain a temporary token for uploading the file. 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 moderation parameters. service_parameters = { # The name of the bucket where the image to be moderated is located. 'ossBucketName': upload_token.bucket_name, # The image to be moderated. 'ossObjectName': object_name, # The unique ID of the data. 'dataId': str(uuid.uuid1()) } image_moderation_request = models.ImageModerationRequest( # Image moderation service: The service code configured for Image Moderation 2.0 in the Content Moderation console. 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__': # The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. # We recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. # Common ways to obtain environment variables: # Obtain the AccessKey ID of your RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain the AccessKey secret of your RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='We recommend that you obtain the AccessKey ID of your RAM user from environment variables' access_key_secret='We recommend that you obtain the AccessKey secret of your RAM user from environment variables' # Change the region ID and endpoint based on your business requirements. 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 is successful. # Obtain 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))
Moderate an image stored in OSS
Scenario
If the image that you want to moderate is stored in an Alibaba Cloud OSS bucket, you can grant the permissions to create an SLR to allow the Content Moderation service to access the OSS bucket. Image Moderation 2.0 uses the SLR to obtain the image from the OSS bucket for moderation. Go to the Cloud Resource Access Authorization page to create an SLR.
Use your Alibaba Cloud account to access the Cloud Resource Access Authorization page to grant permissions.
Run the following command to install the Python SDK:
pip install alibabacloud_green20220302==2.2.11
Use the Python SDK.
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 the client that initiates image moderation requests. def create_client(access_key_id, access_key_secret, endpoint): config = Config( access_key_id=access_key_id, access_key_secret=access_key_secret, # Configure an HTTP proxy. # http_proxy='http://10.10.xx.xx:xxxx', # Configure an HTTPS proxy. # https_proxy='https://10.10.xx.xx:xxxx', # Change the region ID and endpoint based on your business requirements. endpoint=endpoint ) return Client(config) def invoke_function(access_key_id, access_key_secret, endpoint): # Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation performance. client = create_client(access_key_id, access_key_secret, endpoint) # Create a RuntimeObject instance and configure runtime parameters. runtime = util_models.RuntimeOptions() # Construct moderation parameters. service_parameters = { # The region of the bucket where the image to be moderated is located. Example: ap-southeast-1. 'ossRegionId': 'ap-southeast-1', # The name of the bucket where the image to be moderated is located. Example: bucket001. 'ossBucketName': 'bucket001', # The image to be moderated. Example: image/001.jpg. 'ossObjectName': 'image/001.jpg', # The unique ID of the data. 'dataId': str(uuid.uuid1()) } image_moderation_request = models.ImageModerationRequest( # Image moderation service: The service code configured for Image Moderation 2.0 in the Content Moderation console. 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__': # The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. # We recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. # Common ways to obtain environment variables: # Obtain the AccessKey ID of your RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain the AccessKey secret of your RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='We recommend that you obtain the AccessKey ID of your RAM user from environment variables' access_key_secret='We recommend that you obtain the AccessKey secret of your RAM user from environment variables' # Change the region ID and endpoint based on your business requirements. 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 is successful. # Obtain 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
The PHP version must be 5.6 or later.
For more information about the source code, see SDK source code for PHP.
The following three ways of image moderation are supported.
Moderate an image that can be accessed over the Internet
Scenario
If the image to be moderated can be accessed over the Internet, Image Moderation 2.0 can obtain the image from the image URL for moderation.
Install the PHP SDK.
Run the following command to install the related dependencies.
composer require alibabacloud/green-20220302 2.2.10
Use the PHP SDK.
<?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 the client that initiates image moderation requests. * @param $accessKeyId * @param $accessKeySecret * @param $endpoint * @return Green */ function create_client($accessKeyId, $accessKeySecret, $endpoint): Green { $config = new Config([ "accessKeyId" => $accessKeyId, "accessKeySecret" => $accessKeySecret, // Configure an HTTP proxy. // "httpProxy" => "http://10.10.xx.xx:xxxx", // Configure an HTTPS proxy. // "httpsProxy" => "https://10.10.xx.xx:xxxx", "endpoint" => $endpoint, ]); return new Green($config); } /** * Submit an image moderation task. * @param $accessKeyId * @param $accessKeySecret * @param $endpoint * @return ImageModerationResponse */ function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageModerationResponse { // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation performance. $client = create_client($accessKeyId, $accessKeySecret, $endpoint); // Create a RuntimeObject instance and set runtime parameters. $runtime = new RuntimeOptions([]); // Construct moderation parameters. $request = new ImageModerationRequest(); $serviceParameters = array( // The URL of the image to be moderated, which is accessible over the Internet. 'imageUrl' => 'https://img.alicdn.com/tfs/xxxxxxxxxx001.png', // The unique ID of the data to be moderated. 'dataId' => uniqid()); // Image moderation service: The service code configured for Image Moderation 2.0 in the Content Moderation console. Example: baselineCheck_global. $request->service = "baselineCheck_global"; $request->serviceParameters = json_encode($serviceParameters); // Submit the image moderation task. return $client->imageModerationWithOptions($request, $runtime); } /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * We recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. * Common ways to obtain environment variables: * Obtain the AccessKey ID of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ $accessKeyId = 'We recommend that you obtain the AccessKey ID of your RAM user from environment variables'; $accessKeySecret = 'We recommend that you obtain the AccessKey secret of your RAM user from environment variables'; // Change the region ID and endpoint based on your business requirements. $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()); }
Moderate a local image
Scenario
If the image that you want to moderate is stored on your local computer and cannot be accessed over the Internet, you can upload the image to an OSS bucket provided by the Content Moderation service. Image Moderation 2.0 can obtain the image from the OSS bucket for moderation.
Install the PHP SDK.
Install the SDK for Content Moderation:
composer require alibabacloud/green-20220302 2.2.10
Install the OSS SDK:
composer require aliyuncs/oss-sdk-php
Use the PHP SDK.
<?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; // Obtain a temporary token for uploading the file. $tokenArray = array(); // The client that uploads the file. $ossClient = null; /** * Create the client that initiates image moderation requests. * @param $accessKeyId * @param $accessKeySecret * @param $endpoint * @return Green */ function create_client($accessKeyId, $accessKeySecret, $endpoint): Green { $config = new Config([ "accessKeyId" => $accessKeyId, "accessKeySecret" => $accessKeySecret, // Configure an HTTP proxy. // "httpProxy" => "http://10.10.xx.xx:xxxx", // Configure an HTTPS proxy. // "httpsProxy" => "https://10.10.xx.xx:xxxx", "endpoint" => $endpoint, ]); return new Green($config); } /** * Create the client that uploads the file. * @param $tokenData * @return void */ function create_upload_client($tokenData): void { global $isVPC; global $ossClient; // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation 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 the file. * @param $fileName * @param $tokenData * @return string * @throws \OSS\Core\OssException */ function upload_file($filePath, $tokenData): string { global $ossClient; // Initialize an OSSClient instance. 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 an image moderation task. * @param $accessKeyId * @param $accessKeySecret * @param $endpoint * @return ImageModerationResponse * @throws \OSS\Core\OssException */ function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageModerationResponse { global $tokenArray; // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation 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. Example: D:\localPath\exampleFile.png. $filePath = "D:\\localPath\\exampleFile.png"; // Obtain a temporary token for uploading the file. 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 moderation parameters. $request = new ImageModerationRequest(); // Image moderation service: The service code configured for Image Moderation 2.0 in the Content Moderation console. Example: baselineCheck_global. $request->service = "baselineCheck_global"; // The URL of the image to be moderated, which can be accessed over the Internet. $serviceParameters = array( 'ossObjectName' => $objectName, 'ossBucketName' => $tokenArray[$endpoint]->bucketName, 'dataId' => uniqid()); $request->serviceParameters = json_encode($serviceParameters); // Submit the image moderation task. return $client->imageModerationWithOptions($request, $runtime); } /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * We recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. * Common ways to obtain environment variables: * Obtain the AccessKey ID of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ $accessKeyId = 'We recommend that you obtain the AccessKey ID of your RAM user from environment variables'; $accessKeySecret = 'We recommend that you obtain the AccessKey secret of your RAM user from environment variables'; // Change the region ID and endpoint based on your business requirements. $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()); }
Moderate an image stored in OSS
Scenario
If the image that you want to moderate is stored in an Alibaba Cloud OSS bucket, you can grant the permissions to create an SLR to allow the Content Moderation service to access the OSS bucket. Image Moderation 2.0 uses the SLR to obtain the image from the OSS bucket for moderation. Go to the Cloud Resource Access Authorization page to create an SLR.
Use your Alibaba Cloud account to access the Cloud Resource Access Authorization page to grant permissions.
Install the PHP SDK.
composer require alibabacloud/green-20220302 2.2.10
Use the PHP SDK.
<?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 the client that initiates image moderation requests. * @param $accessKeyId * @param $accessKeySecret * @param $endpoint * @return Green */ function create_client($accessKeyId, $accessKeySecret, $endpoint): Green { $config = new Config([ "accessKeyId" => $accessKeyId, "accessKeySecret" => $accessKeySecret, // Configure an HTTP proxy. // "httpProxy" => "http://10.10.xx.xx:xxxx", // Configure an HTTPS proxy. // "httpsProxy" => "https://10.10.xx.xx:xxxx", "endpoint" => $endpoint, ]); return new Green($config); } /** * Submit an image moderation task. * @param $accessKeyId * @param $accessKeySecret * @param $endpoint * @return ImageModerationResponse */ function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageModerationResponse { // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation performance. $client = create_client($accessKeyId, $accessKeySecret, $endpoint); // Create a RuntimeObject instance and set runtime parameters. $runtime = new RuntimeOptions([]); // Construct moderation parameters. $request = new ImageModerationRequest(); $serviceParameters = array( // The image to be moderated. Example: image/001.jpg. 'ossObjectName' => 'image/001.jpg', // The region of the bucket where the image to be moderated is located. Example: ap-southeast-1. 'ossRegionId' => 'ap-southeast-1', // The name of the bucket where the image to be moderated is located. Example: bucket001. 'ossBucketName' => 'bucket001', // The unique ID of the data to be moderated. 'dataId' => uniqid()); // Image moderation service: The service code configured for Image Moderation 2.0 in the Content Moderation console. Example: baselineCheck_global. $request->service = "baselineCheck_global"; $request->serviceParameters = json_encode($serviceParameters); // Submit the image moderation task. return $client->imageModerationWithOptions($request, $runtime); } /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * We recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. * Common ways to obtain environment variables: * Obtain the AccessKey ID of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ $accessKeyId = 'We recommend that you obtain the AccessKey ID of your RAM user from environment variables'; $accessKeySecret = 'We recommend that you obtain the AccessKey secret of your RAM user from environment variables'; // Change the region ID and endpoint based on your business requirements. $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
The following three ways of image moderation are supported.
Moderate an image that can be accessed over the Internet
Scenario
If the image to be moderated can be accessed over the Internet, Image Moderation 2.0 can obtain the image from the image URL for moderation.
Install the Go SDK.
go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2
Use the Go SDK.
package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green20220302 "github.com/alibabacloud-go/green-20220302/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "github.com/google/uuid" "net/http" "os" ) // Create the client that initiates image moderation requests. func createClient(accessKeyId *string, accessKeySecret *string, endpoint *string) (*green20220302.Client, error) { config := &openapi.Config{ AccessKeyId: accessKeyId, AccessKeySecret: accessKeySecret, // Configure an HTTP proxy. // HttpProxy: tea.String("http://10.10.xx.xx:xxxx"), // Configure an HTTPS proxy. // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"), Endpoint: endpoint, } // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation performance. return green20220302.NewClient(config); } func invoke(accessKeyId *string, accessKeySecret *string, endpoint *string) (_result *green20220302.ImageModerationResponse, _err error) { // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation performance. client, _err := createClient(accessKeyId, accessKeySecret, endpoint) if _err != nil { return nil,_err } // Create a RuntimeOptions instance and specify runtime parameters. The settings take effect only on the requests that use the RuntimeOptions instance. runtime := &util.RuntimeOptions{} // Construct an image moderation request. serviceParameters, _ := json.Marshal( map[string]interface{}{ // The URL of the image to be moderated, which is accessible over the Internet. "imageUrl": "https://img.alicdn.com/tfs/xxxxxxxxxx001.png", // The ID of the data to be moderated. "dataId":uuid.New(), }, ) imageModerationRequest := &green20220302.ImageModerationRequest{ // Image moderation service: The service code configured for Image Moderation 2.0 in the Content Moderation console. Example: baselineCheck_global. Service: tea.String("baselineCheck_global"), ServiceParameters: tea.String(string(serviceParameters)), } return client.ImageModerationWithOptions(imageModerationRequest, runtime) } func main() { /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * We recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. * Common ways to obtain environment variables: * Obtain the AccessKey ID of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") * Obtain the AccessKey secret of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ var accessKeyId= tea.String("We recommend that you obtain the AccessKey ID of your RAM user from environment variables"); var accessKeySecret= tea.String("We recommend that you obtain the AccessKey secret of your RAM user from environment variables"); // Change the region ID and endpoint based on your business requirements. 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) } } }
Moderate a local image
Scenario
If the image that you want to moderate is stored on your local computer and cannot be accessed over the Internet, you can upload the image to an OSS bucket provided by the Content Moderation service. Image Moderation 2.0 can obtain the image from the OSS bucket for moderation.
Install the Go SDK.
Install the SDK for Content Moderation:
go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2
Install the OSS SDK:
go get github.com/aliyun/aliyun-oss-go-sdk/oss
Use the Go SDK.
package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green20220302 "github.com/alibabacloud-go/green-20220302/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "github.com/aliyun/aliyun-oss-go-sdk/oss" "github.com/google/uuid" "net/http" "os" "strings" "time" ) // Obtain a temporary token for uploading the file. var TokenMap =make(map[string]*green20220302.DescribeUploadTokenResponseBodyData) // The client that uploads the file. var Bucket *oss.Bucket // Specifies whether the service is deployed in a VPC. var isVPC = false // Create the client that initiates image moderation requests. func createClient(accessKeyId string, accessKeySecret string, endpoint string) (*green20220302.Client, error) { config := &openapi.Config{ AccessKeyId: tea.String(accessKeyId), AccessKeySecret: tea.String(accessKeySecret), // Configure an HTTP proxy. // HttpProxy: tea.String("http://10.10.xx.xx:xxxx"), // Configure an HTTPS proxy. // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"), Endpoint: tea.String(endpoint), } // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation performance. return green20220302.NewClient(config); } // Create the client for uploading the file. 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 the 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: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation performance. client, _err := createClient(accessKeyId, accessKeySecret, endpoint) if _err != nil { return nil,_err } // Create a RuntimeOptions instance and specify runtime parameters. The settings take effect only on the requests that use the RuntimeOptions instance. runtime := &util.RuntimeOptions{} // The full path of the local file. Example: D:\localPath\exampleFile.png. var filePath = "D:\\localPath\\exampleFile.png" // Obtain a temporary token for uploading the file. tokenData,ok:=TokenMap[endpoint]; if !ok || tea.Int32Value(tokenData.Expiration) <= int32(time.Now().Unix()) { // Obtain a temporary token for uploading the file. 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 moderation 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 service code configured for Image Moderation 2.0 in the Content Moderation console. Example: baselineCheck_global. Service: tea.String("baselineCheck_global"), ServiceParameters: tea.String(string(serviceParameters)), } return client.ImageModerationWithOptions(imageModerationRequest, runtime) } func main() { /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * We recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. * Common ways to obtain environment variables: * Obtain the AccessKey ID of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") * Obtain the AccessKey secret of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ var accessKeyId= tea.String("We recommend that you obtain the AccessKey ID of your RAM user from environment variables"); var accessKeySecret= tea.String("We recommend that you obtain the AccessKey secret of your RAM user from environment variables"); // Change the region ID and endpoint based on your business requirements. 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) } } }
Moderate an image stored in OSS
Scenario
If the image that you want to moderate is stored in an Alibaba Cloud OSS bucket, you can grant the permissions to create an SLR to allow the Content Moderation service to access the OSS bucket. Image Moderation 2.0 uses the SLR to obtain the image from the OSS bucket for moderation. Go to the Cloud Resource Access Authorization page to create an SLR.
Use your Alibaba Cloud account to access 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/v2
Use the Go SDK.
package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green20220302 "github.com/alibabacloud-go/green-20220302/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "github.com/google/uuid" "net/http" "os" ) // Create the client that initiates image moderation requests. func createClient(accessKeyId *string, accessKeySecret *string, endpoint *string) (*green20220302.Client, error) { config := &openapi.Config{ AccessKeyId: accessKeyId, AccessKeySecret: accessKeySecret, // Configure an HTTP proxy. // HttpProxy: tea.String("http://10.10.xx.xx:xxxx"), // Configure an HTTPS proxy. // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"), Endpoint: endpoint, } // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation performance. return green20220302.NewClient(config); } func invoke(accessKeyId *string, accessKeySecret *string, endpoint *string) (_result *green20220302.ImageModerationResponse, _err error) { // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation performance. client, _err := createClient(accessKeyId, accessKeySecret, endpoint) if _err != nil { return nil,_err } // Create a RuntimeOptions instance and specify runtime parameters. The settings take effect only on the requests that use the RuntimeOptions instance. runtime := &util.RuntimeOptions{} // Construct an image moderation request. serviceParameters, _ := json.Marshal( map[string]interface{}{ // The region where the OSS bucket of the image to be moderated is located. Example: ap-southeast-1. "ossRegionId": "ap-southeast-1", // The name of the OSS bucket where the image to be moderated is stored. Example: bucket001. "ossBucketName":"bucket001", // The name of the object for the image to be moderated. Example: image/001.jpg. "ossObjectName":"image//001.jpg", // The ID of the data to be moderated. "dataId": uuid.New().String(), }, ) imageModerationRequest := &green20220302.ImageModerationRequest{ // Image moderation service: The service code configured for Image Moderation 2.0 in the Content Moderation console. Example: baselineCheck_global. Service: tea.String("baselineCheck_global"), ServiceParameters: tea.String(string(serviceParameters)), } return client.ImageModerationWithOptions(imageModerationRequest, runtime) } func main() { /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * We recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. * Common ways to obtain environment variables: * Obtain the AccessKey ID of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID") * Obtain the AccessKey secret of your RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ // Change the region ID and endpoint based on your business requirements. 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
For more information about the source code, see SDK source code for Node.js.
The following three ways of image moderation are supported.
Moderate an image that can be accessed over the Internet
Scenario
If the image to be moderated can be accessed over the Internet, Image Moderation 2.0 can obtain the image from the image URL for moderation.
Install the Node.js SDK.
Run the following command to install the related dependencies.
npm install @alicloud/green20220302@2.2.10
Use the Node.js SDK.
const RPCClient = require("@alicloud/pop-core"); const { v4: uuidv4 } = require('uuid'); async function main() { // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation performance. var client = new RPCClient({ /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * We recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. * Common ways to obtain environment variables: * Obtain the AccessKey ID of your RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'] * Obtain the AccessKey secret of your RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] */ accessKeyId: 'We recommend that you obtain the AccessKey ID of your RAM user from environment variables', accessKeySecret: 'We recommend that you obtain the AccessKey secret of your RAM user from environment variables', // Change the region ID and endpoint based on your business requirements. endpoint: "https://green-cip.ap-southeast-1.aliyuncs.com", apiVersion: '2022-03-02', // Configure an HTTP proxy. // httpProxy: "http://xx.xx.xx.xx:xxxx", // Configure an HTTPS proxy. // httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999", }); // Use the following code to create an API request and configure the parameters: var params = { // Image moderation service: The service code configured for Image Moderation 2.0 in the Content Moderation console. Example: baselineCheck_global. "Service": "baselineCheck_global", "ServiceParameters": JSON.stringify({ // The unique ID of the data. "dataId": uuidv4(), // The URL of the image to be moderated, which can be accessed over the Internet. "imageUrl": "https://img.alicdn.com/tfs/xxxxxxxxxx001.png" }) } var requestOption = { method: 'POST', formatParams: false, }; try { // Call the operation to obtain the moderation 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)) });
Moderate a local image
Scenario
If the image that you want to moderate is stored on your local computer and cannot be accessed over the Internet, you can upload the image to an OSS bucket provided by the Content Moderation service. Image Moderation 2.0 can obtain the image from the OSS bucket for moderation.
Install the Node.js SDK.
Install the SDK for Content Moderation:
npm install @alicloud/green20220302@2.2.10
Install the OSS dependency:
npm install ali-oss --save
Use the Node.js SDK.
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; // Obtain a temporary token for uploading the file. var tokenDic = new Array(); // The client that uploads the file. var ossClient; // Create the client that uploads the file. function createClient(accessKeyId, accessKeySecret, endpoint) { return new RPCClient({ accessKeyId: accessKeyId, accessKeySecret: accessKeySecret, endpoint: endpoint, apiVersion: '2022-03-02', // Configure an HTTP proxy. //httpProxy: "http://xx.xx.xx.xx:xxxx", // Configure an HTTPS proxy. //httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999", }); } // Create the client that uploads the file. 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: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation performance. var client = createClient(accessKeyId, accessKeySecret, endpoint); var requestOption = { method: 'POST', formatParams: false, }; // The full path of the local file. Example: D:\localPath\exampleFile.png. var filePath = 'D:\\localPath\\exampleFile.png'; // Obtain a temporary token for uploading a file. if (tokenDic[endpoint] == null || tokenDic[endpoint]['Expiration'] <= Date.parse(new Date() / 1000)) { var tokenResponse = await client.request('DescribeUploadToken', '', requestOption) tokenDic[endpoint] = tokenResponse.Data; } // Obtain the client for uploading the file. 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 a file. const result = await ossClient.put(objectName, path.normalize(filePath)); // Use the following code to create an API request and configure the parameters. var params = { // Image moderation service: The service code configured for Image Moderation 2.0 in the Content Moderation console. Example: baselineCheck_global. "Service": "baselineCheck_global", // Information about uploading the local image. "ServiceParameters": JSON.stringify({ "ossBucketName": tokenDic[endpoint].BucketName, "ossObjectName": objectName }) } // Call the operation to obtain the moderation results. return await client.request('ImageModeration', params, requestOption); } function main() { /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * We recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. * Common ways to obtain environment variables: * Obtain the AccessKey ID of your RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'] * Obtain the AccessKey secret of your RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] */ const accessKeyId: 'We recommend that you obtain the AccessKey ID of your RAM user from environment variables' const accessKeySecret: 'We recommend that you obtain the AccessKey secret of your RAM user from environment variables' // Change the region ID and endpoint based on your business requirements. var endpoint = "https://green-cip.ap-southeast-1.aliyuncs.com" try { // Call the operation to obtain the moderation results. invoke(accessKeyId, accessKeySecret, endpoint).then(function (response) { console.log(JSON.stringify(response)) }) } catch (err) { console.log(err); } } main();
Moderate an image stored in OSS
Scenario
If the image that you want to moderate is stored in an Alibaba Cloud OSS bucket, you can grant the permissions to create an SLR to allow the Content Moderation service to access the OSS bucket. Image Moderation 2.0 uses the SLR to obtain the image from the OSS bucket for moderation. Go to the Cloud Resource Access Authorization page to create an SLR.
Use your Alibaba Cloud account to access the Cloud Resource Access Authorization page to grant permissions.
Install the Node.js SDK.
npm install @alicloud/green20220302@2.2.10
Use the Node.js SDK.
const RPCClient = require("@alicloud/pop-core"); const { v4: uuidv4 } = require('uuid'); async function main() { // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation performance. var client = new RPCClient({ /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * We recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. * Common ways to obtain environment variables: * Obtain the AccessKey ID of your RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'] * Obtain the AccessKey secret of your RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] */ accessKeyId: 'We recommend that you obtain the AccessKey ID of your RAM user from environment variables', accessKeySecret: 'We recommend that you obtain the AccessKey secret of your RAM user from environment variables', // Change the region ID and endpoint based on your business requirements. endpoint: "https://green-cip.ap-southeast-1.aliyuncs.com", apiVersion: '2022-03-02', // Configure an HTTP proxy. // httpProxy: "http://xx.xx.xx.xx:xxxx", // Configure an HTTPS proxy. // httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999", }); // Use the following code to create an API request and configure the parameters: var params = { // Image moderation service: The service code configured for Image Moderation 2.0 in the Content Moderation console. Example: baselineCheck_global. "Service": "baselineCheck_global", // The OSS information about the image to be moderated. "ServiceParameters": JSON.stringify({ // The region of the bucket where the image to be moderated is located. Example: ap-southeast-1. "ossRegionId": "ap-southeast-1", // The name of the bucket where the image to be moderated is located. Example: bucket001. "ossBucketName": "bucket001", // The image to be moderated. Example: image/001.jpg. "ossObjectName": "image/001.jpg", // The unique ID of the data. "dataId": uuidv4() }) } var requestOption = { method: 'POST', formatParams: false, }; try { // Call the operation to obtain the moderation 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
For more information about the source code, see SDK source code for C#.
The following three ways of image moderation are supported.
Moderate an image that can be accessed over the Internet
Scenario
If the image to be moderated can be accessed over the Internet, Image Moderation 2.0 can obtain the image from the image URL for moderation.
Install the C# SDK.
dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10
Use the C# SDK.
// 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) { /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * We recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. * Common ways to obtain environment variables: * Obtain the AccessKey ID of your RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * Obtain the AccessKey secret of your RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ String accessKeyId = "We recommend that you obtain the AccessKey ID of your RAM user from environment variables"; String accessKeySecret = "We recommend that you obtain the AccessKey secret of your RAM user from environment variables"; // Change the region ID and endpoint based on your business requirements. String endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation performance. Client client = createClient(accessKeyId, accessKeySecret, endpoint); // Create a RuntimeOptions instance and specify runtime parameters. The settings take effect only on the requests that use the RuntimeOptions instance. AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); // Construct an image moderation request. Models.ImageModerationRequest imageModerationRequest = new Models.ImageModerationRequest(); // Image moderation service: The service code configured for Image Moderation 2.0 in the Content Moderation console. Example: baselineCheck_global. imageModerationRequest.Service = "baselineCheck_global"; Dictionary<string, object> task = new Dictionary<string, object>(); // The URL of the image to be moderated, which is accessible over the Internet. task.Add( "imageUrl", "https://img.alicdn.com/tfs/xxxxxxxxxx001.png" ); // The ID of the data to be moderated. task.Add("dataId", Guid.NewGuid().ToString()); imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task); try { // Call the operation to obtain the moderation 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 the client that initiates image moderation requests. public static Client createClient( String accessKeyId, String accessKeySecret, String endpoint ) { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, // Configure an HTTP proxy. //HttpProxy = "http://10.10.xx.xx:xxxx", // Configure an HTTPS proxy. //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999", // The endpoint of the service. Endpoint = endpoint, }; return new Client(config); } } }
Moderate a local image
Scenario
If the image that you want to moderate is stored on your local computer and cannot be accessed over the Internet, you can upload the image to an OSS bucket provided by the Content Moderation service. Image Moderation 2.0 can obtain the image from the OSS bucket for moderation.
Install the C# SDK.
Install the SDK for Content Moderation:
dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10
Install the OSS SDK:
dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.8 Install the SDK by using NuGet 1. If NuGet is not installed for your Visual Studio, you must first install NuGet. 2. After you install NuGet, create a project or open an existing project in Visual Studio. Then, choose Tools > NuGet Package Manager > Manage NuGet Packages for Solution. 3. Enter aliyun.oss.sdk in the search box and click Search. Find Aliyun.OSS.SDK (applicable to .NET Framework) or Aliyun.OSS.SDK.NetCore (applicable to .Net Core) in the search results. Select the latest version and click Install.
Use the C# SDK.
// 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 { // Obtain a temporary token for uploading the file. public static Dictionary<String, Models.DescribeUploadTokenResponse> tokenDic = new Dictionary<String, Models.DescribeUploadTokenResponse>(); // The client that uploads the file. 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) { /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * We recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. * Common ways to obtain environment variables: * Obtain the AccessKey ID of your RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * Obtain the AccessKey secret of your RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ String accessKeyId = "We recommend that you obtain the AccessKey ID of your RAM user from environment variables"; String accessKeySecret = "We recommend that you obtain the AccessKey secret of your RAM user from environment variables"; // Change the region ID and endpoint based on your business requirements. 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 the client that initiates image moderation requests. public static Client createClient( String accessKeyId, String accessKeySecret, String endpoint ) { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, // Configure an HTTP proxy. //HttpProxy = "http://10.10.xx.xx:xxxx", // Configure an HTTPS proxy. //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999", // The endpoint of the service. Endpoint = endpoint, }; return new Client(config); } // Create the client that uploads the file. 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 the file. public static String uploadFile( String filePath, Models.DescribeUploadTokenResponse tokenResponse ) { // Create 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 the image moderation request. public static Models.ImageModerationResponse invoke( String accessKeyId, String accessKeySecret, String endpoint ) { // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation performance. Client client = createClient(accessKeyId, accessKeySecret, endpoint); // Create a RuntimeOptions instance and specify runtime parameters. The settings take effect only on the requests that use the RuntimeOptions instance. AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); // The full path of the local file. Example: D:\localPath\exampleFile.png. String filePath = "D:\localPath\exampleFile.png."; try { // Obtain a temporary token for uploading the file. 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 moderation request. Models.ImageModerationRequest imageModerationRequest = new Models.ImageModerationRequest(); // Image moderation service: The service code configured for Image Moderation 2.0 in the Content Moderation console. Example: baselineCheck_global. imageModerationRequest.Service = "baselineCheck_global"; Dictionary<string, object> task = new Dictionary<string, object>(); // The information about the image to be moderated. task.Add("ossBucketName", tokenDic[endpoint].Body.Data.BucketName); task.Add("ossObjectName", objectName); // The ID of the data to be moderated. task.Add("dataId", Guid.NewGuid().ToString()); imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task); // Call the operation to obtain the moderation results. Models.ImageModerationResponse response = client.ImageModerationWithOptions( imageModerationRequest, runtimeOptions ); return response; } catch (Exception _err) { Console.WriteLine(_err); return null; } } } }
Moderate an image stored in OSS
Scenario
If the image that you want to moderate is stored in an Alibaba Cloud OSS bucket, you can grant the permissions to create an SLR to allow the Content Moderation service to access the OSS bucket. Image Moderation 2.0 uses the SLR to obtain the image from the OSS bucket for moderation. Go to the Cloud Resource Access Authorization page to create an SLR.
Use your Alibaba Cloud account to access the Cloud Resource Access Authorization page to grant permissions.
Install the C# SDK.
dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10
Use the C# SDK.
// 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) { /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To avoid security risks, we recommend that you use a RAM user to call API operations or perform routine O&M. * We recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of resources within your account may be compromised. * Common ways to obtain environment variables: * Obtain the AccessKey ID of your RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * Obtain the AccessKey secret of your RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ String accessKeyId = "We recommend that you obtain the AccessKey ID of your RAM user from environment variables"; String accessKeySecret = "We recommend that you obtain the AccessKey secret of your RAM user from environment variables"; // Change the region ID and endpoint based on your business requirements. String endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve the moderation performance. Client client = createClient(accessKeyId, accessKeySecret, endpoint); // Create a RuntimeOptions instance and specify runtime parameters. The settings take effect only on the requests that use the RuntimeOptions instance. AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); // Construct an image moderation request. Models.ImageModerationRequest imageModerationRequest = new Models.ImageModerationRequest(); // Image moderation service: The service code configured for Image Moderation 2.0 in the Content Moderation console. Example: baselineCheck_global. imageModerationRequest.Service = "baselineCheck_global"; Dictionary<string, object> task = new Dictionary<string, object>(); // The region where the OSS bucket of the image to be moderated is located. Example: ap-southeast-1. task.Add("ossRegionId", "ap-southeast-1"); // The name of the OSS bucket where the image to be moderated is stored. Example: bucket001. task.Add("ossBucketName", "bucket001"); // The name of the object for the image to be moderated. Example: image/001.jpg. task.Add("ossObjectName", "image/001.jpg"); // The ID of the data to be moderated. task.Add("dataId", Guid.NewGuid().ToString()); imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task); try { // Call the operation to obtain the moderation 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 the client that initiates image moderation requests. public static Client createClient( String accessKeyId, String accessKeySecret, String endpoint ) { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, // Configure an HTTP proxy. //HttpProxy = "http://10.10.xx.xx:xxxx", // Configure an HTTPS proxy. //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999", // The endpoint of the service. Endpoint = endpoint, }; return new Client(config); } } }
Make HTTPS calls
You can also call the Image Moderation 2.0 API by using HTTPS. To use HTTPS, you must encapsulate the protocol, add and verify a signature, and assemble the URL, body, header, and parameters into a request. Generally, you must use HTTPS to call Image Moderation 2.0 API operations only in the following two scenarios. In other scenarios, we recommend that you use Content Moderation SDKs to call Image Moderation 2.0 API operations.
Your services are directly provided in applications and have high requirements for the client size.
Your services are dependent on specific libraries and are difficult to update.
Call method
Service endpoint: https://green-cip.{region}.aliyuncs.com
Protocol: HTTP
Method: POST
Common request parameters
The input parameters of the Image Moderation 2.0 API include common request parameters and operation-specific request parameters. Common request parameters are used by each API operation. The following table describes the common request parameters.
Parameter
Type
Required
Description
Format
String
Yes
The response format. Valid values:
JSON (default)
XML
Version
String
Yes
The version number of the API. The value is in the YYYY-MM-DD format. Set the value to 2022-03-02.
AccessKeyId
String
Yes
The AccessKey ID that is provided to you by Alibaba Cloud.
Signature
String
Yes
The signature string of the current request. For more information about how signatures are calculated, see the following signature method.
SignatureMethod
String
Yes
The signature method. Set the value to HMAC-SHA1.
Timestamp
String
Yes
The timestamp of the request. Specify the time in the ISO 8601 standard in the yyyy-MM-ddTHH:mm:ssZ format. The time must be in Coordinated Universal Time (UTC). For example, 09:13:14 on December 12, 2022 (UTC+8) is written as 2022-12-12T01:13:14Z.
SignatureVersion
String
Yes
The version of the signature algorithm. Set the value to 1.0.
SignatureNonce
String
Yes
A unique random number that is used to prevent replay attacks. You must use different numbers for different requests.
Action
String
Yes
Set the value to ImageModeration.
Common response parameters
The system returns a unique RequestId for every response regardless of whether the call is successful. Other response parameters include label and confidence. The confidence parameter specifies a confidence score. The response parameters vary with services. For more information, see the documentation of a specific service.
Sample code
The following sample responses are formatted to improve readability. Actual responses are not formatted with line breaks or indentation.
The following is a sample request for the common baseline moderation service of Image Moderation 2.0:
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 &ServiceParameters={"imageUrl": "https://img.alicdn.com/tfs/TB1U4r9AeH2gK0jSZJnXXaT1FXa-2880-480.png", "dataId": "img1234567"}
The following provides a sample JSON code that is returned by the common baseline moderation service of Image Moderation 2.0:
{ "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 2.0 service authenticates each access request. Therefore, each request must contain signature information. Image Moderation 2.0 implements symmetric encryption with an AccessKey pair to authenticate the request sender.
An AccessKey pair is officially issued by Alibaba Cloud. You can apply for and manage it at Alibaba Cloud official website. An AccessKey pair consists of an AccessKey ID and an AccessKey secret. The AccessKey ID is used to verify the identity of the user, and the AccessKey secret is used to encrypt and verify the signature string. You must keep your AccessKey secret strictly confidential.
To sign a request, perform the following steps:
Create a canonicalized query string by using request parameters.
Sort request parameters in alphabetical order of parameter names. These parameters include the common request parameters and the operation-specific parameters. However, the Signature parameter among common request parameters is not included.
Encode the names and values of the relevant request parameters. Parameter names and values must be URL-encoded by using the UTF-8 character set.
NoteMost libraries that support URL encoding, such as java.net.URLEncoder, comply with the Multipurpose Internet Mail Extensions (MIME) encoding rules of application/x-www-form-urlencoded. If this encoding method is used, replace the plus signs (+) in the encoded strings with %20, the asterisks (*) with %2A, and %7E with a tilde (~). This way, you can obtain an encoded string that is created based on the preceding encoding rules.
Take note of the following encoding rules:
Uppercase letters, lowercase letters, digits, and some special characters such as hyphens (-), underscores (_), periods (.), and tildes (~) do not need to be encoded.
Other characters must be encoded in the
%XY
format, where XY represents the ASCII code of the characters in hexadecimal notation. For example, double quotation marks (") are encoded as%22
.Extended UTF-8 characters must be encoded in the
%XY%ZA...
format.Spaces must be encoded as
%20
. Do not encode spaces as plus signs (+).
Connect the encoded parameter names and values by using equal signs (=).
Sort the equal sign-connected strings by their parameter names in alphabetical order and connect them by using ampersands (&) to obtain the canonicalized query string.
Use the canonicalized query string that was created in Step a.i to create a string to sign based on the following rules:
StringToSign= HTTPMethod + "&" + percentEncode("/") + "&" + percentEncode(CanonicalizedQueryString)
NoteHTTPMethod indicates the HTTP method used to make the request, such as POST. percentEncode("/") encodes forward slashes (/) based on the URL encoding rules described in Step a.ii. The encoded value of a forward slash (/) is
%2F
. percentEncode(CanonicalizedQueryString) specifies the encoded string of the canonicalized query string constructed in Step a.i. The encoded string is obtained by following the URL encoding rules described in Step a.ii.Calculate the hash-based message authentication code (HMAC) value of the string to sign based on the HMAC algorithm that is described in RFC 2104.
NoteUse the Secure Hash Algorithm 1 (SHA1) algorithm to calculate the HMAC value of the string to sign. The AccessKey secret appended by an ampersand (
&
) (ASCII:38) is used as the key for HMAC calculation.Encode the HMAC value in Base64 to obtain the signature string.
Add the signature string to the request as the Signature parameter. This way, the API request is signed.
NoteWhen the signature string is submitted to the Content Moderation service as the final request parameter value, the value must be URL-encoded similar to other parameters based on the rules defined in RFC 3986.