콘텐츠 분류 가이드

대상

이 가이드를 사용하여 Cloud Natural Language API를 신속하게 살펴보고 활용하여 애플리케이션 개발을 시작할 수 있습니다. 가이드는 기본적인 프로그래밍에 익숙한 독자를 대상으로 제작되었지만 프로그래밍 관련 지식이 많지 않더라도 진행에는 무리가 없습니다. 이 가이드를 마치면 참조 문서를 사용하여 기본적인 애플리케이션을 만들 수 있습니다.

이 가이드에서는 Python 코드를 사용하여 Natural Language 애플리케이션을 단계별로 안내합니다. 이 가이드의 목적은 Python 클라이언트 라이브러리를 설명하는 것이 아니라 Natural Language API를 호출하는 방법을 설명하는 것입니다. 자바 및 Node.js로 작성된 애플리케이션도 원리적으로 비슷합니다. 다른 언어의 샘플에 대해서는 Natural Language API 샘플(이 가이드에 있는 샘플 포함)을 참조하세요.

기본 요건

이 가이드에는 몇 가지 기본 요건이 있습니다.

개요

이 가이드는 다음과 같이 신뢰도 점수와 함께 콘텐츠를 카테고리로 분류하는 classifyText 요청을 사용하여 기본 Natural Language 애플리케이션을 단계별로 설명합니다.

category: "/Internet & Telecom/Mobile & Wireless/Mobile Apps & Add-Ons"
confidence: 0.6499999761581421

사용할 수 있는 모든 카테고리 라벨의 목록을 보려면 카테고리를 참조하세요.

이 가이드에서는 다음 작업을 수행하기 위한 애플리케이션을 만듭니다.

  • 여러 텍스트 파일을 분류하고 결과를 색인 파일에 씁니다.
  • 입력 쿼리를 처리하여 유사한 텍스트 파일을 찾습니다.
  • 입력 쿼리 카테고리 라벨을 처리하여 유사한 텍스트 파일을 찾습니다.

이 가이드에서는 Wikipedia의 콘텐츠를 사용합니다. 뉴스 기사, 온라인 댓글 등을 처리하기 위한 유사한 애플리케이션을 만들 수도 있습니다.

소스 파일

GitHub의 Python 클라이언트 라이브러리 샘플에서 튜토리얼 소스 코드를 찾을 수 있습니다.

이 가이드에서는 Wikipedia의 샘플 소스 텍스트를 사용합니다. GitHub 프로젝트의 resources/texts 폴더에서 샘플 텍스트 파일을 찾을 수 있습니다.

라이브러리 가져오기

Cloud Natural Language API를 사용하려면 google-cloud-language 라이브러리에서 language 모듈을 가져와야 합니다. language.types 모듈은 요청을 생성하는 데 필요한 클래스를 포함하고 있습니다. language.enums 모듈은 입력 텍스트 유형을 지정하는 데 사용됩니다. 이 가이드에서는 일반 텍스트 콘텐츠(language.enums.Document.Type.PLAIN_TEXT)를 분류합니다.

최종 콘텐츠 분류를 기준으로 텍스트 간 유사성을 계산하기 위해 이 가이드에서는 벡터 계산에 numpy를 사용합니다.

Python

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

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

import argparse
import json
import os

from google.cloud import language_v1
import numpy

1단계: 콘텐츠 분류

Python 클라이언트 라이브러리를 사용하여 Natural Language API에 콘텐츠 분류를 요청할 수 있습니다. Python 클라이언트 라이브러리는 Natural Language API에 보낸 요청과 받은 응답의 세부 사항을 캡슐화합니다.

이 가이드의 classify 함수는 먼저 LanguageServiceClient 클래스의 인스턴스를 생성한 후에 LanguageServiceClient 인스턴스의 classify_text 메서드를 호출함으로써 Natural Language API classifyText 메서드를 호출합니다.

가이드 classify 함수는 이 예시의 텍스트 콘텐츠만 분류합니다. 또한 웹페이지의 소스 HTML을 text로 전달하고 type 매개변수를 language.enums.Document.Type.HTML로 설정하여 웹페이지의 콘텐츠를 분류할 수 있습니다.

자세한 내용은 콘텐츠 분류를 참조하세요. Natural Language API 요청 구조에 대한 자세한 내용은 Natural Language 참조를 참조하세요.

Python

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

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

def classify(text, verbose=True):
    """Classify the input text into categories."""

    language_client = language_v1.LanguageServiceClient()

    document = language_v1.Document(
        content=text, type_=language_v1.Document.Type.PLAIN_TEXT
    )
    response = language_client.classify_text(request={"document": document})
    categories = response.categories

    result = {}

    for category in categories:
        # Turn the categories into a dictionary of the form:
        # {category.name: category.confidence}, so that they can
        # be treated as a sparse vector.
        result[category.name] = category.confidence

    if verbose:
        print(text)
        for category in categories:
            print("=" * 20)
            print("{:<16}: {}".format("category", category.name))
            print("{:<16}: {}".format("confidence", category.confidence))

    return result

반환된 결과는 다음과 같이 카테고리 라벨이 키로 설정되고 신뢰도 점수가 값으로 설정된 사전입니다.

{
    "/Computers & Electronics": 0.800000011920929,
    "/Internet & Telecom/Mobile & Wireless/Mobile Apps & Add-Ons": 0.6499999761581421
}

가이드의 Python 스크립트는 빠른 실험을 위해 명령줄에서 실행할 수 있도록 구성되었습니다. 예를 들어 다음을 실행할 수 있습니다.

python classify_text_tutorial.py classify "Google Home enables users to speak voice commands to interact with services through the Home's intelligent personal assistant called Google Assistant. A large number of services, both in-house and third-party, are integrated, allowing users to listen to music, look at videos or photos, or receive news updates entirely by voice. "

2단계: 여러 텍스트 파일의 색인 생성

가이드 스크립트의 index 함수는 여러 텍스트 파일을 포함하는 디렉터리 및 색인 생성된 출력을 저장하는 파일(기본 파일 이름은 index.json)의 경로를 입력값으로 사용합니다. index 함수는 입력 디렉터리에서 각 텍스트 파일의 콘텐츠를 읽은 후에 텍스트 파일을 Cloud Natural Language API에 전달하여 콘텐츠 카테고리로 분류되도록 합니다.

Python

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

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

def index(path, index_file):
    """Classify each text file in a directory and write
    the results to the index_file.
    """

    result = {}
    for filename in os.listdir(path):
        file_path = os.path.join(path, filename)

        if not os.path.isfile(file_path):
            continue

        try:
            with open(file_path) as f:
                text = f.read()
                categories = classify(text, verbose=False)

                result[filename] = categories
        except Exception:
            print(f"Failed to process {file_path}")

    with open(index_file, "w", encoding="utf-8") as f:
        f.write(json.dumps(result, ensure_ascii=False))

    print(f"Texts indexed in file: {index_file}")
    return result

각 파일에 대한 Cloud Natural Language API의 결과는 JSON 문자열로 직렬화된 단일 사전으로 구성된 후에 파일에 작성됩니다. 예를 들면 다음과 같습니다.

{
    "android.txt": {
        "/Computers & Electronics": 0.800000011920929,
        "/Internet & Telecom/Mobile & Wireless/Mobile Apps & Add-Ons": 0.6499999761581421
    },
    "google.txt": {
        "/Internet & Telecom": 0.5799999833106995,
        "/Business & Industrial": 0.5400000214576721
    }
}

기본 출력 파일 이름 index.json을 사용하여 명령줄에서 텍스트 파일의 색인을 생성하려면 다음 명령어를 실행하세요.

python classify_text_tutorial.py index resources/texts

3단계: 색인 쿼리

카테고리 라벨로 쿼리

색인 파일(기본 파일 이름: index.json)이 생성된 후에는 색인에 쿼리하여 일부 파일 이름 및 신뢰도 점수를 검색할 수 있습니다.

그 방법 중 하나는 카테고리 라벨을 쿼리로 사용하는 것입니다. 이를 위해 가이드에서는 query_category 함수를 사용합니다. similarity와 같은 도우미 함수를 구현하는 방법은 classify_text_tutorial.py 파일에서 찾아볼 수 있습니다. 직접 작성하는 애플리케이션에서는 구체적인 사용 사례에 맞춰 유사성 채점 및 순위를 신중하게 설계해야 합니다.

Python

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

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

def query_category(index_file, category_string, n_top=3):
    """Find the indexed files that are the most similar to
    the query label.

    The list of all available labels:
    https://cloud.google.com/natural-language/docs/categories
    """

    with open(index_file) as f:
        index = json.load(f)

    # Make the category_string into a dictionary so that it is
    # of the same format as what we get by calling classify.
    query_categories = {category_string: 1.0}

    similarities = []
    for filename, categories in index.items():
        similarities.append((filename, similarity(query_categories, categories)))

    similarities = sorted(similarities, key=lambda p: p[1], reverse=True)

    print("=" * 20)
    print(f"Query: {category_string}\n")
    print(f"\nMost similar {n_top} indexed texts:")
    for filename, sim in similarities[:n_top]:
        print(f"\tFilename: {filename}")
        print(f"\tSimilarity: {sim}")
        print("\n")

    return similarities

사용할 수 있는 전체 카테고리 목록은 카테고리를 참조하세요.

이전과 마찬가지로 명령줄에서 query_category 함수를 호출할 수 있습니다.

python classify_text_tutorial.py query-category index.json "/Internet & Telecom/Mobile & Wireless"

다음과 비슷한 출력이 표시됩니다.

Query: /Internet & Telecom/Mobile & Wireless

Most similar 3 indexed texts:
  Filename: android.txt
  Similarity: 0.665573579045

  Filename: google.txt
  Similarity: 0.517527175966

  Filename: gcp.txt
  Similarity: 0.5

텍스트로 쿼리

색인 생성된 텍스트에 포함되지 않은 텍스트로 쿼리할 수도 있습니다. 가이드 query 함수는 query_category 함수와 유사하며, 텍스트 입력을 위한 classifyText 요청을 하고 결과를 사용하여 색인 파일을 쿼리하는 단계가 추가되었습니다.

Python

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

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

def query(index_file, text, n_top=3):
    """Find the indexed files that are the most similar to
    the query text.
    """

    with open(index_file) as f:
        index = json.load(f)

    # Get the categories of the query text.
    query_categories = classify(text, verbose=False)

    similarities = []
    for filename, categories in index.items():
        similarities.append((filename, similarity(query_categories, categories)))

    similarities = sorted(similarities, key=lambda p: p[1], reverse=True)

    print("=" * 20)
    print(f"Query: {text}\n")
    for category, confidence in query_categories.items():
        print(f"\tCategory: {category}, confidence: {confidence}")
    print(f"\nMost similar {n_top} indexed texts:")
    for filename, sim in similarities[:n_top]:
        print(f"\tFilename: {filename}")
        print(f"\tSimilarity: {sim}")
        print("\n")

    return similarities

명령줄에서 이를 수행하려면 다음을 실행합니다.

python classify_text_tutorial.py query index.json "Google Home enables users to speak voice commands to interact with services through the Home's intelligent personal assistant called Google Assistant. A large number of services, both in-house and third-party, are integrated, allowing users to listen to music, look at videos or photos, or receive news updates entirely by voice. "

다음과 비슷한 내용이 출력됩니다.

Query: Google Home enables users to speak voice commands to interact with services through the Home's intelligent personal assistant called Google Assistant. A large number of services, both in-house and third-party, are integrated, allowing users to listen to music, look at videos or photos, or receive news updates entirely by voice.

  Category: /Internet & Telecom, confidence: 0.509999990463
  Category: /Computers & Electronics/Software, confidence: 0.550000011921

Most similar 3 indexed texts:
  Filename: android.txt
  Similarity: 0.600579500049

  Filename: google.txt
  Similarity: 0.401314790229

  Filename: gcp.txt
  Similarity: 0.38772339779

다음 과정

콘텐츠 분류 API를 사용하여 다른 애플리케이션을 만들 수 있습니다. 예를 들면 다음과 같습니다.

  • 자료에 있는 모든 단락을 분류하여 주제 간 전환을 확인합니다.

  • 타임스탬프가 적용된 콘텐츠를 분류하고 시간 경과에 따른 주제 트렌드를 분석합니다.

  • analyzeSentiment 메서드를 사용하여 콘텐츠 카테고리를 콘텐츠 감정과 비교합니다.

  • 콘텐츠 카테고리를 텍스트에서 언급된 항목과 비교합니다.

또한 다른 Google Cloud Platform 제품을 사용하여 워크플로를 간소화할 수 있습니다.

  • 이 가이드의 샘플 애플리케이션에서는 로컬 텍스트 파일을 처리했지만, Google Cloud Storage URI를 classify_text 메서드에 전달함으로써 Google Cloud Storage 버킷에 저장된 텍스트 파일을 처리하도록 코드를 수정할 수도 있습니다.

  • 이 가이드의 샘플 애플리케이션에서는 색인 파일만 로컬에 저장했으며 각 쿼리는 전체 색인 파일을 읽음으로써 처리됩니다. 즉, 색인 생성된 데이터가 많거나 무수한 쿼리를 처리해야 하는 경우에는 지연 시간이 길어질 수 있습니다. Datastore는 색인 데이터를 자연스럽고 편리하게 저장할 수 있는 수단입니다.