콘텐츠 분류

콘텐츠 분류는 문서를 분석하고, 문서에서 찾은 텍스트에 적용되는 콘텐츠 카테고리의 목록을 반환합니다. 문서에서 콘텐츠를 분류하려면 classifyText 메서드를 호출하세요.

classifyText 메서드에 대해 반환되는 콘텐츠 카테고리의 전체 목록은 여기에서 찾아볼 수 있습니다.

classificationModelOptions 필드(선택사항)를 설정하여 classifyText 메서드에 사용할 모델을 선택할 수 있습니다.

이 섹션에서는 문서에서 콘텐츠를 분류하는 방법을 설명합니다. 문서마다 별도의 요청을 제출해야 합니다.

콘텐츠 분류

다음은 문자열로 제공된 콘텐츠를 분류하는 예입니다.

프로토콜

문서에서 콘텐츠를 분류하려면 documents:classifyText REST 메서드에 POST 요청을 하고 다음 예시와 같이 적절한 요청 본문을 제공해야 합니다.

이 예시에서는 gcloud auth application-default print-access-token 명령어를 사용하여 Google Cloud Platform gcloud CLI를 사용하는 프로젝트용으로 설정된 서비스 계정에 대한 액세스 토큰을 얻습니다. gcloud CLI를 설치하고 서비스 계정을 통해 프로젝트를 설정하는 방법에 대한 안내는 빠른 시작을 참조하세요.

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.'
  },
  'classificationModelOptions': {
    'v2Model': {
      'contentCategoriesVersion': 'V2',
    }
  }
}" "https://language.googleapis.com/v1/documents:classifyText"

Go

Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Natural Language Go API 참조 문서를 참조하세요.

Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


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,
		},
		ClassificationModelOptions: &languagepb.ClassificationModelOptions{
			ModelType: &languagepb.ClassificationModelOptions_V2Model_{
				V2Model: &languagepb.ClassificationModelOptions_V2Model{
					ContentCategoriesVersion: languagepb.ClassificationModelOptions_V2Model_V2,
				},
			},
		},
	})
}

Java

Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Natural Language Java API 참조 문서를 참조하세요.

Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// Instantiate the Language client com.google.cloud.language.v2.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

Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Natural Language Node.js API 참조 문서를 참조하세요.

Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// 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',
};

const classificationModelOptions = {
  v2Model: {
    contentCategoriesVersion: 'V2',
  },
};

// Classifies text in the document
const [classification] = await client.classifyText({
  document,
  classificationModelOptions,
});
console.log('Categories:');
classification.categories.forEach(category => {
  console.log(`Name: ${category.name}, Confidence: ${category.confidence}`);
});

Python

Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Natural Language Python API 참조 문서를 참조하세요.

Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import language_v1

def sample_classify_text(text_content):
    """
    Classifying Content in a String

    Args:
      text_content The text content to analyze.
    """

    client = language_v1.LanguageServiceClient()

    # text_content = "That actor on TV makes movies in Hollywood and also stars in a variety of popular new TV shows."

    # Available types: PLAIN_TEXT, HTML
    type_ = language_v1.Document.Type.PLAIN_TEXT

    # Optional. If not specified, the language is automatically detected.
    # For list of supported languages:
    # https://cloud.google.com/natural-language/docs/languages
    language = "en"
    document = {"content": text_content, "type_": type_, "language": language}

    content_categories_version = (
        language_v1.ClassificationModelOptions.V2Model.ContentCategoriesVersion.V2
    )
    response = client.classify_text(
        request={
            "document": document,
            "classification_model_options": {
                "v2_model": {"content_categories_version": content_categories_version}
            },
        }
    )
    # Loop through classified categories returned from the API
    for category in response.categories:
        # Get the name of the category representing the document.
        # See the predefined taxonomy of categories:
        # https://cloud.google.com/natural-language/docs/categories
        print(f"Category name: {category.name}")
        # Get the confidence. Number representing how certain the classifier
        # is that this category represents the provided text.
        print(f"Confidence: {category.confidence}")

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 후 .NET용 자연 언어 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 후 PHP용 자연 언어 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 후 Ruby용 자연 언어 참조 문서를 참조하세요.

Cloud Storage에서 콘텐츠 분류

다음은 Cloud Storage에서 텍스트 파일에 저장된 콘텐츠를 분류하는 예입니다.

프로토콜

Cloud Storage에 저장된 문서의 콘텐츠를 분류하려면 documents:classifyText REST 메서드에 POST 요청을 하고 다음 예시와 같이 적절한 요청 본문 및 문서 경로를 제공해야 합니다.

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>'
  }
  'classificationModelOptions': {
    'v1Model': {
    }
  }
}" "https://language.googleapis.com/v1/documents:classifyText"

Go

Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Natural Language Go API 참조 문서를 참조하세요.

Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


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

Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Natural Language Java API 참조 문서를 참조하세요.

Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// Instantiate the Language client com.google.cloud.language.v2.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

Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Natural Language Node.js API 참조 문서를 참조하세요.

Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// 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
const [classification] = await client.classifyText({document});

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

Python

Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Natural Language Python API 참조 문서를 참조하세요.

Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import language_v1

def sample_classify_text(gcs_content_uri):
    """
    Classifying Content in text file stored in Cloud Storage

    Args:
      gcs_content_uri Google Cloud Storage URI where the file content is located.
      e.g. gs://[Your Bucket]/[Path to File]
      The text file must include at least 20 words.
    """

    client = language_v1.LanguageServiceClient()

    # gcs_content_uri = 'gs://cloud-samples-data/language/classify-entertainment.txt'

    # Available types: PLAIN_TEXT, HTML
    type_ = language_v1.Document.Type.PLAIN_TEXT

    # Optional. If not specified, the language is automatically detected.
    # For list of supported languages:
    # https://cloud.google.com/natural-language/docs/languages
    language = "en"
    document = {
        "gcs_content_uri": gcs_content_uri,
        "type_": type_,
        "language": language,
    }

    response = client.classify_text(request={"document": document})
    # Loop through classified categories returned from the API
    for category in response.categories:
        # Get the name of the category representing the document.
        # See the predefined taxonomy of categories:
        # https://cloud.google.com/natural-language/docs/categories
        print(f"Category name: {category.name}")
        # Get the confidence. Number representing how certain the classifier
        # is that this category represents the provided text.
        print(f"Confidence: {category.confidence}")

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 후 .NET용 자연 언어 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 후 PHP용 자연 언어 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 후 Ruby용 자연 언어 참조 문서를 참조하세요.