AliyunContentSafetyService.java
`@Component
public class AliyunContentSafetyService {

  1. /**
  2. * 图片鉴黄
  3. */
  4. public static final String SCENE_PORN="porn";
  5. /**
  6. * 图片暴恐涉政
  7. */
  8. public static final String SCENE_TERRORISM="terrorism";
  9. /**
  10. * 图文违规
  11. */
  12. public static final String SCENE_AD="ad";
  13. /**
  14. * 图片二维码
  15. */
  16. public static final String SCENE_QRCODE="qrcode";
  17. /**
  18. * 图片不良场景
  19. */
  20. public static final String SCENE_LIVE="live";
  21. /**
  22. * 图片logo
  23. */
  24. public static final String SCENE_LOGO="logo";
  25. /**
  26. * 文本内容检测 文本检测不可和图片检测一起使用
  27. */
  28. public static final String SCENE_ANTISPAM="antispam";
  29. private static final Logger logger=LoggerFactory.getLogger(AliyunContentSafetyService.class);
  30. @Value("${oss.region}")
  31. private static String region;
  32. @Value("${oss.accessKeyId}")
  33. private static String accessKeyId;
  34. @Value("${oss.secretAccessKey}")
  35. private static String secretAccessKey;
  36. /**
  37. * 检测图片
  38. * @param scenes 官方检测场景
  39. * @param bizType 自定义业务检测场景
  40. * @param photos 需要检测的图片地址 非本地
  41. * @return
  42. */
  43. public static List<ContentSafetyResult> photoSafety(List<String> scenes,String bizType,List<String> photos) {
  44. if(photos == null || photos.isEmpty()) {
  45. logger.error("photos is empty");
  46. return null;
  47. }
  48. IClientProfile profile = DefaultProfile
  49. .getProfile(region, accessKeyId, secretAccessKey);
  50. IAcsClient client = new DefaultAcsClient(profile);
  51. ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
  52. // 指定API返回格式。
  53. imageSyncScanRequest.setAcceptFormat(FormatType.JSON);
  54. // 指定请求方法。
  55. imageSyncScanRequest.setMethod(MethodType.POST);
  56. imageSyncScanRequest.setEncoding("utf-8");
  57. // 支持HTTP和HTTPS。
  58. imageSyncScanRequest.setProtocol(ProtocolType.HTTP);
  59. JSONObject httpBody = new JSONObject();
  60. /**
  61. * 设置要检测的风险场景。计费依据此处传递的场景计算。
  62. * 一次请求中可以同时检测多张图片,每张图片可以同时检测多个风险场景,计费按照场景计算。
  63. * 例如,检测2张图片,场景传递porn和terrorism,计费会按照2张图片鉴黄,2张图片暴恐检测计算。
  64. * scenes:表示鉴黄场景。
  65. */
  66. httpBody.put("scenes", scenes);
  67. if(StringUtils.isBlank(bizType)) {
  68. httpBody.put("bizType", Arrays.asList(bizType));
  69. }
  70. List<JSONObject> tasks=new ArrayList<JSONObject>();
  71. for(String photo:photos) {
  72. /**
  73. * 设置待检测图片。一张图片对应一个task。
  74. * 多张图片同时检测时,处理的时间由最后一个处理完的图片决定。
  75. * 通常情况下批量检测的平均响应时间比单张检测的要长。一次批量提交的图片数越多,响应时间被拉长的概率越高。
  76. * 这里以单张图片检测作为示例, 如果是批量图片检测,请自行构建多个task。
  77. */
  78. JSONObject task = new JSONObject();
  79. task.put("dataId", UUID.randomUUID().toString());
  80. // 设置图片链接。
  81. task.put("url", photo);
  82. task.put("time", new Date());
  83. tasks.add(task);
  84. }
  85. httpBody.put("tasks", tasks);
  86. imageSyncScanRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()),
  87. "UTF-8", FormatType.JSON);
  88. /**
  89. * 请设置超时时间。服务端全链路处理超时时间为10秒,请做相应设置。
  90. * 如果您设置的ReadTimeout小于服务端处理的时间,程序中会获得一个read timeout异常。
  91. */
  92. imageSyncScanRequest.setConnectTimeout(3000);
  93. imageSyncScanRequest.setReadTimeout(10000);
  94. HttpResponse httpResponse = null;
  95. try {
  96. httpResponse = client.doAction(imageSyncScanRequest);
  97. logger.info("send photoSafety request");
  98. } catch (Exception e) {
  99. logger.error(e.getMessage(),e);
  100. }
  101. List<ContentSafetyResult> results=new ArrayList<ContentSafetyResult>();
  102. // 服务端接收到请求,完成处理后返回的结果。
  103. if (httpResponse != null && httpResponse.isSuccess()) {
  104. JSONObject scrResponse = JSON.parseObject(org.apache.commons.codec.binary.StringUtils.newStringUtf8(httpResponse.getHttpContent()));
  105. System.out.println(JSON.toJSONString(scrResponse, true));
  106. int requestCode = scrResponse.getIntValue("code");
  107. // 每一张图片的检测结果。
  108. JSONArray taskResults = scrResponse.getJSONArray("data");
  109. if (200 == requestCode) {
  110. for (Object taskResult : taskResults) {
  111. // 单张图片的处理结果。
  112. int taskCode = ((JSONObject) taskResult).getIntValue("code");
  113. // 图片对应检测场景的处理结果。如果是多个场景,则会有每个场景的结果。
  114. JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
  115. if (200 == taskCode) {
  116. for (Object sceneResult : sceneResults) {
  117. ContentSafetyResult result=new ContentSafetyResult();
  118. result.setScene(((JSONObject) sceneResult).getString("scene"));
  119. result.setSuggestion(((JSONObject) sceneResult).getString("suggestion"));
  120. result.setLabel(((JSONObject) sceneResult).getString("label"));
  121. result.setContent(((JSONObject) taskResult).getString("url"));
  122. result.setType(ContentSafetyResult.TYPE_PHOTO);
  123. results.add(result);
  124. }
  125. } else {
  126. // 单张图片处理失败, 原因视具体的情况详细分析。
  127. logger.error("task process fail. task response:" + JSON.toJSONString(taskResult));
  128. return null;
  129. }
  130. }
  131. } else {
  132. /**
  133. * 表明请求整体处理失败,原因视具体的情况详细分析。
  134. */
  135. logger.error("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
  136. return null;
  137. }
  138. }
  139. return results;
  140. }
  141. /**
  142. * 检测文字
  143. * @param content 要检测的文本
  144. * @param scene 官方检测场景
  145. * @return
  146. */
  147. public static List<ContentSafetyResult> textSafety(String content,String scene){
  148. if(StringUtils.isBlank(content)) {
  149. return null;
  150. }
  151. IClientProfile profile = DefaultProfile
  152. .getProfile(region, accessKeyId, secretAccessKey);
  153. IAcsClient client = new DefaultAcsClient(profile);
  154. TextScanRequest textScanRequest = new TextScanRequest();
  155. textScanRequest.setAcceptFormat(FormatType.JSON); // 指定API返回格式。
  156. textScanRequest.setHttpContentType(FormatType.JSON);
  157. textScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法。
  158. textScanRequest.setEncoding("UTF-8");
  159. textScanRequest.setRegionId("cn-beijing");
  160. List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
  161. Map<String, Object> task1 = new LinkedHashMap<String, Object>();
  162. task1.put("dataId", UUID.randomUUID().toString());
  163. /**
  164. * 待检测的文本,长度不超过10000个字符。
  165. */
  166. task1.put("content", content);
  167. tasks.add(task1);
  168. JSONObject data = new JSONObject();
  169. /**
  170. * 检测场景。文本垃圾检测请传递antispam。
  171. **/
  172. data.put("scenes", Arrays.asList(scene));
  173. data.put("tasks", tasks);
  174. try {
  175. textScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
  176. } catch (UnsupportedEncodingException e) {
  177. logger.error(e.getMessage(),e);
  178. return null;
  179. }
  180. // 请务必设置超时时间。
  181. textScanRequest.setConnectTimeout(3000);
  182. textScanRequest.setReadTimeout(6000);
  183. List<ContentSafetyResult> results=new ArrayList<ContentSafetyResult>();
  184. try {
  185. HttpResponse httpResponse = client.doAction(textScanRequest);
  186. if(httpResponse.isSuccess()){
  187. JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
  188. System.out.println(JSON.toJSONString(scrResponse, true));
  189. if (200 == scrResponse.getInteger("code")) {
  190. JSONArray taskResults = scrResponse.getJSONArray("data");
  191. for (Object taskResult : taskResults) {
  192. if(200 == ((JSONObject)taskResult).getInteger("code")){
  193. JSONArray sceneResults = ((JSONObject)taskResult).getJSONArray("results");
  194. for (Object sceneResult : sceneResults) {
  195. ContentSafetyResult result=new ContentSafetyResult();
  196. result.setType(ContentSafetyResult.TYPE_TEXT);
  197. result.setContent(content);
  198. result.setScene(((JSONObject)sceneResult).getString("scene"));
  199. result.setSuggestion(((JSONObject)sceneResult).getString("suggestion"));
  200. result.setLabel(((JSONObject)sceneResult).getString("label"));
  201. results.add(result);
  202. }
  203. }else{
  204. logger.warn("task process fail:" + ((JSONObject)taskResult).getInteger("code"));
  205. }
  206. }
  207. } else {
  208. logger.warn("detect not success. code:" + scrResponse.getInteger("code"));
  209. }
  210. }else{
  211. logger.warn("response not success. status:" + httpResponse.getStatus());
  212. }
  213. } catch (ServerException e) {
  214. logger.error(e.getMessage(),e);
  215. } catch (ClientException e) {
  216. logger.error(e.getMessage(),e);
  217. } catch (Exception e) {
  218. logger.error(e.getMessage(),e);
  219. }
  220. return results;
  221. }
  222. /**
  223. * 查找预警的数据
  224. * @param results
  225. * @return
  226. */
  227. public static List<ContentSafetyResult> findWarningData(List<ContentSafetyResult> results){
  228. if(results == null || results.isEmpty()) {
  229. return Collections.emptyList();
  230. }
  231. List<ContentSafetyResult> warningResults=new ArrayList<ContentSafetyResult>();
  232. for (ContentSafetyResult result : results) {
  233. if(result.getSuggestion() != ContentSafetyResult.SUGGESTION_PASS) {
  234. warningResults.add(result);
  235. }
  236. }
  237. return warningResults;
  238. }

}`

ContentSafetyResult.java
`public class ContentSafetyResult {
/**
* 图片
/
public static final int TYPE_PHOTO=1;
/
*
* 文字
*/
public static final int TYPE_TEXT=2;

  1. /**
  2. * 文本正常,可以直接放行
  3. */
  4. public static final String SUGGESTION_PASS="pass";
  5. /**
  6. * 文本需要进一步人工审核
  7. */
  8. public static final String SUGGESTION_REVIEW="review";
  9. /**
  10. * 文本违规,可以直接删除或者限制公开
  11. */
  12. public static final String SUGGESTION_BLOCK="block";
  13. private Integer type;
  14. private String content;
  15. private String scene;
  16. private String suggestion;
  17. private String label;
  18. public Integer getType() {
  19. return type;
  20. }
  21. public void setType(Integer type) {
  22. this.type = type;
  23. }
  24. public String getContent() {
  25. return content;
  26. }
  27. public void setContent(String content) {
  28. this.content = content;
  29. }
  30. public String getScene() {
  31. return scene;
  32. }
  33. public void setScene(String scene) {
  34. this.scene = scene;
  35. }
  36. public String getSuggestion() {
  37. return suggestion;
  38. }
  39. public void setSuggestion(String suggestion) {
  40. this.suggestion = suggestion;
  41. }
  42. public String getLabel() {
  43. return label;
  44. }
  45. public void setLabel(String label) {
  46. this.label = label;
  47. }
  48. @Override
  49. public String toString() {
  50. return "ContentSafetyResult [type=" + type + ", content=" + content + ", scene=" + scene + ", suggestion="
  51. + suggestion + ", label=" + label + "]";
  52. }

}`

版权声明:本文为pipiapi原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/pipiapi/p/14331879.html