azure.ai.textanalytics package

class azure.ai.textanalytics.AbstractSummaryAction(**kwargs)[source]

AbstractSummaryAction encapsulates the parameters for starting a long-running abstractive summarization operation. For a conceptual discussion of extractive summarization, see the service documentation: https://learn.microsoft.com/azure/cognitive-services/language-service/summarization/overview

Abstractive summarization generates a summary for the input documents. Abstractive summarization is different from extractive summarization in that extractive summarization is the strategy of concatenating extracted sentences from the input document into a summary, while abstractive summarization involves paraphrasing the document using novel sentences.

Note

The abstractive summarization feature is part of a gated preview. Request access here: https://aka.ms/applyforgatedsummarizationfeatures

Keyword Arguments
  • sentence_count (Optional[int]) – It controls the approximate number of sentences in the output summaries.

  • model_version (Optional[str]) – The model version to use for the analysis.

  • string_index_type (Optional[str]) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • disable_service_logs (Optional[bool]) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

Variables
  • sentence_count (Optional[int]) – It controls the approximate number of sentences in the output summaries.

  • model_version (Optional[str]) – The model version to use for the analysis.

  • string_index_type (Optional[str]) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • disable_service_logs (Optional[bool]) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

New in version 2022-10-01-preview: The AbstractSummaryAction model.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.AbstractSummaryResult(**kwargs)[source]

AbstractSummaryResult is a result object which contains the summary generated for a particular document.

Variables
  • id (str) – Unique, non-empty document identifier. Required.

  • detected_language (Optional[DetectedLanguage]) – If ‘language’ is set to ‘auto’ for the document in the request this field will contain the DetectedLanguage for the document.

  • warnings (list[TextAnalyticsWarning]) – Warnings encountered while processing document. Results will still be returned if there are warnings, but they may not be fully accurate.

  • statistics (Optional[TextDocumentStatistics]) – If show_stats=True was specified in the request this field will contain information about the document payload.

  • summaries (list[AbstractiveSummary]) – A list of abstractive summaries. Required.

  • is_error (bool) – Boolean check for error item when iterating over list of results. Always False for an instance of a AbstractSummaryResult.

  • kind (str) – The text analysis kind - “AbstractiveSummarization”.

New in version 2022-10-01-preview: The AbstractSummaryResult model.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.AbstractiveSummary(**kwargs)[source]

An object representing a single summary with context for given document.

Variables
  • text (str) – The text of the summary. Required.

  • contexts (Optional[list[SummaryContext]]) – The context list of the summary.

New in version 2022-10-01-preview: The AbstractiveSummary model.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.AgeResolution(*, value: float, unit: Union[str, _models.AgeUnit], **kwargs)[source]
Keyword Arguments
  • value (float) – The numeric value that the extracted text denotes. Required.

  • unit (str or AgeUnit) – The Age Unit of measurement. Required. Known values are: “Unspecified”, “Year”, “Month”, “Week”, and “Day”.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

get(key, default=None)
has_key(k)
classmethod is_xml_model()
items()
keys()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

update(*args, **kwargs)
values()
class azure.ai.textanalytics.AgeUnit(value)[source]

The Age Unit of measurement.

DAY = 'Day'
MONTH = 'Month'
UNSPECIFIED = 'Unspecified'
WEEK = 'Week'
YEAR = 'Year'
class azure.ai.textanalytics.AnalyzeActionsLROPoller(client: Any, initial_response: Any, deserialization_callback: Callable, polling_method: azure.core.polling._poller.PollingMethod[PollingReturnType])[source]
add_done_callback(func: Callable)None

Add callback function to be run once the long running operation has completed - regardless of the status of the operation.

Parameters

func (callable) – Callback function that takes at least one argument, a completed LongRunningOperation.

cancel()None[source]

Cancel the operation currently being polled.

Returns

None

Return type

None

Raises

HttpResponseError – When the operation has already reached a terminal state.

continuation_token()str

Return a continuation token that allows to restart the poller later.

Returns

An opaque continuation token

Return type

str

done()bool

Check status of the long running operation.

Returns

‘True’ if the process has completed, else ‘False’.

Return type

bool

polling_method()azure.ai.textanalytics._lro.AnalyzeActionsLROPollingMethod[source]

Return the polling method associated to this poller.

Returns

AnalyzeActionsLROPollingMethod

Return type

AnalyzeActionsLROPollingMethod

remove_done_callback(func: Callable)None

Remove a callback from the long running operation.

Parameters

func (callable) – The function to be removed from the callbacks.

Raises

ValueError – if the long running operation has already completed.

result(timeout: Optional[int] = None)PollingReturnType

Return the result of the long running operation, or the result available after the specified timeout.

Returns

The deserialized resource of the long running operation, if one is available.

Raises

HttpResponseError – Server problem with the query.

status()str

Returns the current status string.

Returns

The current status string

Return type

str

wait(timeout: Optional[float] = None)None

Wait on the long running operation for a specified length of time. You can check if this call as ended with timeout with the “done()” method.

Parameters

timeout (float) – Period of time to wait for the long running operation to complete (in seconds).

Raises

HttpResponseError – Server problem with the query.

property details

Long-running operation metadata.

Returns

A mapping of details about the long-running operation.

Return type

Mapping[str, Any]

class azure.ai.textanalytics.AnalyzeHealthcareEntitiesAction(**kwargs)[source]

AnalyzeHealthcareEntitiesAction encapsulates the parameters for starting a long-running healthcare entities analysis operation.

If you just want to analyze healthcare entities in a list of documents, and not perform multiple long running actions on the input of documents, call method begin_analyze_healthcare_entities instead of interfacing with this model.

Keyword Arguments
  • model_version (Optional[str]) – The model version to use for the analysis.

  • string_index_type (Optional[str]) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • disable_service_logs (Optional[bool]) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

  • fhir_version (Optional[str]) – The FHIR Spec version that the result will use to format the fhir_bundle on the result object. For additional information see https://www.hl7.org/fhir/overview.html. The only acceptable values to pass in are None and “4.0.1”. The default value is None.

  • document_type (Optional[str or HealthcareDocumentType]) – Document type that can be provided as input for Fhir Documents. Expect to have fhir_version provided when used. Behavior of using None enum is the same as not using the document_type parameter. Known values are: “None”, “ClinicalTrial”, “DischargeSummary”, “ProgressNote”, “HistoryAndPhysical”, “Consult”, “Imaging”, “Pathology”, and “ProcedureNote”.

Variables
  • model_version (Optional[str]) – The model version to use for the analysis.

  • string_index_type (Optional[str]) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • disable_service_logs (Optional[bool]) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

  • fhir_version (Optional[str]) – The FHIR Spec version that the result will use to format the fhir_bundle on the result object. For additional information see https://www.hl7.org/fhir/overview.html. The only acceptable values to pass in are None and “4.0.1”. The default value is None.

  • document_type (Optional[str or HealthcareDocumentType]) – Document type that can be provided as input for Fhir Documents. Expect to have fhir_version provided when used. Behavior of using None enum is the same as not using the document_type parameter. Known values are: “None”, “ClinicalTrial”, “DischargeSummary”, “ProgressNote”, “HistoryAndPhysical”, “Consult”, “Imaging”, “Pathology”, and “ProcedureNote”.

New in version 2022-05-01: The AnalyzeHealthcareEntitiesAction model.

New in version 2022-10-01-preview: The fhir_version and document_type keyword arguments.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.AnalyzeHealthcareEntitiesLROPoller(client: Any, initial_response: Any, deserialization_callback: Callable, polling_method: azure.core.polling._poller.PollingMethod[PollingReturnType])[source]
add_done_callback(func: Callable)None

Add callback function to be run once the long running operation has completed - regardless of the status of the operation.

Parameters

func (callable) – Callback function that takes at least one argument, a completed LongRunningOperation.

cancel(**kwargs: Any)azure.core.polling._poller.LROPoller[None][source]

Cancel the operation currently being polled.

Keyword Arguments

polling_interval (int) – The polling interval to use to poll the cancellation status. The default value is 5 seconds.

Returns

Returns an instance of an LROPoller that returns None.

Return type

LROPoller[None]

Raises

HttpResponseError – When the operation has already reached a terminal state.

Example:

Cancel an existing health operation.
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

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

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

documents = [
    "RECORD #333582770390100 | MH | 85986313 | | 054351 | 2/14/2001 12:00:00 AM | \
    CORONARY ARTERY DISEASE | Signed | DIS | Admission Date: 5/22/2001 \
    Report Status: Signed Discharge Date: 4/24/2001 ADMISSION DIAGNOSIS: \
    CORONARY ARTERY DISEASE. HISTORY OF PRESENT ILLNESS: \
    The patient is a 54-year-old gentleman with a history of progressive angina over the past several months. \
    The patient had a cardiac catheterization in July of this year revealing total occlusion of the RCA and \
    50% left main disease , with a strong family history of coronary artery disease with a brother dying at \
    the age of 52 from a myocardial infarction and another brother who is status post coronary artery bypass grafting. \
    The patient had a stress echocardiogram done on July , 2001 , which showed no wall motion abnormalities ,\
    but this was a difficult study due to body habitus. The patient went for six minutes with minimal ST depressions \
    in the anterior lateral leads , thought due to fatigue and wrist pain , his anginal equivalent. Due to the patient's \
    increased symptoms and family history and history left main disease with total occasional of his RCA was referred \
    for revascularization with open heart surgery."
]

poller = text_analytics_client.begin_analyze_healthcare_entities(documents)

try:
    poller.cancel()
except HttpResponseError as e:
    # If the operation has already reached a terminal state it cannot be cancelled.
    print(e)

else:
    print("Healthcare entities analysis was successfully cancelled.")

continuation_token()str

Return a continuation token that allows to restart the poller later.

Returns

An opaque continuation token

Return type

str

done()bool

Check status of the long running operation.

Returns

‘True’ if the process has completed, else ‘False’.

Return type

bool

polling_method()azure.ai.textanalytics._lro.AnalyzeHealthcareEntitiesLROPollingMethod[source]

Return the polling method associated to this poller.

Returns

AnalyzeHealthcareEntitiesLROPollingMethod

Return type

AnalyzeHealthcareEntitiesLROPollingMethod

remove_done_callback(func: Callable)None

Remove a callback from the long running operation.

Parameters

func (callable) – The function to be removed from the callbacks.

Raises

ValueError – if the long running operation has already completed.

result(timeout: Optional[int] = None)PollingReturnType

Return the result of the long running operation, or the result available after the specified timeout.

Returns

The deserialized resource of the long running operation, if one is available.

Raises

HttpResponseError – Server problem with the query.

status()str

Returns the current status string.

Returns

The current status string

Return type

str

wait(timeout: Optional[float] = None)None

Wait on the long running operation for a specified length of time. You can check if this call as ended with timeout with the “done()” method.

Parameters

timeout (float) – Period of time to wait for the long running operation to complete (in seconds).

Raises

HttpResponseError – Server problem with the query.

property details

Long-running operation metadata.

Returns

A mapping of details about the long-running operation.

Return type

Mapping[str, Any]

class azure.ai.textanalytics.AnalyzeHealthcareEntitiesResult(**kwargs)[source]

AnalyzeHealthcareEntitiesResult contains the Healthcare entities from a particular document.

Variables
  • id (str) – Unique, non-empty document identifier that matches the document id that was passed in with the request. If not specified in the request, an id is assigned for the document.

  • entities (list[HealthcareEntity]) – Identified Healthcare entities in the document, i.e. in the document “The subject took ibuprofen”, “ibuprofen” is an identified entity from the document.

  • entity_relations (list[HealthcareRelation]) – Identified Healthcare relations between entities. For example, in the document “The subject took 100mg of ibuprofen”, we would identify the relationship between the dosage of 100mg and the medication ibuprofen.

  • warnings (list[TextAnalyticsWarning]) – Warnings encountered while processing document. Results will still be returned if there are warnings, but they may not be fully accurate.

  • statistics (Optional[TextDocumentStatistics]) – If show_stats=true was specified in the request this field will contain information about the document payload.

  • fhir_bundle (Optional[dict[str, any]]) – If fhir_version is passed, this will contain a FHIR compatible object for consumption in other Healthcare tools. For additional information see https://www.hl7.org/fhir/overview.html.

  • detected_language (Optional[str]) – If ‘language’ is set to ‘auto’ for the document in the request this field will contain the detected language for the document.

  • is_error (bool) – Boolean check for error item when iterating over list of results. Always False for an instance of a AnalyzeHealthcareEntitiesResult.

  • kind (str) – The text analysis kind - “Healthcare”.

New in version 2022-10-01-preview: The fhir_bundle and detected_language properties.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.AnalyzeSentimentAction(**kwargs)[source]

AnalyzeSentimentAction encapsulates the parameters for starting a long-running Sentiment Analysis operation.

If you just want to analyze sentiment in a list of documents, and not perform multiple long running actions on the input of documents, call method analyze_sentiment instead of interfacing with this model.

Keyword Arguments
  • model_version (Optional[str]) – The model version to use for the analysis.

  • show_opinion_mining (Optional[bool]) – Whether to mine the opinions of a sentence and conduct more granular analysis around the aspects of a product or service (also known as aspect-based sentiment analysis). If set to true, the returned SentenceSentiment objects will have property mined_opinions containing the result of this analysis.

  • string_index_type (Optional[str]) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • disable_service_logs (Optional[bool]) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

Variables
  • model_version (Optional[str]) – The model version to use for the analysis.

  • show_opinion_mining (Optional[bool]) – Whether to mine the opinions of a sentence and conduct more granular analysis around the aspects of a product or service (also known as aspect-based sentiment analysis). If set to true, the returned SentenceSentiment objects will have property mined_opinions containing the result of this analysis.

  • string_index_type (Optional[str]) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • disable_service_logs (Optional[bool]) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.AnalyzeSentimentResult(**kwargs)[source]

AnalyzeSentimentResult is a result object which contains the overall predicted sentiment and confidence scores for your document and a per-sentence sentiment prediction with scores.

Variables
  • id (str) – Unique, non-empty document identifier that matches the document id that was passed in with the request. If not specified in the request, an id is assigned for the document.

  • sentiment (str) – Predicted sentiment for document (Negative, Neutral, Positive, or Mixed). Possible values include: ‘positive’, ‘neutral’, ‘negative’, ‘mixed’

  • warnings (list[TextAnalyticsWarning]) – Warnings encountered while processing document. Results will still be returned if there are warnings, but they may not be fully accurate.

  • statistics (Optional[TextDocumentStatistics]) – If show_stats=True was specified in the request this field will contain information about the document payload.

  • confidence_scores (SentimentConfidenceScores) – Document level sentiment confidence scores between 0 and 1 for each sentiment label.

  • sentences (list[SentenceSentiment]) – Sentence level sentiment analysis.

  • detected_language (Optional[DetectedLanguage]) – If ‘language’ is set to ‘auto’ for the document in the request this field will contain the DetectedLanguage for the document.

  • is_error (bool) – Boolean check for error item when iterating over list of results. Always False for an instance of a AnalyzeSentimentResult.

  • kind (str) – The text analysis kind - “SentimentAnalysis”.

New in version 2022-10-01-preview: The detected_language property.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.AreaResolution(*, value: float, unit: Union[str, _models.AreaUnit], **kwargs)[source]
Keyword Arguments
  • value (float) – The numeric value that the extracted text denotes. Required.

  • unit (str or AreaUnit) – The area Unit of measurement. Required. Known values are: “Unspecified”, “SquareKilometer”, “SquareHectometer”, “SquareDecameter”, “SquareDecimeter”, “SquareMeter”, “SquareCentimeter”, “SquareMillimeter”, “SquareInch”, “SquareFoot”, “SquareMile”, “SquareYard”, and “Acre”.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

get(key, default=None)
has_key(k)
classmethod is_xml_model()
items()
keys()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

update(*args, **kwargs)
values()
class azure.ai.textanalytics.AreaUnit(value)[source]

The area Unit of measurement.

ACRE = 'Acre'
SQUARE_CENTIMETER = 'SquareCentimeter'
SQUARE_DECAMETER = 'SquareDecameter'
SQUARE_DECIMETER = 'SquareDecimeter'
SQUARE_FOOT = 'SquareFoot'
SQUARE_HECTOMETER = 'SquareHectometer'
SQUARE_INCH = 'SquareInch'
SQUARE_KILOMETER = 'SquareKilometer'
SQUARE_METER = 'SquareMeter'
SQUARE_MILE = 'SquareMile'
SQUARE_MILLIMETER = 'SquareMillimeter'
SQUARE_YARD = 'SquareYard'
UNSPECIFIED = 'Unspecified'
class azure.ai.textanalytics.AssessmentSentiment(**kwargs)[source]

AssessmentSentiment contains the predicted sentiment, confidence scores and other information about an assessment given about a particular target. For example, in the sentence “The food is good”, the assessment of the target ‘food’ is ‘good’.

Variables
  • text (str) – The assessment text.

  • sentiment (str) – The predicted Sentiment for the assessment. Possible values include ‘positive’, ‘mixed’, and ‘negative’.

  • confidence_scores (SentimentConfidenceScores) – The sentiment confidence score between 0 and 1 for the assessment for ‘positive’ and ‘negative’ labels. It’s score for ‘neutral’ will always be 0

  • length (int) – The assessment text length. This value depends on the value of the string_index_type parameter set in the original request, which is UnicodeCodePoints by default.

  • offset (int) – The assessment text offset from the start of the document. The value depends on the value of the string_index_type parameter set in the original request, which is UnicodeCodePoints by default.

  • is_negated (bool) – Whether the value of the assessment is negated. For example, in “The food is not good”, the assessment “good” is negated.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.BaseResolution(**kwargs)[source]

The abstract base class for entity resolutions.

You probably want to use the sub-classes and not this class directly. Known sub-classes are: AgeResolution, AreaResolution, BooleanResolution, CurrencyResolution, DateTimeResolution, InformationResolution, LengthResolution, NumberResolution, NumericRangeResolution, OrdinalResolution, SpeedResolution, TemperatureResolution, TemporalSpanResolution, VolumeResolution, WeightResolution

All required parameters must be populated in order to send to Azure.

Variables

resolution_kind (str or ResolutionKind) – The entity resolution object kind. Required. Known values are: “BooleanResolution”, “DateTimeResolution”, “NumberResolution”, “OrdinalResolution”, “SpeedResolution”, “WeightResolution”, “LengthResolution”, “VolumeResolution”, “AreaResolution”, “AgeResolution”, “InformationResolution”, “TemperatureResolution”, “CurrencyResolution”, “NumericRangeResolution”, and “TemporalSpanResolution”.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod is_xml_model()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

class azure.ai.textanalytics.BooleanResolution(*, value: bool, **kwargs)[source]
Keyword Arguments

value (bool) – Required.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

get(key, default=None)
has_key(k)
classmethod is_xml_model()
items()
keys()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

update(*args, **kwargs)
values()
class azure.ai.textanalytics.CategorizedEntity(**kwargs)[source]

CategorizedEntity contains information about a particular entity found in text.

Variables

New in version v3.1: The offset and length properties.

New in version 2022-10-01-preview: The resolutions property.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.ClassificationCategory(**kwargs)[source]

ClassificationCategory represents a classification of the input document.

Variables
  • category (str) – Classification category for the document.

  • confidence_score (float) – Confidence score between 0 and 1 of the recognized classification.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.ClassificationType(value)[source]

Specifies either one or multiple categories per document. Defaults to multi classification which may return more than one class for each document.

MULTI = 'Multi'
SINGLE = 'Single'
class azure.ai.textanalytics.ClassifyDocumentResult(**kwargs)[source]

ClassifyDocumentResult is a result object which contains the classifications for a particular document.

Variables
  • id (str) – Unique, non-empty document identifier.

  • classifications (list[ClassificationCategory]) – Recognized classification results in the document.

  • warnings (list[TextAnalyticsWarning]) – Warnings encountered while processing document.

  • statistics (Optional[TextDocumentStatistics]) – If show_stats=True was specified in the request this field will contain information about the document payload.

  • detected_language (Optional[DetectedLanguage]) – If ‘language’ is set to ‘auto’ for the document in the request this field will contain the DetectedLanguage for the document.

  • is_error (bool) – Boolean check for error item when iterating over list of results. Always False for an instance of a ClassifyDocumentResult.

  • kind (str) – The text analysis kind - “CustomDocumentClassification”.

New in version 2022-10-01-preview: The detected_language property.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.CurrencyResolution(*, value: float, unit: str, iso4217: Optional[str] = None, **kwargs)[source]
Keyword Arguments
  • value (float) – The numeric value that the extracted text denotes. Required.

  • iso4217 (str) – The alphabetic code based on another ISO standard, ISO 3166, which lists the codes for country names. The first two letters of the ISO 4217 three-letter code are the same as the code for the country name, and, where possible, the third letter corresponds to the first letter of the currency name.

  • unit (str) – The unit of the amount captured in the extracted entity. Required.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

get(key, default=None)
has_key(k)
classmethod is_xml_model()
items()
keys()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

update(*args, **kwargs)
values()
class azure.ai.textanalytics.DateTimeResolution(*, timex: str, date_time_sub_kind: Union[str, _models.DateTimeSubKind], value: str, modifier: Optional[Union[str, _models.TemporalModifier]] = None, **kwargs)[source]
Keyword Arguments
  • timex (str) – An extended ISO 8601 date/time representation as described in (https://github.com/Microsoft/Recognizers-Text/blob/master/Patterns/English/English-DateTime.yaml). Required.

  • date_time_sub_kind (str or DateTimeSubKind) – The DateTime SubKind. Required. Known values are: “Time”, “Date”, “DateTime”, “Duration”, and “Set”.

  • value (str) – The actual time that the extracted text denote. Required.

  • modifier (str or TemporalModifier) – An optional modifier of a date/time instance. Known values are: “AfterApprox”, “Before”, “BeforeStart”, “Approx”, “ReferenceUndefined”, “SinceEnd”, “AfterMid”, “Start”, “After”, “BeforeEnd”, “Until”, “End”, “Less”, “Since”, “AfterStart”, “BeforeApprox”, “Mid”, and “More”.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

get(key, default=None)
has_key(k)
classmethod is_xml_model()
items()
keys()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

update(*args, **kwargs)
values()
class azure.ai.textanalytics.DateTimeSubKind(value)[source]

The DateTime SubKind.

DATE = 'Date'
DATE_TIME = 'DateTime'
DURATION = 'Duration'
SET = 'Set'
TIME = 'Time'
class azure.ai.textanalytics.DetectLanguageInput(**kwargs)[source]

The input document to be analyzed for detecting language.

Keyword Arguments
  • id (str) – Required. Unique, non-empty document identifier.

  • text (str) – Required. The input text to process.

  • country_hint (str) – A country hint to help better detect the language of the text. Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to “US”. Pass in the string “none” to not use a country_hint.

  • id – Unique, non-empty document identifier. Required.

  • text – Required.

  • country_hint

Variables
  • id (str) – Required. Unique, non-empty document identifier.

  • text (str) – Required. The input text to process.

  • country_hint (Optional[str]) – A country hint to help better detect the language of the text. Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to “US”. Pass in the string “none” to not use a country_hint.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod is_xml_model()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

class azure.ai.textanalytics.DetectLanguageResult(**kwargs)[source]

DetectLanguageResult is a result object which contains the detected language of a particular document.

Variables
  • id (str) – Unique, non-empty document identifier that matches the document id that was passed in with the request. If not specified in the request, an id is assigned for the document.

  • primary_language (DetectedLanguage) – The primary language detected in the document.

  • warnings (list[TextAnalyticsWarning]) – Warnings encountered while processing document. Results will still be returned if there are warnings, but they may not be fully accurate.

  • statistics (Optional[TextDocumentStatistics]) – If show_stats=True was specified in the request this field will contain information about the document payload.

  • is_error (bool) – Boolean check for error item when iterating over list of results. Always False for an instance of a DetectLanguageResult.

  • kind (str) – The text analysis kind - “LanguageDetection”.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.DetectedLanguage(**kwargs)[source]

DetectedLanguage contains the predicted language found in text, its confidence score, and its ISO 639-1 representation.

Variables
  • name (str) – Long name of a detected language (e.g. English, French).

  • iso6391_name (str) – A two letter representation of the detected language according to the ISO 639-1 standard (e.g. en, fr).

  • confidence_score (float) – A confidence score between 0 and 1. Scores close to 1 indicate 100% certainty that the identified language is true.

  • script (Optional[str]) – Identifies the script of the input document. Possible values: “Latin”.

New in version 2022-10-01-preview: The script property.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.DocumentError(**kwargs)[source]

DocumentError is an error object which represents an error on the individual document.

Variables
  • id (str) – Unique, non-empty document identifier that matches the document id that was passed in with the request. If not specified in the request, an id is assigned for the document.

  • error (TextAnalyticsError) – The document error.

  • is_error (bool) – Boolean check for error item when iterating over list of results. Always True for an instance of a DocumentError.

  • kind (str) – Error kind - “DocumentError”.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.DynamicClassificationResult(**kwargs)[source]

DynamicClassificationResult is a result object which contains the classifications for a particular document.

Variables
  • id (str) – Unique, non-empty document identifier.

  • classifications (list[ClassificationCategory]) – Recognized classification results in the document.

  • warnings (list[TextAnalyticsWarning]) – Warnings encountered while processing document.

  • statistics (Optional[TextDocumentStatistics]) – If show_stats=True was specified in the request this field will contain information about the document payload.

  • is_error (bool) – Boolean check for error item when iterating over list of results. Always False for an instance of a DynamicClassificationResult.

  • kind (str) – The text analysis kind - “DynamicClassification”.

New in version 2022-10-01-preview: The DynamicClassificationResult model.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.EntityAssociation(value)[source]

Describes if the entity is the subject of the text or if it describes someone else.

OTHER = 'other'
SUBJECT = 'subject'
class azure.ai.textanalytics.EntityCertainty(value)[source]

Describes the entities certainty and polarity.

NEGATIVE = 'negative'
NEGATIVE_POSSIBLE = 'negativePossible'
NEUTRAL_POSSIBLE = 'neutralPossible'
POSITIVE = 'positive'
POSITIVE_POSSIBLE = 'positivePossible'
class azure.ai.textanalytics.EntityConditionality(value)[source]

Describes any conditionality on the entity.

CONDITIONAL = 'conditional'
HYPOTHETICAL = 'hypothetical'
class azure.ai.textanalytics.ExtractKeyPhrasesAction(**kwargs)[source]

ExtractKeyPhrasesAction encapsulates the parameters for starting a long-running key phrase extraction operation

If you just want to extract key phrases from a list of documents, and not perform multiple long running actions on the input of documents, call method extract_key_phrases instead of interfacing with this model.

Keyword Arguments
  • model_version (Optional[str]) – The model version to use for the analysis.

  • disable_service_logs (Optional[bool]) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

Variables
  • model_version (Optional[str]) – The model version to use for the analysis.

  • disable_service_logs (Optional[bool]) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.ExtractKeyPhrasesResult(**kwargs)[source]

ExtractKeyPhrasesResult is a result object which contains the key phrases found in a particular document.

Variables
  • id (str) – Unique, non-empty document identifier that matches the document id that was passed in with the request. If not specified in the request, an id is assigned for the document.

  • key_phrases (list[str]) – A list of representative words or phrases. The number of key phrases returned is proportional to the number of words in the input document.

  • warnings (list[TextAnalyticsWarning]) – Warnings encountered while processing document. Results will still be returned if there are warnings, but they may not be fully accurate.

  • statistics (Optional[TextDocumentStatistics]) – If show_stats=True was specified in the request this field will contain information about the document payload.

  • detected_language (Optional[DetectedLanguage]) – If ‘language’ is set to ‘auto’ for the document in the request this field will contain the DetectedLanguage for the document.

  • is_error (bool) – Boolean check for error item when iterating over list of results. Always False for an instance of a ExtractKeyPhrasesResult.

  • kind (str) – The text analysis kind - “KeyPhraseExtraction”.

New in version 2022-10-01-preview: The detected_language property.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.ExtractSummaryAction(**kwargs)[source]

ExtractSummaryAction encapsulates the parameters for starting a long-running Extractive Text Summarization operation. For a conceptual discussion of extractive summarization, see the service documentation: https://learn.microsoft.com/azure/cognitive-services/language-service/summarization/overview

Keyword Arguments
  • model_version (Optional[str]) – The model version to use for the analysis.

  • string_index_type (Optional[str]) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • disable_service_logs (Optional[bool]) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

  • max_sentence_count (Optional[int]) – Maximum number of sentences to return. Defaults to 3.

  • order_by (Optional[str]) – Possible values include: “Offset”, “Rank”. Default value: “Offset”.

Variables
  • model_version (Optional[str]) – The model version to use for the analysis.

  • string_index_type (Optional[str]) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • disable_service_logs (Optional[bool]) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

  • max_sentence_count (Optional[int]) – Number of sentences to return. Defaults to 3.

  • order_by (Optional[str]) – Possible values include: “Offset”, “Rank”. Default value: “Offset”.

New in version 2022-10-01-preview: The ExtractSummaryAction model.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.ExtractSummaryResult(**kwargs)[source]

ExtractSummaryResult is a result object which contains the extractive text summarization from a particular document.

Variables
  • id (str) – Unique, non-empty document identifier.

  • sentences (list[SummarySentence]) – A ranked list of sentences representing the extracted summary.

  • warnings (list[TextAnalyticsWarning]) – Warnings encountered while processing document.

  • statistics (Optional[TextDocumentStatistics]) – If show_stats=True was specified in the request this field will contain information about the document payload.

  • detected_language (Optional[DetectedLanguage]) – If ‘language’ is set to ‘auto’ for the document in the request this field will contain the DetectedLanguage for the document.

  • is_error (bool) – Boolean check for error item when iterating over list of results. Always False for an instance of an ExtractSummaryResult.

  • kind (str) – The text analysis kind - “ExtractiveSummarization”.

New in version 2022-10-01-preview: The ExtractSummaryResult model.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.HealthcareDocumentType(value)[source]

Document type that can be provided as input for Fhir Documents. Expect to have fhirVersion provided when used. Behavior of using None enum is the same as not using the documentType parameter.

CLINICAL_TRIAL = 'ClinicalTrial'
CONSULT = 'Consult'
DISCHARGE_SUMMARY = 'DischargeSummary'
HISTORY_AND_PHYSICAL = 'HistoryAndPhysical'
IMAGING = 'Imaging'
NONE = 'None'
PATHOLOGY = 'Pathology'
PROCEDURE_NOTE = 'ProcedureNote'
PROGRESS_NOTE = 'ProgressNote'
class azure.ai.textanalytics.HealthcareEntity(**kwargs)[source]

HealthcareEntity contains information about a Healthcare entity found in text.

Variables
  • text (str) – Entity text as appears in the document.

  • normalized_text (Optional[str]) – Normalized version of the raw text we extract from the document. Not all text will have a normalized version.

  • category (str) – Entity category, see the HealthcareEntityCategory type for possible healthcare entity categories.

  • subcategory (Optional[str]) – Entity subcategory.

  • assertion (Optional[HealthcareEntityAssertion]) – Contains various assertions about this entity. For example, if an entity is a diagnosis, is this diagnosis ‘conditional’ on a symptom? Are the doctors ‘certain’ about this diagnosis? Is this diagnosis ‘associated’ with another diagnosis?

  • length (int) – The entity text length. This value depends on the value of the string_index_type parameter specified in the original request, which is UnicodeCodePoints by default.

  • offset (int) – The entity text offset from the start of the document. This value depends on the value of the string_index_type parameter specified in the original request, which is UnicodeCodePoints by default.

  • confidence_score (float) – Confidence score between 0 and 1 of the extracted entity.

  • data_sources (Optional[list[HealthcareEntityDataSource]]) – A collection of entity references in known data sources.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.HealthcareEntityAssertion(**kwargs)[source]

Contains various assertions about a HealthcareEntity.

For example, if an entity is a diagnosis, is this diagnosis ‘conditional’ on a symptom? Are the doctors ‘certain’ about this diagnosis? Is this diagnosis ‘associated’ with another diagnosis?

Variables
  • conditionality (Optional[str]) – Describes whether the healthcare entity it’s on is conditional on another entity. For example, “If the patient has a fever, he has pneumonia”, the diagnosis of pneumonia is ‘conditional’ on whether the patient has a fever. Possible values are “hypothetical” and “conditional”.

  • certainty (Optional[str]) – Describes how certain the healthcare entity it’s on is. For example, in “The patient may have a fever”, the fever entity is not 100% certain, but is instead “positivePossible”. Possible values are “positive”, “positivePossible”, “neutralPossible”, “negativePossible”, and “negative”.

  • association (Optional[str]) – Describes whether the healthcare entity it’s on is the subject of the document, or if this entity describes someone else in the document. For example, in “The subject’s mother has a fever”, the “fever” entity is not associated with the subject themselves, but with the subject’s mother. Possible values are “subject” and “other”.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.HealthcareEntityCategory(value)[source]

Healthcare Entity Category.

ADMINISTRATIVE_EVENT = 'AdministrativeEvent'
AGE = 'Age'
BODY_STRUCTURE = 'BodyStructure'
CARE_ENVIRONMENT = 'CareEnvironment'
CONDITION_QUALIFIER = 'ConditionQualifier'
DATE = 'Date'
DIAGNOSIS = 'Diagnosis'
DIRECTION = 'Direction'
DOSAGE = 'Dosage'
EXAMINATION_NAME = 'ExaminationName'
FAMILY_RELATION = 'FamilyRelation'
FREQUENCY = 'Frequency'
GENDER = 'Gender'
GENE_OR_PROTEIN = 'GeneOrProtein'
HEALTHCARE_PROFESSION = 'HealthcareProfession'
MEASUREMENT_UNIT = 'MeasurementUnit'
MEASUREMENT_VALUE = 'MeasurementValue'
MEDICATION_CLASS = 'MedicationClass'
MEDICATION_FORM = 'MedicationForm'
MEDICATION_NAME = 'MedicationName'
MEDICATION_ROUTE = 'MedicationRoute'
RELATIONAL_OPERATOR = 'RelationalOperator'
SYMPTOM_OR_SIGN = 'SymptomOrSign'
TIME = 'Time'
TREATMENT_NAME = 'TreatmentName'
VARIANT = 'Variant'
class azure.ai.textanalytics.HealthcareEntityDataSource(**kwargs)[source]

HealthcareEntityDataSource contains information representing an entity reference in a known data source.

Variables
  • entity_id (str) – ID of the entity in the given source catalog.

  • name (str) – The name of the entity catalog from where the entity was identified, such as UMLS, CHV, MSH, etc.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.HealthcareEntityRelation(value)[source]

Type of relation. Examples include: ‘DosageOfMedication’ or ‘FrequencyOfMedication’, etc.

ABBREVIATION = 'Abbreviation'
DIRECTION_OF_BODY_STRUCTURE = 'DirectionOfBodyStructure'
DIRECTION_OF_CONDITION = 'DirectionOfCondition'
DIRECTION_OF_EXAMINATION = 'DirectionOfExamination'
DIRECTION_OF_TREATMENT = 'DirectionOfTreatment'
DOSAGE_OF_MEDICATION = 'DosageOfMedication'
FORM_OF_MEDICATION = 'FormOfMedication'
FREQUENCY_OF_MEDICATION = 'FrequencyOfMedication'
FREQUENCY_OF_TREATMENT = 'FrequencyOfTreatment'
QUALIFIER_OF_CONDITION = 'QualifierOfCondition'
RELATION_OF_EXAMINATION = 'RelationOfExamination'
ROUTE_OF_MEDICATION = 'RouteOfMedication'
TIME_OF_CONDITION = 'TimeOfCondition'
TIME_OF_EVENT = 'TimeOfEvent'
TIME_OF_EXAMINATION = 'TimeOfExamination'
TIME_OF_MEDICATION = 'TimeOfMedication'
TIME_OF_TREATMENT = 'TimeOfTreatment'
UNIT_OF_CONDITION = 'UnitOfCondition'
UNIT_OF_EXAMINATION = 'UnitOfExamination'
VALUE_OF_CONDITION = 'ValueOfCondition'
VALUE_OF_EXAMINATION = 'ValueOfExamination'
class azure.ai.textanalytics.HealthcareRelation(**kwargs)[source]

HealthcareRelation is a result object which represents a relation detected in a document.

Every HealthcareRelation is an entity graph of a certain relation type, where all entities are connected and have specific roles within the relation context.

Variables
  • relation_type (str) – The type of relation, i.e. the relationship between “100mg” and “ibuprofen” in the document “The subject took 100 mg of ibuprofen” is “DosageOfMedication”. Possible values found in HealthcareEntityRelation

  • roles (list[HealthcareRelationRole]) – The roles present in this relation. I.e., in the document “The subject took 100 mg of ibuprofen”, the present roles are “Dosage” and “Medication”.

  • confidence_score (Optional[float]) – Confidence score between 0 and 1 of the extracted relation.

New in version 2022-10-01-preview: The confidence_score property.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.HealthcareRelationRole(**kwargs)[source]

A model representing a role in a relation.

For example, in “The subject took 100 mg of ibuprofen”, “100 mg” is a dosage entity fulfilling the role “Dosage” in the extracted relation “DosageOfMedication”.

Variables
  • name (str) – The role of the entity in the relationship. I.e., in the relation “The subject took 100 mg of ibuprofen”, the dosage entity “100 mg” has role “Dosage”.

  • entity (HealthcareEntity) – The entity that is present in the relationship. For example, in “The subject took 100 mg of ibuprofen”, this property holds the dosage entity of “100 mg”.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.InformationResolution(*, value: float, unit: Union[str, _models.InformationUnit], **kwargs)[source]
Keyword Arguments
  • value (float) – The numeric value that the extracted text denotes. Required.

  • unit (str or InformationUnit) – The information (data) Unit of measurement. Required. Known values are: “Unspecified”, “Bit”, “Kilobit”, “Megabit”, “Gigabit”, “Terabit”, “Petabit”, “Byte”, “Kilobyte”, “Megabyte”, “Gigabyte”, “Terabyte”, and “Petabyte”.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

get(key, default=None)
has_key(k)
classmethod is_xml_model()
items()
keys()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

update(*args, **kwargs)
values()
class azure.ai.textanalytics.InformationUnit(value)[source]

The information (data) Unit of measurement.

BIT = 'Bit'
BYTE = 'Byte'
GIGABIT = 'Gigabit'
GIGABYTE = 'Gigabyte'
KILOBIT = 'Kilobit'
KILOBYTE = 'Kilobyte'
MEGABIT = 'Megabit'
MEGABYTE = 'Megabyte'
PETABIT = 'Petabit'
PETABYTE = 'Petabyte'
TERABIT = 'Terabit'
TERABYTE = 'Terabyte'
UNSPECIFIED = 'Unspecified'
class azure.ai.textanalytics.LengthResolution(*, value: float, unit: Union[str, _models.LengthUnit], **kwargs)[source]
Keyword Arguments
  • value (float) – The numeric value that the extracted text denotes. Required.

  • unit (str or LengthUnit) – The length Unit of measurement. Required. Known values are: “Unspecified”, “Kilometer”, “Hectometer”, “Decameter”, “Meter”, “Decimeter”, “Centimeter”, “Millimeter”, “Micrometer”, “Nanometer”, “Picometer”, “Mile”, “Yard”, “Inch”, “Foot”, “LightYear”, and “Pt”.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

get(key, default=None)
has_key(k)
classmethod is_xml_model()
items()
keys()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

update(*args, **kwargs)
values()
class azure.ai.textanalytics.LengthUnit(value)[source]

The length Unit of measurement.

CENTIMETER = 'Centimeter'
DECAMETER = 'Decameter'
DECIMETER = 'Decimeter'
FOOT = 'Foot'
HECTOMETER = 'Hectometer'
INCH = 'Inch'
KILOMETER = 'Kilometer'
LIGHT_YEAR = 'LightYear'
METER = 'Meter'
MICROMETER = 'Micrometer'
MILE = 'Mile'
MILLIMETER = 'Millimeter'
NANOMETER = 'Nanometer'
PICOMETER = 'Picometer'
PT = 'Pt'
UNSPECIFIED = 'Unspecified'
YARD = 'Yard'
class azure.ai.textanalytics.LinkedEntity(**kwargs)[source]

LinkedEntity contains a link to the well-known recognized entity in text. The link comes from a data source like Wikipedia or Bing. It additionally includes all of the matches of this entity found in the document.

Variables
  • name (str) – Entity Linking formal name.

  • matches (list[LinkedEntityMatch]) – List of instances this entity appears in the text.

  • language (str) – Language used in the data source.

  • data_source_entity_id (Optional[str]) – Unique identifier of the recognized entity from the data source.

  • url (str) – URL to the entity’s page from the data source.

  • data_source (str) – Data source used to extract entity linking, such as Wiki/Bing etc.

  • bing_entity_search_api_id (Optional[str]) – Bing Entity Search unique identifier of the recognized entity. Use in conjunction with the Bing Entity Search SDK to fetch additional relevant information.

New in version v3.1: The bing_entity_search_api_id property.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.LinkedEntityMatch(**kwargs)[source]

A match for the linked entity found in text. Provides the confidence score of the prediction and where the entity was found in the text.

Variables
  • confidence_score (float) – If a well-known item is recognized, a decimal number denoting the confidence level between 0 and 1 will be returned.

  • text (str) – Entity text as appears in the request.

  • length (int) – The linked entity match text length. This value depends on the value of the string_index_type parameter set in the original request, which is UnicodeCodePoints by default.

  • offset (int) – The linked entity match text offset from the start of the document. The value depends on the value of the string_index_type parameter set in the original request, which is UnicodeCodePoints by default.

New in version v3.1: The offset and length properties.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.MinedOpinion(**kwargs)[source]

A mined opinion object represents an opinion we’ve extracted from a sentence. It consists of both a target that these opinions are about, and the assessments representing the opinion.

Variables
  • target (Optional[TargetSentiment]) – The target of an opinion about a product/service.

  • assessments (Optional[list[AssessmentSentiment]]) – The assessments representing the opinion of the target.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.MultiLabelClassifyAction(project_name: str, deployment_name: str, **kwargs)[source]

MultiLabelClassifyAction encapsulates the parameters for starting a long-running custom multi label classification operation. For information on regional support of custom features and how to train a model to classify your documents, see https://aka.ms/azsdk/textanalytics/customfunctionalities

Parameters
  • project_name (str) – Required. This field indicates the project name for the model.

  • deployment_name (str) – Required. This field indicates the deployment name for the model.

Keyword Arguments

disable_service_logs (Optional[bool]) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

Variables
  • project_name (str) – This field indicates the project name for the model.

  • deployment_name (str) – This field indicates the deployment name for the model.

  • disable_service_logs (Optional[bool]) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

New in version 2022-05-01: The MultiLabelClassifyAction model.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.NumberKind(value)[source]

The type of the extracted number entity.

DECIMAL = 'Decimal'
FRACTION = 'Fraction'
INTEGER = 'Integer'
PERCENT = 'Percent'
POWER = 'Power'
UNSPECIFIED = 'Unspecified'
class azure.ai.textanalytics.NumberResolution(*, number_kind: Union[str, _models.NumberKind], value: float, **kwargs)[source]
Keyword Arguments
  • number_kind (str or NumberKind) – The type of the extracted number entity. Required. Known values are: “Integer”, “Decimal”, “Power”, “Fraction”, “Percent”, and “Unspecified”.

  • value (float) – A numeric representation of what the extracted text denotes. Required.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

get(key, default=None)
has_key(k)
classmethod is_xml_model()
items()
keys()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

update(*args, **kwargs)
values()
class azure.ai.textanalytics.NumericRangeResolution(*, range_kind: Union[str, _models.RangeKind], minimum: float, maximum: float, **kwargs)[source]
Keyword Arguments
  • range_kind (str or RangeKind) – The kind of range that the resolution object represents. Required. Known values are: “Number”, “Speed”, “Weight”, “Length”, “Volume”, “Area”, “Age”, “Information”, “Temperature”, and “Currency”.

  • minimum (float) – The beginning value of the interval. Required.

  • maximum (float) – The ending value of the interval. Required.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

get(key, default=None)
has_key(k)
classmethod is_xml_model()
items()
keys()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

update(*args, **kwargs)
values()
class azure.ai.textanalytics.OrdinalResolution(*, offset: str, relative_to: Union[str, _models.RelativeTo], value: str, **kwargs)[source]
Keyword Arguments
  • offset (str) – The offset With respect to the reference (e.g., offset = -1 in “show me the second to last”. Required.

  • relative_to (str or RelativeTo) – The reference point that the ordinal number denotes. Required. Known values are: “Current”, “End”, and “Start”.

  • value (str) – A simple arithmetic expression that the ordinal denotes. Required.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

get(key, default=None)
has_key(k)
classmethod is_xml_model()
items()
keys()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

update(*args, **kwargs)
values()
class azure.ai.textanalytics.PiiEntity(**kwargs)[source]

PiiEntity contains information about a Personally Identifiable Information (PII) entity found in text.

Variables
  • text (str) – Entity text as appears in the request.

  • category (str) – Entity category, such as Financial Account Identification/Social Security Number/Phone Number, etc.

  • subcategory (str) – Entity subcategory, such as Credit Card/EU Phone number/ABA Routing Numbers, etc.

  • length (int) – The PII entity text length. This value depends on the value of the string_index_type parameter specified in the original request, which is UnicodeCodePoints by default.

  • offset (int) – The PII entity text offset from the start of the document. This value depends on the value of the string_index_type parameter specified in the original request, which is UnicodeCodePoints by default.

  • confidence_score (float) – Confidence score between 0 and 1 of the extracted entity.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.PiiEntityCategory(value)[source]

Categories of Personally Identifiable Information (PII).

ABA_ROUTING_NUMBER = 'ABARoutingNumber'
ADDRESS = 'Address'
AGE = 'Age'
ALL = 'All'
AR_NATIONAL_IDENTITY_NUMBER = 'ARNationalIdentityNumber'
AT_IDENTITY_CARD = 'ATIdentityCard'
AT_TAX_IDENTIFICATION_NUMBER = 'ATTaxIdentificationNumber'
AT_VALUE_ADDED_TAX_NUMBER = 'ATValueAddedTaxNumber'
AU_BANK_ACCOUNT_NUMBER = 'AUBankAccountNumber'
AU_BUSINESS_NUMBER = 'AUBusinessNumber'
AU_COMPANY_NUMBER = 'AUCompanyNumber'
AU_DRIVERS_LICENSE_NUMBER = 'AUDriversLicenseNumber'
AU_MEDICAL_ACCOUNT_NUMBER = 'AUMedicalAccountNumber'
AU_PASSPORT_NUMBER = 'AUPassportNumber'
AU_TAX_FILE_NUMBER = 'AUTaxFileNumber'
AZURE_DOCUMENT_DB_AUTH_KEY = 'AzureDocumentDBAuthKey'
AZURE_IAAS_DATABASE_CONNECTION_AND_SQL_STRING = 'AzureIAASDatabaseConnectionAndSQLString'
AZURE_IO_T_CONNECTION_STRING = 'AzureIoTConnectionString'
AZURE_PUBLISH_SETTING_PASSWORD = 'AzurePublishSettingPassword'
AZURE_REDIS_CACHE_STRING = 'AzureRedisCacheString'
AZURE_SAS = 'AzureSAS'
AZURE_SERVICE_BUS_STRING = 'AzureServiceBusString'
AZURE_STORAGE_ACCOUNT_GENERIC = 'AzureStorageAccountGeneric'
AZURE_STORAGE_ACCOUNT_KEY = 'AzureStorageAccountKey'
BE_NATIONAL_NUMBER = 'BENationalNumber'
BE_NATIONAL_NUMBER_V2 = 'BENationalNumberV2'
BE_VALUE_ADDED_TAX_NUMBER = 'BEValueAddedTaxNumber'
BG_UNIFORM_CIVIL_NUMBER = 'BGUniformCivilNumber'
BRCPF_NUMBER = 'BRCPFNumber'
BR_NATIONAL_IDRG = 'BRNationalIDRG'
CA_BANK_ACCOUNT_NUMBER = 'CABankAccountNumber'
CA_DRIVERS_LICENSE_NUMBER = 'CADriversLicenseNumber'
CA_HEALTH_SERVICE_NUMBER = 'CAHealthServiceNumber'
CA_PASSPORT_NUMBER = 'CAPassportNumber'
CA_PERSONAL_HEALTH_IDENTIFICATION = 'CAPersonalHealthIdentification'
CA_SOCIAL_INSURANCE_NUMBER = 'CASocialInsuranceNumber'
CH_SOCIAL_SECURITY_NUMBER = 'CHSocialSecurityNumber'
CL_IDENTITY_CARD_NUMBER = 'CLIdentityCardNumber'
CN_RESIDENT_IDENTITY_CARD_NUMBER = 'CNResidentIdentityCardNumber'
CREDIT_CARD_NUMBER = 'CreditCardNumber'
CY_IDENTITY_CARD = 'CYIdentityCard'
CY_TAX_IDENTIFICATION_NUMBER = 'CYTaxIdentificationNumber'
CZ_PERSONAL_IDENTITY_NUMBER = 'CZPersonalIdentityNumber'
CZ_PERSONAL_IDENTITY_V2 = 'CZPersonalIdentityV2'
DATE = 'Date'
DEFAULT = 'Default'
DE_DRIVERS_LICENSE_NUMBER = 'DEDriversLicenseNumber'
DE_IDENTITY_CARD_NUMBER = 'DEIdentityCardNumber'
DE_PASSPORT_NUMBER = 'DEPassportNumber'
DE_TAX_IDENTIFICATION_NUMBER = 'DETaxIdentificationNumber'
DE_VALUE_ADDED_NUMBER = 'DEValueAddedNumber'
DK_PERSONAL_IDENTIFICATION_NUMBER = 'DKPersonalIdentificationNumber'
DK_PERSONAL_IDENTIFICATION_V2 = 'DKPersonalIdentificationV2'
DRUG_ENFORCEMENT_AGENCY_NUMBER = 'DrugEnforcementAgencyNumber'
EE_PERSONAL_IDENTIFICATION_CODE = 'EEPersonalIdentificationCode'
EMAIL = 'Email'
ESDNI = 'ESDNI'
ES_SOCIAL_SECURITY_NUMBER = 'ESSocialSecurityNumber'
ES_TAX_IDENTIFICATION_NUMBER = 'ESTaxIdentificationNumber'
EUGPS_COORDINATES = 'EUGPSCoordinates'
EU_DEBIT_CARD_NUMBER = 'EUDebitCardNumber'
EU_DRIVERS_LICENSE_NUMBER = 'EUDriversLicenseNumber'
EU_NATIONAL_IDENTIFICATION_NUMBER = 'EUNationalIdentificationNumber'
EU_PASSPORT_NUMBER = 'EUPassportNumber'
EU_SOCIAL_SECURITY_NUMBER = 'EUSocialSecurityNumber'
EU_TAX_IDENTIFICATION_NUMBER = 'EUTaxIdentificationNumber'
FI_EUROPEAN_HEALTH_NUMBER = 'FIEuropeanHealthNumber'
FI_NATIONAL_ID = 'FINationalID'
FI_NATIONAL_IDV2 = 'FINationalIDV2'
FI_PASSPORT_NUMBER = 'FIPassportNumber'
FR_DRIVERS_LICENSE_NUMBER = 'FRDriversLicenseNumber'
FR_HEALTH_INSURANCE_NUMBER = 'FRHealthInsuranceNumber'
FR_NATIONAL_ID = 'FRNationalID'
FR_PASSPORT_NUMBER = 'FRPassportNumber'
FR_SOCIAL_SECURITY_NUMBER = 'FRSocialSecurityNumber'
FR_TAX_IDENTIFICATION_NUMBER = 'FRTaxIdentificationNumber'
FR_VALUE_ADDED_TAX_NUMBER = 'FRValueAddedTaxNumber'
GR_NATIONAL_IDV2 = 'GRNationalIDV2'
GR_NATIONAL_ID_CARD = 'GRNationalIDCard'
GR_TAX_IDENTIFICATION_NUMBER = 'GRTaxIdentificationNumber'
HK_IDENTITY_CARD_NUMBER = 'HKIdentityCardNumber'
HR_IDENTITY_CARD_NUMBER = 'HRIdentityCardNumber'
HR_NATIONAL_ID_NUMBER = 'HRNationalIDNumber'
HR_PERSONAL_IDENTIFICATION_NUMBER = 'HRPersonalIdentificationNumber'
HR_PERSONAL_IDENTIFICATION_OIB_NUMBER_V2 = 'HRPersonalIdentificationOIBNumberV2'
HU_PERSONAL_IDENTIFICATION_NUMBER = 'HUPersonalIdentificationNumber'
HU_TAX_IDENTIFICATION_NUMBER = 'HUTaxIdentificationNumber'
HU_VALUE_ADDED_NUMBER = 'HUValueAddedNumber'
ID_IDENTITY_CARD_NUMBER = 'IDIdentityCardNumber'
IE_PERSONAL_PUBLIC_SERVICE_NUMBER = 'IEPersonalPublicServiceNumber'
IE_PERSONAL_PUBLIC_SERVICE_NUMBER_V2 = 'IEPersonalPublicServiceNumberV2'
IL_BANK_ACCOUNT_NUMBER = 'ILBankAccountNumber'
IL_NATIONAL_ID = 'ILNationalID'
INTERNATIONAL_BANKING_ACCOUNT_NUMBER = 'InternationalBankingAccountNumber'
IN_PERMANENT_ACCOUNT = 'INPermanentAccount'
IN_UNIQUE_IDENTIFICATION_NUMBER = 'INUniqueIdentificationNumber'
IP_ADDRESS = 'IPAddress'
IT_DRIVERS_LICENSE_NUMBER = 'ITDriversLicenseNumber'
IT_FISCAL_CODE = 'ITFiscalCode'
IT_VALUE_ADDED_TAX_NUMBER = 'ITValueAddedTaxNumber'
JP_BANK_ACCOUNT_NUMBER = 'JPBankAccountNumber'
JP_DRIVERS_LICENSE_NUMBER = 'JPDriversLicenseNumber'
JP_MY_NUMBER_CORPORATE = 'JPMyNumberCorporate'
JP_MY_NUMBER_PERSONAL = 'JPMyNumberPersonal'
JP_PASSPORT_NUMBER = 'JPPassportNumber'
JP_RESIDENCE_CARD_NUMBER = 'JPResidenceCardNumber'
JP_RESIDENT_REGISTRATION_NUMBER = 'JPResidentRegistrationNumber'
JP_SOCIAL_INSURANCE_NUMBER = 'JPSocialInsuranceNumber'
KR_RESIDENT_REGISTRATION_NUMBER = 'KRResidentRegistrationNumber'
LT_PERSONAL_CODE = 'LTPersonalCode'
LU_NATIONAL_IDENTIFICATION_NUMBER_NATURAL = 'LUNationalIdentificationNumberNatural'
LU_NATIONAL_IDENTIFICATION_NUMBER_NON_NATURAL = 'LUNationalIdentificationNumberNonNatural'
LV_PERSONAL_CODE = 'LVPersonalCode'
MT_IDENTITY_CARD_NUMBER = 'MTIdentityCardNumber'
MT_TAX_ID_NUMBER = 'MTTaxIDNumber'
MY_IDENTITY_CARD_NUMBER = 'MYIdentityCardNumber'
NL_CITIZENS_SERVICE_NUMBER = 'NLCitizensServiceNumber'
NL_CITIZENS_SERVICE_NUMBER_V2 = 'NLCitizensServiceNumberV2'
NL_TAX_IDENTIFICATION_NUMBER = 'NLTaxIdentificationNumber'
NL_VALUE_ADDED_TAX_NUMBER = 'NLValueAddedTaxNumber'
NO_IDENTITY_NUMBER = 'NOIdentityNumber'
NZ_BANK_ACCOUNT_NUMBER = 'NZBankAccountNumber'
NZ_DRIVERS_LICENSE_NUMBER = 'NZDriversLicenseNumber'
NZ_INLAND_REVENUE_NUMBER = 'NZInlandRevenueNumber'
NZ_MINISTRY_OF_HEALTH_NUMBER = 'NZMinistryOfHealthNumber'
NZ_SOCIAL_WELFARE_NUMBER = 'NZSocialWelfareNumber'
ORGANIZATION = 'Organization'
PERSON = 'Person'
PHONE_NUMBER = 'PhoneNumber'
PH_UNIFIED_MULTI_PURPOSE_ID_NUMBER = 'PHUnifiedMultiPurposeIDNumber'
PLREGON_NUMBER = 'PLREGONNumber'
PL_IDENTITY_CARD = 'PLIdentityCard'
PL_NATIONAL_ID = 'PLNationalID'
PL_NATIONAL_IDV2 = 'PLNationalIDV2'
PL_PASSPORT_NUMBER = 'PLPassportNumber'
PL_TAX_IDENTIFICATION_NUMBER = 'PLTaxIdentificationNumber'
PT_CITIZEN_CARD_NUMBER = 'PTCitizenCardNumber'
PT_CITIZEN_CARD_NUMBER_V2 = 'PTCitizenCardNumberV2'
PT_TAX_IDENTIFICATION_NUMBER = 'PTTaxIdentificationNumber'
RO_PERSONAL_NUMERICAL_CODE = 'ROPersonalNumericalCode'
RU_PASSPORT_NUMBER_DOMESTIC = 'RUPassportNumberDomestic'
RU_PASSPORT_NUMBER_INTERNATIONAL = 'RUPassportNumberInternational'
SA_NATIONAL_ID = 'SANationalID'
SE_NATIONAL_ID = 'SENationalID'
SE_NATIONAL_IDV2 = 'SENationalIDV2'
SE_PASSPORT_NUMBER = 'SEPassportNumber'
SE_TAX_IDENTIFICATION_NUMBER = 'SETaxIdentificationNumber'
SG_NATIONAL_REGISTRATION_IDENTITY_CARD_NUMBER = 'SGNationalRegistrationIdentityCardNumber'
SI_TAX_IDENTIFICATION_NUMBER = 'SITaxIdentificationNumber'
SI_UNIQUE_MASTER_CITIZEN_NUMBER = 'SIUniqueMasterCitizenNumber'
SK_PERSONAL_NUMBER = 'SKPersonalNumber'
SQL_SERVER_CONNECTION_STRING = 'SQLServerConnectionString'
SWIFT_CODE = 'SWIFTCode'
TH_POPULATION_IDENTIFICATION_CODE = 'THPopulationIdentificationCode'
TR_NATIONAL_IDENTIFICATION_NUMBER = 'TRNationalIdentificationNumber'
TW_NATIONAL_ID = 'TWNationalID'
TW_PASSPORT_NUMBER = 'TWPassportNumber'
TW_RESIDENT_CERTIFICATE = 'TWResidentCertificate'
UA_PASSPORT_NUMBER_DOMESTIC = 'UAPassportNumberDomestic'
UA_PASSPORT_NUMBER_INTERNATIONAL = 'UAPassportNumberInternational'
UK_DRIVERS_LICENSE_NUMBER = 'UKDriversLicenseNumber'
UK_ELECTORAL_ROLL_NUMBER = 'UKElectoralRollNumber'
UK_NATIONAL_HEALTH_NUMBER = 'UKNationalHealthNumber'
UK_NATIONAL_INSURANCE_NUMBER = 'UKNationalInsuranceNumber'
UK_UNIQUE_TAXPAYER_NUMBER = 'UKUniqueTaxpayerNumber'
URL = 'URL'
USUK_PASSPORT_NUMBER = 'USUKPassportNumber'
US_BANK_ACCOUNT_NUMBER = 'USBankAccountNumber'
US_DRIVERS_LICENSE_NUMBER = 'USDriversLicenseNumber'
US_INDIVIDUAL_TAXPAYER_IDENTIFICATION = 'USIndividualTaxpayerIdentification'
US_SOCIAL_SECURITY_NUMBER = 'USSocialSecurityNumber'
ZA_IDENTIFICATION_NUMBER = 'ZAIdentificationNumber'
class azure.ai.textanalytics.PiiEntityDomain(value)[source]

The different domains of PII entities that users can filter by

PROTECTED_HEALTH_INFORMATION = 'phi'
class azure.ai.textanalytics.RangeKind(value)[source]

The kind of range that the resolution object represents.

AGE = 'Age'
AREA = 'Area'
CURRENCY = 'Currency'
INFORMATION = 'Information'
LENGTH = 'Length'
NUMBER = 'Number'
SPEED = 'Speed'
TEMPERATURE = 'Temperature'
VOLUME = 'Volume'
WEIGHT = 'Weight'
class azure.ai.textanalytics.RecognizeCustomEntitiesAction(project_name: str, deployment_name: str, **kwargs)[source]

RecognizeCustomEntitiesAction encapsulates the parameters for starting a long-running custom entity recognition operation. For information on regional support of custom features and how to train a model to recognize custom entities, see https://aka.ms/azsdk/textanalytics/customentityrecognition

Parameters
  • project_name (str) – Required. This field indicates the project name for the model.

  • deployment_name (str) – This field indicates the deployment name for the model.

Keyword Arguments
  • string_index_type (Optional[str]) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • disable_service_logs (Optional[bool]) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

Variables
  • project_name (str) – This field indicates the project name for the model.

  • deployment_name (str) – This field indicates the deployment name for the model.

  • string_index_type (Optional[str]) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • disable_service_logs (Optional[bool]) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

New in version 2022-05-01: The RecognizeCustomEntitiesAction model.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.RecognizeCustomEntitiesResult(**kwargs)[source]

RecognizeCustomEntitiesResult is a result object which contains the custom recognized entities from a particular document.

Variables
  • id (str) – Unique, non-empty document identifier that matches the document id that was passed in with the request. If not specified in the request, an id is assigned for the document.

  • entities (list[CategorizedEntity]) – Recognized custom entities in the document.

  • warnings (list[TextAnalyticsWarning]) – Warnings encountered while processing document.

  • statistics (Optional[TextDocumentStatistics]) – If show_stats=True was specified in the request this field will contain information about the document payload.

  • detected_language (Optional[DetectedLanguage]) – If ‘language’ is set to ‘auto’ for the document in the request this field will contain the DetectedLanguage for the document.

  • is_error (bool) – Boolean check for error item when iterating over list of results. Always False for an instance of a RecognizeCustomEntitiesResult.

  • kind (str) – The text analysis kind - “CustomEntityRecognition”.

New in version 2022-10-01-preview: The detected_language property.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.RecognizeEntitiesAction(**kwargs)[source]

RecognizeEntitiesAction encapsulates the parameters for starting a long-running Entities Recognition operation.

If you just want to recognize entities in a list of documents, and not perform multiple long running actions on the input of documents, call method recognize_entities instead of interfacing with this model.

Keyword Arguments
  • model_version (Optional[str]) – The model version to use for the analysis.

  • string_index_type (Optional[str]) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • disable_service_logs (Optional[bool]) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

Variables
  • model_version (Optional[str]) – The model version to use for the analysis.

  • string_index_type (Optional[str]) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • disable_service_logs (Optional[bool]) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.RecognizeEntitiesResult(**kwargs)[source]

RecognizeEntitiesResult is a result object which contains the recognized entities from a particular document.

Variables
  • id (str) – Unique, non-empty document identifier that matches the document id that was passed in with the request. If not specified in the request, an id is assigned for the document.

  • entities (list[CategorizedEntity]) – Recognized entities in the document.

  • warnings (list[TextAnalyticsWarning]) – Warnings encountered while processing document. Results will still be returned if there are warnings, but they may not be fully accurate.

  • statistics (Optional[TextDocumentStatistics]) – If show_stats=True was specified in the request this field will contain information about the document payload.

  • detected_language (Optional[DetectedLanguage]) – If ‘language’ is set to ‘auto’ for the document in the request this field will contain the DetectedLanguage for the document.

  • is_error (bool) – Boolean check for error item when iterating over list of results. Always False for an instance of a RecognizeEntitiesResult.

  • kind (str) – The text analysis kind - “EntityRecognition”.

New in version 2022-10-01-preview: The detected_language property.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.RecognizeLinkedEntitiesAction(**kwargs)[source]

RecognizeLinkedEntitiesAction encapsulates the parameters for starting a long-running Linked Entities Recognition operation.

If you just want to recognize linked entities in a list of documents, and not perform multiple long running actions on the input of documents, call method recognize_linked_entities instead of interfacing with this model.

Keyword Arguments
  • model_version (Optional[str]) – The model version to use for the analysis.

  • string_index_type (Optional[str]) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • disable_service_logs (Optional[bool]) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

Variables
  • model_version (Optional[str]) – The model version to use for the analysis.

  • string_index_type (Optional[str]) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • disable_service_logs (Optional[bool]) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.RecognizeLinkedEntitiesResult(**kwargs)[source]

RecognizeLinkedEntitiesResult is a result object which contains links to a well-known knowledge base, like for example, Wikipedia or Bing.

Variables
  • id (str) – Unique, non-empty document identifier that matches the document id that was passed in with the request. If not specified in the request, an id is assigned for the document.

  • entities (list[LinkedEntity]) – Recognized well-known entities in the document.

  • warnings (list[TextAnalyticsWarning]) – Warnings encountered while processing document. Results will still be returned if there are warnings, but they may not be fully accurate.

  • statistics (Optional[TextDocumentStatistics]) – If show_stats=True was specified in the request this field will contain information about the document payload.

  • detected_language (Optional[DetectedLanguage]) – If ‘language’ is set to ‘auto’ for the document in the request this field will contain the DetectedLanguage for the document.

  • is_error (bool) – Boolean check for error item when iterating over list of results. Always False for an instance of a RecognizeLinkedEntitiesResult.

  • kind (str) – The text analysis kind - “EntityLinking”.

New in version 2022-10-01-preview: The detected_language property.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.RecognizePiiEntitiesAction(**kwargs)[source]

RecognizePiiEntitiesAction encapsulates the parameters for starting a long-running PII Entities Recognition operation.

If you just want to recognize pii entities in a list of documents, and not perform multiple long running actions on the input of documents, call method recognize_pii_entities instead of interfacing with this model.

Keyword Arguments
  • model_version (Optional[str]) – The model version to use for the analysis.

  • domain_filter (Optional[str]) – An optional string to set the PII domain to include only a subset of the PII entity categories. Possible values include ‘phi’ or None.

  • categories_filter (Optional[list[str or PiiEntityCategory]]) – Instead of filtering over all PII entity categories, you can pass in a list of the specific PII entity categories you want to filter out. For example, if you only want to filter out U.S. social security numbers in a document, you can pass in [PiiEntityCategory.US_SOCIAL_SECURITY_NUMBER] for this kwarg.

  • string_index_type (Optional[str]) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • disable_service_logs (Optional[bool]) – Defaults to true, meaning that the Language service will not log your input text on the service side for troubleshooting. If set to False, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

Variables
  • model_version (Optional[str]) – The model version to use for the analysis.

  • domain_filter (Optional[str]) – An optional string to set the PII domain to include only a subset of the PII entity categories. Possible values include ‘phi’ or None.

  • categories_filter (Optional[list[str or PiiEntityCategory]]) – Instead of filtering over all PII entity categories, you can pass in a list of the specific PII entity categories you want to filter out. For example, if you only want to filter out U.S. social security numbers in a document, you can pass in [PiiEntityCategory.US_SOCIAL_SECURITY_NUMBER] for this kwarg.

  • string_index_type (Optional[str]) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • disable_service_logs (Optional[bool]) – Defaults to true, meaning that the Language service will not log your input text on the service side for troubleshooting. If set to False, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.RecognizePiiEntitiesResult(**kwargs)[source]

RecognizePiiEntitiesResult is a result object which contains the recognized Personally Identifiable Information (PII) entities from a particular document.

Variables
  • id (str) – Unique, non-empty document identifier that matches the document id that was passed in with the request. If not specified in the request, an id is assigned for the document.

  • entities (list[PiiEntity]) – Recognized PII entities in the document.

  • redacted_text (str) – Returns the text of the input document with all of the PII information redacted out.

  • warnings (list[TextAnalyticsWarning]) – Warnings encountered while processing document. Results will still be returned if there are warnings, but they may not be fully accurate.

  • statistics (Optional[TextDocumentStatistics]) – If show_stats=True was specified in the request this field will contain information about the document payload.

  • detected_language (Optional[DetectedLanguage]) – If ‘language’ is set to ‘auto’ for the document in the request this field will contain the DetectedLanguage for the document.

  • is_error (bool) – Boolean check for error item when iterating over list of results. Always False for an instance of a RecognizePiiEntitiesResult.

  • kind (str) – The text analysis kind - “PiiEntityRecognition”.

New in version 2022-10-01-preview: The detected_language property.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.RelativeTo(value)[source]

The reference point that the ordinal number denotes.

CURRENT = 'Current'
END = 'End'
START = 'Start'
class azure.ai.textanalytics.ResolutionKind(value)[source]

The entity resolution object kind.

AGE_RESOLUTION = 'AgeResolution'
AREA_RESOLUTION = 'AreaResolution'
BOOLEAN_RESOLUTION = 'BooleanResolution'
CURRENCY_RESOLUTION = 'CurrencyResolution'
DATE_TIME_RESOLUTION = 'DateTimeResolution'
INFORMATION_RESOLUTION = 'InformationResolution'
LENGTH_RESOLUTION = 'LengthResolution'
NUMBER_RESOLUTION = 'NumberResolution'
NUMERIC_RANGE_RESOLUTION = 'NumericRangeResolution'
ORDINAL_RESOLUTION = 'OrdinalResolution'
SPEED_RESOLUTION = 'SpeedResolution'
TEMPERATURE_RESOLUTION = 'TemperatureResolution'
TEMPORAL_SPAN_RESOLUTION = 'TemporalSpanResolution'
VOLUME_RESOLUTION = 'VolumeResolution'
WEIGHT_RESOLUTION = 'WeightResolution'
class azure.ai.textanalytics.SentenceSentiment(**kwargs)[source]

SentenceSentiment contains the predicted sentiment and confidence scores for each individual sentence in the document.

Variables
  • text (str) – The sentence text.

  • sentiment (str) – The predicted Sentiment for the sentence. Possible values include: ‘positive’, ‘neutral’, ‘negative’

  • confidence_scores (SentimentConfidenceScores) – The sentiment confidence score between 0 and 1 for the sentence for all labels.

  • length (int) – The sentence text length. This value depends on the value of the string_index_type parameter set in the original request, which is UnicodeCodePoints by default.

  • offset (int) – The sentence text offset from the start of the document. The value depends on the value of the string_index_type parameter set in the original request, which is UnicodeCodePoints by default.

  • mined_opinions (Optional[list[MinedOpinion]]) – The list of opinions mined from this sentence. For example in the sentence “The food is good, but the service is bad”, we would mine the two opinions “food is good” and “service is bad”. Only returned if show_opinion_mining is set to True in the call to analyze_sentiment and api version is v3.1 and up.

New in version v3.1: The offset, length, and mined_opinions properties.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.SentimentConfidenceScores(**kwargs)[source]

The confidence scores (Softmax scores) between 0 and 1. Higher values indicate higher confidence.

Variables
  • positive (float) – Positive score.

  • neutral (float) – Neutral score.

  • negative (float) – Negative score.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.SingleLabelClassifyAction(project_name: str, deployment_name: str, **kwargs)[source]

SingleLabelClassifyAction encapsulates the parameters for starting a long-running custom single label classification operation. For information on regional support of custom features and how to train a model to classify your documents, see https://aka.ms/azsdk/textanalytics/customfunctionalities

Parameters
  • project_name (str) – Required. This field indicates the project name for the model.

  • deployment_name (str) – Required. This field indicates the deployment name for the model.

Keyword Arguments

disable_service_logs (Optional[bool]) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

Variables
  • project_name (str) – This field indicates the project name for the model.

  • deployment_name (str) – This field indicates the deployment name for the model.

  • disable_service_logs (Optional[bool]) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

New in version 2022-05-01: The SingleLabelClassifyAction model.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.SpeedResolution(*, value: float, unit: Union[str, _models.SpeedUnit], **kwargs)[source]
Keyword Arguments
  • value (float) – The numeric value that the extracted text denotes. Required.

  • unit (str or SpeedUnit) – The speed Unit of measurement. Required. Known values are: “Unspecified”, “MeterPerSecond”, “KilometerPerHour”, “KilometerPerMinute”, “KilometerPerSecond”, “MilePerHour”, “Knot”, “FootPerSecond”, “FootPerMinute”, “YardPerMinute”, “YardPerSecond”, “MeterPerMillisecond”, “CentimeterPerMillisecond”, and “KilometerPerMillisecond”.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

get(key, default=None)
has_key(k)
classmethod is_xml_model()
items()
keys()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

update(*args, **kwargs)
values()
class azure.ai.textanalytics.SpeedUnit(value)[source]

The speed Unit of measurement.

CENTIMETER_PER_MILLISECOND = 'CentimeterPerMillisecond'
FOOT_PER_MINUTE = 'FootPerMinute'
FOOT_PER_SECOND = 'FootPerSecond'
KILOMETER_PER_HOUR = 'KilometerPerHour'
KILOMETER_PER_MILLISECOND = 'KilometerPerMillisecond'
KILOMETER_PER_MINUTE = 'KilometerPerMinute'
KILOMETER_PER_SECOND = 'KilometerPerSecond'
KNOT = 'Knot'
METER_PER_MILLISECOND = 'MeterPerMillisecond'
METER_PER_SECOND = 'MeterPerSecond'
MILE_PER_HOUR = 'MilePerHour'
UNSPECIFIED = 'Unspecified'
YARD_PER_MINUTE = 'YardPerMinute'
YARD_PER_SECOND = 'YardPerSecond'
class azure.ai.textanalytics.SummaryContext(**kwargs)[source]

The context of the summary.

Variables
  • offset (int) – Start position for the context. Use of different ‘stringIndexType’ values can affect the offset returned. Required.

  • length (int) – The length of the context. Use of different ‘stringIndexType’ values can affect the length returned. Required.

New in version 2022-10-01-preview: The SummaryContext model.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.SummarySentence(**kwargs)[source]

Represents a single sentence from the extractive text summarization.

Variables
  • text (str) – The extracted sentence text.

  • rank_score (float) – A float value representing the relevance of the sentence within the summary. Higher values indicate higher importance.

  • offset (int) – The sentence offset from the start of the document. The value depends on the value of the string_index_type parameter set in the original request, which is UnicodeCodePoint by default.

  • length (int) – The length of the sentence. This value depends on the value of the string_index_type parameter set in the original request, which is UnicodeCodePoint by default.

New in version 2022-10-01-preview: The SummarySentence model.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.TargetSentiment(**kwargs)[source]

TargetSentiment contains the predicted sentiment, confidence scores and other information about a key component of a product/service. For example in “The food at Hotel Foo is good”, “food” is an key component of “Hotel Foo”.

Variables
  • text (str) – The text value of the target.

  • sentiment (str) – The predicted Sentiment for the target. Possible values include ‘positive’, ‘mixed’, and ‘negative’.

  • confidence_scores (SentimentConfidenceScores) – The sentiment confidence score between 0 and 1 for the target for ‘positive’ and ‘negative’ labels. It’s score for ‘neutral’ will always be 0

  • length (int) – The target text length. This value depends on the value of the string_index_type parameter set in the original request, which is UnicodeCodePoints by default.

  • offset (int) – The target text offset from the start of the document. The value depends on the value of the string_index_type parameter set in the original request, which is UnicodeCodePoints by default.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.TemperatureResolution(*, value: float, unit: Union[str, _models.TemperatureUnit], **kwargs)[source]
Keyword Arguments
  • value (float) – The numeric value that the extracted text denotes. Required.

  • unit (str or TemperatureUnit) – The temperature Unit of measurement. Required. Known values are: “Unspecified”, “Fahrenheit”, “Kelvin”, “Rankine”, and “Celsius”.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

get(key, default=None)
has_key(k)
classmethod is_xml_model()
items()
keys()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

update(*args, **kwargs)
values()
class azure.ai.textanalytics.TemperatureUnit(value)[source]

The temperature Unit of measurement.

CELSIUS = 'Celsius'
FAHRENHEIT = 'Fahrenheit'
KELVIN = 'Kelvin'
RANKINE = 'Rankine'
UNSPECIFIED = 'Unspecified'
class azure.ai.textanalytics.TemporalModifier(value)[source]

An optional modifier of a date/time instance.

AFTER = 'After'
AFTER_APPROX = 'AfterApprox'
AFTER_MID = 'AfterMid'
AFTER_START = 'AfterStart'
APPROX = 'Approx'
BEFORE = 'Before'
BEFORE_APPROX = 'BeforeApprox'
BEFORE_END = 'BeforeEnd'
BEFORE_START = 'BeforeStart'
END = 'End'
LESS = 'Less'
MID = 'Mid'
MORE = 'More'
REFERENCE_UNDEFINED = 'ReferenceUndefined'
SINCE = 'Since'
SINCE_END = 'SinceEnd'
START = 'Start'
UNTIL = 'Until'
class azure.ai.textanalytics.TemporalSpanResolution(*, begin: Optional[str] = None, end: Optional[str] = None, duration: Optional[str] = None, modifier: Optional[Union[str, _models.TemporalModifier]] = None, timex: Optional[str] = None, **kwargs)[source]
Keyword Arguments
as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

get(key, default=None)
has_key(k)
classmethod is_xml_model()
items()
keys()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

update(*args, **kwargs)
values()
class azure.ai.textanalytics.TextAnalysisKind(value)[source]

Enumeration of supported Text Analysis kinds.

New in version 2022-05-01: The TextAnalysisKind enum.

ABSTRACTIVE_SUMMARIZATION = 'AbstractiveSummarization'
CUSTOM_DOCUMENT_CLASSIFICATION = 'CustomDocumentClassification'
CUSTOM_ENTITY_RECOGNITION = 'CustomEntityRecognition'
DYNAMIC_CLASSIFICATION = 'DynamicClassification'
ENTITY_LINKING = 'EntityLinking'
ENTITY_RECOGNITION = 'EntityRecognition'
EXTRACTIVE_SUMMARIZATION = 'ExtractiveSummarization'
HEALTHCARE = 'Healthcare'
KEY_PHRASE_EXTRACTION = 'KeyPhraseExtraction'
LANGUAGE_DETECTION = 'LanguageDetection'
PII_ENTITY_RECOGNITION = 'PiiEntityRecognition'
SENTIMENT_ANALYSIS = 'SentimentAnalysis'
class azure.ai.textanalytics.TextAnalysisLROPoller(*args, **kwargs)[source]

Implements a protocol which returned poller objects are consistent with.

add_done_callback(func: Callable)None[source]

Add callback function to be run once the long running operation has completed - regardless of the status of the operation.

Parameters

func (callable) – Callback function that takes at least one argument, a completed LongRunningOperation.

cancel()None[source]

Cancel the operation currently being polled.

Returns

None

Return type

None

Raises

HttpResponseError – When the operation has already reached a terminal state.

continuation_token()str[source]

Return a continuation token that allows to restart the poller later.

Returns

An opaque continuation token

Return type

str

done()bool[source]

Check status of the long running operation.

Returns

‘True’ if the process has completed, else ‘False’.

Return type

bool

remove_done_callback(func: Callable)None[source]

Remove a callback from the long running operation.

Parameters

func (callable) – The function to be removed from the callbacks.

Raises

ValueError – if the long running operation has already completed.

result(timeout: Optional[int] = None)PollingReturnType_co[source]

Return the result of the long running operation, or the result available after the specified timeout.

Returns

The deserialized resource of the long running operation, if one is available.

Raises

HttpResponseError – Server problem with the query.

status()str[source]

Returns the current status string.

Returns

The current status string

Return type

str

wait(timeout: Optional[float] = None)None[source]

Wait on the long running operation for a specified length of time. You can check if this call as ended with timeout with the “done()” method.

Parameters

timeout (float) – Period of time to wait for the long running operation to complete (in seconds).

Raises

HttpResponseError – Server problem with the query.

property details

Long-running operation metadata.

Returns

A mapping of details about the long-running operation.

Return type

Mapping[str, Any]

class azure.ai.textanalytics.TextAnalyticsApiVersion(value)[source]

Cognitive Service for Language or Text Analytics API versions supported by this package

V2022_05_01 = '2022-05-01'

This version corresponds to the Cognitive Service for Language API.

V2022_10_01_PREVIEW = '2022-10-01-preview'

This is the default version and corresponds to the Cognitive Service for Language API.

V3_0 = 'v3.0'

This version corresponds to Text Analytics API.

V3_1 = 'v3.1'

This version corresponds to Text Analytics API.

class azure.ai.textanalytics.TextAnalyticsClient(endpoint: str, credential: Union[azure.core.credentials.AzureKeyCredential, azure.core.credentials.TokenCredential], **kwargs: Any)[source]

The Language service API is a suite of natural language processing (NLP) skills built with the best-in-class Microsoft machine learning algorithms. The API can be used to analyze unstructured text for tasks such as sentiment analysis, key phrase extraction, entities recognition, and language detection, and more.

Further documentation can be found in https://docs.microsoft.com/azure/cognitive-services/language-service/overview

Parameters
  • endpoint (str) – Supported Cognitive Services or Language resource endpoints (protocol and hostname, for example: ‘https://<resource-name>.cognitiveservices.azure.com’).

  • credential (AzureKeyCredential or TokenCredential) – Credentials needed for the client to connect to Azure. This can be the an instance of AzureKeyCredential if using a Cognitive Services/Language API key or a token credential from azure.identity.

Keyword Arguments
  • default_country_hint (str) – Sets the default country_hint to use for all operations. Defaults to “US”. If you don’t want to use a country hint, pass the string “none”.

  • default_language (str) – Sets the default language to use for all operations. Defaults to “en”.

  • api_version (str or TextAnalyticsApiVersion) – The API version of the service to use for requests. It defaults to the latest service version. Setting to an older version may result in reduced feature compatibility.

Example:

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

text_analytics_client = TextAnalyticsClient(endpoint, AzureKeyCredential(key))
Creating the TextAnalyticsClient with endpoint and token credential from Azure Active Directory.
from azure.ai.textanalytics import TextAnalyticsClient
from azure.identity import DefaultAzureCredential

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

text_analytics_client = TextAnalyticsClient(endpoint, credential=credential)
analyze_sentiment(documents: Union[List[str], List[azure.ai.textanalytics._models.TextDocumentInput], List[Dict[str, str]]], **kwargs: Any)List[Union[azure.ai.textanalytics._models.AnalyzeSentimentResult, azure.ai.textanalytics._models.DocumentError]][source]

Analyze sentiment for a batch of documents. Turn on opinion mining with show_opinion_mining.

Returns a sentiment prediction, as well as sentiment scores for each sentiment class (Positive, Negative, and Neutral) for the document and each sentence within it.

See https://aka.ms/azsdk/textanalytics/data-limits for service data limits.

Parameters

documents (list[str] or list[TextDocumentInput] or list[dict[str, str]]) – The set of documents to process as part of this batch. If you wish to specify the ID and language on a per-item basis you must use as input a list[TextDocumentInput] or a list of dict representations of TextDocumentInput, like {“id”: “1”, “language”: “en”, “text”: “hello world”}.

Keyword Arguments
  • show_opinion_mining (bool) – Whether to mine the opinions of a sentence and conduct more granular analysis around the aspects of a product or service (also known as aspect-based sentiment analysis). If set to true, the returned SentenceSentiment objects will have property mined_opinions containing the result of this analysis. Only available for API version v3.1 and up.

  • language (str) – The 2 letter ISO 639-1 representation of language for the entire batch. For example, use “en” for English; “es” for Spanish etc. If not set, uses “en” for English as default. Per-document language will take precedence over whole batch language. See https://aka.ms/talangs for supported languages in Language API.

  • model_version (str) – This value indicates which model will be used for scoring, e.g. “latest”, “2019-10-01”. If a model-version is not specified, the API will default to the latest, non-preview version. See here for more info: https://aka.ms/text-analytics-model-versioning

  • show_stats (bool) – If set to true, response will contain document level statistics in the statistics field of the document-level response.

  • string_index_type (str) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • disable_service_logs (bool) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

Returns

The combined list of AnalyzeSentimentResult and DocumentError in the order the original documents were passed in.

Return type

list[AnalyzeSentimentResult or DocumentError]

Raises

HttpResponseError or TypeError or ValueError

New in version v3.1: The show_opinion_mining, disable_service_logs, and string_index_type keyword arguments.

Example:

Analyze sentiment in a batch of documents.
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

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

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

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


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

print("Let's visualize the sentiment of each of these documents")
for idx, doc in enumerate(docs):
    print(f"Document text: {documents[idx]}")
    print(f"Overall sentiment: {doc.sentiment}")
begin_analyze_actions(documents: Union[List[str], List[azure.ai.textanalytics._models.TextDocumentInput], List[Dict[str, str]]], actions: List[Union[azure.ai.textanalytics._models.RecognizeEntitiesAction, azure.ai.textanalytics._models.RecognizeLinkedEntitiesAction, azure.ai.textanalytics._models.RecognizePiiEntitiesAction, azure.ai.textanalytics._models.ExtractKeyPhrasesAction, azure.ai.textanalytics._models.AnalyzeSentimentAction, azure.ai.textanalytics._models.RecognizeCustomEntitiesAction, azure.ai.textanalytics._models.SingleLabelClassifyAction, azure.ai.textanalytics._models.MultiLabelClassifyAction, azure.ai.textanalytics._models.AnalyzeHealthcareEntitiesAction, azure.ai.textanalytics._models.ExtractSummaryAction, azure.ai.textanalytics._models.AbstractSummaryAction]], **kwargs: Any)azure.ai.textanalytics._lro.TextAnalysisLROPoller[azure.core.paging.ItemPaged[List[Union[azure.ai.textanalytics._models.RecognizeEntitiesResult, azure.ai.textanalytics._models.RecognizeLinkedEntitiesResult, azure.ai.textanalytics._models.RecognizePiiEntitiesResult, azure.ai.textanalytics._models.ExtractKeyPhrasesResult, azure.ai.textanalytics._models.AnalyzeSentimentResult, azure.ai.textanalytics._models.RecognizeCustomEntitiesResult, azure.ai.textanalytics._models.ClassifyDocumentResult, azure.ai.textanalytics._models.AnalyzeHealthcareEntitiesResult, azure.ai.textanalytics._models.ExtractSummaryResult, azure.ai.textanalytics._models.AbstractSummaryResult, azure.ai.textanalytics._models.DocumentError]]]][source]

Start a long-running operation to perform a variety of text analysis actions over a batch of documents.

We recommend you use this function if you’re looking to analyze larger documents, and / or combine multiple text analysis actions into one call. Otherwise, we recommend you use the action specific endpoints, for example analyze_sentiment().

Note

The abstractive summarization feature is part of a gated preview. Request access here: https://aka.ms/applyforgatedsummarizationfeatures

Note

See the service documentation for regional support of custom action features: https://aka.ms/azsdk/textanalytics/customfunctionalities

Parameters
Keyword Arguments
  • display_name (str) – An optional display name to set for the requested analysis.

  • language (str) – The 2 letter ISO 639-1 representation of language for the entire batch. For example, use “en” for English; “es” for Spanish etc. For automatic language detection, use “auto” (Only supported by API version 2022-10-01-preview and newer). If not set, uses “en” for English as default. Per-document language will take precedence over whole batch language. See https://aka.ms/talangs for supported languages in Language API.

  • autodetect_default_language (str) – Default/fallback language to use for documents requesting automatic language detection.

  • show_stats (bool) – If set to true, response will contain document level statistics.

  • polling_interval (int) – Waiting time between two polls for LRO operations if no Retry-After header is present. Defaults to 5 seconds.

  • continuation_token (str) – Call continuation_token() on the poller object to save the long-running operation (LRO) state into an opaque token. Pass the value as the continuation_token keyword argument to restart the LRO from a saved state.

Returns

An instance of an TextAnalysisLROPoller. Call result() on the poller object to return a pageable heterogeneous list of lists. This list of lists is first ordered by the documents you input, then ordered by the actions you input. For example, if you have documents input [“Hello”, “world”], and actions RecognizeEntitiesAction and AnalyzeSentimentAction, when iterating over the list of lists, you will first iterate over the action results for the “Hello” document, getting the RecognizeEntitiesResult of “Hello”, then the AnalyzeSentimentResult of “Hello”. Then, you will get the RecognizeEntitiesResult and AnalyzeSentimentResult of “world”.

Return type

TextAnalysisLROPoller[ItemPaged[ list[RecognizeEntitiesResult or RecognizeLinkedEntitiesResult or RecognizePiiEntitiesResult or ExtractKeyPhrasesResult or AnalyzeSentimentResult or RecognizeCustomEntitiesResult or ClassifyDocumentResult or AnalyzeHealthcareEntitiesResult or ExtractSummaryResult or AbstractSummaryResult or DocumentError]]]

Raises

HttpResponseError or TypeError or ValueError

New in version v3.1: The begin_analyze_actions client method.

New in version 2022-05-01: The RecognizeCustomEntitiesAction, SingleLabelClassifyAction, MultiLabelClassifyAction, and AnalyzeHealthcareEntitiesAction input options and the corresponding RecognizeCustomEntitiesResult, ClassifyDocumentResult, and AnalyzeHealthcareEntitiesResult result objects

New in version 2022-10-01-preview: The ExtractSummaryAction and AbstractSummaryAction input options and the corresponding ExtractSummaryResult and AbstractSummaryResult result objects. The autodetect_default_language keyword argument.

Example:

Start a long-running operation to perform a variety of text analysis actions over a batch of documents.
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import (
    TextAnalyticsClient,
    RecognizeEntitiesAction,
    RecognizeLinkedEntitiesAction,
    RecognizePiiEntitiesAction,
    ExtractKeyPhrasesAction,
    AnalyzeSentimentAction,
)

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

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

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

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

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

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

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

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

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

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

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

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

begin_analyze_healthcare_entities(documents: Union[List[str], List[azure.ai.textanalytics._models.TextDocumentInput], List[Dict[str, str]]], **kwargs: Any)azure.ai.textanalytics._lro.AnalyzeHealthcareEntitiesLROPoller[azure.core.paging.ItemPaged[Union[azure.ai.textanalytics._models.AnalyzeHealthcareEntitiesResult, azure.ai.textanalytics._models.DocumentError]]][source]

Analyze healthcare entities and identify relationships between these entities in a batch of documents.

Entities are associated with references that can be found in existing knowledge bases, such as UMLS, CHV, MSH, etc.

We also extract the relations found between entities, for example in “The subject took 100 mg of ibuprofen”, we would extract the relationship between the “100 mg” dosage and the “ibuprofen” medication.

Parameters

documents (list[str] or list[TextDocumentInput] or list[dict[str, str]]) – The set of documents to process as part of this batch. If you wish to specify the ID and language on a per-item basis you must use as input a list[TextDocumentInput] or a list of dict representations of TextDocumentInput, like {“id”: “1”, “language”: “en”, “text”: “hello world”}.

Keyword Arguments
  • model_version (str) – This value indicates which model will be used for scoring, e.g. “latest”, “2019-10-01”. If a model-version is not specified, the API will default to the latest, non-preview version. See here for more info: https://aka.ms/text-analytics-model-versioning

  • show_stats (bool) – If set to true, response will contain document level statistics.

  • language (str) – The 2 letter ISO 639-1 representation of language for the entire batch. For example, use “en” for English; “es” for Spanish etc. For automatic language detection, use “auto” (Only supported by API version 2022-10-01-preview and newer). If not set, uses “en” for English as default. Per-document language will take precedence over whole batch language. See https://aka.ms/talangs for supported languages in Language API.

  • autodetect_default_language (str) – Default/fallback language to use for documents requesting automatic language detection.

  • display_name (str) – An optional display name to set for the requested analysis.

  • string_index_type (str) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • polling_interval (int) – Waiting time between two polls for LRO operations if no Retry-After header is present. Defaults to 5 seconds.

  • continuation_token (str) – Call continuation_token() on the poller object to save the long-running operation (LRO) state into an opaque token. Pass the value as the continuation_token keyword argument to restart the LRO from a saved state.

  • disable_service_logs (bool) – Defaults to true, meaning that the Language service will not log your input text on the service side for troubleshooting. If set to False, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

  • fhir_version (str) – The FHIR Spec version that the result will use to format the fhir_bundle on the result object. For additional information see https://www.hl7.org/fhir/overview.html. The only acceptable values to pass in are None and “4.0.1”. The default value is None.

  • document_type (str or HealthcareDocumentType) – Document type that can be provided as input for Fhir Documents. Expect to have fhir_version provided when used. Behavior of using None enum is the same as not using the document_type parameter. Known values are: “None”, “ClinicalTrial”, “DischargeSummary”, “ProgressNote”, “HistoryAndPhysical”, “Consult”, “Imaging”, “Pathology”, and “ProcedureNote”.

Returns

An instance of an AnalyzeHealthcareEntitiesLROPoller. Call result() on the this object to return a heterogeneous pageable of AnalyzeHealthcareEntitiesResult and DocumentError.

Return type

AnalyzeHealthcareEntitiesLROPoller[ItemPaged[ AnalyzeHealthcareEntitiesResult or DocumentError]]

Raises

HttpResponseError or TypeError or ValueError

New in version v3.1: The begin_analyze_healthcare_entities client method.

New in version 2022-05-01: The display_name keyword argument.

New in version 2022-10-01-preview: The fhir_version, document_type, and autodetect_default_language keyword arguments.

Example:

Recognize healthcare entities in a batch of documents.
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient, HealthcareEntityRelation

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

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

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

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

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

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

print("Now, let's get all of medication dosage relations from the documents")
dosage_of_medication_relations = [
    entity_relation
    for doc in docs
    for entity_relation in doc.entity_relations if entity_relation.relation_type == HealthcareEntityRelation.DOSAGE_OF_MEDICATION
]
begin_multi_label_classify(documents: Union[List[str], List[azure.ai.textanalytics._models.TextDocumentInput], List[Dict[str, str]]], project_name: str, deployment_name: str, **kwargs: Any)azure.ai.textanalytics._lro.TextAnalysisLROPoller[azure.core.paging.ItemPaged[Union[azure.ai.textanalytics._models.ClassifyDocumentResult, azure.ai.textanalytics._models.DocumentError]]][source]

Start a long-running custom multi label classification operation.

For information on regional support of custom features and how to train a model to classify your documents, see https://aka.ms/azsdk/textanalytics/customfunctionalities

Parameters
  • documents (list[str] or list[TextDocumentInput] or list[dict[str, str]]) – The set of documents to process as part of this batch. If you wish to specify the ID and language on a per-item basis you must use as input a list[TextDocumentInput] or a list of dict representations of TextDocumentInput, like {“id”: “1”, “language”: “en”, “text”: “hello world”}.

  • project_name (str) – Required. This field indicates the project name for the model.

  • deployment_name (str) – This field indicates the deployment name for the model.

Keyword Arguments
  • language (str) – The 2 letter ISO 639-1 representation of language for the entire batch. For example, use “en” for English; “es” for Spanish etc. For automatic language detection, use “auto” (Only supported by API version 2022-10-01-preview and newer). If not set, uses “en” for English as default. Per-document language will take precedence over whole batch language. See https://aka.ms/talangs for supported languages in Language API.

  • autodetect_default_language (str) – Default/fallback language to use for documents requesting automatic language detection.

  • show_stats (bool) – If set to true, response will contain document level statistics.

  • disable_service_logs (bool) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

  • polling_interval (int) – Waiting time between two polls for LRO operations if no Retry-After header is present. Defaults to 5 seconds.

  • continuation_token (str) – Call continuation_token() on the poller object to save the long-running operation (LRO) state into an opaque token. Pass the value as the continuation_token keyword argument to restart the LRO from a saved state.

  • display_name (str) – An optional display name to set for the requested analysis.

Returns

An instance of an TextAnalysisLROPoller. Call result() on the this object to return a heterogeneous pageable of ClassifyDocumentResult and DocumentError.

Return type

TextAnalysisLROPoller[ItemPaged[ ClassifyDocumentResult or DocumentError]]

Raises

HttpResponseError

New in version 2022-05-01: The begin_multi_label_classify client method.

New in version 2022-10-01-preview: The autodetect_default_language keyword argument.

Example:

Perform multi label classification on a batch of documents.
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]
project_name = os.environ["MULTI_LABEL_CLASSIFY_PROJECT_NAME"]
deployment_name = os.environ["MULTI_LABEL_CLASSIFY_DEPLOYMENT_NAME"]
path_to_sample_document = os.path.abspath(
    os.path.join(
        os.path.abspath(__file__),
        "..",
        "./text_samples/custom_classify_sample.txt",
    )
)

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

with open(path_to_sample_document) as fd:
    document = [fd.read()]

poller = text_analytics_client.begin_multi_label_classify(
    document,
    project_name=project_name,
    deployment_name=deployment_name
)

document_results = poller.result()
for doc, classification_result in zip(document, document_results):
    if classification_result.kind == "CustomDocumentClassification":
        classifications = classification_result.classifications
        print(f"\nThe movie plot '{doc}' was classified as the following genres:\n")
        for classification in classifications:
            print("'{}' with confidence score {}.".format(
                classification.category, classification.confidence_score
            ))
    elif classification_result.is_error is True:
        print("Movie plot '{}' has an error with code '{}' and message '{}'".format(
            doc, classification_result.code, classification_result.message
        ))
begin_recognize_custom_entities(documents: Union[List[str], List[azure.ai.textanalytics._models.TextDocumentInput], List[Dict[str, str]]], project_name: str, deployment_name: str, **kwargs: Any)azure.ai.textanalytics._lro.TextAnalysisLROPoller[azure.core.paging.ItemPaged[Union[azure.ai.textanalytics._models.RecognizeCustomEntitiesResult, azure.ai.textanalytics._models.DocumentError]]][source]

Start a long-running custom named entity recognition operation.

For information on regional support of custom features and how to train a model to recognize custom entities, see https://aka.ms/azsdk/textanalytics/customentityrecognition

Parameters
  • documents (list[str] or list[TextDocumentInput] or list[dict[str, str]]) – The set of documents to process as part of this batch. If you wish to specify the ID and language on a per-item basis you must use as input a list[TextDocumentInput] or a list of dict representations of TextDocumentInput, like {“id”: “1”, “language”: “en”, “text”: “hello world”}.

  • project_name (str) – Required. This field indicates the project name for the model.

  • deployment_name (str) – This field indicates the deployment name for the model.

Keyword Arguments
  • language (str) – The 2 letter ISO 639-1 representation of language for the entire batch. For example, use “en” for English; “es” for Spanish etc. For automatic language detection, use “auto” (Only supported by API version 2022-10-01-preview and newer). If not set, uses “en” for English as default. Per-document language will take precedence over whole batch language. See https://aka.ms/talangs for supported languages in Language API.

  • autodetect_default_language (str) – Default/fallback language to use for documents requesting automatic language detection.

  • show_stats (bool) – If set to true, response will contain document level statistics.

  • disable_service_logs (bool) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

  • string_index_type (str) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • polling_interval (int) – Waiting time between two polls for LRO operations if no Retry-After header is present. Defaults to 5 seconds.

  • continuation_token (str) – Call continuation_token() on the poller object to save the long-running operation (LRO) state into an opaque token. Pass the value as the continuation_token keyword argument to restart the LRO from a saved state.

  • display_name (str) – An optional display name to set for the requested analysis.

Returns

An instance of an TextAnalysisLROPoller. Call result() on the this object to return a heterogeneous pageable of RecognizeCustomEntitiesResult and DocumentError.

Return type

TextAnalysisLROPoller[ItemPaged[ RecognizeCustomEntitiesResult or DocumentError]]

Raises

HttpResponseError

New in version 2022-05-01: The begin_recognize_custom_entities client method.

New in version 2022-10-01-preview: The autodetect_default_language keyword argument.

Example:

Recognize custom entities in a batch of documents.
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]
project_name = os.environ["CUSTOM_ENTITIES_PROJECT_NAME"]
deployment_name = os.environ["CUSTOM_ENTITIES_DEPLOYMENT_NAME"]
path_to_sample_document = os.path.abspath(
    os.path.join(
        os.path.abspath(__file__),
        "..",
        "./text_samples/custom_entities_sample.txt",
    )
)

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

with open(path_to_sample_document) as fd:
    document = [fd.read()]

poller = text_analytics_client.begin_recognize_custom_entities(
    document,
    project_name=project_name,
    deployment_name=deployment_name
)

document_results = poller.result()
for custom_entities_result in document_results:
    if custom_entities_result.kind == "CustomEntityRecognition":
        for entity in custom_entities_result.entities:
            print(
                "Entity '{}' has category '{}' with confidence score of '{}'".format(
                    entity.text, entity.category, entity.confidence_score
                )
            )
    elif custom_entities_result.is_error is True:
        print("...Is an error with code '{}' and message '{}'".format(
            custom_entities_result.code, custom_entities_result.message
            )
        )
begin_single_label_classify(documents: Union[List[str], List[azure.ai.textanalytics._models.TextDocumentInput], List[Dict[str, str]]], project_name: str, deployment_name: str, **kwargs: Any)azure.ai.textanalytics._lro.TextAnalysisLROPoller[azure.core.paging.ItemPaged[Union[azure.ai.textanalytics._models.ClassifyDocumentResult, azure.ai.textanalytics._models.DocumentError]]][source]

Start a long-running custom single label classification operation.

For information on regional support of custom features and how to train a model to classify your documents, see https://aka.ms/azsdk/textanalytics/customfunctionalities

Parameters
  • documents (list[str] or list[TextDocumentInput] or list[dict[str, str]]) – The set of documents to process as part of this batch. If you wish to specify the ID and language on a per-item basis you must use as input a list[TextDocumentInput] or a list of dict representations of TextDocumentInput, like {“id”: “1”, “language”: “en”, “text”: “hello world”}.

  • project_name (str) – Required. This field indicates the project name for the model.

  • deployment_name (str) – This field indicates the deployment name for the model.

Keyword Arguments
  • language (str) – The 2 letter ISO 639-1 representation of language for the entire batch. For example, use “en” for English; “es” for Spanish etc. For automatic language detection, use “auto” (Only supported by API version 2022-10-01-preview and newer). If not set, uses “en” for English as default. Per-document language will take precedence over whole batch language. See https://aka.ms/talangs for supported languages in Language API.

  • autodetect_default_language (str) – Default/fallback language to use for documents requesting automatic language detection.

  • show_stats (bool) – If set to true, response will contain document level statistics.

  • disable_service_logs (bool) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

  • polling_interval (int) – Waiting time between two polls for LRO operations if no Retry-After header is present. Defaults to 5 seconds.

  • continuation_token (str) – Call continuation_token() on the poller object to save the long-running operation (LRO) state into an opaque token. Pass the value as the continuation_token keyword argument to restart the LRO from a saved state.

  • display_name (str) – An optional display name to set for the requested analysis.

Returns

An instance of an TextAnalysisLROPoller. Call result() on the this object to return a heterogeneous pageable of ClassifyDocumentResult and DocumentError.

Return type

TextAnalysisLROPoller[ItemPaged[ ClassifyDocumentResult or DocumentError]]

Raises

HttpResponseError

New in version 2022-05-01: The begin_single_label_classify client method.

New in version 2022-10-01-preview: The autodetect_default_language keyword argument.

Example:

Perform single label classification on a batch of documents.
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

endpoint = os.environ["AZURE_LANGUAGE_ENDPOINT"]
key = os.environ["AZURE_LANGUAGE_KEY"]
project_name = os.environ["SINGLE_LABEL_CLASSIFY_PROJECT_NAME"]
deployment_name = os.environ["SINGLE_LABEL_CLASSIFY_DEPLOYMENT_NAME"]
path_to_sample_document = os.path.abspath(
    os.path.join(
        os.path.abspath(__file__),
        "..",
        "./text_samples/custom_classify_sample.txt",
    )
)

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

with open(path_to_sample_document) as fd:
    document = [fd.read()]

poller = text_analytics_client.begin_single_label_classify(
    document,
    project_name=project_name,
    deployment_name=deployment_name
)

document_results = poller.result()
for doc, classification_result in zip(document, document_results):
    if classification_result.kind == "CustomDocumentClassification":
        classification = classification_result.classifications[0]
        print("The document text '{}' was classified as '{}' with confidence score {}.".format(
            doc, classification.category, classification.confidence_score)
        )
    elif classification_result.is_error is True:
        print("Document text '{}' has an error with code '{}' and message '{}'".format(
            doc, classification_result.code, classification_result.message
        ))
close()None

Close sockets opened by the client. Calling this method is unnecessary when using the client as a context manager.

detect_language(documents: Union[List[str], List[azure.ai.textanalytics._models.DetectLanguageInput], List[Dict[str, str]]], **kwargs: Any)List[Union[azure.ai.textanalytics._models.DetectLanguageResult, azure.ai.textanalytics._models.DocumentError]][source]

Detect language for a batch of documents.

Returns the detected language and a numeric score between zero and one. Scores close to one indicate 100% certainty that the identified language is true. See https://aka.ms/talangs for the list of enabled languages.

See https://aka.ms/azsdk/textanalytics/data-limits for service data limits.

Parameters

documents (list[str] or list[DetectLanguageInput] or list[dict[str, str]]) – The set of documents to process as part of this batch. If you wish to specify the ID and country_hint on a per-item basis you must use as input a list[DetectLanguageInput] or a list of dict representations of DetectLanguageInput, like {“id”: “1”, “country_hint”: “us”, “text”: “hello world”}.

Keyword Arguments
  • country_hint (str) – Country of origin hint for the entire batch. Accepts two letter country codes specified by ISO 3166-1 alpha-2. Per-document country hints will take precedence over whole batch hints. Defaults to “US”. If you don’t want to use a country hint, pass the string “none”.

  • model_version (str) – Version of the model used on the service side for scoring, e.g. “latest”, “2019-10-01”. If a model version is not specified, the API will default to the latest, non-preview version. See here for more info: https://aka.ms/text-analytics-model-versioning

  • show_stats (bool) – If set to true, response will contain document level statistics in the statistics field of the document-level response.

  • disable_service_logs (bool) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

Returns

The combined list of DetectLanguageResult and DocumentError in the order the original documents were passed in.

Return type

list[DetectLanguageResult or DocumentError]

Raises

HttpResponseError or TypeError or ValueError

New in version v3.1: The disable_service_logs keyword argument.

Example:

Detecting language in a batch of documents.
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

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

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

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

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

for idx, doc in enumerate(reviewed_docs):
    print("Review #{} is in '{}', which has ISO639-1 name '{}'\n".format(
        idx, doc.primary_language.name, doc.primary_language.iso6391_name
    ))
dynamic_classification(documents: Union[List[str], List[azure.ai.textanalytics._models.TextDocumentInput], List[Dict[str, str]]], categories: List[str], **kwargs: Any)List[Union[azure.ai.textanalytics._models.DynamicClassificationResult, azure.ai.textanalytics._models.DocumentError]][source]

Perform dynamic classification on a batch of documents.

On the fly classification of the input documents into one or multiple categories. Assigns either one or multiple categories per document. This type of classification doesn’t require model training.

Note

The dynamic classification feature is part of a gated preview. Request access here: https://aka.ms/applyforgatedlanguagefeature

See https://aka.ms/azsdk/textanalytics/data-limits for service data limits.

Parameters
  • documents (list[str] or list[TextDocumentInput] or list[dict[str, str]]) – The set of documents to process as part of this batch. If you wish to specify the ID and language on a per-item basis you must use as input a list[TextDocumentInput] or a list of dict representations of TextDocumentInput, like {“id”: “1”, “language”: “en”, “text”: “hello world”}.

  • categories (list[str]) – A list of categories to which input is classified to.

Keyword Arguments
  • classification_type (str or ClassificationType) – Specifies either one or multiple categories per document. Defaults to multi classification which may return more than one class for each document. Known values are: “Single” and “Multi”.

  • language (str) – The 2 letter ISO 639-1 representation of language for the entire batch. For example, use “en” for English; “es” for Spanish etc. If not set, uses “en” for English as default. Per-document language will take precedence over whole batch language. See https://aka.ms/talangs for supported languages in Language API.

  • model_version (str) – This value indicates which model will be used for scoring, e.g. “latest”, “2019-10-01”. If a model-version is not specified, the API will default to the latest, non-preview version. See here for more info: https://aka.ms/text-analytics-model-versioning

  • show_stats (bool) – If set to true, response will contain document level statistics in the statistics field of the document-level response.

  • disable_service_logs (bool) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

Returns

The combined list of DynamicClassificationResult and DocumentError in the order the original documents were passed in.

Return type

list[DynamicClassificationResult or DocumentError]

Raises

HttpResponseError

New in version 2022-10-01-preview: The dynamic_classification client method.

Example:

Perform dynamic classification on a batch of documents.
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

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

text_analytics_client = TextAnalyticsClient(
    endpoint=endpoint,
    credential=AzureKeyCredential(key),
)
documents = [
    "The WHO is issuing a warning about Monkey Pox.",
    "Mo Salah plays in Liverpool FC in England.",
]
result = text_analytics_client.dynamic_classification(
    documents,
    categories=["Health", "Politics", "Music", "Sports"],
    classification_type="Multi"
)

for doc, classification_result in zip(documents, result):
    if classification_result.kind == "DynamicClassification":
        classifications = classification_result.classifications
        print(f"\n'{doc}' classifications:\n")
        for classification in classifications:
            print("Category '{}' with confidence score {}.".format(
                classification.category, classification.confidence_score
            ))
    elif classification_result.is_error is True:
        print("Document '{}' has an error with code '{}' and message '{}'".format(
            doc, classification_result.code, classification_result.message
        ))
extract_key_phrases(documents: Union[List[str], List[azure.ai.textanalytics._models.TextDocumentInput], List[Dict[str, str]]], **kwargs: Any)List[Union[azure.ai.textanalytics._models.ExtractKeyPhrasesResult, azure.ai.textanalytics._models.DocumentError]][source]

Extract key phrases from a batch of documents.

Returns a list of strings denoting the key phrases in the input text. For example, for the input text “The food was delicious and there were wonderful staff”, the API returns the main talking points: “food” and “wonderful staff”

See https://aka.ms/azsdk/textanalytics/data-limits for service data limits.

Parameters

documents (list[str] or list[TextDocumentInput] or list[dict[str, str]]) – The set of documents to process as part of this batch. If you wish to specify the ID and language on a per-item basis you must use as input a list[TextDocumentInput] or a list of dict representations of TextDocumentInput, like {“id”: “1”, “language”: “en”, “text”: “hello world”}.

Keyword Arguments
  • language (str) – The 2 letter ISO 639-1 representation of language for the entire batch. For example, use “en” for English; “es” for Spanish etc. If not set, uses “en” for English as default. Per-document language will take precedence over whole batch language. See https://aka.ms/talangs for supported languages in Language API.

  • model_version (str) – This value indicates which model will be used for scoring, e.g. “latest”, “2019-10-01”. If a model-version is not specified, the API will default to the latest, non-preview version. See here for more info: https://aka.ms/text-analytics-model-versioning

  • show_stats (bool) – If set to true, response will contain document level statistics in the statistics field of the document-level response.

  • disable_service_logs (bool) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

Returns

The combined list of ExtractKeyPhrasesResult and DocumentError in the order the original documents were passed in.

Return type

list[ExtractKeyPhrasesResult or DocumentError]

Raises

HttpResponseError or TypeError or ValueError

New in version v3.1: The disable_service_logs keyword argument.

Example:

Extract the key phrases in a batch of documents.
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

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

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

result = text_analytics_client.extract_key_phrases(articles)
for idx, doc in enumerate(result):
    if not doc.is_error:
        print("Key phrases in article #{}: {}".format(
            idx + 1,
            ", ".join(doc.key_phrases)
        ))
recognize_entities(documents: Union[List[str], List[azure.ai.textanalytics._models.TextDocumentInput], List[Dict[str, str]]], **kwargs: Any)List[Union[azure.ai.textanalytics._models.RecognizeEntitiesResult, azure.ai.textanalytics._models.DocumentError]][source]

Recognize entities for a batch of documents.

Identifies and categorizes entities in your text as people, places, organizations, date/time, quantities, percentages, currencies, and more. For the list of supported entity types, check: https://aka.ms/taner

See https://aka.ms/azsdk/textanalytics/data-limits for service data limits.

Parameters

documents (list[str] or list[TextDocumentInput] or list[dict[str, str]]) – The set of documents to process as part of this batch. If you wish to specify the ID and language on a per-item basis you must use as input a list[TextDocumentInput] or a list of dict representations of TextDocumentInput, like {“id”: “1”, “language”: “en”, “text”: “hello world”}.

Keyword Arguments
  • language (str) – The 2 letter ISO 639-1 representation of language for the entire batch. For example, use “en” for English; “es” for Spanish etc. If not set, uses “en” for English as default. Per-document language will take precedence over whole batch language. See https://aka.ms/talangs for supported languages in Language API.

  • model_version (str) – This value indicates which model will be used for scoring, e.g. “latest”, “2019-10-01”. If a model-version is not specified, the API will default to the latest, non-preview version. See here for more info: https://aka.ms/text-analytics-model-versioning

  • show_stats (bool) – If set to true, response will contain document level statistics in the statistics field of the document-level response.

  • string_index_type (str) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • disable_service_logs (bool) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

Returns

The combined list of RecognizeEntitiesResult and DocumentError in the order the original documents were passed in.

Return type

list[RecognizeEntitiesResult or DocumentError]

Raises

HttpResponseError or TypeError or ValueError

New in version v3.1: The disable_service_logs and string_index_type keyword arguments.

Example:

Recognize entities in a batch of documents.
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

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

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

result = text_analytics_client.recognize_entities(reviews)
result = [review for review in result if not review.is_error]

for idx, review in enumerate(result):
    for entity in review.entities:
        print(f"Entity '{entity.text}' has category '{entity.category}'")
recognize_linked_entities(documents: Union[List[str], List[azure.ai.textanalytics._models.TextDocumentInput], List[Dict[str, str]]], **kwargs: Any)List[Union[azure.ai.textanalytics._models.RecognizeLinkedEntitiesResult, azure.ai.textanalytics._models.DocumentError]][source]

Recognize linked entities from a well-known knowledge base for a batch of documents.

Identifies and disambiguates the identity of each entity found in 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.

See https://aka.ms/azsdk/textanalytics/data-limits for service data limits.

Parameters

documents (list[str] or list[TextDocumentInput] or list[dict[str, str]]) – The set of documents to process as part of this batch. If you wish to specify the ID and language on a per-item basis you must use as input a list[TextDocumentInput] or a list of dict representations of TextDocumentInput, like {“id”: “1”, “language”: “en”, “text”: “hello world”}.

Keyword Arguments
  • language (str) – The 2 letter ISO 639-1 representation of language for the entire batch. For example, use “en” for English; “es” for Spanish etc. If not set, uses “en” for English as default. Per-document language will take precedence over whole batch language. See https://aka.ms/talangs for supported languages in Language API.

  • model_version (str) – This value indicates which model will be used for scoring, e.g. “latest”, “2019-10-01”. If a model-version is not specified, the API will default to the latest, non-preview version. See here for more info: https://aka.ms/text-analytics-model-versioning

  • show_stats (bool) – If set to true, response will contain document level statistics in the statistics field of the document-level response.

  • string_index_type (str) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • disable_service_logs (bool) – If set to true, you opt-out of having your text input logged on the service side for troubleshooting. By default, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Setting this parameter to true, disables input logging and may limit our ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

Returns

The combined list of RecognizeLinkedEntitiesResult and DocumentError in the order the original documents were passed in.

Return type

list[RecognizeLinkedEntitiesResult or DocumentError]

Raises

HttpResponseError or TypeError or ValueError

New in version v3.1: The disable_service_logs and string_index_type keyword arguments.

Example:

Recognize linked entities in a batch of documents.
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

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

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

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

print(
    "Let's map each entity to it's Wikipedia article. I also want to see how many times each "
    "entity is mentioned in a document\n\n"
)
entity_to_url = {}
for doc in docs:
    for entity in doc.entities:
        print("Entity '{}' has been mentioned '{}' time(s)".format(
            entity.name, len(entity.matches)
        ))
        if entity.data_source == "Wikipedia":
            entity_to_url[entity.name] = entity.url
recognize_pii_entities(documents: Union[List[str], List[azure.ai.textanalytics._models.TextDocumentInput], List[Dict[str, str]]], **kwargs: Any)List[Union[azure.ai.textanalytics._models.RecognizePiiEntitiesResult, azure.ai.textanalytics._models.DocumentError]][source]

Recognize entities containing personal information for a batch of documents.

Returns a list of personal information entities (“SSN”, “Bank Account”, etc) in the document. For the list of supported entity types, check https://aka.ms/tanerpii

See https://aka.ms/azsdk/textanalytics/data-limits for service data limits.

Parameters

documents (list[str] or list[TextDocumentInput] or list[dict[str, str]]) – The set of documents to process as part of this batch. If you wish to specify the ID and language on a per-item basis you must use as input a list[TextDocumentInput] or a list of dict representations of TextDocumentInput, like {“id”: “1”, “language”: “en”, “text”: “hello world”}.

Keyword Arguments
  • language (str) – The 2 letter ISO 639-1 representation of language for the entire batch. For example, use “en” for English; “es” for Spanish etc. If not set, uses “en” for English as default. Per-document language will take precedence over whole batch language. See https://aka.ms/talangs for supported languages in Language API.

  • model_version (str) – This value indicates which model will be used for scoring, e.g. “latest”, “2019-10-01”. If a model-version is not specified, the API will default to the latest, non-preview version. See here for more info: https://aka.ms/text-analytics-model-versioning

  • show_stats (bool) – If set to true, response will contain document level statistics in the statistics field of the document-level response.

  • domain_filter (str or PiiEntityDomain) – Filters the response entities to ones only included in the specified domain. I.e., if set to ‘phi’, will only return entities in the Protected Healthcare Information domain. See https://aka.ms/tanerpii for more information.

  • categories_filter (list[str or PiiEntityCategory]) – Instead of filtering over all PII entity categories, you can pass in a list of the specific PII entity categories you want to filter out. For example, if you only want to filter out U.S. social security numbers in a document, you can pass in [PiiEntityCategory.US_SOCIAL_SECURITY_NUMBER] for this kwarg.

  • string_index_type (str) – Specifies the method used to interpret string offsets. UnicodeCodePoint, the Python encoding, is the default. To override the Python default, you can also pass in Utf16CodeUnit or TextElement_v8. For additional information see https://aka.ms/text-analytics-offsets

  • disable_service_logs (bool) – Defaults to true, meaning that the Language service will not log your input text on the service side for troubleshooting. If set to False, the Language service logs your input text for 48 hours, solely to allow for troubleshooting issues in providing you with the service’s natural language processing functions. Please see Cognitive Services Compliance and Privacy notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai.

Returns

The combined list of RecognizePiiEntitiesResult and DocumentError in the order the original documents were passed in.

Return type

list[RecognizePiiEntitiesResult or DocumentError]

Raises

HttpResponseError or TypeError or ValueError

New in version v3.1: The recognize_pii_entities client method.

Example:

Recognize personally identifiable information entities in a batch of documents.
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

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

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

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

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

class azure.ai.textanalytics.TextAnalyticsError(**kwargs)[source]

TextAnalyticsError contains the error code, message, and other details that explain why the batch or individual document failed to be processed by the service.

Variables
  • code (str) – Error code. Possible values include: ‘invalidRequest’, ‘invalidArgument’, ‘internalServerError’, ‘serviceUnavailable’, ‘invalidParameterValue’, ‘invalidRequestBodyFormat’, ‘emptyRequest’, ‘missingInputRecords’, ‘invalidDocument’, ‘modelVersionIncorrect’, ‘invalidDocumentBatch’, ‘unsupportedLanguageCode’, ‘invalidCountryHint’

  • message (str) – Error message.

  • target (Optional[str]) – Error target.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.TextAnalyticsWarning(**kwargs)[source]

TextAnalyticsWarning contains the warning code and message that explains why the response has a warning.

Variables
  • code (str) – Warning code. Possible values include: ‘LongWordsInDocument’, ‘DocumentTruncated’.

  • message (str) – Warning message.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.TextDocumentBatchStatistics(**kwargs)[source]

TextDocumentBatchStatistics contains information about the request payload. Note: This object is not returned in the response and needs to be retrieved by a response hook.

Variables
  • document_count (int) – Number of documents submitted in the request.

  • valid_document_count (int) – Number of valid documents. This excludes empty, over-size limit or non-supported languages documents.

  • erroneous_document_count (int) – Number of invalid documents. This includes empty, over-size limit or non-supported languages documents.

  • transaction_count (int) – Number of transactions for the request.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.TextDocumentInput(**kwargs)[source]

The input document to be analyzed by the service.

Keyword Arguments
  • id (str) – Required. Unique, non-empty document identifier.

  • text (str) – Required. The input text to process.

  • language (str) – This is the 2 letter ISO 639-1 representation of a language. For example, use “en” for English; “es” for Spanish etc. For automatic language detection, use “auto” (Only supported by long-running operation APIs with API version 2022-10-01-preview or newer). If not set, uses “en” for English as default.

Variables
  • id (str) – Required. Unique, non-empty document identifier.

  • text (str) – Required. The input text to process.

  • language (Optional[str]) – This is the 2 letter ISO 639-1 representation of a language. For example, use “en” for English; “es” for Spanish etc. For automatic language detection, use “auto” (Only supported by long-running operation APIs with API version 2022-10-01-preview or newer). If not set, uses “en” for English as default.

New in version 2022-10-01-preview: The ‘auto’ option for language.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

get(key, default=None)
has_key(k)
classmethod is_xml_model()
items()
keys()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

update(*args, **kwargs)
values()
class azure.ai.textanalytics.TextDocumentStatistics(**kwargs)[source]

TextDocumentStatistics contains information about the document payload.

Variables
  • character_count (int) – Number of text elements recognized in the document.

  • transaction_count (int) – Number of transactions for the document.

get(key, default=None)
has_key(k)
items()
keys()
update(*args, **kwargs)
values()
class azure.ai.textanalytics.VolumeResolution(*, value: float, unit: Union[str, _models.VolumeUnit], **kwargs)[source]
Keyword Arguments
  • value (float) – The numeric value that the extracted text denotes. Required.

  • unit (str or VolumeUnit) – The Volume Unit of measurement. Required. Known values are: “Unspecified”, “CubicMeter”, “CubicCentimeter”, “CubicMillimeter”, “Hectoliter”, “Decaliter”, “Liter”, “Centiliter”, “Milliliter”, “CubicYard”, “CubicInch”, “CubicFoot”, “CubicMile”, “FluidOunce”, “Teaspoon”, “Tablespoon”, “Pint”, “Quart”, “Cup”, “Gill”, “Pinch”, “FluidDram”, “Barrel”, “Minim”, “Cord”, “Peck”, “Bushel”, and “Hogshead”.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

get(key, default=None)
has_key(k)
classmethod is_xml_model()
items()
keys()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

update(*args, **kwargs)
values()
class azure.ai.textanalytics.VolumeUnit(value)[source]

The Volume Unit of measurement.

BARREL = 'Barrel'
BUSHEL = 'Bushel'
CENTILITER = 'Centiliter'
CORD = 'Cord'
CUBIC_CENTIMETER = 'CubicCentimeter'
CUBIC_FOOT = 'CubicFoot'
CUBIC_INCH = 'CubicInch'
CUBIC_METER = 'CubicMeter'
CUBIC_MILE = 'CubicMile'
CUBIC_MILLIMETER = 'CubicMillimeter'
CUBIC_YARD = 'CubicYard'
CUP = 'Cup'
DECALITER = 'Decaliter'
FLUID_DRAM = 'FluidDram'
FLUID_OUNCE = 'FluidOunce'
GILL = 'Gill'
HECTOLITER = 'Hectoliter'
HOGSHEAD = 'Hogshead'
LITER = 'Liter'
MILLILITER = 'Milliliter'
MINIM = 'Minim'
PECK = 'Peck'
PINCH = 'Pinch'
PINT = 'Pint'
QUART = 'Quart'
TABLESPOON = 'Tablespoon'
TEASPOON = 'Teaspoon'
UNSPECIFIED = 'Unspecified'
class azure.ai.textanalytics.WeightResolution(*, value: float, unit: Union[str, _models.WeightUnit], **kwargs)[source]
Keyword Arguments
  • value (float) – The numeric value that the extracted text denotes. Required.

  • unit (str or WeightUnit) – The weight Unit of measurement. Required. Known values are: “Unspecified”, “Kilogram”, “Gram”, “Milligram”, “Gallon”, “MetricTon”, “Ton”, “Pound”, “Ounce”, “Grain”, “PennyWeight”, “LongTonBritish”, “ShortTonUS”, “ShortHundredWeightUS”, “Stone”, and “Dram”.

as_dict(keep_readonly=True, key_transformer=<function attribute_transformer>, **kwargs)

Return a dict that can be JSONify using json.dump.

Advanced usage might optionally use a callback as parameter:

Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains ‘type’ with the msrest type and ‘key’ with the RestAPI encoded key. Value is the current value in this object.

The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict.

See the three examples in this file:

  • attribute_transformer

  • full_restapi_key_transformer

  • last_restapi_key_transformer

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

key_transformer (function) – A key transformer function.

Returns

A dict JSON compatible object

Return type

dict

classmethod deserialize(data, content_type=None)

Parse a str using the RestAPI syntax and return a model.

Parameters
  • data (str) – A str using RestAPI structure. JSON by default.

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

classmethod enable_additional_properties_sending()
classmethod from_dict(data, key_extractors=None, content_type=None)

Parse a dict using given key extractor return a model.

By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor)

Parameters
  • data (dict) – A dict using RestAPI structure

  • content_type (str) – JSON by default, set application/xml if XML.

Returns

An instance of this model

Raises

DeserializationError if something went wrong

get(key, default=None)
has_key(k)
classmethod is_xml_model()
items()
keys()
serialize(keep_readonly=False, **kwargs)

Return the JSON that would be sent to azure from this model.

This is an alias to as_dict(full_restapi_key_transformer, keep_readonly=False).

If you want XML serialization, you can pass the kwargs is_xml=True.

Parameters

keep_readonly (bool) – If you want to serialize the readonly attributes

Returns

A dict JSON compatible object

Return type

dict

update(*args, **kwargs)
values()
class azure.ai.textanalytics.WeightUnit(value)[source]

The weight Unit of measurement.

DRAM = 'Dram'
GALLON = 'Gallon'
GRAIN = 'Grain'
GRAM = 'Gram'
KILOGRAM = 'Kilogram'
LONG_TON_BRITISH = 'LongTonBritish'
METRIC_TON = 'MetricTon'
MILLIGRAM = 'Milligram'
OUNCE = 'Ounce'
PENNY_WEIGHT = 'PennyWeight'
POUND = 'Pound'
SHORT_HUNDRED_WEIGHT_US = 'ShortHundredWeightUS'
SHORT_TON_US = 'ShortTonUS'
STONE = 'Stone'
TON = 'Ton'
UNSPECIFIED = 'Unspecified'