# 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.
# --------------------------------------------------------------------------
import functools
from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar, Union
import warnings

from .....aio._lro_async import AsyncAnalyzeActionsLROPoller, AsyncAnalyzeActionsLROPollingMethod, AsyncAnalyzeHealthcareEntitiesLROPoller, AsyncAnalyzeHealthcareEntitiesLROPollingMethod
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.polling.async_base_polling import AsyncLROBasePolling
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator_async import distributed_trace_async

from ... import models as _models
from ..._vendor import _convert_request
from ...operations._text_analytics_client_operations import build_analyze_request_initial, build_analyze_status_request, build_cancel_health_job_request_initial, build_entities_linking_request, build_entities_recognition_general_request, build_entities_recognition_pii_request, build_health_request_initial, build_health_status_request, build_key_phrases_request, build_languages_request, build_sentiment_request

T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]

class TextAnalyticsClientOperationsMixin:

    async def _analyze_initial(
        self,
        body: Optional["_models.AnalyzeBatchInput"] = None,
        **kwargs: Any
    ) -> Optional["_models.AnalyzeJobState"]:
        cls = kwargs.pop('cls', None)  # type: ClsType[Optional["_models.AnalyzeJobState"]]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        content_type = kwargs.pop('content_type', "application/json")  # type: Optional[str]

        if body is not None:
            json = self._serialize.body(body, 'AnalyzeBatchInput')
        else:
            json = None

        request = build_analyze_request_initial(
            content_type=content_type,
            json=json,
            template_url=self._analyze_initial.metadata['url'],
        )
        request = _convert_request(request)
        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

        pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        deserialized = None
        response_headers = {}
        if response.status_code == 200:
            deserialized = self._deserialize('AnalyzeJobState', pipeline_response)

        if response.status_code == 202:
            response_headers['Operation-Location']=self._deserialize('str', response.headers.get('Operation-Location'))
            

        if cls:
            return cls(pipeline_response, deserialized, response_headers)

        return deserialized

    _analyze_initial.metadata = {'url': '/analyze'}  # type: ignore


    @distributed_trace_async
    async def begin_analyze(
        self,
        body: Optional["_models.AnalyzeBatchInput"] = None,
        **kwargs: Any
    ) -> AsyncAnalyzeActionsLROPoller["_models.AnalyzeJobState"]:
        """Submit analysis job.

        Submit a collection of text documents for analysis. Specify one or more unique tasks to be
        executed.

        :param body: Collection of documents to analyze and tasks to execute.
        :type body: ~azure.ai.textanalytics.v3_1.models.AnalyzeBatchInput
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: By default, your polling method will be AsyncAnalyzeActionsLROPollingMethod.
         Pass in False for this operation to not poll, or pass in your own initialized polling object
         for a personal polling strategy.
        :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no
         Retry-After header is present.
        :return: An instance of AsyncAnalyzeActionsLROPoller that returns either AnalyzeJobState or the
         result of cls(response)
        :rtype:
         ~.....aio._lro_async.AsyncAnalyzeActionsLROPoller[~azure.ai.textanalytics.v3_1.models.AnalyzeJobState]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        content_type = kwargs.pop('content_type', "application/json")  # type: Optional[str]
        polling = kwargs.pop('polling', True)  # type: Union[bool, azure.core.polling.AsyncPollingMethod]
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.AnalyzeJobState"]
        lro_delay = kwargs.pop(
            'polling_interval',
            self._config.polling_interval
        )
        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
        if cont_token is None:
            raw_result = await self._analyze_initial(
                body=body,
                content_type=content_type,
                cls=lambda x,y,z: x,
                **kwargs
            )
        kwargs.pop('error_map', None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = self._deserialize('AnalyzeJobState', pipeline_response)
            if cls:
                return cls(pipeline_response, deserialized, {})
            return deserialized


        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }

        if polling is True: polling_method = AsyncAnalyzeActionsLROPollingMethod(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
        elif polling is False: polling_method = AsyncNoPolling()
        else: polling_method = polling
        if cont_token:
            return AsyncAnalyzeActionsLROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        else:
            return AsyncAnalyzeActionsLROPoller(self._client, raw_result, get_long_running_output, polling_method)

    begin_analyze.metadata = {'url': '/analyze'}  # type: ignore

    @distributed_trace_async
    async def analyze_status(
        self,
        job_id: str,
        show_stats: Optional[bool] = None,
        top: Optional[int] = 20,
        skip: Optional[int] = 0,
        **kwargs: Any
    ) -> "_models.AnalyzeJobState":
        """Get analysis status and results.

        Get the status of an analysis job.  A job may consist of one or more tasks.  Once all tasks are
        completed, the job will transition to the completed state and results will be available for
        each task.

        :param job_id: Job ID for Analyze.
        :type job_id: str
        :param show_stats: (Optional) if set to true, response will contain request and document level
         statistics.
        :type show_stats: bool
        :param top: (Optional) Set the maximum number of results per task. When both $top and $skip are
         specified, $skip is applied first.
        :type top: int
        :param skip: (Optional) Set the number of elements to offset in the response. When both $top
         and $skip are specified, $skip is applied first.
        :type skip: int
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: AnalyzeJobState, or the result of cls(response)
        :rtype: ~azure.ai.textanalytics.v3_1.models.AnalyzeJobState
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.AnalyzeJobState"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        
        request = build_analyze_status_request(
            job_id=job_id,
            show_stats=show_stats,
            top=top,
            skip=skip,
            template_url=self.analyze_status.metadata['url'],
        )
        request = _convert_request(request)
        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

        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.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

        deserialized = self._deserialize('AnalyzeJobState', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    analyze_status.metadata = {'url': '/analyze/jobs/{jobId}'}  # type: ignore


    @distributed_trace_async
    async def health_status(
        self,
        job_id: str,
        top: Optional[int] = 20,
        skip: Optional[int] = 0,
        show_stats: Optional[bool] = None,
        **kwargs: Any
    ) -> "_models.HealthcareJobState":
        """Get healthcare analysis job status and results.

        Get details of the healthcare prediction job specified by the jobId.

        :param job_id: Job ID.
        :type job_id: str
        :param top: (Optional) Set the maximum number of results per task. When both $top and $skip are
         specified, $skip is applied first.
        :type top: int
        :param skip: (Optional) Set the number of elements to offset in the response. When both $top
         and $skip are specified, $skip is applied first.
        :type skip: int
        :param show_stats: (Optional) if set to true, response will contain request and document level
         statistics.
        :type show_stats: bool
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: HealthcareJobState, or the result of cls(response)
        :rtype: ~azure.ai.textanalytics.v3_1.models.HealthcareJobState
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.HealthcareJobState"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        
        request = build_health_status_request(
            job_id=job_id,
            top=top,
            skip=skip,
            show_stats=show_stats,
            template_url=self.health_status.metadata['url'],
        )
        request = _convert_request(request)
        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

        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.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

        deserialized = self._deserialize('HealthcareJobState', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    health_status.metadata = {'url': '/entities/health/jobs/{jobId}'}  # type: ignore


    async def _cancel_health_job_initial(
        self,
        job_id: str,
        **kwargs: Any
    ) -> None:
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        
        request = build_cancel_health_job_request_initial(
            job_id=job_id,
            template_url=self._cancel_health_job_initial.metadata['url'],
        )
        request = _convert_request(request)
        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

        pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [202]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        response_headers = {}
        response_headers['Operation-Location']=self._deserialize('str', response.headers.get('Operation-Location'))


        if cls:
            return cls(pipeline_response, None, response_headers)

    _cancel_health_job_initial.metadata = {'url': '/entities/health/jobs/{jobId}'}  # type: ignore


    @distributed_trace_async
    async def begin_cancel_health_job(
        self,
        job_id: str,
        **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Cancel healthcare prediction job.

        Cancel healthcare prediction job.

        :param job_id: Job ID.
        :type job_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False
         for this operation to not poll, or pass in your own initialized polling object for a personal
         polling strategy.
        :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no
         Retry-After header is present.
        :return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
        :rtype: ~azure.core.polling.AsyncLROPoller[None]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        polling = kwargs.pop('polling', True)  # type: Union[bool, azure.core.polling.AsyncPollingMethod]
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        lro_delay = kwargs.pop(
            'polling_interval',
            self._config.polling_interval
        )
        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
        if cont_token is None:
            raw_result = await self._cancel_health_job_initial(
                job_id=job_id,
                cls=lambda x,y,z: x,
                **kwargs
            )
        kwargs.pop('error_map', None)

        def get_long_running_output(pipeline_response):
            if cls:
                return cls(pipeline_response, None, {})


        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }

        if polling is True: polling_method = AsyncLROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
        elif polling is False: polling_method = AsyncNoPolling()
        else: polling_method = polling
        if cont_token:
            return AsyncLROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        else:
            return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)

    begin_cancel_health_job.metadata = {'url': '/entities/health/jobs/{jobId}'}  # type: ignore

    async def _health_initial(
        self,
        documents: List["_models.MultiLanguageInput"],
        model_version: Optional[str] = None,
        string_index_type: Optional[Union[str, "_models.StringIndexType"]] = None,
        logging_opt_out: Optional[bool] = None,
        **kwargs: Any
    ) -> Optional["_models.HealthcareJobState"]:
        cls = kwargs.pop('cls', None)  # type: ClsType[Optional["_models.HealthcareJobState"]]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        content_type = kwargs.pop('content_type', "application/json")  # type: Optional[str]

        _input = _models.MultiLanguageBatchInput(documents=documents)
        json = self._serialize.body(_input, 'MultiLanguageBatchInput')

        request = build_health_request_initial(
            content_type=content_type,
            model_version=model_version,
            string_index_type=string_index_type,
            logging_opt_out=logging_opt_out,
            json=json,
            template_url=self._health_initial.metadata['url'],
        )
        request = _convert_request(request)
        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

        pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200, 202]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        deserialized = None
        response_headers = {}
        if response.status_code == 200:
            deserialized = self._deserialize('HealthcareJobState', pipeline_response)

        if response.status_code == 202:
            response_headers['Operation-Location']=self._deserialize('str', response.headers.get('Operation-Location'))
            

        if cls:
            return cls(pipeline_response, deserialized, response_headers)

        return deserialized

    _health_initial.metadata = {'url': '/entities/health/jobs'}  # type: ignore


    @distributed_trace_async
    async def begin_health(
        self,
        documents: List["_models.MultiLanguageInput"],
        model_version: Optional[str] = None,
        string_index_type: Optional[Union[str, "_models.StringIndexType"]] = None,
        logging_opt_out: Optional[bool] = None,
        **kwargs: Any
    ) -> AsyncAnalyzeHealthcareEntitiesLROPoller["_models.HealthcareJobState"]:
        """Submit healthcare analysis job.

        Start a healthcare analysis job to recognize healthcare related entities (drugs, conditions,
        symptoms, etc) and their relations.

        :param documents: The set of documents to process as part of this batch.
        :type documents: list[~azure.ai.textanalytics.v3_1.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 string_index_type: (Optional) Specifies the method used to interpret string offsets.
         Defaults to Text Elements (Graphemes) according to Unicode v8.0.0. For additional information
         see https://aka.ms/text-analytics-offsets.
        :type string_index_type: str or ~azure.ai.textanalytics.v3_1.models.StringIndexType
        :param logging_opt_out: (Optional) If set to true, you opt-out of having your text input logged
         for troubleshooting. By default, Text Analytics logs your input text for 48 hours, solely to
         allow for troubleshooting issues in providing you with the Text Analytics natural language
         processing functions. Setting this parameter to true, disables input logging and may limit our
         ability to remediate issues that occur.  Please see Cognitive Services Compliance and Privacy
         notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI
         principles at https://www.microsoft.com/en-us/ai/responsible-ai.
        :type logging_opt_out: bool
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: By default, your polling method will be
         AsyncAnalyzeHealthcareEntitiesLROPollingMethod. Pass in False for this operation to not poll,
         or pass in your own initialized polling object for a personal polling strategy.
        :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no
         Retry-After header is present.
        :return: An instance of AsyncAnalyzeHealthcareEntitiesLROPoller that returns either
         HealthcareJobState or the result of cls(response)
        :rtype:
         ~.....aio._lro_async.AsyncAnalyzeHealthcareEntitiesLROPoller[~azure.ai.textanalytics.v3_1.models.HealthcareJobState]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        content_type = kwargs.pop('content_type', "application/json")  # type: Optional[str]
        polling = kwargs.pop('polling', True)  # type: Union[bool, azure.core.polling.AsyncPollingMethod]
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.HealthcareJobState"]
        lro_delay = kwargs.pop(
            'polling_interval',
            self._config.polling_interval
        )
        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
        if cont_token is None:
            raw_result = await self._health_initial(
                documents=documents,
                model_version=model_version,
                string_index_type=string_index_type,
                logging_opt_out=logging_opt_out,
                content_type=content_type,
                cls=lambda x,y,z: x,
                **kwargs
            )
        kwargs.pop('error_map', None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = self._deserialize('HealthcareJobState', pipeline_response)
            if cls:
                return cls(pipeline_response, deserialized, {})
            return deserialized


        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }

        if polling is True: polling_method = AsyncAnalyzeHealthcareEntitiesLROPollingMethod(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
        elif polling is False: polling_method = AsyncNoPolling()
        else: polling_method = polling
        if cont_token:
            return AsyncAnalyzeHealthcareEntitiesLROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        else:
            return AsyncAnalyzeHealthcareEntitiesLROPoller(self._client, raw_result, get_long_running_output, polling_method)

    begin_health.metadata = {'url': '/entities/health/jobs'}  # type: ignore

    @distributed_trace_async
    async def entities_recognition_general(
        self,
        documents: List["_models.MultiLanguageInput"],
        model_version: Optional[str] = None,
        show_stats: Optional[bool] = None,
        logging_opt_out: Optional[bool] = None,
        string_index_type: Optional[Union[str, "_models.StringIndexType"]] = None,
        **kwargs: Any
    ) -> "_models.EntitiesResult":
        """Named Entity Recognition.

        The API returns a list of general named entities in a given document. For the list of supported
        entity types, check :code:`<a href="https://aka.ms/taner">Supported Entity Types in Text
        Analytics API</a>`. See the :code:`<a href="https://aka.ms/talangs">Supported languages in Text
        Analytics API</a>` for the list of enabled languages.

        :param documents: The set of documents to process as part of this batch.
        :type documents: list[~azure.ai.textanalytics.v3_1.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 request and document level
         statistics.
        :type show_stats: bool
        :param logging_opt_out: (Optional) If set to true, you opt-out of having your text input logged
         for troubleshooting. By default, Text Analytics logs your input text for 48 hours, solely to
         allow for troubleshooting issues in providing you with the Text Analytics natural language
         processing functions. Setting this parameter to true, disables input logging and may limit our
         ability to remediate issues that occur.  Please see Cognitive Services Compliance and Privacy
         notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI
         principles at https://www.microsoft.com/en-us/ai/responsible-ai.
        :type logging_opt_out: bool
        :param string_index_type: (Optional) Specifies the method used to interpret string offsets.
         Defaults to Text Elements (Graphemes) according to Unicode v8.0.0. For additional information
         see https://aka.ms/text-analytics-offsets.
        :type string_index_type: str or ~azure.ai.textanalytics.v3_1.models.StringIndexType
        :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.v3_1.models.EntitiesResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.EntitiesResult"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        content_type = kwargs.pop('content_type', "application/json")  # type: Optional[str]

        _input = _models.MultiLanguageBatchInput(documents=documents)
        json = self._serialize.body(_input, 'MultiLanguageBatchInput')

        request = build_entities_recognition_general_request(
            content_type=content_type,
            model_version=model_version,
            show_stats=show_stats,
            logging_opt_out=logging_opt_out,
            string_index_type=string_index_type,
            json=json,
            template_url=self.entities_recognition_general.metadata['url'],
        )
        request = _convert_request(request)
        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

        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.failsafe_deserialize(_models.ErrorResponse, pipeline_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


    @distributed_trace_async
    async def entities_recognition_pii(
        self,
        documents: List["_models.MultiLanguageInput"],
        model_version: Optional[str] = None,
        show_stats: Optional[bool] = None,
        logging_opt_out: Optional[bool] = None,
        domain: Optional[str] = None,
        string_index_type: Optional[Union[str, "_models.StringIndexType"]] = None,
        pii_categories: Optional[List[Union[str, "_models.PiiCategory"]]] = None,
        **kwargs: Any
    ) -> "_models.PiiResult":
        """Entities containing personal information.

        The API returns a list of entities with personal information (\"SSN\", \"Bank Account\" etc) in
        the document. For the list of supported entity types, check :code:`<a
        href="https://aka.ms/tanerpii">Supported Entity Types in Text Analytics API</a>`. See the
        :code:`<a href="https://aka.ms/talangs">Supported languages in Text Analytics API</a>` for the
        list of enabled languages.

        :param documents: The set of documents to process as part of this batch.
        :type documents: list[~azure.ai.textanalytics.v3_1.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 request and document level
         statistics.
        :type show_stats: bool
        :param logging_opt_out: (Optional) If set to true, you opt-out of having your text input logged
         for troubleshooting. By default, Text Analytics logs your input text for 48 hours, solely to
         allow for troubleshooting issues in providing you with the Text Analytics natural language
         processing functions. Setting this parameter to true, disables input logging and may limit our
         ability to remediate issues that occur.  Please see Cognitive Services Compliance and Privacy
         notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI
         principles at https://www.microsoft.com/en-us/ai/responsible-ai.
        :type logging_opt_out: bool
        :param domain: (Optional) if specified, will set the PII domain to include only a subset of the
         entity categories. Possible values include: 'PHI', 'none'.
        :type domain: str
        :param string_index_type: (Optional) Specifies the method used to interpret string offsets.
         Defaults to Text Elements (Graphemes) according to Unicode v8.0.0. For additional information
         see https://aka.ms/text-analytics-offsets.
        :type string_index_type: str or ~azure.ai.textanalytics.v3_1.models.StringIndexType
        :param pii_categories: (Optional) describes the PII categories to return.
        :type pii_categories: list[str or ~azure.ai.textanalytics.v3_1.models.PiiCategory]
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: PiiResult, or the result of cls(response)
        :rtype: ~azure.ai.textanalytics.v3_1.models.PiiResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.PiiResult"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        content_type = kwargs.pop('content_type', "application/json")  # type: Optional[str]

        _input = _models.MultiLanguageBatchInput(documents=documents)
        json = self._serialize.body(_input, 'MultiLanguageBatchInput')

        request = build_entities_recognition_pii_request(
            content_type=content_type,
            model_version=model_version,
            show_stats=show_stats,
            logging_opt_out=logging_opt_out,
            domain=domain,
            string_index_type=string_index_type,
            pii_categories=pii_categories,
            json=json,
            template_url=self.entities_recognition_pii.metadata['url'],
        )
        request = _convert_request(request)
        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

        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.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

        deserialized = self._deserialize('PiiResult', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    entities_recognition_pii.metadata = {'url': '/entities/recognition/pii'}  # type: ignore


    @distributed_trace_async
    async def entities_linking(
        self,
        documents: List["_models.MultiLanguageInput"],
        model_version: Optional[str] = None,
        show_stats: Optional[bool] = None,
        logging_opt_out: Optional[bool] = None,
        string_index_type: Optional[Union[str, "_models.StringIndexType"]] = None,
        **kwargs: Any
    ) -> "_models.EntityLinkingResult":
        """Linked entities from a well known knowledge base.

        The API returns a list of recognized entities with links to a well known knowledge base. See
        the :code:`<a href="https://aka.ms/talangs">Supported languages in Text Analytics API</a>` for
        the list of enabled languages.

        :param documents: The set of documents to process as part of this batch.
        :type documents: list[~azure.ai.textanalytics.v3_1.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 request and document level
         statistics.
        :type show_stats: bool
        :param logging_opt_out: (Optional) If set to true, you opt-out of having your text input logged
         for troubleshooting. By default, Text Analytics logs your input text for 48 hours, solely to
         allow for troubleshooting issues in providing you with the Text Analytics natural language
         processing functions. Setting this parameter to true, disables input logging and may limit our
         ability to remediate issues that occur.  Please see Cognitive Services Compliance and Privacy
         notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI
         principles at https://www.microsoft.com/en-us/ai/responsible-ai.
        :type logging_opt_out: bool
        :param string_index_type: (Optional) Specifies the method used to interpret string offsets.
         Defaults to Text Elements (Graphemes) according to Unicode v8.0.0. For additional information
         see https://aka.ms/text-analytics-offsets.
        :type string_index_type: str or ~azure.ai.textanalytics.v3_1.models.StringIndexType
        :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.v3_1.models.EntityLinkingResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.EntityLinkingResult"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        content_type = kwargs.pop('content_type', "application/json")  # type: Optional[str]

        _input = _models.MultiLanguageBatchInput(documents=documents)
        json = self._serialize.body(_input, 'MultiLanguageBatchInput')

        request = build_entities_linking_request(
            content_type=content_type,
            model_version=model_version,
            show_stats=show_stats,
            logging_opt_out=logging_opt_out,
            string_index_type=string_index_type,
            json=json,
            template_url=self.entities_linking.metadata['url'],
        )
        request = _convert_request(request)
        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

        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.failsafe_deserialize(_models.ErrorResponse, pipeline_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


    @distributed_trace_async
    async def key_phrases(
        self,
        documents: List["_models.MultiLanguageInput"],
        model_version: Optional[str] = None,
        show_stats: Optional[bool] = None,
        logging_opt_out: Optional[bool] = None,
        **kwargs: Any
    ) -> "_models.KeyPhraseResult":
        """Key Phrases.

        The API returns a list of strings denoting the key phrases in the input text. See the :code:`<a
        href="https://aka.ms/talangs">Supported languages in Text Analytics API</a>` for the list of
        enabled languages.

        :param documents: The set of documents to process as part of this batch.
        :type documents: list[~azure.ai.textanalytics.v3_1.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 request and document level
         statistics.
        :type show_stats: bool
        :param logging_opt_out: (Optional) If set to true, you opt-out of having your text input logged
         for troubleshooting. By default, Text Analytics logs your input text for 48 hours, solely to
         allow for troubleshooting issues in providing you with the Text Analytics natural language
         processing functions. Setting this parameter to true, disables input logging and may limit our
         ability to remediate issues that occur.  Please see Cognitive Services Compliance and Privacy
         notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI
         principles at https://www.microsoft.com/en-us/ai/responsible-ai.
        :type logging_opt_out: 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.v3_1.models.KeyPhraseResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.KeyPhraseResult"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        content_type = kwargs.pop('content_type', "application/json")  # type: Optional[str]

        _input = _models.MultiLanguageBatchInput(documents=documents)
        json = self._serialize.body(_input, 'MultiLanguageBatchInput')

        request = build_key_phrases_request(
            content_type=content_type,
            model_version=model_version,
            show_stats=show_stats,
            logging_opt_out=logging_opt_out,
            json=json,
            template_url=self.key_phrases.metadata['url'],
        )
        request = _convert_request(request)
        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

        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.failsafe_deserialize(_models.ErrorResponse, pipeline_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


    @distributed_trace_async
    async def languages(
        self,
        documents: List["_models.LanguageInput"],
        model_version: Optional[str] = None,
        show_stats: Optional[bool] = None,
        logging_opt_out: Optional[bool] = None,
        **kwargs: Any
    ) -> "_models.LanguageResult":
        """Detect Language.

        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:`<a
        href="https://aka.ms/talangs">Supported languages in Text Analytics API</a>` for the list of
        enabled languages.

        :param documents:
        :type documents: list[~azure.ai.textanalytics.v3_1.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 request and document level
         statistics.
        :type show_stats: bool
        :param logging_opt_out: (Optional) If set to true, you opt-out of having your text input logged
         for troubleshooting. By default, Text Analytics logs your input text for 48 hours, solely to
         allow for troubleshooting issues in providing you with the Text Analytics natural language
         processing functions. Setting this parameter to true, disables input logging and may limit our
         ability to remediate issues that occur.  Please see Cognitive Services Compliance and Privacy
         notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI
         principles at https://www.microsoft.com/en-us/ai/responsible-ai.
        :type logging_opt_out: 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.v3_1.models.LanguageResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.LanguageResult"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        content_type = kwargs.pop('content_type', "application/json")  # type: Optional[str]

        _input = _models.LanguageBatchInput(documents=documents)
        json = self._serialize.body(_input, 'LanguageBatchInput')

        request = build_languages_request(
            content_type=content_type,
            model_version=model_version,
            show_stats=show_stats,
            logging_opt_out=logging_opt_out,
            json=json,
            template_url=self.languages.metadata['url'],
        )
        request = _convert_request(request)
        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

        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.failsafe_deserialize(_models.ErrorResponse, pipeline_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


    @distributed_trace_async
    async def sentiment(
        self,
        documents: List["_models.MultiLanguageInput"],
        model_version: Optional[str] = None,
        show_stats: Optional[bool] = None,
        logging_opt_out: Optional[bool] = None,
        opinion_mining: Optional[bool] = None,
        string_index_type: Optional[Union[str, "_models.StringIndexType"]] = None,
        **kwargs: Any
    ) -> "_models.SentimentResponse":
        """Sentiment.

        The API returns a detailed sentiment analysis for the input text. The analysis is done in
        multiple levels of granularity, start from the a document level, down to sentence and key terms
        (targets and assessments).

        :param documents: The set of documents to process as part of this batch.
        :type documents: list[~azure.ai.textanalytics.v3_1.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 request and document level
         statistics.
        :type show_stats: bool
        :param logging_opt_out: (Optional) If set to true, you opt-out of having your text input logged
         for troubleshooting. By default, Text Analytics logs your input text for 48 hours, solely to
         allow for troubleshooting issues in providing you with the Text Analytics natural language
         processing functions. Setting this parameter to true, disables input logging and may limit our
         ability to remediate issues that occur.  Please see Cognitive Services Compliance and Privacy
         notes at https://aka.ms/cs-compliance for additional details, and Microsoft Responsible AI
         principles at https://www.microsoft.com/en-us/ai/responsible-ai.
        :type logging_opt_out: bool
        :param opinion_mining: (Optional) if set to true, response will contain not only sentiment
         prediction but also opinion mining (aspect-based sentiment analysis) results.
        :type opinion_mining: bool
        :param string_index_type: (Optional) Specifies the method used to interpret string offsets.
         Defaults to Text Elements (Graphemes) according to Unicode v8.0.0. For additional information
         see https://aka.ms/text-analytics-offsets.
        :type string_index_type: str or ~azure.ai.textanalytics.v3_1.models.StringIndexType
        :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.v3_1.models.SentimentResponse
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.SentimentResponse"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        content_type = kwargs.pop('content_type', "application/json")  # type: Optional[str]

        _input = _models.MultiLanguageBatchInput(documents=documents)
        json = self._serialize.body(_input, 'MultiLanguageBatchInput')

        request = build_sentiment_request(
            content_type=content_type,
            model_version=model_version,
            show_stats=show_stats,
            logging_opt_out=logging_opt_out,
            opinion_mining=opinion_mining,
            string_index_type=string_index_type,
            json=json,
            template_url=self.sentiment.metadata['url'],
        )
        request = _convert_request(request)
        path_format_arguments = {
            "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

        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.failsafe_deserialize(_models.ErrorResponse, pipeline_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

