阿里云内容审核增强版
请求参数
名称 | 类型 | 是否必须 | 示例值 | 描述 |
---|---|---|---|---|
service | String | 是 | nickname_detection | |
ServiceParameters | String | 是 |
service参数:
- nickname_detection:用户昵称检测
- chat_detection:私聊互动内容检测
- comment_detection:公聊评论内容检测
- ai_art_detection:AIGC文字检测
- ad_compliance_detection:广告法合规检测
- pgc_detection:PGC教学物料检测
ServiceParameters 参数:
返回参数:查看文档即可
示例
请求示例:
{
"Service":"nickname_detection",
"ServiceParameters":"{\"content\":\"检测内容\",\"accountId\":\"10123****\"}"
}
正常的返回示例:
{
"Code": 200,
"Data": {
"labels": "sexual_content",
"reason": "{\"riskTips\":\"色情_低俗词\",\"riskWords\":\"色情服务\"}"
},
"Message": "OK",
"RequestId": "AAAAAA-BBBB-CCCCC-DDDD-EEEEEEEE****"
}
错误的返回示例:
Maven依赖
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>green20220302</artifactId>
<version>1.0.7</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>tea-openapi</artifactId>
<version>0.2.8</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>tea-console</artifactId>
<version>0.0.1</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>tea-util</artifactId>
<version>0.2.16</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>tea</artifactId>
<version>1.1.14</version>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>
相关工具类
内容审核:
package com.heima.common.aliyun;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.TextModerationRequest;
import com.aliyun.green20220302.models.TextModerationResponse;
import com.aliyun.green20220302.models.TextModerationResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "aliyun")
public class GreenTextScan {
private String accessKeyId;
private String secret;
private String scenes;
public Map greeTextScan(String content) throws Exception {
System.out.println(accessKeyId);
Config config = new Config();
/**
* 阿里云账号AccessKey拥有所有API的访问权限,建议您使用RAM用户进行API访问或日常运维。
* 常见获取环境变量方式:
* 方式一:
* 获取RAM用户AccessKey ID:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
* 获取RAM用户AccessKey Secret:System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
* 方式二:
* 获取RAM用户AccessKey ID:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
* 获取RAM用户AccessKey Secret:System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
*/
config.setAccessKeyId(accessKeyId);
config.setAccessKeySecret(secret);
//接入区域和地址请根据实际情况修改
config.setRegionId("cn-shanghai");
config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
//连接时超时时间,单位毫秒(ms)。
config.setReadTimeout(6000);
//读取时超时时间,单位毫秒(ms)。
config.setConnectTimeout(3000);
//设置http代理。
//config.setHttpProxy("http://10.10.xx.xx:xxxx");
//设置https代理。
//config.setHttpsProxy("https://10.10.xx.xx:xxxx");
// 注意,此处实例化的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);
Map<String, String> resultMap = new HashMap<>();
if (serviceParameters.get("content") == null || serviceParameters.getString("content").trim().length() == 0) {
System.out.println("text moderation content is empty");
resultMap.put("code",String.valueOf( AppHttpCodeEnum.DATA_NOT_EXIST.getCode()));
}
TextModerationRequest textModerationRequest = new TextModerationRequest();
/*
文本检测服务 service code
*/
textModerationRequest.setService(scenes);
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();
resultMap.put("labels", JSON.toJSONString(data.getLabels()));
resultMap.put("reason", data.getReason());
if (data.getReason()==null || StringUtils.isEmpty(data.getReason())){
resultMap.put("suggestion", "pass");
}else {
resultMap.put("suggestion", "block");
}
} else {
resultMap.put("code", String.valueOf(code));
}
} else {
resultMap.put("code", String.valueOf(response.getStatusCode()));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return resultMap;
}
}
图片审核
package com.heima.common.aliyun;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.green.model.v20180509.ImageSyncScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.heima.common.aliyun.util.ClientUploader;
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<byte[]> imageList) throws Exception {
IClientProfile profile = DefaultProfile
.getProfile("cn-shanghai", accessKeyId, secret);
DefaultProfile
.addEndpoint("cn-shanghai", "cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
IAcsClient client = new DefaultAcsClient(profile);
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();
/**
* 设置要检测的场景, 计费是按照该处传递的场景进行
* 一次请求中可以同时检测多张图片,每张图片可以同时检测多个风险场景,计费按照场景计算
* 例如:检测2张图片,场景传递porn、terrorism,计费会按照2张图片鉴黄,2张图片暴恐检测计算
* porn: porn表示色情场景检测
*/
httpBody.put("scenes", Arrays.asList(scenes.split(",")));
/**
* 如果您要检测的文件存于本地服务器上,可以通过下述代码片生成url
* 再将返回的url作为图片地址传递到服务端进行检测
*/
/**
* 设置待检测图片, 一张图片一个task
* 多张图片同时检测时,处理的时间由最后一个处理完的图片决定
* 通常情况下批量检测的平均rt比单张检测的要长, 一次批量提交的图片数越多,rt被拉长的概率越高
* 这里以单张图片检测作为示例, 如果是批量图片检测,请自行构建多个task
*/
ClientUploader clientUploader = ClientUploader.getImageClientUploader(profile, false);
String url = null;
List<JSONObject> urlList = new ArrayList<JSONObject>();
for (byte[] bytes : imageList) {
url = clientUploader.uploadBytes(bytes);
JSONObject task = new JSONObject();
task.put("dataId", UUID.randomUUID().toString());
//设置图片链接为上传后的url
task.put("url", url);
task.put("time", new Date());
urlList.add(task);
}
httpBody.put("tasks", urlList);
imageSyncScanRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()),
"UTF-8", FormatType.JSON);
/**
* 请设置超时时间, 服务端全链路处理超时时间为10秒,请做相应设置
* 如果您设置的ReadTimeout小于服务端处理的时间,程序中会获得一个read timeout异常
*/
imageSyncScanRequest.setConnectTimeout(3000);
imageSyncScanRequest.setReadTimeout(10000);
HttpResponse httpResponse = null;
try {
httpResponse = client.doAction(imageSyncScanRequest);
} catch (Exception e) {
e.printStackTrace();
}
Map<String, String> resultMap = new HashMap<>();
//服务端接收到请求,并完成处理返回的结果
if (httpResponse != null && httpResponse.isSuccess()) {
JSONObject scrResponse = JSON.parseObject(org.apache.commons.codec.binary.StringUtils.newStringUtf8(httpResponse.getHttpContent()));
System.out.println(JSON.toJSONString(scrResponse, true));
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) {
String scene = ((JSONObject) sceneResult).getString("scene");
String label = ((JSONObject) sceneResult).getString("label");
String suggestion = ((JSONObject) sceneResult).getString("suggestion");
//根据scene和suggetion做相关处理
//do something
System.out.println("scene = [" + scene + "]");
System.out.println("suggestion = [" + suggestion + "]");
System.out.println("suggestion = [" + label + "]");
if (!suggestion.equals("pass")) {
resultMap.put("suggestion", suggestion);
resultMap.put("label", label);
return resultMap;
}
}
} else {
//单张图片处理失败, 原因视具体的情况详细分析
System.out.println("task process fail. task response:" + JSON.toJSONString(taskResult));
return null;
}
}
resultMap.put("suggestion","pass");
return resultMap;
} else {
/**
* 表明请求整体处理失败,原因视具体的情况详细分析
*/
System.out.println("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
return null;
}
}
return null;
}
}
查看代码:
我们通过@ConfigurationProperties()
注解实现配置的方式,配置自己的starter:
在resource目录下创建META-INF
在创建spring.factories
文件
内容为:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.heima.common.aliyun.GreenTextScan,\
com.heima.common.aliyun.GreenImageScan
这样在别的模块中引入这个坐标配置相关的属性就可以使用啦:
例如:在xxxx模块中引入该模块的maven坐标,然后在application.yml 文件中引入:
aliyun:
accessKeyId: xxxxxxxx
secret: xxxxxxxxxx
#aliyun.scenes=porn,terrorism,ad,qrcode,live,logo
scenes: terrorism
测试
@Resource
private GreenTextScan greenTextScan;
/**
* 测试文本内容审核
*/
@Test
public void TestScanText() throws Exception {
Map map = greenTextScan.greeTextScan("我要去赌博");
System.out.println(map);
}
返回结果:
{"code":200,"data":{"labels":"contraband","reason":"{\"riskTips\":\"违禁_违禁商品or赌博平台\",\"riskWords\":\"赌博\"}"},"message":"OK","requestId":"92D5CA0D-732D-56E8-8B83-10B094A86EBC"}
{reason={"riskTips":"违禁_违禁商品or赌博平台","riskWords":"赌博"}, suggestion=block, labels="contraband"}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库