This topic shows you how to use SDKs for Python to moderate images for risky content.

Background information

Content Moderation SDK for Python supports both synchronous and asynchronous image moderation.

  • If you use synchronous image moderation, the moderation results are returned in real time.
  • If you use asynchronous image moderation, you must poll the moderation results or configure a callback notification to receive the moderation results.

You can submit the URL of an online image, the URL of an on-premises image, or a binary image stream for image moderation.

Before you begin

Before you call operations, make the following preparations:

Recommended: Submit synchronous image moderation tasks.

Operation Description Supported region
ImageSyncScanRequest Sends synchronous requests to moderate images for risky content in multiple moderation scenarios, including pornography, terrorist content, ad, QR code, undesirable scene, and logo detection.
  • cn-shanghai: China (Shanghai)
  • cn-beijing: China (Beijing)
  • cn-shenzhen: China (Shenzhen)
  • ap-southeast-1: Singapore (Singapore)
  • us-west-1: US (Silicon Valley)
Sample code
  • Submit the URL of an online image for image moderation
    #coding=utf-8
    # The following code provides an example on how to call the synchronous image moderation operation and return the moderation result in real time:
    from aliyunsdkcore import client
    from aliyunsdkgreen.request.v20180509 import ImageSyncScanRequest
    from aliyunsdkgreenextension.request.extension import HttpContentHelper
    import json
    import uuid
    
    # Use the AccessKey pair of your Alibaba Cloud account.
    clt = client.AcsClient("yourAccessKeyId", "yourAccessKeySecret","cn-shanghai")
    # The request object cannot be reused. You must create a request object for each request.
    request = ImageSyncScanRequest.ImageSyncScanRequest()
    request.set_accept_format('JSON')
    task = {
        "dataId": str(uuid.uuid1()),
        "url": "https://test1.jpg"
        }
    
    # Create one task for each image to be moderated.
    # If you moderate multiple images in a request, the total response time that the server spends processing the request starts from when the request is initiated to when the last image is moderated.
    # Generally, the average response time of moderating multiple images in a request is longer than that of moderating a single image. The more images you submit at a time, the higher the probability that the average response time will be extended.
    # In this example, a single image is moderated. If you need to moderate multiple images at a time, create one task for each image to be moderated.
    # You can send a request to moderate multiple images at a time and specify multiple moderation scenarios for each image. The expenses of all scenarios are separately calculated and summed up.
    # For example, if you moderate two images for both pornography and terrorist content, you are charged for moderating two images for pornography and two images for terrorist content.
    request.set_content(HttpContentHelper.toValue({"tasks": [task], "scenes": ["porn"]}))
    response = clt.do_action_with_exception(request)
    print(response)
    result = json.loads(response)
    if 200 == result["code"]:
        taskResults = result["data"]
        for taskResult in taskResults:
            if (200 == taskResult["code"]):
                sceneResults = taskResult["results"]
                for sceneResult in sceneResults:
                    scene = sceneResult["scene"]
                    suggestion = sceneResult["suggestion"]
                    # Take a further action based on the values of the scene and suggestion parameters.
                    # Take different actions on the image based on the different values of the suggestion parameter. For example, delete the illegal data.
                    print(suggestion)
                    print(scene)
  • Submit the URL of an on-premises image for image moderation
    # coding=utf-8
    # The following code provides an example on how to call the synchronous image moderation operation and return the moderation result in real time:
    from aliyunsdkcore import client
    from aliyunsdkgreen.request.v20180509 import ImageSyncScanRequest
    from aliyunsdkgreenextension.request.extension import ClientUploader
    from aliyunsdkgreenextension.request.extension import HttpContentHelper
    import json
    import uuid
    import sys
    
    # Set the default encoding to UTF-8 to support a path containing Chinese characters for on-premises files.
    # Add the following code to the Python 2 environment but not to the Python 3 environment:
    if sys.version_info[0] == 2:
        reload(sys)
        sys.setdefaultencoding('utf-8')
    
    # Use the AccessKey pair of your Alibaba Cloud account.
    clt = client.AcsClient("yourAccessKeyId", "yourAccessKeySecret", "cn-shanghai")
    # The request object cannot be reused. You must create a request object for each request.
    request = ImageSyncScanRequest.ImageSyncScanRequest()
    request.set_accept_format('JSON')
    
    # Use the path of your on-premises file.
    # Upload the on-premises image to the server.
    uploader = ClientUploader.getImageClientUploader(clt)
    url = uploader.uploadFile('d:/test/test.jpg')
    
    # Obtain the uploaded URL for moderation.
    task = {"dataId": str(uuid.uuid1()),
             "url":url
            }
    
    # Create one task for each image to be moderated.
    # If you moderate multiple images in a request, the total response time that the server spends processing the request starts from when the request is initiated to when the last image is moderated.
    # Generally, the average response time of moderating multiple images in a request is longer than that of moderating a single image. The more images you submit at a time, the higher the probability that the average response time will be extended.
    # In this example, a single image is moderated. If you need to moderate multiple images at a time, create one task for each image to be moderated.
    # You can send a request to moderate multiple images at a time and specify multiple moderation scenarios for each image. The expenses of all scenarios are separately calculated and summed up.
    # For example, if you moderate two images for both pornography and terrorist content, you are charged for moderating two images for pornography and two images for terrorist content.
    request.set_content(HttpContentHelper.toValue({"tasks": [task], "scenes": ["porn"]}))
    response = clt.do_action_with_exception(request)
    print(response)
    result = json.loads(response)
    if 200 == result["code"]:
        taskResults = result["data"]
        for taskResult in taskResults:
            if (200 == taskResult["code"]):
                sceneResults = taskResult["results"]
                for sceneResult in sceneResults:
                    # Take a further action based on the values of the scene and suggestion parameters.
                    # Take different actions on the image based on the different values of the suggestion parameter. For example, delete the illegal data.
                    scene = sceneResult["scene"]
                    suggestion = sceneResult["suggestion"]
  • Submit a binary image stream for image moderation
    # coding=utf-8
    # The following code provides an example on how to call the synchronous image moderation operation and return the moderation result in real time:
    from aliyunsdkcore import client
    from aliyunsdkgreen.request.v20180509 import ImageSyncScanRequest
    from aliyunsdkgreenextension.request.extension import ClientUploader
    from aliyunsdkgreenextension.request.extension import HttpContentHelper
    import json
    import uuid
    import sys
    
    # Set the default encoding to UTF-8 to support a path containing Chinese characters for on-premises files.
    # Add the following code to the Python 2 environment but not to the Python 3 environment:
    if sys.version_info[0] == 2:
        reload(sys)
        sys.setdefaultencoding('utf-8')
    
    # Use the AccessKey pair of your Alibaba Cloud account.
    clt = client.AcsClient("yourAccessKeyId", "yourAccessKeySecret","cn-shanghai")
    # The request object cannot be reused. You must create a request object for each request.
    request = ImageSyncScanRequest.ImageSyncScanRequest()
    request.set_accept_format('JSON')
    
    # Read and convert an on-premises file to binary data and submit the binary data for moderation.
    # Use the path of your on-premises image.
    f = open('d:/test/test.jpg',"rb+")
    imageBytes = f.read()
    f.close()
    
    # Upload the binary byte array to the server.
    uploader = ClientUploader.getImageClientUploader(clt)
    url = uploader.uploadBytes(imageBytes)
    
    # Obtain the uploaded URL for moderation.
    task = {
        "dataId": str(uuid.uuid1()),
        "url":url
    }
    
    # Create one task for each image to be moderated.
    # If you moderate multiple images in a request, the total response time that the server spends processing the request starts from when the request is initiated to when the last image is moderated.
    # Generally, the average response time of moderating multiple images in a request is longer than that of moderating a single image. The more images you submit at a time, the higher the probability that the average response time will be extended.
    # In this example, a single image is moderated. If you need to moderate multiple images at a time, create one task for each image to be moderated.
    # You can send a request to moderate multiple images at a time and specify multiple moderation scenarios for each image. The expenses of all scenarios are separately calculated and summed up.
    # For example, if you moderate two images for both pornography and terrorist content, you are charged for moderating two images for pornography and two images for terrorist content.
    request.set_content(HttpContentHelper.toValue({"tasks": [task], "scenes": ["porn"]}))
    response = clt.do_action_with_exception(request)
    print(response)
    result = json.loads(response)
    if 200 == result["code"]:
        taskResults = result["data"]
        for taskResult in taskResults:
            if (200 == taskResult["code"]):
                sceneResults = taskResult["results"]
                for sceneResult in sceneResults:
                    # Take a further action based on the values of the scene and suggestion parameters.
                    # Take different actions on the image based on the different values of the suggestion parameter. For example, delete the illegal data.
                    scene = sceneResult["scene"]
                    suggestion = sceneResult["suggestion"]

Submit asynchronous image moderation tasks

The following section shows you how to use the ImageAsyncScanRequest operation of SDKs for Python to moderate images for risky content. You can send an asynchronous request to submit an image moderation task. When you submit the request, you can specify the callback URL to receive moderation results by setting the callback parameter. Alternatively, you can call the ImageAsyncScanResultsRequest operation to poll the moderation results after Content Moderation processes the image moderation tasks.

Same as synchronous image moderation, you can submit the URL of an online image, the URL of an on-premises image, or a binary image stream for asynchronous image moderation. In this example, the URL of an online image is used.

Operation Description Supported region
ImageAsyncScanRequest Sends asynchronous requests to moderate images for risky content in multiple moderation scenarios, including pornography, terrorist content, ad, QR code, undesirable scene, and logo detection.
Note You can call the ImageAsyncScanResultsRequest operation to poll the moderation results.
  • cn-shanghai: China (Shanghai)
  • cn-beijing: China (Beijing)
  • cn-shenzhen: China (Shenzhen)
  • ap-southeast-1: Singapore (Singapore)
  • us-west-1: US (Silicon Valley)
Sample code
# coding=utf-8
# The following code provides an example on how to call the asynchronous image moderation operation. You must query the moderation result based on the task ID returned by the operation:
from aliyunsdkcore import client
from aliyunsdkcore.profile import region_provider
from aliyunsdkgreen.request.v20180509 import ImageAsyncScanRequest
from aliyunsdkgreenextension.request.extension import HttpContentHelper
import json
import uuid

# Use the AccessKey pair of your Alibaba Cloud account.
clt = client.AcsClient("yourAccessKeyId", "yourAccessKeySecret","cn-shanghai")
region_provider.modify_point('Green', 'cn-shanghai', 'green.cn-shanghai.aliyuncs.com')
# The request object cannot be reused. You must create a request object for each request.
request = ImageAsyncScanRequest.ImageAsyncScanRequest()
request.set_accept_format('JSON')


task1 = {
    "dataId": str(uuid.uuid1()),
    "url":"http://xxx.jpg"
}
# Create one task for each image to be moderated.
# If you moderate multiple images in a request, the total response time that the server spends processing the request starts from when the request is initiated to when the last image is moderated.
# Generally, the average response time of moderating multiple images in a request is longer than that of moderating a single image. The more images you submit at a time, the higher the probability that the average response time will be extended.
# In this example, a single image is moderated. If you need to moderate multiple images at a time, create one task for each image to be moderated.
# You can send a request to moderate multiple images at a time and specify multiple moderation scenarios for each image. The expenses of all scenarios are separately calculated and summed up.
# For example, if you moderate two images for both pornography and terrorist content, you are charged for moderating two images for pornography and two images for terrorist content.
request.set_content(HttpContentHelper.toValue({"tasks": [task1], "scenes": ["porn"]}))
response = clt.do_action_with_exception(request)
print(response)
result = json.loads(response)
if 200 == result["code"]:
    taskResults = result["data"]
    for taskResult in taskResults:
        if(200 == taskResult["code"]):
           taskId = taskResult["taskId"]
           // Save the task ID, which is used to poll the moderation results.
           print(taskId)

Query the results of asynchronous image moderation

Operation Description Supported region
ImageAsyncScanResultsRequest Queries asynchronous image moderation results. You can query the moderation results of multiple asynchronous image moderation tasks at a time.
  • cn-shanghai: China (Shanghai)
  • cn-beijing: China (Beijing)
  • cn-shenzhen: China (Shenzhen)
  • ap-southeast-1: Singapore (Singapore)
  • us-west-1: US (Silicon Valley)
Sample code
# coding=utf-8
from aliyunsdkcore import client
from aliyunsdkcore.profile import region_provider
from aliyunsdkgreen.request.v20180509 import ImageAsyncScanResultsRequest
from aliyunsdkgreenextension.request.extension import HttpContentHelper
import json 

# Use the AccessKey pair of your Alibaba Cloud account.
clt = client.AcsClient("yourAccessKeyId", "yourAccessKeySecret","cn-shanghai")
region_provider.modify_point('Green', 'cn-shanghai', 'green.cn-shanghai.aliyuncs.com')
# The request object cannot be reused. You must create a request object for each request.
request = ImageAsyncScanResultsRequest.ImageAsyncScanResultsRequest()
request.set_accept_format('JSON')

# Query the moderation result based on the task ID.
taskIds = ["img5sO$Zsssss7RYuz4Yyhhe-1q51iZ"]
request.set_content(HttpContentHelper.toValue(taskIds))
response = clt.do_action_with_exception(request)
print(response)
result = json.loads(response)
if 200 == result["code"]:
    taskResults = result["data"]
    for taskResult in taskResults:
        if (200 == taskResult["code"]):
            sceneResults = taskResult["results"]
            for sceneResult in sceneResults:
                # Take a further action based on the values of the scene and suggestion parameters.
                # Take different actions on the image based on the different values of the suggestion parameter. For example, delete the illegal data.
                scene = sceneResult["scene"]
                suggestion = sceneResult["suggestion"]