TencentcloudUtils.java 6.24 KB
Newer Older
刘基明's avatar
刘基明 committed
1 2
package com.tanpu.community.util;

张辰's avatar
张辰 committed
3
import com.tanpu.common.api.*;
刘基明's avatar
刘基明 committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
import com.tanpu.common.constant.ErrorCodeConstant;
import com.tencentcloudapi.cms.v20190321.CmsClient;
import com.tencentcloudapi.cms.v20190321.models.ImageModerationRequest;
import com.tencentcloudapi.cms.v20190321.models.ImageModerationResponse;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.tms.v20200713.TmsClient;
import com.tencentcloudapi.tms.v20200713.models.TextModerationRequest;
import com.tencentcloudapi.tms.v20200713.models.TextModerationResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;

/**
 * 腾讯云工具类
 */
@Slf4j
@Configuration
public class TencentcloudUtils {

    /**
     * 腾讯云的SecretId
     */
    private static String secretId;
    /**
     * 腾讯云的SecretKey
     */
    private static String secretKey;

    /**
     * 腾讯云地区
     */
    private static String region;

    private static TmsClient tmsClient;

    private static CmsClient cmsClient;

    @Value("${tencent.cloud.secretId}")
    public void setSecretId(String secretId) {
        TencentcloudUtils.secretId = secretId;
    }

    @Value("${tencent.cloud.secretKey}")
    public void setSecretKey(String secretKey) {
        TencentcloudUtils.secretKey = secretKey;
    }

    @Value("${tencent.cloud.region}")
    public void setRegion(String region) {
        TencentcloudUtils.region = region;
    }


    public static TmsClient getTmsClient() {
        if (tmsClient == null) {
            tmsClient = new TmsClient(new Credential(secretId, secretKey), region);
        }
        return tmsClient;
    }

    public static CmsClient getCmsClient() {
        if (cmsClient == null) {
            cmsClient = new CmsClient(new Credential(secretId, secretKey), region);
        }
        return cmsClient;
    }

    /**
     * 文本内容安全
     *
     * @param text
     * @return
     */
82
    public static String textModeration(String text) {
刘基明's avatar
刘基明 committed
83 84 85 86 87 88
        TextModerationRequest req = new TextModerationRequest();
        req.setContent(Base64.getEncoder().encodeToString(text.getBytes(StandardCharsets.UTF_8)));
        TextModerationResponse res = null;
        try {
            res = getTmsClient().TextModeration(req);
            // suggestion Block 不通过
89 90
            if (res.getSuggestion().equals("Block") && res.getKeywords().length > 0) {
                return ":"+res.getKeywords()[0];
刘基明's avatar
刘基明 committed
91 92 93
            }
        } catch (TencentCloudSDKException e) {
            log.error("调用腾文本内容安全异常");
刘基明's avatar
刘基明 committed
94
            //调用失败时,不影响用户发布主题
95
            return "";
刘基明's avatar
刘基明 committed
96
        }
97
        return "";
刘基明's avatar
刘基明 committed
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
    }

    /**
     * 图片内容检测
     *
     * @param imageUrl
     * @return
     */
    public static CommonResp imageModeration(String imageUrl) {
        ImageModerationRequest req = new ImageModerationRequest();
        req.setFileUrl(imageUrl);
        ImageModerationResponse res = null;
        try {
            res = getCmsClient().ImageModeration(req);
            if (res.getData() != null && res.getData().getEvilType() != 100) {
                return CommonResp.error(ErrorCodeConstant.CONTENT_ILLEGAL, getImageLabel(res.getData().getEvilType()));
            }
        } catch (TencentCloudSDKException e) {
            log.error("调用腾讯图片内容检测异常");
            return CommonResp.failed("图片检查异常");
        }
        return CommonResp.success();
    }


    public static void main(String[] args) {
        final Base64.Encoder encoder = Base64.getEncoder();
        Credential cred = new Credential("AKIDTjjV2IhK4ZKBm8z5g14vPedNSJuFnTIq", "PaVBZfeQwDVXKr7TZOzM6c9VZNwGJGyA");
        TmsClient client = new TmsClient(cred, "ap-shanghai");
        CmsClient cmsClient = new CmsClient(cred, "ap-shanghai");
        TextModerationRequest req = new TextModerationRequest();
        req.setContent(encoder.encodeToString("卖毒品".getBytes(StandardCharsets.UTF_8)));

        ImageModerationRequest imgReq = new ImageModerationRequest();
        imgReq.setFileUrl("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.08lr.cn%2Fuploads%2Fallimg%2F170513%2F1-1F513164126.jpg&refer=http%3A%2F%2Fwww.08lr.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1617540249&t=2506e9bd61a31ea3bf89d07f4fe49744");
        try {
            TextModerationResponse res = client.TextModeration(req);
            ImageModerationResponse imgRes = cmsClient.ImageModeration(imgReq);
            System.out.println(Arrays.toString(res.getKeywords()));
            System.out.println(imgRes.getData());
        } catch (Exception e) {
139
//            e.printStackTrace();
刘基明's avatar
刘基明 committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
        }

    }

    public static String getTextLabel(String label, String[] keywords) {
        StringBuilder message = new StringBuilder("该内容包含");
        if (label.equals("Porn")) {
            message.append("色情");
        } else if (label.equals("Abuse")) {
            message.append("谩骂");
        } else if (label.equals("Ad")) {
            message.append("广告");
        } else if (label.equals("Polity")) {
            message.append("政治");
        } else if (label.equals("Illegal")) {
            message.append("违法");
        }
        message.append("等敏感词");
        if (keywords != null && keywords.length > 0) {
            message.append(" ");
            message.append(Arrays.toString(keywords));
        }
        return message.toString();
    }

    public static String getImageLabel(Long label) {
        StringBuilder message = new StringBuilder("该图片可能包含");
        if (label.equals(20002)) {
            message.append("色情");
        } else if (label.equals(20007)) {
            message.append("谩骂");
        } else if (label.equals(20001) || label.equals(24001)) {
            message.append("政治");
        } else if (label.equals(20006)) {
            message.append("违法");
        } else if (label.equals(20103)) {
            message.append("性感");
        }
        message.append("敏感内容");
        return message.toString();
    }
}