Python용 Azure Text Analytics 클라이언트 라이브러리 - 버전 5.3.0

Azure Cognitive Service for Language는 텍스트를 이해하고 분석하기 위한 NLP(자연어 처리) 기능을 제공하는 클라우드 기반 서비스이며 다음 기본 기능을 포함합니다.

  • 감정 분석
  • 명명된 엔터티 인식
  • 언어 검색
  • 핵심 문구 추출
  • 엔터티 연결
  • 다중 분석
  • PII(개인 식별 정보) 검색
  • 상태에 대한 Text Analytics
  • 사용자 지정 명명된 엔터티 인식
  • 사용자 지정 텍스트 분류
  • 추출 텍스트 요약
  • 추상 텍스트 요약

소스 코드 | 패키지(PyPI) | 패키지(Conda) | API 참조 설명서 | 제품 설명서 | 샘플

시작

필수 조건

Cognitive Services 또는 언어 서비스 리소스 만들기

언어 서비스는 다중 서비스 및 단일 서비스 액세스를 모두 지원합니다. 단일 엔드포인트/키에서 여러 Cognitive Services에 액세스하려는 경우 Cognitive Services 리소스를 만듭니다. 언어 서비스 액세스에 대해서만 언어 서비스 리소스를 만듭니다. 이 문서의 단계에 따라 Azure Portal 또는 Azure CLI를 사용하여 리소스를 만들 수 있습니다.

클라이언트 라이브러리를 사용하는 서비스와의 상호 작용은 클라이언트로 시작합니다. 클라이언트 개체를 만들려면 리소스에 대한 Cognitive Services 또는 언어 서비스 endpointcredential 액세스할 수 있는 가 필요합니다.

from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

credential = AzureKeyCredential("<api_key>")
text_analytics_client = TextAnalyticsClient(endpoint="https://<resource-name>.cognitiveservices.azure.com/", credential=credential)

일부 Cognitive Services 리소스의 경우 엔드포인트가 위의 코드 조각과 다르게 보일 수 있습니다. 예: https://<region>.api.cognitive.microsoft.com/.

패키지 설치

pip를 사용하여 Python용 Azure Text Analytics 클라이언트 라이브러리를 설치합니다.

pip install azure-ai-textanalytics
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient
endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]

text_analytics_client = TextAnalyticsClient(endpoint, AzureKeyCredential(key))

5.2.X 이상에서는 언어 API용 Azure Cognitive Service를 대상으로 합니다. 이러한 API에는 이전 버전의 Text Analytics 클라이언트 라이브러리에 있는 텍스트 분석 및 자연어 처리 기능이 포함됩니다. 또한 서비스 API가 의미 체계에서 날짜 기반 버전 관리로 변경되었습니다. 이 버전의 클라이언트 라이브러리는 기본적으로 지원되는 최신 API 버전(현재 )으로 설정됩니다 2023-04-01.

이 표에서는 SDK 버전과 지원되는 API 버전의 서비스 간 관계를 보여 줍니다.

SDK 버전 지원되는 API 버전의 서비스
5.3.X - 안정적인 최신 릴리스 3.0, 3.1, 2022-05-01, 2023-04-01(기본값)
5.2.X 3.0, 3.1, 2022-05-01(기본값)
5.1.0 3.0, 3.1(기본값)
5.0.0 3.0

api_version 키워드(keyword) 인수를 클라이언트에 전달하여 API 버전을 선택할 수 있습니다. 최신 언어 서비스 기능의 경우 최신 베타 API 버전을 선택하는 것이 좋습니다. 프로덕션 시나리오의 경우 안정적인 최신 버전을 사용하는 것이 좋습니다. 이전 버전으로 설정하면 기능 호환성이 저하될 수 있습니다.

클라이언트 인증

엔드포인트 가져오기

Azure Portal 또는 Azure CLI를 사용하여 언어 서비스 리소스에 대한 엔드포인트를 찾을 수 있습니다.

# Get the endpoint for the Language service resource
az cognitiveservices account show --name "resource-name" --resource-group "resource-group-name" --query "properties.endpoint"

API 키 가져오기

Azure Portal의 Cognitive Services 또는 언어 서비스 리소스에서 API 키를 가져올 수 있습니다. 또는 아래 Azure CLI 코드 조각을 사용하여 리소스의 API 키를 가져올 수 있습니다.

az cognitiveservices account keys list --name "resource-name" --resource-group "resource-group-name"

API 키 자격 증명을 사용하여 TextAnalyticsClient 만들기

API 키에 대한 값이 있으면 AzureKeyCredential의 instance 문자열로 전달할 수 있습니다. 키를 자격 증명 매개 변수로 사용하여 클라이언트를 인증합니다.

import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient
endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]

text_analytics_client = TextAnalyticsClient(endpoint, AzureKeyCredential(key))

Azure Active Directory 자격 증명을 사용하여 TextAnalyticsClient 만들기

AAD(Azure Active Directory) 토큰 자격 증명을 사용하려면 azure-identity 라이브러리에서 가져온 원하는 자격 증명 형식의 instance 제공합니다. 지역 엔드포인트는 AAD 인증을 지원하지 않습니다. 이러한 유형의 인증을 사용하기 위해 리소스에 대한 사용자 지정 하위 도메인 이름을 만듭니다.

AAD를 사용하여 인증하려면 몇 가지 초기 설정이 필요합니다.

설치 후 azure.identity에서 사용할 자격 증명 유형을 선택할 수 있습니다. 예를 들어 DefaultAzureCredential을 사용하여 클라이언트를 인증할 수 있습니다.

AAD 애플리케이션의 클라이언트 ID, 테넌트 ID 및 클라이언트 암호 값을 환경 변수(AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET

반환된 토큰 자격 증명을 사용하여 클라이언트를 인증합니다.

import os
from azure.ai.textanalytics import TextAnalyticsClient
from azure.identity import DefaultAzureCredential

endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
credential = DefaultAzureCredential()

text_analytics_client = TextAnalyticsClient(endpoint, credential=credential)

주요 개념

TextAnalyticsClient

Text Analytics 클라이언트 라이브러리는 문서의 예제 일괄 처리에 대한 분석을 수행하는 TextAnalyticsClient를 제공합니다. 언어 감지 또는 핵심 구 추출과 같은 특정 텍스트 분석 사용에 액세스하기 위한 동기 및 비동기 작업을 모두 제공합니다.

입력

문서는 언어 서비스의 예측 모델에서 분석할 단일 단위입니다. 각 작업에 대한 입력은 문서 목록 으로 전달됩니다.

각 문서는 목록의 문자열(예: )로 전달될 수 있습니다.

documents = ["I hated the movie. It was so slow!", "The movie made it into my top ten favorites. What a great movie!"]

또는 항목별 문서 id 또는 languagecountry_hint/를 전달하려는 경우 DetectLanguageInput 또는 TextDocumentInput 목록 또는 개체의 dict와 유사한 표현으로 전달할 수 있습니다.

documents = [
    {"id": "1", "language": "en", "text": "I hated the movie. It was so slow!"},
    {"id": "2", "language": "en", "text": "The movie made it into my top ten favorites. What a great movie!"},
]

문서 길이 제한, 최대 일괄 처리 크기 및 지원되는 텍스트 인코딩을 포함하여 입력에 대한 서비스 제한을 참조하세요.

반환 값

단일 문서의 반환 값은 결과 또는 오류 개체일 수 있습니다. 결과 및 오류 개체의 컬렉션을 포함하는 다른 유형의 목록이 각 작업에서 반환됩니다. 이러한 결과/오류는 제공된 문서의 순서와 인덱스 일치합니다.

AnalyzeSentimentResult와 같은 결과는 텍스트 분석 작업의 결과이며 문서 입력에 대한 예측 또는 예측을 포함합니다.

DocumentError오류 개체는 서비스에서 문서를 처리하는 데 문제가 있음을 나타내며 실패한 이유를 포함합니다.

문서 오류 처리

특성을 사용하여 목록의 결과 또는 오류 개체를 필터링할 is_error 수 있습니다. 결과 개체의 경우 항상 False 이고 DocumentError 의 경우 입니다 True.

예를 들어 모든 DocumentErrors를 필터링하려면 목록 이해를 사용할 수 있습니다.

response = text_analytics_client.analyze_sentiment(documents)
successful_responses = [doc for doc in response if not doc.is_error]

특성을 사용하여 kind 결과 형식 간에 필터링할 수도 있습니다.

poller = text_analytics_client.begin_analyze_actions(documents, actions)
response = poller.result()
for result in response:
    if result.kind == "SentimentAnalysis":
        print(f"Sentiment is {result.sentiment}")
    elif result.kind == "KeyPhraseExtraction":
        print(f"Key phrases: {result.key_phrases}")
    elif result.is_error is True:
        print(f"Document error: {result.code}, {result.message}")

Long-Running 작업

장기 실행 작업은 작업을 시작하기 위해 서비스로 전송된 초기 요청으로 구성된 작업이며, 그 다음에는 간격으로 서비스를 폴링하여 작업이 완료되었는지 또는 실패했는지, 성공했는지 여부를 확인하여 결과를 가져옵니다.

의료 분석, 사용자 지정 텍스트 분석 또는 여러 분석을 지원하는 메서드는 장기 실행 작업으로 모델링됩니다. 클라이언트는 폴러 개체를 begin_<method-name> 반환하는 메서드를 노출합니다. 호출자는 메서드에서 begin_<method-name> 반환된 폴러 개체를 호출 result() 하여 작업이 완료되기를 기다려야 합니다. 샘플 코드 조각은 아래의 장기 실행 작업 를 사용하여 설명하기 위해 제공됩니다.

예제

다음 섹션에서는 다음을 포함하여 가장 일반적인 언어 서비스 작업 중 일부를 다루는 몇 가지 코드 조각을 제공합니다.

감정 분석

analyze_sentiment 입력 텍스트를 살펴보고 해당 감정이 긍정, 부정, 중립 또는 혼합인지 여부를 결정합니다. 응답에는 문장별 감정 분석 및 신뢰도 점수가 포함됩니다.

import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]

text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))

documents = [
    """I had the best day of my life. I decided to go sky-diving and it made me appreciate my whole life so much more.
    I developed a deep-connection with my instructor as well, and I feel as if I've made a life-long friend in her.""",
    """This was a waste of my time. All of the views on this drop are extremely boring, all I saw was grass. 0/10 would
    not recommend to any divers, even first timers.""",
    """This was pretty good! The sights were ok, and I had fun with my instructors! Can't complain too much about my experience""",
    """I only have one word for my experience: WOW!!! I can't believe I have had such a wonderful skydiving company right
    in my backyard this whole time! I will definitely be a repeat customer, and I want to take my grandmother skydiving too,
    I know she'll love it!"""
]


result = text_analytics_client.analyze_sentiment(documents, show_opinion_mining=True)
docs = [doc for doc in result if not doc.is_error]

print("Let's visualize the sentiment of each of these documents")
for idx, doc in enumerate(docs):
    print(f"Document text: {documents[idx]}")
    print(f"Overall sentiment: {doc.sentiment}")

반환된 응답은 결과 및 오류 개체의 다른 유형의 목록입니다. list[AnalyzeSentimentResult, DocumentError]

감정 분석에 대한 개념적 논의는 서비스 설명서를 참조하세요. 텍스트에서 개별 측면(예: 제품 또는 서비스의 특성)과 관련된 의견에 대해 보다 세분화된 분석을 수행하는 방법을 보려면 여기를 참조 하세요.

엔터티 인식

recognize_entities 입력 텍스트의 엔터티를 사람, 장소, 조직, 날짜/시간, 수량, 백분율, 통화 등으로 인식하고 범주화합니다.

import os
import typing
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]

text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))
reviews = [
    """I work for Foo Company, and we hired Contoso for our annual founding ceremony. The food
    was amazing and we all can't say enough good words about the quality and the level of service.""",
    """We at the Foo Company re-hired Contoso after all of our past successes with the company.
    Though the food was still great, I feel there has been a quality drop since their last time
    catering for us. Is anyone else running into the same problem?""",
    """Bar Company is over the moon about the service we received from Contoso, the best sliders ever!!!!"""
]

result = text_analytics_client.recognize_entities(reviews)
result = [review for review in result if not review.is_error]
organization_to_reviews: typing.Dict[str, typing.List[str]] = {}

for idx, review in enumerate(result):
    for entity in review.entities:
        print(f"Entity '{entity.text}' has category '{entity.category}'")
        if entity.category == 'Organization':
            organization_to_reviews.setdefault(entity.text, [])
            organization_to_reviews[entity.text].append(reviews[idx])

for organization, reviews in organization_to_reviews.items():
    print(
        "\n\nOrganization '{}' has left us the following review(s): {}".format(
            organization, "\n\n".join(reviews)
        )
    )

반환된 응답은 결과 및 오류 개체의 다른 유형의 목록입니다. list[RecognizeEntitiesResult, DocumentError]

명명된 엔터티 인식지원되는 형식에 대한 개념적 논의는 서비스 설명서를 참조하세요.

연결된 엔터티 인식

recognize_linked_entities 입력 텍스트에 있는 각 엔터티의 ID를 인식하고 모호하게 만듭니다(예: 화성이라는 단어가 행성을 참조하는지, 아니면 로마 전쟁의 신을 가리키는지 결정). 인식된 엔터티는 위키백과 같은 잘 알려진 기술 자료 URL과 연결됩니다.

import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]

text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))
documents = [
    """
    Microsoft was founded by Bill Gates with some friends he met at Harvard. One of his friends,
    Steve Ballmer, eventually became CEO after Bill Gates as well. Steve Ballmer eventually stepped
    down as CEO of Microsoft, and was succeeded by Satya Nadella.
    Microsoft originally moved its headquarters to Bellevue, Washington in January 1979, but is now
    headquartered in Redmond.
    """
]

result = text_analytics_client.recognize_linked_entities(documents)
docs = [doc for doc in result if not doc.is_error]

print(
    "Let's map each entity to it's Wikipedia article. I also want to see how many times each "
    "entity is mentioned in a document\n\n"
)
entity_to_url = {}
for doc in docs:
    for entity in doc.entities:
        print("Entity '{}' has been mentioned '{}' time(s)".format(
            entity.name, len(entity.matches)
        ))
        if entity.data_source == "Wikipedia":
            entity_to_url[entity.name] = entity.url

반환된 응답은 결과 및 오류 개체의 다른 유형의 목록입니다. list[RecognizeLinkedEntitiesResult, DocumentError]

엔터티 연결지원되는 형식에 대한 개념적 논의는 서비스 설명서를 참조하세요.

PII 엔터티 인식

recognize_pii_entities 사회 보장 번호, 은행 계좌 정보, 신용 카드 번호 등과 같은 입력 텍스트에서 PII(개인 식별 정보) 엔터티를 인식하고 분류합니다.

import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]

text_analytics_client = TextAnalyticsClient(
    endpoint=endpoint, credential=AzureKeyCredential(key)
)
documents = [
    """Parker Doe has repaid all of their loans as of 2020-04-25.
    Their SSN is 859-98-0987. To contact them, use their phone number
    555-555-5555. They are originally from Brazil and have Brazilian CPF number 998.214.865-68"""
]

result = text_analytics_client.recognize_pii_entities(documents)
docs = [doc for doc in result if not doc.is_error]

print(
    "Let's compare the original document with the documents after redaction. "
    "I also want to comb through all of the entities that got redacted"
)
for idx, doc in enumerate(docs):
    print(f"Document text: {documents[idx]}")
    print(f"Redacted document text: {doc.redacted_text}")
    for entity in doc.entities:
        print("...Entity '{}' with category '{}' got redacted".format(
            entity.text, entity.category
        ))

반환된 응답은 결과 및 오류 개체의 다른 유형의 목록입니다. list[RecognizePiiEntitiesResult, DocumentError]

지원되는 PII 엔터티 형식은 서비스 설명서를 참조하세요.

참고: PII 엔터티 인식 서비스는 API 버전 v3.1 이상에서 사용할 수 있습니다.

핵심 구 추출

extract_key_phrases 입력 텍스트에서 기본 대화 지점을 결정합니다. 예를 들어 "음식이 맛있었고 훌륭한 직원이 있었다"라는 입력 텍스트의 경우 API는 "food" 및 "wonderful staff"를 반환합니다.

import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]

text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))
articles = [
    """
    Washington, D.C. Autumn in DC is a uniquely beautiful season. The leaves fall from the trees
    in a city chock-full of forests, leaving yellow leaves on the ground and a clearer view of the
    blue sky above...
    """,
    """
    Redmond, WA. In the past few days, Microsoft has decided to further postpone the start date of
    its United States workers, due to the pandemic that rages with no end in sight...
    """,
    """
    Redmond, WA. Employees at Microsoft can be excited about the new coffee shop that will open on campus
    once workers no longer have to work remotely...
    """
]

result = text_analytics_client.extract_key_phrases(articles)
for idx, doc in enumerate(result):
    if not doc.is_error:
        print("Key phrases in article #{}: {}".format(
            idx + 1,
            ", ".join(doc.key_phrases)
        ))

반환된 응답은 결과 및 오류 개체의 다른 유형의 목록입니다. list[ExtractKeyPhrasesResult, DocumentError]

핵심 구 추출에 대한 개념적 논의는 서비스 설명서를 참조하세요.

언어 감지

detect_language 예측된 언어의 신뢰도 점수를 포함하여 입력 텍스트의 언어를 결정합니다.

import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]

text_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))
documents = [
    """
    The concierge Paulette was extremely helpful. Sadly when we arrived the elevator was broken, but with Paulette's help we barely noticed this inconvenience.
    She arranged for our baggage to be brought up to our room with no extra charge and gave us a free meal to refurbish all of the calories we lost from
    walking up the stairs :). Can't say enough good things about my experience!
    """,
    """
    最近由于工作压力太大,我们决定去富酒店度假。那儿的温泉实在太舒服了,我跟我丈夫都完全恢复了工作前的青春精神!加油!
    """
]

result = text_analytics_client.detect_language(documents)
reviewed_docs = [doc for doc in result if not doc.is_error]

print("Let's see what language each review is in!")

for idx, doc in enumerate(reviewed_docs):
    print("Review #{} is in '{}', which has ISO639-1 name '{}'\n".format(
        idx, doc.primary_language.name, doc.primary_language.iso6391_name
    ))

반환된 응답은 결과 및 오류 개체의 다른 유형의 목록입니다. 목록[DetectLanguageResult, DocumentError]

언어 감지언어 및 지역 지원에 대한 개념적 논의는 서비스 설명서를 참조하세요.

의료 엔터티 분석

장기 실행 작업은begin_analyze_healthcare_entities 의료 도메인 내에서 인식되는 엔터티를 추출하고 입력 문서 내의 엔터티 간의 관계를 식별하고 UMLS, CHV, MSH 등과 같은 다양한 잘 알려진 데이터베이스의 알려진 정보 원본에 대한 링크를 식별합니다.

import os
import typing
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient, HealthcareEntityRelation

endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]

text_analytics_client = TextAnalyticsClient(
    endpoint=endpoint,
    credential=AzureKeyCredential(key),
)

documents = [
    """
    Patient needs to take 100 mg of ibuprofen, and 3 mg of potassium. Also needs to take
    10 mg of Zocor.
    """,
    """
    Patient needs to take 50 mg of ibuprofen, and 2 mg of Coumadin.
    """
]

poller = text_analytics_client.begin_analyze_healthcare_entities(documents)
result = poller.result()

docs = [doc for doc in result if not doc.is_error]

print("Let's first visualize the outputted healthcare result:")
for doc in docs:
    for entity in doc.entities:
        print(f"Entity: {entity.text}")
        print(f"...Normalized Text: {entity.normalized_text}")
        print(f"...Category: {entity.category}")
        print(f"...Subcategory: {entity.subcategory}")
        print(f"...Offset: {entity.offset}")
        print(f"...Confidence score: {entity.confidence_score}")
        if entity.data_sources is not None:
            print("...Data Sources:")
            for data_source in entity.data_sources:
                print(f"......Entity ID: {data_source.entity_id}")
                print(f"......Name: {data_source.name}")
        if entity.assertion is not None:
            print("...Assertion:")
            print(f"......Conditionality: {entity.assertion.conditionality}")
            print(f"......Certainty: {entity.assertion.certainty}")
            print(f"......Association: {entity.assertion.association}")
    for relation in doc.entity_relations:
        print(f"Relation of type: {relation.relation_type} has the following roles")
        for role in relation.roles:
            print(f"...Role '{role.name}' with entity '{role.entity.text}'")
    print("------------------------------------------")

print("Now, let's get all of medication dosage relations from the documents")
dosage_of_medication_relations = [
    entity_relation
    for doc in docs
    for entity_relation in doc.entity_relations if entity_relation.relation_type == HealthcareEntityRelation.DOSAGE_OF_MEDICATION
]

참고: 의료 엔터티 분석은 API 버전 v3.1 이상에서만 사용할 수 있습니다.

다중 분석

장기 실행 작업begin_analyze_actions 단일 요청에서 한 문서 집합에 대해 여러 분석을 수행합니다. 현재 단일 요청에서 다음 언어 API의 조합을 사용하여 지원됩니다.

  • 엔터티 인식
  • PII 엔터티 인식
  • 연결된 엔터티 인식
  • 핵심 문구 추출
  • 감정 분석
  • 사용자 지정 엔터티 인식(API 버전 2022-05-01 이상)
  • 사용자 지정 단일 레이블 분류(API 버전 2022-05-01 이상)
  • 사용자 지정 다중 레이블 분류(API 버전 2022-05-01 이상)
  • 의료 엔터티 분석(API 버전 2022-05-01 이상)
  • 추출 요약(API 버전 2023-04-01 이상)
  • 추상 요약(API 버전 2023-04-01 이상)
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import (
    TextAnalyticsClient,
    RecognizeEntitiesAction,
    RecognizeLinkedEntitiesAction,
    RecognizePiiEntitiesAction,
    ExtractKeyPhrasesAction,
    AnalyzeSentimentAction,
)

endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]

text_analytics_client = TextAnalyticsClient(
    endpoint=endpoint,
    credential=AzureKeyCredential(key),
)

documents = [
    'We went to Contoso Steakhouse located at midtown NYC last week for a dinner party, and we adore the spot! '
    'They provide marvelous food and they have a great menu. The chief cook happens to be the owner (I think his name is John Doe) '
    'and he is super nice, coming out of the kitchen and greeted us all.'
    ,

    'We enjoyed very much dining in the place! '
    'The Sirloin steak I ordered was tender and juicy, and the place was impeccably clean. You can even pre-order from their '
    'online menu at www.contososteakhouse.com, call 312-555-0176 or send email to order@contososteakhouse.com! '
    'The only complaint I have is the food didn\'t come fast enough. Overall I highly recommend it!'
]

poller = text_analytics_client.begin_analyze_actions(
    documents,
    display_name="Sample Text Analysis",
    actions=[
        RecognizeEntitiesAction(),
        RecognizePiiEntitiesAction(),
        ExtractKeyPhrasesAction(),
        RecognizeLinkedEntitiesAction(),
        AnalyzeSentimentAction(),
    ],
)

document_results = poller.result()
for doc, action_results in zip(documents, document_results):
    print(f"\nDocument text: {doc}")
    for result in action_results:
        if result.kind == "EntityRecognition":
            print("...Results of Recognize Entities Action:")
            for entity in result.entities:
                print(f"......Entity: {entity.text}")
                print(f".........Category: {entity.category}")
                print(f".........Confidence Score: {entity.confidence_score}")
                print(f".........Offset: {entity.offset}")

        elif result.kind == "PiiEntityRecognition":
            print("...Results of Recognize PII Entities action:")
            for pii_entity in result.entities:
                print(f"......Entity: {pii_entity.text}")
                print(f".........Category: {pii_entity.category}")
                print(f".........Confidence Score: {pii_entity.confidence_score}")

        elif result.kind == "KeyPhraseExtraction":
            print("...Results of Extract Key Phrases action:")
            print(f"......Key Phrases: {result.key_phrases}")

        elif result.kind == "EntityLinking":
            print("...Results of Recognize Linked Entities action:")
            for linked_entity in result.entities:
                print(f"......Entity name: {linked_entity.name}")
                print(f".........Data source: {linked_entity.data_source}")
                print(f".........Data source language: {linked_entity.language}")
                print(
                    f".........Data source entity ID: {linked_entity.data_source_entity_id}"
                )
                print(f".........Data source URL: {linked_entity.url}")
                print(".........Document matches:")
                for match in linked_entity.matches:
                    print(f"............Match text: {match.text}")
                    print(f"............Confidence Score: {match.confidence_score}")
                    print(f"............Offset: {match.offset}")
                    print(f"............Length: {match.length}")

        elif result.kind == "SentimentAnalysis":
            print("...Results of Analyze Sentiment action:")
            print(f"......Overall sentiment: {result.sentiment}")
            print(
                f"......Scores: positive={result.confidence_scores.positive}; \
                neutral={result.confidence_scores.neutral}; \
                negative={result.confidence_scores.negative} \n"
            )

        elif result.is_error is True:
            print(
                f"...Is an error with code '{result.error.code}' and message '{result.error.message}'"
            )

    print("------------------------------------------")

반환된 응답은 각각 개별 분석 결과를 나타내는 여러 반복 가능 개체를 캡슐화하는 개체입니다.

참고: 여러 분석은 API 버전 v3.1 이상에서 사용할 수 있습니다.

선택적 구성

선택적 키워드(keyword) 인수는 클라이언트 및 작업별 수준에서 전달할 수 있습니다. azure-core 참조 설명서 에서는 재시도, 로깅, 전송 프로토콜 등에 사용할 수 있는 구성에 대해 설명합니다.

문제 해결

일반

Text Analytics 클라이언트는 Azure Core에 정의된 예외를 발생합니다.

로깅

이 라이브러리는 로깅에 표준 로깅 라이브러리를 사용합니다. HTTP 세션(URL, 헤더 등)에 대한 기본 정보는 INFO 수준에서 기록됩니다.

logging_enable 키워드 인수를 통해 클라이언트에서 요청/응답 본문 및 미작성 헤더를 포함한 상세 디버그 수준 로깅을 사용할 수 있습니다.

import sys
import logging
from azure.identity import DefaultAzureCredential
from azure.ai.textanalytics import TextAnalyticsClient

# Create a logger for the 'azure' SDK
logger = logging.getLogger('azure')
logger.setLevel(logging.DEBUG)

# Configure a console output
handler = logging.StreamHandler(stream=sys.stdout)
logger.addHandler(handler)

endpoint = "https://<resource-name>.cognitiveservices.azure.com/"
credential = DefaultAzureCredential()

# This client will log detailed information about its HTTP sessions, at DEBUG level
text_analytics_client = TextAnalyticsClient(endpoint, credential, logging_enable=True)
result = text_analytics_client.analyze_sentiment(["I did not like the restaurant. The food was too spicy."])

마찬가지로 logging_enable은 클라이언트에 대해 상세 로깅을 사용하지 않는 경우에도 한 작업에만 사용하게 설정할 수 있습니다.

result = text_analytics_client.analyze_sentiment(documents, logging_enable=True)

다음 단계

추가 샘플 코드

이러한 코드 샘플은 Azure Text Analytics 클라이언트 라이브러리를 사용하는 일반적인 시나리오 작업을 보여 줍니다.

Azure ID에서 Cognitive Services/Language Service API 키 또는 토큰 자격 증명을 사용하여 클라이언트를 인증합니다.

일반적인 시나리오

고급 시나리오

추가 설명서

Azure Cognitive Service for Language에 대한 보다 광범위한 설명서는 docs.microsoft.com Language Service 설명서를 참조하세요 .

참여

이 프로젝트에 대한 기여와 제안을 환영합니다. 대부분의 경우 기여하려면 권한을 부여하며 실제로 기여를 사용할 권한을 당사에 부여한다고 선언하는 CLA(기여자 라이선스 계약)에 동의해야 합니다. 자세한 내용은 cla.microsoft.com.

끌어오기 요청을 제출하면 CLA-bot은 CLA를 제공하고 PR을 적절하게 데코레이팅해야 하는지 여부를 자동으로 결정합니다(예: 레이블, 설명). 봇에서 제공하는 지침을 따르기만 하면 됩니다. 이 작업은 CLA를 사용하여 모든 리포지토리에서 한 번만 수행하면 됩니다.

이 프로젝트에는 Microsoft Open Source Code of Conduct(Microsoft 오픈 소스 준수 사항)가 적용됩니다. 자세한 내용은 Code of Conduct FAQ(규정 FAQ)를 참조하세요. 또는 추가 질문이나 의견은 opencode@microsoft.com으로 문의하세요.