Java调用百度API实现文本与图像审核功能

1 篇文章 0 订阅

文档:

API文档:https://ai.baidu.com/ai-doc/ANTIPORN/ek3h6x90n

SDK下载:https://ai.baidu.com/sdk#anti

github链接:https://github.com/Baidu-AIP/java-sdk

工具类下载地址:

HttpUtil:https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3

FileUtil:https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72

Base64Util:https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2

开发步骤:

1. 添加依赖:${version}可根据官网选择合适的版本,或将相应下载的SDK中的jar引入到项目中。

<dependency>
    <groupId>com.baidu.aip</groupId>
    <artifactId>java-sdk</artifactId>
    <version>${version}</version>
</dependency>

2. 下载工具类引入项目。

3.  获取Access Token的代码,主要功能是获取调用API时必须在URL中带上的access_token参数。

官网鉴权认证机制:https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu

代码如下:

package auth;

/**
 * 百度敏感信息配置
 */
public class BaiduSensitiveConfig {

    /**
     * 百度云应用的AI:创建完应用后平台分配给此应用 AppID
     */
    public static final String APP_ID = "百度云应用的AI";

    /**
     * 百度云应用的AK:创建完应用后平台分配给此应用 API Key
     */
    public static final String API_KEY = "百度云应用的AK";

    /**
     * 百度云应用的SK:创建完应用后平台分配给此应用 Secret Key
     */
    public static final String SECRET_KEY = "百度云应用的SK";
    /**
     * 文本审核接口
     */
    public static final String CHECK_TEXT_URL = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined";

    /**
     * 图片审核接口
     */
    public static final String CHECK_IMAGE_URL = "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined";

}

package auth;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

public class AccessToken {

    public static void main(String[] args) {
        System.out.println(getAuth(BaiduSensitiveConfig.API_KEY, BaiduSensitiveConfig.SECRET_KEY));
    }

    /**
     * 获取API访问权限token
     *
     * @return
     */
    public static String getAuth() {
        //百度云应用的AK  百度云应用的SK
        return getAuth(BaiduSensitiveConfig.API_KEY, BaiduSensitiveConfig.SECRET_KEY);
    }

    /**
     * 获取API访问权限token,该token有一定的有效期,需要自行管理,当失效时需重新获取。
     *
     * @param ak 百度云官网获取的 API Key
     * @param sk 百度云官网获取的 Securet Key
     * @return assess_token 示例:
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public static String getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.out.println("===Token_Result:===" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败!");
            e.printStackTrace(System.err);
        }
        return null;
    }

}

4. 封装接口的返回结果Bean

package entity;

import java.util.List;

/**
 * 文本审核结果返回
 */
public class TextCheckReturn {

    private long log_id;//请求唯一id,用于问题定位
    private String conclusion;//审核结果,可取值:合规、不合规、疑似、审核失败
    private Integer conclusionType;//审核结果类型,可取值1.合规,2.不合规,3.疑似,4.审核失败
    private List<TextData> data;//不合规/疑似/命中白名单项详细信息

    public long getLog_id() {
        return log_id;
    }

    public void setLog_id(long log_id) {
        this.log_id = log_id;
    }

    public String getConclusion() {
        return conclusion;
    }

    public void setConclusion(String conclusion) {
        this.conclusion = conclusion;
    }

    public Integer getConclusionType() {
        return conclusionType;
    }

    public void setConclusionType(Integer conclusionType) {
        this.conclusionType = conclusionType;
    }

    public List<TextData> getData() {
        return data;
    }

    public void setData(List<TextData> data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "{" +
                "log_id=" + log_id +
                ", conclusion='" + conclusion + '\'' +
                ", conclusionType=" + conclusionType +
                ", data=" + data +
                '}';
    }
}
package entity;

import java.util.List;

/**
 * 图像审核结果返回
 */
public class ImageCheckReturn {

    private long log_id;//请求唯一id,用于问题定位
    private String conclusion;//审核结果,可取值:合规、不合规、疑似、审核失败
    private Integer conclusionType;//审核结果类型,可取值1.合规,2.不合规,3.疑似,4.审核失败
    private List<ImageData> data;//不合规/疑似/命中白名单项详细信息

    public long getLog_id() {
        return log_id;
    }

    public void setLog_id(long log_id) {
        this.log_id = log_id;
    }

    public String getConclusion() {
        return conclusion;
    }

    public void setConclusion(String conclusion) {
        this.conclusion = conclusion;
    }

    public Integer getConclusionType() {
        return conclusionType;
    }

    public void setConclusionType(Integer conclusionType) {
        this.conclusionType = conclusionType;
    }

    public List<ImageData> getData() {
        return data;
    }

    public void setData(List<ImageData> data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "{" +
                "log_id=" + log_id +
                ", conclusion='" + conclusion + '\'' +
                ", conclusionType=" + conclusionType +
                ", data=" + data +
                '}';
    }
}
package entity;

import java.util.List;

/**
 * 不合规/疑似/命中白名单项详细信息
 */
public class TextData {

    private String msg;//不合规项描述信息
    private List<Hits> hits;//命中关键词信息

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public List<Hits> getHits() {
        return hits;
    }

    public void setHits(List<Hits> hits) {
        this.hits = hits;
    }

    @Override
    public String toString() {
        return "{" +
                "msg='" + msg + '\'' +
                ", hits=" + hits +
                '}';
    }
}
package entity;

import java.util.List;

/**
 * 命中关键词信息
 */
public class Hits {

    private String datasetName;//违规项目所属数据集名称
    private List<String> words;//违规文本关键字

    public String getDatasetName() {
        return datasetName;
    }

    public void setDatasetName(String datasetName) {
        this.datasetName = datasetName;
    }

    public List<String> getWords() {
        return words;
    }

    public void setWords(List<String> words) {
        this.words = words;
    }

    @Override
    public String toString() {
        return "{" +
                "datasetName='" + datasetName + '\'' +
                ", words=" + words +
                '}';
    }
}

5. 文本、图像审核功能代码

package entity;

public enum ReturnStatusEnum {

    SUCCESS(0),//成功
    FAILURE(1);//失败

    private final int value;

    ReturnStatusEnum(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

package api;

import auth.AccessToken;
import auth.BaiduSensitiveConfig;
import com.alibaba.fastjson.JSON;
import entity.ImageCheckReturn;
import entity.ReturnStatusEnum;
import entity.TextCheckReturn;
import utils.Base64Util;
import utils.FileUtil;
import utils.HttpUtil;

import java.io.File;
import java.net.URLEncoder;
import java.util.Map;
import java.util.TreeMap;

/**
 * 内容审核
 */
public class CheckContent {

    /**
     * 文本审核
     *
     * @param text 需要审核的文本
     * @return
     */
    public static Map<String, Object> checkText(String text) {
        Map<String, Object> map = new TreeMap<String, Object>();
        //获取access_token
        String access_token = AccessToken.getAuth();
        try {
            //设置请求的编码
            String param = "text=" + URLEncoder.encode(text, "UTF-8");
            //调用文本审核接口并取得结果
            String result = HttpUtil.post(BaiduSensitiveConfig.CHECK_TEXT_URL, access_token, param);

            // JSON解析对象
            TextCheckReturn tcr = JSON.parseObject(result, TextCheckReturn.class);
            Integer conclusionType = tcr.getConclusionType();
            if (conclusionType != 1 && !conclusionType.equals("1")) {
                map.put("code", ReturnStatusEnum.FAILURE.getValue());
                map.put("log_id", tcr.getLog_id());
                map.put("conclusion", tcr.getConclusion());
                map.put("conclusionType", conclusionType);
                map.put("data", tcr.getData());
                return map;
            }
            map.put("code", ReturnStatusEnum.SUCCESS.getValue());
            map.put("log_id", tcr.getLog_id());
            map.put("conclusion", tcr.getConclusion());
            map.put("conclusionType", tcr.getConclusionType());
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 图像审核
     *
     * @param imagePath 需要审核的图片路径
     * @return
     */
    public static Map<String, Object> checkImage(String imagePath) {
        if (!new File(imagePath).exists()) {
            throw new NullPointerException("图片不存在");
        }
        Map<String, Object> map = new TreeMap<String, Object>();
        //获取access_token
        String access_token = AccessToken.getAuth();
        try {
            //据文件路径读取byte[]数组
            byte[] imgData = FileUtil.readFileByBytes(imagePath);
            //Base64格式编码
            String imgStr = Base64Util.encode(imgData);
            //URLEncoder格式化编码
            String param = "image=" + URLEncoder.encode(imgStr, "UTF-8");
            //调用图像审核接口
            String result = HttpUtil.post(BaiduSensitiveConfig.CHECK_IMAGE_URL, access_token, param);

            //JSON解析对象
            ImageCheckReturn icr = JSON.parseObject(result, ImageCheckReturn.class);
            Integer conclusionType = icr.getConclusionType();
            if (conclusionType != 1 && !conclusionType.equals("1")) {
                map.put("code", ReturnStatusEnum.FAILURE.getValue());
                map.put("log_id", icr.getLog_id());
                map.put("conclusion", icr.getConclusion());
                map.put("conclusionType", icr.getConclusionType());
                map.put("data", icr.getData());
                return map;
            }
            map.put("code", ReturnStatusEnum.SUCCESS.getValue());
            map.put("log_id", icr.getLog_id());
            map.put("conclusion", icr.getConclusion());
            map.put("conclusionType", icr.getConclusionType());
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

6. 测试

package test;

import api.CheckImageAPI;
import api.CheckTextAPI;
import org.junit.Test;

import java.util.Iterator;
import java.util.Map;

public class TestCheckContent {

    @Test
    public void testText() {
        //成功
        //Map<String, Object> map = CheckTextAPI.checkText("你好");
        //失败
        Map<String, Object> map = CheckTextAPI.checkText("电话 找小姐");

        Iterator<String> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            Object value = map.get(key);
            System.out.println(key + ":" + value);
        }
    }

    @Test
    public void testImage() {
        //成功
        //String imagePath = "C:\\Users\\42405\\Pictures\\Camera Roll\\ca86e620b9e623ff-b8de023d66d64f20-b6d3d90793936caf591d615d1c99b0e2.jpg";
        //失败
        String imagePath = "C:\\Users\\42405\\Pictures\\Camera Roll\\audit%2Fdemo%2Fcensoring-demo.jpg";
        Map<String, Object> map = CheckImageAPI.checkImage(imagePath);

        Iterator<String> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            Object value = map.get(key);
            System.out.println(key + ":" + value);
        }
    }

}

7. 结果

文本审核(接口说明

图像审核(接口说明

附(参考):

https://ai.baidu.com/forum/topic/show/497608

http://aixiaoshuai.mydoc.io/?t=234826

https://blog.csdn.net/qq_36813807/article/details/82499233?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param

你的鼓励将是我创作的最大动力

 

转载请注明出处:BestEternity亲笔。

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值