AI战疫【百度大脑新品体验】疫情谣言过滤
让天涯 发布于2020-04 浏览:2825 回复:0
0
收藏
最后编辑于2022-04

一、功能介绍

疫情谣言过滤功能的数据源来自官方疫情辟谣平台,能够精准识别并过滤疫情相关谣言,目前这项功能已经在文本审核接口策略中默认开启,您只需要点击“创建策略”根据引导点选后“生成策略”,即可“启用”。

二、应用场景

可以在发布文章、回复的时候,进行疫情谣言判断,如果存在谣言,则禁止发布、回复,共同营造一个良好的网络环境,为当前抗疫工作做贡献。

三、使用攻略

说明:本文采用C# 语言,开发环境为.Net Core 3.1,采用在线API接口方式实现。

使用该功能一共分成两步:第一步:创建策略;第二步:调用在线API验证内容进行处理。


(1)创建策略
创建地址:https://ai.baidu.com/censoring#/strategylist

点击策略创建地址,选择“创建策略"。

第一步:填写策略名称,选择相应的APPID,并填写联系人信息,如果有时间限制,可以取消“长期有效”按钮,输入具体的策略生效时间段。

第二步:设置策略审核规则,因为疫情谣言过滤功能已经在文本审核接口策略中默认开启,您只需要点击“创建策略”根据引导点选后“生成策略”,即可“启用”,至于其他功能,可根据需求开启或关闭。

第三步:可以点击“验证策略”,进行策略验证,或者在“策略列表”中,选择相应的策略,点击“验证”来验证策略:

验证结果:

另外,在“策略列表”中,可以选择修改状态来“启用/停用”相应的策略,也可以通过“编辑“按钮来调整策略,更改生效时间等操作:

(2)调用内容审核平台-文本

文档地址:https://ai.baidu.com/ai-doc/ANTIPORN/Vk3h6xaga

接口描述:

内容审核平台提供了针对图像、文本、语音、短视频的自定义审核规则配置功能,用户可以在平台上自助选择审核维度、审核标签,审核松紧度、自定义图像、文本黑白名单、自定义审核敏感人物,然后调用接口,即可按照勾选的维度、松紧度进行审核。

请求说明

接口地址:https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined
请求方式:POST

接口说明:内容审核文本API接口。

注意:

Content-Type为application/x-www-form-urlencoded,然后通过urlencode格式化请求体。

请求参数说明:

响应参数说明:

返回示例:

成功响应示例 ——合规:

{
	"log_id": 15556561295920002,
	"conclusion": "合规",
	"conclusionType": 1
}

或者

{
    "log_id": 15572142621780024,
    "conclusion": "合规",
    "conclusionType": 1,
    "data": [{
        "type": 14,
        "subType": 0,
        "conclusion": "合规",
        "conclusionType": 1,
        "msg": "自定义文本白名单审核通过",
        "hits": [{
            "datasetName": "SLK-测试-自定义文本白名单",
            "words": ["袁运筹"]
        }]
    }]
}

 

成功响应示例——不合规:

{
    "log_id": 123456789,
    "conclusion": "不合规",
    "conclusionType": 2,
    "data": [{
        "type": 11,
        "subType": 0,
        "conclusion": "不合规",
        "conclusionType": 2,
        "msg": "存在百度官方默认违禁词库不合规",
        "hits": [{
            "datasetName": "百度默认黑词库",
            "words": ["免费翻墙"]
        }]
    }, {
        "type": 12,
        "subType": 2,
        "conclusion": "不合规",
        "conclusionType": 2,
        "msg": "存在文本色情不合规",
        "hits": [{
            "datasetName": "百度默认文本反作弊库",
            "probability": 1.0,
            "words": ["电话 找小姐"]
        }]
    }, {
        "type": 12,
        "subType": 3,
        "conclusion": "不合规",
        "conclusionType": 2,
        "msg": "存在政治敏感不合规",
        "hits": [{
            "probability": 1.0,
            "datasetName": "百度默认文本反作弊库",
            "words": ["敏感人物A"]
        }]
    }, {
        "type": 12,
        "subType": 4,
        "conclusion": "不合规",
        "conclusionType": 2,
        "msg": "存在恶意推广不合规",
        "hits": [{
            "probability": 1.0,
            "datasetName": "百度默认文本反作弊库",
            "words": [""]
        }]
    }, {
        "type": 13,
        "subType": 0,
        "conclusion": "不合规",
        "conclusionType": 2,
        "msg": "存在自定义文本黑名单不合规",
        "hits": [{
            "datasetName": "SLK-测试-自定义黑名单",
            "words": ["我是你爹", "他妈的"]
        }]
    }]
}

失败响应示例:

{
    "log_id": 149319909347709,
    "error_code": 0,
    "error_msg":"configId error"
}

(3)源码共享

(3-1)根据 API Key 和 Secret Key 获取 AccessToken

/// 
/// 获取百度access_token
/// 
/// API Key
/// Secret Key
/// 
public static string GetAccessToken(string clientId, string clientSecret)
{
    string authHost = "https://aip.baidubce.com/oauth/2.0/token";
    HttpClient client = new HttpClient();
    List> paraList = new List>();
    paraList.Add(new KeyValuePair("grant_type", "client_credentials"));
    paraList.Add(new KeyValuePair("client_id", clientId));
    paraList.Add(new KeyValuePair("client_secret", clientSecret));

    HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
    string result = response.Content.ReadAsStringAsync().Result;
    JObject jo = (JObject)JsonConvert.DeserializeObject(result);

    string token = jo["access_token"].ToString();
    return token;
}

(3-2)调用API接口获取识别结果

(3-2-1)在Startup.cs 文件 的 Configure(IApplicationBuilder app, IHostingEnvironment env) 方法中开启虚拟目录映射功能:

string webRootPath = HostingEnvironment.WebRootPath;//wwwroot目录

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(
        Path.Combine(webRootPath, "Uploads", "BaiduAIs")),
    RequestPath = "/BaiduAIs"
});

(3-2-2) 建立Index.cshtml文件

(3-2-2-1)前台代码:

    由于html代码无法原生显示,只能简单说明一下:

    主要是一个form表单,需要设置属性enctype="multipart/form-data",否则无法上传图片;

    form表单里面有几个控件:

一个textarea:asp-for="Text" ,输入需要审核的内容;

一个Input:type="text",asp-for="ImageUrl" ,输入网络图片地址;

一个Input:type="file",asp-for="FileUpload" ,上传图片用;

一个Input:type="submit",asp-page-handler="CensorForImg" ,图像审核。

一个Input:type="submit",asp-page-handler="CensorForText" ,文本审核。

一个img:src="@Model.curPath",显示需要审核的图片。

最后显示后台 msg 字符串列表信息,如果需要输出原始Html代码,则需要使用@Html.Raw()函数。 

(3-2-2-2) 后台代码: 

[BindProperty]
public IFormFile FileUpload { get; set; }
[BindProperty]
public string ImageUrl { get; set; }
[BindProperty]
public string Text { get; set; }
private readonly IHostingEnvironment HostingEnvironment;
public List msg = new List();
public string curPath { get; set; }

string BaiduAI_CensorPath="Uploads//BaiduAIs//";
string BaiduAI_CensorUrl="/BaiduAIs/";
string Censor_API_KEY="你的API KEY";
string Censor_SECRET_KEY="你的SECRET KEY";



public async Task OnPostCensorForImgAsync()
{
    if (string.IsNullOrEmpty(ImageUrl) && (FileUpload is null))
    {
        ModelState.AddModelError(string.Empty, "网络图片 或 本地图片 请至少选择一项!");
    }
    if (!ModelState.IsValid)
    {
        return Page();
    }
    msg = new List();

    string webRootPath = HostingEnvironment.WebRootPath;//wwwroot目录
    string fileDir = Path.Combine(webRootPath, BaiduAI_CensorPath);
    string imgName = Guid.NewGuid().ToString("N");

    string imgBase64 = "";

    if (string.IsNullOrEmpty(ImageUrl))
    {
        imgName = await UploadFile(FileUpload, fileDir);
        string fileName = Path.Combine(fileDir, imgName);
        imgBase64 = GetFileBase64(fileName);
        curPath = Path.Combine(BaiduAI_CensorUrl, imgName);
    }
    else
    {
        curPath = ImageUrl;
    }

    string result = GetCensorForImgJson(imgBase64, ImageUrl, Censor_API_KEY, Censor_SECRET_KEY);
    JObject jo = (JObject)JsonConvert.DeserializeObject(result);

    try
    {
        msg.Add("图像审核结果:" + jo["conclusion"].ToString() + " ");
        int conclusionType = int.Parse(jo["conclusionType"].ToString());
        if (!conclusionType.Equals(1) && !conclusionType.Equals(4))
        {
            List data = jo["data"].ToList();
            foreach (JToken jt in data)
            {
                msg.Add(jt["msg"].ToString());
            }
        }
    }
    catch (Exception e)
    {
        msg.Add(result);
    }
    return Page();
}



public async Task OnPostCensorForTextAsync()
{
    if (string.IsNullOrEmpty(Text))
    {
        ModelState.AddModelError(string.Empty, "请输入审核内容!");
    }
    if (!ModelState.IsValid)
    {
        return Page();
    }

    msg = new List();

    string result = GetCensorForTextJson(Text, Censor_API_KEY, Censor_SECRET_KEY);
    JObject jo = (JObject)JsonConvert.DeserializeObject(result);

    try
    {
        msg.Add("文本审核结果:" + jo["conclusion"].ToString() + " ");
        int conclusionType = int.Parse(jo["conclusionType"].ToString());
        if (!conclusionType.Equals(1) && !conclusionType.Equals(4))
        {
            List data = jo["data"].ToList();
            foreach (JToken jt in data)
            {
                msg.Add(jt["msg"].ToString());
            }
        }
    }
    catch (Exception e)
    {
        msg.Add(result);
    }
    return Page();
}

/// 
/// 上传文件,返回文件名
/// 
/// 文件上传控件
/// 文件绝对路径
/// 
public static async Task UploadFile(IFormFile formFile, string fileDir)
{
    if (!Directory.Exists(fileDir))
    {
        Directory.CreateDirectory(fileDir);
    }
    string extension = Path.GetExtension(formFile.FileName);
    string imgName = Guid.NewGuid().ToString("N") + extension;
    var filePath = Path.Combine(fileDir, imgName);

    using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
    {
        await formFile.CopyToAsync(fileStream);
    }

    return imgName;
}

/// 
/// 返回图片的base64编码
/// 
/// 文件绝对路径名称
/// 
public static String GetFileBase64(string fileName)
{
    FileStream filestream = new FileStream(fileName, FileMode.Open);
    byte[] arr = new byte[filestream.Length];
    filestream.Read(arr, 0, (int)filestream.Length);
    string baser64 =  Convert.ToBase64String(arr);
    filestream.Close();
    return baser64;
}

/// 
/// 文件base64解码
/// 
/// 文件base64编码
/// 生成文件路径
public static async Task GetFileFromBase64(string base64Str, string outPath)
{
    var contents = Convert.FromBase64String(base64Str);
    using (var fs = new FileStream(outPath, FileMode.Create, FileAccess.Write))
    {
        fs.Write(contents, 0, contents.Length);
        fs.Flush();
    }
}

/// 
/// 图像审核Json字符串
/// 
/// 图片base64编码
/// 图像URL地址(需要做UrlEncode)
/// API Key
/// Secret Key
/// 
public static string GetCensorForImgJson(string strbaser64, string imgUrl,string clientId, string clientSecret)
{
    string token = GetAccessToken(clientId, clientSecret);
    string host = "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token=" + token;
    Encoding encoding = Encoding.Default;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
    request.Method = "post";
    request.KeepAlive = true;
    string str = "imgType=0" ;
    if (!string.IsNullOrEmpty(strbaser64))
    {
        str += "&image=" + HttpUtility.UrlEncode(strbaser64);
    }
    if (!string.IsNullOrEmpty(imgUrl))
    {
        str += "&imgUrl=" + imgUrl;
    }
    byte[] buffer = encoding.GetBytes(str);
    request.ContentLength = buffer.Length;
    request.GetRequestStream().Write(buffer, 0, buffer.Length);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
    string result = reader.ReadToEnd();
    return result;
}

/// 
/// 文本审核Json字符串
/// 
/// 文本内容
/// API Key
/// Secret Key
/// 
public static string GetCensorForTextJson(string text, string clientId, string clientSecret)
{
    string token = GetAccessToken(clientId, clientSecret);
    string host = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=" + token;
    Encoding encoding = Encoding.Default;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
    request.Method = "post";
    request.KeepAlive = true;
    string str = "text=" + text;
    byte[] buffer = encoding.GetBytes(str);
    request.ContentLength = buffer.Length;
    request.GetRequestStream().Write(buffer, 0, buffer.Length);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
    string result = reader.ReadToEnd();
    return result;
}

四、效果测试

1、页面:

2、识别结果:

2.1

2.2

2.3

五、测试结果及建议

经过测试可以知道,百度的内容审核平台中的“疫情谣言过滤”功能有一定的作用,但是信息库还不全面,比如上图2.3中的“抽烟、喝酒可以防止感染新型冠状病毒“应该是谣言,但是百度的”疫情谣言过滤“却无法正确识别出来,还需要加强处理。

百度的内容审核平台功能的强大之处,在于可以方便的生成策略,然后使用在线API的方式在自己需要的程序、网站里直接调用,其内置了很多基本的策略,可以直接使用,不用自己再辛苦创建。

当然,针对无法过滤部门谣言问题,我们可以在生成策略时,添加“自定义文本黑名单”规则,就能轻松实现最新谣言的过滤,具体可以参考我以前写的一篇更加详细的文章:https://ai.baidu.com/forum/topic/show/955954

所以,加上“自定义文本黑/白名单”规则后,百度的”疫情谣言过滤“功能更加强大,可以进行更加个性化的设置,大大提高内容审核平台的使用场景。

收藏
点赞
0
个赞
TOP
切换版块