Microsoft Azure Text Analytics Client Library for Python
Project description
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
Source code | Package (PyPI) | API reference documentation | Product documentation | Samples
Disclaimer
Azure SDK Python packages support for Python 2.7 has ended 01 January 2022. For more information and questions, please refer to https://github.com/Azure/azure-sdk-for-python/issues/20691
Getting started
Prerequisites
- Python 3.7 later is required to use this package.
- You must have an Azure subscription and a Cognitive Services or Language service resource to use this package.
Create a Cognitive Services or Language service resource
The Language service supports both multi-service and single-service access. 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
Option 1: Azure Portal
Option 2: Azure CLI. Below is an example of how you can create a Language service resource using the CLI:
# Create a new resource group to hold the Language service resource -
# if using an existing resource group, skip this step
az group create --name my-resource-group --location westus2
# Create text analytics
az cognitiveservices account create \
--name text-analytics-resource \
--resource-group my-resource-group \
--kind TextAnalytics \
--sku F0 \
--location westus2 \
--yes
Interaction with the service using the client library begins with a client.
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:
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 install azure-ai-textanalytics
Note that
5.2.Xtargets 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 is2022-05-01.
This table shows the relationship between SDK versions and supported API versions of the service
| SDK version | Supported API version of service |
|---|---|
| 5.2.0 - Latest stable release | 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 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 or Azure CLI:
# Get the endpoint for the Language service resource
az cognitiveservices account show --name "resource-name" --resource-group "resource-group-name" --query "properties.endpoint"
Get the API Key
You can get the API key from the Cognitive Services or Language service resource in the Azure Portal. Alternatively, you can use Azure CLI 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. Use the key as the credential parameter to authenticate the client:
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)
Create a TextAnalyticsClient with an Azure Active Directory Credential
To use an Azure Active Directory (AAD) token credential, provide an instance of the desired credential type obtained from the azure-identity library. Note that regional endpoints do not support AAD authentication. Create a custom subdomain name for your resource in order to use this type of authentication.
Authentication with AAD requires some initial setup:
- Install azure-identity
- Register a new AAD application
- Grant 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 from azure.identity to use. As an example, DefaultAzureCredential 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:
from azure.ai.textanalytics import TextAnalyticsClient
from azure.identity import DefaultAzureCredential
credential = DefaultAzureCredential()
text_analytics_client = TextAnalyticsClient(endpoint="https://<resource-name>.cognitiveservices.azure.com/", credential=credential)
Key concepts
TextAnalyticsClient
The Text Analytics client library provides a TextAnalyticsClient to do analysis on batches of documents. 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.
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 or
TextDocumentInput
or a dict-like representation of the object:
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 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, is the result of a text analysis operation and contains a prediction or predictions about a document input.
The error object, DocumentError, 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 this is True.
For example, to filter out all DocumentErrors you might use list comprehension:
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:
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
The following section provides several code snippets covering some of the most common Language service tasks, including:
- Analyze Sentiment
- Recognize Entities
- Recognize Linked Entities
- Recognize PII Entities
- Extract Key Phrases
- Detect Language
- Healthcare Entities Analysis
- Multiple Analysis
- Custom Entity Recognition
- Custom Single Label Classification
- Custom Multi Label Classification
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.
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient
credential = AzureKeyCredential("<api_key>")
endpoint="https://<resource-name>.cognitiveservices.azure.com/"
text_analytics_client = TextAnalyticsClient(endpoint, credential)
documents = [
"I did not like the restaurant. The food was somehow both too spicy and underseasoned. Additionally, I thought the location was too far away from the playhouse.",
"The restaurant was decorated beautifully. The atmosphere was unlike any other restaurant I've been to.",
"The food was yummy. :)"
]
response = text_analytics_client.analyze_sentiment(documents, language="en")
result = [doc for doc in response if not doc.is_error]
for doc in result:
print(f"Overall sentiment: {doc.sentiment}")
print(
f"Scores: positive={doc.confidence_scores.positive}; "
f"neutral={doc.confidence_scores.neutral}; "
f"negative={doc.confidence_scores.negative}\n"
)
The returned response is a heterogeneous list of result and error objects: list[AnalyzeSentimentResult, DocumentError]
Please refer to the service documentation for a conceptual discussion of 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.
Recognize entities
recognize_entities recognizes and categories entities in its input text as people, places, organizations, date/time, quantities, percentages, currencies, and more.
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient
credential = AzureKeyCredential("<api_key>")
endpoint="https://<resource-name>.cognitiveservices.azure.com/"
text_analytics_client = TextAnalyticsClient(endpoint, credential)
documents = [
"""
Microsoft was founded by Bill Gates and Paul Allen. Its headquarters are located in Redmond. Redmond is a
city in King County, Washington, United States, located 15 miles east of Seattle.
""",
"Jeff bought three dozen eggs because there was a 50% discount."
]
response = text_analytics_client.recognize_entities(documents, language="en")
result = [doc for doc in response if not doc.is_error]
for doc in result:
for entity in doc.entities:
print(f"Entity: {entity.text}")
print(f"...Category: {entity.category}")
print(f"...Confidence Score: {entity.confidence_score}")
print(f"...Offset: {entity.offset}")
The returned response is a heterogeneous list of result and error objects: list[RecognizeEntitiesResult, DocumentError]
Please refer to the service documentation for a conceptual discussion of named entity recognition and supported types.
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.
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient
credential = AzureKeyCredential("<api_key>")
endpoint="https://<resource-name>.cognitiveservices.azure.com/"
text_analytics_client = TextAnalyticsClient(endpoint, credential)
documents = [
"Microsoft was founded by Bill Gates and Paul Allen. Its headquarters are located in Redmond.",
"Easter Island, a Chilean territory, is a remote volcanic island in Polynesia."
]
response = text_analytics_client.recognize_linked_entities(documents, language="en")
result = [doc for doc in response if not doc.is_error]
for doc in result:
for entity in doc.entities:
print(f"Entity: {entity.name}")
print(f"...URL: {entity.url}")
print(f"...Data Source: {entity.data_source}")
print("...Entity matches:")
for match in entity.matches:
print(f"......Entity match text: {match.text}")
print(f"......Confidence Score: {match.confidence_score}")
print(f"......Offset: {match.offset}")
The returned response is a heterogeneous list of result and error objects: list[RecognizeLinkedEntitiesResult, DocumentError]
Please refer to the service documentation for a conceptual discussion of entity linking and supported types.
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.
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient
credential = AzureKeyCredential("<api_key>")
endpoint="https://<resource-name>.cognitiveservices.azure.com/"
text_analytics_client = TextAnalyticsClient(endpoint, credential)
documents = [
"""
We have an employee called Parker who cleans up after customers. The employee's
SSN is 859-98-0987, and their phone number is 555-555-5555.
"""
]
response = text_analytics_client.recognize_pii_entities(documents, language="en")
result = [doc for doc in response if not doc.is_error]
for idx, doc in enumerate(result):
print(f"Document text: {documents[idx]}")
print(f"Redacted document text: {doc.redacted_text}")
for entity in doc.entities:
print(f"...Entity: {entity.text}")
print(f"......Category: {entity.category}")
print(f"......Confidence Score: {entity.confidence_score}")
print(f"......Offset: {entity.offset}")
The returned response is a heterogeneous list of result and error objects: list[RecognizePiiEntitiesResult, DocumentError]
Please refer to the service documentation for supported PII entity types.
Note: The Recognize PII Entities service is available in API version v3.1 and newer.
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".
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient
credential = AzureKeyCredential("<api_key>")
endpoint="https://<resource-name>.cognitiveservices.azure.com/"
text_analytics_client = TextAnalyticsClient(endpoint, credential)
documents = [
"Redmond is a city in King County, Washington, United States, located 15 miles east of Seattle.",
"""
I need to take my cat to the veterinarian. He has been sick recently, and I need to take him
before I travel to South America for the summer.
""",
]
response = text_analytics_client.extract_key_phrases(documents, language="en")
result = [doc for doc in response if not doc.is_error]
for doc in result:
print(doc.key_phrases)
The returned response is a heterogeneous list of result and error objects: list[ExtractKeyPhrasesResult, DocumentError]
Please refer to the service documentation for a conceptual discussion of key phrase extraction.
Detect language
detect_language determines the language of its input text, including the confidence score of the predicted language.
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient
credential = AzureKeyCredential("<api_key>")
endpoint="https://<resource-name>.cognitiveservices.azure.com/"
text_analytics_client = TextAnalyticsClient(endpoint, credential)
documents = [
"""
This whole document is written in English. In order for the whole document to be written
in English, every sentence also has to be written in English, which it is.
""",
"Il documento scritto in italiano.",
"Dies ist in deutsche Sprache verfasst."
]
response = text_analytics_client.detect_language(documents)
result = [doc for doc in response if not doc.is_error]
for doc in result:
print(f"Language detected: {doc.primary_language.name}")
print(f"ISO6391 name: {doc.primary_language.iso6391_name}")
print(f"Confidence score: {doc.primary_language.confidence_score}\n")
The returned response is a heterogeneous list of result and error objects: list[DetectLanguageResult, DocumentError]
Please refer to the service documentation for a conceptual discussion of language detection and language and regional support.
Healthcare Entities Analysis
Long-running operation begin_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.
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient
credential = AzureKeyCredential("<api_key>")
endpoint="https://<resource-name>.cognitiveservices.azure.com/"
text_analytics_client = TextAnalyticsClient(endpoint, credential)
documents = ["Subject is taking 100mg of ibuprofen twice daily"]
poller = text_analytics_client.begin_analyze_healthcare_entities(documents)
result = poller.result()
docs = [doc for doc in result if not doc.is_error]
print("Results of Healthcare Entities Analysis:")
for idx, doc in enumerate(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("------------------------------------------")
Note: Healthcare Entities Analysis is only available with API version v3.1 and newer.
Multiple Analysis
Long-running operation begin_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
- Custom Single Label Classification
- Custom Multi Label Classification
- Healthcare Entities Analysis
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import (
TextAnalyticsClient,
RecognizeEntitiesAction,
AnalyzeSentimentAction,
)
credential = AzureKeyCredential("<api_key>")
endpoint="https://<resource-name>.cognitiveservices.azure.com/"
text_analytics_client = TextAnalyticsClient(endpoint, credential)
documents = ["Microsoft was founded by Bill Gates and Paul Allen."]
poller = text_analytics_client.begin_analyze_actions(
documents,
display_name="Sample Text Analysis",
actions=[
RecognizeEntitiesAction(),
AnalyzeSentimentAction()
]
)
# returns multiple actions results in the same order as the inputted actions
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 == "SentimentAnalysis":
print("...Results of Analyze Sentiment action:")
print(f"......Overall sentiment: {result.sentiment}")
print(f"......Scores: positive={result.confidence_scores.positive}; "
f"neutral={result.confidence_scores.neutral}; "
f"negative={result.confidence_scores.negative}\n")
elif result.is_error is True:
print(f"......Is an error with code '{result.code}' "
f"and message '{result.message}'")
print("------------------------------------------")
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 describes available configurations for retries, logging, transport protocols, and more.
Troubleshooting
General
The Text Analytics client will raise exceptions defined in Azure Core.
Logging
This library uses the standard 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:
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:
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:
Common scenarios
- Analyze sentiment: sample_analyze_sentiment.py (async version)
- Recognize entities: sample_recognize_entities.py (async version)
- Recognize personally identifiable information: sample_recognize_pii_entities.py (async version)
- Recognize linked entities: sample_recognize_linked_entities.py (async version)
- Extract key phrases: sample_extract_key_phrases.py (async version)
- Detect language: sample_detect_language.py (async version)
- Healthcare Entities Analysis: sample_analyze_healthcare_entities.py (async version)
- Multiple Analysis: sample_analyze_actions.py (async version)
- Custom Entity Recognition: sample_recognize_custom_entities.py (async_version)
- Custom Single Label Classification: sample_single_label_classify.py (async_version)
- Custom Multi Label Classification: sample_multi_label_classify.py (async_version)
Advanced scenarios
- Opinion Mining: sample_analyze_sentiment_with_opinion_mining.py (async_version)
Additional documentation
For more extensive documentation on Azure Cognitive Service for Language, see the Language Service 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.
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. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
Release History
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_entitiesclient method to recognize custom named entities in documents. - Added
begin_single_label_classifyclient method to perform custom single label classification on documents. - Added
begin_multi_label_classifyclient method to perform custom multi label classification on documents. - Added property
detailson returned poller objects which contain long-running operation metadata. - Added
TextAnalysisLROPollerandAsyncTextAnalysisLROPollerprotocols to describe the return types from long-running operations. - Added
cancelmethod on the poller objects. Call it to cancel a long-running operation that's in progress. - Added property
kindtoRecognizeEntitiesResult,RecognizePiiEntitiesResult,AnalyzeHealthcareEntitiesResult,DetectLanguageResult,ExtractKeyPhrasesResult,RecognizeLinkedEntitiesResult,AnalyzeSentimentResult,RecognizeCustomEntitiesResult,ClassifyDocumentResult, andDocumentError. - Added enum
TextAnalysisKind.
Breaking Changes
- Removed the Extractive Text Summarization feature and related models:
ExtractSummaryAction,ExtractSummaryResult, andSummarySentence. To access this beta feature, install the5.2.0b4version of the client library. - Removed the
FHIRfeature and related keyword argument and property:fhir_versionandfhir_bundle. To access this beta feature, install the5.2.0b4version of the client library. SingleCategoryClassifyResultandMultiCategoryClassifyResultmodels have been merged into one model:ClassifyDocumentResult.- Renamed
SingleCategoryClassifyActiontoSingleLabelClassifyAction - Renamed
MultiCategoryClassifyActiontoMultiLabelClassifyAction.
Bugs Fixed
- A
HttpResponseErrorwill be immediately raised when the call quota volume is exceeded in aF0tier 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.
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_actionsAPI with theAnalyzeHealthcareEntitiesActiontype. - Added keyword argument
fhir_versiontobegin_analyze_healthcare_entitiesandAnalyzeHealthcareEntitiesAction. Use the keyword to indicate the version for thefhir_bundlecontained on theAnalyzeHealthcareEntitiesResult. - Added property
fhir_bundletoAnalyzeHealthcareEntitiesResult. - Added keyword argument
display_nametobegin_analyze_healthcare_entities.
5.2.0b3 (2022-03-08)
Bugs Fixed
string_index_typenow correctly defaults to the Python defaultUnicodeCodePointforAnalyzeSentimentActionandRecognizeCustomEntitiesAction.- Fixed a bug in
begin_analyze_actionswhere incorrect action types were being sent in the request if targeting the older API versionv3.1in the beta version of the client library. string_index_typeoptionUtf16CodePointis corrected toUtf16CodeUnit.
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_actionsAPI with theRecognizeCustomEntitiesActionandRecognizeCustomEntitiesResulttypes. - Added support for Custom Single Classification through the
begin_analyze_actionsAPI with theSingleCategoryClassifyActionandSingleCategoryClassifyActionResulttypes. - Added support for Custom Multi Classification through the
begin_analyze_actionsAPI with theMultiCategoryClassifyActionandMultiCategoryClassifyActionResulttypes. - 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_actionsandbegin_recognize_healthcare_entitiesmethods. - 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 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
ExtractSummaryActiontype.
Bugs Fixed
RecognizePiiEntitiesActionoptiondisable_service_logsnow correctly defaults toTrue.
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_filtertoRecognizePiiEntitiesAction - Added
HealthcareEntityCategory - Added AAD support for the
begin_analyze_healthcare_entitiesmethods.
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_actionsnow accepts a single action per type. AValueErroris raised if duplicate actions are passed. - Removed:
AnalyzeActionsType - Removed:
AnalyzeActionsResult - Removed:
AnalyzeActionsError - Removed:
HealthcareEntityRelationRoleType - Changed: renamed
HealthcareEntityRelationTypetoHealthcareEntityRelation - Changed: renamed
PiiEntityCategoryTypetoPiiEntityCategory - Changed: renamed
PiiEntityDomainTypetoPiiEntityDomain
5.1.0b7 (2021-05-18)
Breaking Changes
- Renamed
begin_analyze_batch_actionstobegin_analyze_actions. - Renamed
AnalyzeBatchActionsTypetoAnalyzeActionsType. - Renamed
AnalyzeBatchActionsResulttoAnalyzeActionsResult. - Renamed
AnalyzeBatchActionsErrortoAnalyzeActionsError. - Renamed
AnalyzeHealthcareEntitiesResultItemtoAnalyzeHealthcareEntitiesResult. - Fixed
AnalyzeHealthcareEntitiesResult'sstatisticsto be the correct type,TextDocumentStatistics - Remove
RequestStatistics, useTextDocumentBatchStatisticsinstead
New Features
- Added enums
EntityConditionality,EntityCertainty, andEntityAssociation. - Added
AnalyzeSentimentActionas a supported action type forbegin_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.4endpoint through enum valueTextAnalyticsApiVersion.V3_1_PREVIEW - Removed property
related_entitiesonHealthcareEntityand addedentity_relationsonto the document response level for healthcare - Renamed properties
aspectandopinionstotargetandassessmentsrespectively in classMinedOpinion. - Renamed classes
AspectSentimentandOpinionSentimenttoTargetSentimentandAssessmentSentimentrespectively.
New Features
- Added
RecognizeLinkedEntitiesActionas a supported action type forbegin_analyze_batch_actions. - Added parameter
categories_filterto therecognize_pii_entitiesclient method. - Added enum
PiiEntityCategoryType. - Add property
normalized_texttoHealthcareEntity. This property is a normalized version of thetextproperty that already exists on theHealthcareEntity - Add property
assertionontoHealthcareEntity. 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_entitiesis currently in gated preview and can not be used with AAD credentials. For more information, see the Text Analytics for Health documentation.- At time of this SDK release, the service is not respecting the value passed through
model_versiontobegin_analyze_healthcare_entities, it only uses the latest model.
5.1.0b5 (2021-02-10)
Breaking Changes
- Rename
begin_analyzetobegin_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 parameteractions, 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_actionshas 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 propertydocument_resultsof each action result.
New Features
- Renamed
begin_analyze_healthcaretobegin_analyze_healthcare_entities. - Renamed
AnalyzeHealthcareResulttoAnalyzeHealthcareEntitiesResultandAnalyzeHealthcareResultItemtoAnalyzeHealthcareEntitiesResultItem. - Renamed
HealthcareEntityLinktoHealthcareEntityDataSourceand renamed its propertiesidtoentity_idanddata_sourcetoname. - Removed
relationsfromAnalyzeHealthcareEntitiesResultItemand addedrelated_entitiestoHealthcareEntity. - 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_3when callingbegin_analyzeandbegin_analyze_healthcare_entities.begin_analyze_healthcare_entitiesis still in gated preview though. - Added a new parameter
string_index_typeto the service client methodsbegin_analyze_healthcare_entities,analyze_sentiment,recognize_entities,recognize_pii_entities, andrecognize_linked_entitieswhich tells the service how to interpret string offsets. - Added property
lengthtoCategorizedEntity,SentenceSentiment,LinkedEntityMatch,AspectSentiment,OpinionSentiment,PiiEntityandHealthcareEntity.
5.1.0b4 (2021-01-12)
Bug Fixes
- Package requires 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 specifyapi_version=TextAnalyticsApiVersion.V3_1_PREVIEW_3when 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 specifyapi_version=TextAnalyticsApiVersion.V3_1_PREVIEW_3when creating your client. Note that since this is a gated preview, AAD is not supported. More information here.
5.1.0b2 (2020-10-06)
Breaking changes
- Removed property
lengthfromCategorizedEntity,SentenceSentiment,LinkedEntityMatch,AspectSentiment,OpinionSentiment, andPiiEntity. To get the length of the text in these models, just calllen()on thetextproperty. - When a parameter or endpoint is not compatible with the API version you specify, we will now return a
ValueErrorinstead of aNotImplementedError. - Client side validation of input is now disabled by default. This means there will be no
ValidationErrors thrown by the client SDK in the case of malformed input. The error will now be thrown by the service through anHttpResponseError.
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.0to the kwargapi_versionwhen creating your TextAnalyticsClient - We have added an API
recognize_pii_entitieswhich returns entities containing personally identifiable information for a batch of documents. Only available for API version v3.1-preview and up. - Added
offsetandlengthproperties forCategorizedEntity,SentenceSentiment, andLinkedEntityMatch. These properties are only available for API versions v3.1-preview and up.lengthis the number of characters in the text of these modelsoffsetis 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_miningas True when calling theanalyze_sentimentendpoint - Add property
bing_entity_search_api_idto theLinkedEntityclass. 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
warningsproperty on each document-level response object returned from the endpoints. It is a list ofTextAnalyticsWarnings. - Added
textproperty toSentenceSentiment
Breaking changes
- Now targets only the service's v3.0 API, instead of the v3.0-preview.1 API
scoreattribute ofDetectedLanguagehas been renamed toconfidence_score- Removed
grapheme_offsetandgrapheme_lengthfromCategorizedEntity,SentenceSentiment, andLinkedEntityMatch TextDocumentStatisticsattributegrapheme_counthas been renamed tocharacter_count
1.0.0b5
- This was a broken release
1.0.0b4 (2020-04-07)
Breaking changes
- Removed the
recognize_pii_entitiesendpoint and all related models (RecognizePiiEntitiesResultandPiiEntity) from this library. - Removed
TextAnalyticsApiKeyCredentialand now usingAzureKeyCredentialfrom azure.core.credentials as key credential scoreattribute has been renamed toconfidence_scorefor theCategorizedEntity,LinkedEntityMatch, andPiiEntitymodels- All input parameters
inputshave been renamed todocuments
1.0.0b3 (2020-03-10)
Breaking changes
SentimentScorePerLabelhas been renamed toSentimentConfidenceScoresAnalyzeSentimentResultandSentenceSentimentattributesentiment_scoreshas been renamed toconfidence_scoresTextDocumentStatisticsattributecharacter_counthas been renamed tographeme_countLinkedEntityattributeidhas been renamed todata_source_entity_id- Parameters
country_hintandlanguageare now passed as keyword arguments - The keyword argument
response_hookhas been renamed toraw_response_hook lengthandoffsetattributes have been renamed tographeme_lengthandgrapheme_offsetfor theSentenceSentiment,CategorizedEntity,PiiEntity, andLinkedEntityMatchmodels
New features
- Pass
country_hint="none"to not use the default country hint of"US".
Dependency updates
- Adopted 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(), andsingle_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 thecredentialparameter. Passing the API key as a string is no longer supported. detect_languages()is renamed todetect_language().- The
TextAnalyticsErrormodel has been simplified to an object with only attributescode,message, andtarget. NamedEntityhas been renamed toCategorizedEntityand its attributestypetocategoryandsubtypetosubcategory.RecognizePiiEntitiesResultnow contains on the object a list ofPiiEntityinstead ofNamedEntity.AnalyzeSentimentResultattributedocument_scoreshas been renamed tosentiment_scores.SentenceSentimentattributesentence_scoreshas been renamed tosentiment_scores.SentimentConfidenceScorePerLabelhas been renamed toSentimentScorePerLabel.DetectLanguageResultno longer has attributedetected_languages. Useprimary_languageto access the detected language in text.
New features
- Credential class
TextAnalyticsApiKeyCredentialprovides anupdate_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
DocumentErrorobject, anAttributeErroris 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.textanalyticstoazure.ai.textanalytics
- The namespace/package name for Azure Text Analytics client library has changed from
-
New operations and naming:
detect_languageis renamed todetect_languagesentitiesis renamed torecognize_entitieskey_phrasesis renamed toextract_key_phrasessentimentis renamed toanalyze_sentiment- New operation
recognize_pii_entitiesfinds personally identifiable information entities in text - New operation
recognize_linked_entitiesprovides 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, andsingle_recognize_linked_entitiesperform function on a single string instead of a batch of text documents and can be imported from theazure.ai.textanalyticsnamespace. - New client and module-level async APIs added to subnamespace
azure.ai.textanalytics.aio. MultiLanguageInputhas been renamed toTextDocumentInputLanguageInputhas been renamed toDetectLanguageInputDocumentLanguagehas been renamed toDetectLanguageResultDocumentEntitieshas been renamed toRecognizeEntitiesResultDocumentLinkedEntitieshas been renamed toRecognizeLinkedEntitiesResultDocumentKeyPhraseshas been renamed toExtractKeyPhrasesResultDocumentSentimenthas been renamed toAnalyzeSentimentResultDocumentStatisticshas been renamed toTextDocumentStatisticsRequestStatisticshas been renamed toTextDocumentBatchStatisticsEntityhas been renamed toNamedEntityMatchhas been renamed toLinkedEntityMatch- The batching methods'
documentsparameter has been renamedinputs
-
New input types:
detect_languagescan take as input alist[DetectLanguageInput]or alist[str]. A list of dict-like objects in the same shape asDetectLanguageInputis still accepted as input.recognize_entities,recognize_pii_entities,recognize_linked_entities,extract_key_phrases,analyze_sentimentcan take as input alist[TextDocumentInput]orlist[str]. A list of dict-like objects in the same shape asTextDocumentInputis still accepted as input.
-
New parameters/keyword arguments:
- All operations now take a keyword argument
model_versionwhich 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_languagesnow takes a parametercountry_hintwhich 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_sentimentnow take a parameterlanguagewhich 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_hintordefault_languagekeyword argument can be passed at client instantiation to set the default values for all operations. - A
response_hookkeyword argument can be passed with a callback to use the raw response from the service. Additionally, values returned forTextDocumentBatchStatisticsandmodel_versionused must be retrieved using a response hook. show_statsandmodel_versionparameters move to keyword only arguments.
- All operations now take a keyword argument
-
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 calledis_errorcan be used to determine whether the returned response object at that index is a result or an error: detect_languagesnow returns a List[Union[DetectLanguageResult,DocumentError]]recognize_entitiesnow returns a List[Union[RecognizeEntitiesResult,DocumentError]]recognize_pii_entitiesnow returns a List[Union[RecognizePiiEntitiesResult,DocumentError]]recognize_linked_entitiesnow returns a List[Union[RecognizeLinkedEntitiesResult,DocumentError]]extract_key_phrasesnow returns a List[Union[ExtractKeyPhrasesResult,DocumentError]]analyze_sentimentnow 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_languagesreturns aDetectLanguageResultsingle_recognize_entitiesreturns aRecognizeEntitiesResultsingle_recognize_pii_entitiesreturns aRecognizePiiEntitiesResultsingle_recognize_linked_entitiesreturns aRecognizeLinkedEntitiesResultsingle_extract_key_phrasesreturns aExtractKeyPhrasesResultsingle_analyze_sentimentreturns aAnalyzeSentimentResult
- The return types for the batching methods (
-
New underlying REST pipeline implementation, based on the new
azure-corelibrary. -
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-identitycredentials- see the Azure Identity documentation 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.
- All service errors will now use the base type:
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
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file azure-ai-textanalytics-5.2.0.zip.
File metadata
- Download URL: azure-ai-textanalytics-5.2.0.zip
- Upload date:
- Size: 1.5 MB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.28.1 setuptools/58.1.0 requests-toolbelt/0.9.1 tqdm/4.64.1 CPython/3.9.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9ee9eda31082932f38c2372aefefc33b8a85c45d2566d1dcd7b034b7e4c31f77
|
|
| MD5 |
688cedde6bf2e983723a48310aec8ca9
|
|
| BLAKE2b-256 |
1761791c214f957083cce8accdde2de6b17416f097fc5747a2245f95065fa222
|
File details
Details for the file azure_ai_textanalytics-5.2.0-py3-none-any.whl.
File metadata
- Download URL: azure_ai_textanalytics-5.2.0-py3-none-any.whl
- Upload date:
- Size: 239.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.28.1 setuptools/58.1.0 requests-toolbelt/0.9.1 tqdm/4.64.1 CPython/3.9.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
860fdd5c4390b68dcb56be5d14057ee53f5b0662cee07fcf8d539ba76ba8dd59
|
|
| MD5 |
4f962cfd84fc8231d8e00e3926fa8af5
|
|
| BLAKE2b-256 |
8927d739a005b9fd3b69a98b4f0efcdb08bcf45009e0a883ce8d6826a35ff4b6
|