From dae01b1bd1e523860bbd4d163e451072475e62ae Mon Sep 17 00:00:00 2001 From: iscai-msft Date: Thu, 3 Jun 2021 11:16:15 -0400 Subject: [PATCH 1/6] add stats for analyze policies --- .../azure/ai/textanalytics/_policies.py | 59 ++++++++++++-- .../tests/test_analyze.py | 78 ++++++++----------- 2 files changed, 86 insertions(+), 51 deletions(-) diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_policies.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_policies.py index 0db101c7f079..aa7b72229d8e 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_policies.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_policies.py @@ -3,31 +3,76 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ - +from copy import deepcopy from azure.core.pipeline.policies import ContentDecodePolicy from azure.core.pipeline.policies import SansIOHTTPPolicy -from ._models import TextDocumentBatchStatistics +from ._models import TextDocumentBatchStatistics, AnalyzeActionsType +from ._lro import _FINISHED, _FAILED + +def _finished_polling(data): + return bool(data) and data['status'] in _FINISHED.union(_FAILED) +def _get_task_name_from_task_type(task_type): + if task_type == AnalyzeActionsType.RECOGNIZE_ENTITIES: + return "entityRecognitionTasks" + if task_type == AnalyzeActionsType.RECOGNIZE_PII_ENTITIES: + return "entityRecognitionPiiTasks" + if task_type == AnalyzeActionsType.RECOGNIZE_LINKED_ENTITIES: + return "entityLinkingTasks" + if task_type == AnalyzeActionsType.ANALYZE_SENTIMENT: + return "sentimentAnalysisTasks" + return "keyPhraseExtractionTasks" class TextAnalyticsResponseHookPolicy(SansIOHTTPPolicy): def __init__(self, **kwargs): self._response_callback = kwargs.get("raw_response_hook") + self._is_lro = False + self._task_order = None super(TextAnalyticsResponseHookPolicy, self).__init__() def on_request(self, request): self._response_callback = request.context.options.pop("raw_response_hook", self._response_callback) + if not self._task_order: + self._task_order = request.context.options.pop("_task_order", None) def on_response(self, request, response): - + if response.http_response.status_code == 202: + self._is_lro = True # lro calls start with 202 if self._response_callback: data = ContentDecodePolicy.deserialize_from_http_generics(response.http_response) - if data: + if self._is_lro and not _finished_polling(data): + return + statistics = None + model_version = None + action_statistics = None + action_model_versions = None + if self._task_order: + data_copy = deepcopy(data) + action_statistics = [] + action_model_versions = [] + for task in self._task_order: + property_name = _get_task_name_from_task_type(task) + results = data_copy['tasks'][property_name].pop(0)['results'] + if results.get("statistics"): + action_statistics.append(results.pop("statistics")) + if results.get("modelVersion"): + action_model_versions.append(results.pop("modelVersion")) + else: statistics = data.get("statistics", None) model_version = data.get("modelVersion", None) - if statistics or model_version: + if any([statistics, model_version, action_statistics, action_model_versions]): + if statistics: batch_statistics = TextDocumentBatchStatistics._from_generated(statistics) # pylint: disable=protected-access response.statistics = batch_statistics + if action_statistics: + response.action_statistics = [ + TextDocumentBatchStatistics._from_generated(stat) # pylint: disable=protected-access + for stat in action_statistics + ] + if model_version: response.model_version = model_version - response.raw_response = data - self._response_callback(response) + if action_model_versions: + response.action_model_versions = action_model_versions + response.raw_response = data + self._response_callback(response) diff --git a/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze.py b/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze.py index 55819cfad94c..840fdb8af9e8 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze.py +++ b/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze.py @@ -349,50 +349,6 @@ def test_out_of_order_ids_multiple_tasks(self, client): for idx, resp in enumerate(action_result.document_results): self.assertEqual(resp.id, in_order[idx]) - @GlobalTextAnalyticsAccountPreparer() - @TextAnalyticsClientPreparer() - def test_show_stats_and_model_version_multiple_tasks(self, client): - - def callback(resp): - if resp.raw_response: - a = "b" - - docs = [{"id": "56", "text": ":)"}, - {"id": "0", "text": ":("}, - {"id": "19", "text": ":P"}, - {"id": "1", "text": ":D"}] - - poller = client.begin_analyze_actions( - docs, - actions=[ - RecognizeEntitiesAction(model_version="latest"), - ExtractKeyPhrasesAction(model_version="latest"), - RecognizePiiEntitiesAction(model_version="latest"), - RecognizeLinkedEntitiesAction(model_version="latest"), - AnalyzeSentimentAction(model_version="latest") - ], - show_stats=True, - polling_interval=self._interval(), - raw_response_hook=callback, - ) - - response = poller.result() - - action_results = list(response) - assert len(action_results) == 5 - assert action_results[0].action_type == AnalyzeActionsType.RECOGNIZE_ENTITIES - assert action_results[1].action_type == AnalyzeActionsType.EXTRACT_KEY_PHRASES - assert action_results[2].action_type == AnalyzeActionsType.RECOGNIZE_PII_ENTITIES - assert action_results[3].action_type == AnalyzeActionsType.RECOGNIZE_LINKED_ENTITIES - assert action_results[4].action_type == AnalyzeActionsType.ANALYZE_SENTIMENT - - assert all([action_result for action_result in action_results if len(action_result.document_results) == len(docs)]) - - for action_result in action_results: - assert action_result.statistics - for doc in action_result.document_results: - assert doc.statistics - @GlobalTextAnalyticsAccountPreparer() @TextAnalyticsClientPreparer() def test_poller_metadata(self, client): @@ -683,3 +639,37 @@ def callback(resp): polling_interval=self._interval(), raw_response_hook=callback, ).result() + + @GlobalTextAnalyticsAccountPreparer() + @TextAnalyticsClientPreparer() + def test_show_stats_and_model_version(self, client): + actions = [ + AnalyzeSentimentAction(model_version="2020-04-01"), + ExtractKeyPhrasesAction(model_version="2020-07-01"), + ] + documents = ["Show stats", "model version", ""] + + def callback(response): + assert response + assert len(response.action_model_versions) == len(actions) + assert response.action_model_versions[0] == "2020-04-01" + assert response.action_model_versions[1] == "2020-07-01" + assert len(response.action_statistics) == len(actions) + for stat in response.statistics: + assert stat.document_count == len(documents) + assert stat.transaction_count == 2 + assert stat.valid_document_count == 2 + assert stat.erroneous_document_count == 1 + + response = list(client.begin_analyze_actions( + documents=documents, + actions=actions, + polling_interval=self._interval(), + show_stats=True, + raw_response_hook=callback, + ).result()) + + analyze_sentiment_document = response[0].document_results[0] + assert analyze_sentiment_document.statistics.character_count == 10 + assert analyze_sentiment_document.stat + a = "b" \ No newline at end of file From 786883c0fc00c38722fd44855179e80b61ea8ea0 Mon Sep 17 00:00:00 2001 From: iscai-msft Date: Thu, 3 Jun 2021 11:18:04 -0400 Subject: [PATCH 2/6] remove deserializer and custom ItemPaged --- .../azure/ai/textanalytics/__init__.py | 2 - .../azure/ai/textanalytics/_async_paging.py | 20 ----- .../azure/ai/textanalytics/_paging.py | 20 ----- .../azure/ai/textanalytics/_policies.py | 59 ++------------ .../ai/textanalytics/_response_handlers.py | 12 +-- .../textanalytics/_response_handlers_async.py | 12 +-- .../textanalytics/_text_analytics_client.py | 9 +-- .../aio/_text_analytics_client_async.py | 8 +- .../azure-ai-textanalytics/swagger/README.md | 4 +- .../tests/test_analyze.py | 78 +++++++++++-------- 10 files changed, 64 insertions(+), 160 deletions(-) delete mode 100644 sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_async_paging.py delete mode 100644 sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_paging.py diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/__init__.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/__init__.py index 753e2c49ecba..e2ddc1004e4a 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/__init__.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/__init__.py @@ -49,7 +49,6 @@ HealthcareEntityAssertion, AnalyzeSentimentAction ) -from ._paging import AnalyzeHealthcareEntitiesResult from ._generated.v3_1_preview_5.models import ( PiiCategory as PiiEntityCategoryType, RelationType as HealthcareEntityRelationType, @@ -86,7 +85,6 @@ 'PiiEntity', 'PiiEntityDomainType', 'AnalyzeHealthcareEntitiesResultItem', - 'AnalyzeHealthcareEntitiesResult', 'HealthcareEntity', 'HealthcareEntityDataSource', 'RecognizeEntitiesAction', diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_async_paging.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_async_paging.py deleted file mode 100644 index 352396d4dc4d..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_async_paging.py +++ /dev/null @@ -1,20 +0,0 @@ -# coding=utf-8 -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -from azure.core.async_paging import AsyncItemPaged - - -class AnalyzeHealthcareEntitiesResultAsync(AsyncItemPaged): - def __init__(self, *args, **kwargs): - self.model_version = kwargs.pop('model_version') - self.statistics = kwargs.pop('statistics') - super(AnalyzeHealthcareEntitiesResultAsync, self).__init__(*args, **kwargs) - - -class AnalyzeResultAsync(AsyncItemPaged): - def __init__(self, *args, **kwargs): - self.statistics = kwargs.pop('statistics', None) - super(AnalyzeResultAsync, self).__init__(*args, **kwargs) diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_paging.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_paging.py deleted file mode 100644 index 6ca6a2073464..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_paging.py +++ /dev/null @@ -1,20 +0,0 @@ -# coding=utf-8 -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -from azure.core.paging import ItemPaged - - -class AnalyzeHealthcareEntitiesResult(ItemPaged): - def __init__(self, *args, **kwargs): - self.model_version = kwargs.pop('model_version') - self.statistics = kwargs.pop('statistics') - super(AnalyzeHealthcareEntitiesResult, self).__init__(*args, **kwargs) - - -class AnalyzeResult(ItemPaged): - def __init__(self, *args, **kwargs): - self.statistics = kwargs.pop('statistics', None) - super(AnalyzeResult, self).__init__(*args, **kwargs) diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_policies.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_policies.py index aa7b72229d8e..0db101c7f079 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_policies.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_policies.py @@ -3,76 +3,31 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ -from copy import deepcopy + from azure.core.pipeline.policies import ContentDecodePolicy from azure.core.pipeline.policies import SansIOHTTPPolicy -from ._models import TextDocumentBatchStatistics, AnalyzeActionsType -from ._lro import _FINISHED, _FAILED - -def _finished_polling(data): - return bool(data) and data['status'] in _FINISHED.union(_FAILED) +from ._models import TextDocumentBatchStatistics -def _get_task_name_from_task_type(task_type): - if task_type == AnalyzeActionsType.RECOGNIZE_ENTITIES: - return "entityRecognitionTasks" - if task_type == AnalyzeActionsType.RECOGNIZE_PII_ENTITIES: - return "entityRecognitionPiiTasks" - if task_type == AnalyzeActionsType.RECOGNIZE_LINKED_ENTITIES: - return "entityLinkingTasks" - if task_type == AnalyzeActionsType.ANALYZE_SENTIMENT: - return "sentimentAnalysisTasks" - return "keyPhraseExtractionTasks" class TextAnalyticsResponseHookPolicy(SansIOHTTPPolicy): def __init__(self, **kwargs): self._response_callback = kwargs.get("raw_response_hook") - self._is_lro = False - self._task_order = None super(TextAnalyticsResponseHookPolicy, self).__init__() def on_request(self, request): self._response_callback = request.context.options.pop("raw_response_hook", self._response_callback) - if not self._task_order: - self._task_order = request.context.options.pop("_task_order", None) def on_response(self, request, response): - if response.http_response.status_code == 202: - self._is_lro = True # lro calls start with 202 + if self._response_callback: data = ContentDecodePolicy.deserialize_from_http_generics(response.http_response) - if self._is_lro and not _finished_polling(data): - return - statistics = None - model_version = None - action_statistics = None - action_model_versions = None - if self._task_order: - data_copy = deepcopy(data) - action_statistics = [] - action_model_versions = [] - for task in self._task_order: - property_name = _get_task_name_from_task_type(task) - results = data_copy['tasks'][property_name].pop(0)['results'] - if results.get("statistics"): - action_statistics.append(results.pop("statistics")) - if results.get("modelVersion"): - action_model_versions.append(results.pop("modelVersion")) - else: + if data: statistics = data.get("statistics", None) model_version = data.get("modelVersion", None) - if any([statistics, model_version, action_statistics, action_model_versions]): - if statistics: + if statistics or model_version: batch_statistics = TextDocumentBatchStatistics._from_generated(statistics) # pylint: disable=protected-access response.statistics = batch_statistics - if action_statistics: - response.action_statistics = [ - TextDocumentBatchStatistics._from_generated(stat) # pylint: disable=protected-access - for stat in action_statistics - ] - if model_version: response.model_version = model_version - if action_model_versions: - response.action_model_versions = action_model_versions - response.raw_response = data - self._response_callback(response) + response.raw_response = data + self._response_callback(response) diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_response_handlers.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_response_handlers.py index bba2c934d37c..cd977d85b4db 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_response_handlers.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_response_handlers.py @@ -13,6 +13,7 @@ ClientAuthenticationError, ODataV4Format ) +from azure.core.paging import ItemPaged from ._models import ( RecognizeEntitiesResult, CategorizedEntity, @@ -37,7 +38,6 @@ AnalyzeActionsError, _get_indices, ) -from ._paging import AnalyzeHealthcareEntitiesResult, AnalyzeResult class CSODataV4Format(ODataV4Format): @@ -320,19 +320,13 @@ def lro_get_next_page(lro_status_callback, first_page, continuation_token, show_ def healthcare_paged_result(doc_id_order, health_status_callback, _, obj, response_headers, show_stats=False): # pylint: disable=unused-argument - return AnalyzeHealthcareEntitiesResult( + return ItemPaged( functools.partial(lro_get_next_page, health_status_callback, obj, show_stats=show_stats), functools.partial(healthcare_extract_page_data, doc_id_order, obj, response_headers), - model_version=obj.results.model_version, - statistics=RequestStatistics._from_generated(obj.results.statistics) if show_stats else None # pylint: disable=protected-access ) def analyze_paged_result(doc_id_order, task_order, analyze_status_callback, _, obj, response_headers, show_stats=False): # pylint: disable=unused-argument - return AnalyzeResult( + return ItemPaged( functools.partial(lro_get_next_page, analyze_status_callback, obj, show_stats=show_stats), functools.partial(analyze_extract_page_data, doc_id_order, task_order, response_headers) ) - -def _get_deserialize(): - from ._generated.v3_1_preview_5 import TextAnalyticsClient - return TextAnalyticsClient("dummy", "dummy")._deserialize # pylint: disable=protected-access diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_response_handlers_async.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_response_handlers_async.py index c798d75c3c6c..95a2ed2df10e 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_response_handlers_async.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_response_handlers_async.py @@ -8,12 +8,8 @@ import functools from urllib.parse import urlparse, parse_qsl -from azure.core.async_paging import AsyncList +from azure.core.async_paging import AsyncList, AsyncItemPaged from ._models import RequestStatistics -from ._async_paging import ( - AnalyzeHealthcareEntitiesResultAsync, - AnalyzeResultAsync -) from ._response_handlers import healthcare_result, get_iter_items @@ -43,11 +39,9 @@ async def lro_get_next_page_async(lro_status_callback, first_page, continuation_ def healthcare_paged_result(doc_id_order, health_status_callback, response, obj, response_headers, show_stats=False): # pylint: disable=unused-argument - return AnalyzeHealthcareEntitiesResultAsync( + return AsyncItemPaged( functools.partial(lro_get_next_page_async, health_status_callback, obj, show_stats=show_stats), functools.partial(healthcare_extract_page_data_async, doc_id_order, obj, response_headers), - model_version=obj.results.model_version, - statistics=RequestStatistics._from_generated(obj.results.statistics) if show_stats else None # pylint: disable=protected-access ) async def analyze_extract_page_data_async(doc_id_order, task_order, response_headers, analyze_job_state): @@ -57,7 +51,7 @@ async def analyze_extract_page_data_async(doc_id_order, task_order, response_hea def analyze_paged_result( doc_id_order, task_order, analyze_status_callback, response, obj, response_headers, show_stats=False # pylint: disable=unused-argument ): - return AnalyzeResultAsync( + return AsyncItemPaged( functools.partial(lro_get_next_page_async, analyze_status_callback, obj), functools.partial(analyze_extract_page_data_async, doc_id_order, task_order, response_headers), ) diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_text_analytics_client.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_text_analytics_client.py index c8737a4501fc..0fa5d1c929dc 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_text_analytics_client.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_text_analytics_client.py @@ -33,7 +33,6 @@ pii_entities_result, healthcare_paged_result, analyze_paged_result, - _get_deserialize ) from ._models import AnalyzeActionsType @@ -120,7 +119,6 @@ def __init__(self, endpoint, credential, **kwargs): self._default_language = kwargs.pop("default_language", "en") self._default_country_hint = kwargs.pop("default_country_hint", "US") self._string_index_type_default = None if kwargs.get("api_version") == "v3.0" else "UnicodeCodePoint" - self._deserialize = _get_deserialize() @distributed_trace @@ -493,8 +491,7 @@ def recognize_linked_entities( # type: ignore process_http_response_error(error) def _healthcare_result_callback(self, doc_id_order, raw_response, _, headers, show_stats=False): - healthcare_result = self._deserialize( - self._client.models(api_version="v3.1-preview.5").HealthcareJobState, + healthcare_result = self._client.models(api_version="v3.1-preview.5").HealthcareJobState.deserialize( raw_response ) return healthcare_paged_result( @@ -810,8 +807,7 @@ def analyze_sentiment( # type: ignore process_http_response_error(error) def _analyze_result_callback(self, doc_id_order, task_order, raw_response, _, headers, show_stats=False): - analyze_result = self._deserialize( - self._client.models(api_version="v3.1-preview.5").AnalyzeJobState, # pylint: disable=protected-access + analyze_result = self._client.models(api_version="v3.1-preview.5").AnalyzeJobState.deserialize( raw_response ) return analyze_paged_result( @@ -932,6 +928,7 @@ def begin_analyze_actions( # type: ignore ], **kwargs), continuation_token=continuation_token, + _task_order=task_order, **kwargs ) diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_text_analytics_client_async.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_text_analytics_client_async.py index c64a395f7494..e3a018f84670 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_text_analytics_client_async.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_text_analytics_client_async.py @@ -27,7 +27,6 @@ sentiment_result, language_result, pii_entities_result, - _get_deserialize ) from .._response_handlers_async import healthcare_paged_result, analyze_paged_result from .._models import ( @@ -118,7 +117,6 @@ def __init__( # type: ignore self._default_language = kwargs.pop("default_language", "en") self._default_country_hint = kwargs.pop("default_country_hint", "US") self._string_code_unit = None if kwargs.get("api_version") == "v3.0" else "UnicodeCodePoint" - self._deserialize = _get_deserialize() @distributed_trace_async async def detect_language( # type: ignore @@ -669,8 +667,7 @@ async def analyze_sentiment( # type: ignore process_http_response_error(error) def _healthcare_result_callback(self, doc_id_order, raw_response, _, headers, show_stats=False): - healthcare_result = self._deserialize( - self._client.models(api_version="v3.1-preview.5").HealthcareJobState, + healthcare_result = self._client.models(api_version="v3.1-preview.5").HealthcareJobState.deserialize( raw_response ) return healthcare_paged_result( @@ -792,8 +789,7 @@ async def begin_analyze_healthcare_entities( # type: ignore process_http_response_error(error) def _analyze_result_callback(self, doc_id_order, task_order, raw_response, _, headers, show_stats=False): - analyze_result = self._deserialize( - self._client.models(api_version="v3.1-preview.5").AnalyzeJobState, + analyze_result = self._client.models(api_version="v3.1-preview.5").AnalyzeJobState.deserialize( raw_response ) return analyze_paged_result( diff --git a/sdk/textanalytics/azure-ai-textanalytics/swagger/README.md b/sdk/textanalytics/azure-ai-textanalytics/swagger/README.md index d87497518f69..dce6bf058f04 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/swagger/README.md +++ b/sdk/textanalytics/azure-ai-textanalytics/swagger/README.md @@ -60,7 +60,7 @@ namespace: azure.ai.textanalytics.v3_1_preview_5 output-folder: ../azure/ai/textanalytics/_generated/v3_1_preview_5 ``` -### Override Analyze's pager and poller +### Override Analyze's pager poller ``` yaml directive: @@ -75,7 +75,7 @@ directive: ``` -### Override Healthcare's pager and poller +### Override Healthcare's poller ``` yaml directive: diff --git a/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze.py b/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze.py index 840fdb8af9e8..55819cfad94c 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze.py +++ b/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze.py @@ -349,6 +349,50 @@ def test_out_of_order_ids_multiple_tasks(self, client): for idx, resp in enumerate(action_result.document_results): self.assertEqual(resp.id, in_order[idx]) + @GlobalTextAnalyticsAccountPreparer() + @TextAnalyticsClientPreparer() + def test_show_stats_and_model_version_multiple_tasks(self, client): + + def callback(resp): + if resp.raw_response: + a = "b" + + docs = [{"id": "56", "text": ":)"}, + {"id": "0", "text": ":("}, + {"id": "19", "text": ":P"}, + {"id": "1", "text": ":D"}] + + poller = client.begin_analyze_actions( + docs, + actions=[ + RecognizeEntitiesAction(model_version="latest"), + ExtractKeyPhrasesAction(model_version="latest"), + RecognizePiiEntitiesAction(model_version="latest"), + RecognizeLinkedEntitiesAction(model_version="latest"), + AnalyzeSentimentAction(model_version="latest") + ], + show_stats=True, + polling_interval=self._interval(), + raw_response_hook=callback, + ) + + response = poller.result() + + action_results = list(response) + assert len(action_results) == 5 + assert action_results[0].action_type == AnalyzeActionsType.RECOGNIZE_ENTITIES + assert action_results[1].action_type == AnalyzeActionsType.EXTRACT_KEY_PHRASES + assert action_results[2].action_type == AnalyzeActionsType.RECOGNIZE_PII_ENTITIES + assert action_results[3].action_type == AnalyzeActionsType.RECOGNIZE_LINKED_ENTITIES + assert action_results[4].action_type == AnalyzeActionsType.ANALYZE_SENTIMENT + + assert all([action_result for action_result in action_results if len(action_result.document_results) == len(docs)]) + + for action_result in action_results: + assert action_result.statistics + for doc in action_result.document_results: + assert doc.statistics + @GlobalTextAnalyticsAccountPreparer() @TextAnalyticsClientPreparer() def test_poller_metadata(self, client): @@ -639,37 +683,3 @@ def callback(resp): polling_interval=self._interval(), raw_response_hook=callback, ).result() - - @GlobalTextAnalyticsAccountPreparer() - @TextAnalyticsClientPreparer() - def test_show_stats_and_model_version(self, client): - actions = [ - AnalyzeSentimentAction(model_version="2020-04-01"), - ExtractKeyPhrasesAction(model_version="2020-07-01"), - ] - documents = ["Show stats", "model version", ""] - - def callback(response): - assert response - assert len(response.action_model_versions) == len(actions) - assert response.action_model_versions[0] == "2020-04-01" - assert response.action_model_versions[1] == "2020-07-01" - assert len(response.action_statistics) == len(actions) - for stat in response.statistics: - assert stat.document_count == len(documents) - assert stat.transaction_count == 2 - assert stat.valid_document_count == 2 - assert stat.erroneous_document_count == 1 - - response = list(client.begin_analyze_actions( - documents=documents, - actions=actions, - polling_interval=self._interval(), - show_stats=True, - raw_response_hook=callback, - ).result()) - - analyze_sentiment_document = response[0].document_results[0] - assert analyze_sentiment_document.statistics.character_count == 10 - assert analyze_sentiment_document.stat - a = "b" \ No newline at end of file From 38af0140bcc54e399b32c21b8a1e67b87985d5c1 Mon Sep 17 00:00:00 2001 From: iscai-msft Date: Thu, 3 Jun 2021 11:22:04 -0400 Subject: [PATCH 3/6] rename AnalyzeHealthcareEntitiesResultItem -> AnalyzeHealthcareEntitiesResult --- sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md | 1 + .../azure/ai/textanalytics/__init__.py | 4 ++-- .../azure/ai/textanalytics/_models.py | 8 ++++---- .../azure/ai/textanalytics/_response_handlers.py | 4 ++-- .../azure/ai/textanalytics/_text_analytics_client.py | 8 ++++---- .../ai/textanalytics/aio/_text_analytics_client_async.py | 6 +++--- .../azure-ai-textanalytics/tests/test_repr.py | 4 ++-- 7 files changed, 18 insertions(+), 17 deletions(-) diff --git a/sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md b/sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md index 4ae23e24a7e7..5b3bf46ac463 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md +++ b/sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md @@ -10,6 +10,7 @@ - Renamed `AnalyzeBatchActionsType` to `AnalyzeActionsType`. - Renamed `AnalyzeBatchActionsResult` to `AnalyzeActionsResult`. - Renamed `AnalyzeBatchActionsError` to `AnalyzeActionsError`. +- Renamed `AnalyzeHealthcareEntitiesResultItem` to `AnalyzeHealthcareEntitiesResult`. **New Features** - Added enums `EntityConditionality`, `EntityCertainty`, and `EntityAssociation`. diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/__init__.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/__init__.py index e2ddc1004e4a..f79a18c70627 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/__init__.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/__init__.py @@ -32,7 +32,7 @@ RecognizePiiEntitiesResult, PiiEntity, PiiEntityDomainType, - AnalyzeHealthcareEntitiesResultItem, + AnalyzeHealthcareEntitiesResult, HealthcareEntity, HealthcareEntityDataSource, RecognizeEntitiesAction, @@ -84,7 +84,7 @@ 'RecognizePiiEntitiesResult', 'PiiEntity', 'PiiEntityDomainType', - 'AnalyzeHealthcareEntitiesResultItem', + 'AnalyzeHealthcareEntitiesResult', 'HealthcareEntity', 'HealthcareEntityDataSource', 'RecognizeEntitiesAction', diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_models.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_models.py index b0b9af28efff..ddee9b6e11df 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_models.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_models.py @@ -205,9 +205,9 @@ def __repr__(self): )[:1024] -class AnalyzeHealthcareEntitiesResultItem(DictMixin): +class AnalyzeHealthcareEntitiesResult(DictMixin): """ - AnalyzeHealthcareEntitiesResultItem contains the Healthcare entities from a + AnalyzeHealthcareEntitiesResult contains the Healthcare entities from a particular document. :ivar str id: Unique, non-empty document identifier that matches the @@ -230,7 +230,7 @@ class AnalyzeHealthcareEntitiesResultItem(DictMixin): :vartype statistics: ~azure.ai.textanalytics.TextDocumentStatistics :ivar bool is_error: Boolean check for error item when iterating over list of - results. Always False for an instance of a AnalyzeHealthcareEntitiesResultItem. + results. Always False for an instance of a AnalyzeHealthcareEntitiesResult. """ def __init__(self, **kwargs): @@ -256,7 +256,7 @@ def _from_generated(cls, healthcare_result): ) def __repr__(self): - return "AnalyzeHealthcareEntitiesResultItem(id={}, entities={}, entity_relations={}, warnings={}, "\ + return "AnalyzeHealthcareEntitiesResult(id={}, entities={}, entity_relations={}, warnings={}, "\ "statistics={}, is_error={})".format( self.id, repr(self.entities), diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_response_handlers.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_response_handlers.py index cd977d85b4db..b98fb085829d 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_response_handlers.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_response_handlers.py @@ -31,7 +31,7 @@ TextAnalyticsWarning, RecognizePiiEntitiesResult, PiiEntity, - AnalyzeHealthcareEntitiesResultItem, + AnalyzeHealthcareEntitiesResult, AnalyzeActionsResult, RequestStatistics, AnalyzeActionsType, @@ -191,7 +191,7 @@ def pii_entities_result(entity, results, *args, **kwargs): # pylint: disable=un @prepare_result def healthcare_result(health_result, results, *args, **kwargs): # pylint: disable=unused-argument - return AnalyzeHealthcareEntitiesResultItem._from_generated(health_result) # pylint: disable=protected-access + return AnalyzeHealthcareEntitiesResult._from_generated(health_result) # pylint: disable=protected-access def healthcare_extract_page_data(doc_id_order, obj, response_headers, health_job_state): # pylint: disable=unused-argument diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_text_analytics_client.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_text_analytics_client.py index 0fa5d1c929dc..668e4a23e4d6 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_text_analytics_client.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_text_analytics_client.py @@ -60,7 +60,7 @@ RecognizeLinkedEntitiesAction, ExtractKeyPhrasesAction, AnalyzeSentimentAction, - AnalyzeHealthcareEntitiesResultItem, + AnalyzeHealthcareEntitiesResult, AnalyzeActionsResult, ) @@ -508,7 +508,7 @@ def begin_analyze_healthcare_entities( # type: ignore self, documents, # type: Union[List[str], List[TextDocumentInput], List[Dict[str, str]]] **kwargs # type: Any - ): # type: (...) -> LROPoller[ItemPaged[AnalyzeHealthcareEntitiesResultItem]] + ): # type: (...) -> LROPoller[ItemPaged[AnalyzeHealthcareEntitiesResult]] """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, @@ -553,10 +553,10 @@ def begin_analyze_healthcare_entities( # type: ignore additional details, and Microsoft Responsible AI principles at https://www.microsoft.com/ai/responsible-ai. :return: An instance of an AnalyzeHealthcareEntitiesLROPoller. Call `result()` on the this - object to return a pageable of :class:`~azure.ai.textanalytics.AnalyzeHealthcareEntitiesResultItem`. + object to return a pageable of :class:`~azure.ai.textanalytics.AnalyzeHealthcareEntitiesResult`. :rtype: ~azure.core.polling.LROPoller[~azure.core.paging.ItemPaged[ - ~azure.ai.textanalytics.AnalyzeHealthcareEntitiesResultItem]] + ~azure.ai.textanalytics.AnalyzeHealthcareEntitiesResult]] :raises ~azure.core.exceptions.HttpResponseError or TypeError or ValueError or NotImplementedError: .. admonition:: Example: diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_text_analytics_client_async.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_text_analytics_client_async.py index e3a018f84670..6bec34f39db5 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_text_analytics_client_async.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_text_analytics_client_async.py @@ -56,7 +56,7 @@ if TYPE_CHECKING: from azure.core.credentials_async import AsyncTokenCredential from azure.core.credentials import AzureKeyCredential - from .._models import AnalyzeHealthcareEntitiesResultItem + from .._models import AnalyzeHealthcareEntitiesResult class TextAnalyticsClient(AsyncTextAnalyticsClientBase): @@ -684,7 +684,7 @@ async def begin_analyze_healthcare_entities( # type: ignore self, documents, # type: Union[List[str], List[TextDocumentInput], List[Dict[str, str]]] **kwargs # type: Any - ): # type: (...) -> AsyncLROPoller[AsyncItemPaged[AnalyzeHealthcareEntitiesResultItem]] + ): # type: (...) -> AsyncLROPoller[AsyncItemPaged[AnalyzeHealthcareEntitiesResult]] """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, @@ -731,7 +731,7 @@ async def begin_analyze_healthcare_entities( # type: ignore object to return a pageable of :class:`~azure.ai.textanalytics.AnalyzeHealthcareResultItem`. :rtype: ~azure.core.polling.AsyncLROPoller[~azure.core.paging.AsyncItemPaged[ - ~azure.ai.textanalytics.AnalyzeHealthcareEntitiesResultItem]] + ~azure.ai.textanalytics.AnalyzeHealthcareEntitiesResult]] :raises ~azure.core.exceptions.HttpResponseError or TypeError or ValueError or NotImplementedError: .. admonition:: Example: diff --git a/sdk/textanalytics/azure-ai-textanalytics/tests/test_repr.py b/sdk/textanalytics/azure-ai-textanalytics/tests/test_repr.py index 3a0843fd6f22..d898f210c15d 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/tests/test_repr.py +++ b/sdk/textanalytics/azure-ai-textanalytics/tests/test_repr.py @@ -509,7 +509,7 @@ def test_analyze_actions_result_extract_key_phrases(self, extract_key_phrases_re def test_analyze_healthcare_entities_result_item( self, healthcare_entity, healthcare_relation, text_analytics_warning, text_document_statistics ): - model = _models.AnalyzeHealthcareEntitiesResultItem( + model = _models.AnalyzeHealthcareEntitiesResult( id=1, entities=[healthcare_entity[0]], entity_relations=[healthcare_relation[0]], @@ -519,7 +519,7 @@ def test_analyze_healthcare_entities_result_item( ) model_repr = ( - "AnalyzeHealthcareEntitiesResultItem(id=1, entities=[{}], entity_relations=[{}], warnings=[{}], statistics={}, is_error=False)".format( + "AnalyzeHealthcareEntitiesResult(id=1, entities=[{}], entity_relations=[{}], warnings=[{}], statistics={}, is_error=False)".format( healthcare_entity[1], healthcare_relation[1], text_analytics_warning[1], text_document_statistics[1] ) ) From 4021856a9a35526ab5405d13aeb66f888f064b06 Mon Sep 17 00:00:00 2001 From: iscai-msft Date: Thu, 3 Jun 2021 14:16:20 -0400 Subject: [PATCH 4/6] move custom lros, rename, and add docstrings --- .../azure/ai/textanalytics/__init__.py | 7 +- .../_generated/_operations_mixin.py | 8 +- .../_generated/aio/_operations_mixin.py | 18 +-- .../_generated/v3_1_preview_5/_metadata.json | 56 +++---- .../_text_analytics_client_operations.py | 30 ++-- .../_text_analytics_client_operations.py | 16 +- .../azure/ai/textanalytics/_lro.py | 138 +++++++++++++--- .../azure/ai/textanalytics/_models.py | 33 +--- .../ai/textanalytics/_response_handlers.py | 4 - .../textanalytics/_response_handlers_async.py | 1 - .../textanalytics/_text_analytics_client.py | 19 ++- .../azure/ai/textanalytics/aio/__init__.py | 6 + .../{_async_lro.py => aio/_lro_async.py} | 153 +++++++++++++----- .../aio/_text_analytics_client_async.py | 44 ++--- .../azure-ai-textanalytics/swagger/README.md | 47 +++--- ...are.test_show_stats_and_model_version.yaml | 24 +-- .../tests/test_analyze_healthcare.py | 23 +-- .../tests/test_analyze_healthcare_async.py | 26 +-- .../azure-ai-textanalytics/tests/test_repr.py | 21 +-- 19 files changed, 409 insertions(+), 265 deletions(-) rename sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/{_async_lro.py => aio/_lro_async.py} (59%) diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/__init__.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/__init__.py index f79a18c70627..366fae23c386 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/__init__.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/__init__.py @@ -40,7 +40,6 @@ RecognizePiiEntitiesAction, ExtractKeyPhrasesAction, AnalyzeActionsResult, - RequestStatistics, AnalyzeActionsType, AnalyzeActionsError, HealthcareEntityRelationRoleType, @@ -56,6 +55,7 @@ Certainty as EntityCertainty, Association as EntityAssociation ) +from ._lro import AnalyzeHealthcareEntitiesLROPoller, AnalyzeActionsLROPoller __all__ = [ 'TextAnalyticsApiVersion', @@ -92,7 +92,6 @@ 'RecognizePiiEntitiesAction', 'ExtractKeyPhrasesAction', 'AnalyzeActionsResult', - 'RequestStatistics', 'AnalyzeActionsType', "AnalyzeActionsError", "PiiEntityCategoryType", @@ -104,7 +103,9 @@ "EntityConditionality", "EntityCertainty", "EntityAssociation", - "AnalyzeSentimentAction" + "AnalyzeSentimentAction", + "AnalyzeHealthcareEntitiesLROPoller", + "AnalyzeActionsLROPoller", ] __version__ = VERSION diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/_operations_mixin.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/_operations_mixin.py index 7517b50ae34e..02d38c22ea24 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/_operations_mixin.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/_operations_mixin.py @@ -13,7 +13,7 @@ import warnings # FIXME: have to manually reconfigure import path for multiapi operation mixin -from .._lro import AnalyzeBatchActionsLROPoller, AnalyzeBatchActionsLROPollingMethod, AnalyzeHealthcareEntitiesLROPoller, AnalyzeHealthcareEntitiesLROPollingMethod +from .._lro import AnalyzeActionsLROPoller, AnalyzeActionsLROPollingMethod, AnalyzeHealthcareEntitiesLROPoller, AnalyzeHealthcareEntitiesLROPollingMethod from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse @@ -84,12 +84,12 @@ def begin_analyze( :type body: ~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeBatchInput :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AnalyzeBatchActionsLROPollingMethod. + :keyword polling: By default, your polling method will be AnalyzeActionsLROPollingMethod. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of AnalyzeBatchActionsLROPoller that returns either AnalyzeJobState or the result of cls(response) - :rtype: ~...._lro.AnalyzeBatchActionsLROPoller[~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeJobState] + :return: An instance of AnalyzeActionsLROPoller that returns either AnalyzeJobState or the result of cls(response) + :rtype: ~...._lro.AnalyzeActionsLROPoller[~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeJobState] :raises ~azure.core.exceptions.HttpResponseError: """ api_version = self._get_api_version('begin_analyze') diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/aio/_operations_mixin.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/aio/_operations_mixin.py index 289c523cf529..3df38f55a74e 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/aio/_operations_mixin.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/aio/_operations_mixin.py @@ -13,7 +13,7 @@ import warnings # FIXME: have to manually reconfigure import path for multiapi operation mixin -from ..._async_lro import AnalyzeHealthcareEntitiesAsyncLROPoller, AnalyzeHealthcareEntitiesAsyncLROPollingMethod, AsyncAnalyzeBatchActionsLROPoller, AsyncAnalyzeBatchActionsLROPollingMethod +from ...aio._lro_async import AsyncAnalyzeHealthcareEntitiesLROPoller, AsyncAnalyzeHealthcareEntitiesLROPollingMethod, AsyncAnalyzeActionsLROPoller, AsyncAnalyzeActionsLROPollingMethod from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest @@ -70,7 +70,7 @@ async def begin_analyze( self, body: Optional["_models.AnalyzeBatchInput"] = None, **kwargs - ) -> AsyncAnalyzeBatchActionsLROPoller["_models.AnalyzeJobState"]: + ) -> AsyncAnalyzeActionsLROPoller["_models.AnalyzeJobState"]: """Submit analysis job. Submit a collection of text documents for analysis. Specify one or more unique tasks to be @@ -80,12 +80,12 @@ async def begin_analyze( :type body: ~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeBatchInput :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncAnalyzeBatchActionsLROPollingMethod. + :keyword polling: By default, your polling method will be AsyncAnalyzeActionsLROPollingMethod. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of AsyncAnalyzeBatchActionsLROPoller that returns either AnalyzeJobState or the result of cls(response) - :rtype: ~....._async_lro.AsyncAnalyzeBatchActionsLROPoller[~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeJobState] + :return: An instance of AsyncAnalyzeActionsLROPoller that returns either AnalyzeJobState or the result of cls(response) + :rtype: ~....._async_lro.AsyncAnalyzeActionsLROPoller[~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeJobState] :raises ~azure.core.exceptions.HttpResponseError: """ api_version = self._get_api_version('begin_analyze') @@ -142,7 +142,7 @@ async def begin_health( string_index_type: Optional[Union[str, "_models.StringIndexType"]] = None, logging_opt_out: Optional[bool] = None, **kwargs - ) -> AnalyzeHealthcareEntitiesAsyncLROPoller["_models.HealthcareJobState"]: + ) -> AsyncAnalyzeHealthcareEntitiesLROPoller["_models.HealthcareJobState"]: """Submit healthcare analysis job. Start a healthcare analysis job to recognize healthcare related entities (drugs, conditions, @@ -167,12 +167,12 @@ async def begin_health( :type logging_opt_out: bool :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AnalyzeHealthcareEntitiesAsyncLROPollingMethod. + :keyword polling: By default, your polling method will be AsyncAnalyzeHealthcareEntitiesLROPollingMethod. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of AnalyzeHealthcareEntitiesAsyncLROPoller that returns either HealthcareJobState or the result of cls(response) - :rtype: ~....._async_lro.AnalyzeHealthcareEntitiesAsyncLROPoller[~azure.ai.textanalytics.v3_1_preview_5.models.HealthcareJobState] + :return: An instance of AsyncAnalyzeHealthcareEntitiesLROPoller that returns either HealthcareJobState or the result of cls(response) + :rtype: ~....._async_lro.AsyncAnalyzeHealthcareEntitiesLROPoller[~azure.ai.textanalytics.v3_1_preview_5.models.HealthcareJobState] :raises ~azure.core.exceptions.HttpResponseError: """ api_version = self._get_api_version('begin_health') diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/v3_1_preview_5/_metadata.json b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/v3_1_preview_5/_metadata.json index 55a91e01200f..e23c1a9dd8c7 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/v3_1_preview_5/_metadata.json +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/v3_1_preview_5/_metadata.json @@ -1,6 +1,8 @@ { "chosen_version": "v3.1-preview.5", - "total_api_version_list": ["v3.1-preview.5"], + "total_api_version_list": [ + "v3.1-preview.5" + ], "client": { "name": "TextAnalyticsClient", "filename": "_text_analytics_client", @@ -42,8 +44,7 @@ "required": true } }, - "constant": { - }, + "constant": {}, "call": "credential, endpoint", "service_client_specific": { "sync": { @@ -78,20 +79,21 @@ }, "config": { "credential": true, - "credential_scopes": ["https://cognitiveservices.azure.com/.default"], + "credential_scopes": [ + "https://cognitiveservices.azure.com/.default" + ], "credential_default_policy_type": "BearerTokenCredentialPolicy", "credential_default_policy_type_has_async_version": true, "credential_key_header_name": null, "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"]}, \"local\": {\"._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials\": [\"TokenCredential\"]}}}", "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.configuration\": [\"Configuration\"], \"azure.core.pipeline\": [\"policies\"]}, \"local\": {\".._version\": [\"VERSION\"]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\"]}}, \"typing\": {\"azurecore\": {\"azure.core.credentials_async\": [\"AsyncTokenCredential\"]}}}" }, - "operation_groups": { - }, + "operation_groups": {}, "operation_mixins": { - "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.exceptions\": [\"ClientAuthenticationError\", \"HttpResponseError\", \"ResourceExistsError\", \"ResourceNotFoundError\", \"map_error\"], \"azure.core.pipeline\": [\"PipelineResponse\"], \"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"], \"...._lro\": [\"AnalyzeBatchActionsLROPoller\", \"AnalyzeBatchActionsLROPollingMethod\", \"AnalyzeHealthcareEntitiesLROPoller\", \"AnalyzeHealthcareEntitiesLROPollingMethod\"], \"azure.core.polling\": [\"LROPoller\", \"NoPolling\", \"PollingMethod\"], \"azure.core.polling.base_polling\": [\"LROBasePolling\"]}, \"stdlib\": {\"warnings\": [null]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Callable\", \"Dict\", \"Generic\", \"List\", \"Optional\", \"TypeVar\", \"Union\"]}}}", - "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.exceptions\": [\"ClientAuthenticationError\", \"HttpResponseError\", \"ResourceExistsError\", \"ResourceNotFoundError\", \"map_error\"], \"azure.core.pipeline\": [\"PipelineResponse\"], \"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"], \"....._async_lro\": [\"AnalyzeHealthcareEntitiesAsyncLROPoller\", \"AnalyzeHealthcareEntitiesAsyncLROPollingMethod\", \"AsyncAnalyzeBatchActionsLROPoller\", \"AsyncAnalyzeBatchActionsLROPollingMethod\"], \"azure.core.polling\": [\"AsyncLROPoller\", \"AsyncNoPolling\", \"AsyncPollingMethod\"], \"azure.core.polling.async_base_polling\": [\"AsyncLROBasePolling\"]}, \"stdlib\": {\"warnings\": [null]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Callable\", \"Dict\", \"Generic\", \"List\", \"Optional\", \"TypeVar\", \"Union\"]}}}", + "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.exceptions\": [\"ClientAuthenticationError\", \"HttpResponseError\", \"ResourceExistsError\", \"ResourceNotFoundError\", \"map_error\"], \"azure.core.pipeline\": [\"PipelineResponse\"], \"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"], \"...._lro\": [\"AnalyzeActionsLROPoller\", \"AnalyzeActionsLROPollingMethod\", \"AnalyzeHealthcareEntitiesLROPoller\", \"AnalyzeHealthcareEntitiesLROPollingMethod\"], \"azure.core.polling\": [\"LROPoller\", \"NoPolling\", \"PollingMethod\"], \"azure.core.polling.base_polling\": [\"LROBasePolling\"]}, \"stdlib\": {\"warnings\": [null]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Callable\", \"Dict\", \"Generic\", \"List\", \"Optional\", \"TypeVar\", \"Union\"]}}}", + "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.exceptions\": [\"ClientAuthenticationError\", \"HttpResponseError\", \"ResourceExistsError\", \"ResourceNotFoundError\", \"map_error\"], \"azure.core.pipeline\": [\"PipelineResponse\"], \"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"], \"....._async_lro\": [\"AsyncAnalyzeHealthcareEntitiesLROPoller\", \"AsyncAnalyzeHealthcareEntitiesLROPollingMethod\", \"AsyncAnalyzeActionsLROPoller\", \"AsyncAnalyzeActionsLROPollingMethod\"], \"azure.core.polling\": [\"AsyncLROPoller\", \"AsyncNoPolling\", \"AsyncPollingMethod\"], \"azure.core.polling.async_base_polling\": [\"AsyncLROBasePolling\"]}, \"stdlib\": {\"warnings\": [null]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Callable\", \"Dict\", \"Generic\", \"List\", \"Optional\", \"TypeVar\", \"Union\"]}}}", "operations": { - "_analyze_initial" : { + "_analyze_initial": { "sync": { "signature": "def _analyze_initial(\n self,\n body=None, # type: Optional[\"_models.AnalyzeBatchInput\"]\n **kwargs # type: Any\n):\n", "doc": "\"\"\"\n\n:param body: Collection of documents to analyze and tasks to execute.\n:type body: ~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeBatchInput\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: AnalyzeJobState, or the result of cls(response)\n:rtype: ~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeJobState or None\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" @@ -103,19 +105,19 @@ }, "call": "body" }, - "begin_analyze" : { + "begin_analyze": { "sync": { "signature": "def begin_analyze(\n self,\n body=None, # type: Optional[\"_models.AnalyzeBatchInput\"]\n **kwargs # type: Any\n):\n", - "doc": "\"\"\"Submit analysis job.\n\nSubmit a collection of text documents for analysis. Specify one or more unique tasks to be\nexecuted.\n\n:param body: Collection of documents to analyze and tasks to execute.\n:type body: ~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeBatchInput\n:keyword callable cls: A custom type or function that will be passed the direct response\n:keyword str continuation_token: A continuation token to restart a poller from a saved state.\n:keyword polling: By default, your polling method will be AnalyzeBatchActionsLROPollingMethod.\n Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.\n:paramtype polling: bool or ~azure.core.polling.PollingMethod\n:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.\n:return: An instance of AnalyzeBatchActionsLROPoller that returns either AnalyzeJobState or the result of cls(response)\n:rtype: ~...._lro.AnalyzeBatchActionsLROPoller[~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeJobState]\n:raises ~azure.core.exceptions.HttpResponseError:\n\"\"\"" + "doc": "\"\"\"Submit analysis job.\n\nSubmit a collection of text documents for analysis. Specify one or more unique tasks to be\nexecuted.\n\n:param body: Collection of documents to analyze and tasks to execute.\n:type body: ~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeBatchInput\n:keyword callable cls: A custom type or function that will be passed the direct response\n:keyword str continuation_token: A continuation token to restart a poller from a saved state.\n:keyword polling: By default, your polling method will be AnalyzeActionsLROPollingMethod.\n Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.\n:paramtype polling: bool or ~azure.core.polling.PollingMethod\n:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.\n:return: An instance of AnalyzeActionsLROPoller that returns either AnalyzeJobState or the result of cls(response)\n:rtype: ~...._lro.AnalyzeActionsLROPoller[~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeJobState]\n:raises ~azure.core.exceptions.HttpResponseError:\n\"\"\"" }, "async": { "coroutine": true, - "signature": "async def begin_analyze(\n self,\n body: Optional[\"_models.AnalyzeBatchInput\"] = None,\n **kwargs\n) -\u003e AsyncAnalyzeBatchActionsLROPoller[\"_models.AnalyzeJobState\"]:\n", - "doc": "\"\"\"Submit analysis job.\n\nSubmit a collection of text documents for analysis. Specify one or more unique tasks to be\nexecuted.\n\n:param body: Collection of documents to analyze and tasks to execute.\n:type body: ~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeBatchInput\n:keyword callable cls: A custom type or function that will be passed the direct response\n:keyword str continuation_token: A continuation token to restart a poller from a saved state.\n:keyword polling: By default, your polling method will be AsyncAnalyzeBatchActionsLROPollingMethod.\n Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.\n:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod\n:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.\n:return: An instance of AsyncAnalyzeBatchActionsLROPoller that returns either AnalyzeJobState or the result of cls(response)\n:rtype: ~....._async_lro.AsyncAnalyzeBatchActionsLROPoller[~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeJobState]\n:raises ~azure.core.exceptions.HttpResponseError:\n\"\"\"" + "signature": "async def begin_analyze(\n self,\n body: Optional[\"_models.AnalyzeBatchInput\"] = None,\n **kwargs\n) -\u003e AsyncAnalyzeActionsLROPoller[\"_models.AnalyzeJobState\"]:\n", + "doc": "\"\"\"Submit analysis job.\n\nSubmit a collection of text documents for analysis. Specify one or more unique tasks to be\nexecuted.\n\n:param body: Collection of documents to analyze and tasks to execute.\n:type body: ~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeBatchInput\n:keyword callable cls: A custom type or function that will be passed the direct response\n:keyword str continuation_token: A continuation token to restart a poller from a saved state.\n:keyword polling: By default, your polling method will be AsyncAnalyzeActionsLROPollingMethod.\n Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.\n:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod\n:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.\n:return: An instance of AsyncAnalyzeActionsLROPoller that returns either AnalyzeJobState or the result of cls(response)\n:rtype: ~....._async_lro.AsyncAnalyzeActionsLROPoller[~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeJobState]\n:raises ~azure.core.exceptions.HttpResponseError:\n\"\"\"" }, "call": "body" }, - "analyze_status" : { + "analyze_status": { "sync": { "signature": "def analyze_status(\n self,\n job_id, # type: str\n show_stats=None, # type: Optional[bool]\n top=20, # type: Optional[int]\n skip=0, # type: Optional[int]\n **kwargs # type: Any\n):\n", "doc": "\"\"\"Get analysis status and results.\n\nGet the status of an analysis job. A job may consist of one or more tasks. Once all tasks are\ncompleted, the job will transition to the completed state and results will be available for\neach task.\n\n:param job_id: Job ID for Analyze.\n:type job_id: str\n:param show_stats: (Optional) if set to true, response will contain request and document level\n statistics.\n:type show_stats: bool\n:param top: (Optional) Set the maximum number of results per task. When both $top and $skip are\n specified, $skip is applied first.\n:type top: int\n:param skip: (Optional) Set the number of elements to offset in the response. When both $top\n and $skip are specified, $skip is applied first.\n:type skip: int\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: AnalyzeJobState, or the result of cls(response)\n:rtype: ~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeJobState\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" @@ -127,7 +129,7 @@ }, "call": "job_id, show_stats, top, skip" }, - "health_status" : { + "health_status": { "sync": { "signature": "def health_status(\n self,\n job_id, # type: str\n top=20, # type: Optional[int]\n skip=0, # type: Optional[int]\n show_stats=None, # type: Optional[bool]\n **kwargs # type: Any\n):\n", "doc": "\"\"\"Get healthcare analysis job status and results.\n\nGet details of the healthcare prediction job specified by the jobId.\n\n:param job_id: Job ID.\n:type job_id: str\n:param top: (Optional) Set the maximum number of results per task. When both $top and $skip are\n specified, $skip is applied first.\n:type top: int\n:param skip: (Optional) Set the number of elements to offset in the response. When both $top\n and $skip are specified, $skip is applied first.\n:type skip: int\n:param show_stats: (Optional) if set to true, response will contain request and document level\n statistics.\n:type show_stats: bool\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: HealthcareJobState, or the result of cls(response)\n:rtype: ~azure.ai.textanalytics.v3_1_preview_5.models.HealthcareJobState\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" @@ -139,7 +141,7 @@ }, "call": "job_id, top, skip, show_stats" }, - "_cancel_health_job_initial" : { + "_cancel_health_job_initial": { "sync": { "signature": "def _cancel_health_job_initial(\n self,\n job_id, # type: str\n **kwargs # type: Any\n):\n", "doc": "\"\"\"\n\n:param job_id: Job ID.\n:type job_id: str\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: None, or the result of cls(response)\n:rtype: None\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" @@ -151,7 +153,7 @@ }, "call": "job_id" }, - "begin_cancel_health_job" : { + "begin_cancel_health_job": { "sync": { "signature": "def begin_cancel_health_job(\n self,\n job_id, # type: str\n **kwargs # type: Any\n):\n", "doc": "\"\"\"Cancel healthcare prediction job.\n\nCancel healthcare prediction job.\n\n:param job_id: Job ID.\n:type job_id: str\n:keyword callable cls: A custom type or function that will be passed the direct response\n:keyword str continuation_token: A continuation token to restart a poller from a saved state.\n:keyword polling: By default, your polling method will be LROBasePolling.\n Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.\n:paramtype polling: bool or ~azure.core.polling.PollingMethod\n:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.\n:return: An instance of LROPoller that returns either None or the result of cls(response)\n:rtype: ~azure.core.polling.LROPoller[None]\n:raises ~azure.core.exceptions.HttpResponseError:\n\"\"\"" @@ -163,7 +165,7 @@ }, "call": "job_id" }, - "_health_initial" : { + "_health_initial": { "sync": { "signature": "def _health_initial(\n self,\n documents, # type: List[\"_models.MultiLanguageInput\"]\n model_version=None, # type: Optional[str]\n string_index_type=None, # type: Optional[Union[str, \"_models.StringIndexType\"]]\n logging_opt_out=None, # type: Optional[bool]\n **kwargs # type: Any\n):\n", "doc": "\"\"\"\n\n:param documents: The set of documents to process as part of this batch.\n:type documents: list[~azure.ai.textanalytics.v3_1_preview_5.models.MultiLanguageInput]\n:param model_version: (Optional) This value indicates which model will be used for scoring. If\n a model-version is not specified, the API should default to the latest, non-preview version.\n:type model_version: str\n:param string_index_type: (Optional) Specifies the method used to interpret string offsets.\n Defaults to Text Elements (Graphemes) according to Unicode v8.0.0. For additional information\n see https://aka.ms/text-analytics-offsets.\n:type string_index_type: str or ~azure.ai.textanalytics.v3_1_preview_5.models.StringIndexType\n:param logging_opt_out: (Optional) If set to true, you opt-out of having your text input logged\n for troubleshooting. By default, Text Analytics logs your input text for 48 hours, solely to\n allow for troubleshooting issues in providing you with the Text Analytics natural language\n processing functions. Setting this parameter to true, disables input logging and may limit our\n ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy\n notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI\n principles at https://www.microsoft.com/en-us/ai/responsible-ai.\n:type logging_opt_out: bool\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: HealthcareJobState, or the result of cls(response)\n:rtype: ~azure.ai.textanalytics.v3_1_preview_5.models.HealthcareJobState or None\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" @@ -175,19 +177,19 @@ }, "call": "documents, model_version, string_index_type, logging_opt_out" }, - "begin_health" : { + "begin_health": { "sync": { "signature": "def begin_health(\n self,\n documents, # type: List[\"_models.MultiLanguageInput\"]\n model_version=None, # type: Optional[str]\n string_index_type=None, # type: Optional[Union[str, \"_models.StringIndexType\"]]\n logging_opt_out=None, # type: Optional[bool]\n **kwargs # type: Any\n):\n", "doc": "\"\"\"Submit healthcare analysis job.\n\nStart a healthcare analysis job to recognize healthcare related entities (drugs, conditions,\nsymptoms, etc) and their relations.\n\n:param documents: The set of documents to process as part of this batch.\n:type documents: list[~azure.ai.textanalytics.v3_1_preview_5.models.MultiLanguageInput]\n:param model_version: (Optional) This value indicates which model will be used for scoring. If\n a model-version is not specified, the API should default to the latest, non-preview version.\n:type model_version: str\n:param string_index_type: (Optional) Specifies the method used to interpret string offsets.\n Defaults to Text Elements (Graphemes) according to Unicode v8.0.0. For additional information\n see https://aka.ms/text-analytics-offsets.\n:type string_index_type: str or ~azure.ai.textanalytics.v3_1_preview_5.models.StringIndexType\n:param logging_opt_out: (Optional) If set to true, you opt-out of having your text input logged\n for troubleshooting. By default, Text Analytics logs your input text for 48 hours, solely to\n allow for troubleshooting issues in providing you with the Text Analytics natural language\n processing functions. Setting this parameter to true, disables input logging and may limit our\n ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy\n notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI\n principles at https://www.microsoft.com/en-us/ai/responsible-ai.\n:type logging_opt_out: bool\n:keyword callable cls: A custom type or function that will be passed the direct response\n:keyword str continuation_token: A continuation token to restart a poller from a saved state.\n:keyword polling: By default, your polling method will be AnalyzeHealthcareEntitiesLROPollingMethod.\n Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.\n:paramtype polling: bool or ~azure.core.polling.PollingMethod\n:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.\n:return: An instance of AnalyzeHealthcareEntitiesLROPoller that returns either HealthcareJobState or the result of cls(response)\n:rtype: ~...._lro.AnalyzeHealthcareEntitiesLROPoller[~azure.ai.textanalytics.v3_1_preview_5.models.HealthcareJobState]\n:raises ~azure.core.exceptions.HttpResponseError:\n\"\"\"" }, "async": { "coroutine": true, - "signature": "async def begin_health(\n self,\n documents: List[\"_models.MultiLanguageInput\"],\n model_version: Optional[str] = None,\n string_index_type: Optional[Union[str, \"_models.StringIndexType\"]] = None,\n logging_opt_out: Optional[bool] = None,\n **kwargs\n) -\u003e AnalyzeHealthcareEntitiesAsyncLROPoller[\"_models.HealthcareJobState\"]:\n", - "doc": "\"\"\"Submit healthcare analysis job.\n\nStart a healthcare analysis job to recognize healthcare related entities (drugs, conditions,\nsymptoms, etc) and their relations.\n\n:param documents: The set of documents to process as part of this batch.\n:type documents: list[~azure.ai.textanalytics.v3_1_preview_5.models.MultiLanguageInput]\n:param model_version: (Optional) This value indicates which model will be used for scoring. If\n a model-version is not specified, the API should default to the latest, non-preview version.\n:type model_version: str\n:param string_index_type: (Optional) Specifies the method used to interpret string offsets.\n Defaults to Text Elements (Graphemes) according to Unicode v8.0.0. For additional information\n see https://aka.ms/text-analytics-offsets.\n:type string_index_type: str or ~azure.ai.textanalytics.v3_1_preview_5.models.StringIndexType\n:param logging_opt_out: (Optional) If set to true, you opt-out of having your text input logged\n for troubleshooting. By default, Text Analytics logs your input text for 48 hours, solely to\n allow for troubleshooting issues in providing you with the Text Analytics natural language\n processing functions. Setting this parameter to true, disables input logging and may limit our\n ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy\n notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI\n principles at https://www.microsoft.com/en-us/ai/responsible-ai.\n:type logging_opt_out: bool\n:keyword callable cls: A custom type or function that will be passed the direct response\n:keyword str continuation_token: A continuation token to restart a poller from a saved state.\n:keyword polling: By default, your polling method will be AnalyzeHealthcareEntitiesAsyncLROPollingMethod.\n Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.\n:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod\n:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.\n:return: An instance of AnalyzeHealthcareEntitiesAsyncLROPoller that returns either HealthcareJobState or the result of cls(response)\n:rtype: ~....._async_lro.AnalyzeHealthcareEntitiesAsyncLROPoller[~azure.ai.textanalytics.v3_1_preview_5.models.HealthcareJobState]\n:raises ~azure.core.exceptions.HttpResponseError:\n\"\"\"" + "signature": "async def begin_health(\n self,\n documents: List[\"_models.MultiLanguageInput\"],\n model_version: Optional[str] = None,\n string_index_type: Optional[Union[str, \"_models.StringIndexType\"]] = None,\n logging_opt_out: Optional[bool] = None,\n **kwargs\n) -\u003e AsyncAnalyzeHealthcareEntitiesLROPoller[\"_models.HealthcareJobState\"]:\n", + "doc": "\"\"\"Submit healthcare analysis job.\n\nStart a healthcare analysis job to recognize healthcare related entities (drugs, conditions,\nsymptoms, etc) and their relations.\n\n:param documents: The set of documents to process as part of this batch.\n:type documents: list[~azure.ai.textanalytics.v3_1_preview_5.models.MultiLanguageInput]\n:param model_version: (Optional) This value indicates which model will be used for scoring. If\n a model-version is not specified, the API should default to the latest, non-preview version.\n:type model_version: str\n:param string_index_type: (Optional) Specifies the method used to interpret string offsets.\n Defaults to Text Elements (Graphemes) according to Unicode v8.0.0. For additional information\n see https://aka.ms/text-analytics-offsets.\n:type string_index_type: str or ~azure.ai.textanalytics.v3_1_preview_5.models.StringIndexType\n:param logging_opt_out: (Optional) If set to true, you opt-out of having your text input logged\n for troubleshooting. By default, Text Analytics logs your input text for 48 hours, solely to\n allow for troubleshooting issues in providing you with the Text Analytics natural language\n processing functions. Setting this parameter to true, disables input logging and may limit our\n ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy\n notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI\n principles at https://www.microsoft.com/en-us/ai/responsible-ai.\n:type logging_opt_out: bool\n:keyword callable cls: A custom type or function that will be passed the direct response\n:keyword str continuation_token: A continuation token to restart a poller from a saved state.\n:keyword polling: By default, your polling method will be AsyncAnalyzeHealthcareEntitiesLROPollingMethod.\n Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.\n:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod\n:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.\n:return: An instance of AsyncAnalyzeHealthcareEntitiesLROPoller that returns either HealthcareJobState or the result of cls(response)\n:rtype: ~....._async_lro.AsyncAnalyzeHealthcareEntitiesLROPoller[~azure.ai.textanalytics.v3_1_preview_5.models.HealthcareJobState]\n:raises ~azure.core.exceptions.HttpResponseError:\n\"\"\"" }, "call": "documents, model_version, string_index_type, logging_opt_out" }, - "entities_recognition_general" : { + "entities_recognition_general": { "sync": { "signature": "def entities_recognition_general(\n self,\n documents, # type: List[\"_models.MultiLanguageInput\"]\n model_version=None, # type: Optional[str]\n show_stats=None, # type: Optional[bool]\n logging_opt_out=None, # type: Optional[bool]\n string_index_type=None, # type: Optional[Union[str, \"_models.StringIndexType\"]]\n **kwargs # type: Any\n):\n", "doc": "\"\"\"Named Entity Recognition.\n\nThe API returns a list of general named entities in a given document. For the list of supported\nentity types, check :code:`\u003ca href=\"https://aka.ms/taner\"\u003eSupported Entity Types in Text\nAnalytics API\u003c/a\u003e`. See the :code:`\u003ca href=\"https://aka.ms/talangs\"\u003eSupported languages in Text\nAnalytics API\u003c/a\u003e` for the list of enabled languages.\n\n:param documents: The set of documents to process as part of this batch.\n:type documents: list[~azure.ai.textanalytics.v3_1_preview_5.models.MultiLanguageInput]\n:param model_version: (Optional) This value indicates which model will be used for scoring. If\n a model-version is not specified, the API should default to the latest, non-preview version.\n:type model_version: str\n:param show_stats: (Optional) if set to true, response will contain request and document level\n statistics.\n:type show_stats: bool\n:param logging_opt_out: (Optional) If set to true, you opt-out of having your text input logged\n for troubleshooting. By default, Text Analytics logs your input text for 48 hours, solely to\n allow for troubleshooting issues in providing you with the Text Analytics natural language\n processing functions. Setting this parameter to true, disables input logging and may limit our\n ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy\n notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI\n principles at https://www.microsoft.com/en-us/ai/responsible-ai.\n:type logging_opt_out: bool\n:param string_index_type: (Optional) Specifies the method used to interpret string offsets.\n Defaults to Text Elements (Graphemes) according to Unicode v8.0.0. For additional information\n see https://aka.ms/text-analytics-offsets.\n:type string_index_type: str or ~azure.ai.textanalytics.v3_1_preview_5.models.StringIndexType\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: EntitiesResult, or the result of cls(response)\n:rtype: ~azure.ai.textanalytics.v3_1_preview_5.models.EntitiesResult\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" @@ -199,7 +201,7 @@ }, "call": "documents, model_version, show_stats, logging_opt_out, string_index_type" }, - "entities_recognition_pii" : { + "entities_recognition_pii": { "sync": { "signature": "def entities_recognition_pii(\n self,\n documents, # type: List[\"_models.MultiLanguageInput\"]\n model_version=None, # type: Optional[str]\n show_stats=None, # type: Optional[bool]\n logging_opt_out=None, # type: Optional[bool]\n domain=None, # type: Optional[str]\n string_index_type=None, # type: Optional[Union[str, \"_models.StringIndexType\"]]\n pii_categories=None, # type: Optional[List[Union[str, \"_models.PiiCategory\"]]]\n **kwargs # type: Any\n):\n", "doc": "\"\"\"Entities containing personal information.\n\nThe API returns a list of entities with personal information (\\\"SSN\\\", \\\"Bank Account\\\" etc) in\nthe document. For the list of supported entity types, check :code:`\u003ca\nhref=\"https://aka.ms/tanerpii\"\u003eSupported Entity Types in Text Analytics API\u003c/a\u003e`. See the\n:code:`\u003ca href=\"https://aka.ms/talangs\"\u003eSupported languages in Text Analytics API\u003c/a\u003e` for the\nlist of enabled languages.\n\n:param documents: The set of documents to process as part of this batch.\n:type documents: list[~azure.ai.textanalytics.v3_1_preview_5.models.MultiLanguageInput]\n:param model_version: (Optional) This value indicates which model will be used for scoring. If\n a model-version is not specified, the API should default to the latest, non-preview version.\n:type model_version: str\n:param show_stats: (Optional) if set to true, response will contain request and document level\n statistics.\n:type show_stats: bool\n:param logging_opt_out: (Optional) If set to true, you opt-out of having your text input logged\n for troubleshooting. By default, Text Analytics logs your input text for 48 hours, solely to\n allow for troubleshooting issues in providing you with the Text Analytics natural language\n processing functions. Setting this parameter to true, disables input logging and may limit our\n ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy\n notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI\n principles at https://www.microsoft.com/en-us/ai/responsible-ai.\n:type logging_opt_out: bool\n:param domain: (Optional) if specified, will set the PII domain to include only a subset of the\n entity categories. Possible values include: \u0027PHI\u0027, \u0027none\u0027.\n:type domain: str\n:param string_index_type: (Optional) Specifies the method used to interpret string offsets.\n Defaults to Text Elements (Graphemes) according to Unicode v8.0.0. For additional information\n see https://aka.ms/text-analytics-offsets.\n:type string_index_type: str or ~azure.ai.textanalytics.v3_1_preview_5.models.StringIndexType\n:param pii_categories: (Optional) describes the PII categories to return.\n:type pii_categories: list[str or ~azure.ai.textanalytics.v3_1_preview_5.models.PiiCategory]\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: PiiResult, or the result of cls(response)\n:rtype: ~azure.ai.textanalytics.v3_1_preview_5.models.PiiResult\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" @@ -211,7 +213,7 @@ }, "call": "documents, model_version, show_stats, logging_opt_out, domain, string_index_type, pii_categories" }, - "entities_linking" : { + "entities_linking": { "sync": { "signature": "def entities_linking(\n self,\n documents, # type: List[\"_models.MultiLanguageInput\"]\n model_version=None, # type: Optional[str]\n show_stats=None, # type: Optional[bool]\n logging_opt_out=None, # type: Optional[bool]\n string_index_type=None, # type: Optional[Union[str, \"_models.StringIndexType\"]]\n **kwargs # type: Any\n):\n", "doc": "\"\"\"Linked entities from a well known knowledge base.\n\nThe API returns a list of recognized entities with links to a well known knowledge base. See\nthe :code:`\u003ca href=\"https://aka.ms/talangs\"\u003eSupported languages in Text Analytics API\u003c/a\u003e` for\nthe list of enabled languages.\n\n:param documents: The set of documents to process as part of this batch.\n:type documents: list[~azure.ai.textanalytics.v3_1_preview_5.models.MultiLanguageInput]\n:param model_version: (Optional) This value indicates which model will be used for scoring. If\n a model-version is not specified, the API should default to the latest, non-preview version.\n:type model_version: str\n:param show_stats: (Optional) if set to true, response will contain request and document level\n statistics.\n:type show_stats: bool\n:param logging_opt_out: (Optional) If set to true, you opt-out of having your text input logged\n for troubleshooting. By default, Text Analytics logs your input text for 48 hours, solely to\n allow for troubleshooting issues in providing you with the Text Analytics natural language\n processing functions. Setting this parameter to true, disables input logging and may limit our\n ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy\n notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI\n principles at https://www.microsoft.com/en-us/ai/responsible-ai.\n:type logging_opt_out: bool\n:param string_index_type: (Optional) Specifies the method used to interpret string offsets.\n Defaults to Text Elements (Graphemes) according to Unicode v8.0.0. For additional information\n see https://aka.ms/text-analytics-offsets.\n:type string_index_type: str or ~azure.ai.textanalytics.v3_1_preview_5.models.StringIndexType\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: EntityLinkingResult, or the result of cls(response)\n:rtype: ~azure.ai.textanalytics.v3_1_preview_5.models.EntityLinkingResult\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" @@ -223,7 +225,7 @@ }, "call": "documents, model_version, show_stats, logging_opt_out, string_index_type" }, - "key_phrases" : { + "key_phrases": { "sync": { "signature": "def key_phrases(\n self,\n documents, # type: List[\"_models.MultiLanguageInput\"]\n model_version=None, # type: Optional[str]\n show_stats=None, # type: Optional[bool]\n logging_opt_out=None, # type: Optional[bool]\n **kwargs # type: Any\n):\n", "doc": "\"\"\"Key Phrases.\n\nThe API returns a list of strings denoting the key phrases in the input text. See the :code:`\u003ca\nhref=\"https://aka.ms/talangs\"\u003eSupported languages in Text Analytics API\u003c/a\u003e` for the list of\nenabled languages.\n\n:param documents: The set of documents to process as part of this batch.\n:type documents: list[~azure.ai.textanalytics.v3_1_preview_5.models.MultiLanguageInput]\n:param model_version: (Optional) This value indicates which model will be used for scoring. If\n a model-version is not specified, the API should default to the latest, non-preview version.\n:type model_version: str\n:param show_stats: (Optional) if set to true, response will contain request and document level\n statistics.\n:type show_stats: bool\n:param logging_opt_out: (Optional) If set to true, you opt-out of having your text input logged\n for troubleshooting. By default, Text Analytics logs your input text for 48 hours, solely to\n allow for troubleshooting issues in providing you with the Text Analytics natural language\n processing functions. Setting this parameter to true, disables input logging and may limit our\n ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy\n notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI\n principles at https://www.microsoft.com/en-us/ai/responsible-ai.\n:type logging_opt_out: bool\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: KeyPhraseResult, or the result of cls(response)\n:rtype: ~azure.ai.textanalytics.v3_1_preview_5.models.KeyPhraseResult\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" @@ -235,7 +237,7 @@ }, "call": "documents, model_version, show_stats, logging_opt_out" }, - "languages" : { + "languages": { "sync": { "signature": "def languages(\n self,\n documents, # type: List[\"_models.LanguageInput\"]\n model_version=None, # type: Optional[str]\n show_stats=None, # type: Optional[bool]\n logging_opt_out=None, # type: Optional[bool]\n **kwargs # type: Any\n):\n", "doc": "\"\"\"Detect Language.\n\nThe API returns the detected language and a numeric score between 0 and 1. Scores close to 1\nindicate 100% certainty that the identified language is true. See the :code:`\u003ca\nhref=\"https://aka.ms/talangs\"\u003eSupported languages in Text Analytics API\u003c/a\u003e` for the list of\nenabled languages.\n\n:param documents:\n:type documents: list[~azure.ai.textanalytics.v3_1_preview_5.models.LanguageInput]\n:param model_version: (Optional) This value indicates which model will be used for scoring. If\n a model-version is not specified, the API should default to the latest, non-preview version.\n:type model_version: str\n:param show_stats: (Optional) if set to true, response will contain request and document level\n statistics.\n:type show_stats: bool\n:param logging_opt_out: (Optional) If set to true, you opt-out of having your text input logged\n for troubleshooting. By default, Text Analytics logs your input text for 48 hours, solely to\n allow for troubleshooting issues in providing you with the Text Analytics natural language\n processing functions. Setting this parameter to true, disables input logging and may limit our\n ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy\n notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI\n principles at https://www.microsoft.com/en-us/ai/responsible-ai.\n:type logging_opt_out: bool\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: LanguageResult, or the result of cls(response)\n:rtype: ~azure.ai.textanalytics.v3_1_preview_5.models.LanguageResult\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" @@ -247,7 +249,7 @@ }, "call": "documents, model_version, show_stats, logging_opt_out" }, - "sentiment" : { + "sentiment": { "sync": { "signature": "def sentiment(\n self,\n documents, # type: List[\"_models.MultiLanguageInput\"]\n model_version=None, # type: Optional[str]\n show_stats=None, # type: Optional[bool]\n logging_opt_out=None, # type: Optional[bool]\n opinion_mining=None, # type: Optional[bool]\n string_index_type=None, # type: Optional[Union[str, \"_models.StringIndexType\"]]\n **kwargs # type: Any\n):\n", "doc": "\"\"\"Sentiment.\n\nThe API returns a detailed sentiment analysis for the input text. The analysis is done in\nmultiple levels of granularity, start from the a document level, down to sentence and key terms\n(targets and assessments).\n\n:param documents: The set of documents to process as part of this batch.\n:type documents: list[~azure.ai.textanalytics.v3_1_preview_5.models.MultiLanguageInput]\n:param model_version: (Optional) This value indicates which model will be used for scoring. If\n a model-version is not specified, the API should default to the latest, non-preview version.\n:type model_version: str\n:param show_stats: (Optional) if set to true, response will contain request and document level\n statistics.\n:type show_stats: bool\n:param logging_opt_out: (Optional) If set to true, you opt-out of having your text input logged\n for troubleshooting. By default, Text Analytics logs your input text for 48 hours, solely to\n allow for troubleshooting issues in providing you with the Text Analytics natural language\n processing functions. Setting this parameter to true, disables input logging and may limit our\n ability to remediate issues that occur. Please see Cognitive Services Compliance and Privacy\n notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI\n principles at https://www.microsoft.com/en-us/ai/responsible-ai.\n:type logging_opt_out: bool\n:param opinion_mining: (Optional) if set to true, response will contain not only sentiment\n prediction but also opinion mining (aspect-based sentiment analysis) results.\n:type opinion_mining: bool\n:param string_index_type: (Optional) Specifies the method used to interpret string offsets.\n Defaults to Text Elements (Graphemes) according to Unicode v8.0.0. For additional information\n see https://aka.ms/text-analytics-offsets.\n:type string_index_type: str or ~azure.ai.textanalytics.v3_1_preview_5.models.StringIndexType\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: SentimentResponse, or the result of cls(response)\n:rtype: ~azure.ai.textanalytics.v3_1_preview_5.models.SentimentResponse\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/v3_1_preview_5/aio/operations/_text_analytics_client_operations.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/v3_1_preview_5/aio/operations/_text_analytics_client_operations.py index e35731c74e51..a1c7018d9f8a 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/v3_1_preview_5/aio/operations/_text_analytics_client_operations.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/v3_1_preview_5/aio/operations/_text_analytics_client_operations.py @@ -8,7 +8,7 @@ from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar, Union import warnings -from ....._async_lro import AnalyzeHealthcareEntitiesAsyncLROPoller, AnalyzeHealthcareEntitiesAsyncLROPollingMethod, AsyncAnalyzeBatchActionsLROPoller, AsyncAnalyzeBatchActionsLROPollingMethod +from .....aio._lro_async import AsyncAnalyzeHealthcareEntitiesLROPoller, AsyncAnalyzeHealthcareEntitiesLROPollingMethod, AsyncAnalyzeActionsLROPoller, AsyncAnalyzeActionsLROPollingMethod from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest @@ -86,7 +86,7 @@ async def begin_analyze( self, body: Optional["_models.AnalyzeBatchInput"] = None, **kwargs - ) -> AsyncAnalyzeBatchActionsLROPoller["_models.AnalyzeJobState"]: + ) -> AsyncAnalyzeActionsLROPoller["_models.AnalyzeJobState"]: """Submit analysis job. Submit a collection of text documents for analysis. Specify one or more unique tasks to be @@ -96,12 +96,12 @@ async def begin_analyze( :type body: ~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeBatchInput :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AsyncAnalyzeBatchActionsLROPollingMethod. + :keyword polling: By default, your polling method will be AsyncAnalyzeActionsLROPollingMethod. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of AsyncAnalyzeBatchActionsLROPoller that returns either AnalyzeJobState or the result of cls(response) - :rtype: ~....._async_lro.AsyncAnalyzeBatchActionsLROPoller[~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeJobState] + :return: An instance of AsyncAnalyzeActionsLROPoller that returns either AnalyzeJobState or the result of cls(response) + :rtype: ~....._async_lro.AsyncAnalyzeActionsLROPoller[~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeJobState] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] @@ -132,18 +132,18 @@ def get_long_running_output(pipeline_response): 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } - if polling is True: polling_method = AsyncAnalyzeBatchActionsLROPollingMethod(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + if polling is True: polling_method = AsyncAnalyzeActionsLROPollingMethod(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: - return AsyncAnalyzeBatchActionsLROPoller.from_continuation_token( + return AsyncAnalyzeActionsLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: - return AsyncAnalyzeBatchActionsLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncAnalyzeActionsLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_analyze.metadata = {'url': '/analyze'} # type: ignore async def analyze_status( @@ -480,7 +480,7 @@ async def begin_health( string_index_type: Optional[Union[str, "_models.StringIndexType"]] = None, logging_opt_out: Optional[bool] = None, **kwargs - ) -> AnalyzeHealthcareEntitiesAsyncLROPoller["_models.HealthcareJobState"]: + ) -> AsyncAnalyzeHealthcareEntitiesLROPoller["_models.HealthcareJobState"]: """Submit healthcare analysis job. Start a healthcare analysis job to recognize healthcare related entities (drugs, conditions, @@ -505,12 +505,12 @@ async def begin_health( :type logging_opt_out: bool :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AnalyzeHealthcareEntitiesAsyncLROPollingMethod. + :keyword polling: By default, your polling method will be AsyncAnalyzeHealthcareEntitiesLROPollingMethod. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of AnalyzeHealthcareEntitiesAsyncLROPoller that returns either HealthcareJobState or the result of cls(response) - :rtype: ~....._async_lro.AnalyzeHealthcareEntitiesAsyncLROPoller[~azure.ai.textanalytics.v3_1_preview_5.models.HealthcareJobState] + :return: An instance of AsyncAnalyzeHealthcareEntitiesLROPoller that returns either HealthcareJobState or the result of cls(response) + :rtype: ~....._async_lro.AsyncAnalyzeHealthcareEntitiesLROPoller[~azure.ai.textanalytics.v3_1_preview_5.models.HealthcareJobState] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] @@ -544,18 +544,18 @@ def get_long_running_output(pipeline_response): 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } - if polling is True: polling_method = AnalyzeHealthcareEntitiesAsyncLROPollingMethod(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + if polling is True: polling_method = AsyncAnalyzeHealthcareEntitiesLROPollingMethod(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: - return AnalyzeHealthcareEntitiesAsyncLROPoller.from_continuation_token( + return AsyncAnalyzeHealthcareEntitiesLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: - return AnalyzeHealthcareEntitiesAsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AsyncAnalyzeHealthcareEntitiesLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_health.metadata = {'url': '/entities/health/jobs'} # type: ignore async def entities_recognition_general( diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/v3_1_preview_5/operations/_text_analytics_client_operations.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/v3_1_preview_5/operations/_text_analytics_client_operations.py index 4e4906cf15a1..e54d9dfbecf4 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/v3_1_preview_5/operations/_text_analytics_client_operations.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/v3_1_preview_5/operations/_text_analytics_client_operations.py @@ -8,7 +8,7 @@ from typing import TYPE_CHECKING import warnings -from ...._lro import AnalyzeBatchActionsLROPoller, AnalyzeBatchActionsLROPollingMethod, AnalyzeHealthcareEntitiesLROPoller, AnalyzeHealthcareEntitiesLROPollingMethod +from ...._lro import AnalyzeActionsLROPoller, AnalyzeActionsLROPollingMethod, AnalyzeHealthcareEntitiesLROPoller, AnalyzeHealthcareEntitiesLROPollingMethod from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse @@ -92,7 +92,7 @@ def begin_analyze( body=None, # type: Optional["_models.AnalyzeBatchInput"] **kwargs # type: Any ): - # type: (...) -> AnalyzeBatchActionsLROPoller["_models.AnalyzeJobState"] + # type: (...) -> AnalyzeActionsLROPoller["_models.AnalyzeJobState"] """Submit analysis job. Submit a collection of text documents for analysis. Specify one or more unique tasks to be @@ -102,12 +102,12 @@ def begin_analyze( :type body: ~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeBatchInput :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. - :keyword polling: By default, your polling method will be AnalyzeBatchActionsLROPollingMethod. + :keyword polling: By default, your polling method will be AnalyzeActionsLROPollingMethod. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.PollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - :return: An instance of AnalyzeBatchActionsLROPoller that returns either AnalyzeJobState or the result of cls(response) - :rtype: ~...._lro.AnalyzeBatchActionsLROPoller[~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeJobState] + :return: An instance of AnalyzeActionsLROPoller that returns either AnalyzeJobState or the result of cls(response) + :rtype: ~...._lro.AnalyzeActionsLROPoller[~azure.ai.textanalytics.v3_1_preview_5.models.AnalyzeJobState] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod] @@ -138,18 +138,18 @@ def get_long_running_output(pipeline_response): 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } - if polling is True: polling_method = AnalyzeBatchActionsLROPollingMethod(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + if polling is True: polling_method = AnalyzeActionsLROPollingMethod(lro_delay, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = NoPolling() else: polling_method = polling if cont_token: - return AnalyzeBatchActionsLROPoller.from_continuation_token( + return AnalyzeActionsLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: - return AnalyzeBatchActionsLROPoller(self._client, raw_result, get_long_running_output, polling_method) + return AnalyzeActionsLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_analyze.metadata = {'url': '/analyze'} # type: ignore def analyze_status( diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_lro.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_lro.py index e300b2eee949..75541e8ad964 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_lro.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_lro.py @@ -3,7 +3,9 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ +from typing import TYPE_CHECKING, Generic from six.moves.urllib.parse import urlencode +from azure.core.polling._poller import PollingReturnType from azure.core.exceptions import HttpResponseError from azure.core.polling import LROPoller from azure.core.polling.base_polling import LROBasePolling, OperationResourcePolling, OperationFailed, BadStatus @@ -12,6 +14,10 @@ _FAILED = frozenset(["failed"]) _SUCCEEDED = frozenset(["succeeded", "partiallycompleted"]) +if TYPE_CHECKING: + from typing import Any, Optional + import datetime + class TextAnalyticsOperationResourcePolling(OperationResourcePolling): def __init__(self, operation_location_header="operation-location", show_stats=False): @@ -32,6 +38,7 @@ def get_polling_url(self): class TextAnalyticsLROPollingMethod(LROBasePolling): def finished(self): """Is this polling finished? + :rtype: bool """ return TextAnalyticsLROPollingMethod._finished(self.status()) @@ -125,28 +132,56 @@ def id(self): return self._current_body.job_id -class AnalyzeHealthcareEntitiesLROPoller(LROPoller): +class AnalyzeHealthcareEntitiesLROPoller(LROPoller, Generic[PollingReturnType]): + + def polling_method(self): + # type: () -> AnalyzeHealthcareEntitiesLROPollingMethod + """Return the polling method associated to this poller. + """ + return self._polling_method # type: ignore @property def created_on(self): - return self._polling_method.created_on + # type: () -> datetime.datetime + """When your healthcare entities job was created + + :return: When your healthcare entities job was created + :rtype: ~datetime.datetime + """ + return self.polling_method().created_on @property def expires_on(self): - return self._polling_method.expires_on + # type: () -> datetime.datetime + """When your healthcare entities job will expire + + :return: When your healthcare entities job will expire + :rtype: ~datetime.datetime + """ + return self.polling_method().expires_on @property def last_modified_on(self): - return self._polling_method.last_modified_on + # type: () -> datetime.datetime + """When your healthcare entities job was last modified + + :return: When your healthcare entities job was last modified + :rtype: ~datetime.datetime + """ + return self.polling_method().last_modified_on @property def id(self): - return self._polling_method.id + # type: () -> str + """ID of your call to :func:`begin_analyze_healthcare_entities` + + :return: ID of your call to :func:`begin_analyze_healthcare_entities` + :rtype: str + """ + return self.polling_method().id - def cancel( # type: ignore - self, - **kwargs - ): # type: (...) -> LROPoller[None] + def cancel(self, **kwargs): # type: ignore + # type: (Any) -> AnalyzeHealthcareEntitiesLROPoller[None] """Cancel the operation currently being polled. :keyword int polling_interval: The polling interval to use to poll the cancellation status. @@ -182,7 +217,7 @@ def cancel( # type: ignore from ._response_handlers import process_http_response_error process_http_response_error(error) -class AnalyzeBatchActionsLROPollingMethod(TextAnalyticsLROPollingMethod): +class AnalyzeActionsLROPollingMethod(TextAnalyticsLROPollingMethod): @property def _current_body(self): @@ -244,40 +279,103 @@ def id(self): return self._current_body.job_id -class AnalyzeBatchActionsLROPoller(LROPoller): +class AnalyzeActionsLROPoller(LROPoller, Generic[PollingReturnType]): + + def polling_method(self): + # type: () -> AnalyzeActionsLROPollingMethod + """Return the polling method associated to this poller. + """ + return self._polling_method # type: ignore @property def created_on(self): - return self._polling_method.created_on + # type: () -> datetime.datetime + """When your analyze job was created + + :return: When your analyze job was created + :rtype: ~datetime.datetime + """ + return self.polling_method().created_on @property def expires_on(self): - return self._polling_method.expires_on + # type: () -> datetime.datetime + """When your analyze job will expire + + :return: When your analyze job will expire + :rtype: ~datetime.datetime + """ + return self.polling_method().expires_on @property def display_name(self): - return self._polling_method.display_name + # type: () -> Optional[str] + """The display name of your :func:`begin_analyze_actions` call. + + Corresponds to the `display_name` kwarg you pass to your + :func:`begin_analyze_actions` call. + + :return: The display name of your :func:`begin_analyze_actions` call. + :rtype: str + """ + return self.polling_method().display_name @property def actions_failed_count(self): - return self._polling_method.actions_failed_count + # type: () -> int + """Total number of actions that have failed + + :return: Total number of actions that have failed + :rtype: int + """ + return self.polling_method().actions_failed_count @property def actions_in_progress_count(self): - return self._polling_method.actions_in_progress_count + # type: () -> int + """Total number of actions currently in progress + + :return: Total number of actions currently in progress + :rtype: int + """ + return self.polling_method().actions_in_progress_count @property def actions_succeeded_count(self): - return self._polling_method.actions_succeeded_count + # type: () -> int + """Total number of actions that succeeded + + :return: Total number of actions that succeeded + :rtype: int + """ + return self.polling_method().actions_succeeded_count @property def last_modified_on(self): - return self._polling_method.last_modified_on + # type: () -> datetime.datetime + """The last time your actions results were updated + + :return: The last time your actions results were updated + :rtype: ~datetime.datetime + """ + return self.polling_method().last_modified_on @property def total_actions_count(self): - return self._polling_method.total_actions_count + # type: () -> int + """Total number of actions you submitted + + :return: Total number of actions submitted + :rtype: int + """ + return self.polling_method().total_actions_count @property def id(self): - return self._polling_method.id + # type: () -> str + """ID of your :func:`begin_analyze_actions` call. + + :return: ID of your :func:`begin_analyze_actions` call. + :rtype: str + """ + return self.polling_method().id diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_models.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_models.py index ddee9b6e11df..e72b41de3c7c 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_models.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_models.py @@ -1379,24 +1379,19 @@ class AnalyzeActionsResult(DictMixin): :vartype action_type: str or ~azure.ai.textanalytics.AnalyzeActionsType :ivar ~datetime.datetime completed_on: Date and time (UTC) when the result completed on the service. - :ivar statistics: Overall statistics for the action result. - :vartype statistics: ~azure.ai.RequestStatistics """ def __init__(self, **kwargs): self.document_results = kwargs.get("document_results") self.is_error = False self.action_type = kwargs.get("action_type") self.completed_on = kwargs.get("completed_on") - self.statistics = kwargs.get("statistics") def __repr__(self): - return "AnalyzeActionsResult(document_results={}, is_error={}, action_type={}, completed_on={}, " \ - "statistics={})".format( + return "AnalyzeActionsResult(document_results={}, is_error={}, action_type={}, completed_on={})".format( repr(self.document_results), self.is_error, self.action_type, self.completed_on, - repr(self.statistics) )[:1024] @@ -1718,29 +1713,3 @@ def to_generated(self): logging_opt_out=self.disable_service_logs, ) ) - - -class RequestStatistics(DictMixin): - def __init__(self, **kwargs): - self.documents_count = kwargs.get("documents_count") - self.valid_documents_count = kwargs.get("valid_documents_count") - self.erroneous_documents_count = kwargs.get("erroneous_documents_count") - self.transactions_count = kwargs.get("transactions_count") - - @classmethod - def _from_generated(cls, request_statistics): - return cls( - documents_count=request_statistics.documents_count, - valid_documents_count=request_statistics.valid_documents_count, - erroneous_documents_count=request_statistics.erroneous_documents_count, - transactions_count=request_statistics.transactions_count - ) - - def __repr__(self, **kwargs): - return "RequestStatistics(documents_count={}, valid_documents_count={}, erroneous_documents_count={}, " \ - "transactions_count={})".format( - self.documents_count, - self.valid_documents_count, - self.erroneous_documents_count, - self.transactions_count - )[:1024] diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_response_handlers.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_response_handlers.py index b98fb085829d..9af6d2a069ca 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_response_handlers.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_response_handlers.py @@ -33,7 +33,6 @@ PiiEntity, AnalyzeHealthcareEntitiesResult, AnalyzeActionsResult, - RequestStatistics, AnalyzeActionsType, AnalyzeActionsError, _get_indices, @@ -262,9 +261,6 @@ def _get_good_result(current_task_type, index_of_task_result, doc_id_order, resp ) return AnalyzeActionsResult( document_results=document_results, - statistics=RequestStatistics._from_generated( # pylint: disable=protected-access - response_task_to_deserialize.results.statistics - ) if response_task_to_deserialize.results.statistics else None, action_type=current_task_type, completed_on=response_task_to_deserialize.last_update_date_time, ) diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_response_handlers_async.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_response_handlers_async.py index 95a2ed2df10e..682baeba6b4c 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_response_handlers_async.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_response_handlers_async.py @@ -9,7 +9,6 @@ from urllib.parse import urlparse, parse_qsl from azure.core.async_paging import AsyncList, AsyncItemPaged -from ._models import RequestStatistics from ._response_handlers import healthcare_result, get_iter_items diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_text_analytics_client.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_text_analytics_client.py index 668e4a23e4d6..90ed6e9743e5 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_text_analytics_client.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_text_analytics_client.py @@ -4,9 +4,8 @@ # Licensed under the MIT License. # ------------------------------------ import copy -from typing import ( # pylint: disable=unused-import +from typing import ( Union, - Optional, Any, List, Dict, @@ -14,7 +13,6 @@ ) from functools import partial from azure.core.paging import ItemPaged -from azure.core.polling import LROPoller from azure.core.tracing.decorator import distributed_trace from azure.core.exceptions import HttpResponseError from ._base_client import TextAnalyticsClientBase @@ -39,7 +37,7 @@ from ._lro import ( TextAnalyticsOperationResourcePolling, - AnalyzeBatchActionsLROPollingMethod, + AnalyzeActionsLROPollingMethod, AnalyzeHealthcareEntitiesLROPollingMethod, ) @@ -63,6 +61,7 @@ AnalyzeHealthcareEntitiesResult, AnalyzeActionsResult, ) + from ._lro import AnalyzeHealthcareEntitiesLROPoller, AnalyzeActionsLROPoller class TextAnalyticsClient(TextAnalyticsClientBase): @@ -508,7 +507,7 @@ def begin_analyze_healthcare_entities( # type: ignore self, documents, # type: Union[List[str], List[TextDocumentInput], List[Dict[str, str]]] **kwargs # type: Any - ): # type: (...) -> LROPoller[ItemPaged[AnalyzeHealthcareEntitiesResult]] + ): # type: (...) -> AnalyzeHealthcareEntitiesLROPoller[ItemPaged[AnalyzeHealthcareEntitiesResult]] """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, @@ -555,7 +554,7 @@ def begin_analyze_healthcare_entities( # type: ignore :return: An instance of an AnalyzeHealthcareEntitiesLROPoller. Call `result()` on the this object to return a pageable of :class:`~azure.ai.textanalytics.AnalyzeHealthcareEntitiesResult`. :rtype: - ~azure.core.polling.LROPoller[~azure.core.paging.ItemPaged[ + ~azure.ai.textanalytics.AnalyzeHealthcareEntitiesLROPoller[~azure.core.paging.ItemPaged[ ~azure.ai.textanalytics.AnalyzeHealthcareEntitiesResult]] :raises ~azure.core.exceptions.HttpResponseError or TypeError or ValueError or NotImplementedError: @@ -826,7 +825,7 @@ def begin_analyze_actions( # type: ignore documents, # type: Union[List[str], List[TextDocumentInput], List[Dict[str, str]]] actions, # type: List[Union[RecognizeEntitiesAction, RecognizeLinkedEntitiesAction, RecognizePiiEntitiesAction, ExtractKeyPhrasesAction, AnalyzeSentimentAction]] # pylint: disable=line-too-long **kwargs # type: Any - ): # type: (...) -> LROPoller[ItemPaged[AnalyzeActionsResult]] + ): # type: (...) -> AnalyzeActionsLROPoller[ItemPaged[AnalyzeActionsResult]] """Start a long-running operation to perform a variety of text analysis actions over a batch of documents. :param documents: The set of documents to process as part of this batch. @@ -853,11 +852,11 @@ def begin_analyze_actions( # type: ignore :keyword bool show_stats: If set to true, response will contain document level statistics. :keyword int polling_interval: Waiting time between two polls for LRO operations if no Retry-After header is present. Defaults to 30 seconds. - :return: An instance of an LROPoller. Call `result()` on the poller + :return: An instance of an AnalyzeActionsLROPoller. Call `result()` on the poller object to return a pageable heterogeneous list of the action results in the order the actions were sent in this method. :rtype: - ~azure.core.polling.LROPoller[~azure.core.paging.ItemPaged[ + ~azure.ai.textanalytics.AnalyzeActionsLROPoller[~azure.core.paging.ItemPaged[ ~azure.ai.textanalytics.AnalyzeActionsResult]] :raises ~azure.core.exceptions.HttpResponseError or TypeError or ValueError or NotImplementedError: @@ -921,7 +920,7 @@ def begin_analyze_actions( # type: ignore cls=kwargs.pop("cls", partial( self._analyze_result_callback, doc_id_order, task_order, show_stats=show_stats )), - polling=AnalyzeBatchActionsLROPollingMethod( + polling=AnalyzeActionsLROPollingMethod( timeout=polling_interval, lro_algorithms=[ TextAnalyticsOperationResourcePolling(show_stats=show_stats) diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/__init__.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/__init__.py index 08ea8acd7812..a0af0804b106 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/__init__.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/__init__.py @@ -5,7 +5,13 @@ # ------------------------------------ from ._text_analytics_client_async import TextAnalyticsClient +from ._lro_async import ( + AsyncAnalyzeHealthcareEntitiesLROPoller, + AsyncAnalyzeActionsLROPoller, +) __all__ = [ 'TextAnalyticsClient', + 'AsyncAnalyzeHealthcareEntitiesLROPoller', + 'AsyncAnalyzeActionsLROPoller', ] diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_async_lro.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_lro_async.py similarity index 59% rename from sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_async_lro.py rename to sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_lro_async.py index 475a2ebc2b69..5a98528fa85b 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_async_lro.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_lro_async.py @@ -3,7 +3,8 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ - +import datetime +from typing import Optional from azure.core.exceptions import HttpResponseError from azure.core.polling import AsyncLROPoller from azure.core.polling.base_polling import OperationFailed, BadStatus @@ -77,15 +78,15 @@ async def _poll(self): # pylint:disable=invalid-overridden-method self._pipeline_response.http_response ) -class AnalyzeHealthcareEntitiesAsyncLROPollingMethod(TextAnalyticsAsyncLROPollingMethod): +class AsyncAnalyzeHealthcareEntitiesLROPollingMethod(TextAnalyticsAsyncLROPollingMethod): def __init__(self, *args, **kwargs): self._text_analytics_client = kwargs.pop("text_analytics_client") - super(AnalyzeHealthcareEntitiesAsyncLROPollingMethod, self).__init__(*args, **kwargs) + super(AsyncAnalyzeHealthcareEntitiesLROPollingMethod, self).__init__(*args, **kwargs) @property def _current_body(self): - from ._generated.v3_1_preview_5.models import JobMetadata + from .._generated.v3_1_preview_5.models import JobMetadata return JobMetadata.deserialize(self._pipeline_response) @property @@ -113,28 +114,53 @@ def id(self): return self._current_body.job_id -class AnalyzeHealthcareEntitiesAsyncLROPoller(AsyncLROPoller[PollingReturnType]): +class AsyncAnalyzeHealthcareEntitiesLROPoller(AsyncLROPoller[PollingReturnType]): + + def polling_method(self) -> AsyncAnalyzeHealthcareEntitiesLROPollingMethod: # type: ignore + """Return the polling method associated to this poller. + """ + return self._polling_method # type: ignore @property - def created_on(self): - return self._polling_method.created_on + def created_on(self) -> datetime.datetime: + """When your healthcare entities job was created + + :return: When your healthcare entities job was created + :rtype: ~datetime.datetime + """ + return self.polling_method().created_on @property - def expires_on(self): - return self._polling_method.expires_on + def expires_on(self) -> datetime.datetime: + """When your healthcare entities job will expire + + :return: When your healthcare entities job will expire + :rtype: ~datetime.datetime + """ + return self.polling_method().expires_on @property - def last_modified_on(self): - return self._polling_method.last_modified_on + def last_modified_on(self) -> datetime.datetime: + """When your healthcare entities job was last modified + + :return: When your healthcare entities job was last modified + :rtype: ~datetime.datetime + """ + return self.polling_method().last_modified_on @property - def id(self): - return self._polling_method.id + def id(self) -> str: + """ID of your call to :func:`begin_analyze_healthcare_entities` + + :return: ID of your call to :func:`begin_analyze_healthcare_entities` + :rtype: str + """ + return self.polling_method().id async def cancel( # type: ignore self, **kwargs - ): + ) -> "AsyncAnalyzeHealthcareEntitiesLROPoller[None]": """Cancel the operation currently being polled. :keyword int polling_interval: The polling interval to use to poll the cancellation status. @@ -153,7 +179,7 @@ async def cancel( # type: ignore :caption: Cancel an existing health operation. """ polling_interval = kwargs.pop("polling_interval", 5) - await self._polling_method.update_status() + await self.polling_method().update_status() try: return await getattr(self._polling_method, "_text_analytics_client").begin_cancel_health_job( @@ -162,15 +188,15 @@ async def cancel( # type: ignore ) except HttpResponseError as error: - from ._response_handlers import process_http_response_error + from .._response_handlers import process_http_response_error process_http_response_error(error) -class AsyncAnalyzeBatchActionsLROPollingMethod(TextAnalyticsAsyncLROPollingMethod): +class AsyncAnalyzeActionsLROPollingMethod(TextAnalyticsAsyncLROPollingMethod): @property def _current_body(self): - from ._generated.v3_1_preview_5.models import AnalyzeJobMetadata + from .._generated.v3_1_preview_5.models import AnalyzeJobMetadata return AnalyzeJobMetadata.deserialize(self._pipeline_response) @property @@ -228,40 +254,93 @@ def id(self): return self._current_body.job_id -class AsyncAnalyzeBatchActionsLROPoller(AsyncLROPoller[PollingReturnType]): +class AsyncAnalyzeActionsLROPoller(AsyncLROPoller[PollingReturnType]): + + def polling_method(self) -> AsyncAnalyzeActionsLROPollingMethod: # type: ignore + """Return the polling method associated to this poller. + """ + return self._polling_method # type: ignore @property - def created_on(self): - return self._polling_method.created_on + def created_on(self) -> datetime.datetime: + """When your analyze job was created + + :return: When your analyze job was created + :rtype: ~datetime.datetime + """ + return self.polling_method().created_on @property - def display_name(self): - return self._polling_method.display_name + def display_name(self) -> Optional[str]: + """The display name of your :func:`begin_analyze_actions` call. + + Corresponds to the `display_name` kwarg you pass to your + :func:`begin_analyze_actions` call. + + :return: The display name of your :func:`begin_analyze_actions` call. + :rtype: str + """ + return self.polling_method().display_name @property - def expires_on(self): - return self._polling_method.expires_on + def expires_on(self) -> datetime.datetime: + """When your analyze job will expire + + :return: When your analyze job will expire + :rtype: ~datetime.datetime + """ + return self.polling_method().expires_on @property - def actions_failed_count(self): - return self._polling_method.actions_failed_count + def actions_failed_count(self) -> int: + """Total number of actions that have failed + + :return: Total number of actions that have failed + :rtype: int + """ + return self.polling_method().actions_failed_count @property - def actions_in_progress_count(self): - return self._polling_method.actions_in_progress_count + def actions_in_progress_count(self) -> int: + """Total number of actions currently in progress + + :return: Total number of actions currently in progress + :rtype: int + """ + return self.polling_method().actions_in_progress_count @property - def actions_succeeded_count(self): - return self._polling_method.actions_succeeded_count + def actions_succeeded_count(self) -> int: + """Total number of actions that succeeded + + :return: Total number of actions that succeeded + :rtype: int + """ + return self.polling_method().actions_succeeded_count @property - def last_modified_on(self): - return self._polling_method.last_modified_on + def last_modified_on(self) -> datetime.datetime: + """The last time your actions results were updated + + :return: The last time your actions results were updated + :rtype: ~datetime.datetime + """ + return self.polling_method().last_modified_on @property - def total_actions_count(self): - return self._polling_method.total_actions_count + def total_actions_count(self) -> int: + """Total number of actions you submitted + + :return: Total number of actions submitted + :rtype: int + """ + return self.polling_method().total_actions_count @property - def id(self): - return self._polling_method.id + def id(self) -> str: + """ID of your :func:`begin_analyze_actions` call. + + :return: ID of your :func:`begin_analyze_actions` call. + :rtype: str + """ + return self.polling_method().id diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_text_analytics_client_async.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_text_analytics_client_async.py index 6bec34f39db5..d212d26a33b7 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_text_analytics_client_async.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_text_analytics_client_async.py @@ -4,19 +4,18 @@ # Licensed under the MIT License. # ------------------------------------ import copy -from typing import ( # pylint: disable=unused-import +from typing import ( Union, - Optional, Any, List, Dict, TYPE_CHECKING ) from functools import partial -from azure.core.polling import AsyncLROPoller from azure.core.async_paging import AsyncItemPaged from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.exceptions import HttpResponseError +from azure.core.credentials import AzureKeyCredential from ._base_client_async import AsyncTextAnalyticsClientBase from .._request_handlers import _validate_input, _determine_action_type, _check_string_index_type_arg from .._response_handlers import ( @@ -45,18 +44,19 @@ AnalyzeActionsResult, AnalyzeActionsType, RecognizeLinkedEntitiesAction, - AnalyzeSentimentAction + AnalyzeSentimentAction, + AnalyzeHealthcareEntitiesResult, ) from .._lro import TextAnalyticsOperationResourcePolling -from .._async_lro import ( - AnalyzeHealthcareEntitiesAsyncLROPollingMethod, - AsyncAnalyzeBatchActionsLROPollingMethod +from ._lro_async import ( + AsyncAnalyzeHealthcareEntitiesLROPollingMethod, + AsyncAnalyzeActionsLROPollingMethod, + AsyncAnalyzeHealthcareEntitiesLROPoller, + AsyncAnalyzeActionsLROPoller, ) if TYPE_CHECKING: from azure.core.credentials_async import AsyncTokenCredential - from azure.core.credentials import AzureKeyCredential - from .._models import AnalyzeHealthcareEntitiesResult class TextAnalyticsClient(AsyncTextAnalyticsClientBase): @@ -682,9 +682,9 @@ def _healthcare_result_callback(self, doc_id_order, raw_response, _, headers, sh @distributed_trace_async async def begin_analyze_healthcare_entities( # type: ignore self, - documents, # type: Union[List[str], List[TextDocumentInput], List[Dict[str, str]]] - **kwargs # type: Any - ): # type: (...) -> AsyncLROPoller[AsyncItemPaged[AnalyzeHealthcareEntitiesResult]] + documents: Union[List[str], List[TextDocumentInput], List[Dict[str, str]]], + **kwargs: Any, + ) -> AsyncAnalyzeHealthcareEntitiesLROPoller[AsyncItemPaged[AnalyzeHealthcareEntitiesResult]]: """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, @@ -727,10 +727,10 @@ async def begin_analyze_healthcare_entities( # type: ignore 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. - :return: An instance of an AnalyzeHealthcareEntitiesAsyncLROPoller. Call `result()` on the poller + :return: An instance of an AsyncAnalyzeHealthcareEntitiesLROPoller. Call `result()` on the poller object to return a pageable of :class:`~azure.ai.textanalytics.AnalyzeHealthcareResultItem`. :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.core.paging.AsyncItemPaged[ + ~azure.ai.textanalytics.aio.AsyncAnalyzeHealthcareEntitiesLROPoller[~azure.core.paging.AsyncItemPaged[ ~azure.ai.textanalytics.AnalyzeHealthcareEntitiesResult]] :raises ~azure.core.exceptions.HttpResponseError or TypeError or ValueError or NotImplementedError: @@ -767,7 +767,7 @@ async def begin_analyze_healthcare_entities( # type: ignore model_version=model_version, string_index_type=string_index_type, cls=my_cls, - polling=AnalyzeHealthcareEntitiesAsyncLROPollingMethod( + polling=AsyncAnalyzeHealthcareEntitiesLROPollingMethod( text_analytics_client=self._client, timeout=polling_interval, lro_algorithms=[ @@ -805,10 +805,10 @@ def _analyze_result_callback(self, doc_id_order, task_order, raw_response, _, he @distributed_trace_async async def begin_analyze_actions( # type: ignore self, - documents, # type: Union[List[str], List[TextDocumentInput], List[Dict[str, str]]] - actions, # type: List[Union[RecognizeEntitiesAction, RecognizeLinkedEntitiesAction, RecognizePiiEntitiesAction, ExtractKeyPhrasesAction, AnalyzeSentimentAction]] # pylint: disable=line-too-long - **kwargs # type: Any - ): # type: (...) -> AsyncLROPoller[AsyncItemPaged[AnalyzeActionsResult]] + documents: Union[List[str], List[TextDocumentInput], List[Dict[str, str]]], + actions: List[Union[RecognizeEntitiesAction, RecognizeLinkedEntitiesAction, RecognizePiiEntitiesAction, ExtractKeyPhrasesAction, AnalyzeSentimentAction]], # pylint: disable=line-too-long + **kwargs: Any + ) -> AsyncAnalyzeActionsLROPoller[AsyncItemPaged[AnalyzeActionsResult]]: """Start a long-running operation to perform a variety of text analysis actions over a batch of documents. :param documents: The set of documents to process as part of this batch. @@ -835,11 +835,11 @@ async def begin_analyze_actions( # type: ignore :keyword bool show_stats: If set to true, response will contain document level statistics. :keyword int polling_interval: Waiting time between two polls for LRO operations if no Retry-After header is present. Defaults to 30 seconds. - :return: An instance of an LROPoller. Call `result()` on the poller + :return: An instance of an AsyncAnalyzeActionsLROPoller. Call `result()` on the poller object to return a pageable heterogeneous list of the action results in the order the actions were sent in this method. :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.core.async_paging.AsyncItemPaged[ + ~azure.ai.textanalytics.aio.AsyncAnalyzeActionsLROPoller[~azure.core.async_paging.AsyncItemPaged[ ~azure.ai.textanalytics.AnalyzeActionsResult]] :raises ~azure.core.exceptions.HttpResponseError or TypeError or ValueError or NotImplementedError: @@ -903,7 +903,7 @@ async def begin_analyze_actions( # type: ignore cls=kwargs.pop("cls", partial( self._analyze_result_callback, doc_id_order, task_order, show_stats=show_stats )), - polling=AsyncAnalyzeBatchActionsLROPollingMethod( + polling=AsyncAnalyzeActionsLROPollingMethod( timeout=polling_interval, lro_algorithms=[ TextAnalyticsOperationResourcePolling(show_stats=show_stats) diff --git a/sdk/textanalytics/azure-ai-textanalytics/swagger/README.md b/sdk/textanalytics/azure-ai-textanalytics/swagger/README.md index dce6bf058f04..43b4dcbc80d2 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/swagger/README.md +++ b/sdk/textanalytics/azure-ai-textanalytics/swagger/README.md @@ -26,14 +26,14 @@ multiapi: true ```yaml $(multiapi) batch: - - tag: release_3_0 - - tag: release_3_1_preview.5 - - multiapiscript: true + - tag: release_3_0 + - tag: release_3_1_preview.5 + - multiapiscript: true ``` ## Multiapiscript -``` yaml $(multiapiscript) +```yaml $(multiapiscript) output-folder: ../azure/ai/textanalytics/_generated/ default-api: v3_0 clear-output-folder: false @@ -44,7 +44,7 @@ perform-load: false These settings apply only when `--tag=release_3_0` is specified on the command line. -``` yaml $(tag) == 'release_3_0' +```yaml $(tag) == 'release_3_0' input-file: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cognitiveservices/data-plane/TextAnalytics/stable/v3.0/TextAnalytics.json namespace: azure.ai.textanalytics.v3_0 output-folder: ../azure/ai/textanalytics/_generated/v3_0 @@ -62,29 +62,28 @@ output-folder: ../azure/ai/textanalytics/_generated/v3_1_preview_5 ### Override Analyze's pager poller -``` yaml +```yaml directive: - - from: swagger-document - where: '$.paths["/analyze"].post' - transform: > - $["responses"]["200"] = {"description": "dummy schema", "schema": {"$ref": "#/definitions/AnalyzeJobState"}}; - $["x-python-custom-poller-sync"] = "...._lro.AnalyzeBatchActionsLROPoller"; - $["x-python-custom-poller-async"] = "....._async_lro.AsyncAnalyzeBatchActionsLROPoller"; - $["x-python-custom-default-polling-method-sync"] = "...._lro.AnalyzeBatchActionsLROPollingMethod"; - $["x-python-custom-default-polling-method-async"] = "....._async_lro.AsyncAnalyzeBatchActionsLROPollingMethod"; + - from: swagger-document + where: '$.paths["/analyze"].post' + transform: > + $["responses"]["200"] = {"description": "dummy schema", "schema": {"$ref": "#/definitions/AnalyzeJobState"}}; + $["x-python-custom-poller-sync"] = "...._lro.AnalyzeActionsLROPoller"; + $["x-python-custom-poller-async"] = ".....aio._lro_async.AsyncAnalyzeActionsLROPoller"; + $["x-python-custom-default-polling-method-sync"] = "...._lro.AnalyzeActionsLROPollingMethod"; + $["x-python-custom-default-polling-method-async"] = ".....aio._lro_async.AsyncAnalyzeActionsLROPollingMethod"; ``` - ### Override Healthcare's poller -``` yaml +```yaml directive: - - from: swagger-document - where: '$.paths["/entities/health/jobs"].post' - transform: > - $["responses"]["200"] = {"description": "dummy schema", "schema": {"$ref": "#/definitions/HealthcareJobState"}}; - $["x-python-custom-poller-sync"] = "...._lro.AnalyzeHealthcareEntitiesLROPoller"; - $["x-python-custom-poller-async"] = "....._async_lro.AnalyzeHealthcareEntitiesAsyncLROPoller"; - $["x-python-custom-default-polling-method-sync"] = "...._lro.AnalyzeHealthcareEntitiesLROPollingMethod"; - $["x-python-custom-default-polling-method-async"] = "....._async_lro.AnalyzeHealthcareEntitiesAsyncLROPollingMethod"; + - from: swagger-document + where: '$.paths["/entities/health/jobs"].post' + transform: > + $["responses"]["200"] = {"description": "dummy schema", "schema": {"$ref": "#/definitions/HealthcareJobState"}}; + $["x-python-custom-poller-sync"] = "...._lro.AnalyzeHealthcareEntitiesLROPoller"; + $["x-python-custom-poller-async"] = ".....aio._lro_async.AsyncAnalyzeHealthcareEntitiesLROPoller"; + $["x-python-custom-default-polling-method-sync"] = "...._lro.AnalyzeHealthcareEntitiesLROPollingMethod"; + $["x-python-custom-default-polling-method-async"] = ".....aio._lro_async.AsyncAnalyzeHealthcareEntitiesLROPollingMethod"; ``` diff --git a/sdk/textanalytics/azure-ai-textanalytics/tests/recordings/test_analyze_healthcare.test_show_stats_and_model_version.yaml b/sdk/textanalytics/azure-ai-textanalytics/tests/recordings/test_analyze_healthcare.test_show_stats_and_model_version.yaml index 40065e19faa5..aded6666668a 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/tests/recordings/test_analyze_healthcare.test_show_stats_and_model_version.yaml +++ b/sdk/textanalytics/azure-ai-textanalytics/tests/recordings/test_analyze_healthcare.test_show_stats_and_model_version.yaml @@ -16,7 +16,7 @@ interactions: Content-Type: - application/json User-Agent: - - azsdk-python-ai-textanalytics/5.1.0b7 Python/3.9.1 (macOS-10.16-x86_64-i386-64bit) + - azsdk-python-ai-textanalytics/5.1.0b8 Python/3.9.1 (macOS-10.16-x86_64-i386-64bit) method: POST uri: https://westus2.api.cognitive.microsoft.com/text/analytics/v3.1-preview.5/entities/health/jobs?model-version=2021-01-11&stringIndexType=UnicodeCodePoint response: @@ -24,11 +24,11 @@ interactions: string: '' headers: apim-request-id: - - b53feac3-c114-4b6e-80dc-dc94f97ae47d + - fcaab22d-7b8e-4aa7-84ca-40c370c056b5 date: - - Tue, 18 May 2021 17:48:37 GMT + - Thu, 03 Jun 2021 15:29:33 GMT operation-location: - - https://westus2.api.cognitive.microsoft.com/text/analytics/v3.1-preview.5/entities/health/jobs/d8e0f4f8-c97a-4a04-9c8a-873c5d8ddcdf + - https://westus2.api.cognitive.microsoft.com/text/analytics/v3.1-preview.5/entities/health/jobs/66c9040d-afc0-44f9-a0b1-0d1517d26a69 strict-transport-security: - max-age=31536000; includeSubDomains; preload transfer-encoding: @@ -36,7 +36,7 @@ interactions: x-content-type-options: - nosniff x-envoy-upstream-service-time: - - '121' + - '11612' status: code: 202 message: Accepted @@ -50,21 +50,21 @@ interactions: Connection: - keep-alive User-Agent: - - azsdk-python-ai-textanalytics/5.1.0b7 Python/3.9.1 (macOS-10.16-x86_64-i386-64bit) + - azsdk-python-ai-textanalytics/5.1.0b8 Python/3.9.1 (macOS-10.16-x86_64-i386-64bit) method: GET - uri: https://westus2.api.cognitive.microsoft.com/text/analytics/v3.1-preview.5/entities/health/jobs/d8e0f4f8-c97a-4a04-9c8a-873c5d8ddcdf?showStats=True + uri: https://westus2.api.cognitive.microsoft.com/text/analytics/v3.1-preview.5/entities/health/jobs/66c9040d-afc0-44f9-a0b1-0d1517d26a69?showStats=True response: body: - string: '{"jobId":"d8e0f4f8-c97a-4a04-9c8a-873c5d8ddcdf","lastUpdateDateTime":"2021-05-18T17:48:38Z","createdDateTime":"2021-05-18T17:48:37Z","expirationDateTime":"2021-05-19T17:48:37Z","status":"succeeded","errors":[],"results":{"statistics":{"documentsCount":5,"validDocumentsCount":4,"erroneousDocumentsCount":1,"transactionsCount":4},"documents":[{"id":"56","statistics":{"charactersCount":2,"transactionsCount":1},"entities":[],"relations":[],"warnings":[]},{"id":"0","statistics":{"charactersCount":2,"transactionsCount":1},"entities":[],"relations":[],"warnings":[]},{"id":"19","statistics":{"charactersCount":2,"transactionsCount":1},"entities":[],"relations":[],"warnings":[]},{"id":"1","statistics":{"charactersCount":2,"transactionsCount":1},"entities":[],"relations":[],"warnings":[]}],"errors":[{"id":"22","error":{"code":"InvalidArgument","message":"Invalid + string: '{"jobId":"66c9040d-afc0-44f9-a0b1-0d1517d26a69","lastUpdateDateTime":"2021-06-03T15:30:02Z","createdDateTime":"2021-06-03T15:29:22Z","expirationDateTime":"2021-06-04T15:29:22Z","status":"succeeded","errors":[],"results":{"statistics":{"documentsCount":5,"validDocumentsCount":4,"erroneousDocumentsCount":1,"transactionsCount":4},"documents":[{"id":"56","statistics":{"charactersCount":2,"transactionsCount":1},"entities":[],"relations":[],"warnings":[]},{"id":"0","statistics":{"charactersCount":2,"transactionsCount":1},"entities":[],"relations":[],"warnings":[]},{"id":"19","statistics":{"charactersCount":2,"transactionsCount":1},"entities":[],"relations":[],"warnings":[]},{"id":"1","statistics":{"charactersCount":2,"transactionsCount":1},"entities":[],"relations":[],"warnings":[]}],"errors":[{"id":"22","error":{"code":"InvalidArgument","message":"Invalid document in request.","innererror":{"code":"InvalidDocument","message":"Document - text is empty."}}}],"modelVersion":"2021-03-01"}}' + text is empty."}}}],"modelVersion":"2021-05-15"}}' headers: apim-request-id: - - 8061ca7c-e462-448e-afca-7d81b779d4fb + - 6bc222a8-f87f-4ea0-bb4e-0148c7ec591e content-type: - application/json; charset=utf-8 date: - - Tue, 18 May 2021 17:48:42 GMT + - Thu, 03 Jun 2021 15:30:18 GMT strict-transport-security: - max-age=31536000; includeSubDomains; preload transfer-encoding: @@ -72,7 +72,7 @@ interactions: x-content-type-options: - nosniff x-envoy-upstream-service-time: - - '70' + - '7758' status: code: 200 message: OK diff --git a/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze_healthcare.py b/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze_healthcare.py index 120398d51040..5f30ede5c8ca 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze_healthcare.py +++ b/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze_healthcare.py @@ -114,8 +114,14 @@ def test_out_of_order_ids(self, client): expected_order = ["56", "0", "22", "19", "1"] actual_order = [x.id for x in response] + num_error = 0 for idx, resp in enumerate(response): - self.assertEqual(resp.id, expected_order[idx]) + assert resp.id == expected_order[idx] + if resp.is_error: + num_error += 1 + continue + assert not resp.statistics + assert num_error == 1 @GlobalTextAnalyticsAccountPreparer() @TextAnalyticsClientPreparer() @@ -133,15 +139,14 @@ def test_show_stats_and_model_version(self, client): polling_interval=self._interval() ).result() - assert response.model_version # commenting out bc of service error, always uses latest https://github.com/Azure/azure-sdk-for-python/issues/17160 - self.assertEqual(response.statistics.documents_count, 5) - self.assertEqual(response.statistics.transactions_count, 4) - self.assertEqual(response.statistics.valid_documents_count, 4) - self.assertEqual(response.statistics.erroneous_documents_count, 1) - + num_error = 0 for doc in response: - if not doc.is_error: - self.assertIsNotNone(doc.statistics) + if doc.is_error: + num_error += 1 + continue + assert doc.statistics.characters_count + assert doc.statistics.transactions_count + assert num_error == 1 @GlobalTextAnalyticsAccountPreparer() @TextAnalyticsClientPreparer() diff --git a/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze_healthcare_async.py b/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze_healthcare_async.py index d769c7e98498..7657c2e17ace 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze_healthcare_async.py +++ b/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze_healthcare_async.py @@ -140,9 +140,14 @@ async def test_out_of_order_ids(self, client): response.append(r) expected_order = ["56", "0", "22", "19", "1"] - actual_order = [x.id for x in response] + num_error = 0 for idx, resp in enumerate(response): - self.assertEqual(resp.id, expected_order[idx]) + assert resp.id == expected_order[idx] + if resp.is_error: + num_error += 1 + continue + assert not resp.statistics + assert num_error == 1 @GlobalTextAnalyticsAccountPreparer() @TextAnalyticsClientPreparer() @@ -161,16 +166,17 @@ async def test_show_stats_and_model_version(self, client): polling_interval=self._interval() )).result() - self.assertIsNotNone(response) - assert response.model_version # commenting out bc of service error, always uses latest https://github.com/Azure/azure-sdk-for-python/issues/17160 - self.assertEqual(response.statistics.documents_count, 5) - self.assertEqual(response.statistics.transactions_count, 4) - self.assertEqual(response.statistics.valid_documents_count, 4) - self.assertEqual(response.statistics.erroneous_documents_count, 1) + assert response + assert not hasattr(response, "statistics") + num_error = 0 async for doc in response: - if not doc.is_error: - self.assertIsNotNone(doc.statistics) + if doc.is_error: + num_error += 1 + continue + assert doc.statistics.characters_count + assert doc.statistics.transactions_count + assert num_error == 1 @GlobalTextAnalyticsAccountPreparer() @TextAnalyticsClientPreparer() diff --git a/sdk/textanalytics/azure-ai-textanalytics/tests/test_repr.py b/sdk/textanalytics/azure-ai-textanalytics/tests/test_repr.py index d898f210c15d..e4eb4e25f8b6 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/tests/test_repr.py +++ b/sdk/textanalytics/azure-ai-textanalytics/tests/test_repr.py @@ -25,20 +25,6 @@ def text_document_statistics(): assert repr(model) == model_repr return model, model_repr -@pytest.fixture -def request_statistics(): - model = _models.RequestStatistics( - documents_count=1, - valid_documents_count=1, - erroneous_documents_count=0, - transactions_count=1 - ) - - model_repr = "RequestStatistics(documents_count=1, valid_documents_count=1, erroneous_documents_count=0, transactions_count=1)" - - assert repr(model) == model_repr - return model, model_repr - @pytest.fixture def text_analytics_warning(): model = _models.TextAnalyticsWarning( @@ -455,18 +441,17 @@ def test_inner_error_takes_precedence(self): assert error.code == "UnsupportedLanguageCode" assert error.message == "Supplied language not supported. Pass in one of: de,en,es,fr,it,ja,ko,nl,pt-PT,zh-Hans,zh-Hant" - def test_analyze_actions_result_recognize_entities(self, recognize_entities_result, request_statistics): + def test_analyze_actions_result_recognize_entities(self, recognize_entities_result): model = _models.AnalyzeActionsResult( document_results=[recognize_entities_result[0]], - statistics=request_statistics[0], is_error=False, action_type=_models.AnalyzeActionsType.RECOGNIZE_ENTITIES, completed_on=datetime.datetime(1, 1, 1) ) model_repr = ( - "AnalyzeActionsResult(document_results=[{}], is_error={}, action_type={}, completed_on={}, statistics={})".format( - recognize_entities_result[1], False, "recognize_entities", datetime.datetime(1, 1, 1), request_statistics[1] + "AnalyzeActionsResult(document_results=[{}], is_error={}, action_type={}, completed_on={})".format( + recognize_entities_result[1], False, "recognize_entities", datetime.datetime(1, 1, 1) ) ) From 8d50d9a9abf9bc70fc2212166d75efa801522439 Mon Sep 17 00:00:00 2001 From: iscai-msft Date: Thu, 3 Jun 2021 14:24:20 -0400 Subject: [PATCH 5/6] fix tests --- .../ai/textanalytics/_text_analytics_client.py | 1 - .../azure-ai-textanalytics/tests/test_analyze.py | 2 +- .../tests/test_analyze_async.py | 2 +- .../azure-ai-textanalytics/tests/test_repr.py | 14 ++++++-------- 4 files changed, 8 insertions(+), 11 deletions(-) diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_text_analytics_client.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_text_analytics_client.py index 90ed6e9743e5..e41ddda9b05a 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_text_analytics_client.py +++ b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_text_analytics_client.py @@ -927,7 +927,6 @@ def begin_analyze_actions( # type: ignore ], **kwargs), continuation_token=continuation_token, - _task_order=task_order, **kwargs ) diff --git a/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze.py b/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze.py index 55819cfad94c..1484add75994 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze.py +++ b/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze.py @@ -389,7 +389,7 @@ def callback(resp): assert all([action_result for action_result in action_results if len(action_result.document_results) == len(docs)]) for action_result in action_results: - assert action_result.statistics + assert not hasattr(action_result, "statistics") for doc in action_result.document_results: assert doc.statistics diff --git a/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze_async.py b/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze_async.py index 32253f51810b..e8bf3cd7d823 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze_async.py +++ b/sdk/textanalytics/azure-ai-textanalytics/tests/test_analyze_async.py @@ -418,7 +418,7 @@ async def test_show_stats_and_model_version_multiple_tasks(self, client): assert all([action_result for action_result in action_results if len(action_result.document_results) == len(docs)]) for action_result in action_results: - assert action_result.statistics + assert not hasattr(action_result, "statistics") for doc in action_result.document_results: assert doc.statistics diff --git a/sdk/textanalytics/azure-ai-textanalytics/tests/test_repr.py b/sdk/textanalytics/azure-ai-textanalytics/tests/test_repr.py index e4eb4e25f8b6..b522be697b19 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/tests/test_repr.py +++ b/sdk/textanalytics/azure-ai-textanalytics/tests/test_repr.py @@ -457,35 +457,33 @@ def test_analyze_actions_result_recognize_entities(self, recognize_entities_resu assert repr(model) == model_repr - def test_analyze_actions_result_recognize_pii_entities(self, recognize_pii_entities_result, request_statistics): + def test_analyze_actions_result_recognize_pii_entities(self, recognize_pii_entities_result): model = _models.AnalyzeActionsResult( document_results=[recognize_pii_entities_result[0]], - statistics=request_statistics[0], is_error=False, action_type=_models.AnalyzeActionsType.RECOGNIZE_PII_ENTITIES, completed_on=datetime.datetime(1, 1, 1) ) model_repr = ( - "AnalyzeActionsResult(document_results=[{}], is_error={}, action_type={}, completed_on={}, statistics={})".format( - recognize_pii_entities_result[1], False, "recognize_pii_entities", datetime.datetime(1, 1, 1), request_statistics[1] + "AnalyzeActionsResult(document_results=[{}], is_error={}, action_type={}, completed_on={})".format( + recognize_pii_entities_result[1], False, "recognize_pii_entities", datetime.datetime(1, 1, 1) ) ) assert repr(model) == model_repr - def test_analyze_actions_result_extract_key_phrases(self, extract_key_phrases_result, request_statistics): + def test_analyze_actions_result_extract_key_phrases(self, extract_key_phrases_result): model = _models.AnalyzeActionsResult( document_results=[extract_key_phrases_result[0]], - statistics=request_statistics[0], is_error=False, action_type=_models.AnalyzeActionsType.EXTRACT_KEY_PHRASES, completed_on=datetime.datetime(1, 1, 1) ) model_repr = ( - "AnalyzeActionsResult(document_results=[{}], is_error={}, action_type={}, completed_on={}, statistics={})".format( - extract_key_phrases_result[1], False, "extract_key_phrases", datetime.datetime(1, 1, 1), request_statistics[1] + "AnalyzeActionsResult(document_results=[{}], is_error={}, action_type={}, completed_on={})".format( + extract_key_phrases_result[1], False, "extract_key_phrases", datetime.datetime(1, 1, 1) ) ) From ad5339fa9bd6a5f24c68c3fa960207963376215e Mon Sep 17 00:00:00 2001 From: iscai-msft Date: Thu, 3 Jun 2021 14:34:26 -0400 Subject: [PATCH 6/6] update changelog --- sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md b/sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md index 5b3bf46ac463..953e4956eeaa 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md +++ b/sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md @@ -11,6 +11,8 @@ - Renamed `AnalyzeBatchActionsResult` to `AnalyzeActionsResult`. - Renamed `AnalyzeBatchActionsError` to `AnalyzeActionsError`. - Renamed `AnalyzeHealthcareEntitiesResultItem` to `AnalyzeHealthcareEntitiesResult`. +- Fixed `AnalyzeHealthcareEntitiesResult`'s `statistics` to be the correct type, `TextDocumentStatistics` +- Remove `RequestStatistics`, use `TextDocumentBatchStatistics` instead **New Features** - Added enums `EntityConditionality`, `EntityCertainty`, and `EntityAssociation`.