本笔记内容为黑马头条项目的文本-图片内容审核接口部分
目录
一、概述
二、准备工作
三、文本内容审核接口
四、图片审核接口
五、项目集成
一、概述
内容安全是识别服务,支持对图片、视频、文本、语音等对象进行多样化场景检测,有效降低内容违规风险。
目前很多平台都支持内容检测,如阿里云、腾讯云、百度AI、网易云等国内大型互联网公司都对外提供了API。
按照性能和收费来看,黑马头条项目使用的就是阿里云的内容安全接口,使用到了图片和文本的审核。
阿里云收费标准:价格计算器 (aliyun.com)
二、准备工作
您在使用内容检测API之前,需要先注册阿里云账号,添加Access Key并签约云盾内容安全。
操作步骤
1、前往阿里云官网注册账号。如果已有注册账号,请跳过此步骤。
进入阿里云首页后,如果没有阿里云的账户需要先进行注册,才可以进行登录。由于注册较为简单,课程和讲义不在进行体现(注册可以使用多种方式,如淘宝账号、支付宝账号、微博账号等...)。需要实名认证和活体认证。
2、打开云盾内容安全产品试用页面,单击立即开通,正式开通服务。
注意 :现在这个服务需要企业认证才能使用
所以我改用了阿里视觉智能开发平台的审核功能视觉智能开放平台-控制台 (aliyun.com)

购买资源包,我第一次购买不用钱,免费送了1万点

3、在AccessKey管理页面管理您的AccessKeyID和AccessKeySecret。

管理自己的AccessKey,可以新建和删除AccessKey

查看自己的AccessKey,AccessKey默认是隐藏的,第一次申请的时候可以保存AccessKey,点击显示,通过验证手机号后也可以查看

三、文本内容审核接口
文本垃圾内容检测: 文本内容安全 (aliyun.com)

文本垃圾内容Java SDK: Java (aliyun.com)
四、图片审核接口
图片垃圾内容检测:图片内容安全 (aliyun.com)

图片垃圾内容Java SDK:Java (aliyun.com)
五、项目集成
这里的代码是使用智能开发平台的审核功能
①:common模块下面添加工具类,并添加到自动配置
aliyun包下的GreenImageScan.java和GreenTextScan.java

GreenImageScan代码
package com.heima.common.aliyun;
import com.alibaba.fastjson.JSON;
import com.aliyun.imageaudit20191230.models.ScanImageRequest;
import com.aliyun.imageaudit20191230.models.ScanImageResponse;
import com.aliyun.imageaudit20191230.models.ScanImageResponseBody;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.*;
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "aliyun")
public class GreenImageScan {
    private String accessKeyId;
    private String secret;
    private String scenes;
    public Map imageScan(List<String> imageList) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(secret);
        // 访问的域名
        config.endpoint = "imageaudit.cn-shanghai.aliyuncs.com";
        com.aliyun.imageaudit20191230.Client client = new com.aliyun.imageaudit20191230.Client(config);
        List<ScanImageRequest.ScanImageRequestTask> taskList = new ArrayList<>();
        for (String  img: imageList) {
            ScanImageRequest.ScanImageRequestTask task = new ScanImageRequest.ScanImageRequestTask();
            task.setImageURL(img);
            task.setDataId(UUID.randomUUID().toString());
            task.setImageTimeMillisecond(1L);
            task.setInterval(1);
            task.setMaxFrames(1);
            taskList.add(task);
        }
        //场景
        List<String> sceneList = new ArrayList<>();
        sceneList.add(scenes);
        sceneList.add("logo");
        sceneList.add("porn");
        com.aliyun.imageaudit20191230.models.ScanImageRequest scanImageRequest = new com.aliyun.imageaudit20191230.models.ScanImageRequest()
                .setTask(taskList)
                .setScene(sceneList);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            ScanImageResponse scanImageResponse = client.scanImageWithOptions(scanImageRequest, runtime);
            Map<String, String> resultMap = new HashMap<>();
            if (scanImageResponse.getStatusCode() == 200) {
                List<ScanImageResponseBody.ScanImageResponseBodyDataResultsSubResults> subResults = scanImageResponse.body.data.results.get(0).getSubResults();
               
                ListIterator<ScanImageResponseBody.ScanImageResponseBodyDataResultsSubResults> listIterator = subResults.listIterator();
                while (listIterator.hasNext()) {
                    ScanImageResponseBody.ScanImageResponseBodyDataResultsSubResults item = listIterator.next();
                    System.out.println("scene = [" + item.scene + "]");
                    System.out.println("suggestion = [" + item.suggestion + "]");
                    System.out.println("label = [" + item.label + "]");
                    if (!item.suggestion.equals("pass")) {
                        resultMap.put("suggestion", item.suggestion);
                        resultMap.put("label", item.label);
                        return resultMap;
                    }
                }
                resultMap.put("suggestion", "pass");
            } else {
              /*   *
                 * 表明请求整体处理失败,原因视具体的情况详细分析
                 */
                System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scanImageResponse));
                return null;
            }
        } catch (com.aliyun.tea.TeaException teaException) {
            // 获取整体报错信息
            System.out.println(com.aliyun.teautil.Common.toJSONString(teaException));
            // 获取单个字段
            System.out.println(teaException.getCode());
        }
        return null;
      /*  Map<String, String> resultMap = new HashMap<>();
        resultMap.put("suggestion", "pass");
        return resultMap;*/
    }
}GreenTextScan代码
package com.heima.common.aliyun;
import com.aliyun.imageaudit20191230.*;
import com.aliyun.imageaudit20191230.models.ScanTextRequest;
import com.aliyun.imageaudit20191230.models.ScanTextResponse;
import com.aliyun.imageaudit20191230.models.ScanTextResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.*;
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "aliyun")
public class GreenTextScan {
    private String accessKeyId;
    private String secret;
    public Map greeTextScan(String content) throws Exception {
        /*
          初始化配置对象com.aliyun.teaopenapi.models.Config
          Config对象存放 AccessKeyId、AccessKeySecret、endpoint等配置
         */
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(secret);
        // 访问的域名
        config.endpoint = "imageaudit.cn-shanghai.aliyuncs.com";
        Client client = new Client(config);
        ScanTextRequest.ScanTextRequestTasks tasks = new ScanTextRequest.ScanTextRequestTasks()
                .setContent(content);  //审核内容
        ScanTextRequest.ScanTextRequestLabels labels = new ScanTextRequest.ScanTextRequestLabels()
                .setLabel("abuse");  //设置审核类型
        ScanTextRequest scanTextRequest = new ScanTextRequest()
                .setLabels(java.util.Arrays.asList(
                        labels
                ))
                .setTasks(java.util.Arrays.asList(
                        tasks
                ));
        RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        Map<String, String> resultMap = new HashMap<>();
        try {
            // 复制代码运行请自行打印API的返回值
            ScanTextResponse response = client.scanTextWithOptions(scanTextRequest, runtime);
         
            //System.out.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response)));
            if (response.getStatusCode() == 200) {
                ScanTextResponseBody.ScanTextResponseBodyDataElementsResults elementsResults = response.body.getData().elements.get(0).results.get(0);
                if (!elementsResults.suggestion.equals("pass")) {
                    resultMap.put("suggestion", elementsResults.suggestion);
                    resultMap.put("label", elementsResults.label);
                    return resultMap;
                }
                resultMap.put("suggestion", "pass");
                return resultMap;
            } else {
                return null;
            }
        } catch (TeaException error) {
            // 获取整体报错信息
            System.out.println(com.aliyun.teautil.Common.toJSONString(error));
            // 获取单个字段
            System.out.println(error.getCode());
            error.printStackTrace();
        }
        return null;
    }
}添加到自动配置中

②: accessKeyId和secret(需自己申请)
在heima-leadnews-wemedia中的nacos配置中心添加以下配置:
aliyun:
 accessKeyId: LTAI5tCWHCcfvqQzu8k2oKmX
 secret: auoKUFsghimbfVQHpy7gtRyBkoR4vc
#aliyun.scenes=porn,terrorism,ad,qrcode,live,logo
 scenes: terrorism③:在自媒体微服务中测试类中注入审核文本和图片的bean进行测试
package com.heima.wemedia;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.file.service.FileStorageService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@SpringBootTest(classes = WemediaApplication.class)
@RunWith(SpringRunner.class)
public class AliyunTest {
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private FileStorageService fileStorageService;
    @Test
    public void testScanText() throws Exception {
        Map map = greenTextScan.greeTextScan("王天刚去饭店吃饭后发现自己的车子被刮了,破口大骂是哪个傻逼干的?");
        System.out.println(map);
    }
    @Test
    public void testScanImage() throws Exception {
        List<String> list=new ArrayList<>();
        list.add("http://192.168.200.130:9000/leadnews/2021/04/26/ef3cbe458db249f7bd6fb4339e593e55.jpg");
        Map map = greenImageScan.imageScan(list);
        System.out.println(map);
    }
}结束!


















