欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

使用PHP调用华为云的内容审查服务(Content Moderation)

最编程 2024-07-27 16:07:20
...

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