azure-ai-textanalytics


Nameazure-ai-textanalytics JSON
Version 5.3.0 PyPI version JSON
download
home_pagehttps://github.com/Azure/azure-sdk-for-python
SummaryMicrosoft Azure Text Analytics Client Library for Python
upload_time2023-06-15 21:14:32
maintainerNone
docs_urlNone
authorMicrosoft Corporation
requires_python>=3.7
licenseMIT License
keywords azure azure sdk text analytics cognitive services natural language processing
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            # Azure Text Analytics client library for Python

The Azure Cognitive Service for Language is a cloud-based service that provides Natural Language Processing (NLP) features for understanding and analyzing text, and includes the following main features:

- Sentiment Analysis
- Named Entity Recognition
- Language Detection
- Key Phrase Extraction
- Entity Linking
- Multiple Analysis
- Personally Identifiable Information (PII) Detection
- Text Analytics for Health
- Custom Named Entity Recognition
- Custom Text Classification
- Extractive Text Summarization
- Abstractive Text Summarization

[Source code][source_code]
| [Package (PyPI)][ta_pypi]
| [Package (Conda)](https://anaconda.org/microsoft/azure-ai-textanalytics/)
| [API reference documentation][ta_ref_docs]
| [Product documentation][language_product_documentation]
| [Samples][ta_samples]

## Getting started

### Prerequisites

- Python 3.7 later is required to use this package.
- You must have an [Azure subscription][azure_subscription] and a
  [Cognitive Services or Language service resource][ta_or_cs_resource] to use this package.

#### Create a Cognitive Services or Language service resource

The Language service supports both [multi-service and single-service access][multi_and_single_service].
Create a Cognitive Services resource if you plan to access multiple cognitive services under a single endpoint/key. For Language service access only, create a Language service resource.
You can create the resource using the [Azure Portal][azure_portal_create_ta_resource] or [Azure CLI][azure_cli] following the steps in [this document][azure_cli_create_ta_resource].

Interaction with the service using the client library begins with a [client](#textanalyticsclient "TextAnalyticsClient").
To create a client object, you will need the Cognitive Services or Language service `endpoint` to
your resource and a `credential` that allows you access:

```python
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)
```

Note that for some Cognitive Services resources the endpoint might look different from the above code snippet.
For example, `https://<region>.api.cognitive.microsoft.com/`.

### Install the package

Install the Azure Text Analytics client library for Python with [pip][pip]:

```bash
pip install azure-ai-textanalytics
```

<!-- SNIPPET:sample_authentication.create_ta_client_with_key -->

```python
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))
```

<!-- END SNIPPET -->

> Note that `5.2.X` and newer targets the Azure Cognitive Service for Language APIs. These APIs include the text analysis and natural language processing features found in the previous versions of the Text Analytics client library.
In addition, the service API has changed from semantic to date-based versioning. This version of the client library defaults to the latest supported API version, which currently is `2023-04-01`.

This table shows the relationship between SDK versions and supported API versions of the service

| SDK version  | Supported API version of service  |
| ------------ | --------------------------------- |
| 5.3.X - Latest stable release | 3.0, 3.1, 2022-05-01, 2023-04-01 (default) |
| 5.2.X  | 3.0, 3.1, 2022-05-01 (default) |
| 5.1.0  | 3.0, 3.1 (default) |
| 5.0.0  | 3.0 |

API version can be selected by passing the [api_version][text_analytics_client] keyword argument into the client.
For the latest Language service features, consider selecting the most recent beta API version. For production scenarios, the latest stable version is recommended. Setting to an older version may result in reduced feature compatibility.

### Authenticate the client

#### Get the endpoint

You can find the endpoint for your Language service resource using the
[Azure Portal][azure_portal_get_endpoint]
or [Azure CLI][azure_cli_endpoint_lookup]:

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

#### Get the API Key

You can get the [API key][cognitive_authentication_api_key] from the Cognitive Services or Language service resource in the [Azure Portal][azure_portal_get_endpoint].
Alternatively, you can use [Azure CLI][azure_cli_endpoint_lookup] snippet below to get the API key of your resource.

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

#### Create a TextAnalyticsClient with an API Key Credential

Once you have the value for the API key, you can pass it as a string into an instance of [AzureKeyCredential][azure-key-credential]. Use the key as the credential parameter
to authenticate the client:

<!-- SNIPPET:sample_authentication.create_ta_client_with_key -->

```python
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))
```

<!-- END SNIPPET -->

#### Create a TextAnalyticsClient with an Azure Active Directory Credential

To use an [Azure Active Directory (AAD) token credential][cognitive_authentication_aad],
provide an instance of the desired credential type obtained from the
[azure-identity][azure_identity_credentials] library.
Note that regional endpoints do not support AAD authentication. Create a [custom subdomain][custom_subdomain]
name for your resource in order to use this type of authentication.

Authentication with AAD requires some initial setup:

- [Install azure-identity][install_azure_identity]
- [Register a new AAD application][register_aad_app]
- [Grant access][grant_role_access] to the Language service by assigning the `"Cognitive Services Language Reader"` role to your service principal.

After setup, you can choose which type of [credential][azure_identity_credentials] from azure.identity to use.
As an example, [DefaultAzureCredential][default_azure_credential]
can be used to authenticate the client:

Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables:
AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET

Use the returned token credential to authenticate the client:

<!-- SNIPPET:sample_authentication.create_ta_client_with_aad -->

```python
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)
```

<!-- END SNIPPET -->

## Key concepts

### TextAnalyticsClient

The Text Analytics client library provides a [TextAnalyticsClient][text_analytics_client] to do analysis on [batches of documents](#examples "Examples").
It provides both synchronous and asynchronous operations to access a specific use of text analysis, such as language detection or key phrase extraction.

### Input

A **document** is a single unit to be analyzed by the predictive models in the Language service.
The input for each operation is passed as a **list** of documents.

Each document can be passed as a string in the list, e.g.

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

or, if you wish to pass in a per-item document `id` or `language`/`country_hint`, they can be passed as a list of
[DetectLanguageInput][detect_language_input] or
[TextDocumentInput][text_document_input]
or a dict-like representation of the object:

```python
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!"},
]
```

See [service limitations][service_limits] for the input, including document length limits, maximum batch size, and supported text encoding.

### Return Value

The return value for a single document can be a result or error object.
A heterogeneous list containing a collection of result and error objects is returned from each operation.
These results/errors are index-matched with the order of the provided documents.

A **result**, such as [AnalyzeSentimentResult][analyze_sentiment_result],
is the result of a text analysis operation and contains a prediction or predictions about a document input.

The **error** object, [DocumentError][document_error], indicates that the service had trouble processing the document and contains
the reason it was unsuccessful.

### Document Error Handling

You can filter for a result or error object in the list by using the `is_error` attribute. For a result object this is always `False` and for a
[DocumentError][document_error] this is `True`.

For example, to filter out all DocumentErrors you might use list comprehension:

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

You can also use the `kind` attribute to filter between result types:

```python
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 Operations

Long-running operations are operations which consist of an initial request sent to the service to start an operation,
followed by polling the service at intervals to determine whether the operation has completed or failed, and if it has
succeeded, to get the result.

Methods that support healthcare analysis, custom text analysis, or multiple analyses are modeled as long-running operations.
The client exposes a `begin_<method-name>` method that returns a poller object. Callers should wait
for the operation to complete by calling `result()` on the poller object returned from the `begin_<method-name>` method.
Sample code snippets are provided to illustrate using long-running operations [below](#examples "Examples").

## Examples

The following section provides several code snippets covering some of the most common Language service tasks, including:

- [Analyze Sentiment](#analyze-sentiment "Analyze sentiment")
- [Recognize Entities](#recognize-entities "Recognize entities")
- [Recognize Linked Entities](#recognize-linked-entities "Recognize linked entities")
- [Recognize PII Entities](#recognize-pii-entities "Recognize pii entities")
- [Extract Key Phrases](#extract-key-phrases "Extract key phrases")
- [Detect Language](#detect-language "Detect language")
- [Healthcare Entities Analysis](#healthcare-entities-analysis "Healthcare Entities Analysis")
- [Multiple Analysis](#multiple-analysis "Multiple analysis")
- [Custom Entity Recognition][recognize_custom_entities_sample]
- [Custom Single Label Classification][single_label_classify_sample]
- [Custom Multi Label Classification][multi_label_classify_sample]
- [Extractive Summarization][extract_summary_sample]
- [Abstractive Summarization][abstract_summary_sample]

### Analyze Sentiment

[analyze_sentiment][analyze_sentiment] looks at its input text and determines whether its sentiment is positive, negative, neutral or mixed. It's response includes per-sentence sentiment analysis and confidence scores.

<!-- SNIPPET:sample_analyze_sentiment.analyze_sentiment -->

```python
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}")
```

<!-- END SNIPPET -->

The returned response is a heterogeneous list of result and error objects: list[[AnalyzeSentimentResult][analyze_sentiment_result], [DocumentError][document_error]]

Please refer to the service documentation for a conceptual discussion of [sentiment analysis][sentiment_analysis]. To see how to conduct more granular analysis into the opinions related to individual aspects (such as attributes of a product or service) in a text, see [here][opinion_mining_sample].

### Recognize Entities

[recognize_entities][recognize_entities] recognizes and categories entities in its input text as people, places, organizations, date/time, quantities, percentages, currencies, and more.

<!-- SNIPPET:sample_recognize_entities.recognize_entities -->

```python
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)
        )
    )
```

<!-- END SNIPPET -->

The returned response is a heterogeneous list of result and error objects: list[[RecognizeEntitiesResult][recognize_entities_result], [DocumentError][document_error]]

Please refer to the service documentation for a conceptual discussion of [named entity recognition][named_entity_recognition]
and [supported types][named_entity_categories].

### Recognize Linked Entities

[recognize_linked_entities][recognize_linked_entities] recognizes and disambiguates the identity of each entity found in its input text (for example,
determining whether an occurrence of the word Mars refers to the planet, or to the
Roman god of war). Recognized entities are associated with URLs to a well-known knowledge base, like Wikipedia.

<!-- SNIPPET:sample_recognize_linked_entities.recognize_linked_entities -->

```python
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
```

<!-- END SNIPPET -->

The returned response is a heterogeneous list of result and error objects: list[[RecognizeLinkedEntitiesResult][recognize_linked_entities_result], [DocumentError][document_error]]

Please refer to the service documentation for a conceptual discussion of [entity linking][linked_entity_recognition]
and [supported types][linked_entities_categories].

### Recognize PII Entities

[recognize_pii_entities][recognize_pii_entities] recognizes and categorizes Personally Identifiable Information (PII) entities in its input text, such as
Social Security Numbers, bank account information, credit card numbers, and more.

<!-- SNIPPET:sample_recognize_pii_entities.recognize_pii_entities -->

```python
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
        ))
```

<!-- END SNIPPET -->

The returned response is a heterogeneous list of result and error objects: list[[RecognizePiiEntitiesResult][recognize_pii_entities_result], [DocumentError][document_error]]

Please refer to the service documentation for [supported PII entity types][pii_entity_categories].

Note: The Recognize PII Entities service is available in API version v3.1 and newer.

### Extract Key Phrases

[extract_key_phrases][extract_key_phrases] determines the main talking points in its input text. For example, for the input text "The food was delicious and there were wonderful staff", the API returns: "food" and "wonderful staff".

<!-- SNIPPET:sample_extract_key_phrases.extract_key_phrases -->

```python
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)
        ))
```

<!-- END SNIPPET -->

The returned response is a heterogeneous list of result and error objects: list[[ExtractKeyPhrasesResult][extract_key_phrases_result], [DocumentError][document_error]]

Please refer to the service documentation for a conceptual discussion of [key phrase extraction][key_phrase_extraction].

### Detect Language

[detect_language][detect_language] determines the language of its input text, including the confidence score of the predicted language.

<!-- SNIPPET:sample_detect_language.detect_language -->

```python
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
    ))
```

<!-- END SNIPPET -->

The returned response is a heterogeneous list of result and error objects: list[[DetectLanguageResult][detect_language_result], [DocumentError][document_error]]

Please refer to the service documentation for a conceptual discussion of [language detection][language_detection]
and [language and regional support][language_and_regional_support].

### Healthcare Entities Analysis

[Long-running operation](#long-running-operations) [begin_analyze_healthcare_entities][analyze_healthcare_entities] extracts entities recognized within the healthcare domain, and identifies relationships between entities within the input document and links to known sources of information in various well known databases, such as UMLS, CHV, MSH, etc.

<!-- SNIPPET:sample_analyze_healthcare_entities.analyze_healthcare_entities -->

```python
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
]
```

<!-- END SNIPPET -->

Note: Healthcare Entities Analysis is only available with API version v3.1 and newer.

### Multiple Analysis

[Long-running operation](#long-running-operations) [begin_analyze_actions][analyze_actions] performs multiple analyses over one set of documents in a single request. Currently it is supported using any combination of the following Language APIs in a single request:

- Entities Recognition
- PII Entities Recognition
- Linked Entity Recognition
- Key Phrase Extraction
- Sentiment Analysis
- Custom Entity Recognition (API version 2022-05-01 and newer)
- Custom Single Label Classification (API version 2022-05-01 and newer)
- Custom Multi Label Classification (API version 2022-05-01 and newer)
- Healthcare Entities Analysis (API version 2022-05-01 and newer)
- Extractive Summarization (API version 2023-04-01 and newer)
- Abstractive Summarization (API version 2023-04-01 and newer)

<!-- SNIPPET:sample_analyze_actions.analyze -->

```python
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("------------------------------------------")
```

<!-- END SNIPPET -->

The returned response is an object encapsulating multiple iterables, each representing results of individual analyses.

Note: Multiple analysis is available in API version v3.1 and newer.

## Optional Configuration

Optional keyword arguments can be passed in at the client and per-operation level.
The azure-core [reference documentation][azure_core_ref_docs]
describes available configurations for retries, logging, transport protocols, and more.

## Troubleshooting

### General

The Text Analytics client will raise exceptions defined in [Azure Core][azure_core].

### Logging

This library uses the standard
[logging][python_logging] library for logging.
Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFO
level.

Detailed DEBUG level logging, including request/response bodies and unredacted
headers, can be enabled on a client with the `logging_enable` keyword argument:

```python
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."])
```

Similarly, `logging_enable` can enable detailed logging for a single operation,
even when it isn't enabled for the client:

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

## Next steps

### More sample code

These code samples show common scenario operations with the Azure Text Analytics client library.

Authenticate the client with a Cognitive Services/Language service API key or a token credential from [azure-identity][azure_identity]:

- [sample_authentication.py][sample_authentication] ([async version][sample_authentication_async])

Common scenarios

- Analyze sentiment: [sample_analyze_sentiment.py][analyze_sentiment_sample] ([async version][analyze_sentiment_sample_async])
- Recognize entities: [sample_recognize_entities.py][recognize_entities_sample] ([async version][recognize_entities_sample_async])
- Recognize personally identifiable information: [sample_recognize_pii_entities.py][recognize_pii_entities_sample] ([async version][recognize_pii_entities_sample_async])
- Recognize linked entities: [sample_recognize_linked_entities.py][recognize_linked_entities_sample] ([async version][recognize_linked_entities_sample_async])
- Extract key phrases: [sample_extract_key_phrases.py][extract_key_phrases_sample] ([async version][extract_key_phrases_sample_async])
- Detect language: [sample_detect_language.py][detect_language_sample] ([async version][detect_language_sample_async])
- Healthcare Entities Analysis: [sample_analyze_healthcare_entities.py][analyze_healthcare_entities_sample] ([async version][analyze_healthcare_entities_sample_async])
- Multiple Analysis: [sample_analyze_actions.py][analyze_sample] ([async version][analyze_sample_async])
- Custom Entity Recognition: [sample_recognize_custom_entities.py][recognize_custom_entities_sample] ([async_version][recognize_custom_entities_sample_async])
- Custom Single Label Classification: [sample_single_label_classify.py][single_label_classify_sample] ([async_version][single_label_classify_sample_async])
- Custom Multi Label Classification: [sample_multi_label_classify.py][multi_label_classify_sample] ([async_version][multi_label_classify_sample_async])
- Extractive text summarization: [sample_extract_summary.py][extract_summary_sample] ([async version][extract_summary_sample_async])
- Abstractive text summarization: [sample_abstract_summary.py][abstract_summary_sample] ([async version][abstract_summary_sample_async])

Advanced scenarios

- Opinion Mining: [sample_analyze_sentiment_with_opinion_mining.py][opinion_mining_sample] ([async_version][opinion_mining_sample_async])

### Additional documentation

For more extensive documentation on Azure Cognitive Service for Language, see the [Language Service documentation][language_product_documentation] on docs.microsoft.com.

## Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit [cla.microsoft.com][cla].

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the [Microsoft Open Source Code of Conduct][code_of_conduct]. For more information see the [Code of Conduct FAQ][coc_faq] or contact [opencode@microsoft.com][coc_contact] with any additional questions or comments.

<!-- LINKS -->

[source_code]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics
[ta_pypi]: https://pypi.org/project/azure-ai-textanalytics/
[ta_ref_docs]: https://aka.ms/azsdk-python-textanalytics-ref-docs
[ta_samples]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples
[language_product_documentation]: https://docs.microsoft.com/azure/cognitive-services/language-service
[azure_subscription]: https://azure.microsoft.com/free/
[ta_or_cs_resource]: https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account?tabs=multiservice%2Cwindows
[pip]: https://pypi.org/project/pip/
[azure_portal_create_ta_resource]: https://ms.portal.azure.com/#create/Microsoft.CognitiveServicesTextAnalytics
[azure_cli]: https://docs.microsoft.com/cli/azure
[azure_cli_create_ta_resource]: https://learn.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account-cli
[multi_and_single_service]: https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account?tabs=multiservice%2Cwindows
[azure_cli_endpoint_lookup]: https://docs.microsoft.com/cli/azure/cognitiveservices/account?view=azure-cli-latest#az-cognitiveservices-account-show
[azure_portal_get_endpoint]: https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account?tabs=multiservice%2Cwindows#get-the-keys-for-your-resource
[cognitive_authentication]: https://docs.microsoft.com/azure/cognitive-services/authentication
[cognitive_authentication_api_key]: https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account?tabs=multiservice%2Cwindows#get-the-keys-for-your-resource
[install_azure_identity]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#install-the-package
[register_aad_app]: https://docs.microsoft.com/azure/cognitive-services/authentication#assign-a-role-to-a-service-principal
[grant_role_access]: https://docs.microsoft.com/azure/cognitive-services/authentication#assign-a-role-to-a-service-principal
[cognitive_custom_subdomain]: https://docs.microsoft.com/azure/cognitive-services/cognitive-services-custom-subdomains
[custom_subdomain]: https://docs.microsoft.com/azure/cognitive-services/authentication#create-a-resource-with-a-custom-subdomain
[cognitive_authentication_aad]: https://docs.microsoft.com/azure/cognitive-services/authentication#authenticate-with-azure-active-directory
[azure_identity_credentials]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#credentials
[default_azure_credential]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#defaultazurecredential
[service_limits]: https://aka.ms/azsdk/textanalytics/data-limits
[azure-key-credential]: https://aka.ms/azsdk-python-core-azurekeycredential
[document_error]: https://aka.ms/azsdk-python-textanalytics-documenterror
[detect_language_result]: https://aka.ms/azsdk-python-textanalytics-detectlanguageresult
[recognize_entities_result]: https://aka.ms/azsdk-python-textanalytics-recognizeentitiesresult
[recognize_pii_entities_result]: https://aka.ms/azsdk-python-textanalytics-recognizepiientitiesresult
[recognize_linked_entities_result]: https://aka.ms/azsdk-python-textanalytics-recognizelinkedentitiesresult
[analyze_sentiment_result]: https://aka.ms/azsdk-python-textanalytics-analyzesentimentresult
[extract_key_phrases_result]: https://aka.ms/azsdk-python-textanalytics-extractkeyphrasesresult
[text_document_input]: https://aka.ms/azsdk-python-textanalytics-textdocumentinput
[detect_language_input]: https://aka.ms/azsdk-python-textanalytics-detectlanguageinput
[text_analytics_client]: https://aka.ms/azsdk-python-textanalytics-textanalyticsclient
[analyze_sentiment]: https://aka.ms/azsdk-python-textanalytics-analyzesentiment
[analyze_actions]: https://aka.ms/azsdk/python/docs/ref/textanalytics#azure.ai.textanalytics.TextAnalyticsClient.begin_analyze_actions
[analyze_healthcare_entities]: https://aka.ms/azsdk/python/docs/ref/textanalytics#azure.ai.textanalytics.TextAnalyticsClient.begin_analyze_healthcare_entities
[recognize_entities]: https://aka.ms/azsdk-python-textanalytics-recognizeentities
[recognize_pii_entities]: https://aka.ms/azsdk-python-textanalytics-recognizepiientities
[recognize_linked_entities]: https://aka.ms/azsdk-python-textanalytics-recognizelinkedentities
[extract_key_phrases]: https://aka.ms/azsdk-python-textanalytics-extractkeyphrases
[detect_language]: https://aka.ms/azsdk-python-textanalytics-detectlanguage
[language_detection]: https://docs.microsoft.com/azure/cognitive-services/language-service/language-detection/overview
[language_and_regional_support]: https://docs.microsoft.com/azure/cognitive-services/language-service/language-detection/language-support
[sentiment_analysis]: https://docs.microsoft.com/azure/cognitive-services/language-service/sentiment-opinion-mining/overview
[key_phrase_extraction]: https://docs.microsoft.com/azure/cognitive-services/language-service/key-phrase-extraction/overview
[linked_entities_categories]: https://aka.ms/taner
[linked_entity_recognition]: https://docs.microsoft.com/azure/cognitive-services/language-service/entity-linking/overview
[pii_entity_categories]: https://aka.ms/azsdk/language/pii
[named_entity_recognition]: https://docs.microsoft.com/azure/cognitive-services/language-service/named-entity-recognition/overview
[named_entity_categories]: https://aka.ms/taner
[azure_core_ref_docs]: https://aka.ms/azsdk-python-core-policies
[azure_core]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/README.md
[azure_identity]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity
[python_logging]: https://docs.python.org/3/library/logging.html
[sample_authentication]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_authentication.py
[sample_authentication_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_authentication_async.py
[detect_language_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_detect_language.py
[detect_language_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_detect_language_async.py
[analyze_sentiment_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_analyze_sentiment.py
[analyze_sentiment_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_analyze_sentiment_async.py
[extract_key_phrases_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_extract_key_phrases.py
[extract_key_phrases_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_extract_key_phrases_async.py
[recognize_entities_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_recognize_entities.py
[recognize_entities_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_recognize_entities_async.py
[recognize_linked_entities_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_recognize_linked_entities.py
[recognize_linked_entities_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_recognize_linked_entities_async.py
[recognize_pii_entities_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_recognize_pii_entities.py
[recognize_pii_entities_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_async.py
[analyze_healthcare_entities_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_analyze_healthcare_entities.py
[analyze_healthcare_entities_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_analyze_healthcare_entities_async.py
[analyze_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_analyze_actions.py
[analyze_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_analyze_actions_async.py
[opinion_mining_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_analyze_sentiment_with_opinion_mining.py
[opinion_mining_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_analyze_sentiment_with_opinion_mining_async.py
[recognize_custom_entities_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_recognize_custom_entities.py
[recognize_custom_entities_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_recognize_custom_entities_async.py
[single_label_classify_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_single_label_classify.py
[single_label_classify_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_single_label_classify_async.py
[multi_label_classify_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_multi_label_classify.py
[multi_label_classify_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_multi_label_classify_async.py
[healthcare_action_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_analyze_healthcare_action.py
[extract_summary_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_extract_summary.py
[extract_summary_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_extract_summary_async.py
[abstract_summary_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_abstract_summary.py
[abstract_summary_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_abstract_summary_async.py
[cla]: https://cla.microsoft.com
[code_of_conduct]: https://opensource.microsoft.com/codeofconduct/
[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/
[coc_contact]: mailto:opencode@microsoft.com


# Release History

## 5.3.0 (2023-06-15)

This version of the client library defaults to the service API version `2023-04-01`.

### Breaking Changes

> Note: The following changes are only breaking from the previous beta. They are not breaking against previous stable versions.

- Renamed model `ExtractSummaryAction` to `ExtractiveSummaryAction`.
- Renamed model `ExtractSummaryResult` to `ExtractiveSummaryResult`.
- Renamed client method `begin_abstractive_summary` to `begin_abstract_summary`.
- Removed `dynamic_classification` client method and related types: `DynamicClassificationResult` and `ClassificationType`.
- Removed keyword arguments `fhir_version` and `document_type` from `begin_analyze_healthcare_entities` and `AnalyzeHealthcareEntitiesAction`.
- Removed property `fhir_bundle` from `AnalyzeHealthcareEntitiesResult`. 
- Removed enum `HealthcareDocumentType`.
- Removed property `resolutions` from `CategorizedEntity`.
- Removed models and enums related to resolutions: `ResolutionKind`, `AgeResolution`, `AreaResolution`,
  `CurrencyResolution`, `DateTimeResolution`, `InformationResolution`, `LengthResolution`,
  `NumberResolution`, `NumericRangeResolution`, `OrdinalResolution`, `SpeedResolution`, `TemperatureResolution`,
  `TemporalSpanResolution`, `VolumeResolution`, `WeightResolution`, `AgeUnit`, `AreaUnit`, `TemporalModifier`,
  `InformationUnit`, `LengthUnit`, `NumberKind`, `RangeKind`, `RelativeTo`, `SpeedUnit`, `TemperatureUnit`,
  `VolumeUnit`, `DateTimeSubKind`, and `WeightUnit`.
- Removed property `detected_language` from `RecognizeEntitiesResult`, `RecognizePiiEntitiesResult`, `AnalyzeHealthcareEntitiesResult`,
  `ExtractKeyPhrasesResult`, `RecognizeLinkedEntitiesResult`, `AnalyzeSentimentResult`, `RecognizeCustomEntitiesResult`,
  `ClassifyDocumentResult`, `ExtractSummaryResult`, and `AbstractSummaryResult`.
- Removed property `script` from `DetectedLanguage`.

### Features Added

- New enum values added for `HealthcareEntityCategory` and `HealthcareEntityRelation`.

## 5.3.0b2 (2023-03-07)

This version of the client library defaults to the service API version `2022-10-01-preview`.

### Features Added

- Added `begin_extract_summary` client method to perform extractive summarization on documents.
- Added `begin_abstractive_summary` client method to perform abstractive summarization on documents.

### Breaking Changes

- Removed models `BaseResolution` and `BooleanResolution`.
- Removed enum value `BooleanResolution` from `ResolutionKind`.
- Renamed model `AbstractSummaryAction` to `AbstractiveSummaryAction`.
- Renamed model `AbstractSummaryResult` to `AbstractiveSummaryResult`.
- Removed keyword argument `autodetect_default_language` from long-running operation APIs.

### Other Changes

 - Improved static typing in the client library. 

## 5.3.0b1 (2022-11-17)

This version of the client library defaults to the service API version `2022-10-01-preview`.

### Features Added
- Added the Extractive Summarization feature and related models: `ExtractSummaryAction`, `ExtractSummaryResult`, and `SummarySentence`.
  Access the feature through the `begin_analyze_actions` API.
- Added keyword arguments `fhir_version` and `document_type` to `begin_analyze_healthcare_entities` and `AnalyzeHealthcareEntitiesAction`.
- Added property `fhir_bundle` to `AnalyzeHealthcareEntitiesResult`.
- Added property `confidence_score` to `HealthcareRelation`.
- Added enum `HealthcareDocumentType`.
- Added property `resolutions` to `CategorizedEntity`.
- Added models and enums related to resolutions: `BaseResolution`, `ResolutionKind`, `AgeResolution`, `AreaResolution`, 
  `BooleanResolution`, `CurrencyResolution`, `DateTimeResolution`, `InformationResolution`, `LengthResolution`,
  `NumberResolution`, `NumericRangeResolution`, `OrdinalResolution`, `SpeedResolution`, `TemperatureResolution`,
  `TemporalSpanResolution`, `VolumeResolution`, `WeightResolution`, `AgeUnit`, `AreaUnit`, `TemporalModifier`,
  `InformationUnit`, `LengthUnit`, `NumberKind`, `RangeKind`, `RelativeTo`, `SpeedUnit`, `TemperatureUnit`,
  `VolumeUnit`, `DateTimeSubKind`, and `WeightUnit`.
- Added the Abstractive Summarization feature and related models: `AbstractSummaryAction`, `AbstractSummaryResult`, `AbstractiveSummary`,
  and `SummaryContext`. Access the feature through the `begin_analyze_actions` API.
- Added automatic language detection to long-running operation APIs. Pass `auto` into the document `language` hint to use this feature.
- Added `autodetect_default_language` to long-running operation APIs. Pass as the default/fallback language for automatic language detection.
- Added property `detected_language` to `RecognizeEntitiesResult`, `RecognizePiiEntitiesResult`, `AnalyzeHealthcareEntitiesResult`,
  `ExtractKeyPhrasesResult`, `RecognizeLinkedEntitiesResult`, `AnalyzeSentimentResult`, `RecognizeCustomEntitiesResult`,
  `ClassifyDocumentResult`, `ExtractSummaryResult`, and `AbstractSummaryResult` to indicate the language detected by automatic language detection.
- Added property `script` to `DetectedLanguage` to indicate the script of the input document.
- Added the `dynamic_classification` client method to perform dynamic classification on documents without needing to train a model.

### Other Changes
- Removed dependency on `msrest`.

## 5.2.1 (2022-10-26)

### Bugs Fixed
- Returns a more helpful message in the document error when all documents fail for an action in the `begin_analyze_actions` API.

## 5.2.0 (2022-09-08)

### Other Changes

This version of the client library marks a stable release and defaults to the service API version `2022-05-01`.
Includes all changes from `5.2.0b1` to `5.2.0b5`.

## 5.2.0b5 (2022-08-11)

The version of this client library defaults to the API version `2022-05-01`.

### Features Added

- Added `begin_recognize_custom_entities` client method to recognize custom named entities in documents.
- Added `begin_single_label_classify` client method to perform custom single label classification on documents.
- Added `begin_multi_label_classify` client method to perform custom multi label classification on documents.
- Added property `details` on returned poller objects which contain long-running operation metadata.
- Added `TextAnalysisLROPoller` and `AsyncTextAnalysisLROPoller` protocols to describe the return types from long-running operations.
- Added `cancel` method on the poller objects. Call it to cancel a long-running operation that's in progress.
- Added property `kind` to `RecognizeEntitiesResult`, `RecognizePiiEntitiesResult`, `AnalyzeHealthcareEntitiesResult`,
  `DetectLanguageResult`, `ExtractKeyPhrasesResult`, `RecognizeLinkedEntitiesResult`, `AnalyzeSentimentResult`,
  `RecognizeCustomEntitiesResult`, `ClassifyDocumentResult`, and `DocumentError`.
- Added enum `TextAnalysisKind`.

### Breaking Changes

- Removed the Extractive Text Summarization feature and related models: `ExtractSummaryAction`, `ExtractSummaryResult`, and `SummarySentence`. To access this beta feature, install the `5.2.0b4` version of the client library.
- Removed the `FHIR` feature and related keyword argument and property: `fhir_version` and `fhir_bundle`. To access this beta feature, install the `5.2.0b4` version of the client library.
- `SingleCategoryClassifyResult` and `MultiCategoryClassifyResult` models have been merged into one model: `ClassifyDocumentResult`.
- Renamed `SingleCategoryClassifyAction` to `SingleLabelClassifyAction`
- Renamed `MultiCategoryClassifyAction` to `MultiLabelClassifyAction`.

### Bugs Fixed

- A `HttpResponseError` will be immediately raised when the call quota volume is exceeded in a `F0` tier Language resource.

### Other Changes

- Python 3.6 is no longer supported. Please use Python version 3.7 or later. For more details, see [Azure SDK for Python version support policy](https://github.com/Azure/azure-sdk-for-python/wiki/Azure-SDKs-Python-version-support-policy).


## 5.2.0b4 (2022-05-18)

Note that this is the first version of the client library that targets the Azure Cognitive Service for Language APIs which includes the existing text analysis and natural language processing features found in the Text Analytics client library.
In addition, the service API has changed from semantic to date-based versioning. This version of the client library defaults to the latest supported API version, which currently is `2022-04-01-preview`. Support for `v3.2-preview.2` is removed, however, all functionalities are included in the latest version.

### Features Added

- Added support for Healthcare Entities Analysis through the `begin_analyze_actions` API with the `AnalyzeHealthcareEntitiesAction` type.
- Added keyword argument `fhir_version` to `begin_analyze_healthcare_entities` and `AnalyzeHealthcareEntitiesAction`. Use the keyword to indicate the version for the `fhir_bundle` contained on the `AnalyzeHealthcareEntitiesResult`.
- Added property `fhir_bundle` to `AnalyzeHealthcareEntitiesResult`.
- Added keyword argument `display_name` to `begin_analyze_healthcare_entities`.

## 5.2.0b3 (2022-03-08)

### Bugs Fixed
- `string_index_type` now correctly defaults to the Python default `UnicodeCodePoint` for `AnalyzeSentimentAction` and `RecognizeCustomEntitiesAction`.
- Fixed a bug in `begin_analyze_actions` where incorrect action types were being sent in the request if targeting the older API version `v3.1` in the beta version of the client library.
- `string_index_type` option `Utf16CodePoint` is corrected to `Utf16CodeUnit`.

### Other Changes
- Python 2.7 is no longer supported. Please use Python version 3.6 or later.

## 5.2.0b2 (2021-11-02)

This version of the SDK defaults to the latest supported API version, which currently is `v3.2-preview.2`.

### Features Added
- Added support for Custom Entities Recognition through the `begin_analyze_actions` API with the `RecognizeCustomEntitiesAction` and `RecognizeCustomEntitiesResult` types.
- Added support for Custom Single Classification through the `begin_analyze_actions` API with the `SingleCategoryClassifyAction` and `SingleCategoryClassifyActionResult` types.
- Added support for Custom Multi Classification through the `begin_analyze_actions` API with the `MultiCategoryClassifyAction` and `MultiCategoryClassifyActionResult` types.
- Multiple of the same action type is now supported with `begin_analyze_actions`.

### Bugs Fixed
- Restarting a long-running operation from a saved state is now supported for the `begin_analyze_actions` and `begin_recognize_healthcare_entities` methods.
- In the event of an action level error, available partial results are now returned for any successful actions in `begin_analyze_actions`.

### Other Changes
- Package requires [azure-core](https://pypi.org/project/azure-core/) version 1.19.1 or greater

## 5.2.0b1 (2021-08-09)

This version of the SDK defaults to the latest supported API version, which currently is `v3.2-preview.1`.

### Features Added
- Added support for Extractive Summarization actions through the `ExtractSummaryAction` type.

### Bugs Fixed
- `RecognizePiiEntitiesAction` option `disable_service_logs` now correctly defaults to `True`.

### Other Changes
- Python 3.5 is no longer supported.

## 5.1.0 (2021-07-07)

This version of the SDK defaults to the latest supported API version, which currently is `v3.1`.
Includes all changes from `5.1.0b1` to `5.1.0b7`.

Note: this version will be the last to officially support Python 3.5, future versions will require Python 2.7 or Python 3.6+.

### Features Added

- Added `catagories_filter` to `RecognizePiiEntitiesAction`
- Added `HealthcareEntityCategory`
- Added AAD support for the `begin_analyze_healthcare_entities` methods.

### Breaking Changes

- Changed: the response structure of `being_analyze_actions`. Now, we return a list of results, where each result is a list of the action results for the document, in the order the documents and actions were passed.
- Changed: `begin_analyze_actions` now accepts a single action per type. A `ValueError` is raised if duplicate actions are passed.
- Removed: `AnalyzeActionsType`
- Removed: `AnalyzeActionsResult`
- Removed: `AnalyzeActionsError`
- Removed: `HealthcareEntityRelationRoleType`
- Changed: renamed `HealthcareEntityRelationType` to `HealthcareEntityRelation`
- Changed: renamed `PiiEntityCategoryType` to `PiiEntityCategory`
- Changed: renamed `PiiEntityDomainType` to `PiiEntityDomain`

## 5.1.0b7 (2021-05-18)

**Breaking Changes**
- Renamed `begin_analyze_batch_actions` to `begin_analyze_actions`.
- Renamed `AnalyzeBatchActionsType` to `AnalyzeActionsType`.
- Renamed `AnalyzeBatchActionsResult` to `AnalyzeActionsResult`.
- Renamed `AnalyzeBatchActionsError` to `AnalyzeActionsError`.
- Renamed `AnalyzeHealthcareEntitiesResultItem` to `AnalyzeHealthcareEntitiesResult`.
- Fixed `AnalyzeHealthcareEntitiesResult`'s `statistics` to be the correct type, `TextDocumentStatistics`
- Remove `RequestStatistics`, use `TextDocumentBatchStatistics` instead

**New Features**
- Added enums `EntityConditionality`, `EntityCertainty`, and `EntityAssociation`.
- Added `AnalyzeSentimentAction` as a supported action type for `begin_analyze_batch_actions`.
- Added kwarg `disable_service_logs`. If set to true, you opt-out of having your text input logged on the service side for troubleshooting.

## 5.1.0b6 (2021-03-09)

**Breaking Changes**
- By default, we now target the service's `v3.1-preview.4` endpoint through enum value `TextAnalyticsApiVersion.V3_1_PREVIEW`
- Removed property `related_entities` on `HealthcareEntity` and added `entity_relations` onto the document response level for healthcare
- Renamed properties `aspect` and `opinions` to `target` and `assessments` respectively in class `MinedOpinion`.
- Renamed classes `AspectSentiment` and `OpinionSentiment` to `TargetSentiment` and `AssessmentSentiment` respectively.

**New Features**
- Added `RecognizeLinkedEntitiesAction` as a supported action type for `begin_analyze_batch_actions`.
- Added parameter `categories_filter` to the `recognize_pii_entities` client method.
- Added enum `PiiEntityCategoryType`.
- Add property `normalized_text` to `HealthcareEntity`. This property is a normalized version of the `text` property that already
exists on the `HealthcareEntity`
- Add property `assertion` onto `HealthcareEntity`. This contains assertions about the entity itself, i.e. if the entity represents a diagnosis,
is this diagnosis conditional on a symptom?

**Known Issues**

- `begin_analyze_healthcare_entities` is currently in gated preview and can not be used with AAD credentials. For more information, see [the Text Analytics for Health documentation](https://docs.microsoft.com/azure/cognitive-services/text-analytics/how-tos/text-analytics-for-health?tabs=ner#request-access-to-the-public-preview).
- At time of this SDK release, the service is not respecting the value passed through `model_version` to `begin_analyze_healthcare_entities`, it only uses the latest model.

## 5.1.0b5 (2021-02-10)

**Breaking Changes**

- Rename `begin_analyze` to `begin_analyze_batch_actions`.
- Now instead of separate parameters for all of the different types of actions you can pass to `begin_analyze_batch_actions`, we accept one parameter `actions`,
which is a list of actions you would like performed. The results of the actions are returned in the same order as when inputted.
- The response object from `begin_analyze_batch_actions` has also changed. Now, after the completion of your long running operation, we return a paged iterable
of action results, in the same order they've been inputted. The actual document results for each action are included under property `document_results` of
each action result.

**New Features**
- Renamed `begin_analyze_healthcare` to `begin_analyze_healthcare_entities`.
- Renamed `AnalyzeHealthcareResult` to `AnalyzeHealthcareEntitiesResult` and `AnalyzeHealthcareResultItem` to `AnalyzeHealthcareEntitiesResultItem`.
- Renamed `HealthcareEntityLink` to `HealthcareEntityDataSource` and renamed its properties `id` to `entity_id` and `data_source` to `name`.
- Removed `relations` from `AnalyzeHealthcareEntitiesResultItem` and added `related_entities` to `HealthcareEntity`.
- Moved the cancellation logic for the Analyze Healthcare Entities service from
the service client to the poller object returned from `begin_analyze_healthcare_entities`.
- Exposed Analyze Healthcare Entities operation metadata on the poller object returned from `begin_analyze_healthcare_entities`.
- No longer need to specify `api_version=TextAnalyticsApiVersion.V3_1_PREVIEW_3` when calling `begin_analyze` and `begin_analyze_healthcare_entities`. `begin_analyze_healthcare_entities` is still in gated preview though.
- Added a new parameter `string_index_type` to the service client methods `begin_analyze_healthcare_entities`, `analyze_sentiment`, `recognize_entities`, `recognize_pii_entities`, and `recognize_linked_entities` which tells the service how to interpret string offsets.
- Added property `length` to `CategorizedEntity`, `SentenceSentiment`, `LinkedEntityMatch`, `AspectSentiment`, `OpinionSentiment`, `PiiEntity` and
`HealthcareEntity`.

## 5.1.0b4 (2021-01-12)

**Bug Fixes**

- Package requires [azure-core](https://pypi.org/project/azure-core/) version 1.8.2 or greater


## 5.1.0b3 (2020-11-19)

**New Features**
- We have added method `begin_analyze`, which supports long-running batch process of Named Entity Recognition, Personally identifiable Information, and Key Phrase Extraction. To use, you must specify `api_version=TextAnalyticsApiVersion.V3_1_PREVIEW_3` when creating your client.
- We have added method `begin_analyze_healthcare`, which supports the service's Health API. Since the Health API is currently only available in a gated preview, you need to have your subscription on the service's allow list, and you must specify `api_version=TextAnalyticsApiVersion.V3_1_PREVIEW_3` when creating your client. Note that since this is a gated preview, AAD is not supported. More information [here](https://docs.microsoft.com/azure/cognitive-services/text-analytics/how-tos/text-analytics-for-health?tabs=ner#request-access-to-the-public-preview).


## 5.1.0b2 (2020-10-06)

**Breaking changes**
- Removed property `length` from `CategorizedEntity`, `SentenceSentiment`, `LinkedEntityMatch`, `AspectSentiment`, `OpinionSentiment`, and `PiiEntity`.
To get the length of the text in these models, just call `len()` on the `text` property.
- When a parameter or endpoint is not compatible with the API version you specify, we will now return a `ValueError` instead of a `NotImplementedError`.
- Client side validation of input is now disabled by default. This means there will be no `ValidationError`s thrown by the client SDK in the case of malformed input. The error will now be thrown by the service through an `HttpResponseError`.

## 5.1.0b1 (2020-09-17)

**New features**
- We are now targeting the service's v3.1-preview API as the default. If you would like to still use version v3.0 of the service,
pass in `v3.0` to the kwarg `api_version` when creating your TextAnalyticsClient
- We have added an API `recognize_pii_entities` which returns entities containing personally identifiable information for a batch of documents. Only available for API version v3.1-preview and up.
- Added `offset` and `length` properties for `CategorizedEntity`, `SentenceSentiment`, and `LinkedEntityMatch`. These properties are only available for API versions v3.1-preview and up.
  - `length` is the number of characters in the text of these models
  - `offset` is the offset of the text from the start of the document
- We now have added support for opinion mining. To use this feature, you need to make sure you are using the service's
v3.1-preview API. To get this support pass `show_opinion_mining` as True when calling the `analyze_sentiment` endpoint
- Add property `bing_entity_search_api_id` to the `LinkedEntity` class. This property is only available for v3.1-preview and up, and it is to be
used in conjunction with the Bing Entity Search API to fetch additional relevant information about the returned entity.

## 5.0.0 (2020-07-27)

- Re-release of GA version 1.0.0 with an updated version

## 1.0.0 (2020-06-09)

- First stable release of the azure-ai-textanalytics package. Targets the service's v3.0 API.

## 1.0.0b6 (2020-05-27)

**New features**
- We now have a `warnings` property on each document-level response object returned from the endpoints. It is a list of `TextAnalyticsWarning`s.
- Added `text` property to `SentenceSentiment`

**Breaking changes**
- Now targets only the service's v3.0 API, instead of the v3.0-preview.1 API
- `score` attribute of `DetectedLanguage` has been renamed to `confidence_score`
- Removed `grapheme_offset` and `grapheme_length` from `CategorizedEntity`, `SentenceSentiment`, and `LinkedEntityMatch`
- `TextDocumentStatistics` attribute `grapheme_count` has been renamed to `character_count`

## 1.0.0b5

- This was a broken release

## 1.0.0b4 (2020-04-07)

**Breaking changes**
- Removed the `recognize_pii_entities` endpoint and all related models (`RecognizePiiEntitiesResult` and `PiiEntity`)
from this library.
- Removed `TextAnalyticsApiKeyCredential` and now using `AzureKeyCredential` from azure.core.credentials as key credential
- `score` attribute has been renamed to `confidence_score` for the `CategorizedEntity`, `LinkedEntityMatch`, and
`PiiEntity` models
- All input parameters `inputs` have been renamed to `documents`

## 1.0.0b3 (2020-03-10)

**Breaking changes**
- `SentimentScorePerLabel` has been renamed to `SentimentConfidenceScores`
- `AnalyzeSentimentResult` and `SentenceSentiment` attribute `sentiment_scores` has been renamed to `confidence_scores`
- `TextDocumentStatistics` attribute `character_count` has been renamed to `grapheme_count`
- `LinkedEntity` attribute `id` has been renamed to `data_source_entity_id`
- Parameters `country_hint` and `language` are now passed as keyword arguments
- The keyword argument `response_hook` has been renamed to `raw_response_hook`
- `length` and `offset` attributes have been renamed to `grapheme_length` and `grapheme_offset` for the `SentenceSentiment`,
`CategorizedEntity`, `PiiEntity`, and `LinkedEntityMatch` models

**New features**
- Pass `country_hint="none"` to not use the default country hint of `"US"`.

**Dependency updates**
- Adopted [azure-core](https://pypi.org/project/azure-core/) version 1.3.0 or greater

## 1.0.0b2 (2020-02-11)

**Breaking changes**

- The single text, module-level operations `single_detect_language()`, `single_recognize_entities()`, `single_extract_key_phrases()`, `single_analyze_sentiment()`, `single_recognize_pii_entities()`, and `single_recognize_linked_entities()`
have been removed from the client library. Use the batching methods for optimal performance in production environments.
- To use an API key as the credential for authenticating the client, a new credential class `TextAnalyticsApiKeyCredential("<api_key>")` must be passed in for the `credential` parameter.
Passing the API key as a string is no longer supported.
- `detect_languages()` is renamed to `detect_language()`.
- The `TextAnalyticsError` model has been simplified to an object with only attributes `code`, `message`, and `target`.
- `NamedEntity` has been renamed to `CategorizedEntity` and its attributes `type` to `category` and `subtype` to `subcategory`.
- `RecognizePiiEntitiesResult` now contains on the object a list of `PiiEntity` instead of `NamedEntity`.
- `AnalyzeSentimentResult` attribute `document_scores` has been renamed to `sentiment_scores`.
- `SentenceSentiment` attribute `sentence_scores` has been renamed to `sentiment_scores`.
- `SentimentConfidenceScorePerLabel` has been renamed to `SentimentScorePerLabel`.
- `DetectLanguageResult` no longer has attribute `detected_languages`. Use `primary_language` to access the detected language in text.

**New features**

- Credential class `TextAnalyticsApiKeyCredential` provides an `update_key()` method which allows you to update the API key for long-lived clients.

**Fixes and improvements**

- `__repr__` has been added to all of the response objects.
- If you try to access a result attribute on a `DocumentError` object, an `AttributeError` is raised with a custom error message that provides the document ID and error of the invalid document.


## 1.0.0b1 (2020-01-09)

Version (1.0.0b1) is the first preview of our efforts to create a user-friendly and Pythonic client library for Azure Text Analytics. For more information about this, and preview releases of other Azure SDK libraries, please visit
https://azure.github.io/azure-sdk/releases/latest/python.html.

**Breaking changes: New API design**

- New namespace/package name:
  - The namespace/package name for Azure Text Analytics client library has changed from `azure.cognitiveservices.language.textanalytics` to `azure.ai.textanalytics`

- New operations and naming:
  - `detect_language` is renamed to `detect_languages`
  - `entities` is renamed to `recognize_entities`
  - `key_phrases` is renamed to `extract_key_phrases`
  - `sentiment` is renamed to `analyze_sentiment`
  - New operation `recognize_pii_entities` finds personally identifiable information entities in text
  - New operation `recognize_linked_entities` provides links from a well-known knowledge base for each recognized entity
  - New module-level operations `single_detect_language`, `single_recognize_entities`, `single_extract_key_phrases`, `single_analyze_sentiment`, `single_recognize_pii_entities`, and `single_recognize_linked_entities` perform
  function on a single string instead of a batch of text documents and can be imported from the `azure.ai.textanalytics` namespace.
  - New client and module-level async APIs added to subnamespace `azure.ai.textanalytics.aio`.
  - `MultiLanguageInput` has been renamed to `TextDocumentInput`
  - `LanguageInput` has been renamed to `DetectLanguageInput`
  - `DocumentLanguage` has been renamed to `DetectLanguageResult`
  - `DocumentEntities` has been renamed to `RecognizeEntitiesResult`
  - `DocumentLinkedEntities` has been renamed to `RecognizeLinkedEntitiesResult`
  - `DocumentKeyPhrases` has been renamed to `ExtractKeyPhrasesResult`
  - `DocumentSentiment` has been renamed to `AnalyzeSentimentResult`
  - `DocumentStatistics` has been renamed to `TextDocumentStatistics`
  - `RequestStatistics` has been renamed to `TextDocumentBatchStatistics`
  - `Entity` has been renamed to `NamedEntity`
  - `Match` has been renamed to `LinkedEntityMatch`
  - The batching methods' `documents` parameter has been renamed `inputs`

- New input types:
  - `detect_languages` can take as input a `list[DetectLanguageInput]` or a `list[str]`. A list of dict-like objects in the same shape as `DetectLanguageInput` is still accepted as input.
  - `recognize_entities`, `recognize_pii_entities`, `recognize_linked_entities`, `extract_key_phrases`, `analyze_sentiment` can take as input a `list[TextDocumentInput]` or `list[str]`.
  A list of dict-like objects in the same shape as `TextDocumentInput` is still accepted as input.

- New parameters/keyword arguments:
  - All operations now take a keyword argument `model_version` which allows the user to specify a string referencing the desired model version to be used for analysis. If no string specified, it will default to the latest, non-preview version.
  - `detect_languages` now takes a parameter `country_hint` which allows you to specify the country hint for the entire batch. Any per-item country hints will take precedence over a whole batch hint.
  - `recognize_entities`, `recognize_pii_entities`, `recognize_linked_entities`, `extract_key_phrases`, `analyze_sentiment` now take a parameter `language` which allows you to specify the language for the entire batch.
  Any per-item specified language will take precedence over a whole batch hint.
  - A `default_country_hint` or `default_language` keyword argument can be passed at client instantiation to set the default values for all operations.
  - A `response_hook` keyword argument can be passed with a callback to use the raw response from the service. Additionally, values returned for `TextDocumentBatchStatistics` and `model_version` used must be retrieved using a response hook.
  - `show_stats` and `model_version` parameters move to keyword only arguments.

- New return types
  - The return types for the batching methods (`detect_languages`, `recognize_entities`, `recognize_pii_entities`, `recognize_linked_entities`, `extract_key_phrases`, `analyze_sentiment`) now return a heterogeneous list of
  result objects and document errors in the order passed in with the request. To iterate over the list and filter for result or error, a boolean property on each object called `is_error` can be used to determine whether the returned response object at
  that index is a result or an error:
  - `detect_languages` now returns a List[Union[`DetectLanguageResult`, `DocumentError`]]
  - `recognize_entities` now returns a List[Union[`RecognizeEntitiesResult`, `DocumentError`]]
  - `recognize_pii_entities` now returns a List[Union[`RecognizePiiEntitiesResult`, `DocumentError`]]
  - `recognize_linked_entities` now returns a List[Union[`RecognizeLinkedEntitiesResult`, `DocumentError`]]
  - `extract_key_phrases` now returns a List[Union[`ExtractKeyPhrasesResult`, `DocumentError`]]
  - `analyze_sentiment` now returns a List[Union[`AnalyzeSentimentResult`, `DocumentError`]]
  - The module-level, single text operations will return a single result object or raise the error found on the document:
  - `single_detect_languages` returns a `DetectLanguageResult`
  - `single_recognize_entities` returns a `RecognizeEntitiesResult`
  - `single_recognize_pii_entities` returns a `RecognizePiiEntitiesResult`
  - `single_recognize_linked_entities` returns a `RecognizeLinkedEntitiesResult`
  - `single_extract_key_phrases` returns a `ExtractKeyPhrasesResult`
  - `single_analyze_sentiment` returns a `AnalyzeSentimentResult`

- New underlying REST pipeline implementation, based on the new `azure-core` library.
- Client and pipeline configuration is now available via keyword arguments at both the client level, and per-operation. See README for a full list of optional configuration arguments.
- Authentication using `azure-identity` credentials
  - see the
  [Azure Identity documentation](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/identity/azure-identity/README.md)
  for more information
- New error hierarchy:
    - All service errors will now use the base type: `azure.core.exceptions.HttpResponseError`
    - There is one exception type derived from this base type for authentication errors:
        - `ClientAuthenticationError`: Authentication failed.

## 0.2.0 (2019-03-12)

**Features**

- Client class can be used as a context manager to keep the underlying HTTP session open for performance
- New method "entities"
- Model KeyPhraseBatchResultItem has a new parameter statistics
- Model KeyPhraseBatchResult has a new parameter statistics
- Model LanguageBatchResult has a new parameter statistics
- Model LanguageBatchResultItem has a new parameter statistics
- Model SentimentBatchResult has a new parameter statistics

**Breaking changes**

- TextAnalyticsAPI main client has been renamed TextAnalyticsClient
- TextAnalyticsClient parameter is no longer a region but a complete endpoint

**General Breaking changes**

This version uses a next-generation code generator that *might* introduce breaking changes.

- Model signatures now use only keyword-argument syntax. All positional arguments must be re-written as keyword-arguments.
  To keep auto-completion in most cases, models are now generated for Python 2 and Python 3. Python 3 uses the "*" syntax for keyword-only arguments.
- Enum types now use the "str" mixin (class AzureEnum(str, Enum)) to improve the behavior when unrecognized enum values are encountered.
  While this is not a breaking change, the distinctions are important, and are documented here:
  https://docs.python.org/3/library/enum.html#others
  At a glance:

  - "is" should not be used at all.
  - "format" will return the string value, where "%s" string formatting will return `NameOfEnum.stringvalue`. Format syntax should be preferred.

**Bugfixes**

- Compatibility of the sdist with wheel 0.31.0


## 0.1.0 (2018-01-12)

* Initial Release

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/Azure/azure-sdk-for-python",
    "name": "azure-ai-textanalytics",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": null,
    "keywords": "azure,azure sdk,text analytics,cognitive services,natural language processing",
    "author": "Microsoft Corporation",
    "author_email": "azpysdkhelp@microsoft.com",
    "download_url": "https://files.pythonhosted.org/packages/3c/f4/459094eca3819b5dbe01d816a135b71eb37f16b5b50944d8e1eaaa79b88a/azure-ai-textanalytics-5.3.0.zip",
    "platform": null,
    "description": "# Azure Text Analytics client library for Python\n\nThe Azure Cognitive Service for Language is a cloud-based service that provides Natural Language Processing (NLP) features for understanding and analyzing text, and includes the following main features:\n\n- Sentiment Analysis\n- Named Entity Recognition\n- Language Detection\n- Key Phrase Extraction\n- Entity Linking\n- Multiple Analysis\n- Personally Identifiable Information (PII) Detection\n- Text Analytics for Health\n- Custom Named Entity Recognition\n- Custom Text Classification\n- Extractive Text Summarization\n- Abstractive Text Summarization\n\n[Source code][source_code]\n| [Package (PyPI)][ta_pypi]\n| [Package (Conda)](https://anaconda.org/microsoft/azure-ai-textanalytics/)\n| [API reference documentation][ta_ref_docs]\n| [Product documentation][language_product_documentation]\n| [Samples][ta_samples]\n\n## Getting started\n\n### Prerequisites\n\n- Python 3.7 later is required to use this package.\n- You must have an [Azure subscription][azure_subscription] and a\n  [Cognitive Services or Language service resource][ta_or_cs_resource] to use this package.\n\n#### Create a Cognitive Services or Language service resource\n\nThe Language service supports both [multi-service and single-service access][multi_and_single_service].\nCreate a Cognitive Services resource if you plan to access multiple cognitive services under a single endpoint/key. For Language service access only, create a Language service resource.\nYou can create the resource using the [Azure Portal][azure_portal_create_ta_resource] or [Azure CLI][azure_cli] following the steps in [this document][azure_cli_create_ta_resource].\n\nInteraction with the service using the client library begins with a [client](#textanalyticsclient \"TextAnalyticsClient\").\nTo create a client object, you will need the Cognitive Services or Language service `endpoint` to\nyour resource and a `credential` that allows you access:\n\n```python\nfrom azure.core.credentials import AzureKeyCredential\nfrom azure.ai.textanalytics import TextAnalyticsClient\n\ncredential = AzureKeyCredential(\"<api_key>\")\ntext_analytics_client = TextAnalyticsClient(endpoint=\"https://<resource-name>.cognitiveservices.azure.com/\", credential=credential)\n```\n\nNote that for some Cognitive Services resources the endpoint might look different from the above code snippet.\nFor example, `https://<region>.api.cognitive.microsoft.com/`.\n\n### Install the package\n\nInstall the Azure Text Analytics client library for Python with [pip][pip]:\n\n```bash\npip install azure-ai-textanalytics\n```\n\n<!-- SNIPPET:sample_authentication.create_ta_client_with_key -->\n\n```python\nimport os\nfrom azure.core.credentials import AzureKeyCredential\nfrom azure.ai.textanalytics import TextAnalyticsClient\nendpoint = os.environ[\"AZURE_LANGUAGE_ENDPOINT\"]\nkey = os.environ[\"AZURE_LANGUAGE_KEY\"]\n\ntext_analytics_client = TextAnalyticsClient(endpoint, AzureKeyCredential(key))\n```\n\n<!-- END SNIPPET -->\n\n> Note that `5.2.X` and newer targets the Azure Cognitive Service for Language APIs. These APIs include the text analysis and natural language processing features found in the previous versions of the Text Analytics client library.\nIn addition, the service API has changed from semantic to date-based versioning. This version of the client library defaults to the latest supported API version, which currently is `2023-04-01`.\n\nThis table shows the relationship between SDK versions and supported API versions of the service\n\n| SDK version  | Supported API version of service  |\n| ------------ | --------------------------------- |\n| 5.3.X - Latest stable release | 3.0, 3.1, 2022-05-01, 2023-04-01 (default) |\n| 5.2.X  | 3.0, 3.1, 2022-05-01 (default) |\n| 5.1.0  | 3.0, 3.1 (default) |\n| 5.0.0  | 3.0 |\n\nAPI version can be selected by passing the [api_version][text_analytics_client] keyword argument into the client.\nFor the latest Language service features, consider selecting the most recent beta API version. For production scenarios, the latest stable version is recommended. Setting to an older version may result in reduced feature compatibility.\n\n### Authenticate the client\n\n#### Get the endpoint\n\nYou can find the endpoint for your Language service resource using the\n[Azure Portal][azure_portal_get_endpoint]\nor [Azure CLI][azure_cli_endpoint_lookup]:\n\n```bash\n# Get the endpoint for the Language service resource\naz cognitiveservices account show --name \"resource-name\" --resource-group \"resource-group-name\" --query \"properties.endpoint\"\n```\n\n#### Get the API Key\n\nYou can get the [API key][cognitive_authentication_api_key] from the Cognitive Services or Language service resource in the [Azure Portal][azure_portal_get_endpoint].\nAlternatively, you can use [Azure CLI][azure_cli_endpoint_lookup] snippet below to get the API key of your resource.\n\n`az cognitiveservices account keys list --name \"resource-name\" --resource-group \"resource-group-name\"`\n\n#### Create a TextAnalyticsClient with an API Key Credential\n\nOnce you have the value for the API key, you can pass it as a string into an instance of [AzureKeyCredential][azure-key-credential]. Use the key as the credential parameter\nto authenticate the client:\n\n<!-- SNIPPET:sample_authentication.create_ta_client_with_key -->\n\n```python\nimport os\nfrom azure.core.credentials import AzureKeyCredential\nfrom azure.ai.textanalytics import TextAnalyticsClient\nendpoint = os.environ[\"AZURE_LANGUAGE_ENDPOINT\"]\nkey = os.environ[\"AZURE_LANGUAGE_KEY\"]\n\ntext_analytics_client = TextAnalyticsClient(endpoint, AzureKeyCredential(key))\n```\n\n<!-- END SNIPPET -->\n\n#### Create a TextAnalyticsClient with an Azure Active Directory Credential\n\nTo use an [Azure Active Directory (AAD) token credential][cognitive_authentication_aad],\nprovide an instance of the desired credential type obtained from the\n[azure-identity][azure_identity_credentials] library.\nNote that regional endpoints do not support AAD authentication. Create a [custom subdomain][custom_subdomain]\nname for your resource in order to use this type of authentication.\n\nAuthentication with AAD requires some initial setup:\n\n- [Install azure-identity][install_azure_identity]\n- [Register a new AAD application][register_aad_app]\n- [Grant access][grant_role_access] to the Language service by assigning the `\"Cognitive Services Language Reader\"` role to your service principal.\n\nAfter setup, you can choose which type of [credential][azure_identity_credentials] from azure.identity to use.\nAs an example, [DefaultAzureCredential][default_azure_credential]\ncan be used to authenticate the client:\n\nSet the values of the client ID, tenant ID, and client secret of the AAD application as environment variables:\nAZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET\n\nUse the returned token credential to authenticate the client:\n\n<!-- SNIPPET:sample_authentication.create_ta_client_with_aad -->\n\n```python\nimport os\nfrom azure.ai.textanalytics import TextAnalyticsClient\nfrom azure.identity import DefaultAzureCredential\n\nendpoint = os.environ[\"AZURE_LANGUAGE_ENDPOINT\"]\ncredential = DefaultAzureCredential()\n\ntext_analytics_client = TextAnalyticsClient(endpoint, credential=credential)\n```\n\n<!-- END SNIPPET -->\n\n## Key concepts\n\n### TextAnalyticsClient\n\nThe Text Analytics client library provides a [TextAnalyticsClient][text_analytics_client] to do analysis on [batches of documents](#examples \"Examples\").\nIt provides both synchronous and asynchronous operations to access a specific use of text analysis, such as language detection or key phrase extraction.\n\n### Input\n\nA **document** is a single unit to be analyzed by the predictive models in the Language service.\nThe input for each operation is passed as a **list** of documents.\n\nEach document can be passed as a string in the list, e.g.\n\n```python\ndocuments = [\"I hated the movie. It was so slow!\", \"The movie made it into my top ten favorites. What a great movie!\"]\n```\n\nor, if you wish to pass in a per-item document `id` or `language`/`country_hint`, they can be passed as a list of\n[DetectLanguageInput][detect_language_input] or\n[TextDocumentInput][text_document_input]\nor a dict-like representation of the object:\n\n```python\ndocuments = [\n    {\"id\": \"1\", \"language\": \"en\", \"text\": \"I hated the movie. It was so slow!\"},\n    {\"id\": \"2\", \"language\": \"en\", \"text\": \"The movie made it into my top ten favorites. What a great movie!\"},\n]\n```\n\nSee [service limitations][service_limits] for the input, including document length limits, maximum batch size, and supported text encoding.\n\n### Return Value\n\nThe return value for a single document can be a result or error object.\nA heterogeneous list containing a collection of result and error objects is returned from each operation.\nThese results/errors are index-matched with the order of the provided documents.\n\nA **result**, such as [AnalyzeSentimentResult][analyze_sentiment_result],\nis the result of a text analysis operation and contains a prediction or predictions about a document input.\n\nThe **error** object, [DocumentError][document_error], indicates that the service had trouble processing the document and contains\nthe reason it was unsuccessful.\n\n### Document Error Handling\n\nYou can filter for a result or error object in the list by using the `is_error` attribute. For a result object this is always `False` and for a\n[DocumentError][document_error] this is `True`.\n\nFor example, to filter out all DocumentErrors you might use list comprehension:\n\n```python\nresponse = text_analytics_client.analyze_sentiment(documents)\nsuccessful_responses = [doc for doc in response if not doc.is_error]\n```\n\nYou can also use the `kind` attribute to filter between result types:\n\n```python\npoller = text_analytics_client.begin_analyze_actions(documents, actions)\nresponse = poller.result()\nfor result in response:\n    if result.kind == \"SentimentAnalysis\":\n        print(f\"Sentiment is {result.sentiment}\")\n    elif result.kind == \"KeyPhraseExtraction\":\n        print(f\"Key phrases: {result.key_phrases}\")\n    elif result.is_error is True:\n        print(f\"Document error: {result.code}, {result.message}\")\n```\n\n### Long-Running Operations\n\nLong-running operations are operations which consist of an initial request sent to the service to start an operation,\nfollowed by polling the service at intervals to determine whether the operation has completed or failed, and if it has\nsucceeded, to get the result.\n\nMethods that support healthcare analysis, custom text analysis, or multiple analyses are modeled as long-running operations.\nThe client exposes a `begin_<method-name>` method that returns a poller object. Callers should wait\nfor the operation to complete by calling `result()` on the poller object returned from the `begin_<method-name>` method.\nSample code snippets are provided to illustrate using long-running operations [below](#examples \"Examples\").\n\n## Examples\n\nThe following section provides several code snippets covering some of the most common Language service tasks, including:\n\n- [Analyze Sentiment](#analyze-sentiment \"Analyze sentiment\")\n- [Recognize Entities](#recognize-entities \"Recognize entities\")\n- [Recognize Linked Entities](#recognize-linked-entities \"Recognize linked entities\")\n- [Recognize PII Entities](#recognize-pii-entities \"Recognize pii entities\")\n- [Extract Key Phrases](#extract-key-phrases \"Extract key phrases\")\n- [Detect Language](#detect-language \"Detect language\")\n- [Healthcare Entities Analysis](#healthcare-entities-analysis \"Healthcare Entities Analysis\")\n- [Multiple Analysis](#multiple-analysis \"Multiple analysis\")\n- [Custom Entity Recognition][recognize_custom_entities_sample]\n- [Custom Single Label Classification][single_label_classify_sample]\n- [Custom Multi Label Classification][multi_label_classify_sample]\n- [Extractive Summarization][extract_summary_sample]\n- [Abstractive Summarization][abstract_summary_sample]\n\n### Analyze Sentiment\n\n[analyze_sentiment][analyze_sentiment] looks at its input text and determines whether its sentiment is positive, negative, neutral or mixed. It's response includes per-sentence sentiment analysis and confidence scores.\n\n<!-- SNIPPET:sample_analyze_sentiment.analyze_sentiment -->\n\n```python\nimport os\nfrom azure.core.credentials import AzureKeyCredential\nfrom azure.ai.textanalytics import TextAnalyticsClient\n\nendpoint = os.environ[\"AZURE_LANGUAGE_ENDPOINT\"]\nkey = os.environ[\"AZURE_LANGUAGE_KEY\"]\n\ntext_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))\n\ndocuments = [\n    \"\"\"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.\n    I developed a deep-connection with my instructor as well, and I feel as if I've made a life-long friend in her.\"\"\",\n    \"\"\"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\n    not recommend to any divers, even first timers.\"\"\",\n    \"\"\"This was pretty good! The sights were ok, and I had fun with my instructors! Can't complain too much about my experience\"\"\",\n    \"\"\"I only have one word for my experience: WOW!!! I can't believe I have had such a wonderful skydiving company right\n    in my backyard this whole time! I will definitely be a repeat customer, and I want to take my grandmother skydiving too,\n    I know she'll love it!\"\"\"\n]\n\n\nresult = text_analytics_client.analyze_sentiment(documents, show_opinion_mining=True)\ndocs = [doc for doc in result if not doc.is_error]\n\nprint(\"Let's visualize the sentiment of each of these documents\")\nfor idx, doc in enumerate(docs):\n    print(f\"Document text: {documents[idx]}\")\n    print(f\"Overall sentiment: {doc.sentiment}\")\n```\n\n<!-- END SNIPPET -->\n\nThe returned response is a heterogeneous list of result and error objects: list[[AnalyzeSentimentResult][analyze_sentiment_result], [DocumentError][document_error]]\n\nPlease refer to the service documentation for a conceptual discussion of [sentiment analysis][sentiment_analysis]. To see how to conduct more granular analysis into the opinions related to individual aspects (such as attributes of a product or service) in a text, see [here][opinion_mining_sample].\n\n### Recognize Entities\n\n[recognize_entities][recognize_entities] recognizes and categories entities in its input text as people, places, organizations, date/time, quantities, percentages, currencies, and more.\n\n<!-- SNIPPET:sample_recognize_entities.recognize_entities -->\n\n```python\nimport os\nimport typing\nfrom azure.core.credentials import AzureKeyCredential\nfrom azure.ai.textanalytics import TextAnalyticsClient\n\nendpoint = os.environ[\"AZURE_LANGUAGE_ENDPOINT\"]\nkey = os.environ[\"AZURE_LANGUAGE_KEY\"]\n\ntext_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))\nreviews = [\n    \"\"\"I work for Foo Company, and we hired Contoso for our annual founding ceremony. The food\n    was amazing and we all can't say enough good words about the quality and the level of service.\"\"\",\n    \"\"\"We at the Foo Company re-hired Contoso after all of our past successes with the company.\n    Though the food was still great, I feel there has been a quality drop since their last time\n    catering for us. Is anyone else running into the same problem?\"\"\",\n    \"\"\"Bar Company is over the moon about the service we received from Contoso, the best sliders ever!!!!\"\"\"\n]\n\nresult = text_analytics_client.recognize_entities(reviews)\nresult = [review for review in result if not review.is_error]\norganization_to_reviews: typing.Dict[str, typing.List[str]] = {}\n\nfor idx, review in enumerate(result):\n    for entity in review.entities:\n        print(f\"Entity '{entity.text}' has category '{entity.category}'\")\n        if entity.category == 'Organization':\n            organization_to_reviews.setdefault(entity.text, [])\n            organization_to_reviews[entity.text].append(reviews[idx])\n\nfor organization, reviews in organization_to_reviews.items():\n    print(\n        \"\\n\\nOrganization '{}' has left us the following review(s): {}\".format(\n            organization, \"\\n\\n\".join(reviews)\n        )\n    )\n```\n\n<!-- END SNIPPET -->\n\nThe returned response is a heterogeneous list of result and error objects: list[[RecognizeEntitiesResult][recognize_entities_result], [DocumentError][document_error]]\n\nPlease refer to the service documentation for a conceptual discussion of [named entity recognition][named_entity_recognition]\nand [supported types][named_entity_categories].\n\n### Recognize Linked Entities\n\n[recognize_linked_entities][recognize_linked_entities] recognizes and disambiguates the identity of each entity found in its input text (for example,\ndetermining whether an occurrence of the word Mars refers to the planet, or to the\nRoman god of war). Recognized entities are associated with URLs to a well-known knowledge base, like Wikipedia.\n\n<!-- SNIPPET:sample_recognize_linked_entities.recognize_linked_entities -->\n\n```python\nimport os\nfrom azure.core.credentials import AzureKeyCredential\nfrom azure.ai.textanalytics import TextAnalyticsClient\n\nendpoint = os.environ[\"AZURE_LANGUAGE_ENDPOINT\"]\nkey = os.environ[\"AZURE_LANGUAGE_KEY\"]\n\ntext_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))\ndocuments = [\n    \"\"\"\n    Microsoft was founded by Bill Gates with some friends he met at Harvard. One of his friends,\n    Steve Ballmer, eventually became CEO after Bill Gates as well. Steve Ballmer eventually stepped\n    down as CEO of Microsoft, and was succeeded by Satya Nadella.\n    Microsoft originally moved its headquarters to Bellevue, Washington in January 1979, but is now\n    headquartered in Redmond.\n    \"\"\"\n]\n\nresult = text_analytics_client.recognize_linked_entities(documents)\ndocs = [doc for doc in result if not doc.is_error]\n\nprint(\n    \"Let's map each entity to it's Wikipedia article. I also want to see how many times each \"\n    \"entity is mentioned in a document\\n\\n\"\n)\nentity_to_url = {}\nfor doc in docs:\n    for entity in doc.entities:\n        print(\"Entity '{}' has been mentioned '{}' time(s)\".format(\n            entity.name, len(entity.matches)\n        ))\n        if entity.data_source == \"Wikipedia\":\n            entity_to_url[entity.name] = entity.url\n```\n\n<!-- END SNIPPET -->\n\nThe returned response is a heterogeneous list of result and error objects: list[[RecognizeLinkedEntitiesResult][recognize_linked_entities_result], [DocumentError][document_error]]\n\nPlease refer to the service documentation for a conceptual discussion of [entity linking][linked_entity_recognition]\nand [supported types][linked_entities_categories].\n\n### Recognize PII Entities\n\n[recognize_pii_entities][recognize_pii_entities] recognizes and categorizes Personally Identifiable Information (PII) entities in its input text, such as\nSocial Security Numbers, bank account information, credit card numbers, and more.\n\n<!-- SNIPPET:sample_recognize_pii_entities.recognize_pii_entities -->\n\n```python\nimport os\nfrom azure.core.credentials import AzureKeyCredential\nfrom azure.ai.textanalytics import TextAnalyticsClient\n\nendpoint = os.environ[\"AZURE_LANGUAGE_ENDPOINT\"]\nkey = os.environ[\"AZURE_LANGUAGE_KEY\"]\n\ntext_analytics_client = TextAnalyticsClient(\n    endpoint=endpoint, credential=AzureKeyCredential(key)\n)\ndocuments = [\n    \"\"\"Parker Doe has repaid all of their loans as of 2020-04-25.\n    Their SSN is 859-98-0987. To contact them, use their phone number\n    555-555-5555. They are originally from Brazil and have Brazilian CPF number 998.214.865-68\"\"\"\n]\n\nresult = text_analytics_client.recognize_pii_entities(documents)\ndocs = [doc for doc in result if not doc.is_error]\n\nprint(\n    \"Let's compare the original document with the documents after redaction. \"\n    \"I also want to comb through all of the entities that got redacted\"\n)\nfor idx, doc in enumerate(docs):\n    print(f\"Document text: {documents[idx]}\")\n    print(f\"Redacted document text: {doc.redacted_text}\")\n    for entity in doc.entities:\n        print(\"...Entity '{}' with category '{}' got redacted\".format(\n            entity.text, entity.category\n        ))\n```\n\n<!-- END SNIPPET -->\n\nThe returned response is a heterogeneous list of result and error objects: list[[RecognizePiiEntitiesResult][recognize_pii_entities_result], [DocumentError][document_error]]\n\nPlease refer to the service documentation for [supported PII entity types][pii_entity_categories].\n\nNote: The Recognize PII Entities service is available in API version v3.1 and newer.\n\n### Extract Key Phrases\n\n[extract_key_phrases][extract_key_phrases] determines the main talking points in its input text. For example, for the input text \"The food was delicious and there were wonderful staff\", the API returns: \"food\" and \"wonderful staff\".\n\n<!-- SNIPPET:sample_extract_key_phrases.extract_key_phrases -->\n\n```python\nimport os\nfrom azure.core.credentials import AzureKeyCredential\nfrom azure.ai.textanalytics import TextAnalyticsClient\n\nendpoint = os.environ[\"AZURE_LANGUAGE_ENDPOINT\"]\nkey = os.environ[\"AZURE_LANGUAGE_KEY\"]\n\ntext_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))\narticles = [\n    \"\"\"\n    Washington, D.C. Autumn in DC is a uniquely beautiful season. The leaves fall from the trees\n    in a city chock-full of forests, leaving yellow leaves on the ground and a clearer view of the\n    blue sky above...\n    \"\"\",\n    \"\"\"\n    Redmond, WA. In the past few days, Microsoft has decided to further postpone the start date of\n    its United States workers, due to the pandemic that rages with no end in sight...\n    \"\"\",\n    \"\"\"\n    Redmond, WA. Employees at Microsoft can be excited about the new coffee shop that will open on campus\n    once workers no longer have to work remotely...\n    \"\"\"\n]\n\nresult = text_analytics_client.extract_key_phrases(articles)\nfor idx, doc in enumerate(result):\n    if not doc.is_error:\n        print(\"Key phrases in article #{}: {}\".format(\n            idx + 1,\n            \", \".join(doc.key_phrases)\n        ))\n```\n\n<!-- END SNIPPET -->\n\nThe returned response is a heterogeneous list of result and error objects: list[[ExtractKeyPhrasesResult][extract_key_phrases_result], [DocumentError][document_error]]\n\nPlease refer to the service documentation for a conceptual discussion of [key phrase extraction][key_phrase_extraction].\n\n### Detect Language\n\n[detect_language][detect_language] determines the language of its input text, including the confidence score of the predicted language.\n\n<!-- SNIPPET:sample_detect_language.detect_language -->\n\n```python\nimport os\nfrom azure.core.credentials import AzureKeyCredential\nfrom azure.ai.textanalytics import TextAnalyticsClient\n\nendpoint = os.environ[\"AZURE_LANGUAGE_ENDPOINT\"]\nkey = os.environ[\"AZURE_LANGUAGE_KEY\"]\n\ntext_analytics_client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))\ndocuments = [\n    \"\"\"\n    The concierge Paulette was extremely helpful. Sadly when we arrived the elevator was broken, but with Paulette's help we barely noticed this inconvenience.\n    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\n    walking up the stairs :). Can't say enough good things about my experience!\n    \"\"\",\n    \"\"\"\n    \u6700\u8fd1\u7531\u4e8e\u5de5\u4f5c\u538b\u529b\u592a\u5927\uff0c\u6211\u4eec\u51b3\u5b9a\u53bb\u5bcc\u9152\u5e97\u5ea6\u5047\u3002\u90a3\u513f\u7684\u6e29\u6cc9\u5b9e\u5728\u592a\u8212\u670d\u4e86\uff0c\u6211\u8ddf\u6211\u4e08\u592b\u90fd\u5b8c\u5168\u6062\u590d\u4e86\u5de5\u4f5c\u524d\u7684\u9752\u6625\u7cbe\u795e\uff01\u52a0\u6cb9\uff01\n    \"\"\"\n]\n\nresult = text_analytics_client.detect_language(documents)\nreviewed_docs = [doc for doc in result if not doc.is_error]\n\nprint(\"Let's see what language each review is in!\")\n\nfor idx, doc in enumerate(reviewed_docs):\n    print(\"Review #{} is in '{}', which has ISO639-1 name '{}'\\n\".format(\n        idx, doc.primary_language.name, doc.primary_language.iso6391_name\n    ))\n```\n\n<!-- END SNIPPET -->\n\nThe returned response is a heterogeneous list of result and error objects: list[[DetectLanguageResult][detect_language_result], [DocumentError][document_error]]\n\nPlease refer to the service documentation for a conceptual discussion of [language detection][language_detection]\nand [language and regional support][language_and_regional_support].\n\n### Healthcare Entities Analysis\n\n[Long-running operation](#long-running-operations) [begin_analyze_healthcare_entities][analyze_healthcare_entities] extracts entities recognized within the healthcare domain, and identifies relationships between entities within the input document and links to known sources of information in various well known databases, such as UMLS, CHV, MSH, etc.\n\n<!-- SNIPPET:sample_analyze_healthcare_entities.analyze_healthcare_entities -->\n\n```python\nimport os\nimport typing\nfrom azure.core.credentials import AzureKeyCredential\nfrom azure.ai.textanalytics import TextAnalyticsClient, HealthcareEntityRelation\n\nendpoint = os.environ[\"AZURE_LANGUAGE_ENDPOINT\"]\nkey = os.environ[\"AZURE_LANGUAGE_KEY\"]\n\ntext_analytics_client = TextAnalyticsClient(\n    endpoint=endpoint,\n    credential=AzureKeyCredential(key),\n)\n\ndocuments = [\n    \"\"\"\n    Patient needs to take 100 mg of ibuprofen, and 3 mg of potassium. Also needs to take\n    10 mg of Zocor.\n    \"\"\",\n    \"\"\"\n    Patient needs to take 50 mg of ibuprofen, and 2 mg of Coumadin.\n    \"\"\"\n]\n\npoller = text_analytics_client.begin_analyze_healthcare_entities(documents)\nresult = poller.result()\n\ndocs = [doc for doc in result if not doc.is_error]\n\nprint(\"Let's first visualize the outputted healthcare result:\")\nfor doc in docs:\n    for entity in doc.entities:\n        print(f\"Entity: {entity.text}\")\n        print(f\"...Normalized Text: {entity.normalized_text}\")\n        print(f\"...Category: {entity.category}\")\n        print(f\"...Subcategory: {entity.subcategory}\")\n        print(f\"...Offset: {entity.offset}\")\n        print(f\"...Confidence score: {entity.confidence_score}\")\n        if entity.data_sources is not None:\n            print(\"...Data Sources:\")\n            for data_source in entity.data_sources:\n                print(f\"......Entity ID: {data_source.entity_id}\")\n                print(f\"......Name: {data_source.name}\")\n        if entity.assertion is not None:\n            print(\"...Assertion:\")\n            print(f\"......Conditionality: {entity.assertion.conditionality}\")\n            print(f\"......Certainty: {entity.assertion.certainty}\")\n            print(f\"......Association: {entity.assertion.association}\")\n    for relation in doc.entity_relations:\n        print(f\"Relation of type: {relation.relation_type} has the following roles\")\n        for role in relation.roles:\n            print(f\"...Role '{role.name}' with entity '{role.entity.text}'\")\n    print(\"------------------------------------------\")\n\nprint(\"Now, let's get all of medication dosage relations from the documents\")\ndosage_of_medication_relations = [\n    entity_relation\n    for doc in docs\n    for entity_relation in doc.entity_relations if entity_relation.relation_type == HealthcareEntityRelation.DOSAGE_OF_MEDICATION\n]\n```\n\n<!-- END SNIPPET -->\n\nNote: Healthcare Entities Analysis is only available with API version v3.1 and newer.\n\n### Multiple Analysis\n\n[Long-running operation](#long-running-operations) [begin_analyze_actions][analyze_actions] performs multiple analyses over one set of documents in a single request. Currently it is supported using any combination of the following Language APIs in a single request:\n\n- Entities Recognition\n- PII Entities Recognition\n- Linked Entity Recognition\n- Key Phrase Extraction\n- Sentiment Analysis\n- Custom Entity Recognition (API version 2022-05-01 and newer)\n- Custom Single Label Classification (API version 2022-05-01 and newer)\n- Custom Multi Label Classification (API version 2022-05-01 and newer)\n- Healthcare Entities Analysis (API version 2022-05-01 and newer)\n- Extractive Summarization (API version 2023-04-01 and newer)\n- Abstractive Summarization (API version 2023-04-01 and newer)\n\n<!-- SNIPPET:sample_analyze_actions.analyze -->\n\n```python\nimport os\nfrom azure.core.credentials import AzureKeyCredential\nfrom azure.ai.textanalytics import (\n    TextAnalyticsClient,\n    RecognizeEntitiesAction,\n    RecognizeLinkedEntitiesAction,\n    RecognizePiiEntitiesAction,\n    ExtractKeyPhrasesAction,\n    AnalyzeSentimentAction,\n)\n\nendpoint = os.environ[\"AZURE_LANGUAGE_ENDPOINT\"]\nkey = os.environ[\"AZURE_LANGUAGE_KEY\"]\n\ntext_analytics_client = TextAnalyticsClient(\n    endpoint=endpoint,\n    credential=AzureKeyCredential(key),\n)\n\ndocuments = [\n    'We went to Contoso Steakhouse located at midtown NYC last week for a dinner party, and we adore the spot! '\n    '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) '\n    'and he is super nice, coming out of the kitchen and greeted us all.'\n    ,\n\n    'We enjoyed very much dining in the place! '\n    'The Sirloin steak I ordered was tender and juicy, and the place was impeccably clean. You can even pre-order from their '\n    'online menu at www.contososteakhouse.com, call 312-555-0176 or send email to order@contososteakhouse.com! '\n    'The only complaint I have is the food didn\\'t come fast enough. Overall I highly recommend it!'\n]\n\npoller = text_analytics_client.begin_analyze_actions(\n    documents,\n    display_name=\"Sample Text Analysis\",\n    actions=[\n        RecognizeEntitiesAction(),\n        RecognizePiiEntitiesAction(),\n        ExtractKeyPhrasesAction(),\n        RecognizeLinkedEntitiesAction(),\n        AnalyzeSentimentAction(),\n    ],\n)\n\ndocument_results = poller.result()\nfor doc, action_results in zip(documents, document_results):\n    print(f\"\\nDocument text: {doc}\")\n    for result in action_results:\n        if result.kind == \"EntityRecognition\":\n            print(\"...Results of Recognize Entities Action:\")\n            for entity in result.entities:\n                print(f\"......Entity: {entity.text}\")\n                print(f\".........Category: {entity.category}\")\n                print(f\".........Confidence Score: {entity.confidence_score}\")\n                print(f\".........Offset: {entity.offset}\")\n\n        elif result.kind == \"PiiEntityRecognition\":\n            print(\"...Results of Recognize PII Entities action:\")\n            for pii_entity in result.entities:\n                print(f\"......Entity: {pii_entity.text}\")\n                print(f\".........Category: {pii_entity.category}\")\n                print(f\".........Confidence Score: {pii_entity.confidence_score}\")\n\n        elif result.kind == \"KeyPhraseExtraction\":\n            print(\"...Results of Extract Key Phrases action:\")\n            print(f\"......Key Phrases: {result.key_phrases}\")\n\n        elif result.kind == \"EntityLinking\":\n            print(\"...Results of Recognize Linked Entities action:\")\n            for linked_entity in result.entities:\n                print(f\"......Entity name: {linked_entity.name}\")\n                print(f\".........Data source: {linked_entity.data_source}\")\n                print(f\".........Data source language: {linked_entity.language}\")\n                print(\n                    f\".........Data source entity ID: {linked_entity.data_source_entity_id}\"\n                )\n                print(f\".........Data source URL: {linked_entity.url}\")\n                print(\".........Document matches:\")\n                for match in linked_entity.matches:\n                    print(f\"............Match text: {match.text}\")\n                    print(f\"............Confidence Score: {match.confidence_score}\")\n                    print(f\"............Offset: {match.offset}\")\n                    print(f\"............Length: {match.length}\")\n\n        elif result.kind == \"SentimentAnalysis\":\n            print(\"...Results of Analyze Sentiment action:\")\n            print(f\"......Overall sentiment: {result.sentiment}\")\n            print(\n                f\"......Scores: positive={result.confidence_scores.positive}; \\\n                neutral={result.confidence_scores.neutral}; \\\n                negative={result.confidence_scores.negative} \\n\"\n            )\n\n        elif result.is_error is True:\n            print(\n                f\"...Is an error with code '{result.error.code}' and message '{result.error.message}'\"\n            )\n\n    print(\"------------------------------------------\")\n```\n\n<!-- END SNIPPET -->\n\nThe returned response is an object encapsulating multiple iterables, each representing results of individual analyses.\n\nNote: Multiple analysis is available in API version v3.1 and newer.\n\n## Optional Configuration\n\nOptional keyword arguments can be passed in at the client and per-operation level.\nThe azure-core [reference documentation][azure_core_ref_docs]\ndescribes available configurations for retries, logging, transport protocols, and more.\n\n## Troubleshooting\n\n### General\n\nThe Text Analytics client will raise exceptions defined in [Azure Core][azure_core].\n\n### Logging\n\nThis library uses the standard\n[logging][python_logging] library for logging.\nBasic information about HTTP sessions (URLs, headers, etc.) is logged at INFO\nlevel.\n\nDetailed DEBUG level logging, including request/response bodies and unredacted\nheaders, can be enabled on a client with the `logging_enable` keyword argument:\n\n```python\nimport sys\nimport logging\nfrom azure.identity import DefaultAzureCredential\nfrom azure.ai.textanalytics import TextAnalyticsClient\n\n# Create a logger for the 'azure' SDK\nlogger = logging.getLogger('azure')\nlogger.setLevel(logging.DEBUG)\n\n# Configure a console output\nhandler = logging.StreamHandler(stream=sys.stdout)\nlogger.addHandler(handler)\n\nendpoint = \"https://<resource-name>.cognitiveservices.azure.com/\"\ncredential = DefaultAzureCredential()\n\n# This client will log detailed information about its HTTP sessions, at DEBUG level\ntext_analytics_client = TextAnalyticsClient(endpoint, credential, logging_enable=True)\nresult = text_analytics_client.analyze_sentiment([\"I did not like the restaurant. The food was too spicy.\"])\n```\n\nSimilarly, `logging_enable` can enable detailed logging for a single operation,\neven when it isn't enabled for the client:\n\n```python\nresult = text_analytics_client.analyze_sentiment(documents, logging_enable=True)\n```\n\n## Next steps\n\n### More sample code\n\nThese code samples show common scenario operations with the Azure Text Analytics client library.\n\nAuthenticate the client with a Cognitive Services/Language service API key or a token credential from [azure-identity][azure_identity]:\n\n- [sample_authentication.py][sample_authentication] ([async version][sample_authentication_async])\n\nCommon scenarios\n\n- Analyze sentiment: [sample_analyze_sentiment.py][analyze_sentiment_sample] ([async version][analyze_sentiment_sample_async])\n- Recognize entities: [sample_recognize_entities.py][recognize_entities_sample] ([async version][recognize_entities_sample_async])\n- Recognize personally identifiable information: [sample_recognize_pii_entities.py][recognize_pii_entities_sample] ([async version][recognize_pii_entities_sample_async])\n- Recognize linked entities: [sample_recognize_linked_entities.py][recognize_linked_entities_sample] ([async version][recognize_linked_entities_sample_async])\n- Extract key phrases: [sample_extract_key_phrases.py][extract_key_phrases_sample] ([async version][extract_key_phrases_sample_async])\n- Detect language: [sample_detect_language.py][detect_language_sample] ([async version][detect_language_sample_async])\n- Healthcare Entities Analysis: [sample_analyze_healthcare_entities.py][analyze_healthcare_entities_sample] ([async version][analyze_healthcare_entities_sample_async])\n- Multiple Analysis: [sample_analyze_actions.py][analyze_sample] ([async version][analyze_sample_async])\n- Custom Entity Recognition: [sample_recognize_custom_entities.py][recognize_custom_entities_sample] ([async_version][recognize_custom_entities_sample_async])\n- Custom Single Label Classification: [sample_single_label_classify.py][single_label_classify_sample] ([async_version][single_label_classify_sample_async])\n- Custom Multi Label Classification: [sample_multi_label_classify.py][multi_label_classify_sample] ([async_version][multi_label_classify_sample_async])\n- Extractive text summarization: [sample_extract_summary.py][extract_summary_sample] ([async version][extract_summary_sample_async])\n- Abstractive text summarization: [sample_abstract_summary.py][abstract_summary_sample] ([async version][abstract_summary_sample_async])\n\nAdvanced scenarios\n\n- Opinion Mining: [sample_analyze_sentiment_with_opinion_mining.py][opinion_mining_sample] ([async_version][opinion_mining_sample_async])\n\n### Additional documentation\n\nFor more extensive documentation on Azure Cognitive Service for Language, see the [Language Service documentation][language_product_documentation] on docs.microsoft.com.\n\n## Contributing\n\nThis project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit [cla.microsoft.com][cla].\n\nWhen you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.\n\nThis project has adopted the [Microsoft Open Source Code of Conduct][code_of_conduct]. For more information see the [Code of Conduct FAQ][coc_faq] or contact [opencode@microsoft.com][coc_contact] with any additional questions or comments.\n\n<!-- LINKS -->\n\n[source_code]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics\n[ta_pypi]: https://pypi.org/project/azure-ai-textanalytics/\n[ta_ref_docs]: https://aka.ms/azsdk-python-textanalytics-ref-docs\n[ta_samples]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples\n[language_product_documentation]: https://docs.microsoft.com/azure/cognitive-services/language-service\n[azure_subscription]: https://azure.microsoft.com/free/\n[ta_or_cs_resource]: https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account?tabs=multiservice%2Cwindows\n[pip]: https://pypi.org/project/pip/\n[azure_portal_create_ta_resource]: https://ms.portal.azure.com/#create/Microsoft.CognitiveServicesTextAnalytics\n[azure_cli]: https://docs.microsoft.com/cli/azure\n[azure_cli_create_ta_resource]: https://learn.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account-cli\n[multi_and_single_service]: https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account?tabs=multiservice%2Cwindows\n[azure_cli_endpoint_lookup]: https://docs.microsoft.com/cli/azure/cognitiveservices/account?view=azure-cli-latest#az-cognitiveservices-account-show\n[azure_portal_get_endpoint]: https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account?tabs=multiservice%2Cwindows#get-the-keys-for-your-resource\n[cognitive_authentication]: https://docs.microsoft.com/azure/cognitive-services/authentication\n[cognitive_authentication_api_key]: https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account?tabs=multiservice%2Cwindows#get-the-keys-for-your-resource\n[install_azure_identity]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#install-the-package\n[register_aad_app]: https://docs.microsoft.com/azure/cognitive-services/authentication#assign-a-role-to-a-service-principal\n[grant_role_access]: https://docs.microsoft.com/azure/cognitive-services/authentication#assign-a-role-to-a-service-principal\n[cognitive_custom_subdomain]: https://docs.microsoft.com/azure/cognitive-services/cognitive-services-custom-subdomains\n[custom_subdomain]: https://docs.microsoft.com/azure/cognitive-services/authentication#create-a-resource-with-a-custom-subdomain\n[cognitive_authentication_aad]: https://docs.microsoft.com/azure/cognitive-services/authentication#authenticate-with-azure-active-directory\n[azure_identity_credentials]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#credentials\n[default_azure_credential]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity#defaultazurecredential\n[service_limits]: https://aka.ms/azsdk/textanalytics/data-limits\n[azure-key-credential]: https://aka.ms/azsdk-python-core-azurekeycredential\n[document_error]: https://aka.ms/azsdk-python-textanalytics-documenterror\n[detect_language_result]: https://aka.ms/azsdk-python-textanalytics-detectlanguageresult\n[recognize_entities_result]: https://aka.ms/azsdk-python-textanalytics-recognizeentitiesresult\n[recognize_pii_entities_result]: https://aka.ms/azsdk-python-textanalytics-recognizepiientitiesresult\n[recognize_linked_entities_result]: https://aka.ms/azsdk-python-textanalytics-recognizelinkedentitiesresult\n[analyze_sentiment_result]: https://aka.ms/azsdk-python-textanalytics-analyzesentimentresult\n[extract_key_phrases_result]: https://aka.ms/azsdk-python-textanalytics-extractkeyphrasesresult\n[text_document_input]: https://aka.ms/azsdk-python-textanalytics-textdocumentinput\n[detect_language_input]: https://aka.ms/azsdk-python-textanalytics-detectlanguageinput\n[text_analytics_client]: https://aka.ms/azsdk-python-textanalytics-textanalyticsclient\n[analyze_sentiment]: https://aka.ms/azsdk-python-textanalytics-analyzesentiment\n[analyze_actions]: https://aka.ms/azsdk/python/docs/ref/textanalytics#azure.ai.textanalytics.TextAnalyticsClient.begin_analyze_actions\n[analyze_healthcare_entities]: https://aka.ms/azsdk/python/docs/ref/textanalytics#azure.ai.textanalytics.TextAnalyticsClient.begin_analyze_healthcare_entities\n[recognize_entities]: https://aka.ms/azsdk-python-textanalytics-recognizeentities\n[recognize_pii_entities]: https://aka.ms/azsdk-python-textanalytics-recognizepiientities\n[recognize_linked_entities]: https://aka.ms/azsdk-python-textanalytics-recognizelinkedentities\n[extract_key_phrases]: https://aka.ms/azsdk-python-textanalytics-extractkeyphrases\n[detect_language]: https://aka.ms/azsdk-python-textanalytics-detectlanguage\n[language_detection]: https://docs.microsoft.com/azure/cognitive-services/language-service/language-detection/overview\n[language_and_regional_support]: https://docs.microsoft.com/azure/cognitive-services/language-service/language-detection/language-support\n[sentiment_analysis]: https://docs.microsoft.com/azure/cognitive-services/language-service/sentiment-opinion-mining/overview\n[key_phrase_extraction]: https://docs.microsoft.com/azure/cognitive-services/language-service/key-phrase-extraction/overview\n[linked_entities_categories]: https://aka.ms/taner\n[linked_entity_recognition]: https://docs.microsoft.com/azure/cognitive-services/language-service/entity-linking/overview\n[pii_entity_categories]: https://aka.ms/azsdk/language/pii\n[named_entity_recognition]: https://docs.microsoft.com/azure/cognitive-services/language-service/named-entity-recognition/overview\n[named_entity_categories]: https://aka.ms/taner\n[azure_core_ref_docs]: https://aka.ms/azsdk-python-core-policies\n[azure_core]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/core/azure-core/README.md\n[azure_identity]: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity\n[python_logging]: https://docs.python.org/3/library/logging.html\n[sample_authentication]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_authentication.py\n[sample_authentication_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_authentication_async.py\n[detect_language_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_detect_language.py\n[detect_language_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_detect_language_async.py\n[analyze_sentiment_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_analyze_sentiment.py\n[analyze_sentiment_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_analyze_sentiment_async.py\n[extract_key_phrases_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_extract_key_phrases.py\n[extract_key_phrases_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_extract_key_phrases_async.py\n[recognize_entities_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_recognize_entities.py\n[recognize_entities_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_recognize_entities_async.py\n[recognize_linked_entities_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_recognize_linked_entities.py\n[recognize_linked_entities_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_recognize_linked_entities_async.py\n[recognize_pii_entities_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_recognize_pii_entities.py\n[recognize_pii_entities_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_recognize_pii_entities_async.py\n[analyze_healthcare_entities_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_analyze_healthcare_entities.py\n[analyze_healthcare_entities_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_analyze_healthcare_entities_async.py\n[analyze_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_analyze_actions.py\n[analyze_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_analyze_actions_async.py\n[opinion_mining_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_analyze_sentiment_with_opinion_mining.py\n[opinion_mining_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_analyze_sentiment_with_opinion_mining_async.py\n[recognize_custom_entities_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_recognize_custom_entities.py\n[recognize_custom_entities_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_recognize_custom_entities_async.py\n[single_label_classify_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_single_label_classify.py\n[single_label_classify_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_single_label_classify_async.py\n[multi_label_classify_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_multi_label_classify.py\n[multi_label_classify_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_multi_label_classify_async.py\n[healthcare_action_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_analyze_healthcare_action.py\n[extract_summary_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_extract_summary.py\n[extract_summary_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_extract_summary_async.py\n[abstract_summary_sample]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/sample_abstract_summary.py\n[abstract_summary_sample_async]: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/textanalytics/azure-ai-textanalytics/samples/async_samples/sample_abstract_summary_async.py\n[cla]: https://cla.microsoft.com\n[code_of_conduct]: https://opensource.microsoft.com/codeofconduct/\n[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/\n[coc_contact]: mailto:opencode@microsoft.com\n\n\n# Release History\n\n## 5.3.0 (2023-06-15)\n\nThis version of the client library defaults to the service API version `2023-04-01`.\n\n### Breaking Changes\n\n> Note: The following changes are only breaking from the previous beta. They are not breaking against previous stable versions.\n\n- Renamed model `ExtractSummaryAction` to `ExtractiveSummaryAction`.\n- Renamed model `ExtractSummaryResult` to `ExtractiveSummaryResult`.\n- Renamed client method `begin_abstractive_summary` to `begin_abstract_summary`.\n- Removed `dynamic_classification` client method and related types: `DynamicClassificationResult` and `ClassificationType`.\n- Removed keyword arguments `fhir_version` and `document_type` from `begin_analyze_healthcare_entities` and `AnalyzeHealthcareEntitiesAction`.\n- Removed property `fhir_bundle` from `AnalyzeHealthcareEntitiesResult`. \n- Removed enum `HealthcareDocumentType`.\n- Removed property `resolutions` from `CategorizedEntity`.\n- Removed models and enums related to resolutions: `ResolutionKind`, `AgeResolution`, `AreaResolution`,\n  `CurrencyResolution`, `DateTimeResolution`, `InformationResolution`, `LengthResolution`,\n  `NumberResolution`, `NumericRangeResolution`, `OrdinalResolution`, `SpeedResolution`, `TemperatureResolution`,\n  `TemporalSpanResolution`, `VolumeResolution`, `WeightResolution`, `AgeUnit`, `AreaUnit`, `TemporalModifier`,\n  `InformationUnit`, `LengthUnit`, `NumberKind`, `RangeKind`, `RelativeTo`, `SpeedUnit`, `TemperatureUnit`,\n  `VolumeUnit`, `DateTimeSubKind`, and `WeightUnit`.\n- Removed property `detected_language` from `RecognizeEntitiesResult`, `RecognizePiiEntitiesResult`, `AnalyzeHealthcareEntitiesResult`,\n  `ExtractKeyPhrasesResult`, `RecognizeLinkedEntitiesResult`, `AnalyzeSentimentResult`, `RecognizeCustomEntitiesResult`,\n  `ClassifyDocumentResult`, `ExtractSummaryResult`, and `AbstractSummaryResult`.\n- Removed property `script` from `DetectedLanguage`.\n\n### Features Added\n\n- New enum values added for `HealthcareEntityCategory` and `HealthcareEntityRelation`.\n\n## 5.3.0b2 (2023-03-07)\n\nThis version of the client library defaults to the service API version `2022-10-01-preview`.\n\n### Features Added\n\n- Added `begin_extract_summary` client method to perform extractive summarization on documents.\n- Added `begin_abstractive_summary` client method to perform abstractive summarization on documents.\n\n### Breaking Changes\n\n- Removed models `BaseResolution` and `BooleanResolution`.\n- Removed enum value `BooleanResolution` from `ResolutionKind`.\n- Renamed model `AbstractSummaryAction` to `AbstractiveSummaryAction`.\n- Renamed model `AbstractSummaryResult` to `AbstractiveSummaryResult`.\n- Removed keyword argument `autodetect_default_language` from long-running operation APIs.\n\n### Other Changes\n\n - Improved static typing in the client library. \n\n## 5.3.0b1 (2022-11-17)\n\nThis version of the client library defaults to the service API version `2022-10-01-preview`.\n\n### Features Added\n- Added the Extractive Summarization feature and related models: `ExtractSummaryAction`, `ExtractSummaryResult`, and `SummarySentence`.\n  Access the feature through the `begin_analyze_actions` API.\n- Added keyword arguments `fhir_version` and `document_type` to `begin_analyze_healthcare_entities` and `AnalyzeHealthcareEntitiesAction`.\n- Added property `fhir_bundle` to `AnalyzeHealthcareEntitiesResult`.\n- Added property `confidence_score` to `HealthcareRelation`.\n- Added enum `HealthcareDocumentType`.\n- Added property `resolutions` to `CategorizedEntity`.\n- Added models and enums related to resolutions: `BaseResolution`, `ResolutionKind`, `AgeResolution`, `AreaResolution`, \n  `BooleanResolution`, `CurrencyResolution`, `DateTimeResolution`, `InformationResolution`, `LengthResolution`,\n  `NumberResolution`, `NumericRangeResolution`, `OrdinalResolution`, `SpeedResolution`, `TemperatureResolution`,\n  `TemporalSpanResolution`, `VolumeResolution`, `WeightResolution`, `AgeUnit`, `AreaUnit`, `TemporalModifier`,\n  `InformationUnit`, `LengthUnit`, `NumberKind`, `RangeKind`, `RelativeTo`, `SpeedUnit`, `TemperatureUnit`,\n  `VolumeUnit`, `DateTimeSubKind`, and `WeightUnit`.\n- Added the Abstractive Summarization feature and related models: `AbstractSummaryAction`, `AbstractSummaryResult`, `AbstractiveSummary`,\n  and `SummaryContext`. Access the feature through the `begin_analyze_actions` API.\n- Added automatic language detection to long-running operation APIs. Pass `auto` into the document `language` hint to use this feature.\n- Added `autodetect_default_language` to long-running operation APIs. Pass as the default/fallback language for automatic language detection.\n- Added property `detected_language` to `RecognizeEntitiesResult`, `RecognizePiiEntitiesResult`, `AnalyzeHealthcareEntitiesResult`,\n  `ExtractKeyPhrasesResult`, `RecognizeLinkedEntitiesResult`, `AnalyzeSentimentResult`, `RecognizeCustomEntitiesResult`,\n  `ClassifyDocumentResult`, `ExtractSummaryResult`, and `AbstractSummaryResult` to indicate the language detected by automatic language detection.\n- Added property `script` to `DetectedLanguage` to indicate the script of the input document.\n- Added the `dynamic_classification` client method to perform dynamic classification on documents without needing to train a model.\n\n### Other Changes\n- Removed dependency on `msrest`.\n\n## 5.2.1 (2022-10-26)\n\n### Bugs Fixed\n- Returns a more helpful message in the document error when all documents fail for an action in the `begin_analyze_actions` API.\n\n## 5.2.0 (2022-09-08)\n\n### Other Changes\n\nThis version of the client library marks a stable release and defaults to the service API version `2022-05-01`.\nIncludes all changes from `5.2.0b1` to `5.2.0b5`.\n\n## 5.2.0b5 (2022-08-11)\n\nThe version of this client library defaults to the API version `2022-05-01`.\n\n### Features Added\n\n- Added `begin_recognize_custom_entities` client method to recognize custom named entities in documents.\n- Added `begin_single_label_classify` client method to perform custom single label classification on documents.\n- Added `begin_multi_label_classify` client method to perform custom multi label classification on documents.\n- Added property `details` on returned poller objects which contain long-running operation metadata.\n- Added `TextAnalysisLROPoller` and `AsyncTextAnalysisLROPoller` protocols to describe the return types from long-running operations.\n- Added `cancel` method on the poller objects. Call it to cancel a long-running operation that's in progress.\n- Added property `kind` to `RecognizeEntitiesResult`, `RecognizePiiEntitiesResult`, `AnalyzeHealthcareEntitiesResult`,\n  `DetectLanguageResult`, `ExtractKeyPhrasesResult`, `RecognizeLinkedEntitiesResult`, `AnalyzeSentimentResult`,\n  `RecognizeCustomEntitiesResult`, `ClassifyDocumentResult`, and `DocumentError`.\n- Added enum `TextAnalysisKind`.\n\n### Breaking Changes\n\n- Removed the Extractive Text Summarization feature and related models: `ExtractSummaryAction`, `ExtractSummaryResult`, and `SummarySentence`. To access this beta feature, install the `5.2.0b4` version of the client library.\n- Removed the `FHIR` feature and related keyword argument and property: `fhir_version` and `fhir_bundle`. To access this beta feature, install the `5.2.0b4` version of the client library.\n- `SingleCategoryClassifyResult` and `MultiCategoryClassifyResult` models have been merged into one model: `ClassifyDocumentResult`.\n- Renamed `SingleCategoryClassifyAction` to `SingleLabelClassifyAction`\n- Renamed `MultiCategoryClassifyAction` to `MultiLabelClassifyAction`.\n\n### Bugs Fixed\n\n- A `HttpResponseError` will be immediately raised when the call quota volume is exceeded in a `F0` tier Language resource.\n\n### Other Changes\n\n- Python 3.6 is no longer supported. Please use Python version 3.7 or later. For more details, see [Azure SDK for Python version support policy](https://github.com/Azure/azure-sdk-for-python/wiki/Azure-SDKs-Python-version-support-policy).\n\n\n## 5.2.0b4 (2022-05-18)\n\nNote that this is the first version of the client library that targets the Azure Cognitive Service for Language APIs which includes the existing text analysis and natural language processing features found in the Text Analytics client library.\nIn addition, the service API has changed from semantic to date-based versioning. This version of the client library defaults to the latest supported API version, which currently is `2022-04-01-preview`. Support for `v3.2-preview.2` is removed, however, all functionalities are included in the latest version.\n\n### Features Added\n\n- Added support for Healthcare Entities Analysis through the `begin_analyze_actions` API with the `AnalyzeHealthcareEntitiesAction` type.\n- Added keyword argument `fhir_version` to `begin_analyze_healthcare_entities` and `AnalyzeHealthcareEntitiesAction`. Use the keyword to indicate the version for the `fhir_bundle` contained on the `AnalyzeHealthcareEntitiesResult`.\n- Added property `fhir_bundle` to `AnalyzeHealthcareEntitiesResult`.\n- Added keyword argument `display_name` to `begin_analyze_healthcare_entities`.\n\n## 5.2.0b3 (2022-03-08)\n\n### Bugs Fixed\n- `string_index_type` now correctly defaults to the Python default `UnicodeCodePoint` for `AnalyzeSentimentAction` and `RecognizeCustomEntitiesAction`.\n- Fixed a bug in `begin_analyze_actions` where incorrect action types were being sent in the request if targeting the older API version `v3.1` in the beta version of the client library.\n- `string_index_type` option `Utf16CodePoint` is corrected to `Utf16CodeUnit`.\n\n### Other Changes\n- Python 2.7 is no longer supported. Please use Python version 3.6 or later.\n\n## 5.2.0b2 (2021-11-02)\n\nThis version of the SDK defaults to the latest supported API version, which currently is `v3.2-preview.2`.\n\n### Features Added\n- Added support for Custom Entities Recognition through the `begin_analyze_actions` API with the `RecognizeCustomEntitiesAction` and `RecognizeCustomEntitiesResult` types.\n- Added support for Custom Single Classification through the `begin_analyze_actions` API with the `SingleCategoryClassifyAction` and `SingleCategoryClassifyActionResult` types.\n- Added support for Custom Multi Classification through the `begin_analyze_actions` API with the `MultiCategoryClassifyAction` and `MultiCategoryClassifyActionResult` types.\n- Multiple of the same action type is now supported with `begin_analyze_actions`.\n\n### Bugs Fixed\n- Restarting a long-running operation from a saved state is now supported for the `begin_analyze_actions` and `begin_recognize_healthcare_entities` methods.\n- In the event of an action level error, available partial results are now returned for any successful actions in `begin_analyze_actions`.\n\n### Other Changes\n- Package requires [azure-core](https://pypi.org/project/azure-core/) version 1.19.1 or greater\n\n## 5.2.0b1 (2021-08-09)\n\nThis version of the SDK defaults to the latest supported API version, which currently is `v3.2-preview.1`.\n\n### Features Added\n- Added support for Extractive Summarization actions through the `ExtractSummaryAction` type.\n\n### Bugs Fixed\n- `RecognizePiiEntitiesAction` option `disable_service_logs` now correctly defaults to `True`.\n\n### Other Changes\n- Python 3.5 is no longer supported.\n\n## 5.1.0 (2021-07-07)\n\nThis version of the SDK defaults to the latest supported API version, which currently is `v3.1`.\nIncludes all changes from `5.1.0b1` to `5.1.0b7`.\n\nNote: this version will be the last to officially support Python 3.5, future versions will require Python 2.7 or Python 3.6+.\n\n### Features Added\n\n- Added `catagories_filter` to `RecognizePiiEntitiesAction`\n- Added `HealthcareEntityCategory`\n- Added AAD support for the `begin_analyze_healthcare_entities` methods.\n\n### Breaking Changes\n\n- Changed: the response structure of `being_analyze_actions`. Now, we return a list of results, where each result is a list of the action results for the document, in the order the documents and actions were passed.\n- Changed: `begin_analyze_actions` now accepts a single action per type. A `ValueError` is raised if duplicate actions are passed.\n- Removed: `AnalyzeActionsType`\n- Removed: `AnalyzeActionsResult`\n- Removed: `AnalyzeActionsError`\n- Removed: `HealthcareEntityRelationRoleType`\n- Changed: renamed `HealthcareEntityRelationType` to `HealthcareEntityRelation`\n- Changed: renamed `PiiEntityCategoryType` to `PiiEntityCategory`\n- Changed: renamed `PiiEntityDomainType` to `PiiEntityDomain`\n\n## 5.1.0b7 (2021-05-18)\n\n**Breaking Changes**\n- Renamed `begin_analyze_batch_actions` to `begin_analyze_actions`.\n- Renamed `AnalyzeBatchActionsType` to `AnalyzeActionsType`.\n- Renamed `AnalyzeBatchActionsResult` to `AnalyzeActionsResult`.\n- Renamed `AnalyzeBatchActionsError` to `AnalyzeActionsError`.\n- Renamed `AnalyzeHealthcareEntitiesResultItem` to `AnalyzeHealthcareEntitiesResult`.\n- Fixed `AnalyzeHealthcareEntitiesResult`'s `statistics` to be the correct type, `TextDocumentStatistics`\n- Remove `RequestStatistics`, use `TextDocumentBatchStatistics` instead\n\n**New Features**\n- Added enums `EntityConditionality`, `EntityCertainty`, and `EntityAssociation`.\n- Added `AnalyzeSentimentAction` as a supported action type for `begin_analyze_batch_actions`.\n- Added kwarg `disable_service_logs`. If set to true, you opt-out of having your text input logged on the service side for troubleshooting.\n\n## 5.1.0b6 (2021-03-09)\n\n**Breaking Changes**\n- By default, we now target the service's `v3.1-preview.4` endpoint through enum value `TextAnalyticsApiVersion.V3_1_PREVIEW`\n- Removed property `related_entities` on `HealthcareEntity` and added `entity_relations` onto the document response level for healthcare\n- Renamed properties `aspect` and `opinions` to `target` and `assessments` respectively in class `MinedOpinion`.\n- Renamed classes `AspectSentiment` and `OpinionSentiment` to `TargetSentiment` and `AssessmentSentiment` respectively.\n\n**New Features**\n- Added `RecognizeLinkedEntitiesAction` as a supported action type for `begin_analyze_batch_actions`.\n- Added parameter `categories_filter` to the `recognize_pii_entities` client method.\n- Added enum `PiiEntityCategoryType`.\n- Add property `normalized_text` to `HealthcareEntity`. This property is a normalized version of the `text` property that already\nexists on the `HealthcareEntity`\n- Add property `assertion` onto `HealthcareEntity`. This contains assertions about the entity itself, i.e. if the entity represents a diagnosis,\nis this diagnosis conditional on a symptom?\n\n**Known Issues**\n\n- `begin_analyze_healthcare_entities` is currently in gated preview and can not be used with AAD credentials. For more information, see [the Text Analytics for Health documentation](https://docs.microsoft.com/azure/cognitive-services/text-analytics/how-tos/text-analytics-for-health?tabs=ner#request-access-to-the-public-preview).\n- At time of this SDK release, the service is not respecting the value passed through `model_version` to `begin_analyze_healthcare_entities`, it only uses the latest model.\n\n## 5.1.0b5 (2021-02-10)\n\n**Breaking Changes**\n\n- Rename `begin_analyze` to `begin_analyze_batch_actions`.\n- Now instead of separate parameters for all of the different types of actions you can pass to `begin_analyze_batch_actions`, we accept one parameter `actions`,\nwhich is a list of actions you would like performed. The results of the actions are returned in the same order as when inputted.\n- The response object from `begin_analyze_batch_actions` has also changed. Now, after the completion of your long running operation, we return a paged iterable\nof action results, in the same order they've been inputted. The actual document results for each action are included under property `document_results` of\neach action result.\n\n**New Features**\n- Renamed `begin_analyze_healthcare` to `begin_analyze_healthcare_entities`.\n- Renamed `AnalyzeHealthcareResult` to `AnalyzeHealthcareEntitiesResult` and `AnalyzeHealthcareResultItem` to `AnalyzeHealthcareEntitiesResultItem`.\n- Renamed `HealthcareEntityLink` to `HealthcareEntityDataSource` and renamed its properties `id` to `entity_id` and `data_source` to `name`.\n- Removed `relations` from `AnalyzeHealthcareEntitiesResultItem` and added `related_entities` to `HealthcareEntity`.\n- Moved the cancellation logic for the Analyze Healthcare Entities service from\nthe service client to the poller object returned from `begin_analyze_healthcare_entities`.\n- Exposed Analyze Healthcare Entities operation metadata on the poller object returned from `begin_analyze_healthcare_entities`.\n- No longer need to specify `api_version=TextAnalyticsApiVersion.V3_1_PREVIEW_3` when calling `begin_analyze` and `begin_analyze_healthcare_entities`. `begin_analyze_healthcare_entities` is still in gated preview though.\n- Added a new parameter `string_index_type` to the service client methods `begin_analyze_healthcare_entities`, `analyze_sentiment`, `recognize_entities`, `recognize_pii_entities`, and `recognize_linked_entities` which tells the service how to interpret string offsets.\n- Added property `length` to `CategorizedEntity`, `SentenceSentiment`, `LinkedEntityMatch`, `AspectSentiment`, `OpinionSentiment`, `PiiEntity` and\n`HealthcareEntity`.\n\n## 5.1.0b4 (2021-01-12)\n\n**Bug Fixes**\n\n- Package requires [azure-core](https://pypi.org/project/azure-core/) version 1.8.2 or greater\n\n\n## 5.1.0b3 (2020-11-19)\n\n**New Features**\n- We have added method `begin_analyze`, which supports long-running batch process of Named Entity Recognition, Personally identifiable Information, and Key Phrase Extraction. To use, you must specify `api_version=TextAnalyticsApiVersion.V3_1_PREVIEW_3` when creating your client.\n- We have added method `begin_analyze_healthcare`, which supports the service's Health API. Since the Health API is currently only available in a gated preview, you need to have your subscription on the service's allow list, and you must specify `api_version=TextAnalyticsApiVersion.V3_1_PREVIEW_3` when creating your client. Note that since this is a gated preview, AAD is not supported. More information [here](https://docs.microsoft.com/azure/cognitive-services/text-analytics/how-tos/text-analytics-for-health?tabs=ner#request-access-to-the-public-preview).\n\n\n## 5.1.0b2 (2020-10-06)\n\n**Breaking changes**\n- Removed property `length` from `CategorizedEntity`, `SentenceSentiment`, `LinkedEntityMatch`, `AspectSentiment`, `OpinionSentiment`, and `PiiEntity`.\nTo get the length of the text in these models, just call `len()` on the `text` property.\n- When a parameter or endpoint is not compatible with the API version you specify, we will now return a `ValueError` instead of a `NotImplementedError`.\n- Client side validation of input is now disabled by default. This means there will be no `ValidationError`s thrown by the client SDK in the case of malformed input. The error will now be thrown by the service through an `HttpResponseError`.\n\n## 5.1.0b1 (2020-09-17)\n\n**New features**\n- We are now targeting the service's v3.1-preview API as the default. If you would like to still use version v3.0 of the service,\npass in `v3.0` to the kwarg `api_version` when creating your TextAnalyticsClient\n- We have added an API `recognize_pii_entities` which returns entities containing personally identifiable information for a batch of documents. Only available for API version v3.1-preview and up.\n- Added `offset` and `length` properties for `CategorizedEntity`, `SentenceSentiment`, and `LinkedEntityMatch`. These properties are only available for API versions v3.1-preview and up.\n  - `length` is the number of characters in the text of these models\n  - `offset` is the offset of the text from the start of the document\n- We now have added support for opinion mining. To use this feature, you need to make sure you are using the service's\nv3.1-preview API. To get this support pass `show_opinion_mining` as True when calling the `analyze_sentiment` endpoint\n- Add property `bing_entity_search_api_id` to the `LinkedEntity` class. This property is only available for v3.1-preview and up, and it is to be\nused in conjunction with the Bing Entity Search API to fetch additional relevant information about the returned entity.\n\n## 5.0.0 (2020-07-27)\n\n- Re-release of GA version 1.0.0 with an updated version\n\n## 1.0.0 (2020-06-09)\n\n- First stable release of the azure-ai-textanalytics package. Targets the service's v3.0 API.\n\n## 1.0.0b6 (2020-05-27)\n\n**New features**\n- We now have a `warnings` property on each document-level response object returned from the endpoints. It is a list of `TextAnalyticsWarning`s.\n- Added `text` property to `SentenceSentiment`\n\n**Breaking changes**\n- Now targets only the service's v3.0 API, instead of the v3.0-preview.1 API\n- `score` attribute of `DetectedLanguage` has been renamed to `confidence_score`\n- Removed `grapheme_offset` and `grapheme_length` from `CategorizedEntity`, `SentenceSentiment`, and `LinkedEntityMatch`\n- `TextDocumentStatistics` attribute `grapheme_count` has been renamed to `character_count`\n\n## 1.0.0b5\n\n- This was a broken release\n\n## 1.0.0b4 (2020-04-07)\n\n**Breaking changes**\n- Removed the `recognize_pii_entities` endpoint and all related models (`RecognizePiiEntitiesResult` and `PiiEntity`)\nfrom this library.\n- Removed `TextAnalyticsApiKeyCredential` and now using `AzureKeyCredential` from azure.core.credentials as key credential\n- `score` attribute has been renamed to `confidence_score` for the `CategorizedEntity`, `LinkedEntityMatch`, and\n`PiiEntity` models\n- All input parameters `inputs` have been renamed to `documents`\n\n## 1.0.0b3 (2020-03-10)\n\n**Breaking changes**\n- `SentimentScorePerLabel` has been renamed to `SentimentConfidenceScores`\n- `AnalyzeSentimentResult` and `SentenceSentiment` attribute `sentiment_scores` has been renamed to `confidence_scores`\n- `TextDocumentStatistics` attribute `character_count` has been renamed to `grapheme_count`\n- `LinkedEntity` attribute `id` has been renamed to `data_source_entity_id`\n- Parameters `country_hint` and `language` are now passed as keyword arguments\n- The keyword argument `response_hook` has been renamed to `raw_response_hook`\n- `length` and `offset` attributes have been renamed to `grapheme_length` and `grapheme_offset` for the `SentenceSentiment`,\n`CategorizedEntity`, `PiiEntity`, and `LinkedEntityMatch` models\n\n**New features**\n- Pass `country_hint=\"none\"` to not use the default country hint of `\"US\"`.\n\n**Dependency updates**\n- Adopted [azure-core](https://pypi.org/project/azure-core/) version 1.3.0 or greater\n\n## 1.0.0b2 (2020-02-11)\n\n**Breaking changes**\n\n- The single text, module-level operations `single_detect_language()`, `single_recognize_entities()`, `single_extract_key_phrases()`, `single_analyze_sentiment()`, `single_recognize_pii_entities()`, and `single_recognize_linked_entities()`\nhave been removed from the client library. Use the batching methods for optimal performance in production environments.\n- To use an API key as the credential for authenticating the client, a new credential class `TextAnalyticsApiKeyCredential(\"<api_key>\")` must be passed in for the `credential` parameter.\nPassing the API key as a string is no longer supported.\n- `detect_languages()` is renamed to `detect_language()`.\n- The `TextAnalyticsError` model has been simplified to an object with only attributes `code`, `message`, and `target`.\n- `NamedEntity` has been renamed to `CategorizedEntity` and its attributes `type` to `category` and `subtype` to `subcategory`.\n- `RecognizePiiEntitiesResult` now contains on the object a list of `PiiEntity` instead of `NamedEntity`.\n- `AnalyzeSentimentResult` attribute `document_scores` has been renamed to `sentiment_scores`.\n- `SentenceSentiment` attribute `sentence_scores` has been renamed to `sentiment_scores`.\n- `SentimentConfidenceScorePerLabel` has been renamed to `SentimentScorePerLabel`.\n- `DetectLanguageResult` no longer has attribute `detected_languages`. Use `primary_language` to access the detected language in text.\n\n**New features**\n\n- Credential class `TextAnalyticsApiKeyCredential` provides an `update_key()` method which allows you to update the API key for long-lived clients.\n\n**Fixes and improvements**\n\n- `__repr__` has been added to all of the response objects.\n- If you try to access a result attribute on a `DocumentError` object, an `AttributeError` is raised with a custom error message that provides the document ID and error of the invalid document.\n\n\n## 1.0.0b1 (2020-01-09)\n\nVersion (1.0.0b1) is the first preview of our efforts to create a user-friendly and Pythonic client library for Azure Text Analytics. For more information about this, and preview releases of other Azure SDK libraries, please visit\nhttps://azure.github.io/azure-sdk/releases/latest/python.html.\n\n**Breaking changes: New API design**\n\n- New namespace/package name:\n  - The namespace/package name for Azure Text Analytics client library has changed from `azure.cognitiveservices.language.textanalytics` to `azure.ai.textanalytics`\n\n- New operations and naming:\n  - `detect_language` is renamed to `detect_languages`\n  - `entities` is renamed to `recognize_entities`\n  - `key_phrases` is renamed to `extract_key_phrases`\n  - `sentiment` is renamed to `analyze_sentiment`\n  - New operation `recognize_pii_entities` finds personally identifiable information entities in text\n  - New operation `recognize_linked_entities` provides links from a well-known knowledge base for each recognized entity\n  - New module-level operations `single_detect_language`, `single_recognize_entities`, `single_extract_key_phrases`, `single_analyze_sentiment`, `single_recognize_pii_entities`, and `single_recognize_linked_entities` perform\n  function on a single string instead of a batch of text documents and can be imported from the `azure.ai.textanalytics` namespace.\n  - New client and module-level async APIs added to subnamespace `azure.ai.textanalytics.aio`.\n  - `MultiLanguageInput` has been renamed to `TextDocumentInput`\n  - `LanguageInput` has been renamed to `DetectLanguageInput`\n  - `DocumentLanguage` has been renamed to `DetectLanguageResult`\n  - `DocumentEntities` has been renamed to `RecognizeEntitiesResult`\n  - `DocumentLinkedEntities` has been renamed to `RecognizeLinkedEntitiesResult`\n  - `DocumentKeyPhrases` has been renamed to `ExtractKeyPhrasesResult`\n  - `DocumentSentiment` has been renamed to `AnalyzeSentimentResult`\n  - `DocumentStatistics` has been renamed to `TextDocumentStatistics`\n  - `RequestStatistics` has been renamed to `TextDocumentBatchStatistics`\n  - `Entity` has been renamed to `NamedEntity`\n  - `Match` has been renamed to `LinkedEntityMatch`\n  - The batching methods' `documents` parameter has been renamed `inputs`\n\n- New input types:\n  - `detect_languages` can take as input a `list[DetectLanguageInput]` or a `list[str]`. A list of dict-like objects in the same shape as `DetectLanguageInput` is still accepted as input.\n  - `recognize_entities`, `recognize_pii_entities`, `recognize_linked_entities`, `extract_key_phrases`, `analyze_sentiment` can take as input a `list[TextDocumentInput]` or `list[str]`.\n  A list of dict-like objects in the same shape as `TextDocumentInput` is still accepted as input.\n\n- New parameters/keyword arguments:\n  - All operations now take a keyword argument `model_version` which allows the user to specify a string referencing the desired model version to be used for analysis. If no string specified, it will default to the latest, non-preview version.\n  - `detect_languages` now takes a parameter `country_hint` which allows you to specify the country hint for the entire batch. Any per-item country hints will take precedence over a whole batch hint.\n  - `recognize_entities`, `recognize_pii_entities`, `recognize_linked_entities`, `extract_key_phrases`, `analyze_sentiment` now take a parameter `language` which allows you to specify the language for the entire batch.\n  Any per-item specified language will take precedence over a whole batch hint.\n  - A `default_country_hint` or `default_language` keyword argument can be passed at client instantiation to set the default values for all operations.\n  - A `response_hook` keyword argument can be passed with a callback to use the raw response from the service. Additionally, values returned for `TextDocumentBatchStatistics` and `model_version` used must be retrieved using a response hook.\n  - `show_stats` and `model_version` parameters move to keyword only arguments.\n\n- New return types\n  - The return types for the batching methods (`detect_languages`, `recognize_entities`, `recognize_pii_entities`, `recognize_linked_entities`, `extract_key_phrases`, `analyze_sentiment`) now return a heterogeneous list of\n  result objects and document errors in the order passed in with the request. To iterate over the list and filter for result or error, a boolean property on each object called `is_error` can be used to determine whether the returned response object at\n  that index is a result or an error:\n  - `detect_languages` now returns a List[Union[`DetectLanguageResult`, `DocumentError`]]\n  - `recognize_entities` now returns a List[Union[`RecognizeEntitiesResult`, `DocumentError`]]\n  - `recognize_pii_entities` now returns a List[Union[`RecognizePiiEntitiesResult`, `DocumentError`]]\n  - `recognize_linked_entities` now returns a List[Union[`RecognizeLinkedEntitiesResult`, `DocumentError`]]\n  - `extract_key_phrases` now returns a List[Union[`ExtractKeyPhrasesResult`, `DocumentError`]]\n  - `analyze_sentiment` now returns a List[Union[`AnalyzeSentimentResult`, `DocumentError`]]\n  - The module-level, single text operations will return a single result object or raise the error found on the document:\n  - `single_detect_languages` returns a `DetectLanguageResult`\n  - `single_recognize_entities` returns a `RecognizeEntitiesResult`\n  - `single_recognize_pii_entities` returns a `RecognizePiiEntitiesResult`\n  - `single_recognize_linked_entities` returns a `RecognizeLinkedEntitiesResult`\n  - `single_extract_key_phrases` returns a `ExtractKeyPhrasesResult`\n  - `single_analyze_sentiment` returns a `AnalyzeSentimentResult`\n\n- New underlying REST pipeline implementation, based on the new `azure-core` library.\n- Client and pipeline configuration is now available via keyword arguments at both the client level, and per-operation. See README for a full list of optional configuration arguments.\n- Authentication using `azure-identity` credentials\n  - see the\n  [Azure Identity documentation](https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/identity/azure-identity/README.md)\n  for more information\n- New error hierarchy:\n    - All service errors will now use the base type: `azure.core.exceptions.HttpResponseError`\n    - There is one exception type derived from this base type for authentication errors:\n        - `ClientAuthenticationError`: Authentication failed.\n\n## 0.2.0 (2019-03-12)\n\n**Features**\n\n- Client class can be used as a context manager to keep the underlying HTTP session open for performance\n- New method \"entities\"\n- Model KeyPhraseBatchResultItem has a new parameter statistics\n- Model KeyPhraseBatchResult has a new parameter statistics\n- Model LanguageBatchResult has a new parameter statistics\n- Model LanguageBatchResultItem has a new parameter statistics\n- Model SentimentBatchResult has a new parameter statistics\n\n**Breaking changes**\n\n- TextAnalyticsAPI main client has been renamed TextAnalyticsClient\n- TextAnalyticsClient parameter is no longer a region but a complete endpoint\n\n**General Breaking changes**\n\nThis version uses a next-generation code generator that *might* introduce breaking changes.\n\n- Model signatures now use only keyword-argument syntax. All positional arguments must be re-written as keyword-arguments.\n  To keep auto-completion in most cases, models are now generated for Python 2 and Python 3. Python 3 uses the \"*\" syntax for keyword-only arguments.\n- Enum types now use the \"str\" mixin (class AzureEnum(str, Enum)) to improve the behavior when unrecognized enum values are encountered.\n  While this is not a breaking change, the distinctions are important, and are documented here:\n  https://docs.python.org/3/library/enum.html#others\n  At a glance:\n\n  - \"is\" should not be used at all.\n  - \"format\" will return the string value, where \"%s\" string formatting will return `NameOfEnum.stringvalue`. Format syntax should be preferred.\n\n**Bugfixes**\n\n- Compatibility of the sdist with wheel 0.31.0\n\n\n## 0.1.0 (2018-01-12)\n\n* Initial Release\n",
    "bugtrack_url": null,
    "license": "MIT License",
    "summary": "Microsoft Azure Text Analytics Client Library for Python",
    "version": "5.3.0",
    "project_urls": {
        "Homepage": "https://github.com/Azure/azure-sdk-for-python"
    },
    "split_keywords": [
        "azure",
        "azure sdk",
        "text analytics",
        "cognitive services",
        "natural language processing"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "fa2958c3ec979ba9b6ce14db7f8bc96792d8c240e490704864bda39f06110964",
                "md5": "11bb8fcc03a24d2de770f5ac9eb4ab7b",
                "sha256": "69bb736d93de81060e9075d42b6f0b92c25be0fb106da5cb6a6d30e772168221"
            },
            "downloads": -1,
            "filename": "azure_ai_textanalytics-5.3.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "11bb8fcc03a24d2de770f5ac9eb4ab7b",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 298631,
            "upload_time": "2023-06-15T21:14:36",
            "upload_time_iso_8601": "2023-06-15T21:14:36.369048Z",
            "url": "https://files.pythonhosted.org/packages/fa/29/58c3ec979ba9b6ce14db7f8bc96792d8c240e490704864bda39f06110964/azure_ai_textanalytics-5.3.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "3cf4459094eca3819b5dbe01d816a135b71eb37f16b5b50944d8e1eaaa79b88a",
                "md5": "db8cef49eadf3d0506c020269d79bf93",
                "sha256": "4f7d067d5bb08422599ca6175510d39b0911c711301647e5f18e904a5027bf58"
            },
            "downloads": -1,
            "filename": "azure-ai-textanalytics-5.3.0.zip",
            "has_sig": false,
            "md5_digest": "db8cef49eadf3d0506c020269d79bf93",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 538663,
            "upload_time": "2023-06-15T21:14:32",
            "upload_time_iso_8601": "2023-06-15T21:14:32.483061Z",
            "url": "https://files.pythonhosted.org/packages/3c/f4/459094eca3819b5dbe01d816a135b71eb37f16b5b50944d8e1eaaa79b88a/azure-ai-textanalytics-5.3.0.zip",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-06-15 21:14:32",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Azure",
    "github_project": "azure-sdk-for-python",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "lcname": "azure-ai-textanalytics"
}
        
Elapsed time: 0.08354s