XX头条-阿里云内容安全-(文本、图片审核增强版代码)

1.文本审核

public class TextAutoRoute {

    private String accessKeyId;
    private String secret;
    private String GreenEndPoint;

    public Map textAutoRoute(String content) throws Exception {
        Config config = new Config();

        config.setAccessKeyId(accessKeyId);
        config.setAccessKeySecret(secret);
        //接入区域和地址请根据实际情况修改
        config.setRegionId("cn-beijing");
        config.setEndpoint(GreenEndPoint);

        //连接时超时时间,单位毫秒(ms)。
        config.setReadTimeout(6000);
        //读取时超时时间,单位毫秒(ms)。
        config.setConnectTimeout(3000);
        // 注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能
        Client client = new Client(config);

        // 创建RuntimeObject实例并设置运行参数。
        RuntimeOptions runtime = new RuntimeOptions();
        runtime.readTimeout = 10000;
        runtime.connectTimeout = 10000;

        //检测参数构造
        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("content", content);

        if (serviceParameters.get("content") == null || serviceParameters.getString("content").trim().length() == 0) {
            System.out.println("text moderation content is empty");
            return null;
        }

        TextModerationRequest textModerationRequest = new TextModerationRequest();
        //文本检测service:内容安全控制台文本增强版规则配置的serviceCode,示例:chat_detection
        textModerationRequest.setService("chat_detection");
        textModerationRequest.setServiceParameters(serviceParameters.toJSONString());

        // 返回参数Map
        Map<String, String> resultMap = new HashMap<>();

        try {
            // 调用方法获取检测结果。
            TextModerationResponse response = client.textModerationWithOptions(textModerationRequest, runtime);

            // 自动路由。
            if (response != null) {
                // 服务端错误,区域切换到cn-beijing。
                if (500 == response.getStatusCode() || (response.getBody() != null && 500 == (response.getBody().getCode()))) {
                    // 接入区域和地址请根据实际情况修改。
                    config.setRegionId("cn-beijing");
                    config.setEndpoint("green-cip.cn-beijing.aliyuncs.com");
                    client = new Client(config);
                    response = client.textModerationWithOptions(textModerationRequest, runtime);
                }

            }
            // 打印检测结果。
            if (response != null) {
                if (response.getStatusCode() == 200) {
                    TextModerationResponseBody result = response.getBody();
                    System.out.println(JSON.toJSONString(result));
                    Integer code = result.getCode();
                    if (code != null && code == 200) {
                        TextModerationResponseBody.TextModerationResponseBodyData data = result.getData();
                        System.out.println("labels = [" + data.getLabels() + "]");
                        System.out.println("reason = [" + data.getReason() + "]");

                        String label = data.getLabels();
                        resultMap.put("label", label);
                        if (label.isEmpty()) {
                            resultMap.put("suggestion", "pass");
                        } else {
                            resultMap.put("suggestion", "block");
                        }

                        return resultMap;

                    } else {
                        System.out.println("text moderation not success. code:" + code);
                        return null;
                    }
                } else {
                    System.out.println("response not success. status:" + response.getStatusCode());
                    return null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

测试

    @Test
    public void testScanText() throws Exception {
        Map map = textAutoRoute.textAutoRoute("大麻是毒品");
        System.out.println(map);
    }

测试结果

{suggestion=block, label=contraband}

2.图片审核

public class ImageUploadAndCheck {

    private String accessKeyId;
    private String secret;
    private String OssEndPoint;
    private String GreenEndPoint;

    public Map imageUploadAndCheck(byte[] content) throws Exception {
        // 填写Bucket名称
        String bucketName = "can-qiong-wai-mai";
        // 填写Object完整路径(文件名)
        String objectName = UUID.randomUUID() + ".jpg";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(OssEndPoint, accessKeyId, secret);

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(content));

            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return check(bucketName, objectName);
    }

    // 开始审核图片
    private Map check(String bucketName, String objectName) throws Exception {
        // 返回参数Map
        Map<String, String> resultMap = new HashMap<>();

        ImageModerationResponse response = invokeFunction(accessKeyId, secret, GreenEndPoint, bucketName, objectName);
        try {
            if (response != null) {
                if (response.getStatusCode() == 200) {
                    ImageModerationResponseBody body = response.getBody();
                    System.out.println("requestId=" + body.getRequestId());
                    System.out.println("code=" + body.getCode());
                    System.out.println("msg=" + body.getMsg());
                    if (body.getCode() == 200) {
                        ImageModerationResponseBody.ImageModerationResponseBodyData data = body.getData();
                        System.out.println("dataId=" + data.getDataId());
                        List<ImageModerationResponseBody.ImageModerationResponseBodyDataResult> results = data.getResult();
                        for (ImageModerationResponseBody.ImageModerationResponseBodyDataResult result : results) {
                            System.out.println("label=" + result.getLabel());
                            System.out.println("confidence=" + result.getConfidence());
                            String label = result.getLabel();
                            if (label.equals("nonLabel")) {
                                resultMap.put("suggestion", "pass");
                            } else {
                                resultMap.put("suggestion", "block");
                                resultMap.put("label", label);
                            }
                        }
                    } else {
                        System.out.println("image moderation not success. code:" + body.getCode());
                    }
                } else {
                    System.out.println("response not success. status:" + response.getStatusCode());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    private ImageModerationResponse invokeFunction(String accessKeyId, String secret, String GreenEndPoint, String bucketName, String objectName) throws Exception {
        //注意,此处实例化的client请尽可能重复使用,避免重复建立连接,提升检测性能。
        Client client = createClient(accessKeyId, secret, GreenEndPoint);
        // 创建RuntimeObject实例并设置运行参数
        RuntimeOptions runtime = new RuntimeOptions();
        // 检测参数构造。
        Map<String, String> serviceParameters = new HashMap<>();
        //待检测数据唯一标识
        serviceParameters.put("dataId", UUID.randomUUID().toString());
        // 待检测文件所在bucket的区域。
        serviceParameters.put("ossRegionId", "cn-beijing");
        // 待检测文件所在bucket名称。示例:bucket001
        serviceParameters.put("ossBucketName", bucketName);
        // 待检测文件。 示例:image/001.jpg
        serviceParameters.put("ossObjectName", objectName);

        ImageModerationRequest request = new ImageModerationRequest();
        // 图片检测service:内容安全控制台图片增强版规则配置的serviceCode,示例:baselineCheck
        // 支持service请参考:https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
        request.setService("baselineCheck");
        request.setServiceParameters(JSON.toJSONString(serviceParameters));

        ImageModerationResponse response = null;
        try {
            response = client.imageModerationWithOptions(request, runtime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    private Client createClient(String accessKeyId, String accessKeySecret, String GreenEndPoint) throws Exception {
        Config config = new Config();
        config.setAccessKeyId(accessKeyId);
        config.setAccessKeySecret(accessKeySecret);
        config.setEndpoint(GreenEndPoint);
        return new Client(config);
    }
}

测试

    @Test
    public void testScanImage() throws Exception {
        byte[] bytes = fileStorageService.downLoadFile("http://192.168.88.130:9000/leadnews/2024/03/05/63172a530aad480a9ada8aa63837e1db.jpg");
        Map map = imageUploadAndCheck.imageUploadAndCheck(bytes);
        System.out.println(map);
    }

测试结果

{suggestion=block, label=pornographic_adultContent}

3.配置

接入区域和地址请根据实际情况修改

aliyun:
  accessKeyId: 你的accessKeyId
  secret: 你的secret
  GreenEndPoint: green-cip.cn-china.aliyuncs.com       
  OssEndPoint: oss-cn-china.aliyuncs.com     

4.说明

  1. 文本审核改动不大
  2. 图片审核:先将虚拟机minio的图片下载,上传到阿里云OSS,在使用图片审核增强版的方法三,在OSS中审核
  3. WmNewsAutoScanServiceImpl审核图片记得遍历
  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值