zoukankan      html  css  js  c++  java
  • java对接阿里云内容安全接口,实现敏感字图检测

    AliyunContentSafetyService.java
    `@Component
    public class AliyunContentSafetyService {

    /**
     * 图片鉴黄
     */
    public static final String SCENE_PORN="porn";
    /**
     * 图片暴恐涉政
     */
    public static final String SCENE_TERRORISM="terrorism";
    /**
     * 图文违规
     */
    public static final String SCENE_AD="ad";
    /**
     * 图片二维码
     */
    public static final String SCENE_QRCODE="qrcode";
    /**
     * 图片不良场景
     */
    public static final String SCENE_LIVE="live";
    /**
     * 图片logo
     */
    public static final String SCENE_LOGO="logo";
    
    /**
     * 文本内容检测  文本检测不可和图片检测一起使用
     */
    public static final String SCENE_ANTISPAM="antispam";
    
    private static final Logger logger=LoggerFactory.getLogger(AliyunContentSafetyService.class);
    @Value("${oss.region}")
    private static String region;
    @Value("${oss.accessKeyId}")
    private static String accessKeyId; 
    @Value("${oss.secretAccessKey}")
    private static String secretAccessKey;
    
    
    /**
     * 检测图片
     * @param scenes 官方检测场景
     * @param bizType 自定义业务检测场景
     * @param photos 需要检测的图片地址 非本地
     * @return
     */
    public static List<ContentSafetyResult> photoSafety(List<String> scenes,String bizType,List<String> photos) {
        if(photos == null || photos.isEmpty()) {
            logger.error("photos is empty");
            return null;
        }
        IClientProfile profile = DefaultProfile
                .getProfile(region, accessKeyId, secretAccessKey);
          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张图片暴恐检测计算。
           * scenes:表示鉴黄场景。
           */
          httpBody.put("scenes", scenes);
          if(StringUtils.isBlank(bizType)) {
              httpBody.put("bizType", Arrays.asList(bizType));
          }
          
          List<JSONObject> tasks=new ArrayList<JSONObject>();
          for(String photo:photos) {
              /**
               * 设置待检测图片。一张图片对应一个task。
               * 多张图片同时检测时,处理的时间由最后一个处理完的图片决定。
               * 通常情况下批量检测的平均响应时间比单张检测的要长。一次批量提交的图片数越多,响应时间被拉长的概率越高。
               * 这里以单张图片检测作为示例, 如果是批量图片检测,请自行构建多个task。
               */
              JSONObject task = new JSONObject();
              task.put("dataId", UUID.randomUUID().toString());
    
              // 设置图片链接。
              task.put("url", photo);
              task.put("time", new Date());
              
              tasks.add(task);
          }
          httpBody.put("tasks", tasks);
          
          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);
              logger.info("send photoSafety request");
          } catch (Exception e) {
              logger.error(e.getMessage(),e);
          }
          List<ContentSafetyResult> results=new ArrayList<ContentSafetyResult>();
          // 服务端接收到请求,完成处理后返回的结果。
          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) {
                              ContentSafetyResult result=new ContentSafetyResult();
                              result.setScene(((JSONObject) sceneResult).getString("scene"));
                              result.setSuggestion(((JSONObject) sceneResult).getString("suggestion"));
                              result.setLabel(((JSONObject) sceneResult).getString("label"));
                              result.setContent(((JSONObject) taskResult).getString("url"));
                              result.setType(ContentSafetyResult.TYPE_PHOTO);
                              results.add(result);
                          }
                      } else {
                          // 单张图片处理失败, 原因视具体的情况详细分析。
                          logger.error("task process fail. task response:" + JSON.toJSONString(taskResult));
                          return null;
                      }
                  }
              } else {
                  /**
                   * 表明请求整体处理失败,原因视具体的情况详细分析。
                   */
                  logger.error("the whole image scan request failed. response:" + JSON.toJSONString(scrResponse));
                  return null;
              }
          }
          return results;
    }
    
    /**
     * 检测文字
     * @param content 要检测的文本
     * @param scene 官方检测场景
     * @return
     */
    public static List<ContentSafetyResult> textSafety(String content,String scene){
        if(StringUtils.isBlank(content)) {
            return null;
        }
        IClientProfile profile = DefaultProfile
                .getProfile(region, accessKeyId, secretAccessKey);             
            IAcsClient client = new DefaultAcsClient(profile);
            TextScanRequest textScanRequest = new TextScanRequest();
            textScanRequest.setAcceptFormat(FormatType.JSON); // 指定API返回格式。
            textScanRequest.setHttpContentType(FormatType.JSON);
            textScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法。
            textScanRequest.setEncoding("UTF-8");
            textScanRequest.setRegionId("cn-beijing");
            List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();
            Map<String, Object> task1 = new LinkedHashMap<String, Object>();
            task1.put("dataId", UUID.randomUUID().toString());
            /**
             * 待检测的文本,长度不超过10000个字符。
             */
            task1.put("content", content);
            tasks.add(task1);
            JSONObject data = new JSONObject();
    
            /**
             * 检测场景。文本垃圾检测请传递antispam。
             **/
            data.put("scenes", Arrays.asList(scene));
            data.put("tasks", tasks);
    
            try {
                textScanRequest.setHttpContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage(),e);
                return null;
            }
            // 请务必设置超时时间。
            textScanRequest.setConnectTimeout(3000);
            textScanRequest.setReadTimeout(6000);
            List<ContentSafetyResult> results=new ArrayList<ContentSafetyResult>();
            try {
                HttpResponse httpResponse = client.doAction(textScanRequest);
                if(httpResponse.isSuccess()){
                    JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
                    System.out.println(JSON.toJSONString(scrResponse, true));
                    if (200 == scrResponse.getInteger("code")) {
                        JSONArray taskResults = scrResponse.getJSONArray("data");
                        for (Object taskResult : taskResults) {
                            if(200 == ((JSONObject)taskResult).getInteger("code")){
                                JSONArray sceneResults = ((JSONObject)taskResult).getJSONArray("results");
                                for (Object sceneResult : sceneResults) {
                                    ContentSafetyResult result=new ContentSafetyResult();
                                    result.setType(ContentSafetyResult.TYPE_TEXT);
                                    result.setContent(content);
                                    result.setScene(((JSONObject)sceneResult).getString("scene"));
                                    result.setSuggestion(((JSONObject)sceneResult).getString("suggestion"));
                                    result.setLabel(((JSONObject)sceneResult).getString("label"));
                                    results.add(result);
                                }
                            }else{
                                logger.warn("task process fail:" + ((JSONObject)taskResult).getInteger("code"));
                            }
                        }
                    } else {
                        logger.warn("detect not success. code:" + scrResponse.getInteger("code"));
                    }
                }else{
                    logger.warn("response not success. status:" + httpResponse.getStatus());
                }
            } catch (ServerException e) {
                logger.error(e.getMessage(),e);
            } catch (ClientException e) {
                logger.error(e.getMessage(),e);
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
        return results;
    }
    
    /**
     * 查找预警的数据
     * @param results
     * @return
     */
    public static List<ContentSafetyResult> findWarningData(List<ContentSafetyResult> results){
        if(results == null || results.isEmpty()) {
            return Collections.emptyList();
        }
        List<ContentSafetyResult> warningResults=new ArrayList<ContentSafetyResult>();
        for (ContentSafetyResult result : results) {
            if(result.getSuggestion() != ContentSafetyResult.SUGGESTION_PASS) {
                warningResults.add(result);
            }
        }
        return warningResults;
    }
    

    }`

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

    /**
     * 文本正常,可以直接放行
     */
    public static final String SUGGESTION_PASS="pass";
    /**
     * 文本需要进一步人工审核
     */
    public static final String SUGGESTION_REVIEW="review";
    /**
     * 文本违规,可以直接删除或者限制公开
     */
    public static final String SUGGESTION_BLOCK="block";
    
    private Integer type;
    private String  content;
    private String  scene;
    private String  suggestion;
    private String  label;
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getScene() {
        return scene;
    }
    public void setScene(String scene) {
        this.scene = scene;
    }
    public String getSuggestion() {
        return suggestion;
    }
    public void setSuggestion(String suggestion) {
        this.suggestion = suggestion;
    }
    public String getLabel() {
        return label;
    }
    public void setLabel(String label) {
        this.label = label;
    }
    @Override
    public String toString() {
        return "ContentSafetyResult [type=" + type + ", content=" + content + ", scene=" + scene + ", suggestion="
                + suggestion + ", label=" + label + "]";
    }
    

    }`

  • 相关阅读:
    使用 yo 命令行向导给 SAP UI5 应用添加一个新的视图
    SAP Fiori Elements 应用的 manifest.json 文件运行时如何被解析的
    SAP UI5 标准应用的多语言支持
    微软 Excel 365 里如何设置下拉菜单和自动高亮成指定颜色
    SAP Fiori Elements 应用里的 Title 显示的内容是从哪里来的
    本地开发好的 SAP Fiori Elements 应用,如何部署到 ABAP 服务器上?
    如何在 Cypress 测试代码中屏蔽(Suppress)来自应用代码报出的错误消息
    教你一招:让集群慢节点无处可藏
    应用架构步入“无服务器”时代 Serverless技术迎来新发展
    MySQL数据库事务隔离性的实现
  • 原文地址:https://www.cnblogs.com/pipiapi/p/14331879.html
Copyright © 2011-2022 走看看