php调用华为云内容审核Moderation

php语言, 图片审核, 视频审核, aksk验证的方式, 安装SDK的方式
官方文档: https://support.huaweicloud.com/wtsnew-moderation/index.html

1.安装华为云扩展包

composer require huaweicloud/huaweicloud-sdk-php:3.1.55

2.华为云确认服务所在区域, 不能垮区域调用服务, 根据所在区域开通该服务, 并且使用该区域的项目id


image.png

image.png

3.php中的代码(我使用的是laravel框架)

<?php
namespace App\Lib;

use HuaweiCloud\SDK\Core\Auth\BasicCredentials;
use HuaweiCloud\SDK\Core\Http\HttpConfig;
use HuaweiCloud\SDK\Core\Exceptions\ConnectionException;
use HuaweiCloud\SDK\Core\Exceptions\RequestTimeoutException;
use HuaweiCloud\SDK\Core\Exceptions\ServiceResponseException;
use HuaweiCloud\SDK\Moderation\V3\Model\CheckImageModerationRequest;
use HuaweiCloud\SDK\Moderation\V3\Model\ImageDetectionReq;
use HuaweiCloud\SDK\Moderation\V3\Model\RunCreateVideoModerationJobRequest;
use HuaweiCloud\SDK\Moderation\V3\Model\RunQueryVideoModerationJobRequest;
use HuaweiCloud\SDK\Moderation\V3\Model\VideoCreateRequest;
use HuaweiCloud\SDK\Moderation\V3\Model\VideoCreateRequestData;
use HuaweiCloud\SDK\Moderation\V3\ModerationClient;


/**
 * 华为云内容审核
 * https://support.huaweicloud.com/api-moderation/moderation_03_0072.html
 * 使用华为云的服务要确保所在地区的服务是否开通(不同区域的服务不同)
 */
class ContentModeration
{
    private $ak = 'HPAI9****TVS8Z';

    private $sk = 'GTQ8tHloxIL6********j5YkyJJNXzs';

    private $projectId = "0c37715a*********03f2d50a88";//cn-north-4

    private $endpoint = "https://moderation.cn-north-4.myhuaweicloud.com";

    /**
     * 图片审核
     * @param $url string 远程图片地址
     * @return array|string
     */
    public function imageModeration($url)
    {
        $credentials = new BasicCredentials($this->ak,$this->sk,$this->projectId);
        $config = HttpConfig::getDefaultConfig();
        $config->setIgnoreSslVerification(true);

        $client = ModerationClient::newBuilder(new ModerationClient)
            ->withHttpConfig($config)
            ->withEndpoint($this->endpoint)
            ->withCredentials($credentials)
            ->build();
        $request = new CheckImageModerationRequest();

        $body = new ImageDetectionReq();
        $listbodyCategories = array();
//        array_push($listbodyCategories,"terrorism");//暴恐元素的检测
        array_push($listbodyCategories,"porn");//涉黄元素的检测
//        array_push($listbodyCategories,"image_text");//广告图文的检测
        $body->setUrl($url);
        $body->setCategories($listbodyCategories);
        $body->setEventType("album");
        $request->setBody($body);
        try {
            $response = $client->checkImageModeration($request);
            return json_decode($response, true);
            /*
             * 成功返回时
             * ^ array:2 [
                  "request_id" => "568b0ad5dc897ee07c32554c2e3c161b"
                  "result" => array:2 [
                    "suggestion" => "pass"
                    "details" => []
                  ]
                ]
             */
//            echo "\n";
//            echo $response;
        } catch (ConnectionException $e) {
            return $e->getMessage();
//            $msg = $e->getMessage();
//            echo "\n". $msg ."\n";
        } catch (RequestTimeoutException $e) {
            return $e->getMessage();
//            $msg = $e->getMessage();
//            echo "\n". $msg ."\n";
        } catch (ServiceResponseException $e) {
            return  $e->getErrorMsg();
//            echo "\n";
//            echo $e->getHttpStatusCode(). "\n";
//            echo $e->getRequestId(). "\n";
//            echo $e->getErrorCode() . "\n";
//            echo $e->getErrorMsg() . "\n";
        }
    }

    /**
     * 创建视频审核任务
     * @param string $url 远程视频地址
     * @param int $interval 审核时间间隔
     * @return array|string
     */
    public function RunCreateVideoModerationJob($url, $interval=5)
    {
        $credentials = new BasicCredentials($this->ak,$this->sk,$this->projectId);
        $config = HttpConfig::getDefaultConfig();
        $config->setIgnoreSslVerification(true);

        $client = ModerationClient::newBuilder(new ModerationClient)
            ->withHttpConfig($config)
            ->withEndpoint($this->endpoint)
            ->withCredentials($credentials)
            ->build();
        $request = new RunCreateVideoModerationJobRequest();

        $body = new VideoCreateRequest();
        $listbodyImageCategories = array();
        array_push($listbodyImageCategories,"porn");//涉黄
//        array_push($listbodyImageCategories,"politics");//涉政
//        array_push($listbodyImageCategories,"terrorism");//暴恐
//        array_push($listbodyImageCategories,"image_text");//图文违规内容的检测(检测图片中出现的广告、色情、暴恐的文字违规内容以及二维码内容)
        $databody = new VideoCreateRequestData();
        $databody->setUrl($url)
            ->setFrameInterval($interval)
            ->setLanguage("zh");
        $body->setImageCategories($listbodyImageCategories);
        $body->setEventType("default");
        $body->setData($databody);
        $request->setBody($body);
        try {
            $response = $client->RunCreateVideoModerationJob($request);
            return json_decode($response, true);
            /*
             * 成功返回
             * ^ array:2 [
                  "request_id" => "08ba8b28fd8bf6bc40ce6acbfb03810c" //请求id
                  "job_id" => "01694966400_b2359b073d6647918b8ebee58ab40d2c" //任务id
                ]
             */
//            echo "\n";
//            echo $response;
        } catch (ConnectionException $e) {
            return $e->getMessage();
//            $msg = $e->getMessage();
//            echo "\n". $msg ."\n";
        } catch (RequestTimeoutException $e) {
            return $e->getMessage();
//            $msg = $e->getMessage();
//            echo "\n". $msg ."\n";
        } catch (ServiceResponseException $e) {
            return $e->getErrorMsg();
//            echo "\n";
//            echo $e->getHttpStatusCode(). "\n";
//            echo $e->getRequestId(). "\n";
//            echo $e->getErrorCode() . "\n";
//            echo $e->getErrorMsg() . "\n";
        }
    }


    /**
     * 查询视频审核任务(查询视频内容审核作业)
     * @param $iob_id string 视频审核任务的id
     * @return array|string
     */
    public function RunQueryVideoModerationJob($iob_id)
    {
        $credentials = new BasicCredentials($this->ak,$this->sk,$this->projectId);
        $config = HttpConfig::getDefaultConfig();
        $config->setIgnoreSslVerification(true);

        $client = ModerationClient::newBuilder(new ModerationClient)
            ->withHttpConfig($config)
            ->withEndpoint($this->endpoint)
            ->withCredentials($credentials)
            ->build();
        $request = new RunQueryVideoModerationJobRequest();

        $request->setJobId($iob_id);

        try {
            $response = $client->RunQueryVideoModerationJob($request);
            return json_decode($response, true);
            /*
             * 成功返回
             * {
                 "job_id": "01694966400_17914aa922f74190bb0f787e725247b3",
                 "status": "succeeded",
                 "request_params": {
                  "event_type": "default",
                  "data": {
                   "frame_interval": 5,
                   "language": "zh",
                   "url": "https://obs-13705979718.obs.cn-south-1.myhuaweicloud.com/material/2020-07-07/2020_07_07_13_18_00_%E9%B1%BC%E6%97%A8%E9%A5%BF%E4%BA%86%E4%B9%88%E8%B6%85%E5%93%81%E6%97%A5%E7%AB%96%E7%89%88%E3%80%906.24%E6%8D%A2%E5%88%8A%E3%80%91.mp4"
                  },
                  "image_categories": [
                   "image_text",
                   "porn"
                  ]
                 },
                 "result": {
                  "suggestion": "pass",
                  "audio_detail": [],
                  "image_detail": []
                 },
                 "create_time": "2023-09-18T15:29:15.015Z",
                 "update_time": "2023-09-18T15:29:21.021Z",
                 "request_id": "244df3eacb29c87f519953ce18b0353a"
                }
             *
             *
             *
             *失败返回:
             * ^ array:7 [
  "request_id" => "61df71bf57fa3415c438f6bbb4ebf06d"
  "job_id" => "01694966400_b2359b073d6647918b8ebee58ab40d2c"
  "status" => "succeeded"
  "request_params" => array:3 [
    "data" => array:2 [
      "url" => "https://obs-13705979718.obs.cn-south-1.myhuaweicloud.com/material/2020-07-07/2020_07_07_13_21_07_%E9%A3%9F%E7%A0%94%E7%A4%BE.%E7%88%B1%E5%91%B3%E7%94%9F%E6%B4%BB-%E7%AB%96%E5%B1%8F.mp4"
      "frame_interval" => 5
    ]
    "event_type" => "default"
    "image_categories" => array:1 [
      0 => "image_text"
    ]
  ]
  "create_time" => "2023-09-18T15:50:35.035Z"
  "update_time" => "2023-09-18T15:50:39.039Z"
  "result" => array:3 [
    "suggestion" => "block"
    "image_detail" => array:4 [
      0 => array:4 [
        "suggestion" => "block"
        "category" => "image_text"
        "time" => 0
        "detail" => array:2 [
          0 => array:6 [
            "confidence" => 1
            "category" => "image_text"
            "suggestion" => "block"
            "label" => "qr_code"
            "qr_location" => array:4 [
              "top_left_x" => 828
              "top_left_y" => 1261
              "bottom_right_x" => 946
              "bottom_right_y" => 1380
            ]
            "qr_content" => "https://mp.weixin.qq.com/s/xlw2tJYI2NsxeTRF0C1X6w"
          ]
          1 => array:4 [
            "confidence" => 1
            "category" => "image_text"
            "suggestion" => "block"
            "label" => "qr_code"
          ]
        ]
      ]
      1 => array:4 [
        "suggestion" => "block"
        "category" => "image_text"
        "time" => 5
        "detail" => array:2 [
          0 => array:6 [
            "confidence" => 1
            "category" => "image_text"
            "suggestion" => "block"
            "label" => "qr_code"
            "qr_location" => array:4 [
              "top_left_x" => 828
              "top_left_y" => 1262
              "bottom_right_x" => 946
              "bottom_right_y" => 1381
            ]
            "qr_content" => "https://mp.weixin.qq.com/s/xlw2tJYI2NsxeTRF0C1X6w"
          ]
          1 => array:4 [
            "confidence" => 1
            "category" => "image_text"
            "suggestion" => "block"
            "label" => "qr_code"
          ]
        ]
      ]
      2 => array:4 [
        "suggestion" => "block"
        "category" => "image_text"
        "time" => 10
        "detail" => array:2 [
          0 => array:6 [
            "confidence" => 1
            "category" => "image_text"
            "suggestion" => "block"
            "label" => "qr_code"
            "qr_location" => array:4 [
              "top_left_x" => 828
              "top_left_y" => 1262
              "bottom_right_x" => 947
              "bottom_right_y" => 1382
            ]
            "qr_content" => "https://mp.weixin.qq.com/s/xlw2tJYI2NsxeTRF0C1X6w"
          ]
          1 => array:4 [
            "confidence" => 1
            "category" => "image_text"
            "suggestion" => "block"
            "label" => "qr_code"
          ]
        ]
      ]
      3 => array:4 [
        "suggestion" => "block"
        "category" => "image_text"
        "time" => 15
        "detail" => array:2 [
          0 => array:6 [
            "confidence" => 1
            "category" => "image_text"
            "suggestion" => "block"
            "label" => "qr_code"
            "qr_location" => array:4 [
              "top_left_x" => 829
              "top_left_y" => 1262
              "bottom_right_x" => 947
              "bottom_right_y" => 1381
            ]
            "qr_content" => "https://mp.weixin.qq.com/s/xlw2tJYI2NsxeTRF0C1X6w"
          ]
          1 => array:4 [
            "confidence" => 1
            "category" => "image_text"
            "suggestion" => "block"
            "label" => "qr_code"
          ]
        ]
      ]
    ]
    "audio_detail" => []
  ]
]
             */
//            echo "\n";
//            echo $response;
        } catch (ConnectionException $e) {
            return $e->getMessage();
//            $msg = $e->getMessage();
//            echo "\n". $msg ."\n";
        } catch (RequestTimeoutException $e) {
            return $e->getMessage();
//            $msg = $e->getMessage();
//            echo "\n". $msg ."\n";
        } catch (ServiceResponseException $e) {
            return $e->getErrorMsg();
//            echo "\n";
//            echo $e->getHttpStatusCode(). "\n";
//            echo $e->getRequestId(). "\n";
//            echo $e->getErrorCode() . "\n";
//            echo $e->getErrorMsg() . "\n";
        }
    }
}

注: 先在https://console.huaweicloud.com/apiexplorer/#/openapi/Moderation/sdk?api=CheckImageModeration&version=v3调试成功再使用,并且可直接获取对应代码

image.png

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,122评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,070评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,491评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,636评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,676评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,541评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,292评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,211评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,655评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,846评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,965评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,684评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,295评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,894评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,012评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,126评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,914评论 2 355

推荐阅读更多精彩内容