Yandex.Cloud
  • Services
  • Why Yandex.Cloud
  • Pricing
  • Documentation
  • Contact us
Get started
Yandex Vision
  • Getting started
  • Step-by-step instructions
    • All instructions
    • Text recognition
    • Assessing image quality
    • Image moderation
    • Face detection
    • Base64 encoding
  • Concepts
    • Overview
    • Text recognition
      • Overview
      • Template recognition
      • Supported languages
      • Current version restrictions
    • Image classification
      • Overview
      • Supported models
    • Face detection
    • Quotas and limits
  • Access management
  • Pricing policy
  • API reference
    • Authentication in the API
    • gRPC
      • Обзор
      • VisionService
    • REST
      • Handling errors
      • Troubleshooting
      • Overview
      • Vision
        • Overview
        • batchAnalyze
  • Questions and answers
  1. Step-by-step instructions
  2. Image moderation

Image moderation

  • Examples
    • Before getting started
    • Apply the moderation model
    • Ready-to-use function for sending requests in bash

Image classification is currently in the Preview stage.

To determine whether an image matches properties such as adult content, shocking content, or watermarks, use the Image Classification feature.

In the batchAnalyze method, set the type property to Classification, and in the configuration, specify the moderation.

Examples

Before getting started

To use the examples, install cURL and get the authorization data for your account:

User's account on Yandex
Service accounts
Federated account
  1. On the billing page, make sure that your billing account status is ACTIVE or TRIAL_ACTIVE. If you don't have a billing account, create one.
  2. Get an IAM token required for authentication.
  3. Get the ID of any folder that your account is granted the editor role or higher for.
  1. Select the authentication method:

    • Get an IAM token used in the examples.

    • Create an API key. Pass the API key in the Authorization header in the following format:

      Authorization: Api-Key <API key>
      
  2. Assign the editor role or a higher role to the service account for the folder where it was created.

    Don't specify the folder ID in your requests: the service uses the folder where the service account was created.

  1. Authenticate with the CLI as a federated user.

  2. Use the CLI to get an IAM token required for authentication:

    $ yc iam create-token
    
  3. Get the ID of any folder that your account is granted the editor role or higher for.

Apply the moderation model

  1. Prepare an image file that meets the requirements:

    • Supported file formats: JPEG, PNG, PDF.

      You specify the MIME type of the file in the mime_type property. The default is image.

    • Maximum file size: 1 MB.

    • Image size should not exceed 20 MP (length x width).

    Note

    Need an image? Download a sample.

  2. Encode the file as Base64:

    UNIX
    Windows
    PowerShell
    Python
    Node.js
    Java
    Go
    $ base64 -i input.jpg > output.txt
    
    C:> Base64.exe -e input.jpg > output.txt
    
    [Convert]::ToBase64String([IO.File]::ReadAllBytes("./input.jpg")) > output.txt
    
    # Импортируйте библиотеку для кодирования в Base64
    import base64
    
    # Создайте функцию, которая кодирует файл и возвращает результат.
    def encode_file(file):
      file_content = file.read()
      return base64.b64encode(file_content)
    
    // Считайте содержимое файла в память.
    var fs = require('fs');
    var file = fs.readFileSync('/path/to/file');
    
    // Получите содержимое файла в формате Base64.
    var encoded = Buffer.from(file).toString('base64');
    
    // Импортируйте библиотеку для кодирования в Base64.
    import org.apache.commons.codec.binary.Base64;
    
    // Получите содержимое файла в формате Base64.
    byte[] fileData = Base64.encodeBase64(yourFile.getBytes());
    
    import (
        "bufio"
        "encoding/base64"
        "io/ioutil"
        "os"
    )
    
    // Откройте файл
    f, _ := os.Open("/path/to/file")
    
    // Прочитайте содержимое файла.
    reader := bufio.NewReader(f)
    content, _ := ioutil.ReadAll(reader)
    
    // Получите содержимое файла в формате Base64.
    base64.StdEncoding.EncodeToString(content)
    
  3. Create a file with the request body (for example, body.json). In the content property, specify a Base64-encoded image:

    body.json:

    {
        "folderId": "b1gvmob95yysaplct532",
        "analyze_specs": [{
            "content": "iVBORw0KGgo...",
            "features": [{
                "type": "CLASSIFICATION",
                "classificationConfig": {
                    "model": "moderation"
                }
            }]
        }]
    }
    
  4. Send a request using the batchAnalyze method and save the response in a file, such as output.json:

    $ export IAM_TOKEN=CggaATEVAgA...
    $ curl -X POST \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer ${IAM_TOKEN}" \
        -d '@body.json' \
        https://vision.api.cloud.yandex.net/vision/v1/batchAnalyze > output.json
    

    The response will contain the properties and the probability of matching them. You can use these properties to moderate the image:

    {
     "results": [
      {
       "results": [
        {
         "classification": {
          "properties": [
           {
            "name": "adult",
            "probability": 0.0017486262368038297
           },
           {
            "name": "gruesome",
            "probability": 0.0002884353743866086
           },
           {
            "name": "text",
            "probability": 0.13789896667003632
           },
           {
            "name": "watermarks",
            "probability": 0.99908816814422607
           }
          ]
         }
        }
       ]
      }
     ]
    }
    

Ready-to-use function for sending requests in bash

  1. If you don't have the Yandex.Cloud command line interface yet, install and initialize it.

  2. Copy the function to the terminal:

    vision_moderation() {
        curl -H "Authorization: Bearer `yc iam create-token`" \
        "https://vision.api.cloud.yandex.net/vision/v1/batchAnalyze" \
        -d @<(cat << EOF
    {
        "folderId": "`yc config get folder-id`",
        "analyze_specs": [{
            "content": "`base64 -i $1`",
            "features": [{
                "type": "CLASSIFICATION",
                "classificationConfig": {
                    "model": "moderation"
                }
            }]
        }]
    }
    EOF
    )
    }
    

    Explanations:

    • yc iam create-token: get an IAM token.
    • -d @<(cat EOF ... EOF): create a request body.
    • yc config get folder-id: get the ID of the default folder selected in the CLI.
    • base64 -i $1: Base64 encoding of the image passed in the function arguments.
  3. Now you can call this function by passing the image path in the arguments:

    vision_moderation path/to/image.jpg
    
Language
Careers
Privacy policy
Terms of use
© 2021 Yandex.Cloud LLC