Java对接阿里云视频审核(鉴黄、暴恐涉政、广告等等)

第一步:

需要下载封装好的代码包,若是找不到下载路径,可前往https://download.csdn.net/download/weixin_42132397/12475250下载,自行选择噢

第二步:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.green.model.v20180509.ImageSyncScanRequest;
import com.aliyuncs.green.model.v20180509.VideoAsyncScanRequest;
import com.aliyuncs.green.model.v20180509.VideoAsyncScanResultsRequest;
import com.aliyuncs.green.model.v20180509.VideoSyncScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import java.util.*;

public class AliyunVideoSyncCheck {

    /**
     * 异步视频鉴黄
     * @param imageUrl
     * @throws Exception
     */
    public static String aliyunVideoAsyncCheck(String imageUrl) throws Exception {

        IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", "---accessKeyId---", "--accessKeySecret--");
        DefaultProfile.addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        IAcsClient client = new DefaultAcsClient(profile);

        VideoAsyncScanRequest videoAsyncScanRequest = new VideoAsyncScanRequest();
        videoAsyncScanRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
        videoAsyncScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法

        List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
        Map<String, Object> task = new LinkedHashMap<String, Object>();
        task.put("dataId", UUID.randomUUID().toString());
        task.put("url", imageUrl);

        tasks.add(task);
        /**
         * 设置要检测的场景, 计费是按照该处传递的场景进行
         * 视频默认1秒截取一帧,您可以自行控制截帧频率,收费按照视频的截帧数量以及每一帧的检测场景进行计费
         * 举例:1分钟的视频截帧60张,检测色情和暴恐涉政2个场景,收费按照60张暴恐+60张暴恐涉政进行计费
         * porn: porn表示色情场景检测,terrorism表示暴恐涉政场景检测
         */
        JSONObject data = new JSONObject();
        data.put("scenes", Arrays.asList("porn", "terrorism"));
        data.put("tasks", tasks);

        videoAsyncScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);

        /**
         * 请务必设置超时时间
         */
        videoAsyncScanRequest.setConnectTimeout(3000);
        videoAsyncScanRequest.setReadTimeout(6000);
        try {
            HttpResponse httpResponse = client.doAction(videoAsyncScanRequest);

            if(httpResponse.isSuccess()){
                JSONObject jsonObject = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
//                System.out.println(JSON.toJSONString(jsonObject, true));
                if (200 == jsonObject.getInteger("code")) {
                    JSONArray taskResults = jsonObject.getJSONArray("data");
                    for (Object taskResult : taskResults) {
                        if (200 == ((JSONObject) taskResult).getInteger("code")) {
                            String taskId = ((JSONObject) taskResult).getString("taskId");
                            return taskId;
                        }
                    }
                }
            }else{
                System.out.println("response not success. status:" + httpResponse.getStatus());
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询异步检测结果
     * @param taskId
     * @return
     * @throws Exception
     */
    public static boolean getResult(String taskId) throws Exception {
        boolean flag = false;
        IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", "---accessKeyId---", "--accessKeySecret--");
        DefaultProfile.addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        IAcsClient client = new DefaultAcsClient(profile);

        VideoAsyncScanResultsRequest videoAsyncScanResultsRequest = new VideoAsyncScanResultsRequest();
        videoAsyncScanResultsRequest.setAcceptFormat(FormatType.JSON);

        List<String> taskList = new ArrayList<String>();
        // 这里添加要查询的taskId,提交任务的时候需要自行保存taskId
        taskList.add(taskId);

        videoAsyncScanResultsRequest.setHttpContent(JSON.toJSONString(taskList).getBytes("UTF-8"), "UTF-8", FormatType.JSON);

        /**
         * 请务必设置超时时间
         */
        videoAsyncScanResultsRequest.setConnectTimeout(3000);
        videoAsyncScanResultsRequest.setReadTimeout(6000);
        try {
            HttpResponse httpResponse = client.doAction(videoAsyncScanResultsRequest);
            if(httpResponse.isSuccess()){
                JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
//                System.out.println(JSON.toJSONString(jsonObject, true));
                if (200 == scrResponse.getInteger("code")) {
                    JSONArray taskResults = scrResponse.getJSONArray("data");
                    for (Object taskResult : taskResults) {
                        if (200 == ((JSONObject) taskResult).getInteger("code")) {
                            JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                            for (Object sceneResult : sceneResults) {
                                String scene = ((JSONObject) sceneResult).getString("scene");
                                String suggestion = ((JSONObject) sceneResult).getString("suggestion");
                                //根据scene和suggetion做相关的处理
                                //do something
                                System.out.println("scene = [" + scene + "]");
                                System.out.println("suggestion = [" + suggestion + "]");
                                if (!"pass".equals(suggestion)){
                                    flag = false;
                                    return flag;
                                }else {
                                    flag = true;
                                }
                            }
                        } else {
                            System.out.println("task process fail:" + ((JSONObject) taskResult).getInteger("code"));
                        }
                    }
                } else {
                    System.out.println("detect not success. code:" + scrResponse.getInteger("code"));
                }
            }else{
                System.out.println("response not success. status:" + httpResponse.getStatus());
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 同步检测
     * @param imageUrl
     * @return
     * @throws Exception
     */
    public static boolean aliyunVideoSyncCheck(String imageUrl) throws Exception {
        boolean flag = false;
        IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", "---accessKeyId---", "--accessKeySecret--");
        DefaultProfile.addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        IAcsClient client = new DefaultAcsClient(profile);

        VideoSyncScanRequest videoSyncScanRequest = new VideoSyncScanRequest();
        videoSyncScanRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
        videoSyncScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法

        List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
        Map<String, Object> task = new LinkedHashMap<String, Object>();
        task.put("dataId", UUID.randomUUID().toString());

        List<Map<String, Object>> frames = new ArrayList<Map<String, Object>>();
        Map<String, Object> frame1 = new LinkedHashMap<String, Object>();
        frame1.put("offset", 0);
        frame1.put("url", "https://img.alicdn.com/tfs/TB1k_g9l26H8KJjSspmXXb2WXXa-600-600.jpg");

        Map<String, Object> frame2 = new LinkedHashMap<String, Object>();
        frame2.put("offset", 5);
        frame2.put("url", "http://pic12.nipic.com/20110221/6727421_210944911000_2.jpg");

        Map<String, Object> frame3 = new LinkedHashMap<String, Object>();
        frame3.put("offset", 10);
        frame3.put("url", "http://rifleman-share.oss-cn-hangzhou.aliyuncs.com/test/%E6%AD%A3%E5%B8%B8/68d5883924c9e8cc88806a73bd7a8995.jpg");
        frames.addAll(Arrays.asList(frame1, frame2, frame3));

        task.put("frames", frames);
        tasks.add(task);
        /**
         * 设置要检测的场景, 计费是按照该处传递的场景进行
         * 视频默认1秒截取一帧,您可以自行控制截帧频率,收费按照视频的截帧数量以及每一帧的检测场景进行计费
         * 举例:1分钟的视频截帧60张,检测色情和暴恐涉政2个场景,收费按照60张暴恐+60张暴恐涉政进行计费
         * porn: porn表示色情场景检测
         */
        JSONObject data = new JSONObject();
        data.put("scenes", Arrays.asList("porn", "terrorism"));
        data.put("tasks", tasks);

        videoSyncScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);

        /**
         * 请务必设置超时时间
         */
        videoSyncScanRequest.setConnectTimeout(3000);
        videoSyncScanRequest.setReadTimeout(10000);
        try {
            HttpResponse httpResponse = client.doAction(videoSyncScanRequest);

            if(httpResponse.isSuccess()){
                JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                //System.out.println(JSON.toJSONString(jsonObject, true));
                if (200 == scrResponse.getInteger("code")) {
                    JSONArray taskResults = scrResponse.getJSONArray("data");
                    for (Object taskResult : taskResults) {
                        if (200 == ((JSONObject) taskResult).getInteger("code")) {
                            JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                            for (Object sceneResult : sceneResults) {
                                String scene = ((JSONObject) sceneResult).getString("scene");
                                String suggestion = ((JSONObject) sceneResult).getString("suggestion");
                                //根据scene和suggetion做相关的处理
                                //do something
                                System.out.println("scene = [" + scene + "]");
                                System.out.println("suggestion = [" + suggestion + "]");
                                if (!"pass".equals(suggestion)){
                                    flag = false;
                                    return flag;
                                }else {
                                    flag = true;
                                }
                            }
                        } else {
                            System.out.println("task process fail:" + ((JSONObject) taskResult).getInteger("code"));
                        }
                    }
                } else {
                    System.out.println("detect not success. code:" + scrResponse.getInteger("code"));
                }
            }else{
                System.out.println("response not success. status:" + httpResponse.getStatus());
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return flag;
    }


    public static void main(String[] args) throws Exception {
//        boolean b = aliyunVideoSyncCheck("https://chaojiguoke.oss-cn-shanghai.aliyuncs.com/img/da7f5c8153774a0daeb5897d4c962dd5.mp4");
        boolean b = aliyunVideoSyncCheck("https://chaojiguoke.oss-cn-shanghai.aliyuncs.com/img/607d1954d98943a3b1d094173c003c97.mp4");
        if (b){
            System.out.printf("不是黄视频暴视频");
        }else{
            System.out.printf("是黄视频暴视频");
        }
    }

}

阿里云接口文档地址:https://help.aliyun.com/document_detail/53425.html?spm=a2c4g.11186623.6.705.2b611e7f1gZrHl

你可能感兴趣的:(Java)