This topic describes how to use the Python SDK to moderate videos for risky content. You can moderate both images and audio in videos.

  • The Python SDK supports both synchronous and asynchronous video moderation. If you use synchronous video moderation, you can only submit a sequence of image frames captured from a video for 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.
  • 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.

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 asynchronous video moderation tasks

Operation description
Operation Feature Region Description
VideoAsyncScanRequest Sends asynchronous requests to moderate videos for risky content.
  • cn-shanghai: China (Shanghai)
  • cn-beijing: China (Beijing)
  • cn-shenzhen: China (Shenzhen)
  • ap-southeast-1: Singapore
  • us-west-1: US (Silicon Valley)
This operation moderates videos for risky content in multiple moderation scenarios, including pornography, terrorist content, ad, undesirable scene, and logo detection.
Sample code
  • Submit the URL of an online video for video moderation
    #coding=utf-8
    # Call the VideoAsyncScanRequest operation to moderate videos.
    from aliyunsdkcore import client
    from aliyunsdkgreen.request.v20180509 import VideoAsyncScanRequest
    from aliyunsdkgreen.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 = 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 only submit one task in a request. If you want to submit more than one task in a request, submit a ticket.
    # The system charges you based on the moderation scenario that you specify.
    # You can send a request to moderate multiple videos at a time and specify multiple moderation scenarios for each video. The system charges you 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 is used to poll the moderation results at the specified interval.
            print(taskResult["taskId"])
  • Submit the URL of a local video for video moderation
    #coding=utf-8
    # Call the VideoAsyncScanRequest operation to moderate videos.
    from aliyunsdkcore import client
    from aliyunsdkgreen.request.v20180509 import VideoAsyncScanRequest
    from aliyunsdkgreen.request.extension import HttpContentHelper
    from aliyunsdkgreen.request.extension import ClientUploader
    import json
    import uuid
    
    # 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 = VideoAsyncScanRequest.VideoAsyncScanRequest()
    request.set_accept_format('JSON')
    # Use the path of your local video.
    # Upload the local video to the server.
    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 only submit one task in a request. If you want to submit more than one task in a request, submit a ticket.
    # The system charges you based on the moderation scenario that you specify.
    # You can send a request to moderate multiple videos at a time and specify multiple moderation scenarios for each video. The system charges you 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 is used to poll the moderation results at the specified interval.
            print(taskResult["taskId"])
  • Submit a binary video stream for video moderation
    #coding=utf-8
    # Call the VideoAsyncScanRequest operation to moderate videos.
    from aliyunsdkcore import client
    from aliyunsdkgreen.request.v20180509 import VideoAsyncScanRequest
    from aliyunsdkgreen.request.extension import HttpContentHelper
    from aliyunsdkgreen.request.extension import ClientUploader
    import json
    import uuid
    
    # 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 = VideoAsyncScanRequest.VideoAsyncScanRequest()
    request.set_accept_format('JSON')
    # Simulate binary data for moderation.
    # Read and convert a local video to binary data. Use the path of your local video.
    f = open('d:/Terrorist content 1.mp4', "rb+")
    videoBytes = f.read()
    f.close()
    
    # Upload the binary 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 only submit one task in a request. If you want to submit more than one task in a request, submit a ticket.
    # The system charges you based on the moderation scenario that you specify.
    # You can send a request to moderate multiple videos at a time and specify multiple moderation scenarios for each video. The system charges you 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 is used to poll the moderation results at the specified interval.
            print(taskResult["taskId"])
  • Submit a video live stream for video moderation
    #coding=utf-8
    # Call the VideoAsyncScanRequest operation to moderate videos.
    from aliyunsdkcore import client
    from aliyunsdkgreen.request.v20180509 import VideoAsyncScanRequest
    from aliyunsdkgreen.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 = 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 only submit one task in a request. If you want to submit more than one task in a request, submit a ticket.
    # The system charges you based on the moderation scenario that you specify.
    # You can send a request to moderate multiple videos at a time and specify multiple moderation scenarios for each video. The system charges you 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 is used to poll the moderation results at the specified interval.
            print(taskResult["taskId"])
  • Submit a video live stream to moderate both the video images and audio
    #coding=utf-8
    # Call the VideoAsyncScanRequest operation to moderate videos.
    from aliyunsdkcore import client
    from aliyunsdkgreen.request.v20180509 import VideoAsyncScanRequest
    from aliyunsdkgreen.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 = 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 only submit one task in a request. If you want to submit more than one task in a request, submit a ticket.
    # The system charges you based on the moderation scenario that you specify.
    # You can send a request to moderate multiple videos at a time and specify multiple moderation scenarios for each video. The system charges you 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 is used to poll the moderation results at the specified interval.
            print(taskResult["taskId"])

Query the results of asynchronous video moderation

Operation description
Operation Feature Region Description
VideoAsyncScanResultsRequest Queries the results of asynchronous video moderation tasks.
  • cn-shanghai: China (Shanghai)
  • cn-beijing: China (Beijing)
  • cn-shenzhen: China (Shenzhen)
  • ap-southeast-1: Singapore
  • us-west-1: US (Silicon Valley)
This operation queries the video moderation results through polling. We recommend that you configure a callback notification to receive the moderation results.
Sample code
#coding=utf-8
# Call the VideoAsyncScanResultsRequest operation to query the results of asynchronous video moderation tasks.
import json
from aliyunsdkcore import client
from aliyunsdkgreen.request.v20180509 import VideoAsyncScanResultsRequest
from aliyunsdkgreen.request.extension import HttpContentHelper

# Use the AccessKey ID and AccessKey secret of your Alibaba Cloud account. You can add the AccessKey ID and AccessKey secret to the profile or directly enter them in plaintext in the code.
clt = client.AcsClient("Your AccessKey ID", "Your AccessKey secret",'cn-shanghai')
request = VideoAsyncScanResultsRequest.VideoAsyncScanResultsRequest()
request.set_accept_format('JSON')

# The taskIds parameter indicates the list of video moderation task IDs that are used to query the video moderation results.
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
Operation Feature Region Description
VideoSyncScanRequest Sends synchronous requests to moderate videos for risky content.
  • cn-shanghai: China (Shanghai)
  • cn-beijing: China (Beijing)
  • cn-shenzhen: China (Shenzhen)
  • ap-southeast-1: Singapore
  • us-west-1: US (Silicon Valley)
If you use synchronous video moderation, you can only submit a sequence of image frames captured from a video for moderation. We recommend that you use asynchronous video moderation.
Sample code
#coding=utf-8
# Call the VideoSyncScanRequest operation to moderate a sequence of frames captured from a video.
from aliyunsdkcore import client
from aliyunsdkgreen.request.v20180509 import VideoSyncScanRequest
from aliyunsdkgreen.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")
request = VideoSyncScanRequest.VideoSyncScanRequest()
request.set_accept_format('JSON')

task = {
            "frames":[
                {"offset" : 0, "url" : "https://test1.jpg"},
                {"offset" : 2, "url" : "https://test2.jpg"},
                {"offset" : 3, "url" : "https://test3.jpg"}
            ]
        }
print(task)
# Create a video moderation task. By default, you can only submit one task in a request. If you want to submit more than one task in a request, submit a ticket.
# The system charges you based on the moderation scenario that you specify.
# You can send a request to moderate multiple videos at a time and specify multiple moderation scenarios for each video. The system charges you 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 on the video based on the values of the scene and suggestion parameters.
            print(result['suggestion'])
            print(result['scene'])