You can call Video Moderation Version 2.0 using a software development kit (SDK) or native HTTPS. We recommend using the SDK for integration because it handles details such as signature authentication and request body construction. This topic describes how to integrate with Video Moderation Version 2.0.
Step 1: Activate the service
Go to the Content Moderation 2.0 activation page to activate the Video Moderation 2.0 service. After you call the API operations, the system automatically generates bills based on your usage. For more information, see Billing.
After you activate the Video Moderation 2.0 service, the default billing method is pay-as-you-go. Fees are calculated daily based on your actual usage. You are not charged if you do not use the service.
Step 2: Grant permissions to a RAM user
Before you call API operations or use SDKs, you must grant permissions to a Resource Access Management (RAM) user. You can create an AccessKey pair for the RAM user. When you call Alibaba Cloud APIs, you must use the AccessKey pair to complete identity verification. For more information about how to obtain an AccessKey pair, see Obtain an AccessKey pair.
Procedure
Log on to the RAM console as a RAM administrator.
- Create a RAM user.
For more information, see Create a RAM user.
- Grant the
AliyunYundunGreenWebFullAccesssystem policy to the RAM user.For more information, see Grant permissions to a RAM user.
After completing the preceding operations, you can call the Content Moderation API as the RAM user.
Step 3: Install and use the SDK to call the Video Moderation service
The following table describes the supported regions.
Region | Public endpoint | VPC endpoint | Supported services |
Singapore | green-cip.ap-southeast-1.aliyuncs.com | green-cip-vpc.ap-southeast-1.aliyuncs.com | videoDetection_global, videoDetectionByVL_global, liveStreamDetection_global, liveStreamDetectionByVL_global |
US (Virginia) | https://green-cip.us-east-1.aliyuncs.com | https://green-cip-vpc.us-east-1.aliyuncs.com | videoDetection_global, liveStreamDetection_global |
US (Silicon Valley) | https://green-cip.us-west-1.aliyuncs.com | Not available | |
Germany (Frankfurt) | green-cip.eu-central-1.aliyuncs.com | Not available |
If you need SDK sample code in other programming languages, you can use OpenAPI Explorer to debug API operations online. This tool automatically generates SDK sample code for the API operations. The following API operations are available for online debugging:
In Alibaba Cloud SDK code, you can create a default access credential by defining ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. When you call API operations of Alibaba Cloud services, the system directly accesses the credential, reads your AccessKey pair, and then automatically completes authentication. Before you use the SDK sample code, you must configure environment variables. For more information, see Configure credentials.
For more information about the API parameters, see Video File Moderation 2.0 API and Live Stream Moderation 2.0 API.
Java SDK
Java 1.8 or later is required.
For the source code, see Java SDK source code or Java SDK source code (OSS path).
The following three types of video moderation are supported.
Moderate a publicly accessible video
Scenarios
If the video to be moderated is accessible from the Internet, the Video Moderation 2.0 service can retrieve the video file from its URL and moderate it.
Add the following dependency to the pom.xml file to use the SDK in a Maven project.
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>2.2.11</version> </dependency>Integrate with the Java SDK.
Sample code for submitting a video moderation task
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.VideoModerationRequest; import com.aliyun.green20220302.models.VideoModerationResponse; import com.aliyun.green20220302.models.VideoModerationResponseBody; import com.aliyun.teaopenapi.models.Config; public class VideoModerationDemo { public static void main(String[] args) throws Exception { Config config = new Config(); /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Common ways to obtain environment variables: * Method 1: * Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ config.setAccessKeyId("Obtain the AccessKey ID from an environment variable."); config.setAccessKeySecret("Obtain the AccessKey secret from an environment variable."); // Modify the region and endpoint as needed. config.setRegionId("ap-southeast-1"); config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com"); // The connection timeout period in milliseconds (ms). config.setReadTimeout(6000); // The read timeout period in milliseconds (ms). config.setConnectTimeout(3000); // Set the HTTP proxy. //config.setHttpProxy("http://10.10.xx.xx:xxxx"); // Set the HTTPS proxy. //config.setHttpsProxy("https://10.10.xx.xx:xxxx"); Client client = new Client(config); JSONObject serviceParameters = new JSONObject(); serviceParameters.put("url", "https://xxx.oss.aliyuncs.com/xxx.mp4"); VideoModerationRequest videoModerationRequest = new VideoModerationRequest(); // Moderation service: videoDetection_global videoModerationRequest.setService("videoDetection_global"); videoModerationRequest.setServiceParameters(serviceParameters.toJSONString()); try { VideoModerationResponse response = client.videoModeration(videoModerationRequest); if (response.getStatusCode() == 200) { VideoModerationResponseBody result = response.getBody(); System.out.println(JSON.toJSONString(result)); System.out.println("requestId = " + result.getRequestId()); System.out.println("code = " + result.getCode()); System.out.println("msg = " + result.getMessage()); Integer code = result.getCode(); if (200 == code) { VideoModerationResponseBody.VideoModerationResponseBodyData data = result.getData(); System.out.println("taskId = [" + data.getTaskId() + "]"); } else { System.out.println("video moderation not success. code:" + code); } } else { System.out.println("response not success. status:" + response.getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } } }Sample code for querying the result of a video moderation task
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.VideoModerationResultRequest; import com.aliyun.green20220302.models.VideoModerationResultResponse; import com.aliyun.green20220302.models.VideoModerationResultResponseBody; import com.aliyun.teaopenapi.models.Config; public class VideoModerationResultDemo { public static void main(String[] args) throws Exception { Config config = new Config(); /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Common ways to obtain environment variables: * Method 1: * Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ config.setAccessKeyId("Obtain the AccessKey ID from an environment variable."); config.setAccessKeySecret("Obtain the AccessKey secret from an environment variable."); // Modify the region and endpoint as needed. config.setRegionId("ap-southeast-1"); config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com"); // The connection timeout period in milliseconds (ms). config.setReadTimeout(6000); // The read timeout period in milliseconds (ms). config.setConnectTimeout(3000); // Set the HTTP proxy. //config.setHttpProxy("http://10.10.xx.xx:xxxx"); // Set the HTTPS proxy. //config.setHttpsProxy("https://10.10.xx.xx:xxxx"); Client client = new Client(config); JSONObject serviceParameters = new JSONObject(); // The task ID returned after you submit the task. serviceParameters.put("taskId", "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****"); VideoModerationResultRequest videoModerationResultRequest = new VideoModerationResultRequest(); // Moderation service: videoDetection_global videoModerationResultRequest.setService("videoDetection_global"); videoModerationResultRequest.setServiceParameters(serviceParameters.toJSONString()); try { VideoModerationResultResponse response = client.videoModerationResult(videoModerationResultRequest); if (response.getStatusCode() == 200) { VideoModerationResultResponseBody result = response.getBody(); System.out.println("requestId=" + result.getRequestId()); System.out.println("code=" + result.getCode()); System.out.println("msg=" + result.getMessage()); if (200 == result.getCode()) { VideoModerationResultResponseBody.VideoModerationResultResponseBodyData data = result.getData(); System.out.println("dataId = " + data.getDataId()); System.out.println("riskLevel = " + data.getRiskLevel()); System.out.println("audioResult = " + JSON.toJSONString(data.getAudioResult())); System.out.println("frameResult = " + JSON.toJSONString(data.getFrameResult())); } else { System.out.println("video moderation result not success. code:" + result.getCode()); } } else { System.out.println("response not success. status:" + response.getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } } }Sample code for canceling a live stream moderation task
import com.alibaba.fastjson.JSONObject; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.VideoModerationCancelRequest; import com.aliyun.green20220302.models.VideoModerationCancelResponse; import com.aliyun.green20220302.models.VideoModerationCancelResponseBody; import com.aliyun.teaopenapi.models.Config; public class VideoModerationCancelDemo { public static void main(String[] args) throws Exception { Config config = new Config(); /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Common ways to obtain environment variables: * Method 1: * Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ config.setAccessKeyId("Obtain the AccessKey ID from an environment variable."); config.setAccessKeySecret("Obtain the AccessKey secret from an environment variable."); // Modify the region and endpoint as needed. config.setRegionId("ap-southeast-1"); config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com"); // The connection timeout period in milliseconds (ms). config.setReadTimeout(6000); // The read timeout period in milliseconds (ms). config.setConnectTimeout(3000); // Set the HTTP proxy. //config.setHttpProxy("http://xx.xx.xx.xx:xxxx"); // Set the HTTPS proxy. //config.setHttpsProxy("https://xx.xx.xx.xx:xxxx"); Client client = new Client(config); JSONObject serviceParameters = new JSONObject(); // The task ID returned after you submit the task. serviceParameters.put("taskId", "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****"); VideoModerationCancelRequest videoModerationCancelRequest = new VideoModerationCancelRequest(); videoModerationCancelRequest.setService("liveStreamDetection_global"); videoModerationCancelRequest.setServiceParameters(serviceParameters.toJSONString()); try { VideoModerationCancelResponse response = client.videoModerationCancel(videoModerationCancelRequest); if (response.getStatusCode() == 200) { VideoModerationCancelResponseBody result = response.getBody(); System.out.println("requestId=" + result.getRequestId()); System.out.println("code=" + result.getCode()); System.out.println("msg=" + result.getMessage()); if (200 != result.getCode()) { System.out.println("video moderation cancel not success. code:" + result.getCode()); } } else { System.out.println("response not success. status:" + response.getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } } }
Moderate a local video
Scenarios
If the video to be moderated is on your local machine and does not have a public URL, you can upload the video to an Object Storage Service (OSS) bucket provided by Content Moderation. The Video Moderation 2.0 service can directly access OSS, retrieve the video content, and moderate the video.
Add the following dependency to the pom.xml file to use the SDK in a Maven project.
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>2.2.11</version> </dependency>Install the OSS SDK:
<dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.16.3</version> </dependency>Integrate with the Java SDK.
Sample code for submitting a video moderation task
import com.alibaba.fastjson.JSON; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.DescribeUploadTokenResponse; import com.aliyun.green20220302.models.DescribeUploadTokenResponseBody; import com.aliyun.green20220302.models.VideoModerationRequest; import com.aliyun.green20220302.models.VideoModerationResponse; import com.aliyun.green20220302.models.VideoModerationResponseBody; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.model.PutObjectRequest; import com.aliyun.teaopenapi.models.Config; import com.aliyun.teautil.models.RuntimeOptions; import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class LocalVideoModeration { // Specifies whether the service is deployed in a VPC. public static boolean isVPC = false; // The token used to upload the file. The key is the endpoint and the value is the token. public static Map<String, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData> tokenMap = new HashMap<>(); // The client used to upload the file. public static OSS ossClient = null; /** * Create a client to send requests. * * @param accessKeyId * @param accessKeySecret * @param endpoint * @return * @throws Exception */ public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception { Config config = new Config(); config.setAccessKeyId(accessKeyId); config.setAccessKeySecret(accessKeySecret); // Modify the region and endpoint as needed. config.setEndpoint(endpoint); return new Client(config); } /** * Create a client to upload files. * * @param tokenData * @param isVPC */ public static void getOssClient(DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData, boolean isVPC) { // Note: Reuse the instantiated client to avoid repeated connections and improve moderation performance. if (isVPC) { ossClient = new OSSClientBuilder().build(tokenData.ossInternalEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken()); } else { ossClient = new OSSClientBuilder().build(tokenData.ossInternetEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken()); } } /** * Upload a file. * * @param filePath * @param tokenData * @return * @throws Exception */ public static String uploadFile(String filePath, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData) throws Exception { String[] split = filePath.split("\\."); String objectName; if (split.length > 1) { objectName = tokenData.getFileNamePrefix() + UUID.randomUUID() + "." + split[split.length - 1]; } else { objectName = tokenData.getFileNamePrefix() + UUID.randomUUID(); } PutObjectRequest putObjectRequest = new PutObjectRequest(tokenData.getBucketName(), objectName, new File(filePath)); ossClient.putObject(putObjectRequest); return objectName; } public static VideoModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception { // Note: Reuse the instantiated client to avoid repeated connections and improve moderation performance. Client client = createClient(accessKeyId, accessKeySecret, endpoint); RuntimeOptions runtime = new RuntimeOptions(); // The full path of the local file. Example: D:\localPath\exampleFile.mp4. String filePath = "D:\\localPath\\exampleFile.mp4"; // Obtain the token used to upload the file. if (tokenMap.get(endpoint) == null || tokenMap.get(endpoint).expiration <= System.currentTimeMillis() / 1000) { DescribeUploadTokenResponse tokenResponse = client.describeUploadToken(); tokenMap.put(endpoint, tokenResponse.getBody().getData()); } // The client used to upload the file. getOssClient(tokenMap.get(endpoint), isVPC); // Upload the file. String objectName = uploadFile(filePath, tokenMap.get(endpoint)); // Construct moderation parameters. Map<String, String> serviceParameters = new HashMap<>(); // The information about the uploaded file. serviceParameters.put("ossBucketName", tokenMap.get(endpoint).getBucketName()); serviceParameters.put("ossObjectName", objectName); serviceParameters.put("dataId", UUID.randomUUID().toString()); VideoModerationRequest request = new VideoModerationRequest(); // Moderation service: videoDetection_global request.setService("videoDetection_global"); request.setServiceParameters(JSON.toJSONString(serviceParameters)); VideoModerationResponse response = null; try { response = client.videoModerationWithOptions(request, runtime); } catch (Exception e) { e.printStackTrace(); } return response; } public static void main(String[] args) throws Exception { /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Common ways to obtain environment variables: * Method 1: * Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ String accessKeyId = "Obtain the AccessKey ID from an environment variable."; String accessKeySecret = "Obtain the AccessKey secret from an environment variable."; // Modify the region and endpoint as needed. VideoModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com"); try { // Print the moderation results. if (response != null) { if (response.getStatusCode() == 200) { VideoModerationResponseBody body = response.getBody(); System.out.println(JSON.toJSONString(body)); System.out.println("requestId = " + body.getRequestId()); System.out.println("code = " + body.getCode()); System.out.println("msg = " + body.getMessage()); Integer code = body.getCode(); if (200 == code) { VideoModerationResponseBody.VideoModerationResponseBodyData data = body.getData(); System.out.println("taskId = [" + data.getTaskId() + "]"); } else { System.out.println("video moderation not success. code:" + code); } } else { System.out.println("response not success. status:" + response.getStatusCode()); } } } catch (Exception e) { e.printStackTrace(); } } }Sample code for querying the result of a video moderation task
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.VideoModerationResultRequest; import com.aliyun.green20220302.models.VideoModerationResultResponse; import com.aliyun.green20220302.models.VideoModerationResultResponseBody; import com.aliyun.teaopenapi.models.Config; public class VideoModerationResultDemo { public static void main(String[] args) throws Exception { Config config = new Config(); /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Common ways to obtain environment variables: * Method 1: * Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ config.setAccessKeyId("Obtain the AccessKey ID from an environment variable."); config.setAccessKeySecret("Obtain the AccessKey secret from an environment variable."); // Modify the region and endpoint as needed. config.setRegionId("ap-southeast-1"); config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com"); // The connection timeout period in milliseconds (ms). config.setReadTimeout(6000); // The read timeout period in milliseconds (ms). config.setConnectTimeout(3000); // Set the HTTP proxy. //config.setHttpProxy("http://10.10.xx.xx:xxxx"); // Set the HTTPS proxy. //config.setHttpsProxy("https://10.10.xx.xx:xxxx"); Client client = new Client(config); JSONObject serviceParameters = new JSONObject(); // The task ID returned after you submit the task. serviceParameters.put("taskId", "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****"); VideoModerationResultRequest videoModerationResultRequest = new VideoModerationResultRequest(); // Moderation service: videoDetection_global videoModerationResultRequest.setService("videoDetection_global"); videoModerationResultRequest.setServiceParameters(serviceParameters.toJSONString()); try { VideoModerationResultResponse response = client.videoModerationResult(videoModerationResultRequest); if (response.getStatusCode() == 200) { VideoModerationResultResponseBody result = response.getBody(); System.out.println("requestId=" + result.getRequestId()); System.out.println("code=" + result.getCode()); System.out.println("msg=" + result.getMessage()); if (200 == result.getCode()) { VideoModerationResultResponseBody.VideoModerationResultResponseBodyData data = result.getData(); System.out.println("dataId = " + data.getDataId()); System.out.println("riskLevel = " + data.getRiskLevel()); System.out.println("audioResult = " + JSON.toJSONString(data.getAudioResult())); System.out.println("frameResult = " + JSON.toJSONString(data.getFrameResult())); } else { System.out.println("video moderation result not success. code:" + result.getCode()); } } else { System.out.println("response not success. status:" + response.getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } } }Sample code for canceling a live stream moderation task
import com.alibaba.fastjson.JSONObject; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.VideoModerationCancelRequest; import com.aliyun.green20220302.models.VideoModerationCancelResponse; import com.aliyun.green20220302.models.VideoModerationCancelResponseBody; import com.aliyun.teaopenapi.models.Config; public class VideoModerationCancelDemo { public static void main(String[] args) throws Exception { Config config = new Config(); /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Common ways to obtain environment variables: * Method 1: * Obtain the AccessKey ID of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Obtain the AccessKey ID of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ config.setAccessKeyId("Obtain the AccessKey ID from an environment variable."); config.setAccessKeySecret("Obtain the AccessKey secret from an environment variable."); // Modify the region and endpoint as needed. config.setRegionId("ap-southeast-1"); config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com"); // The connection timeout period in milliseconds (ms). config.setReadTimeout(6000); // The read timeout period in milliseconds (ms). config.setConnectTimeout(3000); // Set the HTTP proxy. //config.setHttpProxy("http://xx.xx.xx.xx:xxxx"); // Set the HTTPS proxy. //config.setHttpsProxy("https://xx.xx.xx.xx:xxxx"); Client client = new Client(config); JSONObject serviceParameters = new JSONObject(); // The task ID returned after you submit the task. serviceParameters.put("taskId", "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****"); VideoModerationCancelRequest videoModerationCancelRequest = new VideoModerationCancelRequest(); videoModerationCancelRequest.setService("liveStreamDetection_global"); videoModerationCancelRequest.setServiceParameters(serviceParameters.toJSONString()); try { VideoModerationCancelResponse response = client.videoModerationCancel(videoModerationCancelRequest); if (response.getStatusCode() == 200) { VideoModerationCancelResponseBody result = response.getBody(); System.out.println("requestId=" + result.getRequestId()); System.out.println("code=" + result.getCode()); System.out.println("msg=" + result.getMessage()); if (200 != result.getCode()) { System.out.println("video moderation cancel not success. code:" + result.getCode()); } } else { System.out.println("response not success. status:" + response.getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } } }
Moderate a video in OSS
Scenarios
If the video to be moderated is already stored in OSS, you can grant permissions to a service-linked role to allow the Content Moderation service to access OSS. The Video Moderation 2.0 service can retrieve the video file from OSS through the service-linked role and moderate it. To create a service-linked role, go to the Cloud Resource Access Authorization page.
Add the following dependency to the pom.xml file to use the SDK in a Maven project.
<dependency> <groupId>com.aliyun</groupId> <artifactId>green20220302</artifactId> <version>2.2.11</version> </dependency>Use the Java SDK.
Sample code for submitting a video moderation task
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.VideoModerationRequest; import com.aliyun.green20220302.models.VideoModerationResponse; import com.aliyun.green20220302.models.VideoModerationResponseBody; import com.aliyun.teaopenapi.models.Config; public class VideoModerationDemo { public static void main(String[] args) throws Exception { Config config = new Config(); /** * An AccessKey of an Alibaba Cloud account grants full access to all APIs. For security, use a RAM user for API calls and routine O&M. * Common ways to get environment variables: * Method 1: * Get the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Get the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Get the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Get the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ config.setAccessKeyId("Get the AccessKey ID of the RAM user from an environment variable."); config.setAccessKeySecret("Get the AccessKey secret of the RAM user from an environment variable."); // Modify the region and endpoint as needed. config.setRegionId("ap-southeast-1"); config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com"); // The connection timeout period in milliseconds (ms). config.setReadTimeout(6000); // The read timeout period in milliseconds (ms). config.setConnectTimeout(3000); // Set an HTTP proxy. //config.setHttpProxy("http://10.10.xx.xx:xxxx"); // Set an HTTPS proxy. //config.setHttpsProxy("https://10.10.xx.xx:xxxx"); Client client = new Client(config); JSONObject serviceParameters = new JSONObject(); serviceParameters.put("ossBucketName", "bucket_01"); serviceParameters.put("ossObjectName", "20240307/07/28/test.flv"); serviceParameters.put("ossRegionId", "ap-southeast-1"); VideoModerationRequest videoModerationRequest = new VideoModerationRequest(); // Moderation service: videoDetection_global videoModerationRequest.setService("videoDetection_global"); videoModerationRequest.setServiceParameters(serviceParameters.toJSONString()); try { VideoModerationResponse response = client.videoModeration(videoModerationRequest); if (response.getStatusCode() == 200) { VideoModerationResponseBody result = response.getBody(); System.out.println(JSON.toJSONString(result)); System.out.println("requestId = " + result.getRequestId()); System.out.println("code = " + result.getCode()); System.out.println("msg = " + result.getMessage()); Integer code = result.getCode(); if (200 == code) { VideoModerationResponseBody.VideoModerationResponseBodyData data = result.getData(); System.out.println("taskId = [" + data.getTaskId() + "]"); } else { System.out.println("Video moderation failed. Code: " + code); } } else { System.out.println("Response failed. Status: " + response.getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } } }Sample code for retrieving video moderation results
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.VideoModerationResultRequest; import com.aliyun.green20220302.models.VideoModerationResultResponse; import com.aliyun.green20220302.models.VideoModerationResultResponseBody; import com.aliyun.teaopenapi.models.Config; public class VideoModerationResultDemo { public static void main(String[] args) throws Exception { Config config = new Config(); /** * An AccessKey of an Alibaba Cloud account grants full access to all APIs. For security, use a RAM user for API calls and routine O&M. * Common ways to get environment variables: * Method 1: * Get the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Get the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Get the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Get the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ config.setAccessKeyId("Get the AccessKey ID of the RAM user from an environment variable."); config.setAccessKeySecret("Get the AccessKey secret of the RAM user from an environment variable."); // Modify the region and endpoint as needed. config.setRegionId("ap-southeast-1"); config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com"); // The connection timeout period in milliseconds (ms). config.setReadTimeout(6000); // The read timeout period in milliseconds (ms). config.setConnectTimeout(3000); // Set an HTTP proxy. //config.setHttpProxy("http://10.10.xx.xx:xxxx"); // Set an HTTPS proxy. //config.setHttpsProxy("https://10.10.xx.xx:xxxx"); Client client = new Client(config); JSONObject serviceParameters = new JSONObject(); // The taskId returned when the task was submitted. serviceParameters.put("taskId", "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****"); VideoModerationResultRequest videoModerationResultRequest = new VideoModerationResultRequest(); // Moderation service: videoDetection_global videoModerationResultRequest.setService("videoDetection_global"); videoModerationResultRequest.setServiceParameters(serviceParameters.toJSONString()); try { VideoModerationResultResponse response = client.videoModerationResult(videoModerationResultRequest); if (response.getStatusCode() == 200) { VideoModerationResultResponseBody result = response.getBody(); System.out.println("requestId=" + result.getRequestId()); System.out.println("code=" + result.getCode()); System.out.println("msg=" + result.getMessage()); if (200 == result.getCode()) { VideoModerationResultResponseBody.VideoModerationResultResponseBodyData data = result.getData(); System.out.println("dataId = " + data.getDataId()); System.out.println("riskLevel = " + data.getRiskLevel()); System.out.println("audioResult = " + JSON.toJSONString(data.getAudioResult())); System.out.println("frameResult = " + JSON.toJSONString(data.getFrameResult())); } else { System.out.println("Failed to get video moderation results. Code: " + result.getCode()); } } else { System.out.println("Response failed. Status: " + response.getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } } }Sample code for canceling a live stream moderation task
import com.alibaba.fastjson.JSONObject; import com.aliyun.green20220302.Client; import com.aliyun.green20220302.models.VideoModerationCancelRequest; import com.aliyun.green20220302.models.VideoModerationCancelResponse; import com.aliyun.green20220302.models.VideoModerationCancelResponseBody; import com.aliyun.teaopenapi.models.Config; public class VideoModerationCancelDemo { public static void main(String[] args) throws Exception { Config config = new Config(); /** * An AccessKey of an Alibaba Cloud account grants full access to all APIs. For security, use a RAM user for API calls and routine O&M. * Common ways to get environment variables: * Method 1: * Get the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Get the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); * Method 2: * Get the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Get the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ config.setAccessKeyId("Get the AccessKey ID of the RAM user from an environment variable."); config.setAccessKeySecret("Get the AccessKey secret of the RAM user from an environment variable."); // Modify the region and endpoint as needed. config.setRegionId("ap-southeast-1"); config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com"); // The connection timeout period in milliseconds (ms). config.setReadTimeout(6000); // The read timeout period in milliseconds (ms). config.setConnectTimeout(3000); // Set an HTTP proxy. //config.setHttpProxy("http://xx.xx.xx.xx:xxxx"); // Set an HTTPS proxy. //config.setHttpsProxy("https://xx.xx.xx.xx:xxxx"); Client client = new Client(config); JSONObject serviceParameters = new JSONObject(); // The taskId returned when the task was submitted. serviceParameters.put("taskId", "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****"); VideoModerationCancelRequest videoModerationCancelRequest = new VideoModerationCancelRequest(); videoModerationCancelRequest.setService("liveStreamDetection_global"); videoModerationCancelRequest.setServiceParameters(serviceParameters.toJSONString()); try { VideoModerationCancelResponse response = client.videoModerationCancel(videoModerationCancelRequest); if (response.getStatusCode() == 200) { VideoModerationCancelResponseBody result = response.getBody(); System.out.println("requestId=" + result.getRequestId()); System.out.println("code=" + result.getCode()); System.out.println("msg=" + result.getMessage()); if (200 != result.getCode()) { System.out.println("Failed to cancel video moderation task. Code: " + result.getCode()); } } else { System.out.println("Response failed. Status: " + response.getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } } }
Python SDK
Python 3.6 or later is required.
For more information, see the Python SDK source code.
This SDK supports the following three types of video moderation.
Detect videos accessible over the internet
Scenarios
If a video is accessible over the Internet, the Video Moderation V2.0 service can moderate the video using its URL.
Run the following command to install pip.
pip install alibabacloud_green20220302==2.2.11Use the Python SDK.
Sample code for submitting a video moderation task
#encoding:utf-8 # python version >= 3.6 from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config import json config = Config( # An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Use a Resource Access Management (RAM) user to call API operations or perform routine O&M for better security. # Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all your cloud resources. # Common methods to obtain environment variables: # Obtain the AccessKey ID of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain the AccessKey secret of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='Obtain the AccessKey ID of your RAM user from an environment variable.', access_key_secret='Obtain the AccessKey secret of your RAM user from an environment variable.', # The connection timeout period in milliseconds (ms). connect_timeout=3000, # The read timeout period in milliseconds (ms). read_timeout=6000, # Modify the region and endpoint as needed. region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) clt = Client(config) serviceParameters = { 'url': 'https://xxx.oss.aliyuncs.com/xxx.mp4' } videoModerationRequest = models.VideoModerationRequest( # Detection service: videoDetection_global service='videoDetection_global', service_parameters=json.dumps(serviceParameters) ) try: response = clt.video_moderation(videoModerationRequest) if response.status_code == 200: # The call is successful. # Get the moderation result. result = response.body print('response success. result:{}'.format(result)) else: print('response not success. status:{} ,result:{}'.format(response.status_code, response)) except Exception as err: print(err)Retrieve the results of a video moderation task
# coding=utf-8 # python version >= 3.6 from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config import json config = Config( # An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Use a Resource Access Management (RAM) user to call API operations or perform routine O&M for better security. # Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all your cloud resources. # Common methods to obtain environment variables: # Obtain the AccessKey ID of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain the AccessKey secret of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='Obtain the AccessKey ID of your RAM user from an environment variable.', access_key_secret='Obtain the AccessKey secret of your RAM user from an environment variable.', # The connection timeout period in milliseconds (ms). connect_timeout=3000, # The read timeout period in milliseconds (ms). read_timeout=6000, # Modify the region and endpoint as needed. region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) clt = Client(config) # The taskId that is returned when you submit the task. serviceParameters = { "taskId": 'vi_f_11w5THcbVYctjdxz2C0Afa-1x****' } videoModerationResultRequest = models.VideoModerationResultRequest( # Detection service: videoDetection_global service='videoDetection_global', service_parameters=json.dumps(serviceParameters) ) try: response = clt.video_moderation_result(videoModerationResultRequest) if response.status_code == 200: # The call is successful. # Get the moderation result. result = response.body print('response success. result:{}'.format(result)) else: print('response not success. status:{} ,result:{}'.format(response.status_code, response)) except Exception as err: print(err)Sample code for canceling a live stream moderation task
# coding=utf-8 # python version >= 3.6 from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config import json config = Config( # An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Use a Resource Access Management (RAM) user to call API operations or perform routine O&M for better security. # Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all your cloud resources. # Common methods to obtain environment variables: # Obtain the AccessKey ID of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain the AccessKey secret of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='Obtain the AccessKey ID of your RAM user from an environment variable.', access_key_secret='Obtain the AccessKey secret of your RAM user from an environment variable.', # The connection timeout period in milliseconds (ms). connect_timeout=10000, # The read timeout period in milliseconds (ms). read_timeout=3000, region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) clt = Client(config) # The taskId that is returned when you submit the task. serviceParameters = { "taskId": 'vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****' } videoModerationCancelRequest = models.VideoModerationCancelRequest( # Detection service service='liveStreamDetection_global', service_parameters=json.dumps(serviceParameters) ) try: response = clt.video_moderation_cancel(videoModerationCancelRequest) if response.status_code == 200: # The call is successful. result = response.body print('response success. result:{}'.format(result)) else: print('response not success. status:{} ,result:{}'.format(response.status_code, response)) except Exception as err: print(err)
Detect local videos
Scenarios
If the video you need to moderate is stored on a local machine and is not accessible over the Internet, you can upload the video to an Object Storage Service (OSS) bucket provided by Content Moderation. The Video Moderation V2.0 service can then directly access OSS to retrieve and moderate the video.
Run the following command to install the SDK.
pip install alibabacloud_green20220302==2.2.11Install the OSS SDK:
pip install oss2Use the Python SDK.
Sample code for submitting a video moderation task
from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config from alibabacloud_tea_util.client import Client as UtilClient from alibabacloud_tea_util import models as util_models import json import uuid import oss2 import time config = Config( # An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Use a Resource Access Management (RAM) user to call API operations or perform routine O&M for better security. # Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all your cloud resources. # Common methods to obtain environment variables: # Obtain the AccessKey ID of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain the AccessKey secret of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='Obtain the AccessKey ID of your RAM user from an environment variable.', access_key_secret='Obtain the AccessKey secret of your RAM user from an environment variable.', # The connection timeout period in milliseconds (ms). connect_timeout=10000, # The read timeout period in milliseconds (ms). read_timeout=10000, # Modify the region and endpoint as needed. region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) # Note: Reuse the instantiated client to avoid repeated connections and improve detection performance. client = Client(config) bucket = None upload_token = None def get_oss_client(is_vpc): global upload_token global bucket if (upload_token == None) or int(upload_token.expiration) <= int(time.time()): response = client.describe_upload_token() upload_token = response.body.data auth = oss2.StsAuth(upload_token.access_key_id, upload_token.access_key_secret, upload_token.security_token) end_point = upload_token.oss_internet_end_point if (is_vpc): end_point = upload_token.oss_internal_end_point bucket = oss2.Bucket(auth, end_point, upload_token.bucket_name) def upload_file(file_name, is_vpc): get_oss_client(is_vpc) object_name = upload_token.file_name_prefix + str(uuid.uuid4()) + '.' + file_name.split('.')[-1] bucket.put_object_from_file(object_name, file_name) return object_name def video_moderation_by_local_file(file_path, is_vpc): # 1. Upload the file. object_name = upload_file(file_path, is_vpc) # 2. Detect the video. service_parameters = { 'dataId': str(uuid.uuid4()), 'ossBucketName': upload_token.bucket_name, 'ossObjectName': object_name } video_moderation_request = models.VideoModerationRequest( # Detection service: videoDetection_global service='videoDetection_global', service_parameters=json.dumps(service_parameters) ) # Create a RuntimeObject instance and set runtime parameters. runtime = util_models.RuntimeOptions() runtime.read_timeout = 10000 runtime.connect_timeout = 10000 try: global client response = client.video_moderation_with_options(video_moderation_request, runtime) if response.status_code == 200: # The call is successful. # Get the moderation result. result = response.body print('response success. result:{}'.format(result)) if result.code == 200: result_data = result.data print('result: {}'.format(result_data)) else: print('response not success. status:{} ,result:{}'.format(response.status_code, response)) except Exception as err: print(err) if __name__ == '__main__': # The path of the local file. file_path = 'D:/test/video/b652.mp4' # Specifies whether the service is deployed in a VPC. is_vpc = False # True video_moderation_by_local_file(file_path, is_vpc)Retrieve the results of a video moderation task
# coding=utf-8 # python version >= 3.6 from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config import json config = Config( # An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Use a Resource Access Management (RAM) user to call API operations or perform routine O&M for better security. # Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all your cloud resources. # Common methods to obtain environment variables: # Obtain the AccessKey ID of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain the AccessKey secret of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='Obtain the AccessKey ID of your RAM user from an environment variable.', access_key_secret='Obtain the AccessKey secret of your RAM user from an environment variable.', # The connection timeout period in milliseconds (ms). connect_timeout=3000, # The read timeout period in milliseconds (ms). read_timeout=6000, # Modify the region and endpoint as needed. region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) clt = Client(config) # The taskId that is returned when you submit the task. serviceParameters = { "taskId": 'vi_f_11w5THcbVYctjdxz2C0Afa-1x****' } videoModerationResultRequest = models.VideoModerationResultRequest( # Detection service: videoDetection_global service='videoDetection_global', service_parameters=json.dumps(serviceParameters) ) try: response = clt.video_moderation_result(videoModerationResultRequest) if response.status_code == 200: # The call is successful. # Get the moderation result. result = response.body print('response success. result:{}'.format(result)) else: print('response not success. status:{} ,result:{}'.format(response.status_code, response)) except Exception as err: print(err)Sample code for canceling a live stream moderation task
# coding=utf-8 # python version >= 3.6 from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config import json config = Config( # An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Use a Resource Access Management (RAM) user to call API operations or perform routine O&M for better security. # Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all your cloud resources. # Common methods to obtain environment variables: # Obtain the AccessKey ID of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain the AccessKey secret of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='Obtain the AccessKey ID of your RAM user from an environment variable.', access_key_secret='Obtain the AccessKey secret of your RAM user from an environment variable.', # The connection timeout period in milliseconds (ms). connect_timeout=10000, # The read timeout period in milliseconds (ms). read_timeout=3000, region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) clt = Client(config) # The taskId that is returned when you submit the task. serviceParameters = { "taskId": 'vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****' } videoModerationCancelRequest = models.VideoModerationCancelRequest( # Detection service service='liveStreamDetection_global', service_parameters=json.dumps(serviceParameters) ) try: response = clt.video_moderation_cancel(videoModerationCancelRequest) if response.status_code == 200: # The call is successful. result = response.body print('response success. result:{}'.format(result)) else: print('response not success. status:{} ,result:{}'.format(response.status_code, response)) except Exception as err: print(err)
Detect videos in OSS
Scenarios
If your video files are already stored in Alibaba Cloud Object Storage Service (OSS), you can create a service-linked role to grant Content Moderation access to your OSS resources. The Video Moderation V2.0 service uses this role to retrieve files from OSS for moderation. To create a service-linked role, go to the Cloud Resource Access Authorization page.
You can run the following command to install pip.
pip install alibabacloud_green20220302==2.2.11Use the Python SDK.
Sample code for submitting a video moderation task
#encoding:utf-8 # python version >= 3.6 from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config import json config = Config( # An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Use a Resource Access Management (RAM) user to call API operations or perform routine O&M for better security. # Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all your cloud resources. # Common methods to obtain environment variables: # Obtain the AccessKey ID of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain the AccessKey secret of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='Obtain the AccessKey ID of your RAM user from an environment variable.', access_key_secret='Obtain the AccessKey secret of your RAM user from an environment variable.', # The connection timeout period in milliseconds (ms). connect_timeout=3000, # The read timeout period in milliseconds (ms). read_timeout=6000, # Modify the region and endpoint as needed. region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) clt = Client(config) serviceParameters = { 'ossBucketName': 'bucket_01', 'ossObjectName': '20240307/07/28/test.flv', 'ossRegionId': 'ap-southeast-1' } videoModerationRequest = models.VideoModerationRequest( # Detection service: videoDetection_global service='videoDetection_global', service_parameters=json.dumps(serviceParameters) ) try: response = clt.video_moderation(videoModerationRequest) if response.status_code == 200: # The call is successful. # Get the moderation result. result = response.body print('response success. result:{}'.format(result)) else: print('response not success. status:{} ,result:{}'.format(response.status_code, response)) except Exception as err: print(err)Retrieve the results of a video moderation task
# coding=utf-8 # python version >= 3.6 from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config import json config = Config( # An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Use a Resource Access Management (RAM) user to call API operations or perform routine O&M for better security. # Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all your cloud resources. # Common methods to obtain environment variables: # Obtain the AccessKey ID of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain the AccessKey secret of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='Obtain the AccessKey ID of your RAM user from an environment variable.', access_key_secret='Obtain the AccessKey secret of your RAM user from an environment variable.', # The connection timeout period in milliseconds (ms). connect_timeout=3000, # The read timeout period in milliseconds (ms). read_timeout=6000, # Modify the region and endpoint as needed. region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) clt = Client(config) # The taskId that is returned when you submit the task. serviceParameters = { "taskId": 'vi_f_11w5THcbVYctjdxz2C0Afa-1x****' } videoModerationResultRequest = models.VideoModerationResultRequest( # Detection service: videoDetection_global service='videoDetection_global', service_parameters=json.dumps(serviceParameters) ) try: response = clt.video_moderation_result(videoModerationResultRequest) if response.status_code == 200: # The call is successful. # Get the moderation result. result = response.body print('response success. result:{}'.format(result)) else: print('response not success. status:{} ,result:{}'.format(response.status_code, response)) except Exception as err: print(err)Sample code to cancel a live video stream detection task
# coding=utf-8 # python version >= 3.6 from alibabacloud_green20220302.client import Client from alibabacloud_green20220302 import models from alibabacloud_tea_openapi.models import Config import json config = Config( # An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Use a Resource Access Management (RAM) user to call API operations or perform routine O&M for better security. # Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all your cloud resources. # Common methods to obtain environment variables: # Obtain the AccessKey ID of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'] # Obtain the AccessKey secret of a RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] access_key_id='Obtain the AccessKey ID of your RAM user from an environment variable.', access_key_secret='Obtain the AccessKey secret of your RAM user from an environment variable.', # The connection timeout period in milliseconds (ms). connect_timeout=10000, # The read timeout period in milliseconds (ms). read_timeout=3000, region_id='ap-southeast-1', endpoint='green-cip.ap-southeast-1.aliyuncs.com' ) clt = Client(config) # The taskId that is returned when you submit the task. serviceParameters = { "taskId": 'vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****' } videoModerationCancelRequest = models.VideoModerationCancelRequest( # Detection service service='liveStreamDetection_global', service_parameters=json.dumps(serviceParameters) ) try: response = clt.video_moderation_cancel(videoModerationCancelRequest) if response.status_code == 200: # The call is successful. result = response.body print('response success. result:{}'.format(result)) else: print('response not success. status:{} ,result:{}'.format(response.status_code, response)) except Exception as err: print(err)
PHP SDK
PHP 5.6 or later is supported.
For the source code, see PHP SDK source code.
The following three types of video moderation are supported.
Moderate a publicly accessible video
Scenarios
When a video to be moderated is accessible using a public URL, the Video Moderation Version 2.0 service can retrieve the file from its URL for moderation.
Run the following command to install the required dependencies using Composer.
composer require alibabacloud/green-20220302 2.2.10Integrate with the PHP SDK.
Sample code for submitting a video moderation task
<?php require('vendor/autoload.php'); use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationRequest; use AlibabaCloud\Tea\Exception\TeaUnableRetryError; use Darabonba\OpenApi\Models\Config; use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions; use AlibabaCloud\SDK\Green\V20220302\Green; $config = new Config([ /** * The AccessKey pair of an Alibaba Cloud account has access permissions for all APIs. We recommend that you use a RAM user for API access or routine O&M. * We strongly recommend that you do not hard-code the AccessKey ID and AccessKey secret into your project code. Otherwise, the AccessKey pair may be leaked and compromise the security of all the resources in your account. * Common ways to obtain environment variables: * Obtain the AccessKey ID of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => 'We recommend that you obtain the AccessKey ID of your RAM user from environment variables', "accessKeySecret" => 'We recommend that you obtain the AccessKey secret of your RAM user from environment variables', // Set an HTTP proxy. // "httpProxy" => "http://10.10.xx.xx:xxxx", // Set an HTTPS proxy. // "httpsProxy" => "https://10.10.xx.xx:xxxx", "endpoint" => "green-cip.ap-southeast-1.aliyuncs.com", "regionId" => "ap-southeast-1" ]); // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve moderation performance. $client = new Green($config); $request = new VideoModerationRequest(); // Moderation type: videoDetection_global for video file moderation, liveStreamDetection_global for live video stream moderation $request->service = "videoDetection_global"; $serviceParameters = array("url" => "https://xxx.oss.aliyuncs.com/xxx.mp4"); $request->serviceParameters = json_encode($serviceParameters); $runtime = new RuntimeOptions(); $runtime->readTimeout = 6000; $runtime->connectTimeout = 3000; try { $response = $client->videoModerationWithOptions($request, $runtime); print_r($response->body); if (200 != $response->statusCode) { print_r("response not success. code:" . $response->statusCode); return; } $body = $response->body; print_r("requestId = " . $body->requestId . "\n"); print_r("code = " . $body->code . "\n"); print_r("message = " . $body->message . "\n"); if (200 != $body->code) { print_r("video moderation not success. code:" . $body->code); } $data = $body->data; print_r("taskId = " . $data->taskId); } catch (TeaUnableRetryError $e) { var_dump($e->getMessage()); var_dump($e->getErrorInfo()); var_dump($e->getLastException()); var_dump($e->getLastRequest()); }Sample code for querying the result of a video moderation task
<?php require('vendor/autoload.php'); use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationResultRequest; use AlibabaCloud\Tea\Exception\TeaUnableRetryError; use Darabonba\OpenApi\Models\Config; use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions; use AlibabaCloud\SDK\Green\V20220302\Green; $config = new Config([ /** * The AccessKey pair of an Alibaba Cloud account has permissions for all API operations. We recommend that you use a RAM user for API calls or routine O&M. * We strongly recommend that you do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all resources in your account. * The following code shows how to retrieve environment variables: * Retrieve the AccessKey ID of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Retrieve the AccessKey secret of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => 'Retrieve the AccessKey ID of a RAM user from an environment variable.', "accessKeySecret" => 'Retrieve the AccessKey secret of a RAM user from an environment variable.', // Set the HTTP proxy. // "httpProxy" => "http://10.10.xx.xx:xxxx", // Set the HTTPS proxy. // "httpsProxy" => "https://10.10.xx.xx:xxxx", "endpoint" => "green-cip.ap-southeast-1.aliyuncs.com", "regionId" => "ap-southeast-1" ]); // Note: To improve moderation performance, we recommend that you reuse the instantiated client to avoid repeatedly establishing connections. $client = new Green($config); $request = new VideoModerationResultRequest(); // Moderation type: videoDetection for video file moderation, and liveStreamDetection for live video stream moderation. $request->service = "videoDetection_global"; $serviceParameters = array("taskId" => "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****"); $request->serviceParameters = json_encode($serviceParameters); $runtime = new RuntimeOptions(); $runtime->readTimeout = 6000; $runtime->connectTimeout = 3000; try { $response = $client->videoModerationResultWithOptions($request, $runtime); if (200 != $response->statusCode) { print_r("response not success. code:" . $response->statusCode); return; } $body = $response->body; print_r("requestId = " . $body->requestId . "\n"); print_r("code = " . $body->code . "\n"); print_r("message = " . $body->message . "\n"); if (280 == $body->code) { print_r("processing video moderation. code:" . $body->code); return; } if (200 != $body->code) { print_r("video moderation result not success. code:" . $body->code); return; } $data = $body->data; print_r("liveId = " . $data->liveId . "\n"); print_r("dataId = " . $data->dataId . "\n"); print_r("riskLevel = " . $data->RiskLevel . "\n"); print_r("audioResult = " . json_encode($data->audioResult) . "\n"); print_r("frameResult = " . json_encode($data->frameResult) . "\n"); } catch (TeaUnableRetryError $e) { var_dump($e->getMessage()); var_dump($e->getErrorInfo()); var_dump($e->getLastException()); var_dump($e->getLastRequest()); }Sample code for canceling a live stream moderation task
<?php require('vendor/autoload.php'); use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationCancelRequest; use AlibabaCloud\Tea\Exception\TeaUnableRetryError; use Darabonba\OpenApi\Models\Config; use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions; use AlibabaCloud\SDK\Green\V20220302\Green; $config = new Config([ /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * We strongly recommend that you do not hard-code the AccessKey ID and AccessKey secret into your project code. Otherwise, the AccessKey pair may be leaked and the security of all the resources in your account is compromised. * Common ways to obtain environment variables: * Obtain the AccessKey ID of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => 'We recommend that you obtain the AccessKey ID of your RAM user from environment variables', "accessKeySecret" => 'We recommend that you obtain the AccessKey secret of your RAM user from environment variables', // Configure an HTTP proxy. // "httpProxy" => "http://10.10.xx.xx:xxxx", // Configure an HTTPS proxy. // "httpsProxy" => "https://10.10.xx.xx:xxxx", "endpoint" => "green-cip.ap-southeast-1.aliyuncs.com", "regionId" => "ap-southeast-1" ]); // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve detection performance. $client = new Green($config); $request = new VideoModerationCancelRequest(); // The detection type. videoDetection indicates video file detection, and liveStreamDetection indicates live stream detection. $request->service = "liveStreamDetection_global"; $serviceParameters = array('taskId' => 'vi_s_lyxBXzWhSsxuJjiNHcpQ0N-*****'); $request->serviceParameters = json_encode($serviceParameters); $runtime = new RuntimeOptions(); $runtime->readTimeout = 6000; $runtime->connectTimeout = 3000; try { $response = $client->videoModerationCancel($request, $runtime); print_r($response->body); if (200 == $response->statusCode) { $body = $response->body; print_r("requestId = " . $body->requestId); print_r("code = " . $body->code); print_r("message = " . $body->message); if (200 != $body->code) { print_r("video moderation cancel not success. code:" . $body->code); } } else { print_r("response not success. code:" . $response->statusCode); } } catch (TeaUnableRetryError $e) { var_dump($e->getMessage()); var_dump($e->getErrorInfo()); var_dump($e->getLastException()); var_dump($e->getLastRequest()); }
Moderate a local video
Scenarios
If a video that you need to moderate is stored on a local machine and does not have a publicly accessible URL, you can upload the video to an Object Storage Service (OSS) bucket provided by Content Moderation. The Video Moderation V2.0 service can then directly access OSS to retrieve the video content and perform moderation.
Run the following command to install the required dependencies using Composer.
composer require alibabacloud/green-20220302 2.2.10Install the OSS SDK:
composer require aliyuncs/oss-sdk-phpIntegrate with the PHP SDK.
Sample code for submitting a video moderation task
<?php require('vendor/autoload.php'); use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationResponse; use AlibabaCloud\Tea\Utils\Utils; use Darabonba\OpenApi\Models\Config; use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions; use AlibabaCloud\SDK\Green\V20220302\Green; use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationRequest; use OSS\OssClient; // Specifies whether the service is deployed in a VPC. $isVPC = false; // The token for file uploads. $tokenArray = array(); // The client to upload files. $ossClient = null; /** * Create the client that initiates video moderation requests. * @param $accessKeyId * @param $accessKeySecret * @param $endpoint * @return Green */ function create_client($accessKeyId, $accessKeySecret, $endpoint): Green { $config = new Config([ "accessKeyId" => $accessKeyId, "accessKeySecret" => $accessKeySecret, // Configure an HTTP proxy. // "httpProxy" => "http://10.10.xx.xx:xxxx", // Configure an HTTPS proxy. // "httpsProxy" => "https://10.10.xx.xx:xxxx", "endpoint" => $endpoint, ]); return new Green($config); } /** * Create the client to upload files. * @param $tokenData * @return void */ function create_upload_client($tokenData): void { global $isVPC; global $ossClient; // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve moderation performance. if ($isVPC) { $ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternalEndPoint, false, $tokenData->securityToken); } else { $ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternetEndPoint, false, $tokenData->securityToken); } } /** * Upload a file. * @param $fileName * @param $tokenData * @return string * @throws \OSS\Core\OssException */ function upload_file($filePath, $tokenData): string { global $ossClient; //Initialize an OSSClient instance. create_upload_client($tokenData); $split = explode(".", $filePath); if (count($split) > 1) { $objectName = $tokenData->fileNamePrefix . uniqid() . "." . explode(".", $filePath)[count($split) - 1]; } else { $objectName = $tokenData->fileNamePrefix . uniqid(); } //Upload the file. $ossClient->uploadFile($tokenData->bucketName, $objectName, $filePath); return $objectName; } /** * Submit a moderation task. * @param $accessKeyId * @param $accessKeySecret * @param $endpoint * @return VideoModerationResponse * @throws \OSS\Core\OssException */ function invoke($accessKeyId, $accessKeySecret, $endpoint): VideoModerationResponse { global $tokenArray; // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and improve moderation performance. $client = create_client($accessKeyId, $accessKeySecret, $endpoint); // Create a RuntimeObject instance and configure runtime parameters. $runtime = new RuntimeOptions([]); // The full path of the local file. Example: D:\\localPath\\exampleFile.mp4. $filePath = "D:\\test\\video\\b652.mp4"; //Obtain a temporary token for uploading the file. if (!isset($tokenArray[$endpoint]) || $tokenArray[$endpoint]->expiration <= time()) { $token = $client->describeUploadToken(); $tokenArray[$endpoint] = $token->body->data; } // Upload the file. $objectName = upload_file($filePath, $tokenArray[$endpoint]); // Construct moderation parameters. $request = new VideoModerationRequest(); // Example: videoDetection_global $request->service = "videoDetection_global"; // The OSS information of the file to be moderated. $serviceParameters = array( 'ossObjectName' => $objectName, 'ossBucketName' => $tokenArray[$endpoint]->bucketName, 'dataId' => uniqid()); $request->serviceParameters = json_encode($serviceParameters); // Submit the moderation task. return $client->videoModerationWithOptions($request, $runtime); } /** * An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * We strongly recommend that you do not hard-code the AccessKey ID and AccessKey secret into your project code. Otherwise, the AccessKey pair may be leaked and the security of all the resources within your account is compromised. * Common ways to obtain environment variables: * Obtain the AccessKey ID of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ $accessKeyId = 'We recommend that you obtain the AccessKey ID of your RAM user from environment variables'; $accessKeySecret = 'We recommend that you obtain the AccessKey secret of your RAM user from environment variables'; // Change the region and endpoint as needed. $endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; try { $response = invoke($accessKeyId, $accessKeySecret, $endpoint); print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE)); } catch (Exception $e) { var_dump($e->getMessage()); var_dump($e->getErrorInfo()); var_dump($e->getLastException()); var_dump($e->getLastRequest()); }Sample code for querying the result of a video moderation task
<?php require('vendor/autoload.php'); use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationResultRequest; use AlibabaCloud\Tea\Exception\TeaUnableRetryError; use Darabonba\OpenApi\Models\Config; use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions; use AlibabaCloud\SDK\Green\V20220302\Green; $config = new Config([ /** * An AccessKey of an Alibaba Cloud account has access permissions for all APIs. We recommend that you use a RAM user to make API calls or perform routine O&M. * We strongly recommend that you do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all resources in your account. * Common ways to obtain environment variables: * Obtain the AccessKey ID of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of a RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => 'Obtain your RAM user\'s AccessKey ID from an environment variable', "accessKeySecret" => 'Obtain your RAM user\'s AccessKey secret from an environment variable', // Set an HTTP proxy. // "httpProxy" => "http://10.10.xx.xx:xxxx", // Set an HTTPS proxy. // "httpsProxy" => "https://10.10.xx.xx:xxxx", "endpoint" => "green-cip.ap-southeast-1.aliyuncs.com", "regionId" => "ap-southeast-1" ]); // Note: Reuse the instantiated client as much as possible to avoid repeatedly establishing connections and to improve moderation performance. $client = new Green($config); $request = new VideoModerationResultRequest(); // Moderation type: videoDetection for video file moderation, liveStreamDetection for live video stream moderation. $request->service = "videoDetection_global"; $serviceParameters = array("taskId" => "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****"); $request->serviceParameters = json_encode($serviceParameters); $runtime = new RuntimeOptions(); $runtime->readTimeout = 6000; $runtime->connectTimeout = 3000; try { $response = $client->videoModerationResultWithOptions($request, $runtime); if (200 != $response->statusCode) { print_r("response not success. code:" . $response->statusCode); return; } $body = $response->body; print_r("requestId = " . $body->requestId . "\n"); print_r("code = " . $body->code . "\n"); print_r("message = " . $body->message . "\n"); if (280 == $body->code) { print_r("processing video moderation. code:" . $body->code); return; } if (200 != $body->code) { print_r("video moderation result not success. code:" . $body->code); return; } $data = $body->data; print_r("liveId = " . $data->liveId . "\n"); print_r("dataId = " . $data->dataId . "\n"); print_r("riskLevel = " . $data->RiskLevel . "\n"); print_r("audioResult = " . json_encode($data->audioResult) . "\n"); print_r("frameResult = " . json_encode($data->frameResult) . "\n"); } catch (TeaUnableRetryError $e) { var_dump($e->getMessage()); var_dump($e->getErrorInfo()); var_dump($e->getLastException()); var_dump($e->getLastRequest()); }Sample code for canceling a live stream moderation task
<?php require('vendor/autoload.php'); use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationCancelRequest; use AlibabaCloud\Tea\Exception\TeaUnableRetryError; use Darabonba\OpenApi\Models\Config; use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions; use AlibabaCloud\SDK\Green\V20220302\Green; $config = new Config([ /** * The AccessKey pair of an Alibaba Cloud account has permissions for all API operations. We recommend that you use a RAM user to make API calls or perform routine O&M. * We strongly recommend that you do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all resources in your account. * Common ways to obtain environment variables: * Obtain the AccessKey ID of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Obtain the AccessKey secret of your RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => 'We recommend that you obtain the AccessKey ID of your RAM user from environment variables', "accessKeySecret" => 'We recommend that you obtain the AccessKey secret of your RAM user from environment variables', // Configure an HTTP proxy. // "httpProxy" => "http://10.10.xx.xx:xxxx", // Configure an HTTPS proxy. // "httpsProxy" => "https://10.10.xx.xx:xxxx", "endpoint" => "green-cip.ap-southeast-1.aliyuncs.com", "regionId" => "ap-southeast-1" ]); // Note: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and to improve moderation performance. $client = new Green($config); $request = new VideoModerationCancelRequest(); // Moderation type: videoDetection for video file moderation, and liveStreamDetection for live stream moderation. $request->service = "liveStreamDetection_global"; $serviceParameters = array('taskId' => 'vi_s_lyxBXzWhSsxuJjiNHcpQ0N-*****'); $request->serviceParameters = json_encode($serviceParameters); $runtime = new RuntimeOptions(); $runtime->readTimeout = 6000; $runtime->connectTimeout = 3000; try { $response = $client->videoModerationCancel($request, $runtime); print_r($response->body); if (200 == $response->statusCode) { $body = $response->body; print_r("requestId = " . $body->requestId); print_r("code = " . $body->code); print_r("message = " . $body->message); if (200 != $body->code) { print_r("video moderation cancel not success. code:" . $body->code); } } else { print_r("response not success. code:" . $response->statusCode); } } catch (TeaUnableRetryError $e) { var_dump($e->getMessage()); var_dump($e->getErrorInfo()); var_dump($e->getLastException()); var_dump($e->getLastRequest()); }
Moderate a video in OSS
Scenarios
If the video files that you want to moderate are stored in Alibaba Cloud Object Storage Service (OSS), you can create a service-linked role to grant the Content Moderation service access to OSS. The Video Moderation 2.0 service uses this service-linked role to retrieve files from OSS for moderation. Visit the Cloud Resource Access Authorization page to create the service-linked role.
Run the following command to install the required dependencies using Composer.
composer require alibabacloud/green-20220302 2.2.10Use the PHP SDK.
Sample code for submitting a video moderation task
<?php require('vendor/autoload.php'); use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationRequest; use AlibabaCloud\Tea\Exception\TeaUnableRetryError; use Darabonba\OpenApi\Models\Config; use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions; use AlibabaCloud\SDK\Green\V20220302\Green; $config = new Config([ /** * An AccessKey pair for an Alibaba Cloud account has full API access. For security, use a Resource Access Management (RAM) user for API calls and daily O&M. * Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be compromised, which threatens the security of all your resources. * Common ways to get environment variables: * Get the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Get the AccessKey secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => 'Obtain the AccessKey ID of the RAM user from an environment variable.', "accessKeySecret" => 'Obtain the AccessKey secret of the RAM user from an environment variable.', // Set the HTTP proxy. // "httpProxy" => "http://10.10.xx.xx:xxxx", // Set the HTTPS proxy. // "httpsProxy" => "https://10.10.xx.xx:xxxx", "endpoint" => "green-cip.ap-southeast-1.aliyuncs.com", "regionId" => "ap-southeast-1" ]); // Note: Reuse the instantiated client to avoid repeated connections and improve moderation performance. $client = new Green($config); $request = new VideoModerationRequest(); // Moderation type: videoDetection_global for video file moderation, liveStreamDetection_global for live stream moderation. $request->service = "videoDetection_global"; $serviceParameters = array( // The file to moderate. Example: video/001.mp4 'ossObjectName' => 'video/001.mp4', // The region of the bucket where the file is stored. Example: ap-southeast-1 'ossRegionId' => 'ap-southeast-1', // The name of the bucket where the file is stored. Example: bucket001 'ossBucketName' => 'bucket001', // The unique data ID. 'dataId' => uniqid()); $request->serviceParameters = json_encode($serviceParameters); $runtime = new RuntimeOptions(); $runtime->readTimeout = 6000; $runtime->connectTimeout = 3000; try { $response = $client->videoModerationWithOptions($request, $runtime); print_r($response->body); if (200 != $response->statusCode) { print_r("response not success. code:" . $response->statusCode); return; } $body = $response->body; print_r("requestId = " . $body->requestId . "\n"); print_r("code = " . $body->code . "\n"); print_r("message = " . $body->message . "\n"); if (200 != $body->code) { print_r("video moderation not success. code:" . $body->code); } $data = $body->data; print_r("taskId = " . $data->taskId); } catch (TeaUnableRetryError $e) { var_dump($e->getMessage()); var_dump($e->getErrorInfo()); var_dump($e->getLastException()); var_dump($e->getLastRequest()); }Sample code for retrieving the result of a video moderation task
<?php require('vendor/autoload.php'); use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationResultRequest; use AlibabaCloud\Tea\Exception\TeaUnableRetryError; use Darabonba\OpenApi\Models\Config; use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions; use AlibabaCloud\SDK\Green\V20220302\Green; $config = new Config([ /** * An AccessKey pair for an Alibaba Cloud account has full API access. For security, use a Resource Access Management (RAM) user for API calls and daily O&M. * Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be compromised, which threatens the security of all your resources. * Common ways to get environment variables: * Get the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Get the AccessKey secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => 'Obtain the AccessKey ID of the RAM user from an environment variable.', "accessKeySecret" => 'Obtain the AccessKey secret of the RAM user from an environment variable.', // Set the HTTP proxy. // "httpProxy" => "http://10.10.xx.xx:xxxx", // Set the HTTPS proxy. // "httpsProxy" => "https://10.10.xx.xx:xxxx", "endpoint" => "green-cip.ap-southeast-1.aliyuncs.com", "regionId" => "ap-southeast-1" ]); // Note: Reuse the instantiated client to avoid repeated connections and improve moderation performance. $client = new Green($config); $request = new VideoModerationResultRequest(); // Moderation type: videoDetection_global for video file moderation, liveStreamDetection_global for live stream moderation. $request->service = "videoDetection_global"; $serviceParameters = array("taskId" => "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****"); $request->serviceParameters = json_encode($serviceParameters); $runtime = new RuntimeOptions(); $runtime->readTimeout = 6000; $runtime->connectTimeout = 3000; try { $response = $client->videoModerationResultWithOptions($request, $runtime); if (200 != $response->statusCode) { print_r("response not success. code:" . $response->statusCode); return; } $body = $response->body; print_r("requestId = " . $body->requestId . "\n"); print_r("code = " . $body->code . "\n"); print_r("message = " . $body->message . "\n"); if (280 == $body->code) { print_r("processing video moderation. code:" . $body->code); return; } if (200 != $body->code) { print_r("video moderation result not success. code:" . $body->code); return; } $data = $body->data; print_r("liveId = " . $data->liveId . "\n"); print_r("dataId = " . $data->dataId . "\n"); print_r("riskLevel = " . $data->RiskLevel . "\n"); print_r("audioResult = " . json_encode($data->audioResult) . "\n"); print_r("frameResult = " . json_encode($data->frameResult) . "\n"); } catch (TeaUnableRetryError $e) { var_dump($e->getMessage()); var_dump($e->getErrorInfo()); var_dump($e->getLastException()); var_dump($e->getLastRequest()); }Sample code for canceling a live stream moderation task
<?php require('vendor/autoload.php'); use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationCancelRequest; use AlibabaCloud\Tea\Exception\TeaUnableRetryError; use Darabonba\OpenApi\Models\Config; use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions; use AlibabaCloud\SDK\Green\V20220302\Green; $config = new Config([ /** * An AccessKey pair for an Alibaba Cloud account has full API access. For security, use a Resource Access Management (RAM) user for API calls and daily O&M. * Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be compromised, which threatens the security of all your resources. * Common ways to get environment variables: * Get the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); * Get the AccessKey secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); */ "accessKeyId" => 'Obtain the AccessKey ID of the RAM user from an environment variable.', "accessKeySecret" => 'Obtain the AccessKey secret of the RAM user from an environment variable.', // Set the HTTP proxy. // "httpProxy" => "http://10.10.xx.xx:xxxx", // Set the HTTPS proxy. // "httpsProxy" => "https://10.10.xx.xx:xxxx", "endpoint" => "green-cip.ap-southeast-1.aliyuncs.com", "regionId" => "ap-southeast-1" ]); // Note: Reuse the instantiated client to avoid repeated connections and improve moderation performance. $client = new Green($config); $request = new VideoModerationCancelRequest(); // Moderation type: videoDetection_global for video file moderation, liveStreamDetection_global for live stream moderation. $request->service = "liveStreamDetection_global"; $serviceParameters = array('taskId' => 'vi_s_lyxBXzWhSsxuJjiNHcpQ0N-*****'); $request->serviceParameters = json_encode($serviceParameters); $runtime = new RuntimeOptions(); $runtime->readTimeout = 6000; $runtime->connectTimeout = 3000; try { $response = $client->videoModerationCancel($request, $runtime); print_r($response->body); if (200 == $response->statusCode) { $body = $response->body; print_r("requestId = " . $body->requestId); print_r("code = " . $body->code); print_r("message = " . $body->message); if (200 != $body->code) { print_r("video moderation cancel not success. code:" . $body->code); } } else { print_r("response not success. code:" . $response->statusCode); } } catch (TeaUnableRetryError $e) { var_dump($e->getMessage()); var_dump($e->getErrorInfo()); var_dump($e->getLastException()); var_dump($e->getLastRequest()); }
Go SDK
The following three types of video moderation are supported.
Moderate videos that are publicly accessible on the internet
Scenarios
If a video is accessible from a public URL, the Video Moderation 2.0 service can moderate the video by retrieving the file from the URL.
Run the following command to import the required dependencies.
go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2Use the Go SDK.
Sample code for submitting a video moderation task
package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green20220302 "github.com/alibabacloud-go/green-20220302/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { // Leaking project code may compromise the security of all resources in your account. We recommend that you use a more secure method, such as Security Token Service (STS), to access Alibaba Cloud services. The following sample code is for reference only. config := &openapi.Config{ /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all your resources. * You can obtain the credentials from environment variables. * To obtain the AccessKey ID of a RAM user, run os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"). * To obtain the AccessKey secret of a RAM user, run os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"). */ AccessKeyId: tea.String("Obtain the AccessKey ID of the RAM user from an environment variable."), AccessKeySecret: tea.String("Obtain the AccessKey secret of the RAM user from an environment variable."), // Set the HTTP proxy. // HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"), // Set the HTTPS proxy. // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"), RegionId: tea.String("ap-southeast-1"), Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"), /** * Set the timeout period. The server-side timeout period for a full-link request is 10 seconds. Set the timeout period as needed. * If the value of ReadTimeout is less than the server-side processing time, a ReadTimeout exception occurs. */ ConnectTimeout: tea.Int(3000), ReadTimeout: tea.Int(6000), } client, _err := green20220302.NewClient(config) if _err != nil { panic(_err) } // Create a RuntimeObject instance and set runtime parameters. runtime := &util.RuntimeOptions{} runtime.ReadTimeout = tea.Int(10000) runtime.ConnectTimeout = tea.Int(10000) serviceParameters, _ := json.Marshal( map[string]interface{}{ "url": "https://xxx.oss.aliyuncs.com/xxx.mp4", }, ) request := green20220302.VideoModerationRequest{ Service: tea.String("videoDetection_global"), ServiceParameters: tea.String(string(serviceParameters)), } result, _err := client.VideoModerationWithOptions(&request, runtime) if _err != nil { panic(_err) } if *result.StatusCode != http.StatusOK { fmt.Printf("response not success. status:%d\n", *result.StatusCode) return } body := result.Body fmt.Printf("response success. requestId:%s, code:%d, msg:%s\n", *body.RequestId, *body.Code, *body.Message) if *body.Code != http.StatusOK { fmt.Printf("video moderation not success. code:%d\n", *body.Code) return } data := body.Data fmt.Printf("video moderation taskId:%s\n", *data.TaskId) }Retrieve the result of a video moderation task
package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green20220302 "github.com/alibabacloud-go/green-20220302/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { // Leaking project code may compromise the security of all resources in your account. We recommend that you use a more secure method, such as Security Token Service (STS), to access Alibaba Cloud services. The following sample code is for reference only. config := &openapi.Config{ /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all your resources. * You can obtain the credentials from environment variables. * To obtain the AccessKey ID of a RAM user, run os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"). * To obtain the AccessKey secret of a RAM user, run os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"). */ AccessKeyId: tea.String("Obtain the AccessKey ID of the RAM user from an environment variable."), AccessKeySecret: tea.String("Obtain the AccessKey secret of the RAM user from an environment variable."), // Set the HTTP proxy. // HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"), // Set the HTTPS proxy. // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"), RegionId: tea.String("ap-southeast-1"), Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"), /** * Set the timeout period. The server-side timeout period for a full-link request is 10 seconds. Set the timeout period as needed. * If the value of ReadTimeout is less than the server-side processing time, a ReadTimeout exception occurs. */ ConnectTimeout: tea.Int(3000), ReadTimeout: tea.Int(6000), } client, _err := green20220302.NewClient(config) if _err != nil { panic(_err) } // Create a RuntimeObject instance and set runtime parameters. runtime := &util.RuntimeOptions{} runtime.ReadTimeout = tea.Int(10000) runtime.ConnectTimeout = tea.Int(10000) serviceParameters, _ := json.Marshal( map[string]interface{}{ "taskId": "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****", }, ) request := green20220302.VideoModerationResultRequest{ Service: tea.String("videoDetection_global"), ServiceParameters: tea.String(string(serviceParameters)), } result, _err := client.VideoModerationResultWithOptions(&request, runtime) if _err != nil { panic(_err) } if *result.StatusCode != http.StatusOK { fmt.Printf("response not success. status:%d\n", *result.StatusCode) return } body := result.Body fmt.Printf("response success. requestId:%s, code:%d, msg:%s\n", *body.RequestId, *body.Code, *body.Message) if *body.Code == 280 { fmt.Printf("processing video moderation. code:%d\n", *body.Code) return } if *body.Code != http.StatusOK { fmt.Printf("video moderation result not success. code:%d\n", *body.Code) return } data := body.Data fmt.Printf("video moderation result:%s\n", data) fmt.Printf("video moderation result audioResult:%s\n", data.AudioResult) fmt.Printf("video moderation result frameResult:%s\n", data.FrameResult) }Sample code for canceling a live stream moderation task
package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green20220302 "github.com/alibabacloud-go/green-20220302/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { // Leaking project code may compromise the security of all resources in your account. We recommend that you use a more secure method, such as Security Token Service (STS), to access Alibaba Cloud services. The following sample code is for reference only. config := &openapi.Config{ /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all your resources. * You can obtain the credentials from environment variables. * To obtain the AccessKey ID of a RAM user, run os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"). * To obtain the AccessKey secret of a RAM user, run os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"). */ AccessKeyId: tea.String("Obtain the AccessKey ID of the RAM user from an environment variable."), AccessKeySecret: tea.String("Obtain the AccessKey secret of the RAM user from an environment variable."), // Set the HTTP proxy. // HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"), // Set the HTTPS proxy. // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"), RegionId: tea.String("ap-southeast-1"), Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"), /** * Set the timeout period. The server-side timeout period for a full-link request is 10 seconds. Set the timeout period as needed. * If the value of ReadTimeout is less than the server-side processing time, a ReadTimeout exception occurs. */ ConnectTimeout: tea.Int(3000), ReadTimeout: tea.Int(6000), } client, _err := green20220302.NewClient(config) if _err != nil { panic(_err) } // Create a RuntimeObject instance and set runtime parameters. runtime := &util.RuntimeOptions{} runtime.ReadTimeout = tea.Int(10000) runtime.ConnectTimeout = tea.Int(10000) serviceParameters, _ := json.Marshal( map[string]interface{}{ "taskId": "vi_s_lyxBXzWhSsxuJjiNHcpQ0N-*****", }, ) request := green20220302.VideoModerationCancelRequest{ Service: tea.String("liveStreamDetection_global"), ServiceParameters: tea.String(string(serviceParameters)), } result, _err := client.VideoModerationCancelWithOptions(&request, runtime) if _err != nil { panic(_err) } if *result.StatusCode != http.StatusOK { fmt.Printf("response not success. status:%d\n", *result.StatusCode) return } body := result.Body fmt.Printf("response success. requestId:%s, code:%d, msg:%s\n", *body.RequestId, *body.Code, *body.Message) if *body.Code != http.StatusOK { fmt.Printf("video moderation cancel not success. code:%d\n", *body.Code) } }
Moderate local videos
Scenarios
If the video that you want to moderate is stored on a local machine and is not accessible over the Internet, you can upload the video to an Object Storage Service (OSS) bucket that is provided by Content Moderation. The Video Moderation 2.0 service can directly access OSS to retrieve and moderate the video.
Run the following commands to import the required dependencies.
go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2Install the OSS SDK:
go get github.com/aliyun/aliyun-oss-go-sdk/ossUse the Go SDK.
Sample code for submitting a video moderation task
package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green20220302 "github.com/alibabacloud-go/green-20220302/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "github.com/aliyun/aliyun-oss-go-sdk/oss" "github.com/google/uuid" "net/http" "os" "strings" "time" ) // The token used to upload the file. var TokenMap =make(map[string]*green20220302.DescribeUploadTokenResponseBodyData) // The client used to upload the file. var Bucket *oss.Bucket // Specifies whether the service is deployed in a VPC. var isVPC = false // Create a request client. func createClient(accessKeyId string, accessKeySecret string, endpoint string) (*green20220302.Client, error) { config := &openapi.Config{ AccessKeyId: tea.String(accessKeyId), AccessKeySecret: tea.String(accessKeySecret), // Set the HTTP proxy. // HttpProxy: tea.String("http://10.10.xx.xx:xxxx"), // Set the HTTPS proxy. // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"), Endpoint: tea.String(endpoint), } // Note: To improve moderation performance, reuse the instantiated client to avoid repeatedly establishing connections. return green20220302.NewClient(config); } // Create a client to upload files. func createOssClient(tokenData *green20220302.DescribeUploadTokenResponseBodyData) { if isVPC{ ossClient, err := oss.New(tea.StringValue(tokenData.OssInternalEndPoint), tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken))) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } Bucket, _ =ossClient.Bucket(tea.StringValue(tokenData.BucketName)); }else { ossClient, err := oss.New(tea.StringValue(tokenData.OssInternetEndPoint), tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken))) if err != nil { fmt.Println("Error:", err) os.Exit(-1) } Bucket, _ =ossClient.Bucket(tea.StringValue(tokenData.BucketName)); } } // Upload the file. func uploadFile(filePath string,tokenData *green20220302.DescribeUploadTokenResponseBodyData) (string,error) { createOssClient(tokenData) objectName := tea.StringValue(tokenData.FileNamePrefix) + uuid.New().String() + "." + strings.Split(filePath, ".")[1] // Upload the file. _err := Bucket.PutObjectFromFile(objectName, filePath) if _err != nil { fmt.Println("Error:", _err) os.Exit(-1) } return objectName,_err } func invoke(accessKeyId string, accessKeySecret string, endpoint string) (_result *green20220302.VideoModerationResponse, _err error) { // Note: To improve moderation performance, reuse the instantiated client to avoid repeatedly establishing connections. client, _err := createClient(accessKeyId, accessKeySecret, endpoint) if _err != nil { return nil,_err } // Set runtime parameters. The settings are valid only for requests that use the RuntimeOptions instance. runtime := &util.RuntimeOptions{} // The full path of the local file. Example: D:\localPath\exampleFile.mp4. var filePath = "D:\\localPath\\exampleFile.mp4" // Obtain a temporary token for file upload. tokenData,ok:=TokenMap[endpoint]; if !ok || tea.Int32Value(tokenData.Expiration) <= int32(time.Now().Unix()) { // Obtain a temporary token for file upload. uploadTokenResponse, _err := client.DescribeUploadToken() if _err != nil { return nil,_err } tokenData = uploadTokenResponse.Body.Data TokenMap[endpoint] = tokenData } var objectName, _ = uploadFile(filePath,TokenMap[endpoint]) // Construct a moderation request. serviceParameters, _ := json.Marshal( map[string]interface{}{ "ossBucketName": tea.StringValue(TokenMap[endpoint].BucketName), "ossObjectName": objectName, "dataId": uuid.New().String(), }, ) videoModerationRequest := &green20220302.VideoModerationRequest{ // Example: videoDetection_global Service: tea.String("videoDetection_global"), ServiceParameters: tea.String(string(serviceParameters)), } return client.VideoModerationWithOptions(videoModerationRequest, runtime) } func main() { /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all your resources. * You can obtain the credentials from environment variables. * To obtain the AccessKey ID of a RAM user, run os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"). * To obtain the AccessKey secret of a RAM user, run os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"). */ var accessKeyId= "Obtain the AccessKey ID of the RAM user from an environment variable."; var accessKeySecret= "Obtain the AccessKey secret of the RAM user from an environment variable."; // Modify the region and endpoint as needed. var endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; response,_err := invoke(accessKeyId,accessKeySecret,endpoint) flag := false if _err != nil { var err = &tea.SDKError{} if _t, ok := _err.(*tea.SDKError); ok { err = _t if *err.StatusCode == 500 { flag = true } } } if response == nil || *response.StatusCode == 500 || *response.Body.Code == 500 { flag = true } // Automatic routing. Switch the region to cn-beijing. if flag { endpoint = "green-cip.cn-beijing.aliyuncs.com"; response, _err = invoke(accessKeyId,accessKeySecret,endpoint) } if response != nil { statusCode := tea.IntValue(tea.ToInt(response.StatusCode)) body := response.Body videoModerationResponseData := body.Data fmt.Println("requestId:" + tea.StringValue(body.RequestId)) if statusCode == http.StatusOK { fmt.Println("response success. response:" + body.String()) if tea.IntValue(tea.ToInt(body.Code)) == 200 { result := videoModerationResponseData.Result fmt.Println("response dataId:" + tea.StringValue(videoModerationResponseData.DataId)) for i := 0; i < len(result); i++ { fmt.Println("response label:" + tea.StringValue(result[i].Label)) fmt.Println("response confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence))) } } else { fmt.Println("videomoderation not success. status" + tea.ToString(body.Code)) } } else { fmt.Print("response not success. status:" + tea.ToString(statusCode)) } } }Retrieve the result of a video moderation task
package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green20220302 "github.com/alibabacloud-go/green-20220302/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { // Leaking project code may compromise the security of all resources in your account. We recommend that you use a more secure method, such as Security Token Service (STS), to access Alibaba Cloud services. The following sample code is for reference only. config := &openapi.Config{ /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all your resources. * You can obtain the credentials from environment variables. * To obtain the AccessKey ID of a RAM user, run os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"). * To obtain the AccessKey secret of a RAM user, run os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"). */ AccessKeyId: tea.String("Obtain the AccessKey ID of the RAM user from an environment variable."), AccessKeySecret: tea.String("Obtain the AccessKey secret of the RAM user from an environment variable."), // Set the HTTP proxy. // HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"), // Set the HTTPS proxy. // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"), RegionId: tea.String("ap-southeast-1"), Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"), /** * Set the timeout period. The server-side timeout period for a full-link request is 10 seconds. Set the timeout period as needed. * If the value of ReadTimeout is less than the server-side processing time, a ReadTimeout exception occurs. */ ConnectTimeout: tea.Int(3000), ReadTimeout: tea.Int(6000), } client, _err := green20220302.NewClient(config) if _err != nil { panic(_err) } // Create a RuntimeObject instance and set runtime parameters. runtime := &util.RuntimeOptions{} runtime.ReadTimeout = tea.Int(10000) runtime.ConnectTimeout = tea.Int(10000) serviceParameters, _ := json.Marshal( map[string]interface{}{ "taskId": "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****", }, ) request := green20220302.VideoModerationResultRequest{ Service: tea.String("videoDetection_global"), ServiceParameters: tea.String(string(serviceParameters)), } result, _err := client.VideoModerationResultWithOptions(&request, runtime) if _err != nil { panic(_err) } if *result.StatusCode != http.StatusOK { fmt.Printf("response not success. status:%d\n", *result.StatusCode) return } body := result.Body fmt.Printf("response success. requestId:%s, code:%d, msg:%s\n", *body.RequestId, *body.Code, *body.Message) if *body.Code == 280 { fmt.Printf("processing video moderation. code:%d\n", *body.Code) return } if *body.Code != http.StatusOK { fmt.Printf("video moderation result not success. code:%d\n", *body.Code) return } data := body.Data fmt.Printf("video moderation result:%s\n", data) fmt.Printf("video moderation result audioResult:%s\n", data.AudioResult) fmt.Printf("video moderation result frameResult:%s\n", data.FrameResult) }Sample code for canceling a live stream moderation task
package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green20220302 "github.com/alibabacloud-go/green-20220302/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { // Leaking project code may compromise the security of all resources in your account. We recommend that you use a more secure method, such as Security Token Service (STS), to access Alibaba Cloud services. The following sample code is for reference only. config := &openapi.Config{ /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all your resources. * You can obtain the credentials from environment variables. * To obtain the AccessKey ID of a RAM user, run os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"). * To obtain the AccessKey secret of a RAM user, run os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"). */ AccessKeyId: tea.String("Obtain the AccessKey ID of the RAM user from an environment variable."), AccessKeySecret: tea.String("Obtain the AccessKey secret of the RAM user from an environment variable."), // Set the HTTP proxy. // HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"), // Set the HTTPS proxy. // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"), RegionId: tea.String("ap-southeast-1"), Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"), /** * Set the timeout period. The server-side timeout period for a full-link request is 10 seconds. Set the timeout period as needed. * If the value of ReadTimeout is less than the server-side processing time, a ReadTimeout exception occurs. */ ConnectTimeout: tea.Int(3000), ReadTimeout: tea.Int(6000), } client, _err := green20220302.NewClient(config) if _err != nil { panic(_err) } // Create a RuntimeObject instance and set runtime parameters. runtime := &util.RuntimeOptions{} runtime.ReadTimeout = tea.Int(10000) runtime.ConnectTimeout = tea.Int(10000) serviceParameters, _ := json.Marshal( map[string]interface{}{ "taskId": "vi_s_lyxBXzWhSsxuJjiNHcpQ0N-*****", }, ) request := green20220302.VideoModerationCancelRequest{ Service: tea.String("liveStreamDetection_global"), ServiceParameters: tea.String(string(serviceParameters)), } result, _err := client.VideoModerationCancelWithOptions(&request, runtime) if _err != nil { panic(_err) } if *result.StatusCode != http.StatusOK { fmt.Printf("response not success. status:%d\n", *result.StatusCode) return } body := result.Body fmt.Printf("response success. requestId:%s, code:%d, msg:%s\n", *body.RequestId, *body.Code, *body.Message) if *body.Code != http.StatusOK { fmt.Printf("video moderation cancel not success. code:%d\n", *body.Code) } }
Detecting OSS videos
Scenarios
If the video files that you want to moderate are stored in Alibaba Cloud OSS, you can create a service-linked role to grant Content Moderation the permissions to access OSS. The Video Moderation 2.0 service uses the service-linked role to retrieve the files from OSS and then moderates them. Go to the Cloud Resource Access Authorization page to create a service-linked role.
Run the following command to import the required dependencies.
go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2Use the Go SDK.
Sample code for submitting a video moderation task
package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green20220302 "github.com/alibabacloud-go/green-20220302/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { // Leaking project code may compromise the security of all resources in your account. We recommend that you use a more secure method, such as Security Token Service (STS), to access Alibaba Cloud services. The following sample code is for reference only. config := &openapi.Config{ /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all your resources. * You can obtain the credentials from environment variables. * To obtain the AccessKey ID of a RAM user, run os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"). * To obtain the AccessKey secret of a RAM user, run os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"). */ AccessKeyId: tea.String("Obtain the AccessKey ID of the RAM user from an environment variable."), AccessKeySecret: tea.String("Obtain the AccessKey secret of the RAM user from an environment variable."), // Set the HTTP proxy. // HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"), // Set the HTTPS proxy. // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"), RegionId: tea.String("ap-southeast-1"), Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"), /** * Set the timeout period. The server-side timeout period for a full-link request is 10 seconds. Set the timeout period as needed. * If the value of ReadTimeout is less than the server-side processing time, a ReadTimeout exception occurs. */ ConnectTimeout: tea.Int(3000), ReadTimeout: tea.Int(6000), } client, _err := green20220302.NewClient(config) if _err != nil { panic(_err) } // Create a RuntimeObject instance and set runtime parameters. runtime := &util.RuntimeOptions{} runtime.ReadTimeout = tea.Int(10000) runtime.ConnectTimeout = tea.Int(10000) serviceParameters, _ := json.Marshal( map[string]interface{}{ "ossBucketName": "bucket_01", "ossObjectName": "conect/xxx.mp4", "ossRegionId": "ap-southeast-1", }, ) request := green20220302.VideoModerationRequest{ Service: tea.String("videoDetection_global"), ServiceParameters: tea.String(string(serviceParameters)), } result, _err := client.VideoModerationWithOptions(&request, runtime) if _err != nil { panic(_err) } if *result.StatusCode != http.StatusOK { fmt.Printf("response not success. status:%d\n", *result.StatusCode) return } body := result.Body fmt.Printf("response success. requestId:%s, code:%d, msg:%s\n", *body.RequestId, *body.Code, *body.Message) if *body.Code != http.StatusOK { fmt.Printf("video moderation not success. code:%d\n", *body.Code) return } data := body.Data fmt.Printf("video moderation taskId:%s\n", *data.TaskId) }Retrieve the result of a video moderation task
package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green20220302 "github.com/alibabacloud-go/green-20220302/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { // Leaking project code may compromise the security of all resources in your account. We recommend that you use a more secure method, such as Security Token Service (STS), to access Alibaba Cloud services. The following sample code is for reference only. config := &openapi.Config{ /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all your resources. * You can obtain the credentials from environment variables. * To obtain the AccessKey ID of a RAM user, run os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"). * To obtain the AccessKey secret of a RAM user, run os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"). */ AccessKeyId: tea.String("Obtain the AccessKey ID of the RAM user from an environment variable."), AccessKeySecret: tea.String("Obtain the AccessKey secret of the RAM user from an environment variable."), // Set the HTTP proxy. // HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"), // Set the HTTPS proxy. // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"), RegionId: tea.String("ap-southeast-1"), Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"), /** * Set the timeout period. The server-side timeout period for a full-link request is 10 seconds. Set the timeout period as needed. * If the value of ReadTimeout is less than the server-side processing time, a ReadTimeout exception occurs. */ ConnectTimeout: tea.Int(3000), ReadTimeout: tea.Int(6000), } client, _err := green20220302.NewClient(config) if _err != nil { panic(_err) } // Create a RuntimeObject instance and set runtime parameters. runtime := &util.RuntimeOptions{} runtime.ReadTimeout = tea.Int(10000) runtime.ConnectTimeout = tea.Int(10000) serviceParameters, _ := json.Marshal( map[string]interface{}{ "taskId": "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****", }, ) request := green20220302.VideoModerationResultRequest{ Service: tea.String("videoDetection_global"), ServiceParameters: tea.String(string(serviceParameters)), } result, _err := client.VideoModerationResultWithOptions(&request, runtime) if _err != nil { panic(_err) } if *result.StatusCode != http.StatusOK { fmt.Printf("response not success. status:%d\n", *result.StatusCode) return } body := result.Body fmt.Printf("response success. requestId:%s, code:%d, msg:%s\n", *body.RequestId, *body.Code, *body.Message) if *body.Code == 280 { fmt.Printf("processing video moderation. code:%d\n", *body.Code) return } if *body.Code != http.StatusOK { fmt.Printf("video moderation result not success. code:%d\n", *body.Code) return } data := body.Data fmt.Printf("video moderation result:%s\n", data) fmt.Printf("video moderation result audioResult:%s\n", data.AudioResult) fmt.Printf("video moderation result frameResult:%s\n", data.FrameResult) }Sample code for canceling a live stream moderation task
package main import ( "encoding/json" "fmt" openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client" green20220302 "github.com/alibabacloud-go/green-20220302/client" util "github.com/alibabacloud-go/tea-utils/v2/service" "github.com/alibabacloud-go/tea/tea" "net/http" ) func main() { // Leaking project code may compromise the security of all resources in your account. We recommend that you use a more secure method, such as Security Token Service (STS), to access Alibaba Cloud services. The following sample code is for reference only. config := &openapi.Config{ /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all your resources. * You can obtain the credentials from environment variables. * To obtain the AccessKey ID of a RAM user, run os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"). * To obtain the AccessKey secret of a RAM user, run os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"). */ AccessKeyId: tea.String("Obtain the AccessKey ID of the RAM user from an environment variable."), AccessKeySecret: tea.String("Obtain the AccessKey secret of the RAM user from an environment variable."), // Set the HTTP proxy. // HttpProxy: tea.String("http://xx.xx.xx.xx:xxxx"), // Set the HTTPS proxy. // HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"), RegionId: tea.String("ap-southeast-1"), Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"), /** * Set the timeout period. The server-side timeout period for a full-link request is 10 seconds. Set the timeout period as needed. * If the value of ReadTimeout is less than the server-side processing time, a ReadTimeout exception occurs. */ ConnectTimeout: tea.Int(3000), ReadTimeout: tea.Int(6000), } client, _err := green20220302.NewClient(config) if _err != nil { panic(_err) } // Create a RuntimeObject instance and set runtime parameters. runtime := &util.RuntimeOptions{} runtime.ReadTimeout = tea.Int(10000) runtime.ConnectTimeout = tea.Int(10000) serviceParameters, _ := json.Marshal( map[string]interface{}{ "taskId": "vi_s_lyxBXzWhSsxuJjiNHcpQ0N-*****", }, ) request := green20220302.VideoModerationCancelRequest{ Service: tea.String("liveStreamDetection_global"), ServiceParameters: tea.String(string(serviceParameters)), } result, _err := client.VideoModerationCancelWithOptions(&request, runtime) if _err != nil { panic(_err) } if *result.StatusCode != http.StatusOK { fmt.Printf("response not success. status:%d\n", *result.StatusCode) return } body := result.Body fmt.Printf("response success. requestId:%s, code:%d, msg:%s\n", *body.RequestId, *body.Code, *body.Message) if *body.Code != http.StatusOK { fmt.Printf("video moderation cancel not success. code:%d\n", *body.Code) } }
C# SDK
For more information, see C# SDK source code.
The following three types of video moderation are supported.
Moderate publicly accessible videos
Scenarios
If the video you need to moderate is accessible through a public URL, the Video Moderation V2.0 service can moderate the video by fetching the file from the URL.
Run the following command to import the dependencies.
dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10Use the C# SDK.
Sample code for submitting a video moderation task
using Newtonsoft.Json; using Tea; namespace AlibabaCloud.SDK.Sample { public class Sample { /** * Use your AccessKey ID and AccessKey secret to initialize the client. * @param accessKeyId * @param accessKeySecret * @return Client * @throws Exception */ public static AlibabaCloud.SDK.Green20220302.Client CreateClient(string accessKeyId, string accessKeySecret) { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, }; // The endpoint of the service. config.Endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; return new AlibabaCloud.SDK.Green20220302.Client(config); } public static void Main(string[] args) { // Hard-coding your AccessKey pair in the project code may lead to leakage and compromise the security of all your resources. The following sample code is for reference only. For higher security, we recommend using Security Token Service (STS). /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all your resources. * Common ways to get environment variables: * Get the AccessKey ID of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey secret of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ string accessKeyId = "Get the AccessKey ID of a RAM user from an environment variable.", string accessKeySecret = 'Get the AccessKey secret of a RAM user from an environment variable.', // Note: Reuse the client instance as much as possible to improve moderation performance and avoid repeated connections. AlibabaCloud.SDK.Green20220302.Client client = CreateClient(accessKeyId, accessKeySecret); // Build a moderation request. AlibabaCloud.SDK.Green20220302.Models.VideoModerationRequest videoModerationRequest = new AlibabaCloud.SDK.Green20220302.Models.VideoModerationRequest(); // The moderation service. videoModerationRequest.Service="videoDetection_global"; Dictionary<String,Object> task=new Dictionary<string, object>(); // The URL of the video to moderate. The URL must be publicly accessible. task.Add("url","https://xxxx/xxx/sample.mp4"); videoModerationRequest.ServiceParameters=JsonConvert.SerializeObject(task); // Create a RuntimeObject instance and set runtime parameters. AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); runtime.ReadTimeout = 10000; runtime.ConnectTimeout = 10000; try { // Submit the moderation task. AlibabaCloud.SDK.Green20220302.Models.VideoModerationResponse response= client.VideoModerationWithOptions(videoModerationRequest, runtime); if(response is not null){ Console.WriteLine("response statusCode : "+response.StatusCode); if (response.Body is not null){ Console.WriteLine("requestId : " + response.Body.RequestId); Console.WriteLine("code : " + response.Body.Code); Console.WriteLine("message : " + response.Body.Message); if(response.Body.Data is not null){ Console.WriteLine("taskId : " + response.Body.Data.TaskId); } } } } catch (TeaException error) { // If an error occurs, print it. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } catch (Exception _error) { TeaException error = new TeaException(new Dictionary<string, object> { { "message", _error.Message } }); // If an error occurs, print it. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } } } }Sample code for retrieving the result of a video moderation task
using Newtonsoft.Json; using Tea; namespace AlibabaCloud.SDK.Sample { public class Sample { /** * Use your AccessKey ID and AccessKey secret to initialize the client. * @param accessKeyId * @param accessKeySecret * @return Client * @throws Exception */ public static AlibabaCloud.SDK.Green20220302.Client CreateClient(string accessKeyId, string accessKeySecret) { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, }; // The endpoint of the service. config.Endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; return new AlibabaCloud.SDK.Green20220302.Client(config); } public static void Main(string[] args) { // Hard-coding your AccessKey pair in the project code may lead to leakage and compromise the security of all your resources. The following sample code is for reference only. For higher security, we recommend using Security Token Service (STS). /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all your resources. * Common ways to get environment variables: * Get the AccessKey ID of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey secret of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ string accessKeyId = "Get the AccessKey ID of a RAM user from an environment variable.", string accessKeySecret = 'Get the AccessKey secret of a RAM user from an environment variable.', // Note: Reuse the client instance as much as possible to improve moderation performance and avoid repeated connections. AlibabaCloud.SDK.Green20220302.Client client = CreateClient(accessKeyId, accessKeySecret); // Build a moderation request. AlibabaCloud.SDK.Green20220302.Models.VideoModerationResultRequest videoModerationResultRequest = new AlibabaCloud.SDK.Green20220302.Models.VideoModerationResultRequest(); // The moderation service. videoModerationResultRequest.Service="videoDetection_global"; Dictionary<String,Object> task=new Dictionary<string, object>(); // The ID of the task whose result you want to query. task.Add("taskId","<The ID of the task whose result you want to query>"); videoModerationResultRequest.ServiceParameters=JsonConvert.SerializeObject(task); // Create a RuntimeObject instance and set runtime parameters. AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); runtime.ReadTimeout = 10000; runtime.ConnectTimeout = 10000; try { // Submit the moderation task. AlibabaCloud.SDK.Green20220302.Models.VideoModerationResultResponse response= client.VideoModerationResultWithOptions(videoModerationResultRequest, runtime); if(response is not null){ Console.WriteLine("response statusCode : "+response.StatusCode); if (response.Body is not null){ Console.WriteLine("requestId : " + response.Body.RequestId); Console.WriteLine("code : " + response.Body.Code); Console.WriteLine("message : " + response.Body.Message); if(response.Body.Data is not null){ Console.WriteLine("taskId : " + response.Body.Data.TaskId); Console.WriteLine("liveId : " + response.Body.Data.LiveId); Console.WriteLine("riskLevel : " + response.Body.Data.RiskLevel); Console.WriteLine("url : " + response.Body.Data.Url); Console.WriteLine("sliceDetails : " + JsonConvert.SerializeObject(response.Body.Data.SliceDetails)); } } } } catch (TeaException error) { // If an error occurs, print it. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } catch (Exception _error) { TeaException error = new TeaException(new Dictionary<string, object> { { "message", _error.Message } }); // If an error occurs, print it. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } } } }
Detecting a local video
Scenarios
If the video you need to moderate is on a local machine and does not have a public URL, you can upload the video to an Object Storage Service (OSS) bucket provided by Content Moderation. The Video Moderation V2.0 service can then directly access OSS to retrieve the video content and moderate it.
Run the following command to import the dependencies.
dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10Install the OSS SDK:
Install using NuGet 1. If NuGet is not installed in your Visual Studio, install it first. 2. In Visual Studio, create or open a project. Choose Tools > NuGet Package Manager > Manage NuGet Packages for Solution. 3. Search for aliyun.oss.sdk. In the search results, find Aliyun.OSS.SDK (for .NET Framework) or Aliyun.OSS.SDK.NetCore.Use the C# SDK.
Sample code for submitting a video moderation task
// This file is auto-generated, don't edit it. Thanks. using System; using Newtonsoft.Json; using Aliyun.OSS; namespace AlibabaCloud.SDK.Green20220302 { public class VideoModerationAutoRoute { // The token for file upload. public static Dictionary<String, Models.DescribeUploadTokenResponse> tokenDic = new Dictionary<String, Models.DescribeUploadTokenResponse>(); // The client for file upload. public static OssClient ossClient = null; // Specifies whether the service is deployed in a VPC. public static Boolean isVPC = false; public static void Main(string[] args) { /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all your resources. * Common ways to get environment variables: * Get the AccessKey ID of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey secret of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ String accessKeyId = "Get the AccessKey ID of a RAM user from an environment variable."; String accessKeySecret = "Get the AccessKey secret of a RAM user from an environment variable."; // Modify the region and endpoint as needed. String endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; Models.VideoModerationResponse response = invoke( accessKeyId, accessKeySecret, endpoint ); Console.WriteLine(response.Body.RequestId); Console.WriteLine(JsonConvert.SerializeObject(response.Body)); } // Create a request client. public static Client createClient( String accessKeyId, String accessKeySecret, String endpoint ) { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, // Set the HTTP proxy. //HttpProxy = "http://10.10.xx.xx:xxxx", // Set the HTTPS proxy. //HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999", // The endpoint of the service. Endpoint = endpoint, }; return new Client(config); } // Create a file upload client. private static OssClient getOssClient( Models.DescribeUploadTokenResponse tokenResponse, Boolean isVPC ) { var tokenData = tokenResponse.Body.Data; if (isVPC) { return new OssClient( tokenData.OssInternalEndPoint, tokenData.AccessKeyId, tokenData.AccessKeySecret, tokenData.SecurityToken ); } else { return new OssClient( tokenData.OssInternetEndPoint, tokenData.AccessKeyId, tokenData.AccessKeySecret, tokenData.SecurityToken ); } } // Upload the file. public static String uploadFile( String filePath, Models.DescribeUploadTokenResponse tokenResponse ) { // Create an OssClient instance. ossClient = getOssClient(tokenResponse, isVPC); var tokenData = tokenResponse.Body.Data; String objectName = tokenData.FileNamePrefix + Guid.NewGuid().ToString() + "." + filePath.Split(".").GetValue(1); // Upload the file. ossClient.PutObject(tokenData.BucketName, objectName, filePath); return objectName; } // Submit a moderation request. public static Models.VideoModerationResponse invoke( String accessKeyId, String accessKeySecret, String endpoint ) { // Note: Reuse the client instance as much as possible to improve moderation performance and avoid repeated connections. Client client = createClient(accessKeyId, accessKeySecret, endpoint); // Set runtime parameters. The settings take effect only on requests that use this runtime instance. AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); // The full path of the local file, for example, D:\\localPath\\exampleFile.mp4. String filePath = "D:\\localPath\\exampleFile.mp4"; try { // Get a temporary token for file upload. if ( !tokenDic.ContainsKey(endpoint) || tokenDic[endpoint].Body.Data.Expiration <= DateTimeOffset.Now.ToUnixTimeSeconds() ) { var tokenResponse = client.DescribeUploadToken(); tokenDic[endpoint] = tokenResponse; } // Upload the file. String objectName = uploadFile(filePath, tokenDic[endpoint]); // Build a moderation request. Models.VideoModerationRequest videoModerationRequest = new Models.VideoModerationRequest(); // service example: videoDetection_global videoModerationRequest.Service = "videoDetection_global"; Dictionary<string, object> task = new Dictionary<string, object>(); // The information about the file to moderate. task.Add("ossBucketName", tokenDic[endpoint].Body.Data.BucketName); task.Add("ossObjectName", objectName); // The ID of the data to moderate. task.Add("dataId", Guid.NewGuid().ToString()); videoModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task); // Call the API operation to get the moderation result. Models.VideoModerationResponse response = client.VideoModerationWithOptions( videoModerationRequest, runtimeOptions ); return response; } catch (Exception _err) { Console.WriteLine(_err); return null; } } } }Sample code for retrieving the result of a video moderation task
using Newtonsoft.Json; using Tea; namespace AlibabaCloud.SDK.Sample { public class Sample { /** * Use your AccessKey ID and AccessKey secret to initialize the client. * @param accessKeyId * @param accessKeySecret * @return Client * @throws Exception */ public static AlibabaCloud.SDK.Green20220302.Client CreateClient(string accessKeyId, string accessKeySecret) { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, }; // The endpoint of the service. config.Endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; return new AlibabaCloud.SDK.Green20220302.Client(config); } public static void Main(string[] args) { // Hard-coding your AccessKey pair in the project code may lead to leakage and compromise the security of all your resources. The following sample code is for reference only. For higher security, we recommend using Security Token Service (STS). /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all your resources. * Common ways to get environment variables: * Get the AccessKey ID of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey secret of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ string accessKeyId = "Get the AccessKey ID of a RAM user from an environment variable.", string accessKeySecret = 'Get the AccessKey secret of a RAM user from an environment variable.', // Note: Reuse the client instance as much as possible to improve moderation performance and avoid repeated connections. AlibabaCloud.SDK.Green20220302.Client client = CreateClient(accessKeyId, accessKeySecret); // Build a moderation request. AlibabaCloud.SDK.Green20220302.Models.VideoModerationResultRequest videoModerationResultRequest = new AlibabaCloud.SDK.Green20220302.Models.VideoModerationResultRequest(); // The moderation service. videoModerationResultRequest.Service="videoDetection_global"; Dictionary<String,Object> task=new Dictionary<string, object>(); // The ID of the task whose result you want to query. task.Add("taskId","<The ID of the task whose result you want to query>"); videoModerationResultRequest.ServiceParameters=JsonConvert.SerializeObject(task); // Create a RuntimeObject instance and set runtime parameters. AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); runtime.ReadTimeout = 10000; runtime.ConnectTimeout = 10000; try { // Submit the moderation task. AlibabaCloud.SDK.Green20220302.Models.VideoModerationResultResponse response= client.VideoModerationResultWithOptions(videoModerationResultRequest, runtime); if(response is not null){ Console.WriteLine("response statusCode : "+response.StatusCode); if (response.Body is not null){ Console.WriteLine("requestId : " + response.Body.RequestId); Console.WriteLine("code : " + response.Body.Code); Console.WriteLine("message : " + response.Body.Message); if(response.Body.Data is not null){ Console.WriteLine("taskId : " + response.Body.Data.TaskId); Console.WriteLine("riskLevel : " + response.Body.Data.RiskLevel); Console.WriteLine("liveId : " + response.Body.Data.LiveId); Console.WriteLine("url : " + response.Body.Data.Url); Console.WriteLine("sliceDetails : " + JsonConvert.SerializeObject(response.Body.Data.SliceDetails)); } } } } catch (TeaException error) { // If an error occurs, print it. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } catch (Exception _error) { TeaException error = new TeaException(new Dictionary<string, object> { { "message", _error.Message } }); // If an error occurs, print it. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } } } }
Moderate videos in OSS
Scenarios
If the video files you need to moderate are already stored in Alibaba Cloud Object Storage Service (OSS), you can create a service-linked role to allow the Content Moderation service to access OSS. The Video Moderation V2.0 service then uses the service-linked role to retrieve the files from OSS and moderate them. To create a service-linked role, go to the Cloud Resource Access Authorization page.
Run the following command to import the dependencies.
dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10Use the C# SDK.
Sample code for submitting a video moderation task
using Newtonsoft.Json; using Tea; namespace AlibabaCloud.SDK.Sample { public class Sample { /** * Use your AccessKey ID and AccessKey secret to initialize the client. * @param accessKeyId * @param accessKeySecret * @return Client * @throws Exception */ public static AlibabaCloud.SDK.Green20220302.Client CreateClient(string accessKeyId, string accessKeySecret) { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, }; // The endpoint of the service. config.Endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; return new AlibabaCloud.SDK.Green20220302.Client(config); } public static void Main(string[] args) { // Hard-coding your AccessKey pair in the project code may lead to leakage and compromise the security of all your resources. The following sample code is for reference only. For higher security, we recommend using Security Token Service (STS). /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all your resources. * Common ways to get environment variables: * Get the AccessKey ID of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey secret of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ string accessKeyId = "Get the AccessKey ID of a RAM user from an environment variable.", string accessKeySecret = 'Get the AccessKey secret of a RAM user from an environment variable.', // Note: Reuse the client instance as much as possible to improve moderation performance and avoid repeated connections. AlibabaCloud.SDK.Green20220302.Client client = CreateClient(accessKeyId, accessKeySecret); // Build a moderation request. AlibabaCloud.SDK.Green20220302.Models.VideoModerationRequest videoModerationRequest = new AlibabaCloud.SDK.Green20220302.Models.VideoModerationRequest(); // The moderation service. videoModerationRequest.Service="videoDetection_global"; Dictionary<String,Object> task=new Dictionary<string, object>(); // Example of passing OSS file parameters. task.Add("ossBucketName","bucket_01"); task.Add("ossObjectName","test/sample.wav"); task.Add("ossRegionId","ap-southeast-1"); videoModerationRequest.ServiceParameters=JsonConvert.SerializeObject(task); // Create a RuntimeObject instance and set runtime parameters. AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); runtime.ReadTimeout = 10000; runtime.ConnectTimeout = 10000; try { // Submit the moderation task. AlibabaCloud.SDK.Green20220302.Models.VideoModerationResponse response= client.VideoModerationWithOptions(videoModerationRequest, runtime); if(response is not null){ Console.WriteLine("response statusCode : "+response.StatusCode); if (response.Body is not null){ Console.WriteLine("requestId : " + response.Body.RequestId); Console.WriteLine("code : " + response.Body.Code); Console.WriteLine("message : " + response.Body.Message); if(response.Body.Data is not null){ Console.WriteLine("taskId : " + response.Body.Data.TaskId); } } } } catch (TeaException error) { // If an error occurs, print it. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } catch (Exception _error) { TeaException error = new TeaException(new Dictionary<string, object> { { "message", _error.Message } }); // If an error occurs, print it. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } } } }Sample code for retrieving the result of a video moderation task
using Newtonsoft.Json; using Tea; namespace AlibabaCloud.SDK.Sample { public class Sample { /** * Use your AccessKey ID and AccessKey secret to initialize the client. * @param accessKeyId * @param accessKeySecret * @return Client * @throws Exception */ public static AlibabaCloud.SDK.Green20220302.Client CreateClient(string accessKeyId, string accessKeySecret) { AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config { AccessKeyId = accessKeyId, AccessKeySecret = accessKeySecret, }; // The endpoint of the service. config.Endpoint = "green-cip.ap-southeast-1.aliyuncs.com"; return new AlibabaCloud.SDK.Green20220302.Client(config); } public static void Main(string[] args) { // Hard-coding your AccessKey pair in the project code may lead to leakage and compromise the security of all your resources. The following sample code is for reference only. For higher security, we recommend using Security Token Service (STS). /** * The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. * Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which threatens the security of all your resources. * Common ways to get environment variables: * Get the AccessKey ID of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID") * Get the AccessKey secret of a RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET") */ string accessKeyId = "Get the AccessKey ID of a RAM user from an environment variable.", string accessKeySecret = 'Get the AccessKey secret of a RAM user from an environment variable.', // Note: Reuse the client instance as much as possible to improve moderation performance and avoid repeated connections. AlibabaCloud.SDK.Green20220302.Client client = CreateClient(accessKeyId, accessKeySecret); // Build a moderation request. AlibabaCloud.SDK.Green20220302.Models.VideoModerationResultRequest videoModerationResultRequest = new AlibabaCloud.SDK.Green20220302.Models.VideoModerationResultRequest(); // The moderation service. videoModerationResultRequest.Service="videoDetection_global"; Dictionary<String,Object> task=new Dictionary<string, object>(); // The ID of the task whose result you want to query. task.Add("taskId","<The ID of the task whose result you want to query>"); videoModerationResultRequest.ServiceParameters=JsonConvert.SerializeObject(task); // Create a RuntimeObject instance and set runtime parameters. AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions(); runtime.ReadTimeout = 10000; runtime.ConnectTimeout = 10000; try { // Submit the moderation task. AlibabaCloud.SDK.Green20220302.Models.VideoModerationResultResponse response= client.VideoModerationResultWithOptions(videoModerationResultRequest, runtime); if(response is not null){ Console.WriteLine("response statusCode : "+response.StatusCode); if (response.Body is not null){ Console.WriteLine("requestId : " + response.Body.RequestId); Console.WriteLine("code : " + response.Body.Code); Console.WriteLine("message : " + response.Body.Message); if(response.Body.Data is not null){ Console.WriteLine("taskId : " + response.Body.Data.TaskId); Console.WriteLine("liveId : " + response.Body.Data.LiveId); Console.WriteLine("riskLevel : " + response.Body.Data.RiskLevel); Console.WriteLine("url : " + response.Body.Data.Url); Console.WriteLine("sliceDetails : " + JsonConvert.SerializeObject(response.Body.Data.SliceDetails)); } } } } catch (TeaException error) { // If an error occurs, print it. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } catch (Exception _error) { TeaException error = new TeaException(new Dictionary<string, object> { { "message", _error.Message } }); // If an error occurs, print it. AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message); Console.WriteLine("error : " + error); } } } }
Node.js SDK
For the source code, see the Node.js SDK source code.
The following three types of video moderation are supported.
Moderate a publicly accessible video
Scenarios
If a video is accessible from a public URL, the Video Moderation V2.0 service can moderate the video by retrieving the file from its URL.
Run the following command to import the required dependencies.
npm install @alicloud/green20220302@2.2.10Use the Node.js SDK.
Sample code for submitting a video moderation task
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve moderation performance, reuse the instantiated client to avoid repeatedly establishing connections. // Leaking your project code can expose your AccessKey. This compromises the security of all resources in your account. The following sample code is for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Set the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Set the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: `green-cip.ap-southeast-1.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Create the request object. const videoModerationRequest = new Green20220302.VideoModerationRequest({ // The video moderation service. "service": "videoDetection_global", // The URL of the video to moderate. "serviceParameters": JSON.stringify({"url":"http://aliyundoc.com/test.flv"}) }); // Create a runtime configuration object. const runtime = new Util.RuntimeOptions(); try { // Send the request and get the response. const response = await client.videoModerationWithOptions(videoModerationRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // This code is for demonstration only. Handle exceptions with caution. Do not ignore exceptions in your project. // Error message. console.log('Error occurred:', error.message); } } } Client.main();Sample code for retrieving the result of a video moderation task
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve moderation performance, reuse the instantiated client to avoid repeatedly establishing connections. // Leaking your project code can expose your AccessKey. This compromises the security of all resources in your account. The following sample code is for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Set the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Set the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: `green-cip.ap-southeast-1.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Create the request object. const videoModerationResultRequest = new Green20220302.VideoModerationResultRequest({ // The video moderation service. "service": "videoDetection_global", "serviceParameters": JSON.stringify({"taskId":"<The ID of the task whose result you want to get>"}) }); // Create a runtime configuration object. const runtime = new Util.RuntimeOptions(); try { // Send the request and get the response. const response = await client.videoModerationResultWithOptions(videoModerationResultRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // This code is for demonstration only. Handle exceptions with caution. Do not ignore exceptions in your project. // Error message. console.log('Error occurred:', error.message); } } } Client.main();
Moderate a local video
Scenarios
If the video you need to moderate is on a local machine and does not have a public URL, you can upload the video to an OSS bucket provided by Content Moderation. The Video Moderation V2.0 service can then directly access OSS to retrieve the video content and moderate it.
Run the following command to import the required dependencies.
npm install @alicloud/green20220302@2.2.10Use the Node.js SDK.
Sample code for submitting a video moderation task
const RPCClient = require("@alicloud/pop-core"); const OSS = require('ali-oss'); const { v4: uuidv4 } = require('uuid'); const path = require("path"); // Specifies whether the service is deployed in a VPC. var isVPC = false; // The token for file upload. var tokenDic = new Array(); // The client for file upload. var ossClient; // Create a client for file upload. function createClient(accessKeyId, accessKeySecret, endpoint) { return new RPCClient({ accessKeyId: accessKeyId, accessKeySecret: accessKeySecret, endpoint: endpoint, apiVersion: '2022-03-02', // Set an HTTP proxy. //httpProxy: "http://xx.xx.xx.xx:xxxx", // Set an HTTPS proxy. //httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999", }); } // Create a client for file upload. function getOssClient(tokenData, isVPC) { if (isVPC) { ossClient = new OSS({ accessKeyId: tokenData['AccessKeyId'], accessKeySecret: tokenData['AccessKeySecret'], stsToken: tokenData['SecurityToken'], endpoint: tokenData['OssInternalEndPoint'], bucket: tokenData['BucketName'], }); } else { ossClient = new OSS({ accessKeyId: tokenData['AccessKeyId'], accessKeySecret: tokenData['AccessKeySecret'], stsToken: tokenData['SecurityToken'], endpoint: tokenData['OssInternetEndPoint'], bucket: tokenData['BucketName'], }); } } // Submit a moderation task. async function invoke(accessKeyId, accessKeySecret, endpoint) { // Note: To improve moderation performance, reuse the instantiated client to avoid repeatedly establishing connections. var client = createClient(accessKeyId, accessKeySecret, endpoint); var requestOption = { method: 'POST', formatParams: false, }; // The full path of the local file. Example: D:\\localPath\\exampleFile.mp4. var filePath = 'D:\\localPath\\exampleFile.mp4'; // Get the token for file upload. if (tokenDic[endpoint] == null || tokenDic[endpoint]['Expiration'] <= Date.parse(new Date() / 1000)) { var tokenResponse = await client.request('DescribeUploadToken', '', requestOption) tokenDic[endpoint] = tokenResponse.Data; } // Get the client for file upload. getOssClient(tokenDic[endpoint], isVPC) var split = filePath.split("."); var objectName; if (split.length > 1) { objectName = tokenDic[endpoint].FileNamePrefix + uuidv4() + "." + split[split.length - 1]; } else { objectName = tokenDic[endpoint].FileNamePrefix + uuidv4(); } // Upload the file. const result = await ossClient.put(objectName, path.normalize(filePath)); // Create a moderation API request and set the parameters. var params = { // The video moderation service. Example: videoDetection_global "Service": "videoDetection_global", // Information about the uploaded local video. "ServiceParameters": JSON.stringify({ "ossBucketName": tokenDic[endpoint].BucketName, "ossObjectName": objectName }) } // Call the API operation to get the moderation result. return await client.request('VideoModeration', params, requestOption); } function main() { /** * An AccessKey of an Alibaba Cloud account has permissions for all API operations. Use a RAM user for API access or daily O&M. * Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey may be leaked, which compromises the security of all resources in your account. * Common ways to get environment variables: * Get the AccessKey ID of a RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'] * Get the AccessKey secret of a RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] */ const accessKeyId: 'Get the AccessKey ID of the RAM user from an environment variable.' const accessKeySecret: 'Get the AccessKey secret of the RAM user from an environment variable.' // Modify the region and endpoint as needed. var endpoint = "https://green-cip.ap-southeast-1.aliyuncs.com" try { var response; // Call the API operation to get the moderation result. invoke(accessKeyId, accessKeySecret, endpoint).then(function (response) { console.log(JSON.stringify(response)) }) } catch (err) { console.log(err); } } main();Sample code for retrieving the result of a video moderation task
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve moderation performance, reuse the instantiated client to avoid repeatedly establishing connections. // Leaking your project code can expose your AccessKey. This compromises the security of all resources in your account. The following sample code is for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Set the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Set the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: `green-cip.ap-southeast-1.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Create the request object. const videoModerationResultRequest = new Green20220302.VideoModerationResultRequest({ // The video moderation service. "service": "videoDetection_global", "serviceParameters": JSON.stringify({"taskId":"<The ID of the task whose result you want to get>"}) }); // Create a runtime configuration object. const runtime = new Util.RuntimeOptions(); try { // Send the request and get the response. const response = await client.videoModerationResultWithOptions(videoModerationResultRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // This code is for demonstration only. Handle exceptions with caution. Do not ignore exceptions in your project. // Error message. console.log('Error occurred:', error.message); } } } Client.main();
Moderate a video in OSS
Scenarios
If the video file you need to moderate is already stored in Alibaba Cloud OSS, you can create a service-linked role and grant Content Moderation the permissions to access OSS. The Video Moderation V2.0 service uses the service-linked role to retrieve the file from OSS and then moderates it. To create a service-linked role, go to the Cloud Resource Access Authorization page.
Run the following command to import the required dependencies.
npm install @alicloud/green20220302@2.2.10Use the Node.js SDK.
Sample code for submitting a video moderation task
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve moderation performance, reuse the instantiated client to avoid repeatedly establishing connections. // Leaking your project code can expose your AccessKey. This compromises the security of all resources in your account. The following sample code is for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Set the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Set the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: `green-cip.ap-southeast-1.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Create the request object. const videoModerationRequest = new Green20220302.VideoModerationRequest({ // The video moderation service. "service": "videoDetection_global", // The URL of the video to moderate. "serviceParameters": JSON.stringify({ // The region where the bucket of the file to moderate is located. Example: cn-shanghai "ossRegionId": "cn-shanghai", // The name of the bucket where the file to moderate is located. Example: bucket001 "ossBucketName": "bucket001", // The file to moderate. Example: video/001.mp4 "ossObjectName": "video/001.mp4",}) }); // Create a runtime configuration object. const runtime = new Util.RuntimeOptions(); try { // Send the request and get the response. const response = await client.videoModerationWithOptions(videoModerationRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // This code is for demonstration only. Handle exceptions with caution. Do not ignore exceptions in your project. // Error message. console.log('Error occurred:', error.message); } } } Client.main();Sample code for retrieving the result of a video moderation task
const Green20220302 = require('@alicloud/green20220302'); const OpenApi = require('@alicloud/openapi-client'); const Util = require('@alicloud/tea-util'); // Note: To improve moderation performance, reuse the instantiated client to avoid repeatedly establishing connections. // Leaking your project code can expose your AccessKey. This compromises the security of all resources in your account. The following sample code is for reference only. class Client { static createClient() { const config = new OpenApi.Config({ // Required. Set the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable. accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'], // Required. Set the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable. accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'], endpoint: `green-cip.ap-southeast-1.aliyuncs.com`, }); return new Green20220302.default(config); } static async main() { const client = Client.createClient(); // Create the request object. const videoModerationResultRequest = new Green20220302.VideoModerationResultRequest({ // The video moderation service. "service": "videoDetection_global", "serviceParameters": JSON.stringify({"taskId":"<The ID of the task whose result you want to get>"}) }); // Create a runtime configuration object. const runtime = new Util.RuntimeOptions(); try { // Send the request and get the response. const response = await client.videoModerationResultWithOptions(videoModerationResultRequest, runtime); console.log(JSON.stringify(response.body)); } catch (error) { // This code is for demonstration only. Handle exceptions with caution. Do not ignore exceptions in your project. // Error message. console.log('Error occurred:', error.message); } } } Client.main();
Native HTTPS calls
Call Details
Request endpoint: https://green-cip.{region}.aliyuncs.com
Protocol: HTTPS
Method: POST
Common Request Parameters
API requests for Video Moderation Version 2.0 include common request parameters and operation-specific request parameters. The following table describes the common request parameters.
Name
Type
Required
Description
Format
String
Yes
The format of the response. Valid values:
JSON (default)
XML
Version
String
Yes
The API version number. Use the YYYY-MM-DD format. The current version is 2022-03-02.
AccessKeyId
String
Yes
The AccessKey ID issued by Alibaba Cloud to access the service.
Signature
String
Yes
The signature string. For information about how to calculate the signature, see the Signature method section below.
SignatureMethod
String
Yes
The signature method. Only HMAC-SHA1 is supported.
Timestamp
String
Yes
The timestamp of the request. The timestamp must be in UTC and formatted according to the ISO 8601 standard.
The format is yyyy-MM-ddTHH:mm:ssZ.
For example, 09:13:14 on December 12, 2022 (UTC+8) is represented as 2022-12-12T01:13:14Z.
SignatureVersion
String
Yes
The signature algorithm version. The value is 1.0.
SignatureNonce
String
Yes
A unique random number used to prevent replay attacks. Use a different random number for each request.
Action
String
Yes
Valid values:
VideoModeration
VideoModerationResult
Common Response Parameters
Each API call returns a unique identifier (RequestId), regardless of whether the call is successful. Other response parameters vary based on the API operation called.
{ "RequestId":"20B935A9-XXXXXXXX-XXXXXXXX0C2", "Message":"SUCCESS", "Data":{ "TaskId":"vi_f_O5xxxxxxxxxxxxxxqa-1****" }, "Code":200 }Code Examples
The following response examples are formatted for readability. The actual responses do not include line breaks or indents.
Sample request
Example request
http://green-cip.ap-southeast-1.aliyuncs.com/ ?Format=JSON &Version=2022-03-02 &Signature=vpEEL0zFHfxXYzSFV0n7%2FZiFL9o%3D &SignatureMethod=Hmac-SHA1 &SignatureNonce=15215528852396 &SignatureVersion=1.0 &Action=VideoModeration &AccessKeyId=123****cip &Timestamp=2023-02-03T12:00:00Z &Service=videoDetection_global &ServiceParameters={"url": "https://xxxxxx.aliyuncs.com/sample/****.mp4"}Sample success response
{ "RequestId":"20B935A9-XXXXXXXX-XXXXXXXX0C2", "Message":"SUCCESS", "Data":{ "TaskId":"vi_f_O5xxxxxxxxxxxxxxqa-1x****" }, "Code":200 }Sample request
Sample request
http://green-cip.ap-southeast-1.aliyuncs.com/ ?Format=JSON &Version=2022-03-02 &Signature=vpEEL0zFHfxXYzSFV0n7%2FZiFL9o%3D &SignatureMethod=Hmac-SHA1 &SignatureNonce=15215528852396 &SignatureVersion=1.0 &Action=VideoModerationResult &AccessKeyId=123****cip &Timestamp=2023-02-03T12:00:00Z &Service=videoDetection_global &ServiceParameters={"taskId": "vi_f_O5zxxxxxxxxxxxxxxxx-1x****"}Sample success response
{ "Code": 200, "RequestId": "25106421-XXXX-XXXX-XXXX-15DA5AAAC546", "Message": "success finished", "Data": { "DataId": "ABCDEF-TESTDATAID", "TaskId": "vi_f_VnI6BO74NXFIZm7XXXXXXXXXXXXXX", "RiskLevel": "medium", "FrameResult": { "FrameNum": 2, "FrameSummarys": [ { "Label": "violent_explosion", "Description": "Suspected fireworks content.", "LabelSum": 8 }, { "Label": "sexual_cleavage", "Description": "Suspected content with nudity or suggestive elements.", "LabelSum": 8 } ], "RiskLevel": "medium", "Frames": [ { "Offset": 1, "RiskLevel": "none", "Results": [ { "Result": [ { "Label": "nonLabel", "Description": "No threats detected." } ], "Service": "baselineCheck" }, { "Result": [ { "Label": "nonLabel" } ], "Service": "baselineCheck_pro" } ], "TempUrl": "http://abc.oss-cn-shanghai.aliyuncs.com/test1.jpg" }, { "Offset": 2, "RiskLevel": "medium", "Results": [ { "Result": [ { "Confidence": 74.1, "Label": "violent_explosion", "Description": "Suspected fireworks content." } ], "Service": "baselineCheck" }, { "Result": [ { "Confidence": 1, "Label": "sexual_cleavage", "Description": "Suspected content with nudity or suggestive elements." } ], "Service": "baselineCheck_pro" } ], "TempUrl": "http://abc.oss-cn-shanghai.aliyuncs.com/test2.jpg" } ] } } }
Signature Method
The Video Moderation Version 2.0 service authenticates each request. You must include a signature (Signature) in your request. The service uses an AccessKey ID and an AccessKey secret for symmetric encryption to verify the sender's identity.
Alibaba Cloud issues the AccessKey ID and AccessKey secret. You can request and manage them on the Alibaba Cloud website. The AccessKey ID identifies the user. The AccessKey secret is used to encrypt the signature string and verify the signature string on the server. You must keep your AccessKey secret confidential.
To sign a request, follow these steps:
Use the request parameters to create a canonicalized query string.
Sort all request parameters alphabetically by name. This includes common request parameters and operation-specific parameters, but not the Signature parameter itself.
URL-encode the names and values of the sorted parameters using the UTF-8 character set.
NoteLibraries that support URL encoding, such as `java.net.URLEncoder` in Java, typically encode according to the `application/x-www-form-urlencoded` Multipurpose Internet Mail Extensions (MIME) type rules. You can use these libraries for encoding. After encoding, replace plus signs (+) with `%20`, asterisks (*) with `%2A`, and `%7E` back to tildes (~) to obtain the required encoded string.
The URL encoding rules are as follows:
Do not encode uppercase letters (A-Z), lowercase letters (a-z), digits (0-9), hyphens (-), underscores (_), periods (.), or tildes (~).
Encode other characters into the
%XYformat, where XY is the two-digit hexadecimal representation of the character's ASCII code. For example, a double quotation mark (") is encoded as%22.Encode extended UTF-8 characters into the
%XY%ZA…format.A space ( ) must be encoded as
%20, not as a plus sign (+).
Connect the encoded parameter name and its value with an equal sign (=).
Concatenate the key-value pairs from the previous step using ampersands (&) in alphabetical order of the parameter names. This creates the canonicalized query string.
Use the canonicalized query string to construct the string-to-sign in the following format:
StringToSign= HTTPMethod + "&" + percentEncode("/") + "&" + percentEncode(CanonicalizedQueryString)NoteHTTPMethod is the HTTP method used for the request, such as POST. `percentEncode(/)` is the value obtained by URL-encoding the forward slash (/) character according to the rules in step 1.b, which is
%2F. `percentEncode(CanonicalizedQueryString)` is the string obtained by URL-encoding the canonicalized query string from step 1 according to the rules in step 1.b.Calculate the HMAC value of the string-to-sign as defined in RFC2104.
NoteThe key used for the calculation is your AccessKey secret appended with an ampersand (
&) character (ASCII code 38). The hash algorithm is SHA1.Base64-encode the HMAC value to obtain the signature string (Signature).
Add the resulting signature string to the request as the `Signature` parameter. This completes the request signing process.
NoteWhen you submit the signature value to the Content Moderation server, it must be URL-encoded in the same way as other parameters, according to RFC3986.