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

  • The Python SDK 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 a local image, or a binary image stream for image moderation.

Preparations

Before calling operations, make the following preparations:
  1. Create an AccessKey ID and AccessKey secret of your Alibaba Cloud account. For more information, see Create an AccessKey.
  2. Install Python dependencies. For more information, see Installation.

(Recommended) Submit synchronous image moderation tasks

Operation description

Sample code
  • Submit the URL of an online image for image moderation
    #coding=utf-8
    # The ImageSyncScanRequest operation returns image moderation results 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")
    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.
    # The sample code uses a single image as an example. If you want to moderate multiple images at a time, create one task for each image to be moderated.
    # The system charges you based on the moderation scenario that you specify.
    # 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 calculated separately 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 on the image based on the values of the scene and suggestion parameters.
                    # do something
                    print(suggestion)
                    print(scene)
  • Submit the URL of a local image for image moderation
    #coding=utf-8
    # The ImageSyncScanRequest operation returns image moderation results in real time.
    from aliyunsdkcore import client
    from aliyunsdkgreen.request.v20180509 import ImageSyncScanRequest
    from aliyunsdkgreen.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 local path containing Chinese characters.
    # Add the following code snippet if you use Python 2. If you use Python 3, remove it.
    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")
    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')
    
    # Set the url parameter to the image URL submitted to the server.
    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.
    # The sample code uses a single image as an example. If you want to moderate multiple images at a time, create one task for each image to be moderated.
    # The system charges you based on the moderation scenario that you specify.
    # 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 calculated separately 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 on the image based on the values of the scene and suggestion parameters.
                    # do something
                    scene = sceneResult["scene"]
                    suggestion = sceneResult["suggestion"]
  • Submit a binary image stream for image moderation
    #coding=utf-8
    # The ImageSyncScanRequest operation returns image moderation results in real time.
    from aliyunsdkcore import client
    from aliyunsdkgreen.request.v20180509 import ImageSyncScanRequest
    from aliyunsdkgreen.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 local path containing Chinese characters.
    # Add the following code snippet if you use Python 2. If you use Python 3, remove it.
    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")
    request = ImageSyncScanRequest.ImageSyncScanRequest()
    request.set_accept_format('JSON')
    
    # Simulate binary data for moderation.
    # Read and convert a local image to binary data. Use the path of your local image.
    f = open('d:/test/test.jpg',"rb+")
    imageBytes = f.read()
    f.close()
    
    # Upload the binary stream to the server.
    uploader = ClientUploader.getImageClientUploader(clt)
    url = uploader.uploadBytes(imageBytes)
    
    # Set the url parameter to the image URL submitted to the server.
    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.
    # The sample code uses a single image as an example. If you want to moderate multiple images at a time, create one task for each image to be moderated.
    # The system charges you based on the moderation scenario that you specify.
    # 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 calculated separately 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 on the image based on the values of the scene and suggestion parameters.
                    # do something
                    scene = sceneResult["scene"]
                    suggestion = sceneResult["suggestion"]

Submit asynchronous image moderation tasks

The following section describes how to use the ImageAsyncScanRequest operation of the Python SDK to moderate images for risky content. You can send an asynchronous request to submit an image moderation task. When submitting the request, you can configure a callback notification to receive the moderation results. Alternatively, you can call the ImageAsyncScanResultsRequest operation to poll the moderation results.

As with 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. The following sample code uses the URL of an online image as an example.

Sample code
# coding=utf-8
# Call the ImageAsyncScanRequest operation to moderate images. Save the task ID returned by the operation and use it to poll the moderation results.
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')
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.
# The sample code uses a single image as an example. If you want to moderate multiple images at a time, create one task for each image to be moderated.
# The system charges you based on the moderation scenario that you specify.
# 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 calculated separately 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 at the specified interval. For more information, see the description of the ImageAsyncScanResultsRequest operation.
           print(taskId)

Query the results of asynchronous image moderation

Operation description

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')
request = ImageAsyncScanResultsRequest.ImageAsyncScanResultsRequest()
request.set_accept_format('JSON')

# Use task IDs to query the result of each image moderation task.
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 on the image based on the values of the scene and suggestion parameters.
                # do something
                scene = sceneResult["scene"]
                suggestion = sceneResult["suggestion"]