Package: azure-ai-textanalytics
Azure Text Analytics client library for PythonThe 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 AnalysisNamed Entity RecognitionLanguage DetectionKey Phrase ExtractionEntity LinkingMultiple AnalysisPersonally Identifiable Information (PII) DetectionText Analytics for HealthCustom Named Entity RecognitionCustom Text ClassificationExtractive Text SummarizationAbstractive Text SummarizationSource code|Package (PyPI)|Package (Conda)|API reference documentation|Product documentation|SamplesGetting startedPrerequisitesPython 3.7 later is required to use this package.You must have anAzure subscriptionand aCognitive Services or Language service resourceto use this package.Create a Cognitive Services or Language service resourceThe Language service supports bothmulti-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 theAzure PortalorAzure CLIfollowing the steps inthis document.Interaction with the service using the client library begins with aclient.
To create a client object, you will need the Cognitive Services or Language serviceendpointto
your resource and acredentialthat allows you access:fromazure.core.credentialsimportAzureKeyCredentialfromazure.ai.textanalyticsimportTextAnalyticsClientcredential=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 packageInstall the Azure Text Analytics client library for Python withpip:pipinstallazure-ai-textanalyticsimportosfromazure.core.credentialsimportAzureKeyCredentialfromazure.ai.textanalyticsimportTextAnalyticsClientendpoint=os.environ["AZURE_LANGUAGE_ENDPOINT"]key=os.environ["AZURE_LANGUAGE_KEY"]text_analytics_client=TextAnalyticsClient(endpoint,AzureKeyCredential(key))Note that5.2.Xand 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 is2023-04-01.This table shows the relationship between SDK versions and supported API versions of the serviceSDK versionSupported API version of service5.3.X - Latest stable release3.0, 3.1, 2022-05-01, 2023-04-01 (default)5.2.X3.0, 3.1, 2022-05-01 (default)5.1.03.0, 3.1 (default)5.0.03.0API version can be selected by passing theapi_versionkeyword 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 clientGet the endpointYou can find the endpoint for your Language service resource using theAzure PortalorAzure CLI:# Get the endpoint for the Language service resourceazcognitiveservicesaccountshow--name"resource-name"--resource-group"resource-group-name"--query"properties.endpoint"Get the API KeyYou can get theAPI keyfrom the Cognitive Services or Language service resource in theAzure Portal.
Alternatively, you can useAzure CLIsnippet 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 CredentialOnce you have the value for the API key, you can pass it as a string into an instance ofAzureKeyCredential. Use the key as the credential parameter
to authenticate the client:importosfromazure.core.credentialsimportAzureKeyCredentialfromazure.ai.textanalyticsimportTextAnalyticsClientendpoint=os.environ["AZURE_LANGUAGE_ENDPOINT"]key=os.environ["AZURE_LANGUAGE_KEY"]text_analytics_client=TextAnalyticsClient(endpoint,AzureKeyCredential(key))Create a TextAnalyticsClient with an Azure Active Directory CredentialTo use anAzure Active Directory (AAD) token credential,
provide an instance of the desired credential type obtained from theazure-identitylibrary.
Note that regional endpoints do not support AAD authentication. Create acustom subdomainname for your resource in order to use this type of authentication.Authentication with AAD requires some initial setup:Install azure-identityRegister a new AAD applicationGrant accessto the Language service by assigning the"Cognitive Services Language Reader"role to your service principal.After setup, you can choose which type ofcredentialfrom azure.identity to use.
As an example,DefaultAzureCredentialcan 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_SECRETUse the returned token credential to authenticate the client:importosfromazure.ai.textanalyticsimportTextAnalyticsClientfromazure.identityimportDefaultAzureCredentialendpoint=os.environ["AZURE_LANGUAGE_ENDPOINT"]credential=DefaultAzureCredential()text_analytics_client=TextAnalyticsClient(endpoint,credential=credential)Key conceptsTextAnalyticsClientThe Text Analytics client library provides aTextAnalyticsClientto do analysis onbatches 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.InputAdocumentis a single unit to be analyzed by the predictive models in the Language service.
The input for each operation is passed as alistof 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 documentidorlanguage/country_hint, they can be passed as a list ofDetectLanguageInputorTextDocumentInputor 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!"},]Seeservice limitationsfor the input, including document length limits, maximum batch size, and supported text encoding.Return ValueThe 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.Aresult, such asAnalyzeSentimentResult,
is the result of a text analysis operation and contains a prediction or predictions about a document input.Theerrorobject,DocumentError, indicates that the service had trouble processing the document and contains
the reason it was unsuccessful.Document Error HandlingYou can filter for a result or error object in the list by using theis_errorattribute. For a result object this is alwaysFalseand for aDocumentErrorthis isTrue.For example, to filter out all DocumentErrors you might use list comprehension:response=text_analytics_client.analyze_sentiment(documents)successful_responses=[docfordocinresponseifnotdoc.is_error]You can also use thekindattribute to filter between result types:poller=text_analytics_client.begin_analyze_actions(documents,actions)response=poller.result()forresultinresponse:ifresult.kind=="SentimentAnalysis":print(f"Sentiment is{result.sentiment}")elifresult.kind=="KeyPhraseExtraction":print(f"Key phrases:{result.key_phrases}")elifresult.is_errorisTrue:print(f"Document error:{result.code},{result.message}")Long-Running OperationsLong-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 abegin_<method-name>method that returns a poller object. Callers should wait
for the operation to complete by callingresult()on the poller object returned from thebegin_<method-name>method.
Sample code snippets are provided to illustrate using long-running operationsbelow.ExamplesThe following section provides several code snippets covering some of the most common Language service tasks, including:Analyze SentimentRecognize EntitiesRecognize Linked EntitiesRecognize PII EntitiesExtract Key PhrasesDetect LanguageHealthcare Entities AnalysisMultiple AnalysisCustom Entity RecognitionCustom Single Label ClassificationCustom Multi Label ClassificationExtractive SummarizationAbstractive SummarizationAnalyze Sentimentanalyze_sentimentlooks 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.importosfromazure.core.credentialsimportAzureKeyCredentialfromazure.ai.textanalyticsimportTextAnalyticsClientendpoint=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 wouldnot 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 rightin 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=[docfordocinresultifnotdoc.is_error]print("Let's visualize the sentiment of each of these documents")foridx,docinenumerate(docs):print(f"Document text:{documents[idx]}")print(f"Overall sentiment:{doc.sentiment}")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 ofsentiment 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, seehere.Recognize Entitiesrecognize_entitiesrecognizes and categories entities in its input text as people, places, organizations, date/time, quantities, percentages, currencies, and more.importosimporttypingfromazure.core.credentialsimportAzureKeyCredentialfromazure.ai.textanalyticsimportTextAnalyticsClientendpoint=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 foodwas 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 timecatering 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=[reviewforreviewinresultifnotreview.is_error]organization_to_reviews:typing.Dict[str,typing.List[str]]={}foridx,reviewinenumerate(result):forentityinreview.entities:print(f"Entity '{entity.text}' has category '{entity.category}'")ifentity.category=='Organization':organization_to_reviews.setdefault(entity.text,[])organization_to_reviews[entity.text].append(reviews[idx])fororganization,reviewsinorganization_to_reviews.items():print("\n\nOrganization '{}' has left us the following review(s):{}".format(organization,"\n\n".join(reviews)))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 ofnamed entity recognitionandsupported types.Recognize Linked Entitiesrecognize_linked_entitiesrecognizes 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.importosfromazure.core.credentialsimportAzureKeyCredentialfromazure.ai.textanalyticsimportTextAnalyticsClientendpoint=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 steppeddown as CEO of Microsoft, and was succeeded by Satya Nadella.Microsoft originally moved its headquarters to Bellevue, Washington in January 1979, but is nowheadquartered in Redmond."""]result=text_analytics_client.recognize_linked_entities(documents)docs=[docfordocinresultifnotdoc.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={}fordocindocs:forentityindoc.entities:print("Entity '{}' has been mentioned '{}' time(s)".format(entity.name,len(entity.matches)))ifentity.data_source=="Wikipedia":entity_to_url[entity.name]=entity.urlThe returned response is a heterogeneous list of result and error objects: list[RecognizeLinkedEntitiesResult,DocumentError]Please refer to the service documentation for a conceptual discussion ofentity linkingandsupported types.Recognize PII Entitiesrecognize_pii_entitiesrecognizes and categorizes Personally Identifiable Information (PII) entities in its input text, such as
Social Security Numbers, bank account information, credit card numbers, and more.importosfromazure.core.credentialsimportAzureKeyCredentialfromazure.ai.textanalyticsimportTextAnalyticsClientendpoint=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 number555-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=[docfordocinresultifnotdoc.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")foridx,docinenumerate(docs):print(f"Document text:{documents[idx]}")print(f"Redacted document text:{doc.redacted_text}")forentityindoc.entities:print("...Entity '{}' with category '{}' got redacted".format(entity.text,entity.category))The returned response is a heterogeneous list of result and error objects: list[RecognizePiiEntitiesResult,DocumentError]Please refer to the service documentation forsupported PII entity types.Note: The Recognize PII Entities service is available in API version v3.1 and newer.Extract Key Phrasesextract_key_phrasesdetermines 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".importosfromazure.core.credentialsimportAzureKeyCredentialfromazure.ai.textanalyticsimportTextAnalyticsClientendpoint=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 treesin a city chock-full of forests, leaving yellow leaves on the ground and a clearer view of theblue sky above...""","""Redmond, WA. In the past few days, Microsoft has decided to further postpone the start date ofits 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 campusonce workers no longer have to work remotely..."""]result=text_analytics_client.extract_key_phrases(articles)foridx,docinenumerate(result):ifnotdoc.is_error:print("Key phrases in article #{}:{}".format(idx+1,", ".join(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 ofkey phrase extraction.Detect Languagedetect_languagedetermines the language of its input text, including the confidence score of the predicted language.importosfromazure.core.credentialsimportAzureKeyCredentialfromazure.ai.textanalyticsimportTextAnalyticsClientendpoint=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 fromwalking up the stairs :). Can't say enough good things about my experience!""","""最近由于工作压力太大，我们决定去富酒店度假。那儿的温泉实在太舒服了，我跟我丈夫都完全恢复了工作前的青春精神！加油！"""]result=text_analytics_client.detect_language(documents)reviewed_docs=[docfordocinresultifnotdoc.is_error]print("Let's see what language each review is in!")foridx,docinenumerate(reviewed_docs):print("Review #{}is in '{}', which has ISO639-1 name '{}'\n".format(idx,doc.primary_language.name,doc.primary_language.iso6391_name))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 oflanguage detectionandlanguage and regional support.Healthcare Entities AnalysisLong-running operationbegin_analyze_healthcare_entitiesextracts 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.importosimporttypingfromazure.core.credentialsimportAzureKeyCredentialfromazure.ai.textanalyticsimportTextAnalyticsClient,HealthcareEntityRelationendpoint=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 take10 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=[docfordocinresultifnotdoc.is_error]print("Let's first visualize the outputted healthcare result:")fordocindocs:forentityindoc.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}")ifentity.data_sourcesisnotNone:print("...Data Sources:")fordata_sourceinentity.data_sources:print(f"......Entity ID:{data_source.entity_id}")print(f"......Name:{data_source.name}")ifentity.assertionisnotNone:print("...Assertion:")print(f"......Conditionality:{entity.assertion.conditionality}")print(f"......Certainty:{entity.assertion.certainty}")print(f"......Association:{entity.assertion.association}")forrelationindoc.entity_relations:print(f"Relation of type:{relation.relation_type}has the following roles")forroleinrelation.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_relationfordocindocsforentity_relationindoc.entity_relationsifentity_relation.relation_type==HealthcareEntityRelation.DOSAGE_OF_MEDICATION]Note: Healthcare Entities Analysis is only available with API version v3.1 and newer.Multiple AnalysisLong-running operationbegin_analyze_actionsperforms 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 RecognitionPII Entities RecognitionLinked Entity RecognitionKey Phrase ExtractionSentiment AnalysisCustom 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)importosfromazure.core.credentialsimportAzureKeyCredentialfromazure.ai.textanalyticsimport(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()fordoc,action_resultsinzip(documents,document_results):print(f"\nDocument text:{doc}")forresultinaction_results:ifresult.kind=="EntityRecognition":print("...Results of Recognize Entities Action:")forentityinresult.entities:print(f"......Entity:{entity.text}")print(f".........Category:{entity.category}")print(f".........Confidence Score:{entity.confidence_score}")print(f".........Offset:{entity.offset}")elifresult.kind=="PiiEntityRecognition":print("...Results of Recognize PII Entities action:")forpii_entityinresult.entities:print(f"......Entity:{pii_entity.text}")print(f".........Category:{pii_entity.category}")print(f".........Confidence Score:{pii_entity.confidence_score}")elifresult.kind=="KeyPhraseExtraction":print("...Results of Extract Key Phrases action:")print(f"......Key Phrases:{result.key_phrases}")elifresult.kind=="EntityLinking":print("...Results of Recognize Linked Entities action:")forlinked_entityinresult.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:")formatchinlinked_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}")elifresult.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")elifresult.is_errorisTrue:print(f"...Is an error with code '{result.error.code}' and message '{result.error.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 ConfigurationOptional keyword arguments can be passed in at the client and per-operation level.
The azure-corereference documentationdescribes available configurations for retries, logging, transport protocols, and more.TroubleshootingGeneralThe Text Analytics client will raise exceptions defined inAzure Core.LoggingThis library uses the standardlogginglibrary 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 thelogging_enablekeyword argument:importsysimportloggingfromazure.identityimportDefaultAzureCredentialfromazure.ai.textanalyticsimportTextAnalyticsClient# Create a logger for the 'azure' SDKlogger=logging.getLogger('azure')logger.setLevel(logging.DEBUG)# Configure a console outputhandler=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 leveltext_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_enablecan 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 stepsMore sample codeThese 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 fromazure-identity:sample_authentication.py(async version)Common scenariosAnalyze 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)Extractive text summarization:sample_extract_summary.py(async version)Abstractive text summarization:sample_abstract_summary.py(async version)Advanced scenariosOpinion Mining:sample_analyze_sentiment_with_opinion_mining.py(async_version)Additional documentationFor more extensive documentation on Azure Cognitive Service for Language, see theLanguage Service documentationon docs.microsoft.com.ContributingThis 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, visitcla.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 theMicrosoft Open Source Code of Conduct. For more information see theCode of Conduct FAQor contactopencode@microsoft.comwith any additional questions or comments.Release History5.3.0 (2023-06-15)This version of the client library defaults to the service API version2023-04-01.Breaking ChangesNote: The following changes are only breaking from the previous beta. They are not breaking against previous stable versions.Renamed modelExtractSummaryActiontoExtractiveSummaryAction.Renamed modelExtractSummaryResulttoExtractiveSummaryResult.Renamed client methodbegin_abstractive_summarytobegin_abstract_summary.Removeddynamic_classificationclient method and related types:DynamicClassificationResultandClassificationType.Removed keyword argumentsfhir_versionanddocument_typefrombegin_analyze_healthcare_entitiesandAnalyzeHealthcareEntitiesAction.Removed propertyfhir_bundlefromAnalyzeHealthcareEntitiesResult.Removed enumHealthcareDocumentType.Removed propertyresolutionsfromCategorizedEntity.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, andWeightUnit.Removed propertydetected_languagefromRecognizeEntitiesResult,RecognizePiiEntitiesResult,AnalyzeHealthcareEntitiesResult,ExtractKeyPhrasesResult,RecognizeLinkedEntitiesResult,AnalyzeSentimentResult,RecognizeCustomEntitiesResult,ClassifyDocumentResult,ExtractSummaryResult, andAbstractSummaryResult.Removed propertyscriptfromDetectedLanguage.Features AddedNew enum values added forHealthcareEntityCategoryandHealthcareEntityRelation.5.3.0b2 (2023-03-07)This version of the client library defaults to the service API version2022-10-01-preview.Features AddedAddedbegin_extract_summaryclient method to perform extractive summarization on documents.Addedbegin_abstractive_summaryclient method to perform abstractive summarization on documents.Breaking ChangesRemoved modelsBaseResolutionandBooleanResolution.Removed enum valueBooleanResolutionfromResolutionKind.Renamed modelAbstractSummaryActiontoAbstractiveSummaryAction.Renamed modelAbstractSummaryResulttoAbstractiveSummaryResult.Removed keyword argumentautodetect_default_languagefrom long-running operation APIs.Other ChangesImproved static typing in the client library.5.3.0b1 (2022-11-17)This version of the client library defaults to the service API version2022-10-01-preview.Features AddedAdded the Extractive Summarization feature and related models:ExtractSummaryAction,ExtractSummaryResult, andSummarySentence.
Access the feature through thebegin_analyze_actionsAPI.Added keyword argumentsfhir_versionanddocument_typetobegin_analyze_healthcare_entitiesandAnalyzeHealthcareEntitiesAction.Added propertyfhir_bundletoAnalyzeHealthcareEntitiesResult.Added propertyconfidence_scoretoHealthcareRelation.Added enumHealthcareDocumentType.Added propertyresolutionstoCategorizedEntity.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, andWeightUnit.Added the Abstractive Summarization feature and related models:AbstractSummaryAction,AbstractSummaryResult,AbstractiveSummary,
andSummaryContext. Access the feature through thebegin_analyze_actionsAPI.Added automatic language detection to long-running operation APIs. Passautointo the documentlanguagehint to use this feature.Addedautodetect_default_languageto long-running operation APIs. Pass as the default/fallback language for automatic language detection.Added propertydetected_languagetoRecognizeEntitiesResult,RecognizePiiEntitiesResult,AnalyzeHealthcareEntitiesResult,ExtractKeyPhrasesResult,RecognizeLinkedEntitiesResult,AnalyzeSentimentResult,RecognizeCustomEntitiesResult,ClassifyDocumentResult,ExtractSummaryResult, andAbstractSummaryResultto indicate the language detected by automatic language detection.Added propertyscripttoDetectedLanguageto indicate the script of the input document.Added thedynamic_classificationclient method to perform dynamic classification on documents without needing to train a model.Other ChangesRemoved dependency onmsrest.5.2.1 (2022-10-26)Bugs FixedReturns a more helpful message in the document error when all documents fail for an action in thebegin_analyze_actionsAPI.5.2.0 (2022-09-08)Other ChangesThis version of the client library marks a stable release and defaults to the service API version2022-05-01.
Includes all changes from5.2.0b1to5.2.0b5.5.2.0b5 (2022-08-11)The version of this client library defaults to the API version2022-05-01.Features AddedAddedbegin_recognize_custom_entitiesclient method to recognize custom named entities in documents.Addedbegin_single_label_classifyclient method to perform custom single label classification on documents.Addedbegin_multi_label_classifyclient method to perform custom multi label classification on documents.Added propertydetailson returned poller objects which contain long-running operation metadata.AddedTextAnalysisLROPollerandAsyncTextAnalysisLROPollerprotocols to describe the return types from long-running operations.Addedcancelmethod on the poller objects. Call it to cancel a long-running operation that's in progress.Added propertykindtoRecognizeEntitiesResult,RecognizePiiEntitiesResult,AnalyzeHealthcareEntitiesResult,DetectLanguageResult,ExtractKeyPhrasesResult,RecognizeLinkedEntitiesResult,AnalyzeSentimentResult,RecognizeCustomEntitiesResult,ClassifyDocumentResult, andDocumentError.Added enumTextAnalysisKind.Breaking ChangesRemoved 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 theFHIRfeature 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.RenamedSingleCategoryClassifyActiontoSingleLabelClassifyActionRenamedMultiCategoryClassifyActiontoMultiLabelClassifyAction.Bugs FixedAHttpResponseErrorwill be immediately raised when the call quota volume is exceeded in aF0tier Language resource.Other ChangesPython 3.6 is no longer supported. Please use Python version 3.7 or later. For more details, seeAzure 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 is2022-04-01-preview. Support forv3.2-preview.2is removed, however, all functionalities are included in the latest version.Features AddedAdded support for Healthcare Entities Analysis through thebegin_analyze_actionsAPI with theAnalyzeHealthcareEntitiesActiontype.Added keyword argumentfhir_versiontobegin_analyze_healthcare_entitiesandAnalyzeHealthcareEntitiesAction. Use the keyword to indicate the version for thefhir_bundlecontained on theAnalyzeHealthcareEntitiesResult.Added propertyfhir_bundletoAnalyzeHealthcareEntitiesResult.Added keyword argumentdisplay_nametobegin_analyze_healthcare_entities.5.2.0b3 (2022-03-08)Bugs Fixedstring_index_typenow correctly defaults to the Python defaultUnicodeCodePointforAnalyzeSentimentActionandRecognizeCustomEntitiesAction.Fixed a bug inbegin_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 ChangesPython 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 isv3.2-preview.2.Features AddedAdded support for Custom Entities Recognition through thebegin_analyze_actionsAPI with theRecognizeCustomEntitiesActionandRecognizeCustomEntitiesResulttypes.Added support for Custom Single Classification through thebegin_analyze_actionsAPI with theSingleCategoryClassifyActionandSingleCategoryClassifyActionResulttypes.Added support for Custom Multi Classification through thebegin_analyze_actionsAPI with theMultiCategoryClassifyActionandMultiCategoryClassifyActionResulttypes.Multiple of the same action type is now supported withbegin_analyze_actions.Bugs FixedRestarting a long-running operation from a saved state is now supported for thebegin_analyze_actionsandbegin_recognize_healthcare_entitiesmethods.In the event of an action level error, available partial results are now returned for any successful actions inbegin_analyze_actions.Other ChangesPackage requiresazure-coreversion 1.19.1 or greater5.2.0b1 (2021-08-09)This version of the SDK defaults to the latest supported API version, which currently isv3.2-preview.1.Features AddedAdded support for Extractive Summarization actions through theExtractSummaryActiontype.Bugs FixedRecognizePiiEntitiesActionoptiondisable_service_logsnow correctly defaults toTrue.Other ChangesPython 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 isv3.1.
Includes all changes from5.1.0b1to5.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 AddedAddedcatagories_filtertoRecognizePiiEntitiesActionAddedHealthcareEntityCategoryAdded AAD support for thebegin_analyze_healthcare_entitiesmethods.Breaking ChangesChanged: the response structure ofbeing_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:AnalyzeActionsTypeRemoved:AnalyzeActionsResultRemoved:AnalyzeActionsErrorRemoved:HealthcareEntityRelationRoleTypeChanged: renamedHealthcareEntityRelationTypetoHealthcareEntityRelationChanged: renamedPiiEntityCategoryTypetoPiiEntityCategoryChanged: renamedPiiEntityDomainTypetoPiiEntityDomain5.1.0b7 (2021-05-18)Breaking ChangesRenamedbegin_analyze_batch_actionstobegin_analyze_actions.RenamedAnalyzeBatchActionsTypetoAnalyzeActionsType.RenamedAnalyzeBatchActionsResulttoAnalyzeActionsResult.RenamedAnalyzeBatchActionsErrortoAnalyzeActionsError.RenamedAnalyzeHealthcareEntitiesResultItemtoAnalyzeHealthcareEntitiesResult.FixedAnalyzeHealthcareEntitiesResult'sstatisticsto be the correct type,TextDocumentStatisticsRemoveRequestStatistics, useTextDocumentBatchStatisticsinsteadNew FeaturesAdded enumsEntityConditionality,EntityCertainty, andEntityAssociation.AddedAnalyzeSentimentActionas a supported action type forbegin_analyze_batch_actions.Added kwargdisable_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 ChangesBy default, we now target the service'sv3.1-preview.4endpoint through enum valueTextAnalyticsApiVersion.V3_1_PREVIEWRemoved propertyrelated_entitiesonHealthcareEntityand addedentity_relationsonto the document response level for healthcareRenamed propertiesaspectandopinionstotargetandassessmentsrespectively in classMinedOpinion.Renamed classesAspectSentimentandOpinionSentimenttoTargetSentimentandAssessmentSentimentrespectively.New FeaturesAddedRecognizeLinkedEntitiesActionas a supported action type forbegin_analyze_batch_actions.Added parametercategories_filterto therecognize_pii_entitiesclient method.Added enumPiiEntityCategoryType.Add propertynormalized_texttoHealthcareEntity. This property is a normalized version of thetextproperty that already
exists on theHealthcareEntityAdd propertyassertionontoHealthcareEntity. This contains assertions about the entity itself, i.e. if the entity represents a diagnosis,
is this diagnosis conditional on a symptom?Known Issuesbegin_analyze_healthcare_entitiesis currently in gated preview and can not be used with AAD credentials. For more information, seethe Text Analytics for Health documentation.At time of this SDK release, the service is not respecting the value passed throughmodel_versiontobegin_analyze_healthcare_entities, it only uses the latest model.5.1.0b5 (2021-02-10)Breaking ChangesRenamebegin_analyzetobegin_analyze_batch_actions.Now instead of separate parameters for all of the different types of actions you can pass tobegin_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 frombegin_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 FeaturesRenamedbegin_analyze_healthcaretobegin_analyze_healthcare_entities.RenamedAnalyzeHealthcareResulttoAnalyzeHealthcareEntitiesResultandAnalyzeHealthcareResultItemtoAnalyzeHealthcareEntitiesResultItem.RenamedHealthcareEntityLinktoHealthcareEntityDataSourceand renamed its propertiesidtoentity_idanddata_sourcetoname.RemovedrelationsfromAnalyzeHealthcareEntitiesResultItemand addedrelated_entitiestoHealthcareEntity.Moved the cancellation logic for the Analyze Healthcare Entities service from
the service client to the poller object returned frombegin_analyze_healthcare_entities.Exposed Analyze Healthcare Entities operation metadata on the poller object returned frombegin_analyze_healthcare_entities.No longer need to specifyapi_version=TextAnalyticsApiVersion.V3_1_PREVIEW_3when callingbegin_analyzeandbegin_analyze_healthcare_entities.begin_analyze_healthcare_entitiesis still in gated preview though.Added a new parameterstring_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 propertylengthtoCategorizedEntity,SentenceSentiment,LinkedEntityMatch,AspectSentiment,OpinionSentiment,PiiEntityandHealthcareEntity.5.1.0b4 (2021-01-12)Bug FixesPackage requiresazure-coreversion 1.8.2 or greater5.1.0b3 (2020-11-19)New FeaturesWe have added methodbegin_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 methodbegin_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 informationhere.5.1.0b2 (2020-10-06)Breaking changesRemoved propertylengthfromCategorizedEntity,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 aValueErrorinstead of aNotImplementedError.Client side validation of input is now disabled by default. This means there will be noValidationErrors 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 featuresWe 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 inv3.0to the kwargapi_versionwhen creating your TextAnalyticsClientWe have added an APIrecognize_pii_entitieswhich returns entities containing personally identifiable information for a batch of documents. Only available for API version v3.1-preview and up.Addedoffsetandlengthproperties 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 documentWe 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 passshow_opinion_miningas True when calling theanalyze_sentimentendpointAdd propertybing_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 version1.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 featuresWe now have awarningsproperty on each document-level response object returned from the endpoints. It is a list ofTextAnalyticsWarnings.Addedtextproperty toSentenceSentimentBreaking changesNow targets only the service's v3.0 API, instead of the v3.0-preview.1 APIscoreattribute ofDetectedLanguagehas been renamed toconfidence_scoreRemovedgrapheme_offsetandgrapheme_lengthfromCategorizedEntity,SentenceSentiment, andLinkedEntityMatchTextDocumentStatisticsattributegrapheme_counthas been renamed tocharacter_count1.0.0b5This was a broken release1.0.0b4 (2020-04-07)Breaking changesRemoved therecognize_pii_entitiesendpoint and all related models (RecognizePiiEntitiesResultandPiiEntity)
from this library.RemovedTextAnalyticsApiKeyCredentialand now usingAzureKeyCredentialfrom azure.core.credentials as key credentialscoreattribute has been renamed toconfidence_scorefor theCategorizedEntity,LinkedEntityMatch, andPiiEntitymodelsAll input parametersinputshave been renamed todocuments1.0.0b3 (2020-03-10)Breaking changesSentimentScorePerLabelhas been renamed toSentimentConfidenceScoresAnalyzeSentimentResultandSentenceSentimentattributesentiment_scoreshas been renamed toconfidence_scoresTextDocumentStatisticsattributecharacter_counthas been renamed tographeme_countLinkedEntityattributeidhas been renamed todata_source_entity_idParameterscountry_hintandlanguageare now passed as keyword argumentsThe keyword argumentresponse_hookhas been renamed toraw_response_hooklengthandoffsetattributes have been renamed tographeme_lengthandgrapheme_offsetfor theSentenceSentiment,CategorizedEntity,PiiEntity, andLinkedEntityMatchmodelsNew featuresPasscountry_hint="none"to not use the default country hint of"US".Dependency updatesAdoptedazure-coreversion 1.3.0 or greater1.0.0b2 (2020-02-11)Breaking changesThe single text, module-level operationssingle_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 classTextAnalyticsApiKeyCredential("<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().TheTextAnalyticsErrormodel 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 featuresCredential classTextAnalyticsApiKeyCredentialprovides 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 aDocumentErrorobject, 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 visithttps://azure.github.io/azure-sdk/releases/latest/python.html.Breaking changes: New API designNew namespace/package name:The namespace/package name for Azure Text Analytics client library has changed fromazure.cognitiveservices.language.textanalyticstoazure.ai.textanalyticsNew operations and naming:detect_languageis renamed todetect_languagesentitiesis renamed torecognize_entitieskey_phrasesis renamed toextract_key_phrasessentimentis renamed toanalyze_sentimentNew operationrecognize_pii_entitiesfinds personally identifiable information entities in textNew operationrecognize_linked_entitiesprovides links from a well-known knowledge base for each recognized entityNew module-level operationssingle_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 subnamespaceazure.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 toLinkedEntityMatchThe batching methods'documentsparameter has been renamedinputsNew 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 argumentmodel_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.Adefault_country_hintordefault_languagekeyword argument can be passed at client instantiation to set the default values for all operations.Aresponse_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.New return typesThe 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 aAnalyzeSentimentResultNew underlying REST pipeline implementation, based on the newazure-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 usingazure-identitycredentialssee theAzure Identity documentationfor more informationNew error hierarchy:All service errors will now use the base type:azure.core.exceptions.HttpResponseErrorThere is one exception type derived from this base type for authentication errors:ClientAuthenticationError: Authentication failed.0.2.0 (2019-03-12)FeaturesClient class can be used as a context manager to keep the underlying HTTP session open for performanceNew method "entities"Model KeyPhraseBatchResultItem has a new parameter statisticsModel KeyPhraseBatchResult has a new parameter statisticsModel LanguageBatchResult has a new parameter statisticsModel LanguageBatchResultItem has a new parameter statisticsModel SentimentBatchResult has a new parameter statisticsBreaking changesTextAnalyticsAPI main client has been renamed TextAnalyticsClientTextAnalyticsClient parameter is no longer a region but a complete endpointGeneral Breaking changesThis version uses a next-generation code generator thatmightintroduce 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#othersAt a glance:"is" should not be used at all."format" will return the string value, where "%s" string formatting will returnNameOfEnum.stringvalue. Format syntax should be preferred.BugfixesCompatibility of the sdist with wheel 0.31.00.1.0 (2018-01-12)Initial Release