Todos os produtos
Search
Central de documentação

AI Guardrails:Image Moderation 2.0 SDK e guia de integração

Última atualização: Jul 04, 2026

Este guia orienta você na ativação do Image Moderation 2.0, na configuração de credenciais e na execução da sua primeira chamada de moderação. Dois métodos de integração são suportados: SDK (recomendado) e HTTPS nativo. Sempre que possível, utilize um SDK, pois ele gerencia automaticamente a autenticação por assinatura e a formatação das requisições.

Pré-requisitos

Antes de começar, certifique-se de ter:

  • Uma conta Alibaba Cloud com permissões suficientes para criar usuários RAM e ativar serviços

Etapa 1: Ativar o serviço

Acesse a página Activate Service e ative o Image Moderation 2.0.

O método de faturamento padrão é pagamento conforme o uso — as cobranças são liquidadas diariamente com base no uso real. Se nenhuma chamada de API for realizada, não haverá cobrança. Para detalhes sobre preços, consulte Detalhes de faturamento.

Etapa 2: Criar um usuário RAM e conceder permissões

  1. Faça login no RAM console com sua conta Alibaba Cloud ou um usuário RAM administrador.

  2. Crie um usuário RAM: selecione OpenAPI Access como tipo de acesso e anote o par de AccessKey gerado. Consulte Criar um usuário RAM.

  3. Conceda a política de sistema AliyunYundunGreenWebFullAccess ao usuário RAM. Consulte Conceder permissões a um usuário RAM.

Etapa 3: Configurar credenciais

Armazene seu par de AccessKey como variáveis de ambiente para que seu código possa lê-las sem codificar segredos diretamente.

Linux / macOS

export ALIBABA_CLOUD_ACCESS_KEY_ID=<your-access-key-id>
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<your-access-key-secret>

Windows (Prompt de Comando)

set ALIBABA_CLOUD_ACCESS_KEY_ID=<your-access-key-id>
set ALIBABA_CLOUD_ACCESS_KEY_SECRET=<your-access-key-secret>

Substitua <your-access-key-id> e <your-access-key-secret> pelos valores obtidos na Etapa 2.

Para outras opções de configuração de credenciais, consulte Configurar credenciais.

Etapa 4: Instalar e chamar o SDK

Regiões suportadas

Região

Endpoint público

Endpoint VPC

Códigos de serviço suportados

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

China (Hong Kong)

green-cip.cn-hongkong.aliyuncs.com

green-cip-vpc.cn-hongkong.aliyuncs.com

postImageCheckByVL_cb, postImageCheckByVL_global

Reino Unido (Londres)

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

Nenhum

EUA (Virgínia)

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

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

baselineCheck_global, aigcDetector_global

EUA (Vale do Silício)

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

Nenhum

Alemanha (Frankfurt)

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

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

Para códigos de exemplo do SDK em outras linguagens, utilize o Portal do Desenvolvedor OpenAPI para depurar operações de API — ele gera automaticamente códigos de exemplo para cada linguagem.

Escolher a origem da imagem

Os parâmetros a serem passados dependem do local onde suas imagens estão armazenadas:

Origem da imagem

Ação necessária

URL acessível publicamente

Passe a URL diretamente na requisição

Arquivo local (sem URL pública)

Faça upload primeiro para o bucket OSS do Content Moderation e depois passe a referência do objeto OSS

Arquivo já existente em seu bucket OSS

Conceda acesso ao Content Moderation para o seu bucket e passe a referência do objeto OSS

Entender a resposta

Toda chamada de moderação bem-sucedida retorna um array Result com um ou mais rótulos. Cada rótulo possui dois campos:

Campo

Descrição

Label

Categoria de risco detectada (ex.: pornographic_adultContent, sexual_partialNudity). Consulte Descrições dos rótulos de risco para a lista completa.

Confidence

Valor float entre 0 e 100 indicando a confiança no rótulo. Valores mais altos indicam maior certeza.

Exemplo de resposta:

{
  "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"
}

Java SDK

Requisitos: Java 1.8 ou superior

Código-fonte: Java SDK no GitHub

Detectar imagens acessíveis publicamente

Imagens acessíveis via URL pública podem ser enviadas diretamente à API.

  1. Adicione a dependência ao seu arquivo pom.xml:

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>green20220302</artifactId>
      <version>3.3.3</version>
    </dependency>
  2. Chame a API:

Detectar imagens locais

Imagens locais sem URL pública devem ser enviadas para o bucket do OSS do Content Moderation antes da detecção. O serviço recupera a imagem do OSS para realizar a moderação.

  1. Adicione ambas as dependências ao seu arquivo pom.xml:

    <!-- Content Moderation SDK -->
    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>green20220302</artifactId>
      <version>3.3.3</version>
    </dependency>
    <!-- OSS SDK -->
    <dependency>
      <groupId>com.aliyun.oss</groupId>
      <artifactId>aliyun-sdk-oss</artifactId>
      <version>3.16.3</version>
    </dependency>
  2. Chame a API:

    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 {
    
        // Set to true when running in a VPC environment.
        public static boolean isVPC = false;
    
        // Cache upload tokens by endpoint to avoid fetching a new token for every request.
        public static Map<String, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData> tokenMap = new HashMap<>();
    
        public static OSS ossClient = null;
    
        public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
            Config config = new Config();
            config.setAccessKeyId(accessKeyId);
            config.setAccessKeySecret(accessKeySecret);
            config.setEndpoint(endpoint);
            return new Client(config);
        }
    
        public static void getOssClient(DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData, boolean isVPC) {
            // Reuse the OSS client across requests.
            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());
            }
        }
    
        public static String uploadFile(String filePath, DescribeUploadTokenResponseBody.DescribeUploadTokenResponseBodyData tokenData) throws Exception {
            String[] split = filePath.split("\\.");
            String objectName = split.length > 1
                ? tokenData.getFileNamePrefix() + UUID.randomUUID() + "." + split[split.length - 1]
                : 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 {
            // Reuse the client across requests.
            Client client = createClient(accessKeyId, accessKeySecret, endpoint);
            RuntimeOptions runtime = new RuntimeOptions();
    
            // Replace with the actual path to your local file.
            String filePath = "D:\\localPath\\exampleFile.png";
    
            // Fetch and cache the upload token; refresh it when it expires.
            if (tokenMap.get(endpoint) == null || tokenMap.get(endpoint).expiration <= System.currentTimeMillis() / 1000) {
                DescribeUploadTokenResponse tokenResponse = client.describeUploadToken();
                tokenMap.put(endpoint, tokenResponse.getBody().getData());
            }
            getOssClient(tokenMap.get(endpoint), isVPC);
    
            String objectName = uploadFile(filePath, tokenMap.get(endpoint));
    
            Map<String, String> serviceParameters = new HashMap<>();
            serviceParameters.put("ossBucketName", tokenMap.get(endpoint).getBucketName());
            serviceParameters.put("ossObjectName", objectName);
            serviceParameters.put("dataId", UUID.randomUUID().toString());
    
            ImageModerationRequest request = new ImageModerationRequest();
            request.setService("baselineCheck_global");
            request.setServiceParameters(JSON.toJSONString(serviceParameters));
    
            try {
                return client.imageModerationWithOptions(request, runtime);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    
        public static void main(String[] args) throws Exception {
            String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
            String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
            ImageModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com");
    
            if (response != null && response.getStatusCode() == 200) {
                ImageModerationResponseBody body = response.getBody();
                System.out.println("requestId=" + body.getRequestId());
                if (body.getCode() == 200) {
                    ImageModerationResponseBodyData data = body.getData();
                    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("Moderation failed. code=" + body.getCode());
                }
            }
        }
    }

Detectar imagens do OSS

Imagens já armazenadas no seu bucket do OSS podem ser moderadas diretamente, sem necessidade de novo envio. Primeiro, conceda acesso ao Content Moderation no seu bucket criando a função de serviço AliyunCIPScanOSSRole.

  1. Faça login com sua conta Alibaba Cloud (conta raiz) e acesse a página de Autorização de Acesso a Recursos na Nuvem para conceder a permissão.

  2. Adicione a dependência ao seu arquivo pom.xml:

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>green20220302</artifactId>
      <version>3.3.3</version>
    </dependency>
  3. Chame a API:

    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 {
    
        public static Client createClient(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
            Config config = new Config();
            config.setAccessKeyId(accessKeyId);
            config.setAccessKeySecret(accessKeySecret);
            // Optional: set HTTP/HTTPS proxy if needed
            // config.setHttpProxy("http://10.10.xx.xx:xxxx");
            // config.setHttpsProxy("https://10.10.xx.xx:xxxx");
            config.setEndpoint(endpoint);
            return new Client(config);
        }
    
        public static ImageModerationResponse invokeFunction(String accessKeyId, String accessKeySecret, String endpoint) throws Exception {
            Client client = createClient(accessKeyId, accessKeySecret, endpoint);
            RuntimeOptions runtime = new RuntimeOptions();
    
            Map<String, String> serviceParameters = new HashMap<>();
            serviceParameters.put("dataId", UUID.randomUUID().toString());
            serviceParameters.put("ossRegionId", "ap-southeast-1");   // region where the bucket is located
            serviceParameters.put("ossBucketName", "bucket001");       // your OSS bucket name
            serviceParameters.put("ossObjectName", "image/001.jpg");   // object path in the bucket
    
            ImageModerationRequest request = new ImageModerationRequest();
            request.setService("baselineCheck_global");
            request.setServiceParameters(JSON.toJSONString(serviceParameters));
    
            try {
                return client.imageModerationWithOptions(request, runtime);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    
        public static void main(String[] args) throws Exception {
            String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
            String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
            ImageModerationResponse response = invokeFunction(accessKeyId, accessKeySecret, "green-cip.ap-southeast-1.aliyuncs.com");
    
            if (response != null && response.getStatusCode() == 200) {
                ImageModerationResponseBody body = response.getBody();
                System.out.println("requestId=" + body.getRequestId());
                if (body.getCode() == 200) {
                    ImageModerationResponseBodyData data = body.getData();
                    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("Moderation failed. code=" + body.getCode());
                }
            }
        }
    }

Python SDK

Requisitos: Python 3.6 ou superior

Código-fonte: SDK do Python no PyPI

Detectar imagens acessíveis publicamente

  1. Instale o SDK:

    pip install alibabacloud_green20220302==3.2.4
  2. Chame a API:

    # coding=utf-8
    
    import json
    import os
    import uuid
    
    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
    
    def create_client(access_key_id, access_key_secret, endpoint):
        config = Config(
            access_key_id=access_key_id,
            access_key_secret=access_key_secret,
            # Optional: set HTTP/HTTPS proxy if needed
            # http_proxy='http://10.10.xx.xx:xxxx',
            # https_proxy='https://10.10.xx.xx:xxxx',
            endpoint=endpoint
        )
        return Client(config)
    
    def invoke_function(access_key_id, access_key_secret, endpoint):
        # Reuse the client across requests.
        client = create_client(access_key_id, access_key_secret, endpoint)
        runtime = util_models.RuntimeOptions()
    
        service_parameters = {
            'imageUrl': 'https://img.alicdn.com/tfs/xxxxxxxxxx001.png',  # public URL
            'dataId': str(uuid.uuid1())
        }
    
        image_moderation_request = models.ImageModerationRequest(
            # Set the service code configured in the AI Guardrails console.
            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__':
        # Read credentials from environment variables — do not hardcode them.
        access_key_id = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
        access_key_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        # Change the endpoint to match your region.
        response = invoke_function(access_key_id, access_key_secret, 'green-cip.ap-southeast-1.aliyuncs.com')
    
        if response is not None and response.status_code == 200:
            result = response.body
            if result.code == 200:
                result_data = result.data
                print('result:', result_data)
            else:
                print('Moderation failed. status:', response.status_code)

Detectar imagens locais

  1. Instale ambos os SDKs:

    pip install alibabacloud_green20220302==3.2.4
    pip install oss2
  2. Chame a API:

    import json
    import os
    import time
    import uuid
    
    import oss2
    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
    
    # Set to True when running in a VPC environment.
    is_vpc = False
    # Cache upload tokens by endpoint to avoid fetching a new token for every request.
    token_dict = dict()
    bucket = None
    
    def create_client(access_key_id, access_key_secret, endpoint):
        config = Config(
            access_key_id=access_key_id,
            access_key_secret=access_key_secret,
            endpoint=endpoint
        )
        return Client(config)
    
    def create_oss_bucket(is_vpc, upload_token):
        global bucket
        auth = oss2.StsAuth(upload_token.access_key_id, upload_token.access_key_secret, upload_token.security_token)
        end_point = upload_token.oss_internal_end_point if is_vpc else upload_token.oss_internet_end_point
        # Reuse the bucket client across requests.
        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):
        client = create_client(access_key_id, access_key_secret, endpoint)
        runtime = util_models.RuntimeOptions()
    
        # Replace with the actual path to your local file.
        file_path = 'D:\\localPath\\exampleFile.png'
    
        # Fetch and cache the upload token; refresh it when it expires.
        upload_token = token_dict.setdefault(endpoint, None)
        if upload_token is None or int(upload_token.expiration) <= int(time.time()):
            response = client.describe_upload_token()
            upload_token = response.body.data
            token_dict[endpoint] = upload_token
    
        object_name = upload_file(file_path, upload_token)
    
        service_parameters = {
            'ossBucketName': upload_token.bucket_name,
            'ossObjectName': object_name,
            'dataId': str(uuid.uuid1())
        }
    
        image_moderation_request = models.ImageModerationRequest(
            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__':
        access_key_id = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
        access_key_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        response = invoke_function(access_key_id, access_key_secret, 'green-cip.ap-southeast-1.aliyuncs.com')
    
        if response is not None and response.status_code == 200:
            result = response.body
            if result.code == 200:
                print('result:', result.data)
            else:
                print('Moderation failed. status:', response.status_code)

Detectar imagens do OSS

  1. Conceda acesso ao Content Moderation no seu bucket do OSS: faça login com sua conta Alibaba Cloud (conta raiz) e acesse a página de Autorização de Acesso a Recursos na Nuvem para criar a função de serviço AliyunCIPScanOSSRole.

  2. Instale o SDK:

    pip install alibabacloud_green20220302==3.2.4
  3. Chame a API:

    import json
    import os
    import uuid
    
    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
    
    def create_client(access_key_id, access_key_secret, endpoint):
        config = Config(
            access_key_id=access_key_id,
            access_key_secret=access_key_secret,
            endpoint=endpoint
        )
        return Client(config)
    
    def invoke_function(access_key_id, access_key_secret, endpoint):
        client = create_client(access_key_id, access_key_secret, endpoint)
        runtime = util_models.RuntimeOptions()
    
        service_parameters = {
            'ossRegionId': 'ap-southeast-1',   # region where the bucket is located
            'ossBucketName': 'bucket001',       # your OSS bucket name
            'ossObjectName': 'image/001.jpg',   # object path in the bucket
            'dataId': str(uuid.uuid1())
        }
    
        image_moderation_request = models.ImageModerationRequest(
            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__':
        access_key_id = os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID']
        access_key_secret = os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET']
        response = invoke_function(access_key_id, access_key_secret, 'green-cip.ap-southeast-1.aliyuncs.com')
    
        if response is not None and response.status_code == 200:
            result = response.body
            if result.code == 200:
                print('result:', result.data)
            else:
                print('Moderation failed. status:', response.status_code)

PHP SDK

Requisitos: PHP 5.6 ou superior

Código-fonte: SDK do PHP no Packagist

Detectar imagens acessíveis publicamente

  1. Instale o SDK:

    composer require alibabacloud/green-20220302 3.2.4
  2. Chame a API:

Detectar imagens locais

  1. Instale ambos os SDKs:

    composer require alibabacloud/green-20220302 3.2.4
    composer require aliyuncs/oss-sdk-php
  2. Chame a API:

    <?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 OSS\OssClient;
    
    // Set to true when running in a VPC environment.
    $isVPC = false;
    // Cache upload tokens by endpoint.
    $tokenArray = array();
    $ossClient = null;
    
    function create_client($accessKeyId, $accessKeySecret, $endpoint): Green
    {
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret,
            "endpoint" => $endpoint,
        ]);
        return new Green($config);
    }
    
    function create_upload_client($tokenData): void
    {
        global $isVPC, $ossClient;
        // Reuse the OSS client across requests.
        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);
        }
    }
    
    function upload_file($filePath, $tokenData): string
    {
        global $ossClient;
        create_upload_client($tokenData);
        $split = explode(".", $filePath);
        $objectName = count($split) > 1
            ? $tokenData->fileNamePrefix . uniqid() . "." . end($split)
            : $tokenData->fileNamePrefix . uniqid();
        $ossClient->uploadFile($tokenData->bucketName, $objectName, $filePath);
        return $objectName;
    }
    
    function invoke($accessKeyId, $accessKeySecret, $endpoint): ImageModerationResponse
    {
        global $tokenArray;
        $client = create_client($accessKeyId, $accessKeySecret, $endpoint);
        $runtime = new RuntimeOptions([]);
    
        // Replace with the actual path to your local file.
        $filePath = "D:\\localPath\\exampleFile.png";
    
        // Fetch and cache the upload token; refresh it when it expires.
        if (!isset($tokenArray[$endpoint]) || $tokenArray[$endpoint]->expiration <= time()) {
            $token = $client->describeUploadToken();
            $tokenArray[$endpoint] = $token->body->data;
        }
    
        $objectName = upload_file($filePath, $tokenArray[$endpoint]);
    
        $request = new ImageModerationRequest();
        $request->service = "baselineCheck_global";
        $serviceParameters = array(
            'ossObjectName' => $objectName,
            'ossBucketName' => $tokenArray[$endpoint]->bucketName,
            'dataId' => uniqid()
        );
        $request->serviceParameters = json_encode($serviceParameters);
        return $client->imageModerationWithOptions($request, $runtime);
    }
    
    $accessKeyId = getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    $accessKeySecret = getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    $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());
    }

Detectar imagens do OSS

  1. Conceda acesso ao Content Moderation para o seu bucket do OSS: faça login com sua conta Alibaba Cloud (conta raiz) e acesse a página de Autorização de Acesso a Recursos na Nuvem para criar a função de serviço AliyunCIPScanOSSRole.

  2. Instale o SDK:

    composer require alibabacloud/green-20220302 3.2.4
  3. Chame a API:

Go SDK

Código-fonte: Go SDK no GitHub

Detectar imagens publicamente acessíveis

  1. Instale o SDK:

    go get github.com/alibabacloud-go/green-20220302/v3@v3.2.4
  2. Chame a API:

Detectar imagens locais

  1. Instale ambos os SDKs:

    go get github.com/alibabacloud-go/green-20220302/v3
    go get github.com/aliyun/aliyun-oss-go-sdk/oss
  2. Chame a API:

    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"
    )
    
    // Cache upload tokens by endpoint.
    var TokenMap = make(map[string]*green20220302.DescribeUploadTokenResponseBodyData)
    
    // Set to true when running in a VPC environment.
    var isVPC = false
    var Bucket *oss.Bucket
    
    func createClient(accessKeyId string, accessKeySecret string, endpoint string) (*green20220302.Client, error) {
        config := &openapi.Config{
            AccessKeyId:     tea.String(accessKeyId),
            AccessKeySecret: tea.String(accessKeySecret),
            Endpoint:        tea.String(endpoint),
        }
        return green20220302.NewClient(config)
    }
    
    func createOssClient(tokenData *green20220302.DescribeUploadTokenResponseBodyData) {
        var endPoint string
        if isVPC {
            endPoint = tea.StringValue(tokenData.OssInternalEndPoint)
        } else {
            endPoint = tea.StringValue(tokenData.OssInternetEndPoint)
        }
        ossClient, err := oss.New(endPoint, 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))
    }
    
    func uploadFile(filePath string, tokenData *green20220302.DescribeUploadTokenResponseBodyData) (string, error) {
        createOssClient(tokenData)
        objectName := tea.StringValue(tokenData.FileNamePrefix) + uuid.New().String() + "." + strings.Split(filePath, ".")[1]
        _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) {
        client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
        if _err != nil {
            return nil, _err
        }
        runtime := &util.RuntimeOptions{}
    
        // Replace with the actual path to your local file.
        var filePath = "D:\\localPath\\exampleFile.png"
    
        // Fetch and cache the upload token; refresh it when it expires.
        tokenData, ok := TokenMap[endpoint]
        if !ok || tea.Int32Value(tokenData.Expiration) <= int32(time.Now().Unix()) {
            uploadTokenResponse, _err := client.DescribeUploadToken()
            if _err != nil {
                return nil, _err
            }
            tokenData = uploadTokenResponse.Body.Data
            TokenMap[endpoint] = tokenData
        }
    
        objectName, _ := uploadFile(filePath, TokenMap[endpoint])
    
        serviceParameters, _ := json.Marshal(
            map[string]interface{}{
                "ossBucketName": tea.StringValue(TokenMap[endpoint].BucketName),
                "ossObjectName": objectName,
                "dataId":        uuid.New().String(),
            },
        )
        imageModerationRequest := &green20220302.ImageModerationRequest{
            Service:           tea.String("baselineCheck_global"),
            ServiceParameters: tea.String(string(serviceParameters)),
        }
    
        return client.ImageModerationWithOptions(imageModerationRequest, runtime)
    }
    
    func main() {
        accessKeyId := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")
        accessKeySecret := os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
        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
            fmt.Println("requestId:" + tea.StringValue(body.RequestId))
            if statusCode == http.StatusOK {
                if tea.IntValue(tea.ToInt(body.Code)) == 200 {
                    result := body.Data.Result
                    for i := 0; i < len(result); i++ {
                        fmt.Println("label:" + tea.StringValue(result[i].Label))
                        fmt.Println("confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence)))
                    }
                } else {
                    fmt.Println("Moderation failed. code:", body.Code)
                }
            } else {
                fmt.Println("Request failed. status:", statusCode, "error:", _err)
            }
        }
    }

Detectar imagens do OSS

  1. Conceda acesso do Content Moderation ao seu bucket do OSS: faça login com sua conta Alibaba Cloud (conta raiz) e acesse a página de Autorização de Acesso a Recursos na Nuvem para criar a função de serviço AliyunCIPScanOSSRole.

  2. Instale o SDK:

    go get github.com/alibabacloud-go/green-20220302/v3
  3. Chame a API:

    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"
    )
    
    func createClient(accessKeyId *string, accessKeySecret *string, endpoint *string) (*green20220302.Client, error) {
        config := &openapi.Config{
            AccessKeyId:     accessKeyId,
            AccessKeySecret: accessKeySecret,
            Endpoint:        endpoint,
        }
        return green20220302.NewClient(config)
    }
    
    func invoke(accessKeyId *string, accessKeySecret *string, endpoint *string) (_result *green20220302.ImageModerationResponse, _err error) {
        client, _err := createClient(accessKeyId, accessKeySecret, endpoint)
        if _err != nil {
            return nil, _err
        }
        runtime := &util.RuntimeOptions{}
    
        serviceParameters, _ := json.Marshal(
            map[string]interface{}{
                "ossRegionId":  "ap-southeast-1",  // region where the bucket is located
                "ossBucketName": "bucket001",       // your OSS bucket name
                "ossObjectName": "image/001.jpg",   // object path in the bucket
                "dataId":        uuid.New().String(),
            },
        )
        imageModerationRequest := &green20220302.ImageModerationRequest{
            Service:           tea.String("baselineCheck_global"),
            ServiceParameters: tea.String(string(serviceParameters)),
        }
    
        return client.ImageModerationWithOptions(imageModerationRequest, runtime)
    }
    
    func main() {
        accessKeyId := tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
        accessKeySecret := tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
        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
            fmt.Println("requestId:" + tea.StringValue(body.RequestId))
            if statusCode == http.StatusOK {
                if tea.IntValue(tea.ToInt(body.Code)) == 200 {
                    result := body.Data.Result
                    for i := 0; i < len(result); i++ {
                        fmt.Println("label:" + tea.StringValue(result[i].Label))
                        fmt.Println("confidence:" + tea.ToString(tea.Float32Value(result[i].Confidence)))
                    }
                } else {
                    fmt.Println("Moderation failed. code:", body.Code)
                }
            } else {
                fmt.Println("Request failed. status:", statusCode, "error:", _err)
            }
        }
    }

Node.js SDK

Código-fonte: Node.js SDK no npm

Detectar imagens acessíveis publicamente

  1. Instale o SDK:

    npm install @alicloud/green20220302@3.2.4
  2. Chame a API:

    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 AI Guardrails 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))
    });

Detectar imagens locais

  1. Instale ambas as dependências:

    npm install @alicloud/green20220302@3.2.4
    npm install ali-oss --save
  2. Chame a API:

    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 AI Guardrails 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();

Detectar imagens do OSS

  1. Conceda acesso do Content Moderation ao seu bucket do OSS: faça login com sua conta Alibaba Cloud (conta raiz) e acesse a página de Autorização de Acesso a Recursos na Nuvem para criar a função de serviço AliyunCIPScanOSSRole.

  2. Instale o SDK:

    npm install @alicloud/green20220302@3.2.4
  3. Chame a API:

    const RPCClient = require("@alicloud/pop-core");
    const { v4: uuidv4 } = require('uuid');
    
    async function main() {
        var client = new RPCClient({
            accessKeyId: process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'],
            accessKeySecret: process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'],
            endpoint: "https://green-cip.ap-southeast-1.aliyuncs.com",
            apiVersion: '2022-03-02',
        });
    
        var params = {
            "Service": "baselineCheck_global",
            "ServiceParameters": JSON.stringify({
                "ossRegionId": "ap-southeast-1",  // region where the bucket is located
                "ossBucketName": "bucket001",      // your OSS bucket name
                "ossObjectName": "image/001.jpg",  // object path in the bucket
                "dataId": uuidv4()
            })
        };
    
        var requestOption = { method: 'POST', formatParams: false };
    
        try {
            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

Código-fonte: C# SDK no NuGet

Detectar imagens acessíveis publicamente

  1. Instale o SDK:

    dotnet add package AlibabaCloud.SDK.Green20220302 --version 3.2.4
  2. Chame a API:

    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    
    namespace AlibabaCloud.SDK.Green20220302
    {
        public class ImageModerationAutoRoute
        {
            public static void Main(string[] args)
            {
                // Read credentials from environment variables — do not hardcode them.
                string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
                string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
                // Change the endpoint to match your region.
                string endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
    
                // Reuse the client across requests.
                Client client = createClient(accessKeyId, accessKeySecret, endpoint);
                AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    
                Models.ImageModerationRequest imageModerationRequest = new Models.ImageModerationRequest();
                // Set the service code configured in the AI Guardrails console.
                imageModerationRequest.Service = "baselineCheck_global";
                Dictionary<string, object> task = new Dictionary<string, object>();
                task.Add("imageUrl", "https://img.alicdn.com/tfs/xxxxxxxxxx001.png");  // public URL
                task.Add("dataId", Guid.NewGuid().ToString());
                imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
    
                try
                {
                    Models.ImageModerationResponse response = client.ImageModerationWithOptions(imageModerationRequest, runtimeOptions);
                    Console.WriteLine(response.Body.RequestId);
                    Console.WriteLine(JsonConvert.SerializeObject(response.Body));
                }
                catch (Exception err)
                {
                    Console.WriteLine(err);
                }
            }
    
            public static Client createClient(string accessKeyId, string accessKeySecret, string endpoint)
            {
                AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
                {
                    AccessKeyId = accessKeyId,
                    AccessKeySecret = accessKeySecret,
                    // Optional: set HTTP/HTTPS proxy if needed
                    // HttpProxy = "http://10.10.xx.xx:xxxx",
                    // HttpsProxy = "https://username:password@xxx.xxx.xxx.xxx:9999",
                    Endpoint = endpoint,
                };
                return new Client(config);
            }
        }
    }

Detectar imagens locais

Instale o SDK do Content Moderation e o SDK do OSS:

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

Para o SDK do OSS, instale via NuGet no Visual Studio:

  1. Abra Tools > NuGet Package Manager > Manage NuGet Packages for Solution.

  2. Pesquise por aliyun.oss.sdk.

  3. Selecione Aliyun.OSS.SDK (para .NET Framework) ou Aliyun.OSS.SDK.NetCore (para .NET Core) e clique em Install.

Em seguida, chame a API:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Aliyun.OSS;

namespace AlibabaCloud.SDK.Green20220302
{
    public class ImageModerationAutoRoute
    {
        // Cache upload tokens by endpoint.
        public static Dictionary<string, Models.DescribeUploadTokenResponse> tokenDic =
            new Dictionary<string, Models.DescribeUploadTokenResponse>();

        public static OssClient ossClient = null;

        // Set to true when running in a VPC environment.
        public static bool isVPC = false;

        public static void Main(string[] args)
        {
            string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
            string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
            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));
        }

        public static Client createClient(string accessKeyId, string accessKeySecret, string endpoint)
        {
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
            {
                AccessKeyId = accessKeyId,
                AccessKeySecret = accessKeySecret,
                Endpoint = endpoint,
            };
            return new Client(config);
        }

        private static OssClient getOssClient(Models.DescribeUploadTokenResponse tokenResponse, bool isVPC)
        {
            var tokenData = tokenResponse.Body.Data;
            return isVPC
                ? new OssClient(tokenData.OssInternalEndPoint, tokenData.AccessKeyId, tokenData.AccessKeySecret, tokenData.SecurityToken)
                : new OssClient(tokenData.OssInternetEndPoint, tokenData.AccessKeyId, tokenData.AccessKeySecret, tokenData.SecurityToken);
        }

        public static string uploadFile(string filePath, Models.DescribeUploadTokenResponse tokenResponse)
        {
            ossClient = getOssClient(tokenResponse, isVPC);
            var tokenData = tokenResponse.Body.Data;
            string objectName = tokenData.FileNamePrefix + Guid.NewGuid().ToString() + "." + filePath.Split(".").GetValue(1);
            ossClient.PutObject(tokenData.BucketName, objectName, filePath);
            return objectName;
        }

        public static Models.ImageModerationResponse invoke(string accessKeyId, string accessKeySecret, string endpoint)
        {
            // Reuse the client across requests.
            Client client = createClient(accessKeyId, accessKeySecret, endpoint);
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();

            // Replace with the actual path to your local file.
            string filePath = "D:\\localPath\\exampleFile.png";

            try
            {
                // Fetch and cache the upload token; refresh it when it expires.
                if (!tokenDic.ContainsKey(endpoint) || tokenDic[endpoint].Body.Data.Expiration <= DateTimeOffset.Now.ToUnixTimeSeconds())
                {
                    tokenDic[endpoint] = client.DescribeUploadToken();
                }

                string objectName = uploadFile(filePath, tokenDic[endpoint]);

                Models.ImageModerationRequest imageModerationRequest = new Models.ImageModerationRequest();
                imageModerationRequest.Service = "baselineCheck_global";
                Dictionary<string, object> task = new Dictionary<string, object>();
                task.Add("ossBucketName", tokenDic[endpoint].Body.Data.BucketName);
                task.Add("ossObjectName", objectName);
                task.Add("dataId", Guid.NewGuid().ToString());
                imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);

                return client.ImageModerationWithOptions(imageModerationRequest, runtimeOptions);
            }
            catch (Exception err)
            {
                Console.WriteLine(err);
                return null;
            }
        }
    }
}

Detectar imagens do OSS

  1. Conceda acesso do Content Moderation ao seu bucket do OSS: faça login com sua conta Alibaba Cloud (conta raiz) e acesse a página de Autorização de Acesso a Recursos na Nuvem para criar a função de serviço AliyunCIPScanOSSRole.

  2. Instale o SDK:

    dotnet add package AlibabaCloud.SDK.Green20220302 --version 3.2.4
  3. Chame a API:

    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    
    namespace AlibabaCloud.SDK.Green20220302
    {
        public class OssScanDemo
        {
            public static void Main(string[] args)
            {
                string accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID");
                string accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
                string endpoint = "green-cip.ap-southeast-1.aliyuncs.com";
    
                Client client = createClient(accessKeyId, accessKeySecret, endpoint);
                AlibabaCloud.TeaUtil.Models.RuntimeOptions runtimeOptions = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
    
                Models.ImageModerationRequest imageModerationRequest = new Models.ImageModerationRequest();
                imageModerationRequest.Service = "baselineCheck_global";
                Dictionary<string, object> task = new Dictionary<string, object>();
                task.Add("ossRegionId", "ap-southeast-1");  // region where the bucket is located
                task.Add("ossBucketName", "bucket001");      // your OSS bucket name
                task.Add("ossObjectName", "image/001.jpg");  // object path in the bucket
                task.Add("dataId", Guid.NewGuid().ToString());
                imageModerationRequest.ServiceParameters = JsonConvert.SerializeObject(task);
    
                try
                {
                    Models.ImageModerationResponse response = client.ImageModerationWithOptions(imageModerationRequest, runtimeOptions);
                    Console.WriteLine(response.Body.RequestId);
                    Console.WriteLine(JsonConvert.SerializeObject(response.Body));
                }
                catch (Exception err)
                {
                    Console.WriteLine(err);
                }
            }
    
            public static Client createClient(string accessKeyId, string accessKeySecret, string endpoint)
            {
                AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
                {
                    AccessKeyId = accessKeyId,
                    AccessKeySecret = accessKeySecret,
                    Endpoint = endpoint,
                };
                return new Client(config);
            }
        }
    }

Chamadas HTTPS nativas

Utilize chamadas HTTPS nativas apenas quando um SDK não for adequado ao seu ambiente:

  • Sua aplicação possui restrições rigorosas de tamanho nas dependências do cliente.

  • Você depende de versões específicas de bibliotecas que não podem ser atualizadas.

Ao usar HTTPS nativo, é necessário construir manualmente a URL da requisição, calcular a assinatura HMAC-SHA1 e montar todos os parâmetros da requisição.

Endpoint e protocolo

  • Endpoint: https://green-cip.{region}.aliyuncs.com

  • Protocolo: HTTPS

  • Método: POST

Parâmetros comuns da requisição

Toda requisição exige os seguintes parâmetros:

Parâmetro

Tipo

Obrigatório

Descrição

Format

String

Sim

Formato da resposta: JSON (padrão) ou XML

Version

String

Sim

Versão da API no formato AAAA-MM-DD. Valor: 2022-03-02

AccessKeyId

String

Sim

Seu AccessKey ID

Signature

String

Sim

String de assinatura HMAC-SHA1

SignatureMethod

String

Sim

Algoritmo de assinatura: HMAC-SHA1

Timestamp

String

Sim

Horário da requisição no formato UTC ISO 8601: yyyy-MM-ddTHH:mm:ssZ

SignatureVersion

String

Sim

Versão do algoritmo de assinatura: 1.0

SignatureNonce

String

Sim

Número aleatório único para evitar ataques de replay; utilize um valor diferente para cada requisição

Action

String

Sim

API a ser chamada: ImageModeration (síncrona), ImageModerationAsync (assíncrona)

Parâmetros comuns da resposta

Toda resposta inclui RequestId, independentemente do sucesso da chamada. O array Data.Result contém os campos Label e Confidence. Consulte o formato de resposta e descrições dos campos na seção do SDK acima.

Exemplo de requisição

O exemplo a seguir chama a API síncrona de detecção de linha de base:

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"}

Cálculo da assinatura

O Image Moderation 2.0 utiliza HMAC-SHA1 para autenticar todas as requisições.

Etapa 1: Construir a string de consulta canônica

  1. Ordene todos os parâmetros da requisição alfabeticamente pelo nome do parâmetro (excluindo Signature).

  2. Codifique cada nome e valor de parâmetro em URL usando UTF-8 e as seguintes regras:

    • Não codifique: A–Z, a–z, 0–9, hífen (-), sublinhado (_), ponto (.), til (~)

    • Codifique outros caracteres como %XY (ASCII hexadecimal)

    • Codifique espaços como %20, não como +; codifique * como %2A; substitua %7E por ~

    • Codifique caracteres UTF-8 estendidos como %XY%ZA…

    Bibliotecas padrão de codificação de URL (como java.net.URLEncoder ) seguem as regras do tipo MIME application/x-www-form-urlencoded . Após a codificação, substitua + por %20 , * por %2A e %7E por ~ .
  3. Conecte cada par nome-valor codificado com =.

  4. Una todos os pares em ordem alfabética com & para obter a string de consulta canônica.

Etapa 2: Construir a string a ser assinada

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

Onde percentEncode("/") é %2F e HTTPMethod é POST.

Etapa 3: Calcular o valor HMAC-SHA1

Conforme definido na RFC 2104, calcule o hash HMAC-SHA1 de StringToSign. A chave de assinatura é o seu AccessKey secret seguido por & (ASCII 38).

Etapa 4: Codificar o resultado

Codifique o valor HMAC-SHA1 em Base64 para obter a string Signature.

Etapa 5: Adicionar a assinatura à requisição

Anexe Signature como um parâmetro de consulta codificado em URL, seguindo as regras de codificação da RFC 3986.

Próximos passos