# pylint: disable=too-many-lines
# 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, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast

from azure.core.async_paging import AsyncItemPaged, AsyncList
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 import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict

from ... import models as _models
from ..._vendor import _convert_request
from ...operations._form_recognizer_client_operations import build_analyze_layout_async_request_initial, build_analyze_receipt_async_request_initial, build_analyze_with_custom_model_request_initial, build_copy_custom_model_request_initial, build_delete_custom_model_request, build_generate_model_copy_authorization_request, build_get_analyze_form_result_request, build_get_analyze_layout_result_request, build_get_analyze_receipt_result_request, build_get_custom_model_copy_result_request, build_get_custom_model_request, build_get_custom_models_request, build_list_custom_models_request, build_train_custom_model_async_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]

class FormRecognizerClientOperationsMixin:

    @distributed_trace_async
    async def train_custom_model_async(  # pylint: disable=inconsistent-return-statements
        self,
        train_request: _models.TrainRequest,
        **kwargs: Any
    ) -> None:
        """Train Custom Model.

        Create and train a custom model. The request must include a source parameter that is either an
        externally accessible Azure storage blob container Uri (preferably a Shared Access Signature
        Uri) or valid path to a data folder in a locally mounted drive. When local paths are specified,
        they must follow the Linux/Unix path format and be an absolute path rooted to the input mount
        configuration setting value e.g., if '{Mounts:Input}' configuration setting value is '/input'
        then a valid source path would be '/input/contosodataset'. All data to be trained is expected
        to be under the source folder or sub folders under it. Models are trained using documents that
        are of the following content type - 'application/pdf', 'image/jpeg', 'image/png', 'image/tiff'.
        Other type of content is ignored.

        :param train_request: Training request parameters.
        :type train_request: ~azure.ai.formrecognizer.v2_0.models.TrainRequest
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None, or the result of cls(response)
        :rtype: None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json"))  # type: Optional[str]
        cls = kwargs.pop('cls', None)  # type: ClsType[None]

        _json = self._serialize.body(train_request, 'TrainRequest')

        request = build_train_custom_model_async_request(
            content_type=content_type,
            json=_json,
            template_url=self.train_custom_model_async.metadata['url'],
            headers=_headers,
            params=_params,
        )
        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)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request,
            stream=False,
            **kwargs
        )
        response = pipeline_response.http_response

        if response.status_code not in [201]:
            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)

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


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

    train_custom_model_async.metadata = {'url': "/custom/models"}  # type: ignore


    @distributed_trace_async
    async def get_custom_model(
        self,
        model_id: str,
        include_keys: Optional[bool] = False,
        **kwargs: Any
    ) -> _models.Model:
        """Get Custom Model.

        Get detailed information about a custom model.

        :param model_id: Model identifier.
        :type model_id: str
        :param include_keys: Include list of extracted keys in model information. Default value is
         False.
        :type include_keys: bool
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: Model, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2_0.models.Model
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[_models.Model]

        
        request = build_get_custom_model_request(
            model_id=model_id,
            include_keys=include_keys,
            template_url=self.get_custom_model.metadata['url'],
            headers=_headers,
            params=_params,
        )
        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)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            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('Model', pipeline_response)

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

        return deserialized

    get_custom_model.metadata = {'url': "/custom/models/{modelId}"}  # type: ignore


    @distributed_trace_async
    async def delete_custom_model(  # pylint: disable=inconsistent-return-statements
        self,
        model_id: str,
        **kwargs: Any
    ) -> None:
        """Delete Custom Model.

        Mark model for deletion. Model artifacts will be permanently removed within a predetermined
        period.

        :param model_id: Model identifier.
        :type model_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None, or the result of cls(response)
        :rtype: None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[None]

        
        request = build_delete_custom_model_request(
            model_id=model_id,
            template_url=self.delete_custom_model.metadata['url'],
            headers=_headers,
            params=_params,
        )
        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)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request,
            stream=False,
            **kwargs
        )
        response = pipeline_response.http_response

        if response.status_code not in [204]:
            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)

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

    delete_custom_model.metadata = {'url': "/custom/models/{modelId}"}  # type: ignore


    async def _analyze_with_custom_model_initial(  # pylint: disable=inconsistent-return-statements
        self,
        model_id: str,
        include_text_details: Optional[bool] = False,
        file_stream: Optional[Union[IO, _models.SourcePath]] = None,
        *,
        content_type: Optional[Union[str, "_models.ContentType"]] = "application/json",
        **kwargs: Any
    ) -> None:
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[None]

        _json = None
        _content = None
        content_type = content_type or ""
        if content_type.split(";")[0] in ['application/json']:
            if file_stream is not None:
                _json = self._serialize.body(file_stream, 'SourcePath')
        elif content_type.split(";")[0] in ['application/pdf', 'image/jpeg', 'image/png', 'image/tiff']:
            _content = file_stream
        else:
            raise ValueError(
                "The content_type '{}' is not one of the allowed values: "
                "['application/pdf', 'image/jpeg', 'image/png', 'image/tiff', 'application/json']".format(content_type)
            )

        request = build_analyze_with_custom_model_request_initial(
            model_id=model_id,
            content_type=content_type,
            json=_json,
            content=_content,
            include_text_details=include_text_details,
            template_url=self._analyze_with_custom_model_initial.metadata['url'],
            headers=_headers,
            params=_params,
        )
        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)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            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)

    _analyze_with_custom_model_initial.metadata = {'url': "/custom/models/{modelId}/analyze"}  # type: ignore


    @distributed_trace_async
    async def begin_analyze_with_custom_model(  # pylint: disable=inconsistent-return-statements
        self,
        model_id: str,
        include_text_details: Optional[bool] = False,
        file_stream: Optional[Union[IO, _models.SourcePath]] = None,
        *,
        content_type: Optional[Union[str, "_models.ContentType"]] = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Analyze Form.

        Extract key-value pairs, tables, and semantic values from a given document. The input document
        must be of one of the supported content types - 'application/pdf', 'image/jpeg', 'image/png' or
        'image/tiff'. Alternatively, use 'application/json' type to specify the location (Uri or local
        path) of the document to be analyzed.

        :param model_id: Model identifier.
        :type model_id: str
        :param include_text_details: Include text lines and element references in the result. Default
         value is False.
        :type include_text_details: bool
        :param file_stream: .json, .pdf, .jpg, .png or .tiff type file stream. Default value is None.
        :type file_stream: IO or ~azure.ai.formrecognizer.v2_0.models.SourcePath
        :keyword content_type: Media type of the body sent to the API. Known values are:
         "application/pdf", "image/jpeg", "image/png", "image/tiff", and "application/json". Default
         value is "application/json".
        :paramtype content_type: str or ~azure.ai.formrecognizer.v2_0.models.ContentType
        :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
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        polling = kwargs.pop('polling', True)  # type: Union[bool, AsyncPollingMethod]
        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_with_custom_model_initial(  # type: ignore
                model_id=model_id,
                include_text_details=include_text_details,
                file_stream=file_stream,
                content_type=content_type,
                cls=lambda x,y,z: x,
                headers=_headers,
                params=_params,
                **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 = cast(AsyncPollingMethod, AsyncLROBasePolling(
                lro_delay,
                
                path_format_arguments=path_format_arguments,
                **kwargs
        ))  # type: AsyncPollingMethod
        elif polling is False: polling_method = cast(AsyncPollingMethod, 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
            )
        return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)

    begin_analyze_with_custom_model.metadata = {'url': "/custom/models/{modelId}/analyze"}  # type: ignore

    @distributed_trace_async
    async def get_analyze_form_result(
        self,
        model_id: str,
        result_id: str,
        **kwargs: Any
    ) -> _models.AnalyzeOperationResult:
        """Get Analyze Form Result.

        Obtain current status and the result of the analyze form operation.

        :param model_id: Model identifier.
        :type model_id: str
        :param result_id: Analyze operation result identifier.
        :type result_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: AnalyzeOperationResult, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2_0.models.AnalyzeOperationResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[_models.AnalyzeOperationResult]

        
        request = build_get_analyze_form_result_request(
            model_id=model_id,
            result_id=result_id,
            template_url=self.get_analyze_form_result.metadata['url'],
            headers=_headers,
            params=_params,
        )
        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)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            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('AnalyzeOperationResult', pipeline_response)

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

        return deserialized

    get_analyze_form_result.metadata = {'url': "/custom/models/{modelId}/analyzeResults/{resultId}"}  # type: ignore


    async def _copy_custom_model_initial(  # pylint: disable=inconsistent-return-statements
        self,
        model_id: str,
        copy_request: _models.CopyRequest,
        **kwargs: Any
    ) -> None:
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json"))  # type: Optional[str]
        cls = kwargs.pop('cls', None)  # type: ClsType[None]

        _json = self._serialize.body(copy_request, 'CopyRequest')

        request = build_copy_custom_model_request_initial(
            model_id=model_id,
            content_type=content_type,
            json=_json,
            template_url=self._copy_custom_model_initial.metadata['url'],
            headers=_headers,
            params=_params,
        )
        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)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            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)

    _copy_custom_model_initial.metadata = {'url': "/custom/models/{modelId}/copy"}  # type: ignore


    @distributed_trace_async
    async def begin_copy_custom_model(  # pylint: disable=inconsistent-return-statements
        self,
        model_id: str,
        copy_request: _models.CopyRequest,
        **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Copy Custom Model.

        Copy custom model stored in this resource (the source) to user specified target Form Recognizer
        resource.

        :param model_id: Model identifier.
        :type model_id: str
        :param copy_request: Copy request parameters.
        :type copy_request: ~azure.ai.formrecognizer.v2_0.models.CopyRequest
        :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
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json"))  # type: Optional[str]
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        polling = kwargs.pop('polling', True)  # type: Union[bool, AsyncPollingMethod]
        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._copy_custom_model_initial(  # type: ignore
                model_id=model_id,
                copy_request=copy_request,
                content_type=content_type,
                cls=lambda x,y,z: x,
                headers=_headers,
                params=_params,
                **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 = cast(AsyncPollingMethod, AsyncLROBasePolling(
                lro_delay,
                
                path_format_arguments=path_format_arguments,
                **kwargs
        ))  # type: AsyncPollingMethod
        elif polling is False: polling_method = cast(AsyncPollingMethod, 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
            )
        return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)

    begin_copy_custom_model.metadata = {'url': "/custom/models/{modelId}/copy"}  # type: ignore

    @distributed_trace_async
    async def get_custom_model_copy_result(
        self,
        model_id: str,
        result_id: str,
        **kwargs: Any
    ) -> _models.CopyOperationResult:
        """Get Custom Model Copy Result.

        Obtain current status and the result of a custom model copy operation.

        :param model_id: Model identifier.
        :type model_id: str
        :param result_id: Copy operation result identifier.
        :type result_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: CopyOperationResult, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2_0.models.CopyOperationResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[_models.CopyOperationResult]

        
        request = build_get_custom_model_copy_result_request(
            model_id=model_id,
            result_id=result_id,
            template_url=self.get_custom_model_copy_result.metadata['url'],
            headers=_headers,
            params=_params,
        )
        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)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            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('CopyOperationResult', pipeline_response)

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

        return deserialized

    get_custom_model_copy_result.metadata = {'url': "/custom/models/{modelId}/copyResults/{resultId}"}  # type: ignore


    @distributed_trace_async
    async def generate_model_copy_authorization(
        self,
        **kwargs: Any
    ) -> _models.CopyAuthorizationResult:
        """Generate Copy Authorization.

        Generate authorization to copy a model into the target Form Recognizer resource.

        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: CopyAuthorizationResult, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2_0.models.CopyAuthorizationResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[_models.CopyAuthorizationResult]

        
        request = build_generate_model_copy_authorization_request(
            template_url=self.generate_model_copy_authorization.metadata['url'],
            headers=_headers,
            params=_params,
        )
        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)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request,
            stream=False,
            **kwargs
        )
        response = pipeline_response.http_response

        if response.status_code not in [201]:
            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)

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

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

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

        return deserialized

    generate_model_copy_authorization.metadata = {'url': "/custom/models/copyAuthorization"}  # type: ignore


    async def _analyze_receipt_async_initial(  # pylint: disable=inconsistent-return-statements
        self,
        include_text_details: Optional[bool] = False,
        file_stream: Optional[Union[IO, _models.SourcePath]] = None,
        *,
        content_type: Optional[Union[str, "_models.ContentType"]] = "application/json",
        **kwargs: Any
    ) -> None:
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[None]

        _json = None
        _content = None
        content_type = content_type or ""
        if content_type.split(";")[0] in ['application/json']:
            if file_stream is not None:
                _json = self._serialize.body(file_stream, 'SourcePath')
        elif content_type.split(";")[0] in ['application/pdf', 'image/jpeg', 'image/png', 'image/tiff']:
            _content = file_stream
        else:
            raise ValueError(
                "The content_type '{}' is not one of the allowed values: "
                "['application/pdf', 'image/jpeg', 'image/png', 'image/tiff', 'application/json']".format(content_type)
            )

        request = build_analyze_receipt_async_request_initial(
            content_type=content_type,
            json=_json,
            content=_content,
            include_text_details=include_text_details,
            template_url=self._analyze_receipt_async_initial.metadata['url'],
            headers=_headers,
            params=_params,
        )
        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)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            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)

    _analyze_receipt_async_initial.metadata = {'url': "/prebuilt/receipt/analyze"}  # type: ignore


    @distributed_trace_async
    async def begin_analyze_receipt_async(  # pylint: disable=inconsistent-return-statements
        self,
        include_text_details: Optional[bool] = False,
        file_stream: Optional[Union[IO, _models.SourcePath]] = None,
        *,
        content_type: Optional[Union[str, "_models.ContentType"]] = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Analyze Receipt.

        Extract field text and semantic values from a given receipt document. The input document must
        be of one of the supported content types - 'application/pdf', 'image/jpeg', 'image/png' or
        'image/tiff'. Alternatively, use 'application/json' type to specify the location (Uri or local
        path) of the document to be analyzed.

        :param include_text_details: Include text lines and element references in the result. Default
         value is False.
        :type include_text_details: bool
        :param file_stream: .json, .pdf, .jpg, .png or .tiff type file stream. Default value is None.
        :type file_stream: IO or ~azure.ai.formrecognizer.v2_0.models.SourcePath
        :keyword content_type: Media type of the body sent to the API. Known values are:
         "application/pdf", "image/jpeg", "image/png", "image/tiff", and "application/json". Default
         value is "application/json".
        :paramtype content_type: str or ~azure.ai.formrecognizer.v2_0.models.ContentType
        :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
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        polling = kwargs.pop('polling', True)  # type: Union[bool, AsyncPollingMethod]
        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_receipt_async_initial(  # type: ignore
                include_text_details=include_text_details,
                file_stream=file_stream,
                content_type=content_type,
                cls=lambda x,y,z: x,
                headers=_headers,
                params=_params,
                **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 = cast(AsyncPollingMethod, AsyncLROBasePolling(
                lro_delay,
                
                path_format_arguments=path_format_arguments,
                **kwargs
        ))  # type: AsyncPollingMethod
        elif polling is False: polling_method = cast(AsyncPollingMethod, 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
            )
        return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)

    begin_analyze_receipt_async.metadata = {'url': "/prebuilt/receipt/analyze"}  # type: ignore

    @distributed_trace_async
    async def get_analyze_receipt_result(
        self,
        result_id: str,
        **kwargs: Any
    ) -> _models.AnalyzeOperationResult:
        """Get Analyze Receipt Result.

        Track the progress and obtain the result of the analyze receipt operation.

        :param result_id: Analyze operation result identifier.
        :type result_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: AnalyzeOperationResult, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2_0.models.AnalyzeOperationResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[_models.AnalyzeOperationResult]

        
        request = build_get_analyze_receipt_result_request(
            result_id=result_id,
            template_url=self.get_analyze_receipt_result.metadata['url'],
            headers=_headers,
            params=_params,
        )
        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)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            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('AnalyzeOperationResult', pipeline_response)

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

        return deserialized

    get_analyze_receipt_result.metadata = {'url': "/prebuilt/receipt/analyzeResults/{resultId}"}  # type: ignore


    async def _analyze_layout_async_initial(  # pylint: disable=inconsistent-return-statements
        self,
        file_stream: Optional[Union[IO, _models.SourcePath]] = None,
        *,
        content_type: Optional[Union[str, "_models.ContentType"]] = "application/json",
        **kwargs: Any
    ) -> None:
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[None]

        _json = None
        _content = None
        content_type = content_type or ""
        if content_type.split(";")[0] in ['application/json']:
            if file_stream is not None:
                _json = self._serialize.body(file_stream, 'SourcePath')
        elif content_type.split(";")[0] in ['application/pdf', 'image/jpeg', 'image/png', 'image/tiff']:
            _content = file_stream
        else:
            raise ValueError(
                "The content_type '{}' is not one of the allowed values: "
                "['application/pdf', 'image/jpeg', 'image/png', 'image/tiff', 'application/json']".format(content_type)
            )

        request = build_analyze_layout_async_request_initial(
            content_type=content_type,
            json=_json,
            content=_content,
            template_url=self._analyze_layout_async_initial.metadata['url'],
            headers=_headers,
            params=_params,
        )
        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)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            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)

    _analyze_layout_async_initial.metadata = {'url': "/layout/analyze"}  # type: ignore


    @distributed_trace_async
    async def begin_analyze_layout_async(  # pylint: disable=inconsistent-return-statements
        self,
        file_stream: Optional[Union[IO, _models.SourcePath]] = None,
        *,
        content_type: Optional[Union[str, "_models.ContentType"]] = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Analyze Layout.

        Extract text and layout information from a given document. The input document must be of one of
        the supported content types - 'application/pdf', 'image/jpeg', 'image/png' or 'image/tiff'.
        Alternatively, use 'application/json' type to specify the location (Uri or local path) of the
        document to be analyzed.

        :param file_stream: .json, .pdf, .jpg, .png or .tiff type file stream. Default value is None.
        :type file_stream: IO or ~azure.ai.formrecognizer.v2_0.models.SourcePath
        :keyword content_type: Media type of the body sent to the API. Known values are:
         "application/pdf", "image/jpeg", "image/png", "image/tiff", and "application/json". Default
         value is "application/json".
        :paramtype content_type: str or ~azure.ai.formrecognizer.v2_0.models.ContentType
        :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
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        polling = kwargs.pop('polling', True)  # type: Union[bool, AsyncPollingMethod]
        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_layout_async_initial(  # type: ignore
                file_stream=file_stream,
                content_type=content_type,
                cls=lambda x,y,z: x,
                headers=_headers,
                params=_params,
                **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 = cast(AsyncPollingMethod, AsyncLROBasePolling(
                lro_delay,
                
                path_format_arguments=path_format_arguments,
                **kwargs
        ))  # type: AsyncPollingMethod
        elif polling is False: polling_method = cast(AsyncPollingMethod, 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
            )
        return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)

    begin_analyze_layout_async.metadata = {'url': "/layout/analyze"}  # type: ignore

    @distributed_trace_async
    async def get_analyze_layout_result(
        self,
        result_id: str,
        **kwargs: Any
    ) -> _models.AnalyzeOperationResult:
        """Get Analyze Layout Result.

        Track the progress and obtain the result of the analyze layout operation.

        :param result_id: Analyze operation result identifier.
        :type result_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: AnalyzeOperationResult, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2_0.models.AnalyzeOperationResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[_models.AnalyzeOperationResult]

        
        request = build_get_analyze_layout_result_request(
            result_id=result_id,
            template_url=self.get_analyze_layout_result.metadata['url'],
            headers=_headers,
            params=_params,
        )
        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)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            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('AnalyzeOperationResult', pipeline_response)

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

        return deserialized

    get_analyze_layout_result.metadata = {'url': "/layout/analyzeResults/{resultId}"}  # type: ignore


    @distributed_trace
    def list_custom_models(
        self,
        **kwargs: Any
    ) -> AsyncIterable[_models.Models]:
        """List Custom Models.

        Get information about all custom models.

        :keyword op: Specify whether to return summary or full list of models. Default value is "full".
         Note that overriding this default value may result in unsupported behavior.
        :paramtype op: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either Models or the result of cls(response)
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.formrecognizer.v2_0.models.Models]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        op = kwargs.pop('op', _params.pop('op', "full"))  # type: str
        cls = kwargs.pop('cls', None)  # type: ClsType[_models.Models]

        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})
        def prepare_request(next_link=None):
            if not next_link:
                
                request = build_list_custom_models_request(
                    op=op,
                    template_url=self.list_custom_models.metadata['url'],
                    headers=_headers,
                    params=_params,
                )
                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)  # type: ignore

            else:
                
                request = build_list_custom_models_request(
                    op=op,
                    template_url=next_link,
                    headers=_headers,
                    params=_params,
                )
                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)  # type: ignore

                path_format_arguments = {
                    "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
                }
                request.method = "GET"
            return request

        async def extract_data(pipeline_response):
            deserialized = self._deserialize("Models", pipeline_response)
            list_of_elem = deserialized.model_list
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = await self._client._pipeline.run(  # pylint: disable=protected-access
                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)

            return pipeline_response


        return AsyncItemPaged(
            get_next, extract_data
        )
    list_custom_models.metadata = {'url': "/custom/models"}  # type: ignore

    @distributed_trace_async
    async def get_custom_models(
        self,
        **kwargs: Any
    ) -> _models.Models:
        """Get Custom Models.

        Get information about all custom models.

        :keyword op: Specify whether to return summary or full list of models. Default value is
         "summary". Note that overriding this default value may result in unsupported behavior.
        :paramtype op: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: Models, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2_0.models.Models
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        op = kwargs.pop('op', _params.pop('op', "summary"))  # type: str
        cls = kwargs.pop('cls', None)  # type: ClsType[_models.Models]

        
        request = build_get_custom_models_request(
            op=op,
            template_url=self.get_custom_models.metadata['url'],
            headers=_headers,
            params=_params,
        )
        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)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            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('Models', pipeline_response)

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

        return deserialized

    get_custom_models.metadata = {'url': "/custom/models"}  # type: ignore

