This topic shows you how to use SDKs for Python to moderate videos for risky content. You can moderate both images and audio in videos.

Background information

Content Moderation SDK for Python supports both 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.
  • 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 an on-premises video, or a binary video stream for video moderation.

Before you begin

Before you call operations, make the following preparations:

(Recommended) Submit asynchronous video moderation tasks

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)
  • us-west-1: US (Silicon Valley)
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 pair of your Alibaba Cloud account.
    clt = client.AcsClient("yourAccessKeyId", "yourAccessKeySecret","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 only submit one task in a request. If you want to submit more than one task 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. 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 an on-premises 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 containing Chinese characters for on-premises files.
    # 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 pair of your Alibaba Cloud account.
    clt = client.AcsClient("yourAccessKeyId", "yourAccessKeySecret","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 on-premises video to the server. Use the path of your on-premises file.
    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.
    # 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
    # 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 containing Chinese characters for on-premises files.
    # 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 pair of your Alibaba Cloud account.
    clt = client.AcsClient("yourAccessKeyId", "yourAccessKeySecret","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 and convert an on-premises file to binary data and submit the binary data for moderation.
    # Use the path of your on-premises file.
    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.
    # 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
    # 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 pair of your Alibaba Cloud account.
    clt = client.AcsClient("yourAccessKeyId", "yourAccessKeySecret","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 only submit one task in a request. If you want to submit more than one task 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. 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
    # 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 pair of your Alibaba Cloud account.
    clt = client.AcsClient("yourAccessKeyId", "yourAccessKeySecret","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 only submit one task in a request. If you want to submit more than one task 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. 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 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)
  • us-west-1: US (Silicon Valley)
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 pair of your Alibaba Cloud account.
clt = client.AcsClient("yourAccessKeyId", "yourAccessKeySecret","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 list of IDs of video moderation tasks that 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)
  • us-west-1: US (Silicon Valley)
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 pair of your Alibaba Cloud account.
clt = client.AcsClient("yourAccessKeyId", "yourAccessKeySecret","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"},
                {"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.
# 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"]:
            # Set the subsequent operations based on the result.
            print(result['suggestion'])
            print(result['scene'])