canvin/baidu-censor

百度内容审核接口

v1.3.1 2019-01-25 03:51 UTC

This package is not auto-updated.

Last update: 2024-09-28 09:09:21 UTC


README

本包使用百度aip-php-sdk-2.2.10,去除不必要的接口文件,只作审核使用

安装

composer require canvin/baidu-censor

类文件

example.php--基于thinkphp框架及redis缓存

<?php
/**
 * Created by PhpStorm.
 * User: canvin
 * Date: 2018/12/12
 * Time: 2:22 PM
 */

namespace app\common\service;


use app\common\exception\MessageException;
use baidu\censor\Content;
use baidu\censor\Image;
use think\facade\Cache;

class exampleService
{

    /**
     * 获取百度授权Key
     * Interface getConfig
     * @author CanvinChen
     * @param int $secretNo
     * @param string $type
     * @return mixed
     * @throws MessageException
     */
    public static function getConfig(string $type ='content',int $secretNo = 0)
    {
        //获取百度审核应用授权Key数组
        $secrets = config('censor.secrets');
        $count = count($secrets)-1;
        if($secretNo>$count){
            throw new MessageException('达到所有应用授权Key的审核接口调用上限!',203);
        }
        //获取当前授权组的调用次数
        $redis = Cache::init();
        $keyName = self::getSecretsKey($type);
        $keyExit = $redis->exists($keyName);
        $secretUseTime = $redis->hGet($keyName, $secretNo);
        //检查调用接口是否在允许的次数限制内
        if(($secretUseTime<=500 && $type=='image') || ($secretUseTime<=10000 && $type=='content')){
            $redis->hIncrBy($keyName, $secretNo);
            //设置key的过期时间为每二天零晨
            !$keyExit&&$redis->expireat($keyName, (new \DateTime('tomorrow'))->getTimestamp());
            return $secrets[$secretNo];
        }else{
            $secretNo++;
            return self::getConfig($type, $secretNo);
        }
    }

    /**
     * 文本内容审核
     * Interface content
     * @author CanvinChen
     * @param string $message
     * @param string $cachePath accesstoken缓存目录
     * @return array
     * 通过:
     * [1,'正常']
     * 不通过:
     * [2, ['违规关键字1','违规关键字2']]
     * 超过调用上限
     * [3,'达到所有应用授权Key的审核接口调用上限!']
     * 错误:
     * [4,'错误信息']
     */
    public static function content(string $message, string $cachePath)
    {
        try{
            $config = self::getConfig();
            $censor = new Content($config['AppID'], $config['APIKey'], $config['SecretKey'], $cachePath);
            $data = $censor->antiSpam($message);
            trace('文本审核===============>');
            trace($data);
            if(isset($data['result']['spam'])){
                if($data['result']['spam']===0){
                    return [1,'正常'];
                }else{
                    $words = [];
                    foreach(array_column($data['result']['reject'],'hit') as $vals){
                        $words = array_merge($words, $vals);
                    }
                    return [2, $words];
                }
            }else{
                throw new MessageException($data['error_code'].':'.$data['error_msg']);
            }

        }catch (\Throwable $t){
            if($t->getCode() == 203){
                return [3,$t->getMessage()];
            }else{
                return [4, $t->getMessage()];
            }
        }
    }

    /**
     * 图片检测
     * Interface image
     * @author CanvinChen
     * @param mixed $image
     * @param string $cachePath accesstoken缓存目录
     * @return array
     * 例一:
     * $image = file_get_content('image.jpg')
     * 例二:
     * $image = 'http://aaa.com/image.jpg'
     * 例三:
     * $image = [
     *          file_get_content('image1.jpg'),
     *          file_get_content('image2.jpg'),
     *          ...
     * ]
     * 例四:
     * $image = [
     *      'http://aaa.com/image1.jpg',
     *      'http://aaa.com/image2.jpg',
     *      ...
     * ]
     * 例五:
     *$image = [
      *          'data:image/png;base64,图片base64编码字符串1',
      *          'data:image/jpeg;base64,图片base64编码字符串2',
      *          ...
      * ]
     * 单图审核返回值:
     * 通过:
     * [1,'正常']
     * 不通过:
     * [2, '色情|性感']
     * -------------
     * 多图审核返回值:
     * [[1,'正常'],[2,'性感']]
     * -----------------------
     * 超过调用上限
     * [3,'达到所有应用授权Key的审核接口调用上限!']
     * 错误:
     * [4,'错误信息']
     */
    public static function image($image, string $cachePath)
    {
        try{
            $config = self::getConfig('image');
            $censor = new Image($config['AppID'], $config['APIKey'], $config['SecretKey'], $cachePath);
            $data = $censor->faceAudit($image);
            trace('图片审核===============>');
            trace($data);
            if(isset($data['error_code'])){
                throw new MessageException($data['error_code'].':'.$data['error_msg']);
            }else{
                $result = [];
                //将返回的所有图片检测状态加+,使用状态变更为1通过2不通过
                foreach($data['result'] as $item){
                    if($item['data']['antiporn']['conclusion'] =='正常'){
                        $result [] = [1,$item['data']['antiporn']['conclusion']];
                    }else{
                        $result [] = [2,$item['data']['antiporn']['conclusion']];
                    }
                }

                //传入为多个图片时返回状态数组,否则直接返回结果值
                if(count($result)>1){
                    return $result;
                }else{
                    return $result[0];
                }
            }
        }catch (\Throwable $t){
            if($t->getCode() == 203){
                return [3,$t->getMessage()];
            }else{
                return [4,$t->getMessage()];
            }
        }
    }

    /**
     * 获取授权key调用次数
     * Interface getSecretsKey
     * @author CanvinChen
     * @param string $type
     * @return string
     */
    public static function getSecretsKey(string $type ='content')
    {
        return 'Qa_Secrets_UseTimes_'.$type;
    }
}

censor.php--配置文件

/**
 * 百度文本及图片审核配置
 * User: canvin
 * Date: 2018/12/12
 * Time: 2:28 PM
 */
return [
    'secrets'=> [[//应用1
                'AppID'     => ,
                'APIKey'    => '',
                'SecretKey' => '',
             ],[//应用2
                'AppID'     => ,
                'APIKey'    => '',
                'SecretKey' => '',
                ],
            ]
];

使用:

namespace app\api\controller;
use app\common\service\exampleService;

class Test extends Controller
{

public function testContent(){
//文本审核:
$message = '需要审核的文本';
return json(CensorService::content($message));
}

public function testImage(){
//图片审核:
$image =[
            'https://nos.netease.com/yidun/2-0-0-aa5c792f6721486a83c79a33db3486b9.jpg',
            'https://nos.netease.com/yidun/2-0-0-aa5c792f6721486a83c79a33db3486b9.jpg'
        ];
 return json(CensorService::image($image));
}

接口返回参数及调方法请参考百度接口文档:

>>图片审核

>>文字审核