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

Background information

Content Moderation SDK for PHP supports synchronous and asynchronous video moderation.
  • If you use synchronous video moderation, you can submit only a sequence of image frames captured from a video for moderation. For more information about the related parameters, see Synchronous moderation.
  • If you use asynchronous video moderation, you can submit either a video or a sequence of image frames captured from the video for moderation. We recommend that you use asynchronous video moderation. For more information about the related parameters, see Asynchronous moderation.

You can submit the URL of an online video, the URL of a local video, a binary video stream, or a video live stream for video 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 asynchronous video moderation tasks (recommended)

Operation Description Supported region
VideoAsyncScanRequest Sends asynchronous requests to moderate videos for risky content in multiple moderation scenarios, including pornography, terrorist content, ad, 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 video for video moderation
    #coding=utf-8
    # The following code provides an example on how to call the VideoAsyncScanRequest operation: 
    from aliyunsdkcore import client
    from aliyunsdkgreen.request.v20180509 import VideoAsyncScanRequest
    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 = VideoAsyncScanRequest.VideoAsyncScanRequest()
    request.set_accept_format('JSON')
    
    task = {"dataId": str(uuid.uuid1()),
             "url": "https://xxxx/xxx.mp4"
            }
    print(task)
    # Create a video moderation task. By default, you can submit only one task in a request. If you want to submit multiple tasks in a request, submit a ticket. 
    # You can send a request to moderate multiple videos at a time and specify multiple moderation scenarios for each video. You are charged based on the number of frames captured from each video and the number of moderation scenarios for each video. 
    # For example, if you moderate two videos for both pornography and terrorist content at a time, the total expense is calculated based on the following formula: Total expense = Number of frames captured from the two videos × (Unit price in the pornography detection scenario + Unit price in the terrorist content detection scenario). 
    request.set_content(HttpContentHelper.toValue({"tasks": [task], "scenes": ["terrorism"]}))
    response = clt.do_action_with_exception(request)
    print(response)
    result = json.loads(response)
    if 200 == result["code"]:
        taskResults = result["data"]
        for taskResult in taskResults:
            # Save the task ID, which can be used to poll the moderation results. 
            print(taskResult["taskId"])
  • Submit the URL of a local video for video moderation
    #coding=utf-8
    # The following code provides an example on how to call the VideoAsyncScanRequest operation: 
    from aliyunsdkcore import client
    from aliyunsdkgreen.request.v20180509 import VideoAsyncScanRequest
    from aliyunsdkgreenextension.request.extension import HttpContentHelper
    from aliyunsdkgreenextension.request.extension import ClientUploader
    import json
    import uuid
    
    # Set the default encoding to UTF-8 to support a path whose name contains Chinese characters for local videos. 
    # 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 = VideoAsyncScanRequest.VideoAsyncScanRequest()
    request.set_accept_format('JSON')
    
    # Upload the local video to the server. Use the path of your local video. 
    uploader = ClientUploader.getVideoClientUploader(clt)
    url = uploader.uploadFile('d:/Terrorist content 1.mp4')
    
    task = {"dataId": str(uuid.uuid1()),
             "url": url
            }
    print(task)
    # Create a video moderation task. By default, you can submit only one task in a request. If you want to submit multiple tasks in a request, submit a ticket. 
    # You can send a request to moderate multiple videos at a time and specify multiple moderation scenarios for each video. You are charged based on the number of frames captured from each video and the number of moderation scenarios for each video. 
    # For example, if you moderate two videos for both pornography and terrorist content at a time, the total expense is calculated based on the following formula: Total expense = Number of frames captured from the two videos × (Unit price in the pornography detection scenario + Unit price in the terrorist content detection scenario). 
    request.set_content(HttpContentHelper.toValue({"tasks": [task], "scenes": ["terrorism"]}))
    response = clt.do_action_with_exception(request)
    print(response)
    result = json.loads(response)
    if 200 == result["code"]:
        taskResults = result["data"]
        for taskResult in taskResults:
            # Save the task ID, which can be used to poll the moderation results. 
            print(taskResult["taskId"])
  • Submit a binary video stream for video moderation
    #coding=utf-8
    # The following code provides an example on how to call the VideoAsyncScanRequest operation: 
    from aliyunsdkcore import client
    from aliyunsdkgreen.request.v20180509 import VideoAsyncScanRequest
    from aliyunsdkgreenextension.request.extension import HttpContentHelper
    from aliyunsdkgreenextension.request.extension import ClientUploader
    import json
    import uuid
    
    # Set the default encoding to UTF-8 to support a path whose name contains Chinese characters for local videos. 
    # 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 = VideoAsyncScanRequest.VideoAsyncScanRequest()
    request.set_accept_format('JSON')
    # Read a local video, convert the data in the local video to binary data, and then submit the binary data for moderation. 
    # Use the path of your local video. 
    f = open('d:/Terrorist content 1.mp4', "rb+")
    videoBytes = f.read()
    f.close()
    
    # Upload the binary video stream to the server. 
    uploader = ClientUploader.getVideoClientUploader(clt)
    url = uploader.uploadBytes(videoBytes)  
    
    task = {"dataId": str(uuid.uuid1()),
             "url": url
            }
    print(task)
    # Create a video moderation task. By default, you can submit only one task in a request. If you want to submit multiple tasks in a request, submit a ticket. 
    # You can send a request to moderate multiple videos at a time and specify multiple moderation scenarios for each video. You are charged based on the number of frames captured from each video and the number of moderation scenarios for each video. 
    # For example, if you moderate two videos for both pornography and terrorist content at a time, the total expense is calculated based on the following formula: Total expense = Number of frames captured from the two videos × (Unit price in the pornography detection scenario + Unit price in the terrorist content detection scenario). 
    request.set_content(HttpContentHelper.toValue({"tasks": [task], "scenes": ["terrorism"]}))
    response = clt.do_action_with_exception(request)
    print(response)
    result = json.loads(response)
    if 200 == result["code"]:
        taskResults = result["data"]
        for taskResult in taskResults:
            # Save the task ID, which can be used to poll the moderation results. 
            print(taskResult["taskId"])
  • Submit a video live stream for video moderation
    #coding=utf-8
    # The following code provides an example on how to call the VideoAsyncScanRequest operation: 
    from aliyunsdkcore import client
    from aliyunsdkgreen.request.v20180509 import VideoAsyncScanRequest
    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 = VideoAsyncScanRequest.VideoAsyncScanRequest()
    request.set_accept_format('JSON')
    
    # Set the url parameter to the URL of your live stream. 
    task = {
            "dataId": str(uuid.uuid1()),
            "url": "http://xxx/xxx.flv"
            }
    print(task)
    # Create a video moderation task. By default, you can submit only one task in a request. If you want to submit multiple tasks in a request, submit a ticket. 
    # You can send a request to moderate multiple videos at a time and specify multiple moderation scenarios for each video. You are charged based on the number of frames captured from each video and the number of moderation scenarios for each video. 
    # For example, if you moderate two videos for both pornography and terrorist content at a time, the total expense is calculated based on the following formula: Total expense = Number of frames captured from the two videos × (Unit price in the pornography detection scenario + Unit price in the terrorist content detection scenario). 
    request.set_content(HttpContentHelper.toValue({"tasks": [task], "scenes": ["terrorism"], "live": True}))
    response = clt.do_action_with_exception(request)
    print(response)
    result = json.loads(response)
    if 200 == result["code"]:
        taskResults = result["data"]
        for taskResult in taskResults:
            # Save the task ID, which can be used to poll the moderation results. 
            print(taskResult["taskId"])
  • Submit a video live stream to moderate both the video images and audio
    #coding=utf-8
    # The following code provides an example on how to call the VideoAsyncScanRequest operation: 
    from aliyunsdkcore import client
    from aliyunsdkgreen.request.v20180509 import VideoAsyncScanRequest
    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 = VideoAsyncScanRequest.VideoAsyncScanRequest()
    request.set_accept_format('JSON')
    
    # Set the url parameter to the URL of your live stream. 
    task = {
            "dataId": str(uuid.uuid1()),
            "url": "http://xxx/xxx.flv"
            }
    print(task)
    # Create a video moderation task. By default, you can submit only one task in a request. If you want to submit multiple tasks in a request, submit a ticket. 
    # You can send a request to moderate multiple videos at a time and specify multiple moderation scenarios for each video. You are charged based on the number of frames captured from each video and the number of moderation scenarios for each video. 
    # For example, if you moderate two videos for both pornography and terrorist content at a time, the total expense is calculated based on the following formula: Total expense = Number of frames captured from the two videos × (Unit price in the pornography detection scenario + Unit price in the terrorist content detection scenario). 
    # If you moderate both images and audio in a video, the expense for image moderation is calculated based on the preceding rule and that for audio moderation is calculated based on the audio duration. 
    request.set_content(HttpContentHelper.toValue({"tasks": [task], "scenes": ["terrorism"], "live": True, "audioScenes": ["antispam"]}))
    response = clt.do_action_with_exception(request)
    print(response)
    result = json.loads(response)
    if 200 == result["code"]:
        taskResults = result["data"]
        for taskResult in taskResults:
            # Save the task ID, which can be used to poll the moderation results. 
            print(taskResult["taskId"])

Query the results of asynchronous video moderation

Operation Description Supported region
VideoAsyncScanResultsRequest Queries asynchronous video moderation results.
Note Instead of calling this operation to poll the moderation results, we recommend that you set the callback parameter when you submit asynchronous video moderation tasks to receive the moderation results.
  • 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 VideoAsyncScanResultsRequest operation: 
import json
from aliyunsdkcore import client
from aliyunsdkgreen.request.v20180509 import VideoAsyncScanResultsRequest
from aliyunsdkgreenextension.request.extension import HttpContentHelper

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

# Specify the IDs of the video moderation tasks whose results you want to query. 
taskIds = ['vi3pX@vXC94hPnWsss39WOQ9-1q52ZG']
request.set_content(HttpContentHelper.toValue(taskIds))
response = clt.do_action_with_exception(request)
result = json.loads(response)
if 200 == result["code"]:
    taskResults = result["data"]
    for taskResult in taskResults:
        # The results parameter of each task indicates the moderation results of frames captured from a video. 
        print(taskResult['results'])

Submit synchronous video moderation tasks

Operation Description Supported region
VideoSyncScanRequest Sends synchronous requests to moderate videos for risky content.
Note You can submit only a sequence of frames that are captured from a video for video moderation. To submit other types of videos, we recommend that you use the VideoAsyncScanRequest operation.
  • 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 VideoSyncScanRequest operation. Content Moderation moderates only a submitted sequence of consecutive frames. 
from aliyunsdkcore import client
from aliyunsdkgreen.request.v20180509 import VideoSyncScanRequest
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")
# The request object cannot be reused. You must create a request object for each request. 
request = VideoSyncScanRequest.VideoSyncScanRequest()
request.set_accept_format('JSON')

task = {
            "frames":[
                {"offset" : 0, "url" : "https://test1.jpg"},
                {"offset" : 2, "url" : "https://test2.jpg"},
                null
            ]
        }
print(task)
# Create a video moderation task. By default, you can submit only one task in a request. If you want to submit multiple tasks in a request, submit a ticket. 
# You can send a request to moderate multiple videos at a time and specify multiple moderation scenarios for each video. You are charged based on the number of frames captured from each video and the number of moderation scenarios for each video. 
# For example, if you moderate two videos for both pornography and terrorist content at a time, the total expense is calculated based on the following formula: Total expense = Number of frames captured from the two videos × (Unit price in the pornography detection scenario + Unit price in the terrorist content detection scenario). 
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:
        for result in taskResult["results"]:
            # Take a further action based on the result. 
            print(result['suggestion'])
            print(result['scene'])

Provide feedback on moderation results

If the moderation results are not as expected, you can call the VideoFeedbackRequest operation to modify the results. Content Moderation adds the moderated video frames to the similar image blacklist or whitelist based on your feedback. When you submit a similar video 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
VideoFeedbackRequest Provides feedback on a video 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 VideoFeedbackRequest
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 = VideoFeedbackRequest.VideoFeedbackRequest()
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 video is normal. A value of block indicates that the moderated video contains violations. 
request.set_content(
    json.dumps({"dataId": "Moderated video ID", "taskId": "Video moderation task ID", "url": "Moderated video URL",
                "suggestion": "block", "frames": [{"url": "URL of the captured video frame_1", "offset": "Offset of the captured video frame_1"}],
                "scenes": ["ad", "terrorism"], "note": "Remarks"}))

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