全部产品
Search
文档中心

Content Moderation:Image Moderation 2.0 SDK dan Panduan Integrasi

更新时间:Jan 07, 2026

Image Moderation 2.0 mendukung panggilan SDK dan panggilan HTTPS native. Kami menyarankan Anda menggunakan SDK untuk menghubungkan ke layanan karena metode ini memungkinkan Anda melewati langkah-langkah detail seperti autentikasi signature dan konstruksi format body. Topik ini menjelaskan cara menghubungkan ke Image Moderation 2.0.

Langkah 1: Aktifkan layanan

Kunjungi halaman Aktifkan Layanan dan aktifkan layanan Image Moderation Versi 2.0.

Setelah mengaktifkan layanan Image Moderation Versi 2.0, metode penagihan default adalah bayar sesuai penggunaan, yang mengenakan biaya harian berdasarkan penggunaan aktual Anda. Anda tidak dikenai biaya jika tidak memanggil layanan tersebut. Setelah mengintegrasikan dan menggunakan API, sistem secara otomatis menghasilkan tagihan berdasarkan penggunaan Anda. Untuk informasi selengkapnya, lihat Detail Penagihan.

Langkah 2: Buat pengguna RAM dan berikan izin

Sebelum menggunakan SDK untuk memanggil API Content Moderation, Anda harus membuat pengguna, mendapatkan kredensial akses yang terkait dengan pengguna tersebut, serta memberikan izin kepada pengguna tersebut untuk mengakses resource Alibaba Cloud. Dalam contoh ini, pengguna Resource Access Management (RAM) dibuat, pasangan AccessKey digunakan sebagai kredensial akses, dan pengguna RAM diberikan izin untuk memanggil Content Moderation.

  1. Masuk ke Konsol RAM menggunakan Akun Alibaba Cloud atau pengguna RAM yang memiliki hak administratif.

  2. Buat pengguna RAM, pilih OpenAPI Access, lalu catat pasangan AccessKey yang dihasilkan untuk pengguna RAM tersebut. Untuk informasi selengkapnya tentang cara membuat pengguna RAM, lihat Buat Pengguna RAM.

  3. Berikan kebijakan sistem AliyunYundunGreenWebFullAccess kepada pengguna RAM tersebut. Untuk informasi selengkapnya, lihat Berikan Izin kepada Pengguna RAM.

Langkah 3: Instal dan integrasikan SDK

Wilayah berikut didukung:

Wilayah

Titik akhir publik

Titik akhir VPC

Dukungan

Singapura

green-cip.ap-southeast-1.aliyuncs.com

green-cip-vpc.ap-southeast-1.aliyuncs.com

postImageCheckByVL_global, baselineCheck_global, aigcDetector_global, faceDetect_global, faceDetect_pro_global

UK (London)

green-cip.eu-west-1.aliyuncs.com

None

AS (Virginia)

green-cip.us-east-1.aliyuncs.com

green-cip-vpc.us-east-1.aliyuncs.com

baselineCheck_global, aigcDetector_global

AS (Silicon Valley)

green-cip.us-west-1.aliyuncs.com

None

Jerman (Frankfurt)

green-cip.eu-central-1.aliyuncs.com

green-cip-vpc.eu-central-1.aliyuncs.com

Catatan

Jika Anda memerlukan kode contoh SDK untuk bahasa lain, Anda dapat menggunakan alat debugging online di OpenAPI Developer Portal untuk melakukan debugging operasi API. Alat ini secara otomatis menghasilkan kode contoh pemanggilan SDK untuk operasi API yang sesuai.

Dalam kode SDK Alibaba Cloud, Anda dapat membuat kredensial akses default dengan mendefinisikan variabel lingkungan ALIBABA_CLOUD_ACCESS_KEY_ID dan ALIBABA_CLOUD_ACCESS_KEY_SECRET. Saat Anda memanggil operasi API layanan Alibaba Cloud, sistem langsung mengakses kredensial tersebut, membaca pasangan AccessKey Anda, lalu secara otomatis menyelesaikan autentikasi. Sebelum menggunakan kode contoh SDK, Anda harus mengonfigurasi variabel lingkungan. Untuk informasi selengkapnya, lihat Konfigurasikan Kredensial.

Untuk deskripsi field operasi API, lihat API Deteksi Sinkron Image Moderation Tingkat Lanjut 2.0.

Java SDK

Catatan Penggunaan

Catatan

Untuk informasi selengkapnya tentang nilai dan deskripsi field Label yang dikembalikan oleh operasi API ini, lihat Tabel Deskripsi Label Risiko.

Deteksi citra yang dapat diakses publik

Skenario

Jika citra yang akan dimoderasi dapat diakses melalui URL publik, layanan Image Moderation Versi 2.0 dapat mengambil file dari URL tersebut untuk melakukan moderasi.

  1. Untuk menginstal Java SDK, tambahkan dependensi berikut ke file pom.xml. Anda kemudian dapat menggunakan SDK dalam proyek Maven Anda.

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>green20220302</artifactId>
      <version>2.2.11</version>
    </dependency>
  2. Integrasikan Java SDK.

    • Contoh integrasi API sinkron

      import com.alibaba.fastjson.JSON;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.ImageModerationRequest;
      import com.aliyun.green20220302.models.ImageModerationResponse;
      import com.aliyun.green20220302.models.ImageModerationResponseBody;
      import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyData;
      import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyDataResult;
      import com.aliyun.teaopenapi.models.Config;
      import com.aliyun.teautil.models.RuntimeOptions;
      
      import java.util.HashMap;
      import java.util.List;
      import java.util.Map;
      import java.util.UUID;
      
      public class ImageUrlDemo {
          /**
           * Create a request client.
           *
           * @param accessKeyId
           * @param accessKeySecret
           * @param endpoint
           * @return
           * @throws Exception
           */
          public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              Config config = new Config();
              config.setAccessKeyId(accessKeyId);
              config.setAccessKeySecret(accessKeySecret);
              // Set the HTTP proxy.
              // config.setHttpProxy("http://10.10.xx.xx:xxxx");
              // Set the HTTPS proxy.
              // config.setHttpsProxy("https://10.10.xx.xx:xxxx");
              // Modify the region and endpoint as needed.
              config.setEndpoint(endpoint);
              return new Client(config);
          }
      
          public static ImageModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
              Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
              // Create a RuntimeObject instance and set runtime parameters.
              RuntimeOptions runtime = new RuntimeOptions();
      
              // Construct detection parameters.
              Map<String, String> serviceParameters = new HashMap<>();
              // A publicly accessible URL.
              serviceParameters.put("imageUrl", "https://img.alicdn.com/tfs/xxxxxxxxxx001.png");
              // A unique identifier for the data to be detected.
              serviceParameters.put("dataId", UUID.randomUUID().toString());
      
              ImageModerationRequest request = new ImageModerationRequest();
              // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global
              request.setService("baselineCheck_global");
              request.setServiceParameters(JSON.toJSONString(serviceParameters));
      
              ImageModerationResponse response = null;
              try {
                  response = client.imageModerationWithOptions(request, runtime);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return response;
          }
      
          public static void main(String[] args) throws Exception {
              /**
               * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M.
               * Common ways to get environment variables:
               * Method 1:
               *     Get the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Get the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Get the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Get the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              String accessKeyId = "We recommend that you obtain the AccessKey ID of the RAM user from an environment variable";
              String accessKeySecret = "We recommend that you obtain the AccessKey secret of the RAM user from an environment variable";
              ImageModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com");
      
              // Print the detection results.
              if (response != null) {
                  if (response.getStatusCode() == 200) {
                      ImageModerationResponseBody body = response.getBody();
                      System.out.println("requestId=" + body.getRequestId());
                      System.out.println("code=" + body.getCode());
                      System.out.println("msg=" + body.getMsg());
                      if (body.getCode() == 200) {
                          ImageModerationResponseBodyData data = body.getData();
                          System.out.println("dataId=" + data.getDataId());
                          List<ImageModerationResponseBodyDataResult> results = data.getResult();
                          for (ImageModerationResponseBodyDataResult result : results) {
                              System.out.println("label=" + result.getLabel());
                              System.out.println("confidence=" + result.getConfidence());
                          }
                      } else {
                          System.out.println("image moderation not success. code:" + body.getCode());
                      }
                  } else {
                      System.out.println("response not success. status:" + response.getStatusCode());
                  }
              }
      
          }
      }

Deteksi citra lokal

Skenario

Untuk memoderasi citra yang ada di mesin lokal Anda dan tidak memiliki URL akses publik, Anda dapat mengunggah citra tersebut ke bucket Object Storage Service (OSS) yang disediakan oleh Content Moderation. Layanan Image Moderation Versi 2.0 kemudian dapat langsung mengakses OSS untuk mengambil dan memoderasi konten citra tersebut.

  1. Instal Java SDK.

    Instal SDK Content Moderation:

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>green20220302</artifactId>
      <version>2.2.11</version>
    </dependency>

    Instal SDK OSS:

    <dependency>
      <groupId>com.aliyun.oss</groupId>
      <artifactId>aliyun-sdk-oss</artifactId>
      <version>3.16.3</version>
    </dependency>
  2. Integrasikan Java SDK.

    • Contoh integrasi API sinkron

      import com.alibaba.fastjson.JSON;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.DescribeUploadTokenResponse;
      import com.aliyun.green20220302.models.DescribeUploadTokenResponseBody;
      import com.aliyun.green20220302.models.ImageModerationRequest;
      import com.aliyun.green20220302.models.ImageModerationResponse;
      import com.aliyun.green20220302.models.ImageModerationResponseBody;
      import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyData;
      import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyDataResult;
      import com.aliyun.oss.OSS;
      import com.aliyun.oss.OSSClientBuilder;
      import com.aliyun.oss.model.PutObjectRequest;
      import com.aliyun.teaopenapi.models.Config;
      import com.aliyun.teautil.models.RuntimeOptions;
      
      import java.io.File;
      import java.util.HashMap;
      import java.util.List;
      import java.util.Map;
      import java.util.UUID;
      
      public class ScanLocalImage {
      
          // Specifies whether the service is deployed in a VPC.
          public static boolean isVPC = false;
      
          // File upload token: endpoint->token
          public static Map<String, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData> tokenMap = new HashMap<>();
      
          // Client for file upload requests. 
          public static OSS ossClient = null;
      
          /**
           * Create a request client.
           *
           * @param accessKeyId
           * @param accessKeySecret
           * @param endpoint
           * @return
           * @throws Exception
           */
          public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              Config config = new Config();
              config.setAccessKeyId(accessKeyId);
              config.setAccessKeySecret(accessKeySecret);
              // Modify the region and endpoint as needed.
              config.setEndpoint(endpoint);
              return new Client(config);
          }
      
          /**
           * Create a client for file upload requests.
           *
           * @param tokenData
           * @param isVPC
           */
          public static void getOssClient(DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData, boolean isVPC) {
              // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
              if (isVPC) {
                  ossClient = new OSSClientBuilder().build(tokenData.ossInternalEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken());
              } else {
                  ossClient = new OSSClientBuilder().build(tokenData.ossInternetEndPoint, tokenData.getAccessKeyId(), tokenData.getAccessKeySecret(), tokenData.getSecurityToken());
              }
          }
      
          /**
           * Upload a file.
           *
           * @param filePath
           * @param tokenData
           * @return
           * @throws Exception
           */
          public static String uploadFile(String filePath, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData) throws Exception {
              String[] split = filePath.split("\\.");
              String objectName;
              if (split.length > 1) {
                  objectName = tokenData.getFileNamePrefix() + UUID.randomUUID() + "." + split[split.length - 1];
              } else {
                  objectName = tokenData.getFileNamePrefix() + UUID.randomUUID();
              }
              PutObjectRequest putObjectRequest = new PutObjectRequest(tokenData.getBucketName(), objectName, new File(filePath));
              ossClient.putObject(putObjectRequest);
              return objectName;
          }
      
          public static ImageModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
              Client client = createClient(accessKeyId, accessKeySecret, endpoint);
              RuntimeOptions runtime = new RuntimeOptions();
      
              // The full path of the local file, for example, D:\localPath\exampleFile.png.
              String filePath = "D:\\localPath\\exampleFile.png";
              // Get the file upload token.
              if (tokenMap.get(endpoint) == null || tokenMap.get(endpoint).expiration <= System.currentTimeMillis() / 1000) {
                  DescribeUploadTokenResponse tokenResponse = client.describeUploadToken();
                  tokenMap.put(endpoint,tokenResponse.getBody().getData());
              }
              // Client for file upload requests.
              getOssClient(tokenMap.get(endpoint), isVPC);
      
              // Upload the file.
              String objectName = uploadFile(filePath, tokenMap.get(endpoint));
      
              // Construct detection parameters.
              Map<String, String> serviceParameters = new HashMap<>();
              // File upload information.
              serviceParameters.put("ossBucketName", tokenMap.get(endpoint).getBucketName());
              serviceParameters.put("ossObjectName", objectName);
              serviceParameters.put("dataId", UUID.randomUUID().toString());
      
              ImageModerationRequest request = new ImageModerationRequest();
              // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck
              request.setService("baselineCheck_global");
              request.setServiceParameters(JSON.toJSONString(serviceParameters));
      
              ImageModerationResponse response = null;
              try {
                  response = client.imageModerationWithOptions(request, runtime);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return response;
          }
      
          public static void main(String[] args) throws Exception {
              /**
               * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M.
               * Common ways to get environment variables:
               * Method 1:
               *     Get the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Get the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Get the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Get the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              String accessKeyId = "We recommend that you obtain the AccessKey ID of the RAM user from an environment variable";
              String accessKeySecret = "We recommend that you obtain the AccessKey secret of the RAM user from an environment variable";
              // Modify the region and endpoint as needed.
              ImageModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com");
              try {
                  // Print the detection results.
                  if (response != null) {
                      if (response.getStatusCode() == 200) {
                          ImageModerationResponseBody body = response.getBody();
                          System.out.println("requestId=" + body.getRequestId());
                          System.out.println("code=" + body.getCode());
                          System.out.println("msg=" + body.getMsg());
                          if (body.getCode() == 200) {
                              ImageModerationResponseBodyData data = body.getData();
                              System.out.println("dataId=" + data.getDataId());
                              List<ImageModerationResponseBodyDataResult> results = data.getResult();
                              for (ImageModerationResponseBodyDataResult result : results) {
                                  System.out.println("label=" + result.getLabel());
                                  System.out.println("confidence=" + result.getConfidence());
                              }
                          } else {
                              System.out.println("image moderation not success. code:" + body.getCode());
                          }
                      } else {
                          System.out.println("response not success. status:" + response.getStatusCode());
                      }
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              }
          }
      }

Deteksi citra OSS

Skenario

Untuk memoderasi file citra yang disimpan di Object Storage Service (OSS), Anda dapat membuat peran layanan untuk memberikan akses layanan Content Moderation ke resource OSS Anda. Layanan Image Moderation Versi 2.0 menggunakan peran layanan ini untuk mengambil file dari OSS guna moderasi. Anda dapat membuat peran layanan AliyunCIPScanOSSRole di halaman Otorisasi Akses Resource Cloud.

  1. Gunakan Akun Alibaba Cloud Anda (akun root) untuk menuju ke halaman Otorisasi Akses Resource Cloud untuk memberikan izin.

  2. Untuk menginstal Java SDK, tambahkan dependensi berikut ke file pom.xml. Anda kemudian dapat menggunakan SDK dalam proyek Maven Anda.

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>green20220302</artifactId>
      <version>2.2.11</version>
    </dependency>
  3. Integrasikan Java SDK.

    • Contoh integrasi API sinkron

      import com.alibaba.fastjson.JSON;
      import com.aliyun.green20220302.Client;
      import com.aliyun.green20220302.models.ImageModerationRequest;
      import com.aliyun.green20220302.models.ImageModerationResponse;
      import com.aliyun.green20220302.models.ImageModerationResponseBody;
      import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyData;
      import com.aliyun.green20220302.models.ImageModerationResponseBody.ImageModerationResponseBodyDataResult;
      import com.aliyun.teaopenapi.models.Config;
      import com.aliyun.teautil.models.RuntimeOptions;
      
      import java.util.HashMap;
      import java.util.List;
      import java.util.Map;
      import java.util.UUID;
      
      public class OssScanDemo {
          /**
           * Create a request client.
           *
           * @param accessKeyId
           * @param accessKeySecret
           * @param endpoint
           * @return
           * @throws Exception
           */
          public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              Config config = new Config();
              config.setAccessKeyId(accessKeyId);
              config.setAccessKeySecret(accessKeySecret);
              // Set the HTTP proxy.
              // config.setHttpProxy("http://10.10.xx.xx:xxxx");
              // Set the HTTPS proxy.
              // config.setHttpsProxy("https://10.10.xx.xx:xxxx");
              // Modify the region and endpoint as needed.
              config.setEndpoint(endpoint);
              return new Client(config);
          }
      
          public static ImageModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
              // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
              Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
              // Create a RuntimeObject instance and set runtime parameters.
              RuntimeOptions runtime = new RuntimeOptions();
      
              // Construct detection parameters.
              Map<String, String> serviceParameters = new HashMap<>();
              // A unique identifier for the data to be detected.
              serviceParameters.put("dataId", UUID.randomUUID().toString());
              // The region where the bucket of the file to be detected is located. Example: ap-southeast-1
              serviceParameters.put("ossRegionId", "ap-southeast-1");
              // The name of the bucket where the file to be detected is located. Example: bucket001
              serviceParameters.put("ossBucketName", "bucket001");
              // The file to be detected. Example: image/001.jpg
              serviceParameters.put("ossObjectName", "image/001.jpg");
      
              ImageModerationRequest request = new ImageModerationRequest();
              // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global
              request.setService("baselineCheck_global");
              request.setServiceParameters(JSON.toJSONString(serviceParameters));
      
              ImageModerationResponse response = null;
              try {
                  response = client.imageModerationWithOptions(request, runtime);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return response;
          }
      
          public static void main(String[] args) throws Exception {
              /**
               * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M.
               * Common ways to get environment variables:
               * Method 1:
               *     Get the AccessKey ID of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Get the AccessKey secret of the RAM user: System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               * Method 2:
               *     Get the AccessKey ID of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_ID");
               *     Get the AccessKey secret of the RAM user: System.getProperty("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
               */
              String accessKeyId = "We recommend that you obtain the AccessKey ID of the RAM user from an environment variable";
              String accessKeySecret = "We recommend that you obtain the AccessKey secret of the RAM user from an environment variable";
              ImageModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com");
      
              // Print the detection results.
              if (response != null) {
                  if (response.getStatusCode() == 200) {
                      ImageModerationResponseBody body = response.getBody();
                      System.out.println("requestId=" + body.getRequestId());
                      System.out.println("code=" + body.getCode());
                      System.out.println("msg=" + body.getMsg());
                      if (body.getCode() == 200) {
                          ImageModerationResponseBodyData data = body.getData();
                          System.out.println("dataId=" + data.getDataId());
                          List<ImageModerationResponseBodyDataResult> results = data.getResult();
                          for (ImageModerationResponseBodyDataResult result : results) {
                              System.out.println("label=" + result.getLabel());
                              System.out.println("confidence=" + result.getConfidence());
                          }
                      } else {
                          System.out.println("image moderation not success. code:" + body.getCode());
                      }
                  } else {
                      System.out.println("response not success. status:" + response.getStatusCode());
                  }
              }
          }
      }

Python SDK

Catatan Penggunaan

  • Persyaratan lingkungan: Python 3.6 atau lebih baru.

  • Referensi kode sumber: Untuk kode sumbernya, lihat kode sumber Python SDK.

  • Fitur yang didukung: SDK mendukung tiga jenis deteksi citra berikut.

Catatan

Untuk informasi selengkapnya tentang nilai dan deskripsi field Label yang dikembalikan oleh operasi API ini, lihat Tabel Deskripsi Label Risiko.

Deteksi citra yang dapat diakses publik

Skenario

Jika citra yang akan dimoderasi dapat diakses melalui URL publik, layanan Image Moderation V2.0 dapat mengambil file dari URL tersebut untuk melakukan moderasi.

  1. Jalankan perintah berikut untuk mengimpor dependensi yang diperlukan.

    pip install alibabacloud_green20220302==2.2.11
  2. Integrasikan Python SDK.

    • Contoh integrasi API sinkron

      # coding=utf-8
      
      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      from alibabacloud_tea_util import models as util_models
      import json
      import uuid
      
      
      # Create a request client. 
      def create_client(access_key_id, access_key_secret, endpoint):
          config = Config(
              access_key_id=access_key_id,
              access_key_secret=access_key_secret,
              # Set the HTTP proxy.
              # http_proxy='http://10.10.xx.xx:xxxx',
              # Set the HTTPS proxy.
              # https_proxy='https://10.10.xx.xx:xxxx',
              # Modify the region and endpoint as needed.
              endpoint=endpoint
          )
          return Client(config)
      
      
      def invoke_function(access_key_id, access_key_secret, endpoint):
          # Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
          client = create_client(access_key_id, access_key_secret, endpoint)
          # Create a RuntimeObject instance and set runtime parameters.
          runtime = util_models.RuntimeOptions()
      
          # Construct detection parameters.
          service_parameters = {
              # A publicly accessible image URL.
              'imageUrl': 'https://img.alicdn.com/tfs/xxxxxxxxxx001.png',
              # A unique identifier for the data.
              'dataId': str(uuid.uuid1())
          }
      
          image_moderation_request = models.ImageModerationRequest(
              # Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global
              service='baselineCheck_global',
              service_parameters=json.dumps(service_parameters)
          )
      
          try:
              return client.image_moderation_with_options(image_moderation_request, runtime)
          except Exception as err:
              print(err)
      
      
      if __name__ == '__main__':
          # An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M.
          # We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account.
          # Common ways to get environment variables:
          # Get the AccessKey ID of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
          # Get the AccessKey secret of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          access_key_id='We recommend that you obtain the AccessKey ID of the RAM user from an environment variable'
          access_key_secret='We recommend that you obtain the AccessKey secret of the RAM user from an environment variable'
          # Modify the region and endpoint as needed.
          response = invoke_function(access_key_id, access_key_secret, 'green-cip.ap-southeast-1.aliyuncs.com')
          # Print the results.
          if response is not None:
              if response.status_code == 200:
                  # The call was successful.
                  # Get the moderation results.
                  result = response.body
                  print('response success. result:{}'.format(result))
                  if result.code == 200:
                      result_data = result.data
                      print('result: {}'.format(result_data))
              else:
                  print('response not success. status:{} ,result:{}'.format(response.status_code, response))
      

Deteksi citra lokal

Skenario

Untuk memoderasi citra yang disimpan di mesin lokal dan tidak memiliki URL akses publik, Anda dapat mengunggah citra tersebut ke bucket Object Storage Service (OSS) yang disediakan oleh Content Moderation. Layanan Image Moderation Versi 2.0 kemudian dapat langsung mengakses OSS untuk mengambil dan memoderasi konten citra tersebut.

  1. Instal Python SDK.

    Instal SDK Content Moderation:

    pip install alibabacloud_green20220302==2.2.11

    Instal SDK OSS:

    pip install oss2
  2. Integrasikan Python SDK.

    • Contoh integrasi API sinkron

      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      from alibabacloud_tea_util import models as util_models
      import json
      import uuid
      import oss2
      import time
      import os
      
      # Specifies whether the service is deployed in a VPC.
      is_vpc = False
      # File upload token: endpoint->token
      token_dict = dict()
      # Client for file uploads.
      bucket = None
      
      
      # Create a request client.
      def create_client(access_key_id, access_key_secret, endpoint):
          config = Config(
              access_key_id=access_key_id,
              access_key_secret=access_key_secret,
              # Set the HTTP proxy.
              # http_proxy='http://10.10.xx.xx:xxxx',
              # Set the HTTPS proxy.
              # https_proxy='https://10.10.xx.xx:xxxx',
              # Modify the region and endpoint as needed.
              endpoint=endpoint
          )
          return Client(config)
      
      
      # Create a client for file uploads.
      def create_oss_bucket(is_vpc, upload_token):
          global token_dict
          global bucket
          auth = oss2.StsAuth(upload_token.access_key_id, upload_token.access_key_secret, upload_token.security_token)
      
          if (is_vpc):
              end_point = upload_token.oss_internal_end_point
          else:
              end_point = upload_token.oss_internet_end_point
          # Note: Reuse the instantiated bucket as much as possible to avoid repeated connection establishment and improve detection performance.
          bucket = oss2.Bucket(auth, end_point, upload_token.bucket_name)
      
      
      def upload_file(file_name, upload_token):
          create_oss_bucket(is_vpc, upload_token)
          object_name = upload_token.file_name_prefix + str(uuid.uuid1()) + '.' + file_name.split('.')[-1]
          bucket.put_object_from_file(object_name, file_name)
          return object_name
      
      
      def invoke_function(access_key_id, access_key_secret, endpoint):
          # Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
          client = create_client(access_key_id, access_key_secret, endpoint)
          # Create a RuntimeObject instance and set runtime parameters.
          runtime = util_models.RuntimeOptions()
      
          # The full path of the local file, for example, D:\localPath\exampleFile.png.
          file_path = 'D:\\localPath\\exampleFile.png'
      
          # Get the file upload token.
          upload_token = token_dict.setdefault(endpoint, None)
          if (upload_token == None) or int(upload_token.expiration) <= int(time.time()):
              response = client.describe_upload_token()
              upload_token = response.body.data
              token_dict[endpoint] = upload_token
          # Upload the file.
          object_name = upload_file(file_path, upload_token)
      
          # Construct detection parameters.
          service_parameters = {
              # The name of the bucket where the file to be detected is located.
              'ossBucketName': upload_token.bucket_name,
              # The file to be detected.
              'ossObjectName': object_name,
              # A unique identifier for the data.
              'dataId': str(uuid.uuid1())
          }
      
          image_moderation_request = models.ImageModerationRequest(
              # Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global
              service='baselineCheck_global',
              service_parameters=json.dumps(service_parameters)
          )
      
          try:
              return client.image_moderation_with_options(image_moderation_request, runtime)
          except Exception as err:
              print(err)
      
      
      if __name__ == '__main__':
          # An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M.
          # We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account.
          # Common ways to get environment variables:
          # Get the AccessKey ID of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
          # Get the AccessKey secret of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          access_key_id='We recommend that you obtain the AccessKey ID of the RAM user from an environment variable'
          access_key_secret='We recommend that you obtain the AccessKey secret of the RAM user from an environment variable'
          # Modify the region and endpoint as needed.
          response = invoke_function(access_key_id, access_key_secret, 'green-cip.ap-southeast-1.aliyuncs.com')
          # Print the results.
          if response is not None:
              if response.status_code == 200:
                  # The call was successful.
                  # Get the moderation results.
                  result = response.body
                  print('response success. result:{}'.format(result))
                  if result.code == 200:
                      result_data = result.data
                      print('result: {}'.format(result_data))
              else:
                  print('response not success. status:{} ,result:{}'.format(response.status_code, response))
      

Menggunakan citra OSS untuk deteksi

Skenario

Jika file citra yang perlu Anda moderasi disimpan di Alibaba Cloud Object Storage Service (OSS), Anda dapat membuat peran layanan untuk memberikan akses layanan Content Moderation ke resource OSS Anda. Layanan Image Moderation Versi 2.0 menggunakan peran layanan ini untuk mengambil file dari OSS guna moderasi. Anda dapat membuat peran layanan AliyunCIPScanOSSRole di halaman Otorisasi Akses Resource Cloud.

  1. Gunakan Akun Alibaba Cloud Anda (akun root) untuk menuju ke halaman Otorisasi Akses Resource Cloud untuk memberikan izin.

  2. Jalankan perintah berikut untuk menginstal Python SDK.

    pip install alibabacloud_green20220302==2.2.11
  3. Integrasikan Python SDK.

    • Contoh integrasi API sinkron

      from alibabacloud_green20220302.client import Client
      from alibabacloud_green20220302 import models
      from alibabacloud_tea_openapi.models import Config
      from alibabacloud_tea_util import models as util_models
      import json
      import os
      import uuid
      
      
      # Create a request client.
      def create_client(access_key_id, access_key_secret, endpoint):
          config = Config(
              access_key_id=access_key_id,
              access_key_secret=access_key_secret,
              # Set the HTTP proxy.
              # http_proxy='http://10.10.xx.xx:xxxx',
              # Set the HTTPS proxy.
              # https_proxy='https://10.10.xx.xx:xxxx',
              # Modify the region and endpoint as needed.
              endpoint=endpoint
          )
          return Client(config)
      
      
      def invoke_function(access_key_id, access_key_secret, endpoint):
          # Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
          client = create_client(access_key_id, access_key_secret, endpoint)
          # Create a RuntimeObject instance and set runtime parameters.
          runtime = util_models.RuntimeOptions()
      
          # Construct detection parameters.
          service_parameters = {
              # The region where the bucket of the file to be detected is located. Example: ap-southeast-1
              'ossRegionId': 'ap-southeast-1',
              # The name of the bucket where the file to be detected is located. Example: bucket001
              'ossBucketName': 'bucket001',
              # The file to be detected. Example: image/001.jpg
              'ossObjectName': 'image/001.jpg',
              # A unique identifier for the data.
              'dataId': str(uuid.uuid1())
          }
      
          image_moderation_request = models.ImageModerationRequest(
              # Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global
              service='baselineCheck_global',
              service_parameters=json.dumps(service_parameters)
          )
      
          try:
              return client.image_moderation_with_options(image_moderation_request, runtime)
          except Exception as err:
              print(err)
      
      
      if __name__ == '__main__':
          # An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M.
          # We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account.
          # Common ways to get environment variables:
          # Get the AccessKey ID of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
          # Get the AccessKey secret of the RAM user: os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          access_key_id='We recommend that you obtain the AccessKey ID of the RAM user from an environment variable'
          access_key_secret='We recommend that you obtain the AccessKey secret of the RAM user from an environment variable'
          # Modify the region and endpoint as needed.
          response = invoke_function(access_key_id, access_key_secret, 'green-cip.ap-southeast-1.aliyuncs.com')
          # Print the results.
          if response is not None:
              if response.status_code == 200:
                  # The call was successful.
                  # Get the moderation results.
                  result = response.body
                  print('response success. result:{}'.format(result))
                  if result.code == 200:
                      result_data = result.data
                      print('result: {}'.format(result_data))
              else:
                  print('response not success. status:{} ,result:{}'.format(response.status_code, response))
      

PHP SDK

Catatan Penggunaan

  • Persyaratan lingkungan: PHP 5.6 atau lebih baru.

  • Referensi kode sumber: Untuk informasi selengkapnya, lihat kode sumber PHP SDK.

  • Fitur yang didukung: SDK mendukung tiga jenis deteksi citra berikut.

Catatan

Untuk informasi selengkapnya tentang nilai dan deskripsi field Label yang dikembalikan oleh operasi API ini, lihat Tabel Deskripsi Label Risiko.

Deteksi citra yang dapat diakses publik

Skenario

Jika citra yang akan dimoderasi dapat diakses melalui URL publik, layanan Image Moderation Versi 2.0 dapat mengambil file dari URL tersebut untuk melakukan moderasi.

  1. Instal PHP SDK.

    Jalankan perintah berikut untuk mengimpor dependensi yang diperlukan.

    composer require alibabacloud/green-20220302 2.2.10
  2. Integrasikan PHP SDK.

    • Contoh integrasi API sinkron

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationResponse;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationRequest;
      
      /**
       * Create a request client.
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return Green
       */
      function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
      {
          $config = new Config([
              "accessKeyId" => $accessKeyId,
              "accessKeySecret" => $accessKeySecret,
          		// Set the HTTP proxy.
          		// "httpProxy" => "http://10.10.xx.xx:xxxx",
          		// Set the HTTPS proxy.
          		// "httpsProxy" => "https://10.10.xx.xx:xxxx",
              "endpoint" => $endpoint,
          ]);
          return new Green($config);
      }
      
      /**
       * Submit a detection task.
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return ImageModerationResponse
       */
      function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageModerationResponse
      {
          // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
          $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
          // Create a RuntimeObject instance and set runtime parameters.
          $runtime = new RuntimeOptions([]);
          // Construct detection parameters.
          $request = new ImageModerationRequest();
          $serviceParameters = array(
              // The image to be detected, which is a publicly accessible URL.
              'imageUrl' => 'https://img.alicdn.com/tfs/xxxxxxxxxx001.png',
              // A unique identifier for the detection data.
              'dataId' => uniqid());
          // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global
          $request->service = "baselineCheck_global";
          $request->serviceParameters = json_encode($serviceParameters);
          // Submit for detection.
          return $client->imageModerationWithOptions($request, $runtime);
      }
      
      /**
      * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M.
      * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account.
      * Common ways to get environment variables:
      * Get the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      * Get the AccessKey secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
      */
      $accessKeyId = 'We recommend that you obtain the AccessKey ID of the RAM user from an environment variable';
      $accessKeySecret = 'We recommend that you obtain the AccessKey secret of the RAM user from an environment variable';
      // Modify the region and endpoint as needed.
      $endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
      
      try {
          $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
      } catch (Exception $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }

Deteksi citra lokal

Skenario

Untuk memoderasi citra yang ada di mesin lokal Anda dan tidak memiliki URL akses publik, Anda dapat mengunggahnya ke bucket Object Storage Service (OSS) yang disediakan oleh Content Moderation. Layanan Image Moderation Versi 2.0 kemudian dapat langsung mengakses OSS untuk mengambil dan memoderasi konten citra tersebut.

  1. Instal PHP SDK.

    Instal SDK Content Moderation:

    composer require alibabacloud/green-20220302 2.2.10

    Instal SDK OSS:

    composer require aliyuncs/oss-sdk-php
  2. Integrasikan PHP SDK.

    • Contoh integrasi API sinkron

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationResponse;
      use AlibabaCloud\Tea\Utils\Utils;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationRequest;
      use OSS\OssClient;
      
      // Specifies whether the service is deployed in a VPC.
      $isVPC = false;
      // File upload token.
      $tokenArray = array();
      // Client for file upload requests.
      $ossClient = null;
      
      /**
       * Create a request client.
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return Green
       */
      function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
      {
          $config = new Config([
              "accessKeyId" => $accessKeyId,
              "accessKeySecret" => $accessKeySecret,
          		// Set the HTTP proxy.
         			// "httpProxy" => "http://10.10.xx.xx:xxxx",
         		 	// Set the HTTPS proxy.
         			// "httpsProxy" => "https://10.10.xx.xx:xxxx",
              "endpoint" => $endpoint,
          ]);
          return new Green($config);
      }
      
      /**
       * Create a client for file uploads.
       * @param $tokenData
       * @return void
       */
      function create_upload_client($tokenData): void
      {
          global $isVPC;
          global $ossClient;
          // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
          if ($isVPC) {
              $ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternalEndPoint, false, $tokenData->securityToken);
          } else {
              $ossClient = new OssClient($tokenData->accessKeyId, $tokenData->accessKeySecret, $tokenData->ossInternetEndPoint, false, $tokenData->securityToken);
          }
      }
      
      /**
       * Upload a file.
       * @param $fileName
       * @param $tokenData
       * @return string
       * @throws \OSS\Core\OssException
       */
      function upload_file($filePath, $tokenData): string
      {
          global $ossClient;
          // Initialize OssClient.
          create_upload_client($tokenData);
          $split = explode(".", $filePath);
          if (count($split) > 1) {
              $objectName = $tokenData->fileNamePrefix . uniqid() . "." . explode(".", $filePath)[count($split) - 1];
          } else {
              $objectName = $tokenData->fileNamePrefix . uniqid();
          }
          // Upload the file.
          $ossClient->uploadFile($tokenData->bucketName, $objectName, $filePath);
          return $objectName;
      }
      
      /**
       * Submit a detection task.
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return ImageModerationResponse
       * @throws \OSS\Core\OssException
       */
      function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageModerationResponse
      {
          global $tokenArray;
          // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
          $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
          // Create a RuntimeObject instance and set runtime parameters.
          $runtime = new RuntimeOptions([]);
          // The full path of the local file, for example, D:\\localPath\\exampleFile.png.
          $filePath = "D:\\localPath\\exampleFile.png";
      
          // Get the file upload token.
          if (!isset($tokenArray[$endpoint]) || $tokenArray[$endpoint]->expiration <= time()) {
              $token = $client->describeUploadToken();
              $tokenArray[$endpoint] = $token->body->data;
          }
      
          // Upload the file.
          $objectName = upload_file($filePath, $tokenArray[$endpoint]);
      
          // Construct detection parameters.
          $request = new ImageModerationRequest();
          // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global
          $request->service = "baselineCheck_global";
          // The image to be detected, which is a publicly accessible URL.
          $serviceParameters = array(
              'ossObjectName' => $objectName,
              'ossBucketName' => $tokenArray[$endpoint]->bucketName,
              'dataId' => uniqid());
          $request->serviceParameters = json_encode($serviceParameters);
          // Submit for detection.
          return $client->imageModerationWithOptions($request, $runtime);
      }
      
      /**
      * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M.
      * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account.
      * Common ways to get environment variables:
      * Get the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      * Get the AccessKey secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
      */
      $accessKeyId = 'We recommend that you obtain the AccessKey ID of the RAM user from an environment variable';
      $accessKeySecret = 'We recommend that you obtain the AccessKey secret of the RAM user from an environment variable';
      // Modify the region and endpoint as needed.
      $endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
      
      try {
          $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
      } catch (Exception $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }

Deteksi citra OSS

Skenario

Jika file citra yang ingin Anda moderasi disimpan di Object Storage Service (OSS), Anda dapat membuat peran layanan untuk memberikan akses layanan Content Moderation ke resource OSS Anda. Layanan Image Moderation Versi 2.0 menggunakan peran layanan ini untuk mengambil file dari OSS guna moderasi. Anda dapat membuat peran layanan AliyunCIPScanOSSRole di halaman Otorisasi Akses Resource Cloud.

  1. Gunakan Akun Alibaba Cloud Anda (akun root) untuk menuju ke halaman Otorisasi Akses Resource Cloud untuk memberikan izin.

  2. Instal PHP SDK.

    composer require alibabacloud/green-20220302 2.2.10
  3. Integrasikan PHP SDK.

    • Contoh integrasi API sinkron

      <?php
      require('vendor/autoload.php');
      
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationResponse;
      use Darabonba\OpenApi\Models\Config;
      use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
      use AlibabaCloud\SDK\Green\V20220302\Green;
      use AlibabaCloud\SDK\Green\V20220302\Models\ImageModerationRequest;
      use AlibabaCloud\Tea\Utils\Utils;
      
      /**
       * Create a request client.
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return Green
       */
      function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
      {
          $config = new Config([
              "accessKeyId" => $accessKeyId,
              "accessKeySecret" => $accessKeySecret,
              // Set the HTTP proxy.
              // "httpProxy" => "http://10.10.xx.xx:xxxx",
              // Set the HTTPS proxy.
              // "httpsProxy" => "https://10.10.xx.xx:xxxx",
              "endpoint" => $endpoint,
          ]);
          return new Green($config);
      }
      
      /**
       * Submit a detection task.
       * @param $accessKeyId
       * @param $accessKeySecret
       * @param $endpoint
       * @return ImageModerationResponse
       */
      function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageModerationResponse
      {
          // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
          $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
          // Create a RuntimeObject instance and set runtime parameters.
          $runtime = new RuntimeOptions([]);
          // Construct detection parameters.
          $request = new ImageModerationRequest();
          $serviceParameters = array(
            	// The file to be detected. Example: image/001.jpg
              'ossObjectName' => 'image/001.jpg',
              // The region where the bucket of the file to be detected is located. Example: ap-southeast-1
              'ossRegionId' => 'ap-southeast-1',
            	// The name of the bucket where the file to be detected is located. Example: bucket001
              'ossBucketName' => 'bucket001',
              // A unique identifier for the data to be detected.
              'dataId' => uniqid());
          // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global
          $request->service = "baselineCheck_global";
          $request->serviceParameters = json_encode($serviceParameters);
          // Submit for detection.
          return $client->imageModerationWithOptions($request, $runtime);
      }
      
      /**
      * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M.
      * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account.
      * Common ways to get environment variables:
      * Get the AccessKey ID of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
      * Get the AccessKey secret of the RAM user: getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
      */
      $accessKeyId = 'We recommend that you obtain the AccessKey ID of the RAM user from an environment variable';
      $accessKeySecret = 'We recommend that you obtain the AccessKey secret of the RAM user from an environment variable';
      // Modify the region and endpoint as needed.
      $endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
      
      try {
          $response = invoke($accessKeyId, $accessKeySecret, $endpoint);
          print_r(json_encode($response->body, JSON_UNESCAPED_UNICODE));
      } catch (Exception $e) {
          var_dump($e->getMessage());
          var_dump($e->getErrorInfo());
          var_dump($e->getLastException());
          var_dump($e->getLastRequest());
      }

Go SDK

Catatan Penggunaan

  • Referensi kode sumber: Untuk informasi selengkapnya, lihat kode sumber Go SDK.

  • Fitur yang didukung: SDK mendukung tiga jenis deteksi citra berikut.

Catatan

Untuk informasi selengkapnya tentang nilai dan deskripsi field Label yang dikembalikan oleh operasi API ini, lihat Tabel Deskripsi Label Risiko.

Deteksi citra yang dapat diakses publik

Skenario

Jika citra yang akan dimoderasi dapat diakses melalui URL publik, layanan Image Moderation Versi 2.0 dapat mengambil file citra dari URL tersebut untuk melakukan moderasi.

  1. Instal Go SDK.

    go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2
  2. Integrasikan Go SDK.

    • Contoh integrasi API sinkron

      package main
      
      import (
      	"encoding/json"
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
      	util "github.com/alibabacloud-go/tea-utils/v2/service"
      	"github.com/alibabacloud-go/tea/tea"
      	"github.com/google/uuid"
      	"net/http"
      	"os"
      )
      
      // Create a request client.
      func createClient(accessKeyId *string, accessKeySecret *string, endpoint *string) (*green20220302.Client, error) {
      	config := &openapi.Config{
      		AccessKeyId: accessKeyId,
      		AccessKeySecret: accessKeySecret,
      		// Set the HTTP proxy.
      		// HttpProxy: tea.String("http://10.10.xx.xx:xxxx"),
      		// Set the HTTPS proxy.
      		// HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
      		Endpoint: endpoint,
      	}
      	// Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
      	return green20220302.NewClient(config);
      }
      
      func invoke(accessKeyId *string, accessKeySecret *string, endpoint *string) (_result *green20220302.ImageModerationResponse, _err error) {
      	// Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
      	client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
      	if _err != nil {
      		return nil,_err
      	}
      	// Set runtime parameters. This is valid only for requests that use this runtime parameter instance.
      	runtime := &util.RuntimeOptions{}
      
      	// Construct an image detection request.
      	serviceParameters, _ := json.Marshal(
      		map[string]interface{}{
      			// The URL of the image to be detected, which must be publicly accessible.
      			"imageUrl": "https://img.alicdn.com/tfs/xxxxxxxxxx001.png",
      			// The ID of the data to be detected.
      			"dataId":uuid.New(),
      		},
      	)
      	imageModerationRequest := &green20220302.ImageModerationRequest{
      		// Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global
      		Service:           tea.String("baselineCheck_global"),
      		ServiceParameters: tea.String(string(serviceParameters)),
      	}
      
      	return client.ImageModerationWithOptions(imageModerationRequest, runtime)
      
      }
      
      func main() {
      	/**
      	 * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M.
      	 * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account.
      	 * Common ways to get environment variables:
      	 * Get the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
      	 * Get the AccessKey secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
      	 */
      	var accessKeyId= tea.String("We recommend that you obtain the AccessKey ID of the RAM user from an environment variable");
      	var accessKeySecret= tea.String("We recommend that you obtain the AccessKey secret of the RAM user from an environment variable");
      	// Modify the region and endpoint as needed.
      	var endpoint = tea.String("green-cip.ap-southeast-1.aliyuncs.com");
      	response,_err := invoke(accessKeyId,accessKeySecret,endpoint)
      
      	if response != nil {
      		statusCode := tea.IntValue(tea.ToInt(response.StatusCode))
      		body := response.Body
      		imageModerationResponseData := body.Data
      		fmt.Println("requestId:" + tea.StringValue(body.RequestId))
      		if statusCode == http.StatusOK {
      			fmt.Println("response success. response:" + body.String())
      			if tea.IntValue(tea.ToInt(body.Code)) == 200 {
      				result := imageModerationResponseData.Result
      				fmt.Println("response dataId:" + tea.StringValue(imageModerationResponseData.DataId))
      				for i := 0; i < len(result); i++ {
      					fmt.Println("response label:" + tea.StringValue(result[i].Label))
      					fmt.Println("response confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence)))
      				}
      			} else {
      				fmt.Println("image moderation not success. status" + tea.ToString(body.Code))
      			}
      		} else {
      			fmt.Print("response not success. status:" + tea.ToString(statusCode))
      			fmt.Println("Error:", _err)
      		}
      	}
      }

Deteksi citra lokal

Skenario

Untuk memoderasi citra yang disimpan di mesin lokal Anda dan tidak memiliki URL publik, Anda dapat mengunggah citra tersebut ke bucket Object Storage Service (OSS) yang disediakan oleh Content Moderation. Layanan Image Moderation Versi 2.0 kemudian dapat langsung mengakses OSS untuk mengambil konten citra tersebut guna moderasi.

  1. Instal Go SDK.

    Instal SDK Content Moderation:

    go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2

    Instal SDK OSS:

    go get github.com/aliyun/aliyun-oss-go-sdk/oss
  2. Integrasikan Go SDK.

    • Contoh integrasi API sinkron

      package main
      
      import (
      	"encoding/json"
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
      	util "github.com/alibabacloud-go/tea-utils/v2/service"
      	"github.com/alibabacloud-go/tea/tea"
      	"github.com/aliyun/aliyun-oss-go-sdk/oss"
      	"github.com/google/uuid"
      	"net/http"
      	"os"
      	"strings"
      	"time"
      )
      // File upload token.
      var TokenMap =make(map[string]*green20220302.DescribeUploadTokenResponseBodyData)
      // Client for file uploads.
      var Bucket *oss.Bucket
      // Specifies whether the service is deployed in a VPC.
      var isVPC = false
      // Create a request client.
      func createClient(accessKeyId string, accessKeySecret string, endpoint string) (*green20220302.Client, error) {
      	config := &openapi.Config{
      		AccessKeyId: tea.String(accessKeyId),
      		AccessKeySecret: tea.String(accessKeySecret),
      		// Set the HTTP proxy.
      		// HttpProxy: tea.String("http://10.10.xx.xx:xxxx"),
      		// Set the HTTPS proxy.
      		// HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
      		Endpoint: tea.String(endpoint),
      	}
      	// Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
      	return green20220302.NewClient(config);
      }
      
      // Create a client for file uploads.
      func createOssClient(tokenData *green20220302.DescribeUploadTokenResponseBodyData) {
      	if isVPC{
      		ossClient, err := oss.New(tea.StringValue(tokenData.OssInternalEndPoint), tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken)))
      		if err != nil {
      			fmt.Println("Error:", err)
      			os.Exit(-1)
      		}
      		Bucket, _ =ossClient.Bucket(tea.StringValue(tokenData.BucketName));
      	}else {
      		ossClient, err := oss.New(tea.StringValue(tokenData.OssInternetEndPoint), tea.StringValue(tokenData.AccessKeyId), tea.StringValue(tokenData.AccessKeySecret), oss.SecurityToken(tea.StringValue(tokenData.SecurityToken)))
      		if err != nil {
      			fmt.Println("Error:", err)
      			os.Exit(-1)
      		}
      		Bucket, _ =ossClient.Bucket(tea.StringValue(tokenData.BucketName));
      	}
      }
      
      // Upload a file.
      func uploadFile(filePath string,tokenData *green20220302.DescribeUploadTokenResponseBodyData) (string,error) {
      	createOssClient(tokenData)
      	objectName := tea.StringValue(tokenData.FileNamePrefix) + uuid.New().String() + "." + strings.Split(filePath, ".")[1]
      	// Upload the file.
      	_err := Bucket.PutObjectFromFile(objectName, filePath)
      	if _err != nil {
      		fmt.Println("Error:", _err)
      		os.Exit(-1)
      	}
      	return objectName,_err
      }
      
      func invoke(accessKeyId string, accessKeySecret string, endpoint string) (_result *green20220302.ImageModerationResponse, _err error) {
      	// Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
      	client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
      	if _err != nil {
      		return nil,_err
      	}
      	// Set runtime parameters. This is valid only for requests that use this runtime parameter instance.
      	runtime := &util.RuntimeOptions{}
      	// The full path of the local file, for example, D:\localPath\exampleFile.png.
      	var filePath = "D:\\localPath\\exampleFile.png"
      	// Get a temporary token for file upload.
      	tokenData,ok:=TokenMap[endpoint];
      	if !ok || tea.Int32Value(tokenData.Expiration) <= int32(time.Now().Unix()) {
      		// Get a temporary token for file upload.
      		uploadTokenResponse, _err := client.DescribeUploadToken()
      		if _err != nil {
      			return nil,_err		}
      		tokenData = uploadTokenResponse.Body.Data
      		TokenMap[endpoint] = tokenData
      	}
      	var objectName, _ = uploadFile(filePath,TokenMap[endpoint])
      
      	// Construct an image detection request.
      	serviceParameters, _ := json.Marshal(
      		map[string]interface{}{
      			"ossBucketName": tea.StringValue(TokenMap[endpoint].BucketName),
      			"ossObjectName": objectName,
      			"dataId":   uuid.New().String(),
      		},
      	)
      	imageModerationRequest := &green20220302.ImageModerationRequest{
      		// Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global
      		Service:           tea.String("baselineCheck_global"),
      		ServiceParameters: tea.String(string(serviceParameters)),
      	}
      
      	return client.ImageModerationWithOptions(imageModerationRequest, runtime)
      
      }
      
      func main() {
      	/**
      	 * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M.
      	 * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account.
      	 * Common ways to get environment variables:
      	 * Get the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
      	 * Get the AccessKey secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
      	 */
      	var accessKeyId= "We recommend that you obtain the AccessKey ID of the RAM user from an environment variable";
      	var accessKeySecret= "We recommend that you obtain the AccessKey secret of the RAM user from an environment variable";
      	// Modify the region and endpoint as needed.
      	var endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
      	response,_err := invoke(accessKeyId,accessKeySecret,endpoint)
      
      	if response != nil {
      		statusCode := tea.IntValue(tea.ToInt(response.StatusCode))
      		body := response.Body
      		imageModerationResponseData := body.Data
      		fmt.Println("requestId:" + tea.StringValue(body.RequestId))
      		if statusCode == http.StatusOK {
      			fmt.Println("response success. response:" + body.String())
      			if tea.IntValue(tea.ToInt(body.Code)) == 200 {
      				result := imageModerationResponseData.Result
      				fmt.Println("response dataId:" + tea.StringValue(imageModerationResponseData.DataId))
      				for i := 0; i < len(result); i++ {
      					fmt.Println("response label:" + tea.StringValue(result[i].Label))
      					fmt.Println("response confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence)))
      				}
      			} else {
      				fmt.Println("image moderation not success. status" + tea.ToString(body.Code))
      			}
      		} else {
      			fmt.Print("response not success. status:" + tea.ToString(statusCode))
      			fmt.Println("Error:", _err)
      		}
      	}
      }

Deteksi citra OSS

Skenario

Jika file citra yang perlu Anda moderasi disimpan di Alibaba Cloud Object Storage Service (OSS), Anda dapat membuat peran layanan untuk memberikan otorisasi layanan Content Moderation untuk mengakses resource OSS Anda. Layanan Image Moderation V2.0 menggunakan peran layanan ini untuk mengambil file dari OSS guna moderasi. Anda dapat membuat peran layanan AliyunCIPScanOSSRole di halaman Otorisasi Akses Resource Cloud.

  1. Gunakan Akun Alibaba Cloud Anda (akun root) untuk menuju ke halaman Otorisasi Akses Resource Cloud untuk memberikan izin.

  2. Jalankan perintah berikut untuk menginstal Go SDK.

    go git clone --branch v2.2.11 github.com/alibabacloud-go/green-20220302/v2
  3. Integrasikan Go SDK.

    • Contoh integrasi API sinkron

      package main
      
      import (
      	"encoding/json"
      	"fmt"
      	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
      	green20220302 "github.com/alibabacloud-go/green-20220302/v3/client"
      	util "github.com/alibabacloud-go/tea-utils/v2/service"
      	"github.com/alibabacloud-go/tea/tea"
      	"github.com/google/uuid"
      	"net/http"
      	"os"
      )
      
      // Create a request client.
      func createClient(accessKeyId *string, accessKeySecret *string, endpoint *string) (*green20220302.Client, error) {
      	config := &openapi.Config{
      		AccessKeyId: accessKeyId,
      		AccessKeySecret: accessKeySecret,
      		// Set the HTTP proxy.
      		// HttpProxy: tea.String("http://10.10.xx.xx:xxxx"),
      		// Set the HTTPS proxy.
      		// HttpsProxy: tea.String("https://username:password@xxx.xxx.xxx.xxx:9999"),
      		Endpoint: endpoint,
      	}
      	// Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
      	return green20220302.NewClient(config);
      }
      
      func invoke(accessKeyId *string, accessKeySecret *string, endpoint *string) (_result *green20220302.ImageModerationResponse, _err error) {
      	// Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
      	client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
      	if _err != nil {
      		return nil,_err
      	}
      	// Set runtime parameters. This is valid only for requests that use this runtime parameter instance.
      	runtime := &util.RuntimeOptions{}
      
      	// Construct an image detection request.
      		serviceParameters, _ := json.Marshal(
      			map[string]interface{}{
      				// The region where the bucket of the image to be detected is located. Example: ap-southeast-1
      				"ossRegionId": "ap-southeast-1",
      				// The name of the bucket where the image to be detected is located. Example: bucket001
      				"ossBucketName":"bucket001",
      				// The name of the object of the image to be detected. Example: image/001.jpg
      				"ossObjectName":"image//001.jpg",
      				// The ID of the data to be detected.
      				"dataId":   uuid.New().String(),
      			},
      		)
      		imageModerationRequest := &green20220302.ImageModerationRequest{
      			// Image moderation service, the serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global
      			Service:           tea.String("baselineCheck_global"),
      			ServiceParameters: tea.String(string(serviceParameters)),
      		}
      
      	return client.ImageModerationWithOptions(imageModerationRequest, runtime)
      
      }
      
      func main() {
      	/**
      	 * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M.
      	 * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account.
      	 * Common ways to get environment variables:
      	 * Get the AccessKey ID of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
      	 * Get the AccessKey secret of the RAM user: os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
      	 */
      	
      	// Modify the region and endpoint as needed.
      	var endpoint = tea.String("green-cip.ap-southeast-1.aliyuncs.com");
      	response,_err := invoke(accessKeyId,accessKeySecret,endpoint)
      
      	if response != nil {
      		statusCode := tea.IntValue(tea.ToInt(response.StatusCode))
      		body := response.Body
      		imageModerationResponseData := body.Data
      		fmt.Println("requestId:" + tea.StringValue(body.RequestId))
      		if statusCode == http.StatusOK {
      			fmt.Println("response success. response:" + body.String())
      			if tea.IntValue(tea.ToInt(body.Code)) == 200 {
      				result := imageModerationResponseData.Result
      				fmt.Println("response dataId:" + tea.StringValue(imageModerationResponseData.DataId))
      				for i := 0; i < len(result); i++ {
      					fmt.Println("response label:" + tea.StringValue(result[i].Label))
      					fmt.Println("response confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence)))
      				}
      			} else {
      				fmt.Println("image moderation not success. status" + tea.ToString(body.Code))
      			}
      		} else {
      			fmt.Print("response not success. status:" + tea.ToString(statusCode))
      			fmt.Println("Error:", _err)
      		}
      	}
      }

Node.js SDK

Catatan Penggunaan

  • Referensi kode sumber: Untuk informasi selengkapnya, lihat kode sumber Node.js SDK.

  • Fitur yang didukung: SDK mendukung tiga jenis deteksi citra berikut.

Catatan

Untuk informasi selengkapnya tentang nilai dan deskripsi field Label yang dikembalikan oleh operasi API ini, lihat Tabel Deskripsi Label Risiko.

Deteksi citra yang dapat diakses publik

Skenario

Jika citra yang memerlukan moderasi dapat diakses melalui URL publik, layanan Image Moderation V2.0 dapat mengambil file dari URL citra tersebut untuk moderasi.

  1. Instal Node.js SDK.

    Jalankan perintah berikut untuk mengimpor dependensi yang relevan.

    npm install @alicloud/green20220302@2.2.10
  2. Integrasikan Node.js SDK.

    • Contoh integrasi API sinkron

      const RPCClient = require("@alicloud/pop-core");
      const { v4: uuidv4 } = require('uuid');
      
      async function main() {
          // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
          var client = new RPCClient({
      				/**
               * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M.
               * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account.
               * Common ways to get environment variables:
               * Get the AccessKey ID of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID']
               * Get the AccessKey secret of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
               */
              accessKeyId: 'We recommend that you obtain the AccessKey ID of the RAM user from an environment variable',
              accessKeySecret: 'We recommend that you obtain the AccessKey secret of the RAM user from an environment variable',
              // Modify the region and endpoint as needed.
              endpoint: "https://green-cip.ap-southeast-1.aliyuncs.com",
              apiVersion: '2022-03-02',
              // Set the HTTP proxy.
              // httpProxy: "http://xx.xx.xx.xx:xxxx",
              // Set the HTTPS proxy.
              // httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999",
          });
          // Create an API request and set parameters.
          var params = {
              // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global
              "Service": "baselineCheck_global",
              "ServiceParameters": JSON.stringify({
                  // A unique identifier for the data.
                  "dataId": uuidv4(),
                  // The URL of the image to be detected, which must be publicly accessible.
                  "imageUrl": "https://img.alicdn.com/tfs/xxxxxxxxxx001.png"
              })
          }
      
          var requestOption = {
              method: 'POST',
              formatParams: false,
          };
      
          try {
              // Call the API operation to get the detection results.
              var response = await client.request('ImageModeration', params, requestOption)
          } catch (err) {
              console.log(err);
          }
      
          return response;
      }
      
      main().then(function (response) {
          console.log(JSON.stringify(response))
      });

Deteksi citra lokal

Skenario

Untuk memoderasi citra yang ada di mesin lokal Anda dan tidak memiliki URL akses publik, Anda dapat mengunggahnya ke bucket Object Storage Service (OSS) yang disediakan oleh Content Moderation. Layanan Image Moderation Versi 2.0 kemudian dapat langsung mengakses OSS untuk mengambil dan memoderasi konten citra tersebut.

  1. Instal Node.js SDK.

    Instal SDK Content Moderation:

    npm install @alicloud/green20220302@2.2.10

    Instal dependensi OSS:

    npm install ali-oss --save
  2. Integrasikan Node.js SDK.

    • Contoh integrasi API sinkron

      const RPCClient = require("@alicloud/pop-core");
      const OSS = require('ali-oss');
      const { v4: uuidv4 } = require('uuid');
      const path = require("path");
      
      // Specifies whether the service is deployed in a VPC.
      var isVPC = false;
      // File upload token.
      var tokenDic = new Array();
      // Client for file uploads.
      var ossClient;
      
      // Create a client for file uploads.
      function createClient(accessKeyId, accessKeySecret, endpoint) {
          return new RPCClient({
              accessKeyId: accessKeyId,
              accessKeySecret: accessKeySecret,
              endpoint: endpoint,
              apiVersion: '2022-03-02',
              // Set the HTTP proxy.
              // httpProxy: "http://xx.xx.xx.xx:xxxx",
              // Set the HTTPS proxy.
              // httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999",
          });
      }
      
      // Create a client for file uploads.
      function getOssClient(tokenData, isVPC) {
          if (isVPC) {
              ossClient = new OSS({
                  accessKeyId: tokenData['AccessKeyId'],
                  accessKeySecret: tokenData['AccessKeySecret'],
                  stsToken: tokenData['SecurityToken'],
                  endpoint: tokenData['OssInternalEndPoint'],
                  bucket: tokenData['BucketName'],
              });
          } else {
              ossClient = new OSS({
                  accessKeyId: tokenData['AccessKeyId'],
                  accessKeySecret: tokenData['AccessKeySecret'],
                  stsToken: tokenData['SecurityToken'],
                  endpoint: tokenData['OssInternetEndPoint'],
                  bucket: tokenData['BucketName'],
              });
          }
      }
      
      
      async function invoke(accessKeyId, accessKeySecret, endpoint) {
          // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
          var client = createClient(accessKeyId, accessKeySecret, endpoint);
          var requestOption = {
              method: 'POST',
              formatParams: false,
          };
          // The full path of the local file, for example, D:\\localPath\\exampleFile.png.
          var filePath = 'D:\\localPath\\exampleFile.png';
      
          // Get the file upload token.
          if (tokenDic[endpoint] == null || tokenDic[endpoint]['Expiration'] <= Date.parse(new Date() / 1000)) {
              var tokenResponse = await client.request('DescribeUploadToken', '', requestOption)
              tokenDic[endpoint] = tokenResponse.Data;
          }
      
          // Get the client for file uploads.
          getOssClient(tokenDic[endpoint], isVPC)
          var split = filePath.split(".");
          var objectName;
          if (split.length > 1) {
              objectName = tokenDic[endpoint].FileNamePrefix + uuidv4() + "." + split[split.length - 1];
          } else {
              objectName = tokenDic[endpoint].FileNamePrefix + uuidv4();
          }
          // Upload the file.
          const result = await ossClient.put(objectName, path.normalize(filePath));
      
          // Create a detection API request and set parameters.
          var params = {
              // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global
              "Service": "baselineCheck_global",
              // Information about the uploaded local image.
              "ServiceParameters": JSON.stringify({
                  "ossBucketName": tokenDic[endpoint].BucketName,
                  "ossObjectName": objectName
              })
          }
          // Call the API operation to get the detection results.
          return await client.request('ImageModeration', params, requestOption);
      }
      
      
      
      function main() {
      	/**
          * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M.
          * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account.
          * Common ways to get environment variables:
          * Get the AccessKey ID of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID']
          * Get the AccessKey secret of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
          */
          const accessKeyId: 'We recommend that you obtain the AccessKey ID of the RAM user from an environment variable'
          const accessKeySecret: 'We recommend that you obtain the AccessKey secret of the RAM user from an environment variable'
          // Modify the region and endpoint as needed.
          var endpoint = "https://green-cip.ap-southeast-1.aliyuncs.com"
      
          try {
              // Call the API operation to get the detection results.
              invoke(accessKeyId, accessKeySecret, endpoint).then(function (response) {
                      console.log(JSON.stringify(response))
              })
          } catch (err) {
              console.log(err);
          }
      }
      
      main();

Deteksi citra OSS

Skenario

Jika file citra yang ingin Anda moderasi disimpan di Object Storage Service (OSS), Anda dapat membuat peran layanan untuk memberikan akses layanan Content Moderation ke resource OSS Anda. Layanan Image Moderation Versi 2.0 menggunakan peran layanan ini untuk mengambil file dari OSS guna moderasi. Anda dapat membuat peran layanan AliyunCIPScanOSSRole di halaman Otorisasi Akses Resource Cloud.

  1. Gunakan Akun Alibaba Cloud Anda (akun root) untuk menuju ke halaman Otorisasi Akses Resource Cloud untuk memberikan izin.

  2. Instal Node.js SDK.

    npm install @alicloud/green20220302@2.2.10
  3. Integrasikan Node.js SDK.

    • Contoh integrasi API sinkron

      const RPCClient = require("@alicloud/pop-core");
      const { v4: uuidv4 } = require('uuid');
      
      async function main() {
          // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
          var client = new RPCClient({
      				/**
               * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M.
               * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account.
               * Common ways to get environment variables:
               * Get the AccessKey ID of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID']
               * Get the AccessKey secret of the RAM user: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
               */
              accessKeyId: 'We recommend that you obtain the AccessKey ID of the RAM user from an environment variable',
              accessKeySecret: 'We recommend that you obtain the AccessKey secret of the RAM user from an environment variable',
              // Modify the region and endpoint as needed.
              endpoint: "https://green-cip.ap-southeast-1.aliyuncs.com",
              apiVersion: '2022-03-02',
              // Set the HTTP proxy.
              // httpProxy: "http://xx.xx.xx.xx:xxxx",
              // Set the HTTPS proxy.
              // httpsProxy: "https://username:password@xxx.xxx.xxx.xxx:9999",
          });
      
          // Create an API request and set parameters.
          var params = {
              // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global
              "Service": "baselineCheck_global",
              // OSS information of the image to be detected.
              "ServiceParameters": JSON.stringify({
                  // The region where the bucket of the file to be detected is located. Example: ap-southeast-1
                  "ossRegionId": "ap-southeast-1",
                  // The name of the bucket where the file to be detected is located. Example: bucket001
                  "ossBucketName": "bucket001",
                  // The file to be detected. Example: image/001.jpg
                  "ossObjectName": "image/001.jpg",
                  // A unique identifier for the data.
                  "dataId": uuidv4()
              })
          }
      
          var requestOption = {
              method: 'POST',
              formatParams: false,
          };
      
          try {
              // Call the API operation to get the detection results.
              var response = await client.request('ImageModeration', params, requestOption)
              return response;
          } catch (err) {
              console.log(err);
          }
      }
      
      main().then(function (response) {
          console.log(JSON.stringify(response))
      });

C# SDK

Tindakan Pencegahan

  • Referensi kode sumber: Untuk informasi selengkapnya, lihat kode sumber C# SDK.

  • Fitur yang didukung: SDK mendukung tiga jenis deteksi citra berikut.

Catatan

Untuk informasi selengkapnya tentang nilai dan deskripsi field Label yang dikembalikan oleh operasi API ini, lihat Tabel Deskripsi Label Risiko.

Deteksi citra yang dapat diakses publik

Skenario

Jika citra yang akan dimoderasi dapat diakses melalui URL publik, layanan Image Moderation Versi 2.0 dapat mengambil file dari URL citra tersebut untuk melakukan moderasi.

  1. Anda dapat menginstal C# SDK.

    dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10
  2. Integrasikan C# SDK.

    • Contoh integrasi API sinkron

      // This file is auto-generated, don't edit it. Thanks.
      
      using Newtonsoft.Json;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class ImageModerationAutoRoute
          {
              public static void Main(string[] args)
              {
                  /**
                  * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M.
                  * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account.
                  * Common ways to get environment variables:
                  * Get the AccessKey ID of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  String accessKeyId = "We recommend that you obtain the AccessKey ID of the RAM user from an environment variable";
                  String accessKeySecret = "We recommend that you obtain the AccessKey secret of the RAM user from an environment variable";
                  // Modify the region and endpoint as needed.
                  String endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
                  // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  // Set runtime parameters. This is valid only for requests that use this runtime parameter instance.
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
                  // Construct an image detection request.
                  Models.ImageModerationRequest imageModerationRequest =
                      new Models.ImageModerationRequest();
                  // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global
                  imageModerationRequest.Service = "baselineCheck_global";
                  Dictionary<string, object> task = new Dictionary<string, object>();
                  // The URL of the image to be detected, which must be publicly accessible.
                  task.Add(
                      "imageUrl",
                      "https://img.alicdn.com/tfs/xxxxxxxxxx001.png"
                  );
                  // The ID of the data to be detected.
                  task.Add("dataId", Guid.NewGuid().ToString());
                  imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
      
                  try
                  {
                      // Call the API operation to get the detection results.
                      Models.ImageModerationResponse response = client.ImageModerationWithOptions(
                          imageModerationRequest,
                          runtimeOptions
                      );
      
                      Console.WriteLine(response.Body.RequestId);
                      Console.WriteLine(JsonConvert.SerializeObject(response.Body));
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                  }
              }
      
              // Create a request client.
              public static Client createClient(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  AlibabaCloud.OpenApiClient.Models.Config config =
                      new AlibabaCloud.OpenApiClient.Models.Config
                      {
                          AccessKeyId = accessKeyId,
                          AccessKeySecret = accessKeySecret,
                          // Set the HTTP proxy.
                          // HttpProxy = "http://10.10.xx.xx:xxxx",
                          // Set the HTTPS proxy.
                          // HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          // The domain name to access.
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
          }
      }

Deteksi citra lokal

Skenario

Untuk memoderasi citra yang ada di mesin lokal Anda dan tidak memiliki URL akses publik, Anda dapat mengunggahnya ke bucket Object Storage Service (OSS) yang disediakan oleh Content Moderation. Layanan Image Moderation V2.0 kemudian dapat langsung mengakses OSS untuk mengambil citra tersebut dan melakukan moderasi.

  1. Instal C# SDK.

    Instal SDK Content Moderation:

    dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10

    Instal SDK OSS:

    //.
    dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.8
    //.
    Install via NuGet 
    1. If your Visual Studio does not have NuGet installed, install it first.
    2. In Visual Studio, create a new project or open an existing one. Choose Tools > NuGet Package Manager > Manage NuGet Packages for Solution.
    3. Search for aliyun.oss.sdk. In the results, find Aliyun.OSS.SDK (for .NET Framework) or Aliyun.OSS.SDK.NetCore (for .Net Core), select the latest version, and click Install.
  2. Integrasikan C# SDK.

    • Contoh integrasi API sinkron

      // This file is auto-generated, don't edit it. Thanks.
      
      using System;
      using Newtonsoft.Json;
      using Aliyun.OSS;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class ImageModerationAutoRoute
          {
              // File upload token.
              public static Dictionary<String, Models.DescribeUploadTokenResponse> tokenDic =
                  new Dictionary<String, Models.DescribeUploadTokenResponse>();
      
              // Client for file uploads.
              public static OssClient ossClient = null;
      
              // Specifies whether the service is deployed in a VPC.
              public static Boolean isVPC = false;
      
              public static void Main(string[] args)
              {
                  /**
                  * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M.
                  * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account.
                  * Common ways to get environment variables:
                  * Get the AccessKey ID of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  String accessKeyId = "We recommend that you obtain the AccessKey ID of the RAM user from an environment variable";
                  String accessKeySecret = "We recommend that you obtain the AccessKey secret of the RAM user from an environment variable";
                  // Modify the region and endpoint as needed.
                  String endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
      
                  Models.ImageModerationResponse response = invoke(
                      accessKeyId,
                      accessKeySecret,
                      endpoint
                  );
              
                  Console.WriteLine(response.Body.RequestId);
                  Console.WriteLine(JsonConvert.SerializeObject(response.Body));
              }
      
              // Create a request client.
              public static Client createClient(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  AlibabaCloud.OpenApiClient.Models.Config config =
                      new AlibabaCloud.OpenApiClient.Models.Config
                      {
                          AccessKeyId = accessKeyId,
                          AccessKeySecret = accessKeySecret,
                          // Set the HTTP proxy.
                          // HttpProxy = "http://10.10.xx.xx:xxxx",
                          // Set the HTTPS proxy.
                          // HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          // The domain name to access.
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
      
              // Create a client for file uploads.
              private static OssClient getOssClient(
                  Models.DescribeUploadTokenResponse tokenResponse,
                  Boolean isVPC
              )
              {
                  var tokenData = tokenResponse.Body.Data;
                  if (isVPC)
                  {
                      return new OssClient(
                          tokenData.OssInternalEndPoint,
                          tokenData.AccessKeyId,
                          tokenData.AccessKeySecret,
                          tokenData.SecurityToken
                      );
                  }
                  else
                  {
                      return new OssClient(
                          tokenData.OssInternetEndPoint,
                          tokenData.AccessKeyId,
                          tokenData.AccessKeySecret,
                          tokenData.SecurityToken
                      );
                  }
              }
      
              // Upload a file.
              public static String uploadFile(
                  String filePath,
                  Models.DescribeUploadTokenResponse tokenResponse
              )
              {
                  // Construct an OssClient instance.
                  ossClient = getOssClient(tokenResponse, isVPC);
                  var tokenData = tokenResponse.Body.Data;
      
                  String objectName =
                      tokenData.FileNamePrefix
                      + Guid.NewGuid().ToString()
                      + "."
                      + filePath.Split(".").GetValue(1);
                  // Upload the file.
                  ossClient.PutObject(tokenData.BucketName, objectName, filePath);
                  return objectName;
              }
      
              // Submit a detection request.
              public static Models.ImageModerationResponse invoke(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  // Set runtime parameters. This is valid only for requests that use this runtime parameter instance.
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
                  // The full path of the local file, for example, D:\localPath\exampleFile.png.
                  String filePath = "D:\\localPath\\exampleFile.png.";
                  try
                  {
                      // Get a temporary token for file upload.
                      if (
                          !tokenDic.ContainsKey(endpoint)
                          || tokenDic[endpoint].Body.Data.Expiration
                              <= DateTimeOffset.Now.ToUnixTimeSeconds()
                      )
                      {
                          var tokenResponse = client.DescribeUploadToken();
                          tokenDic[endpoint] = tokenResponse;
                      }
                      // Upload the file.
                      String objectName = uploadFile(filePath, tokenDic[endpoint]);
                      // Construct an image detection request.
                      Models.ImageModerationRequest imageModerationRequest =
                          new Models.ImageModerationRequest();
                      // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global
                      imageModerationRequest.Service = "baselineCheck_global";
                      Dictionary<string, object> task = new Dictionary<string, object>();
                      // Information about the image to be detected.
                      task.Add("ossBucketName", tokenDic[endpoint].Body.Data.BucketName);
                      task.Add("ossObjectName", objectName);
                      // The ID of the data to be detected.
                      task.Add("dataId", Guid.NewGuid().ToString());
                      imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
                      // Call the API operation to get the detection results.
                      Models.ImageModerationResponse response = client.ImageModerationWithOptions(
                          imageModerationRequest,
                          runtimeOptions
                      );
                      return response;
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                      return null;
                  }
              }
          }
      }

Deteksi citra OSS

Skenario

Jika file citra yang perlu Anda moderasi disimpan di Alibaba Cloud Object Storage Service (OSS), Anda dapat membuat peran layanan untuk memberikan akses layanan Content Moderation ke resource OSS Anda. Layanan Image Moderation Versi 2.0 menggunakan peran layanan ini untuk mengambil file dari OSS guna moderasi. Anda dapat membuat peran layanan AliyunCIPScanOSSRole di halaman Otorisasi Akses Resource Cloud.

  1. Gunakan Akun Alibaba Cloud Anda (akun root) untuk menuju ke halaman Otorisasi Akses Resource Cloud untuk memberikan izin.

  2. Instal C# SDK.

    dotnet add package AlibabaCloud.SDK.Green20220302 --version 2.2.10
  3. Integrasikan C# SDK.

    • Contoh integrasi API sinkron

      // This file is auto-generated, don't edit it. Thanks.
      
      using Newtonsoft.Json;
      
      namespace AlibabaCloud.SDK.Green20220302
      {
          public class OssScanDemo
          {
              public static void Main(string[] args)
              {
                  /**
                  * An Alibaba Cloud account's AccessKey has full permissions for all API operations. We recommend that you use a RAM user for API calls and routine O&M.
                  * We strongly recommend that you do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and threaten the security of all resources in your account.
                  * Common ways to get environment variables:
                  * Get the AccessKey ID of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID")
                  * Get the AccessKey secret of the RAM user: Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
                  */
                  String accessKeyId = "We recommend that you obtain the AccessKey ID of the RAM user from an environment variable";
                  String accessKeySecret = "We recommend that you obtain the AccessKey secret of the RAM user from an environment variable";
                  // Modify the region and endpoint as needed.
                  String endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
                  // Note: Reuse the instantiated client as much as possible to avoid repeated connection establishment and improve detection performance.
                  Client client = createClient(accessKeyId, accessKeySecret, endpoint);
      
                  // Set runtime parameters. This is valid only for requests that use this runtime parameter instance.
                  AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions =
                      new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
      
                  // Construct an image detection request.
                  Models.ImageModerationRequest imageModerationRequest =
                      new Models.ImageModerationRequest();
                  // Image moderation service: The serviceCode configured in the Content Moderation console for the Image Moderation Pro rule. Example: baselineCheck_global
                  imageModerationRequest.Service = "baselineCheck_global";
                  Dictionary<string, object> task = new Dictionary<string, object>();
                  // The region where the bucket of the image to be detected is located. Example: ap-southeast-1
                  task.Add("ossRegionId", "ap-southeast-1");
                  // The name of the bucket where the image to be detected is located. Example: bucket001
                  task.Add("ossBucketName", "bucket001");
                  // The name of the object of the image to be detected. Example: image/001.jpg
                  task.Add("ossObjectName", "image/001.jpg");
                  // The ID of the data to be detected.
                  task.Add("dataId", Guid.NewGuid().ToString());
                  imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
                  try
                  {
                      // Call the API operation to get the detection results.
                      Models.ImageModerationResponse response = client.ImageModerationWithOptions(
                          imageModerationRequest,
                          runtimeOptions
                      );
      
                      Console.WriteLine(response.Body.RequestId);
                      Console.WriteLine(JsonConvert.SerializeObject(response.Body));
                  }
                  catch (Exception _err)
                  {
                      Console.WriteLine(_err);
                  }
              }
      
              // Create a request client.
              public static Client createClient(
                  String accessKeyId,
                  String accessKeySecret,
                  String endpoint
              )
              {
                  AlibabaCloud.OpenApiClient.Models.Config config =
                      new AlibabaCloud.OpenApiClient.Models.Config
                      {
                          AccessKeyId = accessKeyId,
                          AccessKeySecret = accessKeySecret,
                          // Set the HTTP proxy.
                          // HttpProxy = "http://10.10.xx.xx:xxxx",
                          // Set the HTTPS proxy.
                          // HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                          // The domain name to access.
                          Endpoint = endpoint,
                      };
                  return new Client(config);
              }
          }
      }

Panggilan native HTTPS

Layanan API Content Moderation Versi 2.0 juga mendukung panggilan HTTPS native. Metode ini mengharuskan Anda menangani penandatanganan dan verifikasi permintaan secara manual, serta merakit permintaan, termasuk URL, body, header, dan parameter. Panggilan HTTPS native biasanya hanya diperlukan dalam dua skenario berikut. Jika kasus penggunaan Anda bukan salah satu dari dua skenario ini, kami menyarankan Anda menggunakan SDK untuk melakukan panggilan.

  1. Penggunaan langsung dalam aplikasi dengan persyaratan tinggi terhadap ukuran klien.

  2. Ketergantungan khusus pada paket library tertentu yang tidak nyaman untuk ditingkatkan.

  • Calling method

    Titik akhir permintaan layanan: https://green-cip.{region}.aliyuncs.com

    Protokol: HTTPS

    Metode: POST

  • Common request parameters

    Parameter permintaan untuk operasi API Image Moderation V2.0 terdiri dari parameter permintaan umum dan parameter permintaan spesifik API. Parameter permintaan umum diperlukan untuk semua operasi API. Tabel berikut menjelaskan parameter permintaan umum tersebut.

    Nama

    Type

    Wajib

    Deskripsi

    Format

    String

    Ya

    Format pesan respons. Nilai yang valid:

    • JSON (default)

    • XML

    Version

    String

    Ya

    Nomor versi API, dalam format YYYY-MM-DD. Versi ini adalah 2022-03-02.

    AccessKeyId

    String

    Ya

    ID AccessKey yang dikeluarkan oleh Alibaba Cloud untuk mengakses layanan.

    Signature

    String

    Ya

    String tanda tangan. Untuk informasi tentang cara menghitung tanda tangan, lihat metode tanda tangan di bawah.

    SignatureMethod

    String

    Ya

    Metode penandatanganan. Saat ini mendukung HMAC-SHA1.

    Timestamp

    String

    Ya

    Stempel waktu permintaan. Format tanggal harus mengikuti standar ISO 8601 dan dalam UTC. Formatnya adalah yyyy-MM-ddTHH:mm:ssZ. Misalnya, 09:13:14 pada 12 Desember 2022 (UTC+8) direpresentasikan sebagai 2022-12-12T01:13:14Z.

    SignatureVersion

    String

    Ya

    Versi algoritma tanda tangan. Nilainya adalah 1.0.

    SignatureNonce

    String

    Ya

    Bilangan acak unik yang digunakan untuk mencegah serangan replay jaringan. Permintaan berbeda harus menggunakan nilai acak yang berbeda.

    Action

    String

    Ya

    • API citra sinkron: ImageModeration

    • API citra asinkron: ImageAsyncModeration

    • API untuk mendapatkan hasil moderasi citra asinkron: DescribeImageModerationResult

    • API citra sinkron multi-layanan: ImageBatchModeration

  • Common response parameters

    Untuk setiap panggilan API yang Anda kirimkan, sistem mengembalikan pengidentifikasi unik, RequestId, terlepas dari apakah panggilan tersebut berhasil atau tidak. Parameter respons lainnya mencakup label dan skor kepercayaan. Parameter yang dikembalikan bervariasi tergantung layanan. Untuk informasi selengkapnya, lihat dokumentasi layanan spesifik.

    Catatan

    Untuk informasi selengkapnya tentang nilai dan deskripsi field Label yang dikembalikan oleh operasi API ini, lihat Tabel Deskripsi Label Risiko.

  • Code example

    Contoh respons berikut diformat agar mudah dibaca. Respons aktual tidak diformat dengan jeda baris atau indentasi.

    Berikut adalah contoh permintaan untuk Image Moderation V2.0 - API Sinkron Deteksi Garis Dasar Umum. Untuk operasi API lainnya, lihat dokumentasi API spesifik untuk parameter permintaan bisnis:

    https://green-cip.ap-southeast-1.aliyuncs.com/ 
        ?Format=JSON
        &Version=2022-03-02
        &Signature=vpEEL0zFHfxXYzSFV0n7%2FZiFL9o%3D
        &SignatureMethod=Hmac-SHA1
        &SignatureNonce=15215528852396
        &SignatureVersion=1.0
        &Action=ImageModeration
        &AccessKeyId=123****cip
        &Timestamp=2022-12-12T12:00:00Z
        &Service=baselineCheck_global
        &ServiceParameters={"imageUrl": "https://img.alicdn.com/tfs/TB1U4r9AeH2gK0jSZJnXXaT1FXa-2880-480.png",
        "dataId": "img1234567"}

    Berikut adalah contoh kode JSON dari parameter yang dikembalikan untuk Image Moderation Versi 2.0 - API sinkron Deteksi Garis Dasar Umum:

    {
        "Msg": "OK",
        "Code": 200,
        "Data": {
            "DataId": "uimg123****",
            "Result": [
                {
                    "Label": "pornographic_adultContent",
                    "Confidence": 81.3
                },
                {
                    "Label": "sexual_partialNudity",
                    "Confidence": 98.9
                }
            ]
        },
        "RequestId": "ABCD1234-1234-1234-1234-1234XYZ"
    }
  • Signature method

    Layanan Image Moderation V2.0 mengotentikasi setiap permintaan. Oleh karena itu, setiap permintaan harus menyertakan tanda tangan. Layanan Image Moderation V2.0 memverifikasi identitas pengirim menggunakan enkripsi simetris dengan ID AccessKey dan rahasia AccessKey.

    ID AccessKey dan rahasia AccessKey dikeluarkan oleh Alibaba Cloud. Anda dapat mengajukan dan mengelolanya di situs web Alibaba Cloud. ID AccessKey digunakan untuk mengidentifikasi Anda. Rahasia AccessKey adalah kunci yang digunakan untuk mengenkripsi string tanda tangan dan untuk verifikasi sisi server terhadap string tanda tangan. Kunci ini harus dirahasiakan sepenuhnya.

    Untuk mengakses layanan, tandatangani permintaan menggunakan metode berikut:

    1. Buat string kueri terkanonisasi dari parameter permintaan.

      1. Urutkan semua parameter permintaan (termasuk parameter permintaan umum dan parameter permintaan spesifik API, tetapi tidak termasuk parameter Signature) secara alfabet berdasarkan nama mereka.

      2. Encode nama dan nilai parameter permintaan. Nama dan nilai harus di-encode URL menggunakan set karakter UTF-8.

        Catatan

        Pustaka yang mendukung encoding URL, seperti java.net.URLEncoder di Java, biasanya melakukan encoding berdasarkan aturan tipe MIME application/x-www-form-urlencoded. Anda dapat menggunakan metode ini untuk encoding. Ganti tanda plus (+) dalam string yang di-encode dengan %20, tanda bintang (*) dengan %2A, dan %7E dengan tilde (~) untuk mendapatkan string yang di-encode sesuai aturan yang dijelaskan sebelumnya.

        Aturan encoding URL adalah sebagai berikut:

        • Karakter A-Z, a-z, 0-9, dan karakter tanda hubung (-), garis bawah (_), titik (.), dan tilde (~) tidak di-encode.

        • Karakter lain di-encode dalam format %XY, di mana XY adalah representasi heksadesimal dari kode ASCII karakter tersebut. Misalnya, tanda kutip ganda Inggris (") di-encode sebagai %22.

        • Karakter UTF-8 yang diperluas di-encode dalam format %XY%ZA….

        • Perhatikan bahwa spasi Inggris ( ) harus di-encode sebagai %20, bukan tanda plus (+).

      3. Hubungkan nama dan nilai parameter yang di-encode dengan tanda sama dengan (=).

      4. Hubungkan string yang digabungkan dengan tanda sama dengan dalam urutan alfabet nama parameter menggunakan tanda ampersand (&) untuk mendapatkan string kueri terkanonisasi.

    2. Buat string untuk ditandatangani dari string ternormalisasi pada langkah a.i berdasarkan aturan berikut.

      StringToSign=
      HTTPMethod + "&" +
      percentEncode("/") + "&" +
      percentEncode(CanonicalizedQueryString)
      Catatan

      Dalam format ini, HTTPMethod adalah metode HTTP yang digunakan untuk mengirimkan permintaan, seperti POST. percentEncode(/) adalah nilai yang diperoleh dengan meng-encode karakter (/) berdasarkan aturan encoding URL yang dijelaskan pada langkah sebelumnya, yaitu %2F. percentEncode(CanonicalizedQueryString) adalah string yang diperoleh dengan meng-encode string kueri terkanonisasi dari langkah sebelumnya berdasarkan aturan encoding URL yang sama.

    3. Seperti yang didefinisikan dalam RFC 2104, gunakan string untuk menandatangani untuk menghitung nilai tanda tangan HMAC.

      Catatan

      Kunci yang digunakan untuk perhitungan tanda tangan adalah rahasia AccessKey Anda yang ditambahkan dengan karakter ampersand (&) (kode ASCII 38). Algoritma hash adalah SHA1.

    4. Encode nilai HMAC menjadi string berdasarkan aturan encoding Base64 untuk mendapatkan nilai tanda tangan (Signature).

    5. Tambahkan nilai tanda tangan sebagai parameter Signature ke parameter permintaan.

      Catatan

      Ketika nilai tanda tangan dikirimkan ke server Content Moderation sebagai parameter permintaan akhir, nilai tersebut harus di-encode URL berdasarkan aturan RFC 3986, mirip dengan parameter lainnya.