diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/__init__.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/__init__.py deleted file mode 100644 index 748335a88191..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/__init__.py +++ /dev/null @@ -1,52 +0,0 @@ -# coding=utf-8 -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -from ._text_analytics_client import TextAnalyticsClient -from ._version import VERSION -from ._models import ( - DetectLanguageInput, - TextDocumentInput, - DetectedLanguage, - DocumentError, - CategorizedEntity, - LinkedEntity, - AnalyzeSentimentResult, - RecognizeEntitiesResult, - DetectLanguageResult, - TextAnalyticsError, - TextAnalyticsWarning, - ExtractKeyPhrasesResult, - RecognizeLinkedEntitiesResult, - TextDocumentStatistics, - LinkedEntityMatch, - TextDocumentBatchStatistics, - SentenceSentiment, - SentimentConfidenceScores -) - -__all__ = [ - 'TextAnalyticsClient', - 'DetectLanguageInput', - 'TextDocumentInput', - 'DetectedLanguage', - 'RecognizeEntitiesResult', - 'DetectLanguageResult', - 'CategorizedEntity', - 'TextAnalyticsError', - 'TextAnalyticsWarning', - 'ExtractKeyPhrasesResult', - 'RecognizeLinkedEntitiesResult', - 'AnalyzeSentimentResult', - 'TextDocumentStatistics', - 'DocumentError', - 'LinkedEntity', - 'LinkedEntityMatch', - 'TextDocumentBatchStatistics', - 'SentenceSentiment', - 'SentimentConfidenceScores' -] - -__version__ = VERSION diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_base_client.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_base_client.py deleted file mode 100644 index cf79ffd26524..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_base_client.py +++ /dev/null @@ -1,51 +0,0 @@ -# coding=utf-8 -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -from azure.core.pipeline.policies import AzureKeyCredentialPolicy -from azure.core.credentials import AzureKeyCredential -from ._policies import TextAnalyticsResponseHookPolicy -from ._user_agent import USER_AGENT -from ._generated import TextAnalyticsClient - -def _authentication_policy(credential): - authentication_policy = None - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if isinstance(credential, AzureKeyCredential): - authentication_policy = AzureKeyCredentialPolicy( - name="Ocp-Apim-Subscription-Key", credential=credential - ) - elif credential is not None and not hasattr(credential, "get_token"): - raise TypeError("Unsupported credential: {}. Use an instance of AzureKeyCredential " - "or a token credential from azure.identity".format(type(credential))) - return authentication_policy - - -class TextAnalyticsClientBase(object): - def __init__(self, endpoint, credential, **kwargs): - self._client = TextAnalyticsClient( - endpoint=endpoint, - credential=credential, - sdk_moniker=USER_AGENT, - authentication_policy=_authentication_policy(credential), - custom_hook_policy=TextAnalyticsResponseHookPolicy(**kwargs), - **kwargs - ) - - - def __enter__(self): - self._client.__enter__() # pylint:disable=no-member - return self - - def __exit__(self, *args): - self._client.__exit__(*args) # pylint:disable=no-member - - def close(self): - # type: () -> None - """Close sockets opened by the client. - Calling this method is unnecessary when using the client as a context manager. - """ - self._client.close() diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/__init__.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/__init__.py deleted file mode 100644 index bab4e1ff9cac..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._text_analytics_client import TextAnalyticsClient -__all__ = ['TextAnalyticsClient'] - -try: - from ._patch import patch_sdk - patch_sdk() -except ImportError: - pass diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/_configuration.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/_configuration.py deleted file mode 100644 index 4870417a532a..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/_configuration.py +++ /dev/null @@ -1,68 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import TYPE_CHECKING - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any - - from azure.core.credentials import TokenCredential - -VERSION = "unknown" - -class TextAnalyticsClientConfiguration(Configuration): - """Configuration for TextAnalyticsClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. - :type credential: ~azure.core.credentials.TokenCredential - :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus.api.cognitive.microsoft.com). - :type endpoint: str - """ - - def __init__( - self, - credential, # type: "TokenCredential" - endpoint, # type: str - **kwargs # type: Any - ): - # type: (...) -> None - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if endpoint is None: - raise ValueError("Parameter 'endpoint' must not be None.") - super(TextAnalyticsClientConfiguration, self).__init__(**kwargs) - - self.credential = credential - self.endpoint = endpoint - self.credential_scopes = ['https://cognitiveservices.azure.com/.default'] - self.credential_scopes.extend(kwargs.pop('credential_scopes', [])) - kwargs.setdefault('sdk_moniker', 'ai-textanalytics/{}'.format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, - **kwargs # type: Any - ): - # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') - if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/_text_analytics_client.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/_text_analytics_client.py deleted file mode 100644 index d54e09733c38..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/_text_analytics_client.py +++ /dev/null @@ -1,60 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import TYPE_CHECKING - -from azure.core import PipelineClient -from msrest import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any - -from ._configuration import TextAnalyticsClientConfiguration -from .operations import TextAnalyticsClientOperationsMixin -from . import models - - -class TextAnalyticsClient(TextAnalyticsClientOperationsMixin): - """The Text Analytics API is a suite of text analytics web services built with best-in-class Microsoft machine learning algorithms. The API can be used to analyze unstructured text for tasks such as sentiment analysis, key phrase extraction and language detection. No training data is needed to use this API; just bring your text data. This API uses advanced natural language processing techniques to deliver best in class predictions. Further documentation can be found in https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview. - - :param credential: Credential needed for the client to connect to Azure. - :type credential: ~azure.core.credentials.TokenCredential - :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus.api.cognitive.microsoft.com). - :type endpoint: str - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - """ - - def __init__( - self, - credential, # type: "TokenCredential" - endpoint, # type: str - **kwargs # type: Any - ): - # type: (...) -> None - base_url = '{Endpoint}/text/analytics/v3.0' - self._config = TextAnalyticsClientConfiguration(credential, endpoint, **kwargs) - self._client = PipelineClient(base_url=base_url, config=self._config, **kwargs) - - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> TextAnalyticsClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/aio/__init__.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/aio/__init__.py deleted file mode 100644 index ffe1820f1f27..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/aio/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._text_analytics_client_async import TextAnalyticsClient -__all__ = ['TextAnalyticsClient'] diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/aio/_configuration_async.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/aio/_configuration_async.py deleted file mode 100644 index 4865a1884975..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/aio/_configuration_async.py +++ /dev/null @@ -1,64 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, TYPE_CHECKING - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core.credentials import TokenCredential - -VERSION = "unknown" - -class TextAnalyticsClientConfiguration(Configuration): - """Configuration for TextAnalyticsClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus.api.cognitive.microsoft.com). - :type endpoint: str - """ - - def __init__( - self, - credential: "AsyncTokenCredential", - endpoint: str, - **kwargs: Any - ) -> None: - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if endpoint is None: - raise ValueError("Parameter 'endpoint' must not be None.") - super(TextAnalyticsClientConfiguration, self).__init__(**kwargs) - - self.credential = credential - self.endpoint = endpoint - self.credential_scopes = ['https://cognitiveservices.azure.com/.default'] - self.credential_scopes.extend(kwargs.pop('credential_scopes', [])) - kwargs.setdefault('sdk_moniker', 'ai-textanalytics/{}'.format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') - if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/aio/_text_analytics_client_async.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/aio/_text_analytics_client_async.py deleted file mode 100644 index de28032b0db2..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/aio/_text_analytics_client_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core import AsyncPipelineClient -from msrest import Deserializer, Serializer - -from ._configuration_async import TextAnalyticsClientConfiguration -from .operations_async import TextAnalyticsClientOperationsMixin -from .. import models - - -class TextAnalyticsClient(TextAnalyticsClientOperationsMixin): - """The Text Analytics API is a suite of text analytics web services built with best-in-class Microsoft machine learning algorithms. The API can be used to analyze unstructured text for tasks such as sentiment analysis, key phrase extraction and language detection. No training data is needed to use this API; just bring your text data. This API uses advanced natural language processing techniques to deliver best in class predictions. Further documentation can be found in https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview. - - :param credential: Credential needed for the client to connect to Azure. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus.api.cognitive.microsoft.com). - :type endpoint: str - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. - """ - - def __init__( - self, - credential: "AsyncTokenCredential", - endpoint: str, - **kwargs: Any - ) -> None: - base_url = '{Endpoint}/text/analytics/v3.0' - self._config = TextAnalyticsClientConfiguration(credential, endpoint, **kwargs) - self._client = AsyncPipelineClient(base_url=base_url, config=self._config, **kwargs) - - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) - - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "TextAnalyticsClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/aio/operations_async/__init__.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/aio/operations_async/__init__.py deleted file mode 100644 index e6429ee824b7..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/aio/operations_async/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._text_analytics_client_operations_async import TextAnalyticsClientOperationsMixin - -__all__ = [ - 'TextAnalyticsClientOperationsMixin', -] diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/aio/operations_async/_text_analytics_client_operations_async.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/aio/operations_async/_text_analytics_client_operations_async.py deleted file mode 100644 index d09be1dbc240..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/aio/operations_async/_text_analytics_client_operations_async.py +++ /dev/null @@ -1,380 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar -import warnings - -from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest - -from ... import models - -T = TypeVar('T') -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] - -class TextAnalyticsClientOperationsMixin: - - async def entities_recognition_general( - self, - documents: List["models.MultiLanguageInput"], - model_version: Optional[str] = None, - show_stats: Optional[bool] = None, - **kwargs - ) -> "models.EntitiesResult": - """The API returns a list of general named entities in a given document. For the list of supported entity types, check :code:`Supported Entity Types in Text Analytics API`. See the :code:`Supported languages in Text Analytics API` for the list of enabled languages. - - Named Entity Recognition. - - :param documents: The set of documents to process as part of this batch. - :type documents: list[~azure.ai.textanalytics.models.MultiLanguageInput] - :param model_version: (Optional) This value indicates which model will be used for scoring. If - a model-version is not specified, the API should default to the latest, non-preview version. - :type model_version: str - :param show_stats: (Optional) if set to true, response will contain input and document level - statistics. - :type show_stats: bool - :keyword callable cls: A custom type or function that will be passed the direct response - :return: EntitiesResult or the result of cls(response) - :rtype: ~azure.ai.textanalytics.models.EntitiesResult - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["models.EntitiesResult"] - error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} - error_map.update(kwargs.pop('error_map', {})) - - _input = models.MultiLanguageBatchInput(documents=documents) - content_type = kwargs.pop("content_type", "application/json") - - # Construct URL - url = self.entities_recognition_general.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if model_version is not None: - query_parameters['model-version'] = self._serialize.query("model_version", model_version, 'str') - if show_stats is not None: - query_parameters['showStats'] = self._serialize.query("show_stats", show_stats, 'bool') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = 'application/json' - - # Construct and send request - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(_input, 'MultiLanguageBatchInput') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize(models.TextAnalyticsError, response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize('EntitiesResult', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - entities_recognition_general.metadata = {'url': '/entities/recognition/general'} # type: ignore - - async def entities_linking( - self, - documents: List["models.MultiLanguageInput"], - model_version: Optional[str] = None, - show_stats: Optional[bool] = None, - **kwargs - ) -> "models.EntityLinkingResult": - """The API returns a list of recognized entities with links to a well-known knowledge base. See the :code:`Supported languages in Text Analytics API` for the list of enabled languages. - - Linked entities from a well-known knowledge base. - - :param documents: The set of documents to process as part of this batch. - :type documents: list[~azure.ai.textanalytics.models.MultiLanguageInput] - :param model_version: (Optional) This value indicates which model will be used for scoring. If - a model-version is not specified, the API should default to the latest, non-preview version. - :type model_version: str - :param show_stats: (Optional) if set to true, response will contain input and document level - statistics. - :type show_stats: bool - :keyword callable cls: A custom type or function that will be passed the direct response - :return: EntityLinkingResult or the result of cls(response) - :rtype: ~azure.ai.textanalytics.models.EntityLinkingResult - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["models.EntityLinkingResult"] - error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} - error_map.update(kwargs.pop('error_map', {})) - - _input = models.MultiLanguageBatchInput(documents=documents) - content_type = kwargs.pop("content_type", "application/json") - - # Construct URL - url = self.entities_linking.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if model_version is not None: - query_parameters['model-version'] = self._serialize.query("model_version", model_version, 'str') - if show_stats is not None: - query_parameters['showStats'] = self._serialize.query("show_stats", show_stats, 'bool') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = 'application/json' - - # Construct and send request - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(_input, 'MultiLanguageBatchInput') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize(models.TextAnalyticsError, response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize('EntityLinkingResult', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - entities_linking.metadata = {'url': '/entities/linking'} # type: ignore - - async def key_phrases( - self, - documents: List["models.MultiLanguageInput"], - model_version: Optional[str] = None, - show_stats: Optional[bool] = None, - **kwargs - ) -> "models.KeyPhraseResult": - """The API returns a list of strings denoting the key phrases in the input text. See the :code:`Supported languages in Text Analytics API` for the list of enabled languages. - - Key Phrases. - - :param documents: The set of documents to process as part of this batch. - :type documents: list[~azure.ai.textanalytics.models.MultiLanguageInput] - :param model_version: (Optional) This value indicates which model will be used for scoring. If - a model-version is not specified, the API should default to the latest, non-preview version. - :type model_version: str - :param show_stats: (Optional) if set to true, response will contain input and document level - statistics. - :type show_stats: bool - :keyword callable cls: A custom type or function that will be passed the direct response - :return: KeyPhraseResult or the result of cls(response) - :rtype: ~azure.ai.textanalytics.models.KeyPhraseResult - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["models.KeyPhraseResult"] - error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} - error_map.update(kwargs.pop('error_map', {})) - - _input = models.MultiLanguageBatchInput(documents=documents) - content_type = kwargs.pop("content_type", "application/json") - - # Construct URL - url = self.key_phrases.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if model_version is not None: - query_parameters['model-version'] = self._serialize.query("model_version", model_version, 'str') - if show_stats is not None: - query_parameters['showStats'] = self._serialize.query("show_stats", show_stats, 'bool') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = 'application/json' - - # Construct and send request - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(_input, 'MultiLanguageBatchInput') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize(models.TextAnalyticsError, response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize('KeyPhraseResult', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - key_phrases.metadata = {'url': '/keyPhrases'} # type: ignore - - async def languages( - self, - documents: List["models.LanguageInput"], - model_version: Optional[str] = None, - show_stats: Optional[bool] = None, - **kwargs - ) -> "models.LanguageResult": - """The API returns the detected language and a numeric score between 0 and 1. Scores close to 1 indicate 100% certainty that the identified language is true. See the :code:`Supported languages in Text Analytics API` for the list of enabled languages. - - Detect Language. - - :param documents: - :type documents: list[~azure.ai.textanalytics.models.LanguageInput] - :param model_version: (Optional) This value indicates which model will be used for scoring. If - a model-version is not specified, the API should default to the latest, non-preview version. - :type model_version: str - :param show_stats: (Optional) if set to true, response will contain input and document level - statistics. - :type show_stats: bool - :keyword callable cls: A custom type or function that will be passed the direct response - :return: LanguageResult or the result of cls(response) - :rtype: ~azure.ai.textanalytics.models.LanguageResult - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["models.LanguageResult"] - error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} - error_map.update(kwargs.pop('error_map', {})) - - _input = models.LanguageBatchInput(documents=documents) - content_type = kwargs.pop("content_type", "application/json") - - # Construct URL - url = self.languages.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if model_version is not None: - query_parameters['model-version'] = self._serialize.query("model_version", model_version, 'str') - if show_stats is not None: - query_parameters['showStats'] = self._serialize.query("show_stats", show_stats, 'bool') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = 'application/json' - - # Construct and send request - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(_input, 'LanguageBatchInput') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize(models.TextAnalyticsError, response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize('LanguageResult', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - languages.metadata = {'url': '/languages'} # type: ignore - - async def sentiment( - self, - documents: List["models.MultiLanguageInput"], - model_version: Optional[str] = None, - show_stats: Optional[bool] = None, - **kwargs - ) -> "models.SentimentResponse": - """The API returns a sentiment prediction, as well as sentiment scores for each sentiment class (Positive, Negative, and Neutral) for the document and each sentence within it. See the :code:`Supported languages in Text Analytics API` for the list of enabled languages. - - Sentiment. - - :param documents: The set of documents to process as part of this batch. - :type documents: list[~azure.ai.textanalytics.models.MultiLanguageInput] - :param model_version: (Optional) This value indicates which model will be used for scoring. If - a model-version is not specified, the API should default to the latest, non-preview version. - :type model_version: str - :param show_stats: (Optional) if set to true, response will contain input and document level - statistics. - :type show_stats: bool - :keyword callable cls: A custom type or function that will be passed the direct response - :return: SentimentResponse or the result of cls(response) - :rtype: ~azure.ai.textanalytics.models.SentimentResponse - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["models.SentimentResponse"] - error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} - error_map.update(kwargs.pop('error_map', {})) - - _input = models.MultiLanguageBatchInput(documents=documents) - content_type = kwargs.pop("content_type", "application/json") - - # Construct URL - url = self.sentiment.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if model_version is not None: - query_parameters['model-version'] = self._serialize.query("model_version", model_version, 'str') - if show_stats is not None: - query_parameters['showStats'] = self._serialize.query("show_stats", show_stats, 'bool') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = 'application/json' - - # Construct and send request - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(_input, 'MultiLanguageBatchInput') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize(models.TextAnalyticsError, response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize('SentimentResponse', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - sentiment.metadata = {'url': '/sentiment'} # type: ignore diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/models/__init__.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/models/__init__.py deleted file mode 100644 index 474336e92e7a..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/models/__init__.py +++ /dev/null @@ -1,104 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -try: - from ._models_py3 import DetectedLanguage - from ._models_py3 import DocumentEntities - from ._models_py3 import DocumentError - from ._models_py3 import DocumentKeyPhrases - from ._models_py3 import DocumentLanguage - from ._models_py3 import DocumentLinkedEntities - from ._models_py3 import DocumentSentiment - from ._models_py3 import DocumentStatistics - from ._models_py3 import EntitiesResult - from ._models_py3 import Entity - from ._models_py3 import EntityLinkingResult - from ._models_py3 import InnerError - from ._models_py3 import KeyPhraseResult - from ._models_py3 import LanguageBatchInput - from ._models_py3 import LanguageInput - from ._models_py3 import LanguageResult - from ._models_py3 import LinkedEntity - from ._models_py3 import Match - from ._models_py3 import MultiLanguageBatchInput - from ._models_py3 import MultiLanguageInput - from ._models_py3 import RequestStatistics - from ._models_py3 import SentenceSentiment - from ._models_py3 import SentimentConfidenceScorePerLabel - from ._models_py3 import SentimentResponse - from ._models_py3 import TextAnalyticsError - from ._models_py3 import TextAnalyticsWarning -except (SyntaxError, ImportError): - from ._models import DetectedLanguage # type: ignore - from ._models import DocumentEntities # type: ignore - from ._models import DocumentError # type: ignore - from ._models import DocumentKeyPhrases # type: ignore - from ._models import DocumentLanguage # type: ignore - from ._models import DocumentLinkedEntities # type: ignore - from ._models import DocumentSentiment # type: ignore - from ._models import DocumentStatistics # type: ignore - from ._models import EntitiesResult # type: ignore - from ._models import Entity # type: ignore - from ._models import EntityLinkingResult # type: ignore - from ._models import InnerError # type: ignore - from ._models import KeyPhraseResult # type: ignore - from ._models import LanguageBatchInput # type: ignore - from ._models import LanguageInput # type: ignore - from ._models import LanguageResult # type: ignore - from ._models import LinkedEntity # type: ignore - from ._models import Match # type: ignore - from ._models import MultiLanguageBatchInput # type: ignore - from ._models import MultiLanguageInput # type: ignore - from ._models import RequestStatistics # type: ignore - from ._models import SentenceSentiment # type: ignore - from ._models import SentimentConfidenceScorePerLabel # type: ignore - from ._models import SentimentResponse # type: ignore - from ._models import TextAnalyticsError # type: ignore - from ._models import TextAnalyticsWarning # type: ignore - -from ._text_analytics_client_enums import ( - DocumentSentimentValue, - ErrorCodeValue, - InnerErrorCodeValue, - SentenceSentimentValue, - WarningCodeValue, -) - -__all__ = [ - 'DetectedLanguage', - 'DocumentEntities', - 'DocumentError', - 'DocumentKeyPhrases', - 'DocumentLanguage', - 'DocumentLinkedEntities', - 'DocumentSentiment', - 'DocumentStatistics', - 'EntitiesResult', - 'Entity', - 'EntityLinkingResult', - 'InnerError', - 'KeyPhraseResult', - 'LanguageBatchInput', - 'LanguageInput', - 'LanguageResult', - 'LinkedEntity', - 'Match', - 'MultiLanguageBatchInput', - 'MultiLanguageInput', - 'RequestStatistics', - 'SentenceSentiment', - 'SentimentConfidenceScorePerLabel', - 'SentimentResponse', - 'TextAnalyticsError', - 'TextAnalyticsWarning', - 'DocumentSentimentValue', - 'ErrorCodeValue', - 'InnerErrorCodeValue', - 'SentenceSentimentValue', - 'WarningCodeValue', -] diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/models/_models.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/models/_models.py deleted file mode 100644 index 9c178ac255dd..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/models/_models.py +++ /dev/null @@ -1,1026 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from azure.core.exceptions import HttpResponseError -import msrest.serialization - - -class DetectedLanguage(msrest.serialization.Model): - """DetectedLanguage. - - All required parameters must be populated in order to send to Azure. - - :param name: Required. Long name of a detected language (e.g. English, French). - :type name: str - :param iso6391_name: Required. A two letter representation of the detected language according - to the ISO 639-1 standard (e.g. en, fr). - :type iso6391_name: str - :param confidence_score: Required. A confidence score between 0 and 1. Scores close to 1 - indicate 100% certainty that the identified language is true. - :type confidence_score: float - """ - - _validation = { - 'name': {'required': True}, - 'iso6391_name': {'required': True}, - 'confidence_score': {'required': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'iso6391_name': {'key': 'iso6391Name', 'type': 'str'}, - 'confidence_score': {'key': 'confidenceScore', 'type': 'float'}, - } - - def __init__( - self, - **kwargs - ): - super(DetectedLanguage, self).__init__(**kwargs) - self.name = kwargs['name'] - self.iso6391_name = kwargs['iso6391_name'] - self.confidence_score = kwargs['confidence_score'] - - -class DocumentEntities(msrest.serialization.Model): - """DocumentEntities. - - All required parameters must be populated in order to send to Azure. - - :param id: Required. Unique, non-empty document identifier. - :type id: str - :param entities: Required. Recognized entities in the document. - :type entities: list[~azure.ai.textanalytics.models.Entity] - :param warnings: Required. Warnings encountered while processing document. - :type warnings: list[~azure.ai.textanalytics.models.TextAnalyticsWarning] - :param statistics: if showStats=true was specified in the request this field will contain - information about the document payload. - :type statistics: ~azure.ai.textanalytics.models.DocumentStatistics - """ - - _validation = { - 'id': {'required': True}, - 'entities': {'required': True}, - 'warnings': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'entities': {'key': 'entities', 'type': '[Entity]'}, - 'warnings': {'key': 'warnings', 'type': '[TextAnalyticsWarning]'}, - 'statistics': {'key': 'statistics', 'type': 'DocumentStatistics'}, - } - - def __init__( - self, - **kwargs - ): - super(DocumentEntities, self).__init__(**kwargs) - self.id = kwargs['id'] - self.entities = kwargs['entities'] - self.warnings = kwargs['warnings'] - self.statistics = kwargs.get('statistics', None) - - -class DocumentError(msrest.serialization.Model): - """DocumentError. - - All required parameters must be populated in order to send to Azure. - - :param id: Required. Document Id. - :type id: str - :param error: Required. Document Error. - :type error: ~azure.ai.textanalytics.models.TextAnalyticsError - """ - - _validation = { - 'id': {'required': True}, - 'error': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'error': {'key': 'error', 'type': 'TextAnalyticsError'}, - } - - def __init__( - self, - **kwargs - ): - super(DocumentError, self).__init__(**kwargs) - self.id = kwargs['id'] - self.error = kwargs['error'] - - -class DocumentKeyPhrases(msrest.serialization.Model): - """DocumentKeyPhrases. - - All required parameters must be populated in order to send to Azure. - - :param id: Required. Unique, non-empty document identifier. - :type id: str - :param key_phrases: Required. A list of representative words or phrases. The number of key - phrases returned is proportional to the number of words in the input document. - :type key_phrases: list[str] - :param warnings: Required. Warnings encountered while processing document. - :type warnings: list[~azure.ai.textanalytics.models.TextAnalyticsWarning] - :param statistics: if showStats=true was specified in the request this field will contain - information about the document payload. - :type statistics: ~azure.ai.textanalytics.models.DocumentStatistics - """ - - _validation = { - 'id': {'required': True}, - 'key_phrases': {'required': True}, - 'warnings': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'key_phrases': {'key': 'keyPhrases', 'type': '[str]'}, - 'warnings': {'key': 'warnings', 'type': '[TextAnalyticsWarning]'}, - 'statistics': {'key': 'statistics', 'type': 'DocumentStatistics'}, - } - - def __init__( - self, - **kwargs - ): - super(DocumentKeyPhrases, self).__init__(**kwargs) - self.id = kwargs['id'] - self.key_phrases = kwargs['key_phrases'] - self.warnings = kwargs['warnings'] - self.statistics = kwargs.get('statistics', None) - - -class DocumentLanguage(msrest.serialization.Model): - """DocumentLanguage. - - All required parameters must be populated in order to send to Azure. - - :param id: Required. Unique, non-empty document identifier. - :type id: str - :param detected_language: Required. Detected Language. - :type detected_language: ~azure.ai.textanalytics.models.DetectedLanguage - :param warnings: Required. Warnings encountered while processing document. - :type warnings: list[~azure.ai.textanalytics.models.TextAnalyticsWarning] - :param statistics: if showStats=true was specified in the request this field will contain - information about the document payload. - :type statistics: ~azure.ai.textanalytics.models.DocumentStatistics - """ - - _validation = { - 'id': {'required': True}, - 'detected_language': {'required': True}, - 'warnings': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'detected_language': {'key': 'detectedLanguage', 'type': 'DetectedLanguage'}, - 'warnings': {'key': 'warnings', 'type': '[TextAnalyticsWarning]'}, - 'statistics': {'key': 'statistics', 'type': 'DocumentStatistics'}, - } - - def __init__( - self, - **kwargs - ): - super(DocumentLanguage, self).__init__(**kwargs) - self.id = kwargs['id'] - self.detected_language = kwargs['detected_language'] - self.warnings = kwargs['warnings'] - self.statistics = kwargs.get('statistics', None) - - -class DocumentLinkedEntities(msrest.serialization.Model): - """DocumentLinkedEntities. - - All required parameters must be populated in order to send to Azure. - - :param id: Required. Unique, non-empty document identifier. - :type id: str - :param entities: Required. Recognized well-known entities in the document. - :type entities: list[~azure.ai.textanalytics.models.LinkedEntity] - :param warnings: Required. Warnings encountered while processing document. - :type warnings: list[~azure.ai.textanalytics.models.TextAnalyticsWarning] - :param statistics: if showStats=true was specified in the request this field will contain - information about the document payload. - :type statistics: ~azure.ai.textanalytics.models.DocumentStatistics - """ - - _validation = { - 'id': {'required': True}, - 'entities': {'required': True}, - 'warnings': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'entities': {'key': 'entities', 'type': '[LinkedEntity]'}, - 'warnings': {'key': 'warnings', 'type': '[TextAnalyticsWarning]'}, - 'statistics': {'key': 'statistics', 'type': 'DocumentStatistics'}, - } - - def __init__( - self, - **kwargs - ): - super(DocumentLinkedEntities, self).__init__(**kwargs) - self.id = kwargs['id'] - self.entities = kwargs['entities'] - self.warnings = kwargs['warnings'] - self.statistics = kwargs.get('statistics', None) - - -class DocumentSentiment(msrest.serialization.Model): - """DocumentSentiment. - - All required parameters must be populated in order to send to Azure. - - :param id: Required. Unique, non-empty document identifier. - :type id: str - :param sentiment: Required. Predicted sentiment for document (Negative, Neutral, Positive, or - Mixed). Possible values include: "positive", "neutral", "negative", "mixed". - :type sentiment: str or ~azure.ai.textanalytics.models.DocumentSentimentValue - :param statistics: if showStats=true was specified in the request this field will contain - information about the document payload. - :type statistics: ~azure.ai.textanalytics.models.DocumentStatistics - :param confidence_scores: Required. Document level sentiment confidence scores between 0 and 1 - for each sentiment class. - :type confidence_scores: ~azure.ai.textanalytics.models.SentimentConfidenceScorePerLabel - :param sentences: Required. Sentence level sentiment analysis. - :type sentences: list[~azure.ai.textanalytics.models.SentenceSentiment] - :param warnings: Required. Warnings encountered while processing document. - :type warnings: list[~azure.ai.textanalytics.models.TextAnalyticsWarning] - """ - - _validation = { - 'id': {'required': True}, - 'sentiment': {'required': True}, - 'confidence_scores': {'required': True}, - 'sentences': {'required': True}, - 'warnings': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'sentiment': {'key': 'sentiment', 'type': 'str'}, - 'statistics': {'key': 'statistics', 'type': 'DocumentStatistics'}, - 'confidence_scores': {'key': 'confidenceScores', 'type': 'SentimentConfidenceScorePerLabel'}, - 'sentences': {'key': 'sentences', 'type': '[SentenceSentiment]'}, - 'warnings': {'key': 'warnings', 'type': '[TextAnalyticsWarning]'}, - } - - def __init__( - self, - **kwargs - ): - super(DocumentSentiment, self).__init__(**kwargs) - self.id = kwargs['id'] - self.sentiment = kwargs['sentiment'] - self.statistics = kwargs.get('statistics', None) - self.confidence_scores = kwargs['confidence_scores'] - self.sentences = kwargs['sentences'] - self.warnings = kwargs['warnings'] - - -class DocumentStatistics(msrest.serialization.Model): - """if showStats=true was specified in the request this field will contain information about the document payload. - - All required parameters must be populated in order to send to Azure. - - :param characters_count: Required. Number of text elements recognized in the document. - :type characters_count: int - :param transactions_count: Required. Number of transactions for the document. - :type transactions_count: int - """ - - _validation = { - 'characters_count': {'required': True}, - 'transactions_count': {'required': True}, - } - - _attribute_map = { - 'characters_count': {'key': 'charactersCount', 'type': 'int'}, - 'transactions_count': {'key': 'transactionsCount', 'type': 'int'}, - } - - def __init__( - self, - **kwargs - ): - super(DocumentStatistics, self).__init__(**kwargs) - self.characters_count = kwargs['characters_count'] - self.transactions_count = kwargs['transactions_count'] - - -class EntitiesResult(msrest.serialization.Model): - """EntitiesResult. - - All required parameters must be populated in order to send to Azure. - - :param documents: Required. Response by document. - :type documents: list[~azure.ai.textanalytics.models.DocumentEntities] - :param errors: Required. Errors by document id. - :type errors: list[~azure.ai.textanalytics.models.DocumentError] - :param statistics: if showStats=true was specified in the request this field will contain - information about the request payload. - :type statistics: ~azure.ai.textanalytics.models.RequestStatistics - :param model_version: Required. This field indicates which model is used for scoring. - :type model_version: str - """ - - _validation = { - 'documents': {'required': True}, - 'errors': {'required': True}, - 'model_version': {'required': True}, - } - - _attribute_map = { - 'documents': {'key': 'documents', 'type': '[DocumentEntities]'}, - 'errors': {'key': 'errors', 'type': '[DocumentError]'}, - 'statistics': {'key': 'statistics', 'type': 'RequestStatistics'}, - 'model_version': {'key': 'modelVersion', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(EntitiesResult, self).__init__(**kwargs) - self.documents = kwargs['documents'] - self.errors = kwargs['errors'] - self.statistics = kwargs.get('statistics', None) - self.model_version = kwargs['model_version'] - - -class Entity(msrest.serialization.Model): - """Entity. - - All required parameters must be populated in order to send to Azure. - - :param text: Required. Entity text as appears in the request. - :type text: str - :param category: Required. Entity type, such as Person/Location/Org/SSN etc. - :type category: str - :param subcategory: Entity sub type, such as Age/Year/TimeRange etc. - :type subcategory: str - :param offset: Required. Start position (in Unicode characters) for the entity text. - :type offset: int - :param length: Required. Length (in Unicode characters) for the entity text. - :type length: int - :param confidence_score: Required. Confidence score between 0 and 1 of the extracted entity. - :type confidence_score: float - """ - - _validation = { - 'text': {'required': True}, - 'category': {'required': True}, - 'offset': {'required': True}, - 'length': {'required': True}, - 'confidence_score': {'required': True}, - } - - _attribute_map = { - 'text': {'key': 'text', 'type': 'str'}, - 'category': {'key': 'category', 'type': 'str'}, - 'subcategory': {'key': 'subcategory', 'type': 'str'}, - 'offset': {'key': 'offset', 'type': 'int'}, - 'length': {'key': 'length', 'type': 'int'}, - 'confidence_score': {'key': 'confidenceScore', 'type': 'float'}, - } - - def __init__( - self, - **kwargs - ): - super(Entity, self).__init__(**kwargs) - self.text = kwargs['text'] - self.category = kwargs['category'] - self.subcategory = kwargs.get('subcategory', None) - self.offset = kwargs['offset'] - self.length = kwargs['length'] - self.confidence_score = kwargs['confidence_score'] - - -class EntityLinkingResult(msrest.serialization.Model): - """EntityLinkingResult. - - All required parameters must be populated in order to send to Azure. - - :param documents: Required. Response by document. - :type documents: list[~azure.ai.textanalytics.models.DocumentLinkedEntities] - :param errors: Required. Errors by document id. - :type errors: list[~azure.ai.textanalytics.models.DocumentError] - :param statistics: if showStats=true was specified in the request this field will contain - information about the request payload. - :type statistics: ~azure.ai.textanalytics.models.RequestStatistics - :param model_version: Required. This field indicates which model is used for scoring. - :type model_version: str - """ - - _validation = { - 'documents': {'required': True}, - 'errors': {'required': True}, - 'model_version': {'required': True}, - } - - _attribute_map = { - 'documents': {'key': 'documents', 'type': '[DocumentLinkedEntities]'}, - 'errors': {'key': 'errors', 'type': '[DocumentError]'}, - 'statistics': {'key': 'statistics', 'type': 'RequestStatistics'}, - 'model_version': {'key': 'modelVersion', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(EntityLinkingResult, self).__init__(**kwargs) - self.documents = kwargs['documents'] - self.errors = kwargs['errors'] - self.statistics = kwargs.get('statistics', None) - self.model_version = kwargs['model_version'] - - -class InnerError(msrest.serialization.Model): - """InnerError. - - All required parameters must be populated in order to send to Azure. - - :param code: Required. Error code. Possible values include: "invalidParameterValue", - "invalidRequestBodyFormat", "emptyRequest", "missingInputRecords", "invalidDocument", - "modelVersionIncorrect", "invalidDocumentBatch", "unsupportedLanguageCode", - "invalidCountryHint". - :type code: str or ~azure.ai.textanalytics.models.InnerErrorCodeValue - :param message: Required. Error message. - :type message: str - :param details: Error details. - :type details: dict[str, str] - :param target: Error target. - :type target: str - :param innererror: Inner error contains more specific information. - :type innererror: ~azure.ai.textanalytics.models.InnerError - """ - - _validation = { - 'code': {'required': True}, - 'message': {'required': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'details': {'key': 'details', 'type': '{str}'}, - 'target': {'key': 'target', 'type': 'str'}, - 'innererror': {'key': 'innererror', 'type': 'InnerError'}, - } - - def __init__( - self, - **kwargs - ): - super(InnerError, self).__init__(**kwargs) - self.code = kwargs['code'] - self.message = kwargs['message'] - self.details = kwargs.get('details', None) - self.target = kwargs.get('target', None) - self.innererror = kwargs.get('innererror', None) - - -class KeyPhraseResult(msrest.serialization.Model): - """KeyPhraseResult. - - All required parameters must be populated in order to send to Azure. - - :param documents: Required. Response by document. - :type documents: list[~azure.ai.textanalytics.models.DocumentKeyPhrases] - :param errors: Required. Errors by document id. - :type errors: list[~azure.ai.textanalytics.models.DocumentError] - :param statistics: if showStats=true was specified in the request this field will contain - information about the request payload. - :type statistics: ~azure.ai.textanalytics.models.RequestStatistics - :param model_version: Required. This field indicates which model is used for scoring. - :type model_version: str - """ - - _validation = { - 'documents': {'required': True}, - 'errors': {'required': True}, - 'model_version': {'required': True}, - } - - _attribute_map = { - 'documents': {'key': 'documents', 'type': '[DocumentKeyPhrases]'}, - 'errors': {'key': 'errors', 'type': '[DocumentError]'}, - 'statistics': {'key': 'statistics', 'type': 'RequestStatistics'}, - 'model_version': {'key': 'modelVersion', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(KeyPhraseResult, self).__init__(**kwargs) - self.documents = kwargs['documents'] - self.errors = kwargs['errors'] - self.statistics = kwargs.get('statistics', None) - self.model_version = kwargs['model_version'] - - -class LanguageBatchInput(msrest.serialization.Model): - """LanguageBatchInput. - - All required parameters must be populated in order to send to Azure. - - :param documents: Required. - :type documents: list[~azure.ai.textanalytics.models.LanguageInput] - """ - - _validation = { - 'documents': {'required': True}, - } - - _attribute_map = { - 'documents': {'key': 'documents', 'type': '[LanguageInput]'}, - } - - def __init__( - self, - **kwargs - ): - super(LanguageBatchInput, self).__init__(**kwargs) - self.documents = kwargs['documents'] - - -class LanguageInput(msrest.serialization.Model): - """LanguageInput. - - All required parameters must be populated in order to send to Azure. - - :param id: Required. Unique, non-empty document identifier. - :type id: str - :param text: Required. - :type text: str - :param country_hint: - :type country_hint: str - """ - - _validation = { - 'id': {'required': True}, - 'text': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'text': {'key': 'text', 'type': 'str'}, - 'country_hint': {'key': 'countryHint', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(LanguageInput, self).__init__(**kwargs) - self.id = kwargs['id'] - self.text = kwargs['text'] - self.country_hint = kwargs.get('country_hint', None) - - -class LanguageResult(msrest.serialization.Model): - """LanguageResult. - - All required parameters must be populated in order to send to Azure. - - :param documents: Required. Response by document. - :type documents: list[~azure.ai.textanalytics.models.DocumentLanguage] - :param errors: Required. Errors by document id. - :type errors: list[~azure.ai.textanalytics.models.DocumentError] - :param statistics: if showStats=true was specified in the request this field will contain - information about the request payload. - :type statistics: ~azure.ai.textanalytics.models.RequestStatistics - :param model_version: Required. This field indicates which model is used for scoring. - :type model_version: str - """ - - _validation = { - 'documents': {'required': True}, - 'errors': {'required': True}, - 'model_version': {'required': True}, - } - - _attribute_map = { - 'documents': {'key': 'documents', 'type': '[DocumentLanguage]'}, - 'errors': {'key': 'errors', 'type': '[DocumentError]'}, - 'statistics': {'key': 'statistics', 'type': 'RequestStatistics'}, - 'model_version': {'key': 'modelVersion', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(LanguageResult, self).__init__(**kwargs) - self.documents = kwargs['documents'] - self.errors = kwargs['errors'] - self.statistics = kwargs.get('statistics', None) - self.model_version = kwargs['model_version'] - - -class LinkedEntity(msrest.serialization.Model): - """LinkedEntity. - - All required parameters must be populated in order to send to Azure. - - :param name: Required. Entity Linking formal name. - :type name: str - :param matches: Required. List of instances this entity appears in the text. - :type matches: list[~azure.ai.textanalytics.models.Match] - :param language: Required. Language used in the data source. - :type language: str - :param id: Unique identifier of the recognized entity from the data source. - :type id: str - :param url: Required. URL for the entity's page from the data source. - :type url: str - :param data_source: Required. Data source used to extract entity linking, such as Wiki/Bing - etc. - :type data_source: str - """ - - _validation = { - 'name': {'required': True}, - 'matches': {'required': True}, - 'language': {'required': True}, - 'url': {'required': True}, - 'data_source': {'required': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'matches': {'key': 'matches', 'type': '[Match]'}, - 'language': {'key': 'language', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'url': {'key': 'url', 'type': 'str'}, - 'data_source': {'key': 'dataSource', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(LinkedEntity, self).__init__(**kwargs) - self.name = kwargs['name'] - self.matches = kwargs['matches'] - self.language = kwargs['language'] - self.id = kwargs.get('id', None) - self.url = kwargs['url'] - self.data_source = kwargs['data_source'] - - -class Match(msrest.serialization.Model): - """Match. - - All required parameters must be populated in order to send to Azure. - - :param confidence_score: Required. If a well-known item is recognized, a decimal number - denoting the confidence level between 0 and 1 will be returned. - :type confidence_score: float - :param text: Required. Entity text as appears in the request. - :type text: str - :param offset: Required. Start position (in Unicode characters) for the entity match text. - :type offset: int - :param length: Required. Length (in Unicode characters) for the entity match text. - :type length: int - """ - - _validation = { - 'confidence_score': {'required': True}, - 'text': {'required': True}, - 'offset': {'required': True}, - 'length': {'required': True}, - } - - _attribute_map = { - 'confidence_score': {'key': 'confidenceScore', 'type': 'float'}, - 'text': {'key': 'text', 'type': 'str'}, - 'offset': {'key': 'offset', 'type': 'int'}, - 'length': {'key': 'length', 'type': 'int'}, - } - - def __init__( - self, - **kwargs - ): - super(Match, self).__init__(**kwargs) - self.confidence_score = kwargs['confidence_score'] - self.text = kwargs['text'] - self.offset = kwargs['offset'] - self.length = kwargs['length'] - - -class MultiLanguageBatchInput(msrest.serialization.Model): - """Contains a set of input documents to be analyzed by the service. - - All required parameters must be populated in order to send to Azure. - - :param documents: Required. The set of documents to process as part of this batch. - :type documents: list[~azure.ai.textanalytics.models.MultiLanguageInput] - """ - - _validation = { - 'documents': {'required': True}, - } - - _attribute_map = { - 'documents': {'key': 'documents', 'type': '[MultiLanguageInput]'}, - } - - def __init__( - self, - **kwargs - ): - super(MultiLanguageBatchInput, self).__init__(**kwargs) - self.documents = kwargs['documents'] - - -class MultiLanguageInput(msrest.serialization.Model): - """Contains an input document to be analyzed by the service. - - All required parameters must be populated in order to send to Azure. - - :param id: Required. A unique, non-empty document identifier. - :type id: str - :param text: Required. The input text to process. - :type text: str - :param language: (Optional) This is the 2 letter ISO 639-1 representation of a language. For - example, use "en" for English; "es" for Spanish etc. If not set, use "en" for English as - default. - :type language: str - """ - - _validation = { - 'id': {'required': True}, - 'text': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'text': {'key': 'text', 'type': 'str'}, - 'language': {'key': 'language', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(MultiLanguageInput, self).__init__(**kwargs) - self.id = kwargs['id'] - self.text = kwargs['text'] - self.language = kwargs.get('language', None) - - -class RequestStatistics(msrest.serialization.Model): - """if showStats=true was specified in the request this field will contain information about the request payload. - - All required parameters must be populated in order to send to Azure. - - :param documents_count: Required. Number of documents submitted in the request. - :type documents_count: int - :param valid_documents_count: Required. Number of valid documents. This excludes empty, over- - size limit or non-supported languages documents. - :type valid_documents_count: int - :param erroneous_documents_count: Required. Number of invalid documents. This includes empty, - over-size limit or non-supported languages documents. - :type erroneous_documents_count: int - :param transactions_count: Required. Number of transactions for the request. - :type transactions_count: long - """ - - _validation = { - 'documents_count': {'required': True}, - 'valid_documents_count': {'required': True}, - 'erroneous_documents_count': {'required': True}, - 'transactions_count': {'required': True}, - } - - _attribute_map = { - 'documents_count': {'key': 'documentsCount', 'type': 'int'}, - 'valid_documents_count': {'key': 'validDocumentsCount', 'type': 'int'}, - 'erroneous_documents_count': {'key': 'erroneousDocumentsCount', 'type': 'int'}, - 'transactions_count': {'key': 'transactionsCount', 'type': 'long'}, - } - - def __init__( - self, - **kwargs - ): - super(RequestStatistics, self).__init__(**kwargs) - self.documents_count = kwargs['documents_count'] - self.valid_documents_count = kwargs['valid_documents_count'] - self.erroneous_documents_count = kwargs['erroneous_documents_count'] - self.transactions_count = kwargs['transactions_count'] - - -class SentenceSentiment(msrest.serialization.Model): - """SentenceSentiment. - - All required parameters must be populated in order to send to Azure. - - :param text: The sentence text. - :type text: str - :param sentiment: Required. The predicted Sentiment for the sentence. Possible values include: - "positive", "neutral", "negative". - :type sentiment: str or ~azure.ai.textanalytics.models.SentenceSentimentValue - :param confidence_scores: Required. The sentiment confidence score between 0 and 1 for the - sentence for all classes. - :type confidence_scores: ~azure.ai.textanalytics.models.SentimentConfidenceScorePerLabel - :param offset: Required. The sentence offset from the start of the document. - :type offset: int - :param length: Required. The length of the sentence by Unicode standard. - :type length: int - """ - - _validation = { - 'sentiment': {'required': True}, - 'confidence_scores': {'required': True}, - 'offset': {'required': True}, - 'length': {'required': True}, - } - - _attribute_map = { - 'text': {'key': 'text', 'type': 'str'}, - 'sentiment': {'key': 'sentiment', 'type': 'str'}, - 'confidence_scores': {'key': 'confidenceScores', 'type': 'SentimentConfidenceScorePerLabel'}, - 'offset': {'key': 'offset', 'type': 'int'}, - 'length': {'key': 'length', 'type': 'int'}, - } - - def __init__( - self, - **kwargs - ): - super(SentenceSentiment, self).__init__(**kwargs) - self.text = kwargs.get('text', None) - self.sentiment = kwargs['sentiment'] - self.confidence_scores = kwargs['confidence_scores'] - self.offset = kwargs['offset'] - self.length = kwargs['length'] - - -class SentimentConfidenceScorePerLabel(msrest.serialization.Model): - """Represents the confidence scores between 0 and 1 across all sentiment classes: positive, neutral, negative. - - All required parameters must be populated in order to send to Azure. - - :param positive: Required. - :type positive: float - :param neutral: Required. - :type neutral: float - :param negative: Required. - :type negative: float - """ - - _validation = { - 'positive': {'required': True}, - 'neutral': {'required': True}, - 'negative': {'required': True}, - } - - _attribute_map = { - 'positive': {'key': 'positive', 'type': 'float'}, - 'neutral': {'key': 'neutral', 'type': 'float'}, - 'negative': {'key': 'negative', 'type': 'float'}, - } - - def __init__( - self, - **kwargs - ): - super(SentimentConfidenceScorePerLabel, self).__init__(**kwargs) - self.positive = kwargs['positive'] - self.neutral = kwargs['neutral'] - self.negative = kwargs['negative'] - - -class SentimentResponse(msrest.serialization.Model): - """SentimentResponse. - - All required parameters must be populated in order to send to Azure. - - :param documents: Required. Sentiment analysis per document. - :type documents: list[~azure.ai.textanalytics.models.DocumentSentiment] - :param errors: Required. Errors by document id. - :type errors: list[~azure.ai.textanalytics.models.DocumentError] - :param statistics: if showStats=true was specified in the request this field will contain - information about the request payload. - :type statistics: ~azure.ai.textanalytics.models.RequestStatistics - :param model_version: Required. This field indicates which model is used for scoring. - :type model_version: str - """ - - _validation = { - 'documents': {'required': True}, - 'errors': {'required': True}, - 'model_version': {'required': True}, - } - - _attribute_map = { - 'documents': {'key': 'documents', 'type': '[DocumentSentiment]'}, - 'errors': {'key': 'errors', 'type': '[DocumentError]'}, - 'statistics': {'key': 'statistics', 'type': 'RequestStatistics'}, - 'model_version': {'key': 'modelVersion', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(SentimentResponse, self).__init__(**kwargs) - self.documents = kwargs['documents'] - self.errors = kwargs['errors'] - self.statistics = kwargs.get('statistics', None) - self.model_version = kwargs['model_version'] - - -class TextAnalyticsError(msrest.serialization.Model): - """TextAnalyticsError. - - All required parameters must be populated in order to send to Azure. - - :param code: Required. Error code. Possible values include: "invalidRequest", - "invalidArgument", "internalServerError", "serviceUnavailable". - :type code: str or ~azure.ai.textanalytics.models.ErrorCodeValue - :param message: Required. Error message. - :type message: str - :param target: Error target. - :type target: str - :param innererror: Inner error contains more specific information. - :type innererror: ~azure.ai.textanalytics.models.InnerError - :param details: Details about specific errors that led to this reported error. - :type details: list[~azure.ai.textanalytics.models.TextAnalyticsError] - """ - - _validation = { - 'code': {'required': True}, - 'message': {'required': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'innererror': {'key': 'innererror', 'type': 'InnerError'}, - 'details': {'key': 'details', 'type': '[TextAnalyticsError]'}, - } - - def __init__( - self, - **kwargs - ): - super(TextAnalyticsError, self).__init__(**kwargs) - self.code = kwargs['code'] - self.message = kwargs['message'] - self.target = kwargs.get('target', None) - self.innererror = kwargs.get('innererror', None) - self.details = kwargs.get('details', None) - - -class TextAnalyticsWarning(msrest.serialization.Model): - """TextAnalyticsWarning. - - All required parameters must be populated in order to send to Azure. - - :param code: Required. Error code. Possible values include: "LongWordsInDocument", - "DocumentTruncated". - :type code: str or ~azure.ai.textanalytics.models.WarningCodeValue - :param message: Required. Warning message. - :type message: str - :param target_ref: A JSON pointer reference indicating the target object. - :type target_ref: str - """ - - _validation = { - 'code': {'required': True}, - 'message': {'required': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target_ref': {'key': 'targetRef', 'type': 'str'}, - } - - def __init__( - self, - **kwargs - ): - super(TextAnalyticsWarning, self).__init__(**kwargs) - self.code = kwargs['code'] - self.message = kwargs['message'] - self.target_ref = kwargs.get('target_ref', None) diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/models/_models_py3.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/models/_models_py3.py deleted file mode 100644 index b969f1ca74e8..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/models/_models_py3.py +++ /dev/null @@ -1,1154 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Dict, List, Optional, Union - -from azure.core.exceptions import HttpResponseError -import msrest.serialization - -from ._text_analytics_client_enums import * - - -class DetectedLanguage(msrest.serialization.Model): - """DetectedLanguage. - - All required parameters must be populated in order to send to Azure. - - :param name: Required. Long name of a detected language (e.g. English, French). - :type name: str - :param iso6391_name: Required. A two letter representation of the detected language according - to the ISO 639-1 standard (e.g. en, fr). - :type iso6391_name: str - :param confidence_score: Required. A confidence score between 0 and 1. Scores close to 1 - indicate 100% certainty that the identified language is true. - :type confidence_score: float - """ - - _validation = { - 'name': {'required': True}, - 'iso6391_name': {'required': True}, - 'confidence_score': {'required': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'iso6391_name': {'key': 'iso6391Name', 'type': 'str'}, - 'confidence_score': {'key': 'confidenceScore', 'type': 'float'}, - } - - def __init__( - self, - *, - name: str, - iso6391_name: str, - confidence_score: float, - **kwargs - ): - super(DetectedLanguage, self).__init__(**kwargs) - self.name = name - self.iso6391_name = iso6391_name - self.confidence_score = confidence_score - - -class DocumentEntities(msrest.serialization.Model): - """DocumentEntities. - - All required parameters must be populated in order to send to Azure. - - :param id: Required. Unique, non-empty document identifier. - :type id: str - :param entities: Required. Recognized entities in the document. - :type entities: list[~azure.ai.textanalytics.models.Entity] - :param warnings: Required. Warnings encountered while processing document. - :type warnings: list[~azure.ai.textanalytics.models.TextAnalyticsWarning] - :param statistics: if showStats=true was specified in the request this field will contain - information about the document payload. - :type statistics: ~azure.ai.textanalytics.models.DocumentStatistics - """ - - _validation = { - 'id': {'required': True}, - 'entities': {'required': True}, - 'warnings': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'entities': {'key': 'entities', 'type': '[Entity]'}, - 'warnings': {'key': 'warnings', 'type': '[TextAnalyticsWarning]'}, - 'statistics': {'key': 'statistics', 'type': 'DocumentStatistics'}, - } - - def __init__( - self, - *, - id: str, - entities: List["Entity"], - warnings: List["TextAnalyticsWarning"], - statistics: Optional["DocumentStatistics"] = None, - **kwargs - ): - super(DocumentEntities, self).__init__(**kwargs) - self.id = id - self.entities = entities - self.warnings = warnings - self.statistics = statistics - - -class DocumentError(msrest.serialization.Model): - """DocumentError. - - All required parameters must be populated in order to send to Azure. - - :param id: Required. Document Id. - :type id: str - :param error: Required. Document Error. - :type error: ~azure.ai.textanalytics.models.TextAnalyticsError - """ - - _validation = { - 'id': {'required': True}, - 'error': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'error': {'key': 'error', 'type': 'TextAnalyticsError'}, - } - - def __init__( - self, - *, - id: str, - error: "TextAnalyticsError", - **kwargs - ): - super(DocumentError, self).__init__(**kwargs) - self.id = id - self.error = error - - -class DocumentKeyPhrases(msrest.serialization.Model): - """DocumentKeyPhrases. - - All required parameters must be populated in order to send to Azure. - - :param id: Required. Unique, non-empty document identifier. - :type id: str - :param key_phrases: Required. A list of representative words or phrases. The number of key - phrases returned is proportional to the number of words in the input document. - :type key_phrases: list[str] - :param warnings: Required. Warnings encountered while processing document. - :type warnings: list[~azure.ai.textanalytics.models.TextAnalyticsWarning] - :param statistics: if showStats=true was specified in the request this field will contain - information about the document payload. - :type statistics: ~azure.ai.textanalytics.models.DocumentStatistics - """ - - _validation = { - 'id': {'required': True}, - 'key_phrases': {'required': True}, - 'warnings': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'key_phrases': {'key': 'keyPhrases', 'type': '[str]'}, - 'warnings': {'key': 'warnings', 'type': '[TextAnalyticsWarning]'}, - 'statistics': {'key': 'statistics', 'type': 'DocumentStatistics'}, - } - - def __init__( - self, - *, - id: str, - key_phrases: List[str], - warnings: List["TextAnalyticsWarning"], - statistics: Optional["DocumentStatistics"] = None, - **kwargs - ): - super(DocumentKeyPhrases, self).__init__(**kwargs) - self.id = id - self.key_phrases = key_phrases - self.warnings = warnings - self.statistics = statistics - - -class DocumentLanguage(msrest.serialization.Model): - """DocumentLanguage. - - All required parameters must be populated in order to send to Azure. - - :param id: Required. Unique, non-empty document identifier. - :type id: str - :param detected_language: Required. Detected Language. - :type detected_language: ~azure.ai.textanalytics.models.DetectedLanguage - :param warnings: Required. Warnings encountered while processing document. - :type warnings: list[~azure.ai.textanalytics.models.TextAnalyticsWarning] - :param statistics: if showStats=true was specified in the request this field will contain - information about the document payload. - :type statistics: ~azure.ai.textanalytics.models.DocumentStatistics - """ - - _validation = { - 'id': {'required': True}, - 'detected_language': {'required': True}, - 'warnings': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'detected_language': {'key': 'detectedLanguage', 'type': 'DetectedLanguage'}, - 'warnings': {'key': 'warnings', 'type': '[TextAnalyticsWarning]'}, - 'statistics': {'key': 'statistics', 'type': 'DocumentStatistics'}, - } - - def __init__( - self, - *, - id: str, - detected_language: "DetectedLanguage", - warnings: List["TextAnalyticsWarning"], - statistics: Optional["DocumentStatistics"] = None, - **kwargs - ): - super(DocumentLanguage, self).__init__(**kwargs) - self.id = id - self.detected_language = detected_language - self.warnings = warnings - self.statistics = statistics - - -class DocumentLinkedEntities(msrest.serialization.Model): - """DocumentLinkedEntities. - - All required parameters must be populated in order to send to Azure. - - :param id: Required. Unique, non-empty document identifier. - :type id: str - :param entities: Required. Recognized well-known entities in the document. - :type entities: list[~azure.ai.textanalytics.models.LinkedEntity] - :param warnings: Required. Warnings encountered while processing document. - :type warnings: list[~azure.ai.textanalytics.models.TextAnalyticsWarning] - :param statistics: if showStats=true was specified in the request this field will contain - information about the document payload. - :type statistics: ~azure.ai.textanalytics.models.DocumentStatistics - """ - - _validation = { - 'id': {'required': True}, - 'entities': {'required': True}, - 'warnings': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'entities': {'key': 'entities', 'type': '[LinkedEntity]'}, - 'warnings': {'key': 'warnings', 'type': '[TextAnalyticsWarning]'}, - 'statistics': {'key': 'statistics', 'type': 'DocumentStatistics'}, - } - - def __init__( - self, - *, - id: str, - entities: List["LinkedEntity"], - warnings: List["TextAnalyticsWarning"], - statistics: Optional["DocumentStatistics"] = None, - **kwargs - ): - super(DocumentLinkedEntities, self).__init__(**kwargs) - self.id = id - self.entities = entities - self.warnings = warnings - self.statistics = statistics - - -class DocumentSentiment(msrest.serialization.Model): - """DocumentSentiment. - - All required parameters must be populated in order to send to Azure. - - :param id: Required. Unique, non-empty document identifier. - :type id: str - :param sentiment: Required. Predicted sentiment for document (Negative, Neutral, Positive, or - Mixed). Possible values include: "positive", "neutral", "negative", "mixed". - :type sentiment: str or ~azure.ai.textanalytics.models.DocumentSentimentValue - :param statistics: if showStats=true was specified in the request this field will contain - information about the document payload. - :type statistics: ~azure.ai.textanalytics.models.DocumentStatistics - :param confidence_scores: Required. Document level sentiment confidence scores between 0 and 1 - for each sentiment class. - :type confidence_scores: ~azure.ai.textanalytics.models.SentimentConfidenceScorePerLabel - :param sentences: Required. Sentence level sentiment analysis. - :type sentences: list[~azure.ai.textanalytics.models.SentenceSentiment] - :param warnings: Required. Warnings encountered while processing document. - :type warnings: list[~azure.ai.textanalytics.models.TextAnalyticsWarning] - """ - - _validation = { - 'id': {'required': True}, - 'sentiment': {'required': True}, - 'confidence_scores': {'required': True}, - 'sentences': {'required': True}, - 'warnings': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'sentiment': {'key': 'sentiment', 'type': 'str'}, - 'statistics': {'key': 'statistics', 'type': 'DocumentStatistics'}, - 'confidence_scores': {'key': 'confidenceScores', 'type': 'SentimentConfidenceScorePerLabel'}, - 'sentences': {'key': 'sentences', 'type': '[SentenceSentiment]'}, - 'warnings': {'key': 'warnings', 'type': '[TextAnalyticsWarning]'}, - } - - def __init__( - self, - *, - id: str, - sentiment: Union[str, "DocumentSentimentValue"], - confidence_scores: "SentimentConfidenceScorePerLabel", - sentences: List["SentenceSentiment"], - warnings: List["TextAnalyticsWarning"], - statistics: Optional["DocumentStatistics"] = None, - **kwargs - ): - super(DocumentSentiment, self).__init__(**kwargs) - self.id = id - self.sentiment = sentiment - self.statistics = statistics - self.confidence_scores = confidence_scores - self.sentences = sentences - self.warnings = warnings - - -class DocumentStatistics(msrest.serialization.Model): - """if showStats=true was specified in the request this field will contain information about the document payload. - - All required parameters must be populated in order to send to Azure. - - :param characters_count: Required. Number of text elements recognized in the document. - :type characters_count: int - :param transactions_count: Required. Number of transactions for the document. - :type transactions_count: int - """ - - _validation = { - 'characters_count': {'required': True}, - 'transactions_count': {'required': True}, - } - - _attribute_map = { - 'characters_count': {'key': 'charactersCount', 'type': 'int'}, - 'transactions_count': {'key': 'transactionsCount', 'type': 'int'}, - } - - def __init__( - self, - *, - characters_count: int, - transactions_count: int, - **kwargs - ): - super(DocumentStatistics, self).__init__(**kwargs) - self.characters_count = characters_count - self.transactions_count = transactions_count - - -class EntitiesResult(msrest.serialization.Model): - """EntitiesResult. - - All required parameters must be populated in order to send to Azure. - - :param documents: Required. Response by document. - :type documents: list[~azure.ai.textanalytics.models.DocumentEntities] - :param errors: Required. Errors by document id. - :type errors: list[~azure.ai.textanalytics.models.DocumentError] - :param statistics: if showStats=true was specified in the request this field will contain - information about the request payload. - :type statistics: ~azure.ai.textanalytics.models.RequestStatistics - :param model_version: Required. This field indicates which model is used for scoring. - :type model_version: str - """ - - _validation = { - 'documents': {'required': True}, - 'errors': {'required': True}, - 'model_version': {'required': True}, - } - - _attribute_map = { - 'documents': {'key': 'documents', 'type': '[DocumentEntities]'}, - 'errors': {'key': 'errors', 'type': '[DocumentError]'}, - 'statistics': {'key': 'statistics', 'type': 'RequestStatistics'}, - 'model_version': {'key': 'modelVersion', 'type': 'str'}, - } - - def __init__( - self, - *, - documents: List["DocumentEntities"], - errors: List["DocumentError"], - model_version: str, - statistics: Optional["RequestStatistics"] = None, - **kwargs - ): - super(EntitiesResult, self).__init__(**kwargs) - self.documents = documents - self.errors = errors - self.statistics = statistics - self.model_version = model_version - - -class Entity(msrest.serialization.Model): - """Entity. - - All required parameters must be populated in order to send to Azure. - - :param text: Required. Entity text as appears in the request. - :type text: str - :param category: Required. Entity type, such as Person/Location/Org/SSN etc. - :type category: str - :param subcategory: Entity sub type, such as Age/Year/TimeRange etc. - :type subcategory: str - :param offset: Required. Start position (in Unicode characters) for the entity text. - :type offset: int - :param length: Required. Length (in Unicode characters) for the entity text. - :type length: int - :param confidence_score: Required. Confidence score between 0 and 1 of the extracted entity. - :type confidence_score: float - """ - - _validation = { - 'text': {'required': True}, - 'category': {'required': True}, - 'offset': {'required': True}, - 'length': {'required': True}, - 'confidence_score': {'required': True}, - } - - _attribute_map = { - 'text': {'key': 'text', 'type': 'str'}, - 'category': {'key': 'category', 'type': 'str'}, - 'subcategory': {'key': 'subcategory', 'type': 'str'}, - 'offset': {'key': 'offset', 'type': 'int'}, - 'length': {'key': 'length', 'type': 'int'}, - 'confidence_score': {'key': 'confidenceScore', 'type': 'float'}, - } - - def __init__( - self, - *, - text: str, - category: str, - offset: int, - length: int, - confidence_score: float, - subcategory: Optional[str] = None, - **kwargs - ): - super(Entity, self).__init__(**kwargs) - self.text = text - self.category = category - self.subcategory = subcategory - self.offset = offset - self.length = length - self.confidence_score = confidence_score - - -class EntityLinkingResult(msrest.serialization.Model): - """EntityLinkingResult. - - All required parameters must be populated in order to send to Azure. - - :param documents: Required. Response by document. - :type documents: list[~azure.ai.textanalytics.models.DocumentLinkedEntities] - :param errors: Required. Errors by document id. - :type errors: list[~azure.ai.textanalytics.models.DocumentError] - :param statistics: if showStats=true was specified in the request this field will contain - information about the request payload. - :type statistics: ~azure.ai.textanalytics.models.RequestStatistics - :param model_version: Required. This field indicates which model is used for scoring. - :type model_version: str - """ - - _validation = { - 'documents': {'required': True}, - 'errors': {'required': True}, - 'model_version': {'required': True}, - } - - _attribute_map = { - 'documents': {'key': 'documents', 'type': '[DocumentLinkedEntities]'}, - 'errors': {'key': 'errors', 'type': '[DocumentError]'}, - 'statistics': {'key': 'statistics', 'type': 'RequestStatistics'}, - 'model_version': {'key': 'modelVersion', 'type': 'str'}, - } - - def __init__( - self, - *, - documents: List["DocumentLinkedEntities"], - errors: List["DocumentError"], - model_version: str, - statistics: Optional["RequestStatistics"] = None, - **kwargs - ): - super(EntityLinkingResult, self).__init__(**kwargs) - self.documents = documents - self.errors = errors - self.statistics = statistics - self.model_version = model_version - - -class InnerError(msrest.serialization.Model): - """InnerError. - - All required parameters must be populated in order to send to Azure. - - :param code: Required. Error code. Possible values include: "invalidParameterValue", - "invalidRequestBodyFormat", "emptyRequest", "missingInputRecords", "invalidDocument", - "modelVersionIncorrect", "invalidDocumentBatch", "unsupportedLanguageCode", - "invalidCountryHint". - :type code: str or ~azure.ai.textanalytics.models.InnerErrorCodeValue - :param message: Required. Error message. - :type message: str - :param details: Error details. - :type details: dict[str, str] - :param target: Error target. - :type target: str - :param innererror: Inner error contains more specific information. - :type innererror: ~azure.ai.textanalytics.models.InnerError - """ - - _validation = { - 'code': {'required': True}, - 'message': {'required': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'details': {'key': 'details', 'type': '{str}'}, - 'target': {'key': 'target', 'type': 'str'}, - 'innererror': {'key': 'innererror', 'type': 'InnerError'}, - } - - def __init__( - self, - *, - code: Union[str, "InnerErrorCodeValue"], - message: str, - details: Optional[Dict[str, str]] = None, - target: Optional[str] = None, - innererror: Optional["InnerError"] = None, - **kwargs - ): - super(InnerError, self).__init__(**kwargs) - self.code = code - self.message = message - self.details = details - self.target = target - self.innererror = innererror - - -class KeyPhraseResult(msrest.serialization.Model): - """KeyPhraseResult. - - All required parameters must be populated in order to send to Azure. - - :param documents: Required. Response by document. - :type documents: list[~azure.ai.textanalytics.models.DocumentKeyPhrases] - :param errors: Required. Errors by document id. - :type errors: list[~azure.ai.textanalytics.models.DocumentError] - :param statistics: if showStats=true was specified in the request this field will contain - information about the request payload. - :type statistics: ~azure.ai.textanalytics.models.RequestStatistics - :param model_version: Required. This field indicates which model is used for scoring. - :type model_version: str - """ - - _validation = { - 'documents': {'required': True}, - 'errors': {'required': True}, - 'model_version': {'required': True}, - } - - _attribute_map = { - 'documents': {'key': 'documents', 'type': '[DocumentKeyPhrases]'}, - 'errors': {'key': 'errors', 'type': '[DocumentError]'}, - 'statistics': {'key': 'statistics', 'type': 'RequestStatistics'}, - 'model_version': {'key': 'modelVersion', 'type': 'str'}, - } - - def __init__( - self, - *, - documents: List["DocumentKeyPhrases"], - errors: List["DocumentError"], - model_version: str, - statistics: Optional["RequestStatistics"] = None, - **kwargs - ): - super(KeyPhraseResult, self).__init__(**kwargs) - self.documents = documents - self.errors = errors - self.statistics = statistics - self.model_version = model_version - - -class LanguageBatchInput(msrest.serialization.Model): - """LanguageBatchInput. - - All required parameters must be populated in order to send to Azure. - - :param documents: Required. - :type documents: list[~azure.ai.textanalytics.models.LanguageInput] - """ - - _validation = { - 'documents': {'required': True}, - } - - _attribute_map = { - 'documents': {'key': 'documents', 'type': '[LanguageInput]'}, - } - - def __init__( - self, - *, - documents: List["LanguageInput"], - **kwargs - ): - super(LanguageBatchInput, self).__init__(**kwargs) - self.documents = documents - - -class LanguageInput(msrest.serialization.Model): - """LanguageInput. - - All required parameters must be populated in order to send to Azure. - - :param id: Required. Unique, non-empty document identifier. - :type id: str - :param text: Required. - :type text: str - :param country_hint: - :type country_hint: str - """ - - _validation = { - 'id': {'required': True}, - 'text': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'text': {'key': 'text', 'type': 'str'}, - 'country_hint': {'key': 'countryHint', 'type': 'str'}, - } - - def __init__( - self, - *, - id: str, - text: str, - country_hint: Optional[str] = None, - **kwargs - ): - super(LanguageInput, self).__init__(**kwargs) - self.id = id - self.text = text - self.country_hint = country_hint - - -class LanguageResult(msrest.serialization.Model): - """LanguageResult. - - All required parameters must be populated in order to send to Azure. - - :param documents: Required. Response by document. - :type documents: list[~azure.ai.textanalytics.models.DocumentLanguage] - :param errors: Required. Errors by document id. - :type errors: list[~azure.ai.textanalytics.models.DocumentError] - :param statistics: if showStats=true was specified in the request this field will contain - information about the request payload. - :type statistics: ~azure.ai.textanalytics.models.RequestStatistics - :param model_version: Required. This field indicates which model is used for scoring. - :type model_version: str - """ - - _validation = { - 'documents': {'required': True}, - 'errors': {'required': True}, - 'model_version': {'required': True}, - } - - _attribute_map = { - 'documents': {'key': 'documents', 'type': '[DocumentLanguage]'}, - 'errors': {'key': 'errors', 'type': '[DocumentError]'}, - 'statistics': {'key': 'statistics', 'type': 'RequestStatistics'}, - 'model_version': {'key': 'modelVersion', 'type': 'str'}, - } - - def __init__( - self, - *, - documents: List["DocumentLanguage"], - errors: List["DocumentError"], - model_version: str, - statistics: Optional["RequestStatistics"] = None, - **kwargs - ): - super(LanguageResult, self).__init__(**kwargs) - self.documents = documents - self.errors = errors - self.statistics = statistics - self.model_version = model_version - - -class LinkedEntity(msrest.serialization.Model): - """LinkedEntity. - - All required parameters must be populated in order to send to Azure. - - :param name: Required. Entity Linking formal name. - :type name: str - :param matches: Required. List of instances this entity appears in the text. - :type matches: list[~azure.ai.textanalytics.models.Match] - :param language: Required. Language used in the data source. - :type language: str - :param id: Unique identifier of the recognized entity from the data source. - :type id: str - :param url: Required. URL for the entity's page from the data source. - :type url: str - :param data_source: Required. Data source used to extract entity linking, such as Wiki/Bing - etc. - :type data_source: str - """ - - _validation = { - 'name': {'required': True}, - 'matches': {'required': True}, - 'language': {'required': True}, - 'url': {'required': True}, - 'data_source': {'required': True}, - } - - _attribute_map = { - 'name': {'key': 'name', 'type': 'str'}, - 'matches': {'key': 'matches', 'type': '[Match]'}, - 'language': {'key': 'language', 'type': 'str'}, - 'id': {'key': 'id', 'type': 'str'}, - 'url': {'key': 'url', 'type': 'str'}, - 'data_source': {'key': 'dataSource', 'type': 'str'}, - } - - def __init__( - self, - *, - name: str, - matches: List["Match"], - language: str, - url: str, - data_source: str, - id: Optional[str] = None, - **kwargs - ): - super(LinkedEntity, self).__init__(**kwargs) - self.name = name - self.matches = matches - self.language = language - self.id = id - self.url = url - self.data_source = data_source - - -class Match(msrest.serialization.Model): - """Match. - - All required parameters must be populated in order to send to Azure. - - :param confidence_score: Required. If a well-known item is recognized, a decimal number - denoting the confidence level between 0 and 1 will be returned. - :type confidence_score: float - :param text: Required. Entity text as appears in the request. - :type text: str - :param offset: Required. Start position (in Unicode characters) for the entity match text. - :type offset: int - :param length: Required. Length (in Unicode characters) for the entity match text. - :type length: int - """ - - _validation = { - 'confidence_score': {'required': True}, - 'text': {'required': True}, - 'offset': {'required': True}, - 'length': {'required': True}, - } - - _attribute_map = { - 'confidence_score': {'key': 'confidenceScore', 'type': 'float'}, - 'text': {'key': 'text', 'type': 'str'}, - 'offset': {'key': 'offset', 'type': 'int'}, - 'length': {'key': 'length', 'type': 'int'}, - } - - def __init__( - self, - *, - confidence_score: float, - text: str, - offset: int, - length: int, - **kwargs - ): - super(Match, self).__init__(**kwargs) - self.confidence_score = confidence_score - self.text = text - self.offset = offset - self.length = length - - -class MultiLanguageBatchInput(msrest.serialization.Model): - """Contains a set of input documents to be analyzed by the service. - - All required parameters must be populated in order to send to Azure. - - :param documents: Required. The set of documents to process as part of this batch. - :type documents: list[~azure.ai.textanalytics.models.MultiLanguageInput] - """ - - _validation = { - 'documents': {'required': True}, - } - - _attribute_map = { - 'documents': {'key': 'documents', 'type': '[MultiLanguageInput]'}, - } - - def __init__( - self, - *, - documents: List["MultiLanguageInput"], - **kwargs - ): - super(MultiLanguageBatchInput, self).__init__(**kwargs) - self.documents = documents - - -class MultiLanguageInput(msrest.serialization.Model): - """Contains an input document to be analyzed by the service. - - All required parameters must be populated in order to send to Azure. - - :param id: Required. A unique, non-empty document identifier. - :type id: str - :param text: Required. The input text to process. - :type text: str - :param language: (Optional) This is the 2 letter ISO 639-1 representation of a language. For - example, use "en" for English; "es" for Spanish etc. If not set, use "en" for English as - default. - :type language: str - """ - - _validation = { - 'id': {'required': True}, - 'text': {'required': True}, - } - - _attribute_map = { - 'id': {'key': 'id', 'type': 'str'}, - 'text': {'key': 'text', 'type': 'str'}, - 'language': {'key': 'language', 'type': 'str'}, - } - - def __init__( - self, - *, - id: str, - text: str, - language: Optional[str] = None, - **kwargs - ): - super(MultiLanguageInput, self).__init__(**kwargs) - self.id = id - self.text = text - self.language = language - - -class RequestStatistics(msrest.serialization.Model): - """if showStats=true was specified in the request this field will contain information about the request payload. - - All required parameters must be populated in order to send to Azure. - - :param documents_count: Required. Number of documents submitted in the request. - :type documents_count: int - :param valid_documents_count: Required. Number of valid documents. This excludes empty, over- - size limit or non-supported languages documents. - :type valid_documents_count: int - :param erroneous_documents_count: Required. Number of invalid documents. This includes empty, - over-size limit or non-supported languages documents. - :type erroneous_documents_count: int - :param transactions_count: Required. Number of transactions for the request. - :type transactions_count: long - """ - - _validation = { - 'documents_count': {'required': True}, - 'valid_documents_count': {'required': True}, - 'erroneous_documents_count': {'required': True}, - 'transactions_count': {'required': True}, - } - - _attribute_map = { - 'documents_count': {'key': 'documentsCount', 'type': 'int'}, - 'valid_documents_count': {'key': 'validDocumentsCount', 'type': 'int'}, - 'erroneous_documents_count': {'key': 'erroneousDocumentsCount', 'type': 'int'}, - 'transactions_count': {'key': 'transactionsCount', 'type': 'long'}, - } - - def __init__( - self, - *, - documents_count: int, - valid_documents_count: int, - erroneous_documents_count: int, - transactions_count: int, - **kwargs - ): - super(RequestStatistics, self).__init__(**kwargs) - self.documents_count = documents_count - self.valid_documents_count = valid_documents_count - self.erroneous_documents_count = erroneous_documents_count - self.transactions_count = transactions_count - - -class SentenceSentiment(msrest.serialization.Model): - """SentenceSentiment. - - All required parameters must be populated in order to send to Azure. - - :param text: The sentence text. - :type text: str - :param sentiment: Required. The predicted Sentiment for the sentence. Possible values include: - "positive", "neutral", "negative". - :type sentiment: str or ~azure.ai.textanalytics.models.SentenceSentimentValue - :param confidence_scores: Required. The sentiment confidence score between 0 and 1 for the - sentence for all classes. - :type confidence_scores: ~azure.ai.textanalytics.models.SentimentConfidenceScorePerLabel - :param offset: Required. The sentence offset from the start of the document. - :type offset: int - :param length: Required. The length of the sentence by Unicode standard. - :type length: int - """ - - _validation = { - 'sentiment': {'required': True}, - 'confidence_scores': {'required': True}, - 'offset': {'required': True}, - 'length': {'required': True}, - } - - _attribute_map = { - 'text': {'key': 'text', 'type': 'str'}, - 'sentiment': {'key': 'sentiment', 'type': 'str'}, - 'confidence_scores': {'key': 'confidenceScores', 'type': 'SentimentConfidenceScorePerLabel'}, - 'offset': {'key': 'offset', 'type': 'int'}, - 'length': {'key': 'length', 'type': 'int'}, - } - - def __init__( - self, - *, - sentiment: Union[str, "SentenceSentimentValue"], - confidence_scores: "SentimentConfidenceScorePerLabel", - offset: int, - length: int, - text: Optional[str] = None, - **kwargs - ): - super(SentenceSentiment, self).__init__(**kwargs) - self.text = text - self.sentiment = sentiment - self.confidence_scores = confidence_scores - self.offset = offset - self.length = length - - -class SentimentConfidenceScorePerLabel(msrest.serialization.Model): - """Represents the confidence scores between 0 and 1 across all sentiment classes: positive, neutral, negative. - - All required parameters must be populated in order to send to Azure. - - :param positive: Required. - :type positive: float - :param neutral: Required. - :type neutral: float - :param negative: Required. - :type negative: float - """ - - _validation = { - 'positive': {'required': True}, - 'neutral': {'required': True}, - 'negative': {'required': True}, - } - - _attribute_map = { - 'positive': {'key': 'positive', 'type': 'float'}, - 'neutral': {'key': 'neutral', 'type': 'float'}, - 'negative': {'key': 'negative', 'type': 'float'}, - } - - def __init__( - self, - *, - positive: float, - neutral: float, - negative: float, - **kwargs - ): - super(SentimentConfidenceScorePerLabel, self).__init__(**kwargs) - self.positive = positive - self.neutral = neutral - self.negative = negative - - -class SentimentResponse(msrest.serialization.Model): - """SentimentResponse. - - All required parameters must be populated in order to send to Azure. - - :param documents: Required. Sentiment analysis per document. - :type documents: list[~azure.ai.textanalytics.models.DocumentSentiment] - :param errors: Required. Errors by document id. - :type errors: list[~azure.ai.textanalytics.models.DocumentError] - :param statistics: if showStats=true was specified in the request this field will contain - information about the request payload. - :type statistics: ~azure.ai.textanalytics.models.RequestStatistics - :param model_version: Required. This field indicates which model is used for scoring. - :type model_version: str - """ - - _validation = { - 'documents': {'required': True}, - 'errors': {'required': True}, - 'model_version': {'required': True}, - } - - _attribute_map = { - 'documents': {'key': 'documents', 'type': '[DocumentSentiment]'}, - 'errors': {'key': 'errors', 'type': '[DocumentError]'}, - 'statistics': {'key': 'statistics', 'type': 'RequestStatistics'}, - 'model_version': {'key': 'modelVersion', 'type': 'str'}, - } - - def __init__( - self, - *, - documents: List["DocumentSentiment"], - errors: List["DocumentError"], - model_version: str, - statistics: Optional["RequestStatistics"] = None, - **kwargs - ): - super(SentimentResponse, self).__init__(**kwargs) - self.documents = documents - self.errors = errors - self.statistics = statistics - self.model_version = model_version - - -class TextAnalyticsError(msrest.serialization.Model): - """TextAnalyticsError. - - All required parameters must be populated in order to send to Azure. - - :param code: Required. Error code. Possible values include: "invalidRequest", - "invalidArgument", "internalServerError", "serviceUnavailable". - :type code: str or ~azure.ai.textanalytics.models.ErrorCodeValue - :param message: Required. Error message. - :type message: str - :param target: Error target. - :type target: str - :param innererror: Inner error contains more specific information. - :type innererror: ~azure.ai.textanalytics.models.InnerError - :param details: Details about specific errors that led to this reported error. - :type details: list[~azure.ai.textanalytics.models.TextAnalyticsError] - """ - - _validation = { - 'code': {'required': True}, - 'message': {'required': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target': {'key': 'target', 'type': 'str'}, - 'innererror': {'key': 'innererror', 'type': 'InnerError'}, - 'details': {'key': 'details', 'type': '[TextAnalyticsError]'}, - } - - def __init__( - self, - *, - code: Union[str, "ErrorCodeValue"], - message: str, - target: Optional[str] = None, - innererror: Optional["InnerError"] = None, - details: Optional[List["TextAnalyticsError"]] = None, - **kwargs - ): - super(TextAnalyticsError, self).__init__(**kwargs) - self.code = code - self.message = message - self.target = target - self.innererror = innererror - self.details = details - - -class TextAnalyticsWarning(msrest.serialization.Model): - """TextAnalyticsWarning. - - All required parameters must be populated in order to send to Azure. - - :param code: Required. Error code. Possible values include: "LongWordsInDocument", - "DocumentTruncated". - :type code: str or ~azure.ai.textanalytics.models.WarningCodeValue - :param message: Required. Warning message. - :type message: str - :param target_ref: A JSON pointer reference indicating the target object. - :type target_ref: str - """ - - _validation = { - 'code': {'required': True}, - 'message': {'required': True}, - } - - _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, - 'target_ref': {'key': 'targetRef', 'type': 'str'}, - } - - def __init__( - self, - *, - code: Union[str, "WarningCodeValue"], - message: str, - target_ref: Optional[str] = None, - **kwargs - ): - super(TextAnalyticsWarning, self).__init__(**kwargs) - self.code = code - self.message = message - self.target_ref = target_ref diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/models/_text_analytics_client_enums.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/models/_text_analytics_client_enums.py deleted file mode 100644 index e96d02393a83..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/models/_text_analytics_client_enums.py +++ /dev/null @@ -1,56 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from enum import Enum - -class DocumentSentimentValue(str, Enum): - """Predicted sentiment for document (Negative, Neutral, Positive, or Mixed). - """ - - positive = "positive" - neutral = "neutral" - negative = "negative" - mixed = "mixed" - -class ErrorCodeValue(str, Enum): - """Error code. - """ - - invalid_request = "invalidRequest" - invalid_argument = "invalidArgument" - internal_server_error = "internalServerError" - service_unavailable = "serviceUnavailable" - -class InnerErrorCodeValue(str, Enum): - """Error code. - """ - - invalid_parameter_value = "invalidParameterValue" - invalid_request_body_format = "invalidRequestBodyFormat" - empty_request = "emptyRequest" - missing_input_records = "missingInputRecords" - invalid_document = "invalidDocument" - model_version_incorrect = "modelVersionIncorrect" - invalid_document_batch = "invalidDocumentBatch" - unsupported_language_code = "unsupportedLanguageCode" - invalid_country_hint = "invalidCountryHint" - -class SentenceSentimentValue(str, Enum): - """The predicted Sentiment for the sentence. - """ - - positive = "positive" - neutral = "neutral" - negative = "negative" - -class WarningCodeValue(str, Enum): - """Error code. - """ - - long_words_in_document = "LongWordsInDocument" - document_truncated = "DocumentTruncated" diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/operations/__init__.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/operations/__init__.py deleted file mode 100644 index 4384511c0346..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/operations/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._text_analytics_client_operations import TextAnalyticsClientOperationsMixin - -__all__ = [ - 'TextAnalyticsClientOperationsMixin', -] diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/operations/_text_analytics_client_operations.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/operations/_text_analytics_client_operations.py deleted file mode 100644 index 77c33a1778c7..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/operations/_text_analytics_client_operations.py +++ /dev/null @@ -1,389 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import warnings - -from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse - -from .. import models - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar - - T = TypeVar('T') - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -class TextAnalyticsClientOperationsMixin(object): - - def entities_recognition_general( - self, - documents, # type: List["models.MultiLanguageInput"] - model_version=None, # type: Optional[str] - show_stats=None, # type: Optional[bool] - **kwargs # type: Any - ): - # type: (...) -> "models.EntitiesResult" - """The API returns a list of general named entities in a given document. For the list of supported entity types, check :code:`Supported Entity Types in Text Analytics API`. See the :code:`Supported languages in Text Analytics API` for the list of enabled languages. - - Named Entity Recognition. - - :param documents: The set of documents to process as part of this batch. - :type documents: list[~azure.ai.textanalytics.models.MultiLanguageInput] - :param model_version: (Optional) This value indicates which model will be used for scoring. If - a model-version is not specified, the API should default to the latest, non-preview version. - :type model_version: str - :param show_stats: (Optional) if set to true, response will contain input and document level - statistics. - :type show_stats: bool - :keyword callable cls: A custom type or function that will be passed the direct response - :return: EntitiesResult or the result of cls(response) - :rtype: ~azure.ai.textanalytics.models.EntitiesResult - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["models.EntitiesResult"] - error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} - error_map.update(kwargs.pop('error_map', {})) - - _input = models.MultiLanguageBatchInput(documents=documents) - content_type = kwargs.pop("content_type", "application/json") - - # Construct URL - url = self.entities_recognition_general.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if model_version is not None: - query_parameters['model-version'] = self._serialize.query("model_version", model_version, 'str') - if show_stats is not None: - query_parameters['showStats'] = self._serialize.query("show_stats", show_stats, 'bool') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = 'application/json' - - # Construct and send request - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(_input, 'MultiLanguageBatchInput') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize(models.TextAnalyticsError, response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize('EntitiesResult', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - entities_recognition_general.metadata = {'url': '/entities/recognition/general'} # type: ignore - - def entities_linking( - self, - documents, # type: List["models.MultiLanguageInput"] - model_version=None, # type: Optional[str] - show_stats=None, # type: Optional[bool] - **kwargs # type: Any - ): - # type: (...) -> "models.EntityLinkingResult" - """The API returns a list of recognized entities with links to a well-known knowledge base. See the :code:`Supported languages in Text Analytics API` for the list of enabled languages. - - Linked entities from a well-known knowledge base. - - :param documents: The set of documents to process as part of this batch. - :type documents: list[~azure.ai.textanalytics.models.MultiLanguageInput] - :param model_version: (Optional) This value indicates which model will be used for scoring. If - a model-version is not specified, the API should default to the latest, non-preview version. - :type model_version: str - :param show_stats: (Optional) if set to true, response will contain input and document level - statistics. - :type show_stats: bool - :keyword callable cls: A custom type or function that will be passed the direct response - :return: EntityLinkingResult or the result of cls(response) - :rtype: ~azure.ai.textanalytics.models.EntityLinkingResult - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["models.EntityLinkingResult"] - error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} - error_map.update(kwargs.pop('error_map', {})) - - _input = models.MultiLanguageBatchInput(documents=documents) - content_type = kwargs.pop("content_type", "application/json") - - # Construct URL - url = self.entities_linking.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if model_version is not None: - query_parameters['model-version'] = self._serialize.query("model_version", model_version, 'str') - if show_stats is not None: - query_parameters['showStats'] = self._serialize.query("show_stats", show_stats, 'bool') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = 'application/json' - - # Construct and send request - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(_input, 'MultiLanguageBatchInput') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize(models.TextAnalyticsError, response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize('EntityLinkingResult', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - entities_linking.metadata = {'url': '/entities/linking'} # type: ignore - - def key_phrases( - self, - documents, # type: List["models.MultiLanguageInput"] - model_version=None, # type: Optional[str] - show_stats=None, # type: Optional[bool] - **kwargs # type: Any - ): - # type: (...) -> "models.KeyPhraseResult" - """The API returns a list of strings denoting the key phrases in the input text. See the :code:`Supported languages in Text Analytics API` for the list of enabled languages. - - Key Phrases. - - :param documents: The set of documents to process as part of this batch. - :type documents: list[~azure.ai.textanalytics.models.MultiLanguageInput] - :param model_version: (Optional) This value indicates which model will be used for scoring. If - a model-version is not specified, the API should default to the latest, non-preview version. - :type model_version: str - :param show_stats: (Optional) if set to true, response will contain input and document level - statistics. - :type show_stats: bool - :keyword callable cls: A custom type or function that will be passed the direct response - :return: KeyPhraseResult or the result of cls(response) - :rtype: ~azure.ai.textanalytics.models.KeyPhraseResult - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["models.KeyPhraseResult"] - error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} - error_map.update(kwargs.pop('error_map', {})) - - _input = models.MultiLanguageBatchInput(documents=documents) - content_type = kwargs.pop("content_type", "application/json") - - # Construct URL - url = self.key_phrases.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if model_version is not None: - query_parameters['model-version'] = self._serialize.query("model_version", model_version, 'str') - if show_stats is not None: - query_parameters['showStats'] = self._serialize.query("show_stats", show_stats, 'bool') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = 'application/json' - - # Construct and send request - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(_input, 'MultiLanguageBatchInput') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize(models.TextAnalyticsError, response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize('KeyPhraseResult', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - key_phrases.metadata = {'url': '/keyPhrases'} # type: ignore - - def languages( - self, - documents, # type: List["models.LanguageInput"] - model_version=None, # type: Optional[str] - show_stats=None, # type: Optional[bool] - **kwargs # type: Any - ): - # type: (...) -> "models.LanguageResult" - """The API returns the detected language and a numeric score between 0 and 1. Scores close to 1 indicate 100% certainty that the identified language is true. See the :code:`Supported languages in Text Analytics API` for the list of enabled languages. - - Detect Language. - - :param documents: - :type documents: list[~azure.ai.textanalytics.models.LanguageInput] - :param model_version: (Optional) This value indicates which model will be used for scoring. If - a model-version is not specified, the API should default to the latest, non-preview version. - :type model_version: str - :param show_stats: (Optional) if set to true, response will contain input and document level - statistics. - :type show_stats: bool - :keyword callable cls: A custom type or function that will be passed the direct response - :return: LanguageResult or the result of cls(response) - :rtype: ~azure.ai.textanalytics.models.LanguageResult - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["models.LanguageResult"] - error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} - error_map.update(kwargs.pop('error_map', {})) - - _input = models.LanguageBatchInput(documents=documents) - content_type = kwargs.pop("content_type", "application/json") - - # Construct URL - url = self.languages.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if model_version is not None: - query_parameters['model-version'] = self._serialize.query("model_version", model_version, 'str') - if show_stats is not None: - query_parameters['showStats'] = self._serialize.query("show_stats", show_stats, 'bool') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = 'application/json' - - # Construct and send request - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(_input, 'LanguageBatchInput') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize(models.TextAnalyticsError, response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize('LanguageResult', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - languages.metadata = {'url': '/languages'} # type: ignore - - def sentiment( - self, - documents, # type: List["models.MultiLanguageInput"] - model_version=None, # type: Optional[str] - show_stats=None, # type: Optional[bool] - **kwargs # type: Any - ): - # type: (...) -> "models.SentimentResponse" - """The API returns a sentiment prediction, as well as sentiment scores for each sentiment class (Positive, Negative, and Neutral) for the document and each sentence within it. See the :code:`Supported languages in Text Analytics API` for the list of enabled languages. - - Sentiment. - - :param documents: The set of documents to process as part of this batch. - :type documents: list[~azure.ai.textanalytics.models.MultiLanguageInput] - :param model_version: (Optional) This value indicates which model will be used for scoring. If - a model-version is not specified, the API should default to the latest, non-preview version. - :type model_version: str - :param show_stats: (Optional) if set to true, response will contain input and document level - statistics. - :type show_stats: bool - :keyword callable cls: A custom type or function that will be passed the direct response - :return: SentimentResponse or the result of cls(response) - :rtype: ~azure.ai.textanalytics.models.SentimentResponse - :raises: ~azure.core.exceptions.HttpResponseError - """ - cls = kwargs.pop('cls', None) # type: ClsType["models.SentimentResponse"] - error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} - error_map.update(kwargs.pop('error_map', {})) - - _input = models.MultiLanguageBatchInput(documents=documents) - content_type = kwargs.pop("content_type", "application/json") - - # Construct URL - url = self.sentiment.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if model_version is not None: - query_parameters['model-version'] = self._serialize.query("model_version", model_version, 'str') - if show_stats is not None: - query_parameters['showStats'] = self._serialize.query("show_stats", show_stats, 'bool') - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = 'application/json' - - # Construct and send request - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(_input, 'MultiLanguageBatchInput') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) - - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize(models.TextAnalyticsError, response) - raise HttpResponseError(response=response, model=error) - - deserialized = self._deserialize('SentimentResponse', pipeline_response) - - if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - sentiment.metadata = {'url': '/sentiment'} # type: ignore diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/py.typed b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_generated/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_models.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_models.py deleted file mode 100644 index 692178449da8..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_models.py +++ /dev/null @@ -1,688 +0,0 @@ -# coding=utf-8 -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -from ._generated.models._models import LanguageInput -from ._generated.models._models import MultiLanguageInput - - -class DictMixin(object): - - def __setitem__(self, key, item): - self.__dict__[key] = item - - def __getitem__(self, key): - return self.__dict__[key] - - def __repr__(self): - return str(self) - - def __len__(self): - return len(self.keys()) - - def __delitem__(self, key): - self.__dict__[key] = None - - def __eq__(self, other): - """Compare objects by comparing all attributes.""" - if isinstance(other, self.__class__): - return self.__dict__ == other.__dict__ - return False - - def __ne__(self, other): - """Compare objects by comparing all attributes.""" - return not self.__eq__(other) - - def __str__(self): - return str({k: v for k, v in self.__dict__.items() if not k.startswith('_')}) - - def has_key(self, k): - return k in self.__dict__ - - def update(self, *args, **kwargs): - return self.__dict__.update(*args, **kwargs) - - def keys(self): - return [k for k in self.__dict__ if not k.startswith('_')] - - def values(self): - return [v for k, v in self.__dict__.items() if not k.startswith('_')] - - def items(self): - return [(k, v) for k, v in self.__dict__.items() if not k.startswith('_')] - - def get(self, key, default=None): - if key in self.__dict__: - return self.__dict__[key] - return default - - -class DetectedLanguage(DictMixin): - """DetectedLanguage contains the predicted language found in text, - its confidence score, and ISO 639-1 representation. - - :param name: Long name of a detected language (e.g. English, - French). - :type name: str - :param iso6391_name: A two letter representation of the detected - language according to the ISO 639-1 standard (e.g. en, fr). - :type iso6391_name: str - :param confidence_score: A confidence score between 0 and 1. Scores close - to 1 indicate 100% certainty that the identified language is true. - :type confidence_score: float - """ - - def __init__(self, **kwargs): - self.name = kwargs.get("name", None) - self.iso6391_name = kwargs.get("iso6391_name", None) - self.confidence_score = kwargs.get("confidence_score", None) - - @classmethod - def _from_generated(cls, language): - return cls( - name=language.name, iso6391_name=language.iso6391_name, confidence_score=language.confidence_score - ) - - def __repr__(self): - return "DetectedLanguage(name={}, iso6391_name={}, confidence_score={})" \ - .format(self.name, self.iso6391_name, self.confidence_score)[:1024] - - -class RecognizeEntitiesResult(DictMixin): - """RecognizeEntitiesResult is a result object which contains - the recognized entities from a particular document. - - :param id: Unique, non-empty document identifier that matches the - document id that was passed in with the request. If not specified - in the request, an id is assigned for the document. - :type id: str - :param entities: Recognized entities in the document. - :type entities: - list[~azure.ai.textanalytics.CategorizedEntity] - :param warnings: Warnings encountered while processing document. Results will still be returned - if there are warnings, but they may not be fully accurate. - :type warnings: list[~azure.ai.textanalytics.TextAnalyticsWarning] - :param statistics: If show_stats=true was specified in the request this - field will contain information about the document payload. - :type statistics: - ~azure.ai.textanalytics.TextDocumentStatistics - :param bool is_error: Boolean check for error item when iterating over list of - results. Always False for an instance of a RecognizeEntitiesResult. - """ - - def __init__(self, **kwargs): - self.id = kwargs.get("id", None) - self.entities = kwargs.get("entities", None) - self.warnings = kwargs.get("warnings", []) - self.statistics = kwargs.get("statistics", None) - self.is_error = False - - def __repr__(self): - return "RecognizeEntitiesResult(id={}, entities={}, warnings={}, statistics={}, is_error={})" \ - .format(self.id, repr(self.entities), repr(self.warnings), repr(self.statistics), self.is_error)[:1024] - - -class DetectLanguageResult(DictMixin): - """DetectLanguageResult is a result object which contains - the detected language of a particular document. - - :param id: Unique, non-empty document identifier that matches the - document id that was passed in with the request. If not specified - in the request, an id is assigned for the document. - :type id: str - :param primary_language: The primary language detected in the document. - :type primary_language: ~azure.ai.textanalytics.DetectedLanguage - :param warnings: Warnings encountered while processing document. Results will still be returned - if there are warnings, but they may not be fully accurate. - :type warnings: list[~azure.ai.textanalytics.TextAnalyticsWarning] - :param statistics: If show_stats=true was specified in the request this - field will contain information about the document payload. - :type statistics: - ~azure.ai.textanalytics.TextDocumentStatistics - :param bool is_error: Boolean check for error item when iterating over list of - results. Always False for an instance of a DetectLanguageResult. - """ - - def __init__(self, **kwargs): - self.id = kwargs.get("id", None) - self.primary_language = kwargs.get("primary_language", None) - self.warnings = kwargs.get("warnings", []) - self.statistics = kwargs.get("statistics", None) - self.is_error = False - - def __repr__(self): - return "DetectLanguageResult(id={}, primary_language={}, warnings={}, statistics={}, "\ - "is_error={})".format(self.id, repr(self.primary_language), repr(self.warnings), - repr(self.statistics), self.is_error)[:1024] - - -class CategorizedEntity(DictMixin): - """CategorizedEntity contains information about a particular - entity found in text. - - :param text: Entity text as appears in the request. - :type text: str - :param category: Entity category, such as Person/Location/Org/SSN etc - :type category: str - :param subcategory: Entity subcategory, such as Age/Year/TimeRange etc - :type subcategory: str - :param confidence_score: Confidence score between 0 and 1 of the extracted - entity. - :type confidence_score: float - """ - - def __init__(self, **kwargs): - self.text = kwargs.get('text', None) - self.category = kwargs.get('category', None) - self.subcategory = kwargs.get('subcategory', None) - self.confidence_score = kwargs.get('confidence_score', None) - - @classmethod - def _from_generated(cls, entity): - return cls( - text=entity.text, - category=entity.category, - subcategory=entity.subcategory, - confidence_score=entity.confidence_score, - ) - - def __repr__(self): - return "CategorizedEntity(text={}, category={}, subcategory={}, confidence_score={})".format( - self.text, self.category, self.subcategory, self.confidence_score - )[:1024] - - -class TextAnalyticsError(DictMixin): - """TextAnalyticsError contains the error code, message, and - other details that explain why the batch or individual document - failed to be processed by the service. - - :param code: Error code. Possible values include: - 'invalidRequest', 'invalidArgument', 'internalServerError', - 'serviceUnavailable', 'invalidParameterValue', 'invalidRequestBodyFormat', - 'emptyRequest', 'missingInputRecords', 'invalidDocument', 'modelVersionIncorrect', - 'invalidDocumentBatch', 'unsupportedLanguageCode', 'invalidCountryHint' - :type code: str - :param message: Error message. - :type message: str - :param target: Error target. - :type target: str - """ - - def __init__(self, **kwargs): - self.code = kwargs.get('code', None) - self.message = kwargs.get('message', None) - self.target = kwargs.get('target', None) - - @classmethod - def _from_generated(cls, err): - if err.innererror: - return cls( - code=err.innererror.code, - message=err.innererror.message, - target=err.innererror.target - ) - return cls( - code=err.code, - message=err.message, - target=err.target - ) - - def __repr__(self): - return "TextAnalyticsError(code={}, message={}, target={})" \ - .format(self.code, self.message, self.target)[:1024] - -class TextAnalyticsWarning(DictMixin): - """TextAnalyticsWarning contains the warning code and message that explains why - the response has a warning. - - :param code: Warning code. Possible values include: 'LongWordsInDocument', - 'DocumentTruncated'. - :type code: str - :param message: Warning message. - :type message: str - """ - - def __init__(self, **kwargs): - self.code = kwargs.get('code', None) - self.message = kwargs.get('message', None) - - @classmethod - def _from_generated(cls, warning): - return cls( - code=warning.code, - message=warning.message, - ) - - def __repr__(self): - return "TextAnalyticsWarning(code={}, message={})" \ - .format(self.code, self.message)[:1024] - - -class ExtractKeyPhrasesResult(DictMixin): - """ExtractKeyPhrasesResult is a result object which contains - the key phrases found in a particular document. - - :param id: Unique, non-empty document identifier that matches the - document id that was passed in with the request. If not specified - in the request, an id is assigned for the document. - :type id: str - :param key_phrases: A list of representative words or phrases. - The number of key phrases returned is proportional to the number of words - in the input document. - :type key_phrases: list[str] - :param warnings: Warnings encountered while processing document. Results will still be returned - if there are warnings, but they may not be fully accurate. - :type warnings: list[~azure.ai.textanalytics.TextAnalyticsWarning] - :param statistics: If show_stats=true was specified in the request this - field will contain information about the document payload. - :type statistics: - ~azure.ai.textanalytics.TextDocumentStatistics - :param bool is_error: Boolean check for error item when iterating over list of - results. Always False for an instance of a ExtractKeyPhrasesResult. - """ - - def __init__(self, **kwargs): - self.id = kwargs.get("id", None) - self.key_phrases = kwargs.get("key_phrases", None) - self.warnings = kwargs.get("warnings", []) - self.statistics = kwargs.get("statistics", None) - self.is_error = False - - def __repr__(self): - return "ExtractKeyPhrasesResult(id={}, key_phrases={}, warnings={}, statistics={}, is_error={})" \ - .format(self.id, self.key_phrases, repr(self.warnings), repr(self.statistics), self.is_error)[:1024] - - -class RecognizeLinkedEntitiesResult(DictMixin): - """RecognizeLinkedEntitiesResult is a result object which contains - links to a well-known knowledge base, like for example, Wikipedia or Bing. - - :param id: Unique, non-empty document identifier that matches the - document id that was passed in with the request. If not specified - in the request, an id is assigned for the document. - :type id: str - :param entities: Recognized well-known entities in the document. - :type entities: - list[~azure.ai.textanalytics.LinkedEntity] - :param warnings: Warnings encountered while processing document. Results will still be returned - if there are warnings, but they may not be fully accurate. - :type warnings: list[~azure.ai.textanalytics.TextAnalyticsWarning] - :param statistics: If show_stats=true was specified in the request this - field will contain information about the document payload. - :type statistics: - ~azure.ai.textanalytics.TextDocumentStatistics - :param bool is_error: Boolean check for error item when iterating over list of - results. Always False for an instance of a RecognizeLinkedEntitiesResult. - """ - - def __init__(self, **kwargs): - self.id = kwargs.get("id", None) - self.entities = kwargs.get("entities", None) - self.warnings = kwargs.get("warnings", []) - self.statistics = kwargs.get("statistics", None) - self.is_error = False - - def __repr__(self): - return "RecognizeLinkedEntitiesResult(id={}, entities={}, warnings={}, statistics={}, is_error={})" \ - .format(self.id, repr(self.entities), repr(self.warnings), repr(self.statistics), self.is_error)[:1024] - - -class AnalyzeSentimentResult(DictMixin): - """AnalyzeSentimentResult is a result object which contains - the overall predicted sentiment and confidence scores for your document - and a per-sentence sentiment prediction with scores. - - :param id: Unique, non-empty document identifier that matches the - document id that was passed in with the request. If not specified - in the request, an id is assigned for the document. - :type id: str - :param sentiment: Predicted sentiment for document (Negative, - Neutral, Positive, or Mixed). Possible values include: 'positive', - 'neutral', 'negative', 'mixed' - :type sentiment: str - :param warnings: Warnings encountered while processing document. Results will still be returned - if there are warnings, but they may not be fully accurate. - :type warnings: list[~azure.ai.textanalytics.TextAnalyticsWarning] - :param statistics: If show_stats=true was specified in the request this - field will contain information about the document payload. - :type statistics: - ~azure.ai.textanalytics.TextDocumentStatistics - :param confidence_scores: Document level sentiment confidence - scores between 0 and 1 for each sentiment label. - :type confidence_scores: - ~azure.ai.textanalytics.SentimentConfidenceScores - :param sentences: Sentence level sentiment analysis. - :type sentences: - list[~azure.ai.textanalytics.SentenceSentiment] - :param bool is_error: Boolean check for error item when iterating over list of - results. Always False for an instance of a AnalyzeSentimentResult. - """ - - def __init__(self, **kwargs): - self.id = kwargs.get("id", None) - self.sentiment = kwargs.get("sentiment", None) - self.warnings = kwargs.get("warnings", []) - self.statistics = kwargs.get("statistics", None) - self.confidence_scores = kwargs.get("confidence_scores", None) - self.sentences = kwargs.get("sentences", None) - self.is_error = False - - def __repr__(self): - return "AnalyzeSentimentResult(id={}, sentiment={}, warnings={}, statistics={}, confidence_scores={}, "\ - "sentences={}, is_error={})".format( - self.id, self.sentiment, repr(self.warnings), repr(self.statistics), - repr(self.confidence_scores), repr(self.sentences), self.is_error)[:1024] - - -class TextDocumentStatistics(DictMixin): - """TextDocumentStatistics contains information about - the document payload. - - :param character_count: Number of text elements recognized in - the document. - :type character_count: int - :param transaction_count: Number of transactions for the - document. - :type transaction_count: int - """ - - def __init__(self, **kwargs): - self.character_count = kwargs.get("character_count", None) - self.transaction_count = kwargs.get("transaction_count", None) - - @classmethod - def _from_generated(cls, stats): - if stats is None: - return None - return cls( - character_count=stats.characters_count, - transaction_count=stats.transactions_count, - ) - - def __repr__(self): - return "TextDocumentStatistics(character_count={}, transaction_count={})" \ - .format(self.character_count, self.transaction_count)[:1024] - - -class DocumentError(DictMixin): - """DocumentError is an error object which represents an error on - the individual document. - - :param id: Unique, non-empty document identifier that matches the - document id that was passed in with the request. If not specified - in the request, an id is assigned for the document. - :type id: str - :param error: The document error. - :type error: ~azure.ai.textanalytics.TextAnalyticsError - :param bool is_error: Boolean check for error item when iterating over list of - results. Always True for an instance of a DocumentError. - """ - - def __init__(self, **kwargs): - self.id = kwargs.get("id", None) - self.error = kwargs.get("error", None) - self.is_error = True - - def __getattr__(self, attr): - result_set = set() - result_set.update( - RecognizeEntitiesResult().keys() - + DetectLanguageResult().keys() + RecognizeLinkedEntitiesResult().keys() - + AnalyzeSentimentResult().keys() + ExtractKeyPhrasesResult().keys() - ) - result_attrs = result_set.difference(DocumentError().keys()) - if attr in result_attrs: - raise AttributeError( - "'DocumentError' object has no attribute '{}'. The service was unable to process this document:\n" - "Document Id: {}\nError: {} - {}\n". - format(attr, self.id, self.error.code, self.error.message) - ) - raise AttributeError("'DocumentError' object has no attribute '{}'".format(attr)) - - @classmethod - def _from_generated(cls, doc_err): - return cls( - id=doc_err.id, - error=TextAnalyticsError._from_generated(doc_err.error), # pylint: disable=protected-access - is_error=True - ) - - def __repr__(self): - return "DocumentError(id={}, error={}, is_error={})" \ - .format(self.id, repr(self.error), self.is_error)[:1024] - - -class DetectLanguageInput(LanguageInput): - """The input document to be analyzed for detecting language. - - :param id: Required. Unique, non-empty document identifier. - :type id: str - :param text: Required. The input text to process. - :type text: str - :param country_hint: A country hint to help better detect - the language of the text. Accepts two letter country codes - specified by ISO 3166-1 alpha-2. Defaults to "US". Pass - in the string "none" to not use a country_hint. - :type country_hint: str - """ - - def __init__(self, **kwargs): - super(DetectLanguageInput, self).__init__(**kwargs) - self.id = kwargs.get("id", None) - self.text = kwargs.get("text", None) - self.country_hint = kwargs.get("country_hint", None) - - def __repr__(self): - return "DetectLanguageInput(id={}, text={}, country_hint={})" \ - .format(self.id, self.text, self.country_hint)[:1024] - - -class LinkedEntity(DictMixin): - """LinkedEntity contains a link to the well-known recognized - entity in text. The link comes from a data source like Wikipedia - or Bing. It additionally includes all of the matches of this - entity found in the document. - - :param name: Entity Linking formal name. - :type name: str - :param matches: List of instances this entity appears in the text. - :type matches: - list[~azure.ai.textanalytics.LinkedEntityMatch] - :param language: Language used in the data source. - :type language: str - :param data_source_entity_id: Unique identifier of the recognized entity from the data - source. - :type data_source_entity_id: str - :param url: URL to the entity's page from the data source. - :type url: str - :param data_source: Data source used to extract entity linking, - such as Wiki/Bing etc. - :type data_source: str - """ - - def __init__(self, **kwargs): - self.name = kwargs.get("name", None) - self.matches = kwargs.get("matches", None) - self.language = kwargs.get("language", None) - self.data_source_entity_id = kwargs.get("data_source_entity_id", None) - self.url = kwargs.get("url", None) - self.data_source = kwargs.get("data_source", None) - - @classmethod - def _from_generated(cls, entity): - return cls( - name=entity.name, - matches=[LinkedEntityMatch._from_generated(e) for e in entity.matches], # pylint: disable=protected-access - language=entity.language, - data_source_entity_id=entity.id, - url=entity.url, - data_source=entity.data_source, - ) - - def __repr__(self): - return "LinkedEntity(name={}, matches={}, language={}, data_source_entity_id={}, url={}, " \ - "data_source={})".format(self.name, repr(self.matches), self.language, self.data_source_entity_id, - self.url, self.data_source)[:1024] - - -class LinkedEntityMatch(DictMixin): - """A match for the linked entity found in text. Provides - the confidence score of the prediction and where the entity - was found in the text. - - :param confidence_score: If a well-known item is recognized, a - decimal number denoting the confidence level between 0 and 1 will be - returned. - :type confidence_score: float - :param text: Entity text as appears in the request. - :type text: str - """ - - def __init__(self, **kwargs): - self.confidence_score = kwargs.get("confidence_score", None) - self.text = kwargs.get("text", None) - - @classmethod - def _from_generated(cls, match): - return cls( - confidence_score=match.confidence_score, - text=match.text - ) - - def __repr__(self): - return "LinkedEntityMatch(confidence_score={}, text={})".format( - self.confidence_score, self.text - )[:1024] - - -class TextDocumentInput(MultiLanguageInput): - """The input document to be analyzed by the service. - - :param id: Required. A unique, non-empty document identifier. - :type id: str - :param text: Required. The input text to process. - :type text: str - :param language: This is the 2 letter ISO 639-1 representation - of a language. For example, use "en" for English; "es" for Spanish etc. If - not set, uses "en" for English as default. - :type language: str - """ - - def __init__(self, **kwargs): - super(TextDocumentInput, self).__init__(**kwargs) - self.id = kwargs.get("id", None) - self.text = kwargs.get("text", None) - self.language = kwargs.get("language", None) - - def __repr__(self): - return "TextDocumentInput(id={}, text={}, language={})" \ - .format(self.id, self.text, self.language)[:1024] - - -class TextDocumentBatchStatistics(DictMixin): - """TextDocumentBatchStatistics contains information about the - request payload. Note: This object is not returned - in the response and needs to be retrieved by a response hook. - - :param document_count: Number of documents submitted in the request. - :type document_count: int - :param valid_document_count: Number of valid documents. This - excludes empty, over-size limit or non-supported languages documents. - :type valid_document_count: int - :param erroneous_document_count: Number of invalid documents. - This includes empty, over-size limit or non-supported languages documents. - :type erroneous_document_count: int - :param transaction_count: Number of transactions for the request. - :type transaction_count: long - """ - - def __init__(self, **kwargs): - self.document_count = kwargs.get("document_count", None) - self.valid_document_count = kwargs.get("valid_document_count", None) - self.erroneous_document_count = kwargs.get("erroneous_document_count", None) - self.transaction_count = kwargs.get("transaction_count", None) - - @classmethod - def _from_generated(cls, statistics): - if statistics is None: - return None - return cls( - document_count=statistics["documentsCount"], - valid_document_count=statistics["validDocumentsCount"], - erroneous_document_count=statistics["erroneousDocumentsCount"], - transaction_count=statistics["transactionsCount"], - ) - - def __repr__(self): - return "TextDocumentBatchStatistics(document_count={}, valid_document_count={}, erroneous_document_count={}, " \ - "transaction_count={})".format(self.document_count, self.valid_document_count, - self.erroneous_document_count, self.transaction_count)[:1024] - - -class SentenceSentiment(DictMixin): - """SentenceSentiment contains the predicted sentiment and - confidence scores for each individual sentence in the document. - - :param text: The sentence text. - :type text: str - :param sentiment: The predicted Sentiment for the sentence. - Possible values include: 'positive', 'neutral', 'negative' - :type sentiment: str - :param confidence_scores: The sentiment confidence score between 0 - and 1 for the sentence for all labels. - :type confidence_scores: - ~azure.ai.textanalytics.SentimentConfidenceScores - """ - - def __init__(self, **kwargs): - self.text = kwargs.get("text", None) - self.sentiment = kwargs.get("sentiment", None) - self.confidence_scores = kwargs.get("confidence_scores", None) - - @classmethod - def _from_generated(cls, sentence): - return cls( - text=sentence.text, - sentiment=sentence.sentiment, - confidence_scores=SentimentConfidenceScores._from_generated(sentence.confidence_scores), # pylint: disable=protected-access - ) - - def __repr__(self): - return "SentenceSentiment(text={}, sentiment={}, confidence_scores={})".format( - self.text, - self.sentiment, - repr(self.confidence_scores) - )[:1024] - - -class SentimentConfidenceScores(DictMixin): - """The confidence scores (Softmax scores) between 0 and 1. - Higher values indicate higher confidence. - - :param positive: Positive score. - :type positive: float - :param neutral: Neutral score. - :type neutral: float - :param negative: Negative score. - :type negative: float - """ - - def __init__(self, **kwargs): - self.positive = kwargs.get('positive', None) - self.neutral = kwargs.get('neutral', None) - self.negative = kwargs.get('negative', None) - - @classmethod - def _from_generated(cls, score): - return cls( - positive=score.positive, - neutral=score.neutral, - negative=score.negative - ) - - def __repr__(self): - return "SentimentConfidenceScores(positive={}, neutral={}, negative={})" \ - .format(self.positive, self.neutral, self.negative)[:1024] diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_policies.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_policies.py deleted file mode 100644 index be9292570474..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_policies.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -from azure.core.pipeline.policies import ContentDecodePolicy -from azure.core.pipeline.policies import SansIOHTTPPolicy -from ._models import TextDocumentBatchStatistics - - -class TextAnalyticsResponseHookPolicy(SansIOHTTPPolicy): - def __init__(self, **kwargs): - self._response_callback = kwargs.get("raw_response_hook") - super(TextAnalyticsResponseHookPolicy, self).__init__() - - def on_request(self, request): - self._response_callback = request.context.options.pop("raw_response_hook", self._response_callback) - - def on_response(self, request, response): - if self._response_callback: - data = ContentDecodePolicy.deserialize_from_http_generics(response.http_response) - statistics = data.get("statistics", None) - model_version = data.get("modelVersion", None) - - batch_statistics = TextDocumentBatchStatistics._from_generated(statistics) # pylint: disable=protected-access - response.statistics = batch_statistics - response.model_version = model_version - response.raw_response = data - self._response_callback(response) diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_request_handlers.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_request_handlers.py deleted file mode 100644 index 6d901cf2a7a0..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_request_handlers.py +++ /dev/null @@ -1,66 +0,0 @@ -# coding=utf-8 -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - - -import six - -from ._models import ( - DetectLanguageInput, - TextDocumentInput, -) - - -def _validate_batch_input(documents, hint, whole_batch_hint): - """Validate that batch input has either all string docs - or dict/DetectLanguageInput/TextDocumentInput, not a mix of both. - Assign country and language hints on a whole batch or per-item - basis. - - :param list documents: The input documents. - :return: A list of DetectLanguageInput or TextDocumentInput - """ - if not documents: - raise ValueError("Input documents can not be empty or None") - - if isinstance(documents, six.string_types): - raise TypeError("Input documents cannot be a string.") - - if isinstance(documents, dict): - raise TypeError("Input documents cannot be a dict") - - if not all(isinstance(x, six.string_types) for x in documents): - if not all(isinstance(x, (dict, TextDocumentInput, DetectLanguageInput)) for x in documents): - raise TypeError("Mixing string and dictionary/object document input unsupported.") - - - request_batch = [] - for idx, doc in enumerate(documents): - if isinstance(doc, six.string_types): - if hint == "country_hint" and whole_batch_hint.lower() == "none": - whole_batch_hint = "" - document = {"id": str(idx), hint: whole_batch_hint, "text": doc} - request_batch.append(document) - if isinstance(doc, dict): - item_hint = doc.get(hint, None) - if item_hint is None: - doc = {"id": doc.get("id", None), hint: whole_batch_hint, "text": doc.get("text", None)} - elif item_hint.lower() == "none": - doc = {"id": doc.get("id", None), hint: "", "text": doc.get("text", None)} - request_batch.append(doc) - if isinstance(doc, TextDocumentInput): - item_hint = doc.language - if item_hint is None: - doc = TextDocumentInput(id=doc.id, language=whole_batch_hint, text=doc.text) - request_batch.append(doc) - if isinstance(doc, DetectLanguageInput): - item_hint = doc.country_hint - if item_hint is None: - doc = DetectLanguageInput(id=doc.id, country_hint=whole_batch_hint, text=doc.text) - elif item_hint.lower() == "none": - doc = DetectLanguageInput(id=doc.id, country_hint="", text=doc.text) - request_batch.append(doc) - - return request_batch 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 deleted file mode 100644 index 0f38ba8b8c6d..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_response_handlers.py +++ /dev/null @@ -1,149 +0,0 @@ -# coding=utf-8 -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -import json -from azure.core.exceptions import ( - HttpResponseError, - ClientAuthenticationError, - ODataV4Format -) -from ._models import ( - RecognizeEntitiesResult, - CategorizedEntity, - TextDocumentStatistics, - RecognizeLinkedEntitiesResult, - LinkedEntity, - ExtractKeyPhrasesResult, - AnalyzeSentimentResult, - SentenceSentiment, - DetectLanguageResult, - DetectedLanguage, - DocumentError, - SentimentConfidenceScores, - TextAnalyticsError, - TextAnalyticsWarning -) - -class CSODataV4Format(ODataV4Format): - - def __init__(self, odata_error): - try: - if odata_error["error"]["innererror"]: - super(CSODataV4Format, self).__init__(odata_error["error"]["innererror"]) - except KeyError: - super(CSODataV4Format, self).__init__(odata_error) - - -def process_batch_error(error): - """Raise detailed error message. - """ - raise_error = HttpResponseError - if error.status_code == 401: - raise_error = ClientAuthenticationError - raise raise_error(response=error.response, error_format=CSODataV4Format) - -def order_results(response, combined): - """Order results in the order the user passed them in. - - :param response: Used to get the original documents in the request - :param combined: A combined list of the results | errors - :return: In order list of results | errors (if any) - """ - request = json.loads(response.http_response.request.body)["documents"] - mapping = {item.id: item for item in combined} - ordered_response = [mapping[item["id"]] for item in request] - return ordered_response - - -def prepare_result(func): - def _get_error_code_and_message(error): - if hasattr(error.error, 'innererror') and error.error.innererror: - return error.error.innererror.code, error.error.innererror.message - return error.error.code, error.error.message - - def _deal_with_too_many_documents(response, obj): - # special case for now if there are too many documents in the request - too_many_documents_errors = [ - error for error in obj.errors if error.id == "" - ] - if too_many_documents_errors: - too_many_documents_error = too_many_documents_errors[0] - response.status_code = 400 - response.reason = "Bad Request" - code, message = _get_error_code_and_message(too_many_documents_error) - raise HttpResponseError( - message="({}) {}".format(code, message), - response=response - ) - - def wrapper(response, obj, response_headers): # pylint: disable=unused-argument - if obj.errors: - _deal_with_too_many_documents(response.http_response, obj) - combined = obj.documents + obj.errors - results = order_results(response, combined) - else: - results = obj.documents - - for idx, item in enumerate(results): - if hasattr(item, "error"): - results[idx] = DocumentError(id=item.id, error=TextAnalyticsError._from_generated(item.error)) # pylint: disable=protected-access - else: - results[idx] = func(item) - return results - - return wrapper - - -@prepare_result -def language_result(language): - return DetectLanguageResult( - id=language.id, - primary_language=DetectedLanguage._from_generated(language.detected_language), # pylint: disable=protected-access - warnings=[TextAnalyticsWarning._from_generated(w) for w in language.warnings], # pylint: disable=protected-access - statistics=TextDocumentStatistics._from_generated(language.statistics), # pylint: disable=protected-access - ) - - -@prepare_result -def entities_result(entity): - return RecognizeEntitiesResult( - id=entity.id, - entities=[CategorizedEntity._from_generated(e) for e in entity.entities], # pylint: disable=protected-access - warnings=[TextAnalyticsWarning._from_generated(w) for w in entity.warnings], # pylint: disable=protected-access - statistics=TextDocumentStatistics._from_generated(entity.statistics), # pylint: disable=protected-access - ) - - -@prepare_result -def linked_entities_result(entity): - return RecognizeLinkedEntitiesResult( - id=entity.id, - entities=[LinkedEntity._from_generated(e) for e in entity.entities], # pylint: disable=protected-access - warnings=[TextAnalyticsWarning._from_generated(w) for w in entity.warnings], # pylint: disable=protected-access - statistics=TextDocumentStatistics._from_generated(entity.statistics), # pylint: disable=protected-access - ) - - -@prepare_result -def key_phrases_result(phrases): - return ExtractKeyPhrasesResult( - id=phrases.id, - key_phrases=phrases.key_phrases, - warnings=[TextAnalyticsWarning._from_generated(w) for w in phrases.warnings], # pylint: disable=protected-access - statistics=TextDocumentStatistics._from_generated(phrases.statistics), # pylint: disable=protected-access - ) - - -@prepare_result -def sentiment_result(sentiment): - return AnalyzeSentimentResult( - id=sentiment.id, - sentiment=sentiment.sentiment, - warnings=[TextAnalyticsWarning._from_generated(w) for w in sentiment.warnings], # pylint: disable=protected-access - statistics=TextDocumentStatistics._from_generated(sentiment.statistics), # pylint: disable=protected-access - confidence_scores=SentimentConfidenceScores._from_generated(sentiment.confidence_scores), # pylint: disable=protected-access - sentences=[SentenceSentiment._from_generated(s) for s in sentiment.sentences], # pylint: disable=protected-access - ) 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 deleted file mode 100644 index 3d32c1dad8bb..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_text_analytics_client.py +++ /dev/null @@ -1,412 +0,0 @@ -# coding=utf-8 -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -from typing import ( # pylint: disable=unused-import - Union, - Optional, - Any, - List, - Dict, - TYPE_CHECKING, -) -from azure.core.tracing.decorator import distributed_trace -from azure.core.exceptions import HttpResponseError -from ._base_client import TextAnalyticsClientBase -from ._request_handlers import _validate_batch_input -from ._response_handlers import ( - process_batch_error, - entities_result, - linked_entities_result, - key_phrases_result, - sentiment_result, - language_result -) - -if TYPE_CHECKING: - from azure.core.credentials import TokenCredential, AzureKeyCredential - from ._models import ( - DetectLanguageInput, - TextDocumentInput, - DetectLanguageResult, - RecognizeEntitiesResult, - RecognizeLinkedEntitiesResult, - ExtractKeyPhrasesResult, - AnalyzeSentimentResult, - DocumentError, - ) - - -class TextAnalyticsClient(TextAnalyticsClientBase): - """The Text Analytics API is a suite of text analytics web services built with best-in-class - Microsoft machine learning algorithms. The API can be used to analyze unstructured text for - tasks such as sentiment analysis, key phrase extraction, and language detection. No training data - is needed to use this API - just bring your text data. This API uses advanced natural language - processing techniques to deliver best in class predictions. - - Further documentation can be found in - https://docs.microsoft.com/azure/cognitive-services/text-analytics/overview - - :param str endpoint: Supported Cognitive Services or Text Analytics resource - endpoints (protocol and hostname, for example: https://westus2.api.cognitive.microsoft.com). - :param credential: Credentials needed for the client to connect to Azure. - This can be the an instance of AzureKeyCredential if using a - cognitive services/text analytics API key or a token credential - from :mod:`azure.identity`. - :type credential: :class:`~azure.core.credentials.AzureKeyCredential` or - :class:`~azure.core.credentials.TokenCredential` - :keyword str default_country_hint: Sets the default country_hint to use for all operations. - Defaults to "US". If you don't want to use a country hint, pass the string "none". - :keyword str default_language: Sets the default language to use for all operations. - Defaults to "en". - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_authentication.py - :start-after: [START create_ta_client_with_key] - :end-before: [END create_ta_client_with_key] - :language: python - :dedent: 8 - :caption: Creating the TextAnalyticsClient with endpoint and API key. - - .. literalinclude:: ../samples/sample_authentication.py - :start-after: [START create_ta_client_with_aad] - :end-before: [END create_ta_client_with_aad] - :language: python - :dedent: 8 - :caption: Creating the TextAnalyticsClient with endpoint and token credential from Azure Active Directory. - """ - - def __init__(self, endpoint, credential, **kwargs): - # type: (str, Union[AzureKeyCredential, TokenCredential], Any) -> None - super(TextAnalyticsClient, self).__init__( - endpoint=endpoint, - credential=credential, - **kwargs - ) - self._default_language = kwargs.pop("default_language", "en") - self._default_country_hint = kwargs.pop("default_country_hint", "US") - - @distributed_trace - def detect_language( # type: ignore - self, - documents, # type: Union[List[str], List[DetectLanguageInput], List[Dict[str, str]]] - **kwargs # type: Any - ): - # type: (...) -> List[Union[DetectLanguageResult, DocumentError]] - """Detects Language for a batch of documents. - - Returns the detected language and a numeric score between zero and - one. Scores close to one indicate 100% certainty that the identified - language is true. See https://aka.ms/talangs for the list of enabled languages. - - See https://docs.microsoft.com/azure/cognitive-services/text-analytics/overview#data-limits - for document length limits, maximum batch size, and supported text encoding. - - :param documents: The set of documents to process as part of this batch. - If you wish to specify the ID and country_hint on a per-item basis you must - use as input a list[:class:`~azure.ai.textanalytics.DetectLanguageInput`] or a list of - dict representations of :class:`~azure.ai.textanalytics.DetectLanguageInput`, like - `{"id": "1", "country_hint": "us", "text": "hello world"}`. - :type documents: - list[str] or list[~azure.ai.textanalytics.DetectLanguageInput] - :keyword str country_hint: A country hint for the entire batch. Accepts two - letter country codes specified by ISO 3166-1 alpha-2. Per-document - country hints will take precedence over whole batch hints. Defaults to - "US". If you don't want to use a country hint, pass the string "none". - :keyword str model_version: This value indicates which model will - be used for scoring, e.g. "latest", "2019-10-01". If a model-version - is not specified, the API will default to the latest, non-preview version. - :keyword bool show_stats: If set to true, response will contain document - level statistics. - :return: The combined list of :class:`~azure.ai.textanalytics.DetectLanguageResult` and - :class:`~azure.ai.textanalytics.DocumentError` in the order the original documents were - passed in. - :rtype: list[~azure.ai.textanalytics.DetectLanguageResult, - ~azure.ai.textanalytics.DocumentError] - :raises ~azure.core.exceptions.HttpResponseError or TypeError or ValueError: - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_detect_language.py - :start-after: [START batch_detect_language] - :end-before: [END batch_detect_language] - :language: python - :dedent: 8 - :caption: Detecting language in a batch of documents. - """ - country_hint_arg = kwargs.pop("country_hint", None) - country_hint = country_hint_arg if country_hint_arg is not None else self._default_country_hint - docs = _validate_batch_input(documents, "country_hint", country_hint) - model_version = kwargs.pop("model_version", None) - show_stats = kwargs.pop("show_stats", False) - try: - return self._client.languages( - documents=docs, - model_version=model_version, - show_stats=show_stats, - cls=kwargs.pop("cls", language_result), - **kwargs - ) - except HttpResponseError as error: - process_batch_error(error) - - @distributed_trace - def recognize_entities( # type: ignore - self, - documents, # type: Union[List[str], List[TextDocumentInput], List[Dict[str, str]]] - **kwargs # type: Any - ): - # type: (...) -> List[Union[RecognizeEntitiesResult, DocumentError]] - """Entity Recognition for a batch of documents. - - Identifies and categorizes entities in your text as people, places, - organizations, date/time, quantities, percentages, currencies, and more. - For the list of supported entity types, check: https://aka.ms/taner - - See https://docs.microsoft.com/azure/cognitive-services/text-analytics/overview#data-limits - for document length limits, maximum batch size, and supported text encoding. - - :param documents: The set of documents to process as part of this batch. - If you wish to specify the ID and language on a per-item basis you must - use as input a list[:class:`~azure.ai.textanalytics.TextDocumentInput`] or a list - of dict representations of :class:`~azure.ai.textanalytics.TextDocumentInput`, - like `{"id": "1", "language": "en", "text": "hello world"}`. - :type documents: - list[str] or list[~azure.ai.textanalytics.TextDocumentInput] - :keyword str language: The 2 letter ISO 639-1 representation of language for the - entire batch. For example, use "en" for English; "es" for Spanish etc. - If not set, uses "en" for English as default. Per-document language will - take precedence over whole batch language. See https://aka.ms/talangs for - supported languages in Text Analytics API. - :keyword str model_version: This value indicates which model will - be used for scoring, e.g. "latest", "2019-10-01". If a model-version - is not specified, the API will default to the latest, non-preview version. - :keyword bool show_stats: If set to true, response will contain document level statistics. - :return: The combined list of :class:`~azure.ai.textanalytics.RecognizeEntitiesResult` and - :class:`~azure.ai.textanalytics.DocumentError` in the order the original documents - were passed in. - :rtype: list[~azure.ai.textanalytics.RecognizeEntitiesResult, - ~azure.ai.textanalytics.DocumentError] - :raises ~azure.core.exceptions.HttpResponseError or TypeError or ValueError: - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_recognize_entities.py - :start-after: [START batch_recognize_entities] - :end-before: [END batch_recognize_entities] - :language: python - :dedent: 8 - :caption: Recognize entities in a batch of documents. - """ - language_arg = kwargs.pop("language", None) - language = language_arg if language_arg is not None else self._default_language - docs = _validate_batch_input(documents, "language", language) - model_version = kwargs.pop("model_version", None) - show_stats = kwargs.pop("show_stats", False) - try: - return self._client.entities_recognition_general( - documents=docs, - model_version=model_version, - show_stats=show_stats, - cls=kwargs.pop("cls", entities_result), - **kwargs - ) - except HttpResponseError as error: - process_batch_error(error) - - @distributed_trace - def recognize_linked_entities( # type: ignore - self, - documents, # type: Union[List[str], List[TextDocumentInput], List[Dict[str, str]]] - **kwargs # type: Any - ): - # type: (...) -> List[Union[RecognizeLinkedEntitiesResult, DocumentError]] - """Recognize linked entities from a well-known knowledge base for a batch of documents. - - Identifies and disambiguates the identity of each entity found in text (for example, - determining whether an occurrence of the word Mars refers to the planet, or to the - Roman god of war). Recognized entities are associated with URLs to a well-known - knowledge base, like Wikipedia. - - See https://docs.microsoft.com/azure/cognitive-services/text-analytics/overview#data-limits - for document length limits, maximum batch size, and supported text encoding. - - :param documents: The set of documents to process as part of this batch. - If you wish to specify the ID and language on a per-item basis you must - use as input a list[:class:`~azure.ai.textanalytics.TextDocumentInput`] or a list of - dict representations of :class:`~azure.ai.textanalytics.TextDocumentInput`, like - `{"id": "1", "language": "en", "text": "hello world"}`. - :type documents: - list[str] or list[~azure.ai.textanalytics.TextDocumentInput] - :keyword str language: The 2 letter ISO 639-1 representation of language for the - entire batch. For example, use "en" for English; "es" for Spanish etc. - If not set, uses "en" for English as default. Per-document language will - take precedence over whole batch language. See https://aka.ms/talangs for - supported languages in Text Analytics API. - :keyword str model_version: This value indicates which model will - be used for scoring, e.g. "latest", "2019-10-01". If a model-version - is not specified, the API will default to the latest, non-preview version. - :keyword bool show_stats: If set to true, response will contain document level statistics. - :return: The combined list of :class:`~azure.ai.textanalytics.RecognizeLinkedEntitiesResult` - and :class:`~azure.ai.textanalytics.DocumentError` in the order the original documents - were passed in. - :rtype: list[~azure.ai.textanalytics.RecognizeLinkedEntitiesResult, - ~azure.ai.textanalytics.DocumentError] - :raises ~azure.core.exceptions.HttpResponseError or TypeError or ValueError: - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_recognize_linked_entities.py - :start-after: [START batch_recognize_linked_entities] - :end-before: [END batch_recognize_linked_entities] - :language: python - :dedent: 8 - :caption: Recognize linked entities in a batch of documents. - """ - language_arg = kwargs.pop("language", None) - language = language_arg if language_arg is not None else self._default_language - docs = _validate_batch_input(documents, "language", language) - model_version = kwargs.pop("model_version", None) - show_stats = kwargs.pop("show_stats", False) - try: - return self._client.entities_linking( - documents=docs, - model_version=model_version, - show_stats=show_stats, - cls=kwargs.pop("cls", linked_entities_result), - **kwargs - ) - except HttpResponseError as error: - process_batch_error(error) - - @distributed_trace - def extract_key_phrases( # type: ignore - self, - documents, # type: Union[List[str], List[TextDocumentInput], List[Dict[str, str]]] - **kwargs # type: Any - ): - # type: (...) -> List[Union[ExtractKeyPhrasesResult, DocumentError]] - """Extract Key Phrases from a batch of documents. - - Returns a list of strings denoting the key phrases in the input - text. For example, for the input text "The food was delicious and there - were wonderful staff", the API returns the main talking points: "food" - and "wonderful staff" - - See https://docs.microsoft.com/azure/cognitive-services/text-analytics/overview#data-limits - for document length limits, maximum batch size, and supported text encoding. - - :param documents: The set of documents to process as part of this batch. - If you wish to specify the ID and language on a per-item basis you must - use as input a list[:class:`~azure.ai.textanalytics.TextDocumentInput`] or a list of - dict representations of :class:`~azure.ai.textanalytics.TextDocumentInput`, like - `{"id": "1", "language": "en", "text": "hello world"}`. - :type documents: - list[str] or list[~azure.ai.textanalytics.TextDocumentInput] - :keyword str language: The 2 letter ISO 639-1 representation of language for the - entire batch. For example, use "en" for English; "es" for Spanish etc. - If not set, uses "en" for English as default. Per-document language will - take precedence over whole batch language. See https://aka.ms/talangs for - supported languages in Text Analytics API. - :keyword str model_version: This value indicates which model will - be used for scoring, e.g. "latest", "2019-10-01". If a model-version - is not specified, the API will default to the latest, non-preview version. - :keyword bool show_stats: If set to true, response will contain document level statistics. - :return: The combined list of :class:`~azure.ai.textanalytics.ExtractKeyPhrasesResult` and - :class:`~azure.ai.textanalytics.DocumentError` in the order the original documents were - passed in. - :rtype: list[~azure.ai.textanalytics.ExtractKeyPhrasesResult, - ~azure.ai.textanalytics.DocumentError] - :raises ~azure.core.exceptions.HttpResponseError or TypeError or ValueError: - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_extract_key_phrases.py - :start-after: [START batch_extract_key_phrases] - :end-before: [END batch_extract_key_phrases] - :language: python - :dedent: 8 - :caption: Extract the key phrases in a batch of documents. - """ - language_arg = kwargs.pop("language", None) - language = language_arg if language_arg is not None else self._default_language - docs = _validate_batch_input(documents, "language", language) - model_version = kwargs.pop("model_version", None) - show_stats = kwargs.pop("show_stats", False) - try: - return self._client.key_phrases( - documents=docs, - model_version=model_version, - show_stats=show_stats, - cls=kwargs.pop("cls", key_phrases_result), - **kwargs - ) - except HttpResponseError as error: - process_batch_error(error) - - @distributed_trace - def analyze_sentiment( # type: ignore - self, - documents, # type: Union[List[str], List[TextDocumentInput], List[Dict[str, str]]] - **kwargs # type: Any - ): - # type: (...) -> List[Union[AnalyzeSentimentResult, DocumentError]] - """Analyze sentiment for a batch of documents. - - Returns a sentiment prediction, as well as sentiment scores for - each sentiment class (Positive, Negative, and Neutral) for the document - and each sentence within it. - - See https://docs.microsoft.com/azure/cognitive-services/text-analytics/overview#data-limits - for document length limits, maximum batch size, and supported text encoding. - - :param documents: The set of documents to process as part of this batch. - If you wish to specify the ID and language on a per-item basis you must - use as input a list[:class:`~azure.ai.textanalytics.TextDocumentInput`] or a list of - dict representations of :class:`~azure.ai.textanalytics.TextDocumentInput`, like - `{"id": "1", "language": "en", "text": "hello world"}`. - :type documents: - list[str] or list[~azure.ai.textanalytics.TextDocumentInput] - :keyword str language: The 2 letter ISO 639-1 representation of language for the - entire batch. For example, use "en" for English; "es" for Spanish etc. - If not set, uses "en" for English as default. Per-document language will - take precedence over whole batch language. See https://aka.ms/talangs for - supported languages in Text Analytics API. - :keyword str model_version: This value indicates which model will - be used for scoring, e.g. "latest", "2019-10-01". If a model-version - is not specified, the API will default to the latest, non-preview version. - :keyword bool show_stats: If set to true, response will contain document level statistics. - :return: The combined list of :class:`~azure.ai.textanalytics.AnalyzeSentimentResult` and - :class:`~azure.ai.textanalytics.DocumentError` in the order the original documents were - passed in. - :rtype: list[~azure.ai.textanalytics.AnalyzeSentimentResult, - ~azure.ai.textanalytics.DocumentError] - :raises ~azure.core.exceptions.HttpResponseError or TypeError or ValueError: - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_analyze_sentiment.py - :start-after: [START batch_analyze_sentiment] - :end-before: [END batch_analyze_sentiment] - :language: python - :dedent: 8 - :caption: Analyze sentiment in a batch of documents. - """ - language_arg = kwargs.pop("language", None) - language = language_arg if language_arg is not None else self._default_language - docs = _validate_batch_input(documents, "language", language) - model_version = kwargs.pop("model_version", None) - show_stats = kwargs.pop("show_stats", False) - try: - return self._client.sentiment( - documents=docs, - model_version=model_version, - show_stats=show_stats, - cls=kwargs.pop("cls", sentiment_result), - **kwargs - ) - except HttpResponseError as error: - process_batch_error(error) diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_user_agent.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_user_agent.py deleted file mode 100644 index dd1abdfe3e9a..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_user_agent.py +++ /dev/null @@ -1,12 +0,0 @@ -# coding=utf-8 -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -import platform -from ._version import VERSION - -USER_AGENT = "ai-textanalytics/{} Python/{} ({})".format( - VERSION, platform.python_version(), platform.platform() -) diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_version.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_version.py deleted file mode 100644 index 5c9f115397ae..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/_version.py +++ /dev/null @@ -1,7 +0,0 @@ -# coding=utf-8 -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -VERSION = "1.0.0b7" 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 deleted file mode 100644 index a3d4ff19e3d8..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/__init__.py +++ /dev/null @@ -1,11 +0,0 @@ -# coding=utf-8 -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -from ._text_analytics_client_async import TextAnalyticsClient - -__all__ = [ - 'TextAnalyticsClient' -] diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_base_client_async.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_base_client_async.py deleted file mode 100644 index f586dae39b9a..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_base_client_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# coding=utf-8 -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -from typing import Any -from azure.core.credentials import AzureKeyCredential -from azure.core.pipeline.policies import AzureKeyCredentialPolicy -from ._policies_async import AsyncTextAnalyticsResponseHookPolicy -from .._generated.aio import TextAnalyticsClient -from .._user_agent import USER_AGENT - - -def _authentication_policy(credential): - authentication_policy = None - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if isinstance(credential, AzureKeyCredential): - authentication_policy = AzureKeyCredentialPolicy( - name="Ocp-Apim-Subscription-Key", credential=credential - ) - elif credential is not None and not hasattr(credential, "get_token"): - raise TypeError("Unsupported credential: {}. Use an instance of AzureKeyCredential " - "or a token credential from azure.identity".format(type(credential))) - return authentication_policy - - -class AsyncTextAnalyticsClientBase(object): - def __init__(self, endpoint, credential, **kwargs): - self._client = TextAnalyticsClient( - endpoint=endpoint, - credential=credential, - sdk_moniker=USER_AGENT, - authentication_policy=_authentication_policy(credential), - custom_hook_policy=AsyncTextAnalyticsResponseHookPolicy(**kwargs), - **kwargs - ) - - - async def __aenter__(self) -> "AsyncTextAnalyticsClientBase": - await self._client.__aenter__() - return self - - async def __aexit__(self, *args: "Any") -> None: - await self._client.__aexit__(*args) - - async def close(self) -> None: - """Close sockets opened by the client. - Calling this method is unnecessary when using the client as a context manager. - """ - await self._client.__aexit__() diff --git a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_policies_async.py b/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_policies_async.py deleted file mode 100644 index c8ba797a8743..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_policies_async.py +++ /dev/null @@ -1,35 +0,0 @@ -# coding=utf-8 -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -import asyncio -from azure.core.pipeline.policies import ContentDecodePolicy -from azure.core.pipeline.policies import SansIOHTTPPolicy -from .._models import TextDocumentBatchStatistics - - -class AsyncTextAnalyticsResponseHookPolicy(SansIOHTTPPolicy): - - def __init__(self, **kwargs): - self._response_callback = kwargs.get('raw_response_hook') - super(AsyncTextAnalyticsResponseHookPolicy, self).__init__() - - async def on_request(self, request): - self._response_callback = request.context.options.pop("raw_response_hook", self._response_callback) - - async def on_response(self, request, response): - if self._response_callback: - data = ContentDecodePolicy.deserialize_from_http_generics(response.http_response) - statistics = data.get("statistics", None) - model_version = data.get("modelVersion", None) - - batch_statistics = TextDocumentBatchStatistics._from_generated(statistics) # pylint: disable=protected-access - response.statistics = batch_statistics - response.model_version = model_version - response.raw_response = data - if asyncio.iscoroutine(self._response_callback): - await self._response_callback(response) - else: - self._response_callback(response) 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 deleted file mode 100644 index 5c649e1f5c4d..000000000000 --- a/sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_text_analytics_client_async.py +++ /dev/null @@ -1,412 +0,0 @@ -# coding=utf-8 -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -from typing import ( # pylint: disable=unused-import - Union, - Optional, - Any, - List, - Dict, - TYPE_CHECKING -) -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.exceptions import HttpResponseError -from ._base_client_async import AsyncTextAnalyticsClientBase -from .._request_handlers import _validate_batch_input -from .._response_handlers import ( - process_batch_error, - entities_result, - linked_entities_result, - key_phrases_result, - sentiment_result, - language_result -) -from .._models import ( - DetectLanguageInput, - TextDocumentInput, - DetectLanguageResult, - RecognizeEntitiesResult, - RecognizeLinkedEntitiesResult, - ExtractKeyPhrasesResult, - AnalyzeSentimentResult, - DocumentError, -) - -if TYPE_CHECKING: - from azure.core.credentials_async import AsyncTokenCredential - from azure.core.credentials import AzureKeyCredential - - -class TextAnalyticsClient(AsyncTextAnalyticsClientBase): - """The Text Analytics API is a suite of text analytics web services built with best-in-class - Microsoft machine learning algorithms. The API can be used to analyze unstructured text for - tasks such as sentiment analysis, key phrase extraction, and language detection. No training data - is needed to use this API - just bring your text data. This API uses advanced natural language - processing techniques to deliver best in class predictions. - - Further documentation can be found in - https://docs.microsoft.com/azure/cognitive-services/text-analytics/overview - - :param str endpoint: Supported Cognitive Services or Text Analytics resource - endpoints (protocol and hostname, for example: https://westus2.api.cognitive.microsoft.com). - :param credential: Credentials needed for the client to connect to Azure. - This can be the an instance of AzureKeyCredential if using a - cognitive services/text analytics API key or a token credential - from :mod:`azure.identity`. - :type credential: :class:`~azure.core.credentials.AzureKeyCredential` - or :class:`~azure.core.credentials_async.AsyncTokenCredential` - :keyword str default_country_hint: Sets the default country_hint to use for all operations. - Defaults to "US". If you don't want to use a country hint, pass the string "none". - :keyword str default_language: Sets the default language to use for all operations. - Defaults to "en". - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_authentication_async.py - :start-after: [START create_ta_client_with_key_async] - :end-before: [END create_ta_client_with_key_async] - :language: python - :dedent: 8 - :caption: Creating the TextAnalyticsClient with endpoint and API key. - - .. literalinclude:: ../samples/async_samples/sample_authentication_async.py - :start-after: [START create_ta_client_with_aad_async] - :end-before: [END create_ta_client_with_aad_async] - :language: python - :dedent: 8 - :caption: Creating the TextAnalyticsClient with endpoint and token credential from Azure Active Directory. - """ - - def __init__( # type: ignore - self, - endpoint: str, - credential: Union["AzureKeyCredential", "AsyncTokenCredential"], - **kwargs: Any - ) -> None: - super(TextAnalyticsClient, self).__init__( - endpoint=endpoint, - credential=credential, - **kwargs - ) - self._default_language = kwargs.pop("default_language", "en") - self._default_country_hint = kwargs.pop("default_country_hint", "US") - - @distributed_trace_async - async def detect_language( # type: ignore - self, - documents: Union[List[str], List[DetectLanguageInput], List[Dict[str, str]]], - **kwargs: Any - ) -> List[Union[DetectLanguageResult, DocumentError]]: - """Detects Language for a batch of documents. - - Returns the detected language and a numeric score between zero and - one. Scores close to one indicate 100% certainty that the identified - language is true. See https://aka.ms/talangs for the list of enabled languages. - - See https://docs.microsoft.com/azure/cognitive-services/text-analytics/overview#data-limits - for document length limits, maximum batch size, and supported text encoding. - - :param documents: The set of documents to process as part of this batch. - If you wish to specify the ID and country_hint on a per-item basis you must - use as input a list[:class:`~azure.ai.textanalytics.DetectLanguageInput`] or a list of - dict representations of :class:`~azure.ai.textanalytics.DetectLanguageInput`, like - `{"id": "1", "country_hint": "us", "text": "hello world"}`. - :type documents: - list[str] or list[~azure.ai.textanalytics.DetectLanguageInput] - :keyword str country_hint: A country hint for the entire batch. Accepts two - letter country codes specified by ISO 3166-1 alpha-2. Per-document - country hints will take precedence over whole batch hints. Defaults to - "US". If you don't want to use a country hint, pass the string "none". - :keyword str model_version: This value indicates which model will - be used for scoring, e.g. "latest", "2019-10-01". If a model-version - is not specified, the API will default to the latest, non-preview version. - :keyword bool show_stats: If set to true, response will contain document - level statistics. - :return: The combined list of :class:`~azure.ai.textanalytics.DetectLanguageResult` - and :class:`~azure.ai.textanalytics.DocumentError` in the order the original documents - were passed in. - :rtype: list[~azure.ai.textanalytics.DetectLanguageResult, - ~azure.ai.textanalytics.DocumentError] - :raises ~azure.core.exceptions.HttpResponseError or TypeError or ValueError: - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_detect_language_async.py - :start-after: [START batch_detect_language_async] - :end-before: [END batch_detect_language_async] - :language: python - :dedent: 8 - :caption: Detecting language in a batch of documents. - """ - country_hint_arg = kwargs.pop("country_hint", None) - country_hint = country_hint_arg if country_hint_arg is not None else self._default_country_hint - docs = _validate_batch_input(documents, "country_hint", country_hint) - model_version = kwargs.pop("model_version", None) - show_stats = kwargs.pop("show_stats", False) - try: - return await self._client.languages( - documents=docs, - model_version=model_version, - show_stats=show_stats, - cls=kwargs.pop("cls", language_result), - **kwargs - ) - except HttpResponseError as error: - process_batch_error(error) - - @distributed_trace_async - async def recognize_entities( # type: ignore - self, - documents: Union[List[str], List[TextDocumentInput], List[Dict[str, str]]], - **kwargs: Any - ) -> List[Union[RecognizeEntitiesResult, DocumentError]]: - """Entity Recognition for a batch of documents. - - Identifies and categorizes entities in your text as people, places, - organizations, date/time, quantities, percentages, currencies, and more. - For the list of supported entity types, check: https://aka.ms/taner - - See https://docs.microsoft.com/azure/cognitive-services/text-analytics/overview#data-limits - for document length limits, maximum batch size, and supported text encoding. - - :param documents: The set of documents to process as part of this batch. - If you wish to specify the ID and language on a per-item basis you must - use as input a list[:class:`~azure.ai.textanalytics.TextDocumentInput`] or a list of - dict representations of :class:`~azure.ai.textanalytics.TextDocumentInput`, like - `{"id": "1", "language": "en", "text": "hello world"}`. - :type documents: - list[str] or list[~azure.ai.textanalytics.TextDocumentInput] - :keyword str language: The 2 letter ISO 639-1 representation of language for the - entire batch. For example, use "en" for English; "es" for Spanish etc. - If not set, uses "en" for English as default. Per-document language will - take precedence over whole batch language. See https://aka.ms/talangs for - supported languages in Text Analytics API. - :keyword str model_version: This value indicates which model will - be used for scoring, e.g. "latest", "2019-10-01". If a model-version - is not specified, the API will default to the latest, non-preview version. - :keyword bool show_stats: If set to true, response will contain document level statistics. - :return: The combined list of :class:`~azure.ai.textanalytics.RecognizeEntitiesResult` and - :class:`~azure.ai.textanalytics.DocumentError` in the order the original documents were - passed in. - :rtype: list[~azure.ai.textanalytics.RecognizeEntitiesResult, - ~azure.ai.textanalytics.DocumentError] - :raises ~azure.core.exceptions.HttpResponseError or TypeError or ValueError: - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_recognize_entities_async.py - :start-after: [START batch_recognize_entities_async] - :end-before: [END batch_recognize_entities_async] - :language: python - :dedent: 8 - :caption: Recognize entities in a batch of documents. - """ - language_arg = kwargs.pop("language", None) - language = language_arg if language_arg is not None else self._default_language - docs = _validate_batch_input(documents, "language", language) - model_version = kwargs.pop("model_version", None) - show_stats = kwargs.pop("show_stats", False) - try: - return await self._client.entities_recognition_general( - documents=docs, - model_version=model_version, - show_stats=show_stats, - cls=kwargs.pop("cls", entities_result), - **kwargs - ) - except HttpResponseError as error: - process_batch_error(error) - - @distributed_trace_async - async def recognize_linked_entities( # type: ignore - self, - documents: Union[List[str], List[TextDocumentInput], List[Dict[str, str]]], - **kwargs: Any - ) -> List[Union[RecognizeLinkedEntitiesResult, DocumentError]]: - """Recognize linked entities from a well-known knowledge base for a batch of documents. - - Identifies and disambiguates the identity of each entity found in text (for example, - determining whether an occurrence of the word Mars refers to the planet, or to the - Roman god of war). Recognized entities are associated with URLs to a well-known - knowledge base, like Wikipedia. - - See https://docs.microsoft.com/azure/cognitive-services/text-analytics/overview#data-limits - for document length limits, maximum batch size, and supported text encoding. - - :param documents: The set of documents to process as part of this batch. - If you wish to specify the ID and language on a per-item basis you must - use as input a list[:class:`~azure.ai.textanalytics.TextDocumentInput`] or a list of - dict representations of :class:`~azure.ai.textanalytics.TextDocumentInput`, like - `{"id": "1", "language": "en", "text": "hello world"}`. - :type documents: - list[str] or list[~azure.ai.textanalytics.TextDocumentInput] - :keyword str language: The 2 letter ISO 639-1 representation of language for the - entire batch. For example, use "en" for English; "es" for Spanish etc. - If not set, uses "en" for English as default. Per-document language will - take precedence over whole batch language. See https://aka.ms/talangs for - supported languages in Text Analytics API. - :keyword str model_version: This value indicates which model will - be used for scoring, e.g. "latest", "2019-10-01". If a model-version - is not specified, the API will default to the latest, non-preview version. - :keyword bool show_stats: If set to true, response will contain document level statistics. - :return: The combined list of :class:`~azure.ai.textanalytics.RecognizeLinkedEntitiesResult` - and :class:`~azure.ai.textanalytics.DocumentError` in the order the original documents - were passed in. - :rtype: list[~azure.ai.textanalytics.RecognizeLinkedEntitiesResult, - ~azure.ai.textanalytics.DocumentError] - :raises ~azure.core.exceptions.HttpResponseError or TypeError or ValueError: - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_recognize_linked_entities_async.py - :start-after: [START batch_recognize_linked_entities_async] - :end-before: [END batch_recognize_linked_entities_async] - :language: python - :dedent: 8 - :caption: Recognize linked entities in a batch of documents. - """ - language_arg = kwargs.pop("language", None) - language = language_arg if language_arg is not None else self._default_language - docs = _validate_batch_input(documents, "language", language) - model_version = kwargs.pop("model_version", None) - show_stats = kwargs.pop("show_stats", False) - try: - return await self._client.entities_linking( - documents=docs, - model_version=model_version, - show_stats=show_stats, - cls=kwargs.pop("cls", linked_entities_result), - **kwargs - ) - except HttpResponseError as error: - process_batch_error(error) - - @distributed_trace_async - async def extract_key_phrases( # type: ignore - self, - documents: Union[List[str], List[TextDocumentInput], List[Dict[str, str]]], - **kwargs: Any - ) -> List[Union[ExtractKeyPhrasesResult, DocumentError]]: - """Extract Key Phrases from a batch of documents. - - Returns a list of strings denoting the key phrases in the input - text. For example, for the input text "The food was delicious and there - were wonderful staff", the API returns the main talking points: "food" - and "wonderful staff" - - See https://docs.microsoft.com/azure/cognitive-services/text-analytics/overview#data-limits - for document length limits, maximum batch size, and supported text encoding. - - :param documents: The set of documents to process as part of this batch. - If you wish to specify the ID and language on a per-item basis you must - use as input a list[:class:`~azure.ai.textanalytics.TextDocumentInput`] or a list of - dict representations of :class:`~azure.ai.textanalytics.TextDocumentInput`, like - `{"id": "1", "language": "en", "text": "hello world"}`. - :type documents: - list[str] or list[~azure.ai.textanalytics.TextDocumentInput] - :keyword str language: The 2 letter ISO 639-1 representation of language for the - entire batch. For example, use "en" for English; "es" for Spanish etc. - If not set, uses "en" for English as default. Per-document language will - take precedence over whole batch language. See https://aka.ms/talangs for - supported languages in Text Analytics API. - :keyword str model_version: This value indicates which model will - be used for scoring, e.g. "latest", "2019-10-01". If a model-version - is not specified, the API will default to the latest, non-preview version. - :keyword bool show_stats: If set to true, response will contain document level statistics. - :return: The combined list of :class:`~azure.ai.textanalytics.ExtractKeyPhrasesResult` and - :class:`~azure.ai.textanalytics.DocumentError` in the order the original documents were - passed in. - :rtype: list[~azure.ai.textanalytics.ExtractKeyPhrasesResult, - ~azure.ai.textanalytics.DocumentError] - :raises ~azure.core.exceptions.HttpResponseError or TypeError or ValueError: - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_extract_key_phrases_async.py - :start-after: [START batch_extract_key_phrases_async] - :end-before: [END batch_extract_key_phrases_async] - :language: python - :dedent: 8 - :caption: Extract the key phrases in a batch of documents. - """ - language_arg = kwargs.pop("language", None) - language = language_arg if language_arg is not None else self._default_language - docs = _validate_batch_input(documents, "language", language) - model_version = kwargs.pop("model_version", None) - show_stats = kwargs.pop("show_stats", False) - try: - return await self._client.key_phrases( - documents=docs, - model_version=model_version, - show_stats=show_stats, - cls=kwargs.pop("cls", key_phrases_result), - **kwargs - ) - except HttpResponseError as error: - process_batch_error(error) - - @distributed_trace_async - async def analyze_sentiment( # type: ignore - self, - documents: Union[List[str], List[TextDocumentInput], List[Dict[str, str]]], - **kwargs: Any - ) -> List[Union[AnalyzeSentimentResult, DocumentError]]: - """Analyze sentiment for a batch of documents. - - Returns a sentiment prediction, as well as sentiment scores for - each sentiment class (Positive, Negative, and Neutral) for the document - and each sentence within it. - - See https://docs.microsoft.com/azure/cognitive-services/text-analytics/overview#data-limits - for document length limits, maximum batch size, and supported text encoding. - - :param documents: The set of documents to process as part of this batch. - If you wish to specify the ID and language on a per-item basis you must - use as input a list[:class:`~azure.ai.textanalytics.TextDocumentInput`] or a list of - dict representations of :class:`~azure.ai.textanalytics.TextDocumentInput`, like - `{"id": "1", "language": "en", "text": "hello world"}`. - :type documents: - list[str] or list[~azure.ai.textanalytics.TextDocumentInput] - :keyword str language: The 2 letter ISO 639-1 representation of language for the - entire batch. For example, use "en" for English; "es" for Spanish etc. - If not set, uses "en" for English as default. Per-document language will - take precedence over whole batch language. See https://aka.ms/talangs for - supported languages in Text Analytics API. - :keyword str model_version: This value indicates which model will - be used for scoring, e.g. "latest", "2019-10-01". If a model-version - is not specified, the API will default to the latest, non-preview version. - :keyword bool show_stats: If set to true, response will contain document level statistics. - :return: The combined list of :class:`~azure.ai.textanalytics.AnalyzeSentimentResult` and - :class:`~azure.ai.textanalytics.DocumentError` in the order the original documents were - passed in. - :rtype: list[~azure.ai.textanalytics.AnalyzeSentimentResult, - ~azure.ai.textanalytics.DocumentError] - :raises ~azure.core.exceptions.HttpResponseError or TypeError or ValueError: - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_analyze_sentiment_async.py - :start-after: [START batch_analyze_sentiment_async] - :end-before: [END batch_analyze_sentiment_async] - :language: python - :dedent: 8 - :caption: Analyze sentiment in a batch of documents. - """ - language_arg = kwargs.pop("language", None) - language = language_arg if language_arg is not None else self._default_language - docs = _validate_batch_input(documents, "language", language) - model_version = kwargs.pop("model_version", None) - show_stats = kwargs.pop("show_stats", False) - try: - return await self._client.sentiment( - documents=docs, - model_version=model_version, - show_stats=show_stats, - cls=kwargs.pop("cls", sentiment_result), - **kwargs - ) - except HttpResponseError as error: - process_batch_error(error)