Classifying Content

Content Classification analyzes a document and returns a list of content categories that apply to the text found in the document. To classify the content in a document, call the classifyText method.

A complete list of content categories returned for the classifyText method are found here.

This section demonstrates how to classify content in a document.

Classifying Content

Here is an example of classifying content provided as a string:

Protocol

To classify content from a document, make a POST request to the documents:classifyText REST method and provide the appropriate request body as shown in the following example.

The example uses the gcloud auth application-default print-access-token command to obtain an access token for a service account set up for the project using the Google Cloud Platform Cloud SDK. For instructions on installing the Cloud SDK, setting up a project with a service account see the Quickstart.

curl -X POST \
     -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
     -H "Content-Type: application/json; charset=utf-8" \
     --data "{
  'document':{
    'type':'PLAIN_TEXT',
    'content':'Google, headquartered in Mountain View, unveiled the new Android
    phone at the Consumer Electronic Show.  Sundar Pichai said in his keynote
    that users love their new Android phones.'
  }
}" "https://language.googleapis.com/v1/documents:classifyText"

C#

For more on installing and creating a Natural Language API client, refer to Natural Language API Client Libraries.

        private static void ClassifyTextFromText(string text)
        {
            var client = LanguageServiceClient.Create();
            var response = client.ClassifyText(new Document()
            {
                Content = text,
                Type = Document.Types.Type.PlainText
            });
            WriteCategories(response.Categories);
        }

        private static void WriteCategories(IEnumerable<ClassificationCategory> categories)
        {
            Console.WriteLine("Categories:");
            foreach (var category in categories)
            {
                Console.WriteLine($"\tCategory: {category.Name}");
                Console.WriteLine($"\t\tConfidence: {category.Confidence}");
            }
        }

Go

For more on installing and creating a Natural Language API client, refer to Natural Language API Client Libraries.

func classifyText(ctx context.Context, client *language.Client, text string) (*languagepb.ClassifyTextResponse, error) {
	return client.ClassifyText(ctx, &languagepb.ClassifyTextRequest{
		Document: &languagepb.Document{
			Source: &languagepb.Document_Content{
				Content: text,
			},
			Type: languagepb.Document_PLAIN_TEXT,
		},
	})
}

Java

For more on installing and creating a Natural Language API client, refer to Natural Language API Client Libraries.

// Instantiate the Language client com.google.cloud.language.v1.LanguageServiceClient
try (LanguageServiceClient language = LanguageServiceClient.create()) {
  // set content to the text string
  Document doc = Document.newBuilder()
      .setContent(text)
      .setType(Type.PLAIN_TEXT)
      .build();
  ClassifyTextRequest request = ClassifyTextRequest.newBuilder()
      .setDocument(doc)
      .build();
  // detect categories in the given text
  ClassifyTextResponse response = language.classifyText(request);

  for (ClassificationCategory category : response.getCategoriesList()) {
    System.out.printf("Category name : %s, Confidence : %.3f\n",
        category.getName(), category.getConfidence());
  }
}

Node.js

For more on installing and creating a Natural Language API client, refer to Natural Language API Client Libraries.

// Imports the Google Cloud client library
const language = require('@google-cloud/language');

// Creates a client
const client = new language.LanguageServiceClient();

/**
 * TODO(developer): Uncomment the following line to run this code.
 */
// const text = 'Your text to analyze, e.g. Hello, world!';

// Prepares a document, representing the provided text
const document = {
  content: text,
  type: 'PLAIN_TEXT',
};

// Classifies text in the document
client
  .classifyText({document: document})
  .then(results => {
    const classification = results[0];

    console.log('Categories:');
    classification.categories.forEach(category => {
      console.log(
        `Name: ${category.name}, Confidence: ${category.confidence}`
      );
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

Python

For more on installing and creating a Natural Language API client, refer to Natural Language API Client Libraries.

def classify_text(text):
    """Classifies content categories of the provided text."""
    client = language.LanguageServiceClient()

    if isinstance(text, six.binary_type):
        text = text.decode('utf-8')

    document = types.Document(
        content=text.encode('utf-8'),
        type=enums.Document.Type.PLAIN_TEXT)

    categories = client.classify_text(document).categories

    for category in categories:
        print(u'=' * 20)
        print(u'{:<16}: {}'.format('name', category.name))
        print(u'{:<16}: {}'.format('confidence', category.confidence))

PHP

For more on installing and creating a Natural Language API client, refer to Natural Language API Client Libraries.

namespace Google\Cloud\Samples\Language;

use Google\Cloud\Language\LanguageClient;

/**
 * Classify text (20+ words) into categories.
 * ```
 * classify_text(
 *     'The first two gubernatorial elections since President Donald Trump ' .
 *     'took office went in favor of Democratic candidates in Virginia and ' .
 *     'New Jersey.'
 * );
 * ```
 *
 * @param string $text The text to analyze.
 * @param string $projectId (optional) Your Google Cloud Project ID
 */

function classify_text($text, $projectId = null)
{
    // Make sure we have enough words (20+) to call classifyText
    if (str_word_count($text) < 20) {
        printf('20+ words are required to classify text.' . PHP_EOL);
        return;
    }

    // Create the Natural Language client
    $language = new LanguageClient([
        'projectId' => $projectId,
    ]);

    // Call the classifyText function
    $response = $language->classifyText($text);
    $categories = $response->categories();

    // Print out information about each category
    foreach ($categories as $category) {
        printf('Category Name: %s' . PHP_EOL, $category['name']);
        printf('Confidence: %s' . PHP_EOL, $category['confidence']);
        printf(PHP_EOL);
    }
}

Ruby

For more on installing and creating a Natural Language API client, refer to Natural Language API Client Libraries.

# text_content = "Text to classify"

require "google/cloud/language"

language = Google::Cloud::Language.new
response = language.classify_text content: text_content, type: :PLAIN_TEXT

categories = response.categories

categories.each do |category|
  puts "Name: #{category.name} Confidence: #{category.confidence}"
end

Classifying Content from Google Cloud Storage

Here is an example of classifying content stored in a text file on Google Cloud Storage:

Protocol

To classify content from a document stored in Google Cloud Storage, make a POST request to the documents:classifyText REST method and provide the appropriate request body with the path to the document as shown in the following example.

curl -X POST \
     -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
     -H "Content-Type: application/json; charset=utf-8" \
     --data "{
  'document':{
    'type':'PLAIN_TEXT',
    'gcsContentUri':'gs://<bucket-name>/<object-name>'
  }
}" "https://language.googleapis.com/v1/documents:classifyText"

C#

For more on installing and creating a Natural Language API client, refer to Natural Language API Client Libraries.

private static void ClassifyTextFromFile(string gcsUri)
{
    var client = LanguageServiceClient.Create();
    var response = client.ClassifyText(new Document()
    {
        GcsContentUri = gcsUri,
        Type = Document.Types.Type.PlainText
    });
    WriteCategories(response.Categories);
}
private static void WriteCategories(IEnumerable<ClassificationCategory> categories)
{
    Console.WriteLine("Categories:");
    foreach (var category in categories)
    {
        Console.WriteLine($"\tCategory: {category.Name}");
        Console.WriteLine($"\t\tConfidence: {category.Confidence}");
    }
}

Go

For more on installing and creating a Natural Language API client, refer to Natural Language API Client Libraries.

func classifyTextFromGCS(ctx context.Context, gcsURI string) (*languagepb.ClassifyTextResponse, error) {
	return client.ClassifyText(ctx, &languagepb.ClassifyTextRequest{
		Document: &languagepb.Document{
			Source: &languagepb.Document_GcsContentUri{
				GcsContentUri: gcsURI,
			},
			Type: languagepb.Document_PLAIN_TEXT,
		},
	})
}

Java

For more on installing and creating a Natural Language API client, refer to Natural Language API Client Libraries.

// Instantiate the Language client com.google.cloud.language.v1.LanguageServiceClient
try (LanguageServiceClient language = LanguageServiceClient.create()) {
  // set the GCS content URI path
  Document doc = Document.newBuilder()
      .setGcsContentUri(gcsUri)
      .setType(Type.PLAIN_TEXT)
      .build();
  ClassifyTextRequest request = ClassifyTextRequest.newBuilder()
      .setDocument(doc)
      .build();
  // detect categories in the given file
  ClassifyTextResponse response = language.classifyText(request);

  for (ClassificationCategory category : response.getCategoriesList()) {
    System.out.printf("Category name : %s, Confidence : %.3f\n",
        category.getName(), category.getConfidence());
  }
}

Node.js

For more on installing and creating a Natural Language API client, refer to Natural Language API Client Libraries.

// Imports the Google Cloud client library.
const language = require('@google-cloud/language');

// Creates a client.
const client = new language.LanguageServiceClient();

/**
 * TODO(developer): Uncomment the following lines to run this code
 */
// const bucketName = 'Your bucket name, e.g. my-bucket';
// const fileName = 'Your file name, e.g. my-file.txt';

// Prepares a document, representing a text file in Cloud Storage
const document = {
  gcsContentUri: `gs://${bucketName}/${fileName}`,
  type: 'PLAIN_TEXT',
};

// Classifies text in the document
client
  .classifyText({document: document})
  .then(results => {
    const classification = results[0];

    console.log('Categories:');
    classification.categories.forEach(category => {
      console.log(
        `Name: ${category.name}, Confidence: ${category.confidence}`
      );
    });
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

Python

def classify_file(gcs_uri):
    """Classifies content categories of the text in a Google Cloud Storage
    file.
    """
    client = language.LanguageServiceClient()

    document = types.Document(
        gcs_content_uri=gcs_uri,
        type=enums.Document.Type.PLAIN_TEXT)

    categories = client.classify_text(document).categories

    for category in categories:
        print(u'=' * 20)
        print(u'{:<16}: {}'.format('name', category.name))
        print(u'{:<16}: {}'.format('confidence', category.confidence))

PHP

For more on installing and creating a Natural Language API client, refer to Natural Language API Client Libraries.

namespace Google\Cloud\Samples\Language;

use Google\Cloud\Language\LanguageClient;

/**
 * Classify text (20+ words) into categories.
 * ```
 * classify_text_from_file('gs://storage-bucket/file-name');
 * ```
 *
 * @param string $cloud_storage_uri Your Cloud Storage bucket URI
 * @param string $projectId (optional) Your Google Cloud Project ID
 */

function classify_text_from_file($cloud_storage_uri, $projectId = null)
{
    // Create the Natural Language client
    $language = new LanguageClient([
        'projectId' => $projectId,
    ]);

    // Call the classifyText function
    $response = $language->classifyText($cloud_storage_uri);
    $categories = $response->categories();

    // Print out information about each category
    foreach ($categories as $category) {
        printf('Category Name: %s' . PHP_EOL, $category['name']);
        printf('Confidence: %s' . PHP_EOL, $category['confidence']);
        printf(PHP_EOL);
    }
}

Ruby

For more on installing and creating a Natural Language API client, refer to Natural Language API Client Libraries.

# storage_path = "Path to file in Google Cloud Storage, eg. gs://bucket/file"

require "google/cloud/language"

language = Google::Cloud::Language.new
response = language.classify_text gcs_content_uri: storage_path, type: :PLAIN_TEXT

categories = response.categories

categories.each do |category|
  puts "Name: #{category.name} Confidence: #{category.confidence}"
end

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Natural Language API Documentation