SpringBoot项目实现阿里云的文字以及图片审核
·
一.阿里云图片的上传以及审核 (通过图片的URL)
上传的图片URL需要是在阿里云商存储的图片路径,并且必须携带https:// 或者 http
@Slf4j
@Data
@ConfigurationProperties(prefix = "custom-config.upload-file.oss") //扫描配置文件
@Component
public class OssFileServiceImpl implements OssFileService
{
private String accessKey;
private String secretKey;
private String bucketName;
private String endpoint;
//设置获取client
private IAcsClient getClient() {
DefaultProfile profile = DefaultProfile.getProfile("cn-shenzhen", "your_accessKey", "your_secretKey");
DefaultProfile.addEndpoint("cn-shenzhen", "Green", "green.cn-shenzhen.aliyuncs.com"); //地区要和图片存储的地区一致
//实例化client , 重复使用可以提高检测性能
return new DefaultAcsClient(profile);
}
//将图片上传到Oss
@Override
public String uploadImg(byte[] base64, String fileName) {
try {
// 用于在OSS上命名,建议格式 :年月日/文件名.后缀名,此时可以 以时间建立一个文件夹保存上传的图片
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String transformDate = simpleDateFormat.format(new Date());
String objectName = transformDate + "/" + System.currentTimeMillis() + "_" + fileName;
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, secretKey);
// 设置设置 HTTP 头 里边的 Content-Type
ObjectMetadata objectMetadata = new ObjectMetadata();
// objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
objectMetadata.setContentDisposition("inline");
// 上传文件
ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(base64) , objectMetadata);
String url = bucketName+"."+endpoint +"/"+ objectName;
// 关闭OSSClient
ossClient.shutdown();
//审核图片
String err = checkUploadFile("https://"+url); //图片上传完成之后,拿到在阿里云商存储的链接 , 审核上传的图片
System.out.println(err);
if (err.equals("block") || err.equals("error")) {
return "error";
}
return url;
} catch (Exception e) {
// 处理异常
log.error("上传文件异常: " + e.getMessage(), e);
// 返回错误状态或抛出自定义异常
return "error";
}
}
//审核上传的图片
public static String checkUploadFile(String url) {
ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
//指定API返回格式
imageSyncScanRequest.setAcceptFormat(FormatType.JSON);
//指定请求方法
imageSyncScanRequest.setMethod(MethodType.POST);
imageSyncScanRequest.setEncoding("utf-8");
//支持http 和 https
imageSyncScanRequest.setProtocol(ProtocolType.HTTP);
JSONObject httpBody = new JSONObject();
/**
* 设置要检测的风险场景
* porn : 鉴黄
* terrorism : 暴恐
* ad : 广告
* live : 不良场景
* qrcode : 二维码
* logo : 商标
* 图片审核是分场景收费的
*/
httpBody.put("scenes" , Arrays.asList("porn","terrorism","ad","live","qrcode","logo"));
/**
* 设置待检测图片 , 一张图片对应一个task
*/
JSONObject task = new JSONObject();
task.put("dataId" , UUID.randomUUID().toString());
//设置图片链接为上传后的URL. URL中有特殊自读,需要对URL进行encode编码
task.put("url" , url);
task.put("time" , new Date());
httpBody.put("tasks" , Collections.singletonList(task));
imageSyncScanRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()),
"UTF-8", FormatType.JSON);
//设置超时时间
imageSyncScanRequest.setConnectTimeout(3000);
imageSyncScanRequest.setReadTimeout(10000);
HttpResponse httpResponse = null;
IAcsClient client = new OssFileServiceImpl().getClient();
try
{
httpResponse = client.doAction(imageSyncScanRequest);
}
catch (Exception e)
{
e.printStackTrace();
}
//服务端接收请求 , 完成处理后返回的结果
if (httpResponse != null && httpResponse.isSuccess())
{
JSONObject scrResponse = JSON.parseObject(org.apache.commons.codec.binary.StringUtils.newStringUtf8(httpResponse.getHttpContent()));
int requestCode = scrResponse.getIntValue("code");
//每一张图片的检测结果
JSONArray taskResults = scrResponse.getJSONArray("data");
if (200 == requestCode)
{
for (Object taskResult : taskResults)
{
//单张图片的处理结果
int taskCode = ((JSONObject) taskResult).getIntValue("code");
//图片对应检测场景的处理结果. 如果是多个场景 , 则会有每一个场景的检测结果
JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
if (200 == taskCode)
{
for (Object sceneResult : sceneResults)
{
System.out.println("开始审核");
String scene = ((JSONObject) sceneResult).getString("scene");
String suggestion = ((JSONObject) sceneResult).getString("suggestion");
//根据 scene 和 suggestion 做相关处理
System.out.println("scene = [" + scene + "]");
System.out.println("suggestion = [" + suggestion + "]");
if ("review".equals(suggestion) || "block".equals(suggestion))
{
System.out.println("图片审核不通过");
//只要不是"pass" , 直接拒绝 , 删除图片
OssFileServiceImpl ossFileService = new OssFileServiceImpl();
ossFileService.deleteImg(url);
return "block";
}
System.out.println("图片审核成功");
return "pass";
}
}
else
{
// 单张图片处理失败,原因视具体的情况详细分析。
System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
}
}
}
else
{
/**
* 表明请求整体处理失败,原因视具体的情况详细分析。
*/
System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
}
}
log.error("checkImageisFail");
return "error";
}
}
二.阿里云文字审核
文字审核和图片审核相似,但是文字审核是不分场景的.
@Slf4j
@Data
@Component
public class OssTxtServiceImpl implements OssTxtService {
private static final String region = "cn-shenzhen";
private String accessKey;
private String secretKey;
//设置获取client
private IAcsClient getClient() {
DefaultProfile profile = DefaultProfile.getProfile("cn-shenzhen", "your_accesskey", "your_secretkey");
DefaultProfile.addEndpoint("cn-shenzhen", "Green", "green.cn-shenzhen.aliyuncs.com");
//实例化client , 重复使用可以提高检测性能
// DefaultProfile profile1 = DefaultProfile.getProfile(region, accessKeyId, accessKeySecret);
return new DefaultAcsClient(profile);
}
@Override
public List<Map<String,String>> checkText(String text) throws UnsupportedEncodingException {
TextScanRequest textScanRequest = new TextScanRequest();
textScanRequest.setAcceptFormat(FormatType.JSON); // 指定API返回格式。
textScanRequest.setHttpContentType(FormatType.JSON);
textScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法。
textScanRequest.setEncoding("UTF-8");
textScanRequest.setRegionId(region);
List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
Map<String, Object> task1 = new LinkedHashMap<String, Object>();
task1.put("dataId", UUID.randomUUID().toString());
/**
* 待检测的文本,长度不超过10000个字符。
*/
task1.put("content", text);
tasks.add(task1);
JSONObject data = new JSONObject();
/**
* 检测场景。文本垃圾检测请传递antispam。
**/
data.put("scenes", Arrays.asList("antispam"));
data.put("tasks", tasks);
System.out.println(JSON.toJSONString(data, true));
textScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
// 请务必设置超时时间。
textScanRequest.setConnectTimeout(3000);
textScanRequest.setReadTimeout(6000);
try {
HttpResponse httpResponse = new OssTxtServiceImpl().getClient().doAction(textScanRequest);
if(httpResponse.isSuccess()){
JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
System.out.println(JSON.toJSONString(scrResponse, true));
if (200 == scrResponse.getInteger("code")) {
List<Map<String,String>> resultMaps = new ArrayList<>();
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做相关处理。
// suggestion为pass表示未命中垃圾。suggestion为block表示命中了垃圾,可以通过label字段查看命中的垃圾分类。
System.out.println("args = [" + scene + "]");
System.out.println("args = [" + suggestion + "]");
Map<String, String> resultMap = new HashMap<>();
resultMap.put("scene",scene);
resultMap.put("suggestion",suggestion);
resultMaps.add(resultMap);
}
}else{
System.out.println("task process fail:" + ((JSONObject)taskResult).getInteger("code"));
}
}
return resultMaps;
} else {
System.out.println("detect not success. code:" + scrResponse.getInteger("code"));
}
}else{
System.out.println("response not success. status:" + httpResponse.getStatus());
}
} catch (Exception e){
log.error("checkText is error" , e);
}
return null;
}
}
审核时传入需要审核的文字内容
返回值的一个List<Map<String , String>> 类型的数据,可以通过下面的方式获取到返回参数,判断审核是否通过.
//用户昵称审核
List<Map<String , String>> result = ossTxtService.checkText("需要审核的文本内容");
if ("block".equals(result.get(0).get("suggestion"))) {
return "审核不通过"
}
审核的文本内容最大字符长度是100000.
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)