All Products
Search
Document Center

Content Moderation:Image moderation

Last Updated:Jul 31, 2023

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

Description

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

  • If you use synchronous image moderation, the moderation results are returned in real time. For more information about the related parameters, see /green/image/scan.

  • 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 the related parameters, see /green/image/asyncscan and /green/image/results.

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.

(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

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 results in real time: 
    from aliyunsdkcore import client
    from aliyunsdkgreen.request.v20180509 import ImageSyncScanRequest
    import json
    import uuid
    
    # Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
    # 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']
    clt = client.AcsClient("We recommend that you obtain the AccessKey ID of your RAM user from environment variables", "We recommend that you obtain the AccessKey secret of your RAM user from environment variables", "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://www.aliyun.com/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 begins when the request is initiated and ends upon moderation of the last image. 
    # In most cases, 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 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(json.dumps({"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 further action based on the values of the scene and suggestion parameters. 
                    # Perform different operations on the image based on different values of the suggestion parameter. For example, delete images that contain undesirable content. 
                    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 results 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')
    
    # Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
    # 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']
    clt = client.AcsClient("We recommend that you obtain the AccessKey ID of your RAM user from environment variables", "We recommend that you obtain the AccessKey secret of your RAM user from environment variables", "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 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 begins when the request is initiated and ends upon moderation of the last image. 
    # In most cases, 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 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 further action based on the values of the scene and suggestion parameters. 
                    # Perform different operations on the image based on different values of the suggestion parameter. For example, delete images that contain undesirable content. 
                    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 results 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')
    
    # Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
    # 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']
    clt = client.AcsClient("We recommend that you obtain the AccessKey ID of your RAM user from environment variables", "We recommend that you obtain the AccessKey secret of your RAM user from environment variables", "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 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 begins when the request is initiated and ends upon moderation of the last image. 
    # In most cases, 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 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 further action based on the values of the scene and suggestion parameters. 
                    # Perform different operations on the image based on different values of the suggestion parameter. For example, delete images that contain undesirable content. 
                    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 using 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

Sample code

# coding=utf-8
# The following code provides an example on how to call the ImageAsyncScanRequest operation. You must query the moderation results 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

# Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
# 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']
clt = client.AcsClient("We recommend that you obtain the AccessKey ID of your RAM user from environment variables", "We recommend that you obtain the AccessKey secret of your RAM user from environment variables", "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://example.com/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 begins when the request is initiated and ends upon moderation of the last image. 
# In most cases, 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 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"]
           # Record 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

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 

# Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
# 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']
clt = client.AcsClient("We recommend that you obtain the AccessKey ID of your RAM user from environment variables", "We recommend that you obtain the AccessKey secret of your RAM user from environment variables", "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 results 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 further action based on the values of the scene and suggestion parameters. 
                # Perform different operations on the image based on different values of the suggestion parameter. For example, delete images that contain undesirable content. 
                scene = sceneResult["scene"]
                suggestion = sceneResult["suggestion"]

Provide feedback on image moderation results

If the results of image moderation do not meet your expectations, 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 /green/image/feedback.

Operation

Description

Supported region

ImageScanFeedbackRequest

Provides feedback on image moderation results and modifies the machine-assisted moderation results based on the feedback.

  • cn-shanghai: China (Shanghai)

  • cn-beijing: China (Beijing)

  • cn-shenzhen: China (Shenzhen)

  • ap-southeast-1: Singapore

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 pair of your Alibaba Cloud account. 
# Note: We recommend that you reuse the instantiated client as much as possible. This improves moderation performance and avoids repeated client connections. 
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 results 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)
    result = json.loads(response)
    if 200 == result["code"]:
        print("response success.")
except Exception as err:
    print(err)