由于黑马头条采用的阿里云内容审核1.0版本,我们没办法使用,这边我采用百度云服务
1.导入百度云jar包
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>4.16.2</version>
</dependency>
2.百度云鉴权认证工具
package com.heima.common.aliyun.baiduyun;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.springframework.http.HttpStatus;
import java.util.Calendar;
/**
* 百度云鉴权认证工具
*/
public class AuthUtil {
private static Calendar expireDate;
private static boolean flag = false;
private static String accessToken;
static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
private static Boolean needAuth() {
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 1);
return !flag || c.after(expireDate);
}
/**
* 获取权限token
* @return access_token
*/
public static String getAccessToken(String clientId, String clientSecret) throws Exception {
if (needAuth()) {
flag = true;
JSONObject auth = getAuth(clientId, clientSecret);
accessToken = auth.getString("access_token");
expireDate = Calendar.getInstance();
expireDate.add(Calendar.SECOND, auth.getIntValue("expires_in"));
}
return accessToken;
}
/**
* 从用户的AK,SK生成鉴权签名(Access Token)
*
* @return 鉴权签名(Access Token)
* @throws Exception IO异常
*/
private static JSONObject getAuth(String clientId, String clientSecret) throws Exception {
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "");
Request request = new Request.Builder()
.url(String.format("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s", clientId, clientSecret))
.method("POST", body)
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.build();
Response response = HTTP_CLIENT.newCall(request).execute();
if (response.code() != HttpStatus.OK.value()) {
throw new RuntimeException("百度云AccessToken获取失败");
}
return JSONObject.parseObject(response.body().string());
}
}
3.文本审核和图片审核
package com.heima.common.aliyun.baiduyun;
import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import java.util.*;
@Getter
@Setter
@Slf4j
@Component
@ConfigurationProperties(prefix = "baiduyun")
public class ContentCensor {
private String baiduyunId;
private String baiduyunSecret;
/**
* 文本审核
*
* @param text 待审核文本
* @return 审核结果 { log_id, conclusion, conclusionType }
* @throws Exception 审核异常
*/
public Map<String, Object> textCensor(String text) throws Exception {
String accessToken = AuthUtil.getAccessToken(baiduyunId, baiduyunSecret);
FormBody formBody = new FormBody.Builder().add("text", text).build();
Request request = new Request.Builder()
.url(String.format("https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=%s", accessToken))
.method("POST", formBody)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.addHeader("Accept", "application/json")
.build();
Response response = AuthUtil.HTTP_CLIENT.newCall(request).execute();
String strBody = response.body().string();
if (response.code() != HttpStatus.OK.value()) {
JSONObject errObj = JSONObject.parseObject(strBody);
log.error("百度文本审核接口调用失败:error_code: {}, error_msg: {}", errObj.getString("error_code"), errObj.getString("error_msg"));
throw new RuntimeException("百度文本审核接口调用失败");
}
JSONObject resultObj = JSONObject.parseObject(strBody);
System.out.println(resultObj);
Map<String, Object> result = new HashMap<>();
result.put("log_id", resultObj.getString("log_id"));
result.put("conclusion", resultObj.getString("conclusion"));
result.put("conclusionType", resultObj.getShortValue("conclusionType"));
return result;
}
/**
* 图像审核
*
* @param imgParams 待审核图像列表 Base64字符串列表
* @return 审核结果 { log_id, conclusion, conclusionType }
* @throws Exception 审核异常
*/
public Map imgCensor(ArrayList<byte[]> imgParams) throws Exception {
String accessToken = AuthUtil.getAccessToken(baiduyunId, baiduyunSecret);
Request.Builder builder = new Request.Builder()
.url(String.format("https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token=%s", accessToken))
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.addHeader("Accept", "application/json");
Map<String, Object> result = new HashMap<>();
for (Object imgParam : imgParams) {
FormBody formBody = new FormBody.Builder().add("image", String.valueOf(imgParam)).build();
Request request = builder.method("POST", formBody).build();
Response response = AuthUtil.HTTP_CLIENT.newCall(request).execute();
String strBody = response.body().string();
if (response.code() != HttpStatus.OK.value()) {
JSONObject errObj = JSONObject.parseObject(strBody);
log.error("百度图像审核接口调用失败:error_code: {}, error_msg: {}", errObj.getString("error_code"), errObj.getString("error_msg"));
throw new RuntimeException("百度文本审核接口调用失败");
}
JSONObject resultObj = JSONObject.parseObject(strBody);
System.out.println(resultObj);
Short conclusionType = resultObj.getShort("conclusionType");
// 审核不是通过
if (!Objects.equals(conclusionType, TextCensorResultEnum.COMPLIANCE.type())) {
result.put("log_id", resultObj.getString("log_id"));
result.put("conclusion", resultObj.getString("conclusion"));
result.put("conclusionType", resultObj.getShortValue("conclusionType"));
return result;
}
}
result.put("conclusionType", TextCensorResultEnum.COMPLIANCE.type());
return result;
}
}
4.使用枚举返回
package com.heima.common.aliyun.baiduyun;
public enum TextCensorResultEnum {
COMPLIANCE((short) 1, "合规"),
NON_COMPLIANCE((short) 2, "不合规"),
SUSPECTED((short) 3, "疑似"),
AUDIT_FAILED((short) 4, "审核失败");
private final Short type;
private final String desc;
TextCensorResultEnum(Short type, String desc) {
this.type = type;
this.desc = desc;
}
public Short type() {
return type;
}
public String desc() {
return desc;
}
}