阿里云文本关键词过滤检测

来源:互联网 发布:维生素软件 编辑:程序博客网 时间:2024/06/03 12:53

功能描述

关键词检测是对文本检测的最简单的一种方式,本文章对一段文本进行关键词的匹配,判断是否包含特定关键词。​

HTTP 接口描述

场景(scene)中文名 场景(scene) 分类(label) 备注 关键词检测 keyword normal 正常文本 关键词检测 keyword spam 含违规信息 关键词检测 keyword ad 广告 关键词检测 keyword politics 渉政 关键词检测 keyword terrorism 暴恐 关键词检测 keyword porn 色情 关键词检测 keyword contraband 违禁 关键词检测 keyword customized 自定义(比如命中自定义关键词)

​​​​

1.2 文本关键词检测 (uri: /green/text/scan)

检测文本是否为命中特定关键词。请求body是一个结构体,说明如下:​

字段类型是否必须说明bizType字符串可选业务类型,调用方从绿网申请所得。每个bizType对应不同的算法/模型。根据配置,后端可根据该字段对请求做不同处理。属于高级用法scenes字符串数组必须字符串数组,场景定义参考1.1小节;关键词检测,scenes请填写keywordtasksJSON数组必须文本检测任务列表;每个元素是个结构体,最多支持100个,即100段文本的检测.参见下表。

JSON数组中的每个元素是一个结构体,有如下字段:

字段类型是否必须说明clientInfoJSON结构体可选客户端信息,参考[调用方式/公共请求参数/公共查询参数]小节中ClientInfo结构体描述。服务器会把[调用方式/公共请求参数/公共查询参数]小节中全局的clientInfo和这里的独立的clientInfo合并。独立的clientInfo优先级更高。dataId字符串可选调用者通常保证一次请求中,所有的dataId不重复content字符串必须待检测文本time整形可选内容创建/编辑时间,单位mscategory字符串可选内容类别,取值范围为[“post”, “reply”, “comment”, “title”, “others”];也可以自定义的其他类型,但长度不超过64字节action字符串可选操作类型,取值范围为[“new”, “edit”, “share”, “others”];也可以自定义的其他操作类型,但长度不超过64字节relatedDataId字符串可选相关dataId;当contentType为reply或comment时,该字段设置相关的主贴或对应的comment的dataIdrelatedContent字符串可选相关字符串;当contentType为reply或comment时,该字段设置为主贴内容或对应的comment

返回body中的Data字段是JSON数组,每一个元素有如下字段:

字段类型是否必须说明code整形必须错误码,和http的status code一致msg字符串必须错误描述信息dataId字符串可选对应的请求中的dataIdtaskId字符串必须绿网服务器返回的唯一标识该检测任务的IDcontent字符串可选对应的请求中的contentresults数组可选当成功时(code == 200),该结果的包含一个或多个元素。每个元素是个结构体。参见下表。

上表results中包含的元素说明:

字段类型是否必须说明scene字符串必须风险场景suggestion字符串必须建议用户处理,取值范围:[“pass”, “review”, “block”], pass:文本正常,review:需要人工审核,block:文本违规,可以直接删除或者做限制处理label字符串必须该文本的分类,取值范围参考1.1小节rate浮点数必须结果为该分类的概率;值越高,越趋于该分类;取值为[0.00-100.00], 分值仅供参考,您只需要关注label和suggestion的取值即可extrasJSON对象可选附加信息,命中的上下文.该值将来可能会调整,建议不要在业务上进行依赖

各语言SDK依赖开发环境准备

请参照 https://develop.aliyun.com/sdk/java?spm=5176.doc28430.2.1.Qp3LL4 准备阿里云SDK依赖环境, 进行开发.

添加依赖包 maven
内容检测API SDK包含阿里云Java SDK公共部分和内容检测部分,公共部分依赖 aliyun-java-sdk-core , 内容检测部分依赖 aliyun-java-sdk-green

Maven Dependencies

  1. <dependency>
  2. <groupId>com.aliyun</groupId>
  3. <artifactId>aliyun-java-sdk-core</artifactId>
  4. <version>3.0.7</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.aliyun</groupId>
  8. <artifactId>aliyun-java-sdk-green</artifactId>
  9. <version>3.0.0</version>
  10. </dependency>

代码实现
1.1 config.properties

阿里云accessKeyId、accessKeySecretaccessKeyId=你的accessKeyIdaccessKeySecret=你的accessKeySecret调用阿里绿网服务的regionId,目前服务有两个集群,支持cn-hangzhou、cn-shanghairegionId=cn-hangzhou

1.2 BaseSample.java

import java.io.IOException;
import java.util.Properties;

/**
* Created by liqingfeng.lh on 17/01/12.

public class BaseSample {

protected static String accessKeyId;protected static String accessKeySecret;protected static String regionId;static {    Properties properties = new Properties();    try {        properties.load(BaseSample.class.getResourceAsStream("config.properties"));        accessKeyId = properties.getProperty("accessKeyId");        accessKeySecret = properties.getProperty("accessKeySecret");        regionId = properties.getProperty("regionId");    } catch(IOException e) {        e.printStackTrace();    }}protected static String getDomain(){     if("cn-shanghai".equals(regionId)){         return "green.cn-shanghai.aliyuncs.com";     }    return "green.cn-hangzhou.aliyuncs.com";}protected static String getEndPointName(){    return regionId;}

}

1.3 TextKeywordScanSample.java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

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.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.green.model.v20170112.TextScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

/**
* Created by liqingfeng on 16/3/2.
* 文本检测
*/
public class TextKeywordScanSample extends BaseSample {

public static void main(String[] args) throws Exception {    //请替换成你自己的accessKeyId、accessKeySecret    IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);    DefaultProfile.addEndpoint(getEndPointName(), regionId, "Green", getDomain());    IAcsClient client = new DefaultAcsClient(profile);    TextScanRequest textScanRequest = new TextScanRequest();    textScanRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式    textScanRequest.setContentType(FormatType.JSON);    textScanRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法    textScanRequest.setEncoding("UTF-8");    textScanRequest.setRegionId(regionId);    List<Map<String, Object>> tasks = new ArrayList<Map<String, Object>>();    Map<String, Object> task1 = new LinkedHashMap<String, Object>();    task1.put("dataId", UUID.randomUUID().toString());    task1.put("content", "你想要检测的关键字");    tasks.add(task1);    JSONObject data = new JSONObject();    data.put("scenes", Arrays.asList("keyword"));    data.put("tasks", tasks);    textScanRequest.setContent(data.toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);    /**     * 请务必设置超时时间     */    textScanRequest.setConnectTimeout(3000);    textScanRequest.setReadTimeout(6000);    try {        HttpResponse httpResponse = client.doAction(textScanRequest);        if(httpResponse.isSuccess()){            JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getContent(), "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) {                            String scene = ((JSONObject)sceneResult).getString("scene");                            String suggestion = ((JSONObject)sceneResult).getString("suggestion");                            //根据scene和suggetion做相关的处理                            //do something                            System.out.println("args = [" + scene + "]");                            System.out.println("args = [" + suggestion + "]");                        }                    }else{                        System.out.println("task process fail:" + ((JSONObject)taskResult).getInteger("code"));                    }                }            } else {                System.out.println("detect not success. code:" + scrResponse.getInteger("code"));            }        }else{            System.out.println("response not success. status:" + httpResponse.getStatus());        }    } catch (ServerException e) {        e.printStackTrace();    } catch (ClientException e) {        e.printStackTrace();    } catch (Exception e){        e.printStackTrace();    }}

}

请求body例子:

  1. {
  2. "scenes":[
  3. "keyword"
  4. ],
  5. "tasks":[
  6. {
  7. "dataId":"f14cde88-a5d3-44f7-b1a1-80d95b474f99",
  8. "content":"balala1"
  9. },
  10. {
  11. "dataId":"4a57e971-62b1-4a75-9563-cc2703b28244",
  12. "content":"balala2"
  13. }
  14. ]
  15. }

响应例子:

  1. {
  2. "msg":"OK",
  3. "code":200,
  4. "data":[
  5. {
  6. "msg":"OK",
  7. "code":200,
  8. "dataId":"f14cde88-a5d3-44f7-b1a1-80d95b474f99",
  9. "results":[
  10. {
  11. "rate":99.91,
  12. "suggestion":"block",
  13. "extras":{
  14. "hitContext":"balala"
  15. },
  16. "label":"porn",
  17. "scene":"keyword"
  18. }
  19. ],
  20. "content":"balala",
  21. "taskId":"6cb22909-bb61-4848-8fab-0d4bc8dc4b9c-1494295749828"
  22. },
  23. {
  24. "msg":"OK",
  25. "code":200,
  26. "dataId":"4a57e971-62b1-4a75-9563-cc2703b28244",
  27. "results":[
  28. {
  29. "rate":99.91,
  30. "suggestion":"block",
  31. "extras":{
  32. "hitContext":"balala"
  33. },
  34. "label":"spam",
  35. "scene":"keyword"
  36. }
  37. ],
  38. "content":"balala",
  39. "taskId":"1249a8c2-5bb3-477c-98d9-f78dad8ae15b-1494295749828"
  40. }
  41. ],
  42. "requestId":"96B928F4-1668-4F43-A3ED-4480ACBDA24C"
  43. }

总结
根据返回根据scene(场景)和suggetion(pass or block)做相关的处理,