阿里云sdk请求文本审核(项目使用)

pom.xml配置如下:

<dependency>
	<groupId>com.aliyun</groupId>
	<artifactId>green20220302</artifactId>
	<version>2.2.8</version>
</dependency>

Java代码如下:

package com.ksource.api.audit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ksource.api.constant.AIConstant;
import com.aliyun.green20220302.models.TextModerationRequest;
import com.aliyun.green20220302.models.TextModerationResponse;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.TextModerationResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.ksource.common.api.entity.ModelTemplate;

import java.util.*;

/**
 * @Author dxy
 * @Date 2024/10/29 17:51
 * @Description 阿里云文本审核入口
 */
public class AliyunContentAudit {


    /**
     * @description: 从账号池取值后调用阿里云文本审核接口
     * @author: dxy
     * @date: 2024/11/1 11:25
     * @param: text
     * @param: modelTemplate
     * @return: java.lang.Boolean
     */
    public static Boolean modelRequestByPoolObjJudge(String text, ModelTemplate modelTemplate){
        JSONObject modelParamObj=modelTemplate.getAccount();
        /*权限认证参数*/
        String accessKeyId = modelParamObj.getString(AIConstant.API_KEY);
        String accessKeySecret = modelParamObj.getString(AIConstant.SECRET_KEY);
        /*请求地址*/
        String apiAddress=modelTemplate.getApiAddress();
        try{
            Map<String, String> resultMap = textScan(text,accessKeyId,accessKeySecret,apiAddress);
            // 打印文本审核结果,Block为未通过,Pass为通过
            String suggestionVal = resultMap.get(AIConstant.SUGGESTION);
            if (AIConstant.PASS.equals(suggestionVal)){
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @description: 文本审核
     * @author: dxy
     * @date: 2024/11/1 11:28
     * @param: text
     * @param: accessKeyId
     * @param: accessKeySecret
     * @return: java.util.Map
     */
    public static Map textScan(String text, String accessKeyId, String accessKeySecret, String apiAddress) throws Exception {
        Config config = new Config();
        config.setAccessKeyId(accessKeyId);
        config.setAccessKeySecret(accessKeySecret);
        //接入区域和地址请根据实际情况修改
        config.setRegionId("cn-shanghai");
        config.setEndpoint(apiAddress);
        //连接时超时时间,单位毫秒(ms)。
        config.setReadTimeout(6000);
        //读取时超时时间,单位毫秒(ms)。
        config.setConnectTimeout(3000);
        Client client = new Client(config);

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

        //检测参数构造
        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put(AIConstant.CONTENT, text);

        //检测结果构造
        Map<String,String> resultMap = new HashMap<>();
        if (serviceParameters.get(AIConstant.CONTENT) == null || serviceParameters.getString(AIConstant.CONTENT).trim().length() == 0) {
            resultMap.put(AIConstant.SUGGESTION,"检测内容为空");
            System.out.println("text moderation content is empty");
            return resultMap;
        }
        TextModerationRequest textModerationRequest = new TextModerationRequest();
        //文本检测service:内容安全控制台文本增强版规则配置的serviceCode,示例:chat_detection
        textModerationRequest.setService("comment_detection");
        textModerationRequest.setServiceParameters(serviceParameters.toJSONString());

        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();
                        if (data.getLabels().isEmpty() && data.getReason().isEmpty()) {
                            resultMap.put(AIConstant.SUGGESTION, AIConstant.PASS);
                        }else {
                            resultMap.put(AIConstant.SUGGESTION, AIConstant.BLOCK);
                            resultMap.put("labels",data.getLabels());
                            resultMap.put("reason", data.getReason());
                        }
                        System.out.println("labels = [" + data.getLabels() + "]");
                        System.out.println("reason = [" + data.getReason() + "]");
                    } else {
                        System.out.println("text moderation not success. code:" + code);
                    }
                } else {
                    System.out.println("response not success. status:" + response.getStatusCode());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }
}
posted @ 2025-03-12 11:46  岁月淡忘了谁  阅读(90)  评论(0)    收藏  举报