This topic describes how to use Content Moderation SDK for Python to moderate images for risky content.

Background information

Synchronous image moderation and asynchronous image moderation are supported.

  • If you use synchronous image moderation, the moderation results are returned in real time. For more information about the related parameters, see Synchronous moderation.
  • If you use asynchronous image moderation, you must poll the moderation results or configure a callback notification to receive the moderation results. For more information about parameters, see Asynchronous moderation.

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

Prerequisites

  • Python dependencies are installed. For more information, see Installation.
    Note You must use the required Python version described in the Installation topic to install the dependencies. Otherwise, subsequent operation calls fail.
  • The Extension.Uploader utility class is downloaded and imported into your project if you want to submit a local image or a binary image stream for image moderation.

Submit synchronous image moderation tasks (recommended)

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)
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 ImageSyncScanRequest 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 ID and AccessKey secret of your Alibaba Cloud account. 
    clt = client.AcsClient("Your AccessKey ID", "Your AccessKey secret", "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 a 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 is extended. 
    # In this example, a single image is moderated. If you want to moderate multiple images at a time, create a 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 different values of the suggestion parameter. For example, delete the illegal data. 
                    print(suggestion)
                    print(scene)
  • Submit the URL of a local image for image moderation
    # coding=utf-8
    # The following code provides an example on how to call the ImageSyncScanRequest 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 whose name contains Chinese characters for local images. 
    # 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 ID and AccessKey secret of your Alibaba Cloud account. 
    clt = client.AcsClient("Your AccessKey ID", "Your AccessKey secret", "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 local image. 
    # Upload the local image to the server. 
    uploader = ClientUploader.getImageClientUploader(clt)
    url = uploader.uploadFile('d:/test/test.jpg')
    
    # Obtain the URL of the uploaded image for moderation. 
    task = {"dataId": str(uuid.uuid1()),
             "url":url
            }
    
    # Create a 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 is extended. 
    # In this example, a single image is moderated. If you want to moderate multiple images at a time, create a 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 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 ImageSyncScanRequest 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 whose name contains Chinese characters for local images. 
    # 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 ID and AccessKey secret of your Alibaba Cloud account. 
    clt = client.AcsClient("Your AccessKey ID", "Your AccessKey secret", "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 a local image, convert the data in the local image to binary data, and then submit the binary data for moderation. 
    # Use the path of your local image. 
    f = open('d:/test/test.jpg',"rb+")
    imageBytes = f.read()
    f.close()
    
    # Upload the binary image stream to the server. 
    uploader = ClientUploader.getImageClientUploader(clt)
    url = uploader.uploadBytes(imageBytes)
    
    # Obtain the URL of the uploaded binary image stream for moderation. 
    task = {
        "dataId": str(uuid.uuid1()),
        "url":url
    }
    
    # Create a 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 is extended. 
    # In this example, a single image is moderated. If you want to moderate multiple images at a time, create a 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 different values of the suggestion parameter. For example, delete the illegal data. 
                    scene = sceneResult["scene"]
                    suggestion = sceneResult["suggestion"]

Submit asynchronous image moderation tasks

This section shows you how to use Content Moderation SDK for Python to submit asynchronous image moderation tasks. When you submit a request, you can configure a callback notification to receive the moderation results. Alternatively, you can call the ImageAsyncScanResultsRequest operation to poll the moderation results.

Same as synchronous image moderation, you can submit the URL of an online image, the URL of a local 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.
  • cn-shanghai: China (Shanghai)
  • cn-beijing: China (Beijing)
  • cn-shenzhen: China (Shenzhen)
  • ap-southeast-1: Singapore (Singapore)
Sample code
# coding=utf-8
# The following code provides an example on how to call the ImageAsyncScanRequest 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 ID and AccessKey secret of your Alibaba Cloud account. 
clt = client.AcsClient("Your AccessKey ID", "Your AccessKey secret", "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 a 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 is extended. 
# In this example, a single image is moderated. If you want to moderate multiple images at a time, create a 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 can be 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)
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 ID and AccessKey secret of your Alibaba Cloud account. 
clt = client.AcsClient("Your AccessKey ID", "Your AccessKey secret", "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 different values of the suggestion parameter. For example, delete the illegal data. 
                scene = sceneResult["scene"]
                suggestion = sceneResult["suggestion"]

Provide feedback on moderation results

If the results of image moderation are not as expected, you can call the ImageScanFeedbackRequest operation to modify the results. Content Moderation adds the moderated image to the similar image blacklist or whitelist based on your feedback. When you submit a similar image for moderation, Content Moderation returns moderation results based on the label in your feedback.

For more information, see Give feedback on moderation results.

Operation Description Supported region
ImageScanFeedbackRequest Provides feedback on an image moderation result and modifies the machine-assisted moderation result based on the feedback.
Sample code
# coding=utf-8

from aliyunsdkcore import client
from aliyunsdkcore.profile import region_provider
from aliyunsdkgreen.request.v20180509 import ImageScanFeedbackRequest
import json

# Use the AccessKey ID and AccessKey secret of your Alibaba Cloud account. 
clt = client.AcsClient("Your AccessKey ID", "Your AccessKey secret", "cn-shanghai")
region_provider.modify_point('Green', 'cn-shanghai', 'green.cn-shanghai.aliyuncs.com')
request = ImageScanFeedbackRequest.ImageScanFeedbackRequest()
request.set_accept_format('JSON')
# scenes: the moderation scenarios. You can specify one or more moderation scenarios. 
# suggestion: the moderation result that you expect to return. A value of pass indicates that the moderated image is normal. A value of block indicates that the moderated image contains violations. 
request.set_content(json.dumps({"suggestion": "block", "scenes": ["ad", "terrorism"], "url": "Image URL"}))

try:
    response = clt.do_action_with_exception(request)
    print response
except Exception, err:
    print err.__str__()