Video Moderation 2.0 supports integration via software development kits (SDKs) and native HTTPS requests. SDKs handle signature verification and request formatting automatically, so use an SDK unless you have a specific reason to call the API directly.
How it works
Video moderation uses an asynchronous two-step API:
Submit a task — call
VideoModerationwith your video source and the target service name. The API returns ataskId.Poll for results — call
VideoModerationResultwith thetaskIdto retrieve the moderation outcome. CheckriskLevel,audioResult, andframeResultin the response.
For live streams, call VideoModerationCancel to stop an in-progress moderation task.
All examples in this guide use the videoDetection_global or liveStreamDetection_global service name to submit tasks.
Prerequisites
Before you begin, ensure that you have:
Activated the Content Moderation service
Created a RAM user with the
AliyunYundunGreenWebFullAccesspolicyCreated an AccessKey pair for the RAM user
Configured
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRETas environment variables
Step 1: Activate the service
Go to the Activate Content Moderation 2.0 service page. After activation, billing defaults to pay-as-you-go — daily fees apply only when you call the API. For billing details, see Billing.
Step 2: Grant permissions to a RAM user
Grant permissions to a Resource Access Management (RAM) user and create an AccessKey pair for authentication when calling Alibaba Cloud API operations. For more information, see Obtain an AccessKey pair.
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.
Step 3: Install the SDK and integrate
Supported regions and endpoints
| 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) | green-cip.us-east-1.aliyuncs.com | green-cip-vpc.us-east-1.aliyuncs.com | videoDetection_global, liveStreamDetection_global |
| US (Silicon Valley) | green-cip.us-west-1.aliyuncs.com | Not available | — |
| Germany (Frankfurt) | green-cip.eu-central-1.aliyuncs.com | Not available | — |
For SDK samples in other programming languages, use OpenAPI Explorer to auto-generate code. The following API operations are available for online debugging:
Submit a video moderation task
Query the results of a video moderation task
Cancel a live stream moderation task
Set the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables before running the samples. The SDK reads these variables automatically for authentication. For more information, see Configure credentials.
For API parameter details, see Video File Moderation 2.0 API and Live Stream Moderation 2.0 API.
SDK for Java
Java 1.8 or later is required.
Source code: SDK source code for Java or SDK source code for Java (OSS path).
Add the following dependency to your pom.xml:
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>green20220302</artifactId>
<version>2.2.11</version>
</dependency>Detect videos accessible over the internet
If the video has a publicly accessible URL, Video Moderation 2.0 fetches the file directly from that URL.2.02.02.02.02.02.02.02.02.02.02.02.02.02.02.02.02.02.0
Submit a 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 methods to obtain environment variables:
* Method 1:
* Obtain the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
* Method 2:
* Obtain the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
config.setAccessKeyId("Obtain the AccessKey ID of your RAM user from an environment variable.");
config.setAccessKeySecret("Obtain the AccessKey secret of your 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");
//Connection timeout in milliseconds (ms).
config.setReadTimeout(6000);
//Read timeout 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 ID of the task that is returned when 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("Failed to query the video moderation result. Code:" + result.getCode());
}
} else {
System.out.println("Request failed. Status:" + response.getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}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 methods to obtain environment variables:
* Method 1:
* Obtain the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
* Method 2:
* Obtain the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
config.setAccessKeyId("Obtain the AccessKey ID of your RAM user from an environment variable.");
config.setAccessKeySecret("Obtain the AccessKey secret of your 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");
//Connection timeout in milliseconds (ms).
config.setReadTimeout(6000);
//Read timeout 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("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("Request failed. Status:" + response.getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}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 methods to obtain environment variables:
* Method 1:
* Obtain the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
* Method 2:
* Obtain the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
config.setAccessKeyId("Obtain the AccessKey ID of your RAM user from an environment variable.");
config.setAccessKeySecret("Obtain the AccessKey secret of your 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");
//Connection timeout in milliseconds (ms).
config.setReadTimeout(6000);
//Read timeout 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 ID of the task that is returned when 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("Failed to query the video moderation result. Code:" + result.getCode());
}
} else {
System.out.println("Request failed. Status:" + response.getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}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 methods to obtain environment variables:
* Method 1:
* Obtain the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
* Method 2:
* Obtain the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
config.setAccessKeyId("Obtain the AccessKey ID of your RAM user from an environment variable.");
config.setAccessKeySecret("Obtain the AccessKey secret of your 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");
//Connection timeout in milliseconds (ms).
config.setReadTimeout(6000);
//Read timeout 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 ID of the task that is returned when 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("Failed to cancel the video moderation task. Code:" + result.getCode());
}
} else {
System.out.println("Request failed. Status:" + response.getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}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 methods to obtain environment variables:
* Method 1:
* Obtain the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
* Method 2:
* Obtain the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
config.setAccessKeyId("Obtain the AccessKey ID of your RAM user from an environment variable.");
config.setAccessKeySecret("Obtain the AccessKey secret of your 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");
//Connection timeout in milliseconds (ms).
config.setReadTimeout(6000);
//Read timeout 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 ID of the task that is returned when 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("Failed to cancel the video moderation task. Code:" + result.getCode());
}
} else {
System.out.println("Request failed. Status:" + response.getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}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 for file upload requests.
public static OSS ossClient = null;
/**
* Create a request client.
*
* @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 file upload client.
*
* @param tokenData
* @param isVPC
*/
public static void getOssClient(DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData, boolean isVPC) {
//Note: We recommend that you reuse the instantiated client to avoid repeatedly establishing 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 the 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: We recommend that you reuse the instantiated client to avoid repeatedly establishing 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 for file upload.
if (tokenMap.get(endpoint) == null || tokenMap.get(endpoint).expiration <= System.currentTimeMillis() / 1000) {
DescribeUploadTokenResponse tokenResponse = client.describeUploadToken();
tokenMap.put(endpoint, tokenResponse.getBody().getData());
}
//The client for file upload requests.
getOssClient(tokenMap.get(endpoint), isVPC);
//Upload the file.
String objectName = uploadFile(filePath, tokenMap.get(endpoint));
// Construct moderation parameters.
Map<String, String> serviceParameters = new HashMap<>();
//File upload information.
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 methods to obtain environment variables:
* Method 1:
* Obtain the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
* Method 2:
* Obtain the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
String accessKeyId = "Obtain the AccessKey ID of your RAM user from an environment variable.";
String accessKeySecret = "Obtain the AccessKey secret of your RAM user 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 result.
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 failed. Code:" + code);
}
} else {
System.out.println("Request failed. Status:" + response.getStatusCode());
}
}
} catch (Exception e) {
e.printStackTrace();
}
} }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 methods to obtain environment variables:
* Method 1:
* Obtain the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
* Method 2:
* Obtain the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
config.setAccessKeyId("Obtain the AccessKey ID of your RAM user from an environment variable.");
config.setAccessKeySecret("Obtain the AccessKey secret of your 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");
//Connection timeout in milliseconds (ms).
config.setReadTimeout(6000);
//Read timeout 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 ID of the task that is returned when 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("Failed to query the video moderation result. Code:" + result.getCode());
}
} else {
System.out.println("Request failed. Status:" + response.getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}Query moderation results
Poll this endpoint with the taskId returned from the submission call.
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();
config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.setRegionId("ap-southeast-1");
config.setEndpoint("green-cip.ap-southeast-1.aliyuncs.com");
config.setConnectTimeout(3000);
config.setReadTimeout(6000);
Client client = new Client(config);
JSONObject serviceParameters = new JSONObject();
// Use the taskId returned by the submission call.
serviceParameters.put("taskId", "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****");
VideoModerationResultRequest videoModerationResultRequest = new VideoModerationResultRequest();
videoModerationResultRequest.setService("videoDetection_global");
videoModerationResultRequest.setServiceParameters(serviceParameters.toJSONString());
try {
VideoModerationResultResponse response = client.videoModerationResult(videoModerationResultRequest);
if (response.getStatusCode() == 200) {
VideoModerationResultResponseBody result = response.getBody();
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 query moderation result. Code: " + result.getCode());
}
} else {
System.out.println("Request failed. Status: " + response.getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}Cancel 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.
* Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all your resources may be compromised.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
"accessKeyId" => 'Obtain the AccessKey ID of your RAM user from an environment variable.',
"accessKeySecret" => 'Obtain the AccessKey secret of your 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: We recommend that you reuse the instantiated client to avoid repeatedly establishing connections and improve moderation performance.
$client = new Green($config);
$request = new VideoModerationCancelRequest();
// Moderation service: 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("Failed to cancel the video moderation task. Code:" . $body->code);
}
} else {
print_r("Request failed. Code:" . $response->statusCode);
}
} catch (TeaUnableRetryError $e) {
var_dump($e->getMessage());
var_dump($e->getErrorInfo());
var_dump($e->getLastException());
var_dump($e->getLastRequest());
}<?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 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 and the security of all your resources may be compromised.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
"accessKeyId" => 'Obtain the AccessKey ID of your RAM user from an environment variable.',
"accessKeySecret" => 'Obtain the AccessKey secret of your 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: We recommend that you reuse the instantiated client to avoid repeatedly establishing connections and improve moderation performance.
$client = new Green($config);
$request = new VideoModerationResultRequest();
// Moderation service: videoDetection for video file moderation and liveStreamDetection 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("Request failed. 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("The video moderation task is being processed. Code:" . $body->code);
return;
}
if (200 != $body->code) {
print_r("Failed to query the video moderation result. 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());
}<?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 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 and the security of all your resources may be compromised.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
"accessKeyId" => 'Obtain the AccessKey ID of your RAM user from an environment variable.',
"accessKeySecret" => 'Obtain the AccessKey secret of your 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: We recommend that you reuse the instantiated client to avoid repeatedly establishing connections and improve moderation performance.
$client = new Green($config);
$request = new VideoModerationRequest();
// Moderation service: videoDetection_global for video file moderation and liveStreamDetection_global for live stream moderation.
$request->service = "videoDetection_global";
$serviceParameters = array(
// The file to be moderated. Example: video/001.mp4
'ossObjectName' => 'video/001.mp4',
// The region where the bucket is located. Example: cn-shanghai
'ossRegionId' => 'ap-southeast-1',
// The name of the bucket. Example: bucket001
'ossBucketName' => 'bucket001',
// The unique ID of the data.
'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("Request failed. 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 failed. 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());
}<?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 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 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" => 'We recommend that you obtain the AccessKey ID of a RAM user from environment variables',
"accessKeySecret" => 'We recommend that you obtain the AccessKey secret of a RAM user from environment variables',
// 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: We recommend that you reuse the instantiated client as much as possible to avoid repeatedly establishing connections and to improve detection 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());
}<?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 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 and the security of all your resources may be compromised.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
"accessKeyId" => 'Obtain the AccessKey ID of your RAM user from an environment variable.',
"accessKeySecret" => 'Obtain the AccessKey secret of your 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: We recommend that you reuse the instantiated client to avoid repeatedly establishing connections and improve moderation performance.
$client = new Green($config);
$request = new VideoModerationResultRequest();
// Moderation service: videoDetection for video file moderation and liveStreamDetection 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("Request failed. 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("The video moderation task is being processed. Code:" . $body->code);
return;
}
if (200 != $body->code) {
print_r("Failed to query the video moderation result. 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());
}<?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 upload.
$tokenArray = array();
// The client for file upload requests.
$ossClient = null;
/**
* Create a request client.
* @param $accessKeyId
* @param $accessKeySecret
* @param $endpoint
* @return Green
*/
function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
{
$config = new 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",
"endpoint" => $endpoint,
]);
return new Green($config);
}
/**
* Create a file upload client.
* @param $tokenData
* @return void
*/
function create_upload_client($tokenData): void
{
global $isVPC;
global $ossClient;
// Note: We recommend that you reuse the instantiated client 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 the 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 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 the token for file upload.
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);
}
/**
* 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 and the security of all your resources may be compromised.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
$accessKeyId = 'Obtain the AccessKey ID of your RAM user from an environment variable.';
$accessKeySecret = 'Obtain the AccessKey secret of your RAM user from an environment variable.';
// Modify 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());
}<?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.
* Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all your resources may be compromised.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* Obtain the AccessKey secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
"accessKeyId" => 'Obtain the AccessKey ID of your RAM user from an environment variable.',
"accessKeySecret" => 'Obtain the AccessKey secret of your 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: We recommend that you reuse the instantiated client to avoid repeatedly establishing connections and improve moderation performance.
$client = new Green($config);
$request = new VideoModerationCancelRequest();
// Moderation service: 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("Failed to cancel the video moderation task. Code:" . $body->code);
}
} else {
print_r("Request failed. Code:" . $response->statusCode);
}
} catch (TeaUnableRetryError $e) {
var_dump($e->getMessage());
var_dump($e->getErrorInfo());
var_dump($e->getLastException());
var_dump($e->getLastRequest());
}# 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(
# 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 and the security of all your resources may be compromised.
# Common methods to obtain environment variables:
# Obtain the AccessKey ID of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
# Obtain the AccessKey secret of the 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.',
# Connection timeout in milliseconds (ms).
connect_timeout=10000,
# Read timeout in milliseconds (ms).
read_timeout=3000,
region_id='ap-southeast-1',
endpoint='green-cip.ap-southeast-1.aliyuncs.com'
)
clt = Client(config)
# The ID of the task that is returned when you submit the task.
serviceParameters = {
"taskId": 'vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****'
}
videoModerationCancelRequest = models.VideoModerationCancelRequest(
# Moderation service
service='liveStreamDetection_global',
service_parameters=json.dumps(serviceParameters)
)
try:
response = clt.video_moderation_cancel(videoModerationCancelRequest)
if response.status_code == 200:
# The request is successful.
result = response.body
print('Request successful. Result:{}'.format(result))
else:
print('Request failed. Status:{} ,Result:{}'.format(response.status_code, response))
except Exception as err:
print(err)# 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(
# 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 and the security of all your resources may be compromised.
# Common methods to obtain environment variables:
# Obtain the AccessKey ID of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
# Obtain the AccessKey secret of the 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.',
#Connection timeout in milliseconds (ms).
connect_timeout=3000,
#Read timeout 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 ID of the task that is returned when you submit the task.
serviceParameters = {
"taskId": 'vi_f_11w5THcbVYctjdxz2C0Afa-1x****'
}
videoModerationResultRequest = models.VideoModerationResultRequest(
# Moderation service: videoDetection_global
service='videoDetection_global',
service_parameters=json.dumps(serviceParameters)
)
try:
response = clt.video_moderation_result(videoModerationResultRequest)
if response.status_code == 200:
# The request is successful.
# Obtain the moderation result.
result = response.body
print('Request successful. Result:{}'.format(result))
else:
print('Request failed. Status:{} ,Result:{}'.format(response.status_code, response))
except Exception as err:
print(err)#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(
# 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 and the security of all your resources may be compromised.
# Common methods to obtain environment variables:
# Obtain the AccessKey ID of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
# Obtain the AccessKey secret of the 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.',
#Connection timeout in milliseconds (ms).
connect_timeout=3000,
#Read timeout 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(
# Moderation service: videoDetection_global
service='videoDetection_global',
service_parameters=json.dumps(serviceParameters)
)
try:
response = clt.video_moderation(videoModerationRequest)
if response.status_code == 200:
# The request is successful.
# Obtain the moderation result.
result = response.body
print('Request successful. Result:{}'.format(result))
else:
print('Request failed. Status:{} ,Result:{}'.format(response.status_code, response))
except Exception as err:
print(err)# 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(
# 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 and the security of all your resources may be compromised.
# Common methods to obtain environment variables:
# Obtain the AccessKey ID of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
# Obtain the AccessKey secret of the 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.',
# Connection timeout in milliseconds (ms).
connect_timeout=10000,
# Read timeout in milliseconds (ms).
read_timeout=3000,
region_id='ap-southeast-1',
endpoint='green-cip.ap-southeast-1.aliyuncs.com'
)
clt = Client(config)
# The ID of the task that is returned when you submit the task.
serviceParameters = {
"taskId": 'vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****'
}
videoModerationCancelRequest = models.VideoModerationCancelRequest(
# Moderation service
service='liveStreamDetection_global',
service_parameters=json.dumps(serviceParameters)
)
try:
response = clt.video_moderation_cancel(videoModerationCancelRequest)
if response.status_code == 200:
# The request is successful.
result = response.body
print('Request successful. Result:{}'.format(result))
else:
print('Request failed. Status:{} ,Result:{}'.format(response.status_code, response))
except Exception as err:
print(err)# 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(
# 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 and the security of all your resources may be compromised.
# Common methods to obtain environment variables:
# Obtain the AccessKey ID of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
# Obtain the AccessKey secret of the 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.',
#Connection timeout in milliseconds (ms).
connect_timeout=3000,
#Read timeout 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 ID of the task that is returned when you submit the task.
serviceParameters = {
"taskId": 'vi_f_11w5THcbVYctjdxz2C0Afa-1x****'
}
videoModerationResultRequest = models.VideoModerationResultRequest(
# Moderation service: videoDetection_global
service='videoDetection_global',
service_parameters=json.dumps(serviceParameters)
)
try:
response = clt.video_moderation_result(videoModerationResultRequest)
if response.status_code == 200:
# The request is successful.
# Obtain the moderation result.
result = response.body
print('Request successful. Result:{}'.format(result))
else:
print('Request failed. Status:{} ,Result:{}'.format(response.status_code, response))
except Exception as err:
print(err)# 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(
# 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 and the security of all your resources may be compromised.
# Common methods to obtain environment variables:
# Obtain the AccessKey ID of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
# Obtain the AccessKey secret of the 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.',
# Connection timeout in milliseconds (ms).
connect_timeout=10000,
# Read timeout in milliseconds (ms).
read_timeout=3000,
region_id='ap-southeast-1',
endpoint='green-cip.ap-southeast-1.aliyuncs.com'
)
clt = Client(config)
# The ID of the task that is returned when you submit the task.
serviceParameters = {
"taskId": 'vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****'
}
videoModerationCancelRequest = models.VideoModerationCancelRequest(
# Moderation service
service='liveStreamDetection_global',
service_parameters=json.dumps(serviceParameters)
)
try:
response = clt.video_moderation_cancel(videoModerationCancelRequest)
if response.status_code == 200:
# The request is successful.
result = response.body
print('Request successful. Result:{}'.format(result))
else:
print('Request failed. Status:{} ,Result:{}'.format(response.status_code, response))
except Exception as err:
print(err)Detect local videos
If the video doesn't have a public URL, upload it to an Object Storage Service (OSS) bucket provided by Content Moderation. Video Moderation 2.0 accesses the file directly through OSS.
Add both dependencies:
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>green20220302</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.16.3</version>
</dependency>Submit a moderation task
The code below handles the full workflow: get an upload token, upload the local file to the Content Moderation OSS bucket, then submit the 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 {
// Set to true if running in a VPC environment.
public static boolean isVPC = false;
// Cache upload tokens by endpoint to avoid repeated token requests.
public static Map<String, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData> tokenMap = new HashMap<>();
// Reuse the OSS client to improve performance.
public static OSS ossClient = null;
public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
Config config = new Config();
config.setAccessKeyId(accessKeyId);
config.setAccessKeySecret(accessKeySecret);
config.setEndpoint(endpoint);
return new Client(config);
}
public static void getOssClient(DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData, boolean isVPC) {
// Reuse the OSS client to avoid repeated connection overhead.
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());
}
}
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 {
// Reuse the client to avoid repeated connection overhead.
Client client = createClient(accessKeyId, accessKeySecret, endpoint);
RuntimeOptions runtime = new RuntimeOptions();
// Full path of the local video file.
String filePath = "D:\\localPath\\exampleFile.mp4";
// Refresh the upload token if it has expired.
if (tokenMap.get(endpoint) == null || tokenMap.get(endpoint).expiration <= System.currentTimeMillis() / 1000) {
DescribeUploadTokenResponse tokenResponse = client.describeUploadToken();
tokenMap.put(endpoint, tokenResponse.getBody().getData());
}
getOssClient(tokenMap.get(endpoint), isVPC);
String objectName = uploadFile(filePath, tokenMap.get(endpoint));
Map<String, String> serviceParameters = new HashMap<>();
serviceParameters.put("ossBucketName", tokenMap.get(endpoint).getBucketName());
serviceParameters.put("ossObjectName", objectName);
serviceParameters.put("dataId", UUID.randomUUID().toString());
VideoModerationRequest request = new VideoModerationRequest();
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 {
String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
VideoModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com");
try {
if (response != null && response.getStatusCode() == 200) {
VideoModerationResponseBody body = response.getBody();
System.out.println(JSON.toJSONString(body));
if (200 == body.getCode()) {
VideoModerationResponseBody.VideoModerationResponseBodyData data = body.getData();
System.out.println("taskId = [" + data.getTaskId() + "]");
} else {
System.out.println("Video moderation failed. Code: " + body.getCode());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}Query moderation results and Cancel a live stream moderation task — use the same code as shown in the Detect videos accessible over the internet section.
Detect videos stored in OSS
If the video is already in an OSS bucket you own, create a service role so Content Moderation can access it directly. Go to the Cloud Resource Access Authorization page to create the AliyunCIPScanOSSRole service role.
Add the dependency:
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>green20220302</artifactId>
<version>2.2.11</version>
</dependency>Submit a moderation task
Query moderation results and Cancel a live stream moderation task — use the same code as shown in the Detect videos accessible over the internet section.
SDK for Python
Python 3.6 or later is required.
Source code: SDK source code for Python.
Install the SDK:
pip install alibabacloud_green20220302==2.2.11Detect videos accessible over the internet
Submit a moderation task
# encoding: utf-8
# Python 3.6+
import json
import os
from alibabacloud_green20220302.client import Client
from alibabacloud_green20220302 import models
from alibabacloud_tea_openapi.models import Config
config = Config(
# Read credentials from environment variables — never hardcode them.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
# Update the region and endpoint as needed.
region_id='ap-southeast-1',
endpoint='green-cip.ap-southeast-1.aliyuncs.com',
connect_timeout=3000,
read_timeout=6000,
)
clt = Client(config)
service_parameters = {
'url': 'https://xxx.oss.aliyuncs.com/xxx.mp4'
}
video_moderation_request = models.VideoModerationRequest(
service='videoDetection_global',
service_parameters=json.dumps(service_parameters)
)
try:
response = clt.video_moderation(video_moderation_request)
if response.status_code == 200:
result = response.body
print('Request successful. Result: {}'.format(result))
else:
print('Request failed. Status: {}, Result: {}'.format(response.status_code, response))
except Exception as err:
print(err)Query moderation results
# encoding: utf-8
# Python 3.6+
import json
import os
from alibabacloud_green20220302.client import Client
from alibabacloud_green20220302 import models
from alibabacloud_tea_openapi.models import Config
config = Config(
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
region_id='ap-southeast-1',
endpoint='green-cip.ap-southeast-1.aliyuncs.com',
connect_timeout=3000,
read_timeout=6000,
)
clt = Client(config)
# Use the taskId returned by the submission call.
service_parameters = {
'taskId': 'vi_f_11w5THcbVYctjdxz2C0Afa-1x****'
}
video_moderation_result_request = models.VideoModerationResultRequest(
service='videoDetection_global',
service_parameters=json.dumps(service_parameters)
)
try:
response = clt.video_moderation_result(video_moderation_result_request)
if response.status_code == 200:
result = response.body
print('Request successful. Result: {}'.format(result))
else:
print('Request failed. Status: {}, Result: {}'.format(response.status_code, response))
except Exception as err:
print(err)Cancel a live stream moderation task
# encoding: utf-8
# Python 3.6+
import json
import os
from alibabacloud_green20220302.client import Client
from alibabacloud_green20220302 import models
from alibabacloud_tea_openapi.models import Config
config = Config(
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
region_id='ap-southeast-1',
endpoint='green-cip.ap-southeast-1.aliyuncs.com',
connect_timeout=10000,
read_timeout=3000,
)
clt = Client(config)
# Use the taskId returned by the live stream submission call.
service_parameters = {
'taskId': 'vi_f_11w5THcbVYctjdxz2C0Afa-1x****'
}
video_moderation_cancel_request = models.VideoModerationCancelRequest(
service='liveStreamDetection_global',
service_parameters=json.dumps(service_parameters)
)
try:
response = clt.video_moderation_cancel(video_moderation_cancel_request)
if response.status_code == 200:
result = response.body
print('Request successful. Result: {}'.format(result))
else:
print('Request failed. Status: {}, Result: {}'.format(response.status_code, response))
except Exception as err:
print(err)Detect local videos
Upload the local file to the Content Moderation OSS bucket, then submit the moderation task.
Submit a moderation task
# encoding: utf-8
# Python 3.6+
import json
import os
import uuid
import time
from alibabacloud_green20220302.client import Client
from alibabacloud_green20220302 import models
from alibabacloud_tea_openapi.models import Config
import oss2
# Set to True if running in a VPC environment.
IS_VPC = False
config = Config(
# Read credentials from environment variables — never hardcode them.
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
# Update the region and endpoint as needed.
region_id='ap-southeast-1',
endpoint='green-cip.ap-southeast-1.aliyuncs.com',
connect_timeout=10000,
read_timeout=10000,
)
# Reuse the client to improve performance.
client = Client(config)
upload_token = None
bucket = None
def get_oss_client(is_vpc):
global upload_token
global bucket
# Refresh the token if it is not set or has expired.
if upload_token is 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_internal_end_point if is_vpc else upload_token.oss_internet_end_point
bucket = oss2.Bucket(auth, end_point, upload_token.bucket_name)
def upload_file(file_path, is_vpc):
get_oss_client(is_vpc)
object_name = upload_token.file_name_prefix + str(uuid.uuid4()) + '.' + file_path.split('.')[-1]
bucket.put_object_from_file(object_name, file_path)
return object_name
# Full path of the local video file.
file_path = '/local/path/example.mp4'
object_name = upload_file(file_path, IS_VPC)
service_parameters = {
'ossBucketName': upload_token.bucket_name,
'ossObjectName': object_name,
'dataId': str(uuid.uuid4()),
}
video_moderation_request = models.VideoModerationRequest(
service='videoDetection_global',
service_parameters=json.dumps(service_parameters)
)
try:
response = client.video_moderation(video_moderation_request)
if response.status_code == 200:
result = response.body
print('Request successful. Result: {}'.format(result))
else:
print('Request failed. Status: {}, Result: {}'.format(response.status_code, response))
except Exception as err:
print(err)Query moderation results and Cancel a live stream moderation task — use the same code as shown in the Detect videos accessible over the internet section.
Detect videos stored in OSS
Create the AliyunCIPScanOSSRole service role first. See Detect videos stored in OSS in the Java section for setup instructions.
Submit a moderation task
# encoding: utf-8
# Python 3.6+
import json
import os
from alibabacloud_green20220302.client import Client
from alibabacloud_green20220302 import models
from alibabacloud_tea_openapi.models import Config
config = Config(
access_key_id=os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'],
access_key_secret=os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
region_id='ap-southeast-1',
endpoint='green-cip.ap-southeast-1.aliyuncs.com',
connect_timeout=3000,
read_timeout=6000,
)
clt = Client(config)
service_parameters = {
'ossBucketName': 'bucket_01',
'ossObjectName': '20240307/07/28/test.flv',
'ossRegionId': 'ap-southeast-1',
}
video_moderation_request = models.VideoModerationRequest(
service='videoDetection_global',
service_parameters=json.dumps(service_parameters)
)
try:
response = clt.video_moderation(video_moderation_request)
if response.status_code == 200:
result = response.body
print('Request successful. Result: {}'.format(result))
else:
print('Request failed. Status: {}, Result: {}'.format(response.status_code, response))
except Exception as err:
print(err)Query moderation results and Cancel a live stream moderation task — use the same code as shown in the Detect videos accessible over the internet section.
SDK for PHP
PHP 5.6 or later is required.
For the source code and installation instructions, see SDK source code for PHP.
Install the SDK:
composer require alibabacloud/green-20220302 2.2.10Detect videos accessible over the internet
Submit a moderation task
<?php
use AlibabaCloud\SDK\Green\V20220302\Green;
use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;
$config = new Config([
// Read credentials from environment variables — never hardcode them.
'accessKeyId' => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
'accessKeySecret' => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
// Update the region and endpoint as needed.
'regionId' => 'ap-southeast-1',
'endpoint' => 'green-cip.ap-southeast-1.aliyuncs.com',
'connectTimeout' => 3000,
'readTimeout' => 6000,
]);
$client = new Green($config);
$serviceParameters = json_encode([
'url' => 'https://xxx.oss.aliyuncs.com/xxx.mp4',
]);
$request = new VideoModerationRequest([
'service' => 'videoDetection_global',
'serviceParameters' => $serviceParameters,
]);
try {
$response = $client->videoModerationWithOptions($request, new RuntimeOptions([]));
if ($response->statusCode === 200) {
$result = $response->body;
echo 'Request successful. taskId: ' . $result->data->taskId . PHP_EOL;
} else {
echo 'Request failed. Status: ' . $response->statusCode . PHP_EOL;
}
} catch (Exception $e) {
echo $e->getMessage() . PHP_EOL;
}Query moderation results
<?php
use AlibabaCloud\SDK\Green\V20220302\Green;
use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationResultRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;
$config = new Config([
'accessKeyId' => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
'accessKeySecret' => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
'regionId' => 'ap-southeast-1',
'endpoint' => 'green-cip.ap-southeast-1.aliyuncs.com',
'connectTimeout' => 3000,
'readTimeout' => 6000,
]);
$client = new Green($config);
// Use the taskId returned by the submission call.
$serviceParameters = json_encode([
'taskId' => 'vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****',
]);
$request = new VideoModerationResultRequest([
'service' => 'videoDetection_global',
'serviceParameters' => $serviceParameters,
]);
try {
$response = $client->videoModerationResultWithOptions($request, new RuntimeOptions([]));
if ($response->statusCode === 200) {
$result = $response->body;
if ($result->code === 200) {
$data = $result->data;
echo 'liveId: ' . $data->liveId . PHP_EOL;
echo 'dataId: ' . $data->dataId . PHP_EOL;
echo 'riskLevel: ' . $data->RiskLevel . PHP_EOL;
} else {
echo 'Failed to query moderation result. Code: ' . $result->code . PHP_EOL;
}
} else {
echo 'Request failed. Status: ' . $response->statusCode . PHP_EOL;
}
} catch (Exception $e) {
echo $e->getMessage() . PHP_EOL;
}Cancel a live stream moderation task
<?php
use AlibabaCloud\SDK\Green\V20220302\Green;
use AlibabaCloud\SDK\Green\V20220302\Models\VideoModerationCancelRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;
$config = new Config([
'accessKeyId' => getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
'accessKeySecret' => getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
'regionId' => 'ap-southeast-1',
'endpoint' => 'green-cip.ap-southeast-1.aliyuncs.com',
'connectTimeout' => 3000,
'readTimeout' => 6000,
]);
$client = new Green($config);
// Use the taskId returned by the live stream submission call.
$serviceParameters = json_encode([
'taskId' => 'vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****',
]);
$request = new VideoModerationCancelRequest([
'service' => 'liveStreamDetection_global',
'serviceParameters' => $serviceParameters,
]);
try {
$response = $client->videoModerationCancelWithOptions($request, new RuntimeOptions([]));
if ($response->statusCode === 200) {
$result = $response->body;
if ($result->code !== 200) {
echo 'Failed to cancel moderation task. Code: ' . $result->code . PHP_EOL;
}
} else {
echo 'Request failed. Status: ' . $response->statusCode . PHP_EOL;
}
} catch (Exception $e) {
echo $e->getMessage() . PHP_EOL;
}Detect local videos and videos stored in OSS
Follow the same patterns as the Java and Python sections. Configure serviceParameters as follows:
Local video: Call
DescribeUploadTokenfirst, upload the file to the returned OSS bucket, then setossBucketName,ossObjectName, anddataIdinserviceParameters.OSS video: Set
ossBucketName,ossObjectName, andossRegionIdinserviceParameters(requires theAliyunCIPScanOSSRoleservice role).
SDK for Go
For the source code, see SDK source code for Go.
Install the dependencies:
go get github.com/alibabacloud-go/green-20220302/v2
go get github.com/alibabacloud-go/green-20220302/v3/client
go get github.com/alibabacloud-go/darabonba-openapi/v2/client
go get github.com/alibabacloud-go/tea-utils/v2/service
go get github.com/alibabacloud-go/tea/teaDetect videos accessible over the internet
Submit a moderation task
package main
import (
"encoding/json"
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
"net/http"
)
func main() {
// If the project code is leaked, the AccessKey pair may be disclosed, which compromises the security of all your resources. The following sample code is for reference only. We recommend that you use a more secure method, such as Security Token Service (STS), to call API operations.
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 and the security of all your resources may be compromised.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
* Obtain the AccessKey secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
AccessKeyId: tea.String("Obtain the AccessKey ID of your RAM user from an environment variable."),
AccessKeySecret: tea.String("Obtain the AccessKey secret of your 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 a timeout period. The server-side end-to-end processing timeout is 10 seconds. Configure the timeout period accordingly.
* If the ReadTimeout period that you set is less than the server-side processing time, a ReadTimeout exception is returned.
*/
ConnectTimeout: tea.Int(3000),
ReadTimeout: tea.Int(6000),
}
client, _err := green20220302.NewClient(config)
if _err != nil {
panic(_err)
}
// Create a RuntimeObject instance and configure 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("Request failed. Status:%d\n", *result.StatusCode)
return
}
body := result.Body
fmt.Printf("Request successful. RequestId:%s, Code:%d, Message:%s\n", *body.RequestId, *body.Code, *body.Message)
if *body.Code != http.StatusOK {
fmt.Printf("Failed to cancel the video moderation task. Code:%d\n", *body.Code)
}
}package main
import (
"encoding/json"
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
"net/http"
)
func main() {
// If the project code is leaked, the AccessKey pair may be disclosed, which compromises the security of all your resources. The following sample code is for reference only. We recommend that you use a more secure method, such as Security Token Service (STS), to call API operations.
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 and the security of all your resources may be compromised.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
* Obtain the AccessKey secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
AccessKeyId: tea.String("Obtain the AccessKey ID of your RAM user from an environment variable."),
AccessKeySecret: tea.String("Obtain the AccessKey secret of your 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 a timeout period. The server-side end-to-end processing timeout is 10 seconds. Configure the timeout period accordingly.
* If the ReadTimeout period that you set is less than the server-side processing time, a ReadTimeout exception is returned.
*/
ConnectTimeout: tea.Int(3000),
ReadTimeout: tea.Int(6000),
}
client, _err := green20220302.NewClient(config)
if _err != nil {
panic(_err)
}
// Create a RuntimeObject instance and configure 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("Request failed. Status:%d\n", *result.StatusCode)
return
}
body := result.Body
fmt.Printf("Request successful. RequestId:%s, Code:%d, Message:%s\n", *body.RequestId, *body.Code, *body.Message)
if *body.Code == 280 {
fmt.Printf("The video moderation task is being processed. Code:%d\n", *body.Code)
return
}
if *body.Code != http.StatusOK {
fmt.Printf("Failed to query the video moderation result. Code:%d\n", *body.Code)
return
}
data := body.Data
fmt.Printf("Video moderation result:%s\n", data)
fmt.Printf("Video moderation audio result:%s\n", data.AudioResult)
fmt.Printf("Video moderation frame result:%s\n", data.FrameResult)
}package main
import (
"encoding/json"
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
"net/http"
)
func main() {
// If the project code is leaked, the AccessKey pair may be disclosed, which compromises the security of all your resources. The following sample code is for reference only. We recommend that you use a more secure method, such as Security Token Service (STS), to call API operations.
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 and the security of all your resources may be compromised.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
* Obtain the AccessKey secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
AccessKeyId: tea.String("Obtain the AccessKey ID of your RAM user from an environment variable."),
AccessKeySecret: tea.String("Obtain the AccessKey secret of your 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 a timeout period. The server-side end-to-end processing timeout is 10 seconds. Configure the timeout period accordingly.
* If the ReadTimeout period that you set is less than the server-side processing time, a ReadTimeout exception is returned.
*/
ConnectTimeout: tea.Int(3000),
ReadTimeout: tea.Int(6000),
}
client, _err := green20220302.NewClient(config)
if _err != nil {
panic(_err)
}
// Create a RuntimeObject instance and configure 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("Request failed. Status:%d\n", *result.StatusCode)
return
}
body := result.Body
fmt.Printf("Request successful. RequestId:%s, Code:%d, Message:%s\n", *body.RequestId, *body.Code, *body.Message)
if *body.Code != http.StatusOK {
fmt.Printf("Video moderation failed. Code:%d\n", *body.Code)
return
}
data := body.Data
fmt.Printf("Video moderation taskId:%s\n", *data.TaskId)
}package main
import (
"encoding/json"
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
"net/http"
)
func main() {
// If the project code is leaked, the AccessKey pair may be disclosed, which compromises the security of all your resources. The following sample code is for reference only. We recommend that you use a more secure method, such as Security Token Service (STS), to call API operations.
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 and the security of all your resources may be compromised.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
* Obtain the AccessKey secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
AccessKeyId: tea.String("Obtain the AccessKey ID of your RAM user from an environment variable."),
AccessKeySecret: tea.String("Obtain the AccessKey secret of your 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 a timeout period. The server-side end-to-end processing timeout is 10 seconds. Configure the timeout period accordingly.
* If the ReadTimeout period that you set is less than the server-side processing time, a ReadTimeout exception is returned.
*/
ConnectTimeout: tea.Int(3000),
ReadTimeout: tea.Int(6000),
}
client, _err := green20220302.NewClient(config)
if _err != nil {
panic(_err)
}
// Create a RuntimeObject instance and configure 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("Request failed. Status:%d\n", *result.StatusCode)
return
}
body := result.Body
fmt.Printf("Request successful. RequestId:%s, Code:%d, Message:%s\n", *body.RequestId, *body.Code, *body.Message)
if *body.Code != http.StatusOK {
fmt.Printf("Failed to cancel the video moderation task. Code:%d\n", *body.Code)
}
}package main
import (
"encoding/json"
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
"net/http"
)
func main() {
// If the project code is leaked, the AccessKey pair may be disclosed, which compromises the security of all your resources. The following sample code is for reference only. We recommend that you use a more secure method, such as Security Token Service (STS), to call API operations.
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 and the security of all your resources may be compromised.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
* Obtain the AccessKey secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
AccessKeyId: tea.String("Obtain the AccessKey ID of your RAM user from an environment variable."),
AccessKeySecret: tea.String("Obtain the AccessKey secret of your 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 a timeout period. The server-side end-to-end processing timeout is 10 seconds. Configure the timeout period accordingly.
* If the ReadTimeout period that you set is less than the server-side processing time, a ReadTimeout exception is returned.
*/
ConnectTimeout: tea.Int(3000),
ReadTimeout: tea.Int(6000),
}
client, _err := green20220302.NewClient(config)
if _err != nil {
panic(_err)
}
// Create a RuntimeObject instance and configure 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("Request failed. Status:%d\n", *result.StatusCode)
return
}
body := result.Body
fmt.Printf("Request successful. RequestId:%s, Code:%d, Message:%s\n", *body.RequestId, *body.Code, *body.Message)
if *body.Code == 280 {
fmt.Printf("The video moderation task is being processed. Code:%d\n", *body.Code)
return
}
if *body.Code != http.StatusOK {
fmt.Printf("Failed to query the video moderation result. Code:%d\n", *body.Code)
return
}
data := body.Data
fmt.Printf("Video moderation result:%s\n", data)
fmt.Printf("Video moderation audio result:%s\n", data.AudioResult)
fmt.Printf("Video moderation frame result:%s\n", data.FrameResult)
}package main
import (
"encoding/json"
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
green20220302 "github.com/alibabacloud-go/green-20220302/v3/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 for file upload.
var TokenMap =make(map[string]*green20220302.DescribeUploadTokenResponseBodyData)
//The client for file upload.
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: We recommend that you reuse the instantiated client to avoid repeatedly establishing connections and improve moderation performance.
return green20220302.NewClient(config);
}
//Create a file upload client.
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: We recommend that you reuse the instantiated client to avoid repeatedly establishing connections and improve moderation performance.
client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
if _err != nil {
return nil,_err
}
//Set runtime parameters. The settings take effect only for requests that use this 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 and the security of all your resources may be compromised.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
* Obtain the AccessKey secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
var accessKeyId= "Obtain the AccessKey ID of your RAM user from an environment variable.";
var accessKeySecret= "Obtain the AccessKey secret of your 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 China (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("Request successful. 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("Video moderation failed. Status:" + tea.ToString(body.Code))
}
} else {
fmt.Print("Request failed. Status:" + tea.ToString(statusCode))
}
}
}package main
import (
"encoding/json"
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
"net/http"
)
func main() {
// If the project code is leaked, the AccessKey pair may be disclosed, which compromises the security of all your resources. The following sample code is for reference only. We recommend that you use a more secure method, such as Security Token Service (STS), to call API operations.
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 and the security of all your resources may be compromised.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
* Obtain the AccessKey secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
AccessKeyId: tea.String("Obtain the AccessKey ID of your RAM user from an environment variable."),
AccessKeySecret: tea.String("Obtain the AccessKey secret of your 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 a timeout period. The server-side end-to-end processing timeout is 10 seconds. Configure the timeout period accordingly.
* If the ReadTimeout period that you set is less than the server-side processing time, a ReadTimeout exception is returned.
*/
ConnectTimeout: tea.Int(3000),
ReadTimeout: tea.Int(6000),
}
client, _err := green20220302.NewClient(config)
if _err != nil {
panic(_err)
}
// Create a RuntimeObject instance and configure 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("Request failed. Status:%d\n", *result.StatusCode)
return
}
body := result.Body
fmt.Printf("Request successful. RequestId:%s, Code:%d, Message:%s\n", *body.RequestId, *body.Code, *body.Message)
if *body.Code != http.StatusOK {
fmt.Printf("Failed to cancel the video moderation task. Code:%d\n", *body.Code)
}
}package main
import (
"encoding/json"
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
"net/http"
)
func main() {
// If the project code is leaked, the AccessKey pair may be disclosed, which compromises the security of all your resources. The following sample code is for reference only. We recommend that you use a more secure method, such as Security Token Service (STS), to call API operations.
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 and the security of all your resources may be compromised.
* Common methods to obtain environment variables:
* Obtain the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
* Obtain the AccessKey secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
*/
AccessKeyId: tea.String("Obtain the AccessKey ID of your RAM user from an environment variable."),
AccessKeySecret: tea.String("Obtain the AccessKey secret of your 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 a timeout period. The server-side end-to-end processing timeout is 10 seconds. Configure the timeout period accordingly.
* If the ReadTimeout period that you set is less than the server-side processing time, a ReadTimeout exception is returned.
*/
ConnectTimeout: tea.Int(3000),
ReadTimeout: tea.Int(6000),
}
client, _err := green20220302.NewClient(config)
if _err != nil {
panic(_err)
}
// Create a RuntimeObject instance and configure 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("Request failed. Status:%d\n", *result.StatusCode)
return
}
body := result.Body
fmt.Printf("Request successful. RequestId:%s, Code:%d, Message:%s\n", *body.RequestId, *body.Code, *body.Message)
if *body.Code == 280 {
fmt.Printf("The video moderation task is being processed. Code:%d\n", *body.Code)
return
}
if *body.Code != http.StatusOK {
fmt.Printf("Failed to query the video moderation result. Code:%d\n", *body.Code)
return
}
data := body.Data
fmt.Printf("Video moderation result:%s\n", data)
fmt.Printf("Video moderation audio result:%s\n", data.AudioResult)
fmt.Printf("Video moderation frame result:%s\n", data.FrameResult)
}Query moderation results
package main
import (
"encoding/json"
"fmt"
"os"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
green "github.com/alibabacloud-go/green-20220302/v3/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
)
func main() {
config := &openapi.Config{
AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
RegionId: tea.String("ap-southeast-1"),
Endpoint: tea.String("green-cip.ap-southeast-1.aliyuncs.com"),
ConnectTimeout: tea.Int(3000),
ReadTimeout: tea.Int(6000),
}
client, _ := green.NewClient(config)
// Use the taskId returned by the submission call.
serviceParameters, _ := json.Marshal(map[string]string{
"taskId": "vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****",
})
request := &green.VideoModerationResultRequest{
Service: tea.String("videoDetection_global"),
ServiceParameters: tea.String(string(serviceParameters)),
}
runtime := &util.RuntimeOptions{}
response, err := client.VideoModerationResultWithOptions(request, runtime)
if err != nil {
fmt.Println(err)
return
}
if *response.StatusCode == 200 && *response.Body.Code == 200 {
data := response.Body.Data
fmt.Println("dataId:", *data.DataId)
fmt.Println("riskLevel:", *data.RiskLevel)
} else {
fmt.Println("Failed to query moderation result. Code:", *response.Body.Code)
}
}Cancel a live stream moderation task
Detect local videos
If the video doesn't have a public URL, upload it to the Content Moderation OSS bucket first. The code below handles token caching with expiration check, file upload, and moderation task submission. If the initial request fails with a 500 error, the code automatically retries using the China (Beijing) endpoint.
Install the OSS SDK:
go get github.com/aliyun/aliyun-oss-go-sdk/ossSubmit a moderation task
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
"time"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
green "github.com/alibabacloud-go/green-20220302/v3/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"
)
// Cache upload tokens by endpoint to avoid repeated token requests.
var TokenMap = make(map[string]*green.DescribeUploadTokenResponseBodyData)
// OSS bucket client for file upload.
var Bucket *oss.Bucket
// Set to true if running in a VPC environment.
var isVPC = false
func createClient(accessKeyId string, accessKeySecret string, endpoint string) (*green.Client, error) {
config := &openapi.Config{
AccessKeyId: tea.String(accessKeyId),
AccessKeySecret: tea.String(accessKeySecret),
Endpoint: tea.String(endpoint),
}
return green.NewClient(config)
}
func createOssClient(tokenData *green.DescribeUploadTokenResponseBodyData) {
var ossClient *oss.Client
var err error
if isVPC {
ossClient, err = oss.New(tea.StringValue(tokenData.OssInternalEndPoint), tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken)))
} 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))
}
func uploadFile(filePath string, tokenData *green.DescribeUploadTokenResponseBodyData) (string, error) {
createOssClient(tokenData)
objectName := tea.StringValue(tokenData.FileNamePrefix) + uuid.New().String() + "." + strings.Split(filePath, ".")[1]
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) (*green.VideoModerationResponse, error) {
client, err := createClient(accessKeyId, accessKeySecret, endpoint)
if err != nil {
return nil, err
}
runtime := &util.RuntimeOptions{}
// Full path of the local video file.
filePath := "D:\\localPath\\exampleFile.mp4"
// Refresh the upload token if it has expired.
tokenData, ok := TokenMap[endpoint]
if !ok || tea.Int32Value(tokenData.Expiration) <= int32(time.Now().Unix()) {
uploadTokenResponse, err := client.DescribeUploadToken()
if err != nil {
return nil, err
}
tokenData = uploadTokenResponse.Body.Data
TokenMap[endpoint] = tokenData
}
objectName, _ := uploadFile(filePath, TokenMap[endpoint])
serviceParameters, _ := json.Marshal(map[string]interface{}{
"ossBucketName": tea.StringValue(TokenMap[endpoint].BucketName),
"ossObjectName": objectName,
"dataId": uuid.New().String(),
})
request := &green.VideoModerationRequest{
Service: tea.String("videoDetection_global"),
ServiceParameters: tea.String(string(serviceParameters)),
}
return client.VideoModerationWithOptions(request, runtime)
}
func main() {
accessKeyId := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
accessKeySecret := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
endpoint := "green-cip.ap-southeast-1.aliyuncs.com"
response, err := invoke(accessKeyId, accessKeySecret, endpoint)
// Automatic routing: if the request fails with a 500 error, retry using the China (Beijing) endpoint.
flag := false
if err != nil {
if sdkErr, ok := err.(*tea.SDKError); ok && *sdkErr.StatusCode == 500 {
flag = true
}
}
if response == nil || *response.StatusCode == 500 || *response.Body.Code == 500 {
flag = true
}
if flag {
endpoint = "green-cip.cn-beijing.aliyuncs.com"
response, err = invoke(accessKeyId, accessKeySecret, endpoint)
}
if response != nil {
statusCode := int(*response.StatusCode)
body := response.Body
fmt.Println("requestId:", *body.RequestId)
if statusCode == http.StatusOK {
fmt.Println("Request successful. Response:", body.String())
if *body.Code == 200 {
data := body.Data
fmt.Println("dataId:", *data.DataId)
fmt.Println("taskId:", *data.TaskId)
} else {
fmt.Println("Video moderation failed. Code:", *body.Code)
}
} else {
fmt.Println("Request failed. Status:", statusCode)
}
}
if err != nil {
fmt.Println("Error:", err)
}
}Query moderation results and Cancel a live stream moderation task — use the same code as shown in the Detect videos accessible over the internet section.
Detect videos stored in OSS
Follow the same patterns as the Java and Python sections, configuring serviceParameters with the appropriate fields for each scenario.
SDK for Node.js
For the source code, see SDK source code for Node.js.
Install the SDK:
npm install @alicloud/green20220302@2.2.10Detect videos accessible over the internet
Submit a moderation task
const Green20220302 = require('@alicloud/green20220302');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
// Note: We recommend that you reuse the instantiated client to avoid repeatedly establishing connections and improve moderation performance.
// If the project code is leaked, the AccessKey pair may be disclosed, which compromises the security of all your resources. The following sample code is for reference only.
class Client {
static createClient() {
const config = new OpenApi.Config({
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured.
accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured.
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 a request object.
const videoModerationResultRequest = new Green20220302.VideoModerationResultRequest({
// The video moderation service.
"service": "videoDetection_global",
"serviceParameters": JSON.stringify({"taskId":"<The ID of the video moderation task whose result you want to query>"})
});
// Create a runtime configuration object.
const runtime = new Util.RuntimeOptions();
try {
// Send the request and obtain the response.
const response = await client.videoModerationResultWithOptions(videoModerationResultRequest, runtime);
console.log(JSON.stringify(response.body));
} catch (error) {
// We recommend that you handle exceptions with caution in your business code and do not ignore them. In this example, only the error message is printed.
// The error message.
console.log('Error occurred:', error.message);
}
}
}
Client.main();const Green20220302 = require('@alicloud/green20220302');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
// Note: We recommend that you reuse the instantiated client to avoid repeatedly establishing connections and improve moderation performance.
// If the project code is leaked, the AccessKey pair may be disclosed, which compromises the security of all your resources. The following sample code is for reference only.
class Client {
static createClient() {
const config = new OpenApi.Config({
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured.
accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured.
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 a request object.
const videoModerationRequest = new Green20220302.VideoModerationRequest({
// The video moderation service.
"service": "videoDetection_global",
// The URL of the video to be moderated.
"serviceParameters": JSON.stringify({
// The region where the bucket is located. Example: cn-shanghai
"ossRegionId": "cn-shanghai",
// The name of the bucket. Example: bucket001
"ossBucketName": "bucket001",
// The file to be moderated. Example: video/001.mp4
"ossObjectName": "video/001.mp4",})
});
// Create a runtime configuration object.
const runtime = new Util.RuntimeOptions();
try {
// Send the request and obtain the response.
const response = await client.videoModerationWithOptions(videoModerationRequest, runtime);
console.log(JSON.stringify(response.body));
} catch (error) {
// We recommend that you handle exceptions with caution in your business code and do not ignore them. In this example, only the error message is printed.
// The error message.
console.log('Error occurred:', error.message);
}
}
}
Client.main();const Green20220302 = require('@alicloud/green20220302');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
// Note: We recommend that you reuse the instantiated client to avoid repeatedly establishing connections and improve moderation performance.
// If the project code is leaked, the AccessKey pair may be disclosed, which compromises the security of all your resources. The following sample code is for reference only.
class Client {
static createClient() {
const config = new OpenApi.Config({
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured.
accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured.
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 a request object.
const videoModerationResultRequest = new Green20220302.VideoModerationResultRequest({
// The video moderation service.
"service": "videoDetection_global",
"serviceParameters": JSON.stringify({"taskId":"<The ID of the video moderation task whose result you want to query>"})
});
// Create a runtime configuration object.
const runtime = new Util.RuntimeOptions();
try {
// Send the request and obtain the response.
const response = await client.videoModerationResultWithOptions(videoModerationResultRequest, runtime);
console.log(JSON.stringify(response.body));
} catch (error) {
// We recommend that you handle exceptions with caution in your business code and do not ignore them. In this example, only the error message is printed.
// The error message.
console.log('Error occurred:', error.message);
}
}
}
Client.main();const Green20220302 = require('@alicloud/green20220302');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
// Note: We recommend that you reuse the instantiated client to avoid repeatedly establishing connections and improve moderation performance.
// If the project code is leaked, the AccessKey pair may be disclosed, which compromises the security of all your resources. The following sample code is for reference only.
class Client {
static createClient() {
const config = new OpenApi.Config({
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured.
accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
// Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured.
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 a request object.
const videoModerationResultRequest = new Green20220302.VideoModerationResultRequest({
// The video moderation service.
"service": "videoDetection_global",
"serviceParameters": JSON.stringify({"taskId":"<The ID of the video moderation task whose result you want to query>"})
});
// Create a runtime configuration object.
const runtime = new Util.RuntimeOptions();
try {
// Send the request and obtain the response.
const response = await client.videoModerationResultWithOptions(videoModerationResultRequest, runtime);
console.log(JSON.stringify(response.body));
} catch (error) {
// We recommend that you handle exceptions with caution in your business code and do not ignore them. In this example, only the error message is printed.
// The error message.
console.log('Error occurred:', error.message);
}
}
}
Client.main();Query moderation results
'use strict';
const Green = require('@alicloud/green20220302');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
async function main() {
const config = new OpenApi.Config({
accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
regionId: 'ap-southeast-1',
endpoint: 'green-cip.ap-southeast-1.aliyuncs.com',
connectTimeout: 3000,
readTimeout: 6000,
});
const client = new Green.default(config);
// Use the taskId returned by the submission call.
const serviceParameters = JSON.stringify({
taskId: 'vi_f_O5z5iaIis3iI0X2oNYj7qa-1x****',
});
const request = new Green.VideoModerationResultRequest({
service: 'videoDetection_global',
serviceParameters: serviceParameters,
});
try {
const response = await client.videoModerationResultWithOptions(request, new Util.RuntimeOptions({}));
if (response.statusCode === 200 && response.body.code === 200) {
const data = response.body.data;
console.log('dataId:', data.dataId);
console.log('riskLevel:', data.riskLevel);
} else {
console.log('Failed to query moderation result. Code:', response.body.code);
}
} catch (err) {
console.error(err.message);
}
}
main();Cancel a live stream moderation task
Detect local videos and videos stored in OSS
Follow the same patterns as the Java and Python sections, configuring serviceParameters with the appropriate fields for each scenario.