All Products
Search
Document Center

Content Moderation:Video moderation

Last Updated:Jul 31, 2023

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

Description

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

  • If you use synchronous video moderation, you can submit only a sequence of frames captured from a video for moderation. For more information about the related parameters, see /green/video/syncscan.

  • (Recommended) If you use asynchronous video moderation, you can submit a video or a sequence of frames captured from the video for moderation. For more information about the related parameters, see /green/video/asyncscan and /green/video/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 asynchronous video moderation tasks

Operation

Description

Supported region

VideoAsyncScanRequest

Sends asynchronous requests to moderate videos for risky content across 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

Sample code

  • Submit the URL of a 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
    
    # 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 = VideoAsyncScanRequest.VideoAsyncScanRequest()
    request.set_accept_format('JSON')
    
    task = {"dataId": str(uuid.uuid1()),
             "url": "https://www.aliyundoc.com/xxx.mp4"
            }
    print(task)
    # Create a video moderation task. By default, you can submit only one task in a request. 
    # 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 fee is calculated by using the following formula: Total fee = 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 query the video 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: 
    import sys
    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')
    
    # 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 = 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. 
    # 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 fee is calculated by using the following formula: Total fee = 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 query the video 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: 
    import sys
    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')
    
    # 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 = 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. 
    # 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 fee is calculated by using the following formula: Total fee = 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 query the video 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
    
    # 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 = 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://www.aliyundoc.com/xxx.flv"
            }
    print(task)
    # Create a video moderation task. By default, you can submit only one task in a request. 
    # 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 fee is calculated by using the following formula: Total fee = 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 query the video moderation results. 
            print(taskResult["taskId"])
  • Submit a video live stream to moderate both the video images and the 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
    
    # 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 = 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://www.aliyundoc.com/xxx.flv"
            }
    print(task)
    # Create a video moderation task. By default, you can submit only one task in a request. 
    # 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 fee is calculated by using the following formula: Total fee = 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 fee for image moderation is calculated based on the preceding rule, and the fee 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 query the video moderation results. 
            print(taskResult["taskId"])

Query the results of asynchronous video moderation

Operation

Description

Supported region

VideoAsyncScanResultsRequest

Queries the results of asynchronous video moderation.

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

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

# 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 = 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

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

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

task = {
            "frames":[
                {"offset" : 0, "url" : "https://example.com/test1.jpg"},
                {"offset" : 2, "url" : "https://example.com/test2.jpg"},
                {"offset" : 3, "url" : "https://example.com/test3.jpg"}
            ]
        }
print(task)
# Create a video moderation task. By default, you can submit only one task in a request. 
# 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 send a request to moderate two videos for both pornography and terrorist content at a time, the total expense is calculated by using the following formula: Total expense = Number of frames captured from the two videos × (Unit price for the pornography detection scenario + Unit price for 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"]:
            # Perform subsequent operations based on the results. 
            print(result['suggestion'])
            print(result['scene'])

Provide feedback on moderation results

If the moderation results do not meet your expectations, 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 frame for moderation, Content Moderation returns moderation results based on the label in your feedback.

For more information, see /green/video/feedback.

Operation

Description

Supported region

VideoFeedbackRequest

Provides feedback on video 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 VideoFeedbackRequest
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')
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": "ID of the moderated video", "taskId": "ID of the video moderation task", "url": "URL of the moderated video",
                "suggestion": "block", "frames": [{"url": "URL of captured video frame 1", "offset": "Offset of captured video frame 1"}],
                "scenes": ["ad", "terrorism"], "note": "Remarks"}))

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)