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

  • 6
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
要实现指定审核人,可以在代码中设置一个审核人的用户id或用户名,然后在审核时判断当前用户是否为审核人,如果是,则直接通过审核,否则需要提交审核请求等待审核审核。 至于对接七牛后台进行内容审核,可以使用七牛提供的内容审核API。具体步骤如下: 1. 注册七牛账号并开通内容审核服务 2. 在代码中调用七牛提供的java SDK,使用API进行内容审核 3. 将需要审核的图片或视频上传到七牛云存储 4. 调用审核API,传入审核对象的url和审核类型(如鉴黄、敏感人物、暴恐等) 5. 获取审核结果并根据结果进行处理,如禁止上传或提示用户删除不符合规定的内容。 以下是一个简单的示例代码: ```java import com.qiniu.util.Auth; import com.qiniu.util.StringMap; import com.qiniu.util.UrlSafeBase64; import okhttp3.*; import java.io.IOException; public class QiniuContentReviewDemo { private static final String ACCESS_KEY = "your_access_key"; private static final String SECRET_KEY = "your_secret_key"; private static final String BUCKET_NAME = "your_bucket_name"; public static void main(String[] args) throws Exception { // 构建审核请求 String url = "http://ai.qiniuapi.com/v3/image/censor"; String body = "{\"data\": {\"uri\": \"" + encodeUrl("http://your_domain.com/your_image.jpg") + "\"}, \"params\": {\"scenes\": [\"pulp\",\"terror\",\"politician\"]}}"; RequestBody requestBody = RequestBody.create(body, MediaType.parse("application/json")); Request request = new Request.Builder() .url(url) .post(requestBody) .addHeader("Content-Type", "application/json") .addHeader("Authorization", "Qiniu " + getAccessToken(url, body)) .build(); // 发送请求并获取结果 OkHttpClient client = new OkHttpClient(); Response response = client.newCall(request).execute(); String result = response.body().string(); // 处理审核结果 if (response.isSuccessful()) { System.out.println(result); // TODO: 解析审核结果并进行处理 } else { System.err.println("Content review failed: " + result); } } // 获取七牛API的访问令牌 private static String getAccessToken(String url, String body) { StringMap headers = new StringMap(); String accessToken = Auth.create(ACCESS_KEY, SECRET_KEY).signRequestV2(url, "POST", body.getBytes(), headers); return accessToken; } // 将url进行base64编码 private static String encodeUrl(String url) { return UrlSafeBase64.encodeToString(url); } } ``` 这个示例代码使用了七牛提供的java SDK,并调用了七牛的内容审核API进行鉴黄、敏感人物、暴恐审核。需要注意的是,这个示例代码只是一个简单的示例,实际使用时需要根据具体需求进行修改和扩展。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值