# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.0.6282, generator: {generator})
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
import warnings

from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.polling.base_polling import LROBasePolling
from azure.core.tracing.decorator import distributed_trace

from .. import models

if TYPE_CHECKING:
    # pylint: disable=unused-import,ungrouped-imports
    from typing import Any, Callable, Dict, Generic, IO, Iterable, Optional, TypeVar, Union

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

class FormRecognizerClientOperationsMixin(object):

    @distributed_trace
    def train_custom_model_async(
        self,
        train_request,  # type: "models.TrainRequest"
        **kwargs  # type: Any
    ):
        # type: (...) -> 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.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
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {404: ResourceNotFoundError, 409: ResourceExistsError}
        error_map.update(kwargs.pop('error_map', {}))
        content_type = kwargs.pop("content_type", "application/json")

        # Construct URL
        url = self.train_custom_model_async.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')

        # Construct and send request
        body_content_kwargs = {}  # type: Dict[str, Any]
        body_content = self._serialize.body(train_request, 'TrainRequest')
        body_content_kwargs['content'] = body_content
        request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)

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

        if response.status_code not in [201]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize(models.ErrorResponse, 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
    def get_custom_model(
        self,
        model_id,  # type: str
        include_keys=False,  # type: Optional[bool]
        **kwargs  # type: Any
    ):
        # type: (...) -> "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.
        :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.models.Model
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.Model"]
        error_map = {404: ResourceNotFoundError, 409: ResourceExistsError}
        error_map.update(kwargs.pop('error_map', {}))

        # Construct URL
        url = self.get_custom_model.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
            'modelId': self._serialize.url("model_id", model_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        if include_keys is not None:
            query_parameters['includeKeys'] = self._serialize.query("include_keys", include_keys, 'bool')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Accept'] = 'application/json'

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize(models.ErrorResponse, 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
    def delete_custom_model(
        self,
        model_id,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> 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
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {404: ResourceNotFoundError, 409: ResourceExistsError}
        error_map.update(kwargs.pop('error_map', {}))

        # Construct URL
        url = self.delete_custom_model.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
            'modelId': self._serialize.url("model_id", model_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]

        # Construct and send request
        request = self._client.delete(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(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(models.ErrorResponse, response)
            raise HttpResponseError(response=response, model=error)

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

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

    def _analyze_with_custom_model_initial(
        self,
        model_id,  # type: str
        include_text_details=False,  # type: Optional[bool]
        file_stream=None,  # type: Optional[Union[IO, "models.SourcePath"]]
        **kwargs  # type: Any
    ):
        # type: (...) -> None
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {404: ResourceNotFoundError, 409: ResourceExistsError}
        error_map.update(kwargs.pop('error_map', {}))
        content_type = kwargs.pop("content_type", "application/json")

        # Construct URL
        url = self._analyze_with_custom_model_initial.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
            'modelId': self._serialize.url("model_id", model_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        if include_text_details is not None:
            query_parameters['includeTextDetails'] = self._serialize.query("include_text_details", include_text_details, 'bool')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')

        # Construct and send request
        body_content_kwargs = {}  # type: Dict[str, Any]
        if header_parameters['Content-Type'].split(";")[0] in ['application/pdf', 'image/jpeg', 'image/png', 'image/tiff']:
            body_content_kwargs['stream_content'] = file_stream
        elif header_parameters['Content-Type'].split(";")[0] in ['application/json']:
            if file_stream is not None:
                body_content = self._serialize.body(file_stream, 'SourcePath')
            else:
                body_content = None
            body_content_kwargs['content'] = body_content
        else:
            raise ValueError(
                "The content_type '{}' is not one of the allowed values: "
                "['application/pdf', 'image/jpeg', 'image/png', 'image/tiff', 'application/json']".format(header_parameters['Content-Type'])
            )
        request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)

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

        if response.status_code not in [202]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize(models.ErrorResponse, response)
            raise HttpResponseError(response=response, model=error)

        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
    def begin_analyze_with_custom_model(
        self,
        model_id,  # type: str
        include_text_details=False,  # type: Optional[bool]
        file_stream=None,  # type: Optional[Union[IO, "models.SourcePath"]]
        **kwargs  # type: Any
    ):
        # type: (...) -> LROPoller
        """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.
        :type include_text_details: bool
        :param file_stream: .json, .pdf, .jpg, .png or .tiff type file stream.
        :type file_stream: ~azure.ai.formrecognizer.models.SourcePath
        :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: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :paramtype polling: bool or ~azure.core.polling.PollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
        :return: An instance of LROPoller that returns either None or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        polling = kwargs.pop('polling', False)  # type: Union[bool, PollingMethod]
        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 = self._analyze_with_custom_model_initial(
                model_id=model_id,
                include_text_details=include_text_details,
                file_stream=file_stream,
                cls=lambda x,y,z: x,
                **kwargs
            )

        kwargs.pop('error_map', None)
        kwargs.pop('content_type', None)

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

        if polling is True: polling_method = LROBasePolling(lro_delay,  **kwargs)
        elif polling is False: polling_method = NoPolling()
        else: polling_method = polling
        if cont_token:
            return LROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        else:
            return LROPoller(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
    def get_analyze_form_result(
        self,
        model_id,  # type: str
        result_id,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> "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.models.AnalyzeOperationResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.AnalyzeOperationResult"]
        error_map = {404: ResourceNotFoundError, 409: ResourceExistsError}
        error_map.update(kwargs.pop('error_map', {}))

        # Construct URL
        url = self.get_analyze_form_result.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
            'modelId': self._serialize.url("model_id", model_id, 'str'),
            'resultId': self._serialize.url("result_id", result_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Accept'] = 'application/json'

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize(models.ErrorResponse, 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

    def _copy_custom_model_initial(
        self,
        model_id,  # type: str
        copy_request,  # type: "models.CopyRequest"
        **kwargs  # type: Any
    ):
        # type: (...) -> None
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {404: ResourceNotFoundError, 409: ResourceExistsError}
        error_map.update(kwargs.pop('error_map', {}))
        content_type = kwargs.pop("content_type", "application/json")

        # Construct URL
        url = self._copy_custom_model_initial.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
            'modelId': self._serialize.url("model_id", model_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')

        # Construct and send request
        body_content_kwargs = {}  # type: Dict[str, Any]
        body_content = self._serialize.body(copy_request, 'CopyRequest')
        body_content_kwargs['content'] = body_content
        request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)

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

        if response.status_code not in [202]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize(models.ErrorResponse, response)
            raise HttpResponseError(response=response, model=error)

        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
    def begin_copy_custom_model(
        self,
        model_id,  # type: str
        copy_request,  # type: "models.CopyRequest"
        **kwargs  # type: Any
    ):
        # type: (...) -> LROPoller
        """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.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: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :paramtype polling: bool or ~azure.core.polling.PollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
        :return: An instance of LROPoller that returns either None or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        polling = kwargs.pop('polling', False)  # type: Union[bool, PollingMethod]
        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 = self._copy_custom_model_initial(
                model_id=model_id,
                copy_request=copy_request,
                cls=lambda x,y,z: x,
                **kwargs
            )

        kwargs.pop('error_map', None)
        kwargs.pop('content_type', None)

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

        if polling is True: polling_method = LROBasePolling(lro_delay,  **kwargs)
        elif polling is False: polling_method = NoPolling()
        else: polling_method = polling
        if cont_token:
            return LROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        else:
            return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
    begin_copy_custom_model.metadata = {'url': '/custom/models/{modelId}/copy'}  # type: ignore

    @distributed_trace
    def get_custom_model_copy_result(
        self,
        model_id,  # type: str
        result_id,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> "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.models.CopyOperationResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.CopyOperationResult"]
        error_map = {404: ResourceNotFoundError, 409: ResourceExistsError}
        error_map.update(kwargs.pop('error_map', {}))

        # Construct URL
        url = self.get_custom_model_copy_result.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
            'modelId': self._serialize.url("model_id", model_id, 'str'),
            'resultId': self._serialize.url("result_id", result_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Accept'] = 'application/json'

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize(models.ErrorResponse, 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
    def generate_model_copy_authorization(
        self,
        **kwargs  # type: Any
    ):
        # type: (...) -> "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.models.CopyAuthorizationResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.CopyAuthorizationResult"]
        error_map = {404: ResourceNotFoundError, 409: ResourceExistsError}
        error_map.update(kwargs.pop('error_map', {}))

        # Construct URL
        url = self.generate_model_copy_authorization.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Accept'] = 'application/json'

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(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(models.ErrorResponse, 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

    def _analyze_receipt_async_initial(
        self,
        include_text_details=False,  # type: Optional[bool]
        file_stream=None,  # type: Optional[Union[IO, "models.SourcePath"]]
        **kwargs  # type: Any
    ):
        # type: (...) -> None
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {404: ResourceNotFoundError, 409: ResourceExistsError}
        error_map.update(kwargs.pop('error_map', {}))
        content_type = kwargs.pop("content_type", "application/json")

        # Construct URL
        url = self._analyze_receipt_async_initial.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        if include_text_details is not None:
            query_parameters['includeTextDetails'] = self._serialize.query("include_text_details", include_text_details, 'bool')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')

        # Construct and send request
        body_content_kwargs = {}  # type: Dict[str, Any]
        if header_parameters['Content-Type'].split(";")[0] in ['application/pdf', 'image/jpeg', 'image/png', 'image/tiff']:
            body_content_kwargs['stream_content'] = file_stream
        elif header_parameters['Content-Type'].split(";")[0] in ['application/json']:
            if file_stream is not None:
                body_content = self._serialize.body(file_stream, 'SourcePath')
            else:
                body_content = None
            body_content_kwargs['content'] = body_content
        else:
            raise ValueError(
                "The content_type '{}' is not one of the allowed values: "
                "['application/pdf', 'image/jpeg', 'image/png', 'image/tiff', 'application/json']".format(header_parameters['Content-Type'])
            )
        request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)

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

        if response.status_code not in [202]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize(models.ErrorResponse, response)
            raise HttpResponseError(response=response, model=error)

        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
    def begin_analyze_receipt_async(
        self,
        include_text_details=False,  # type: Optional[bool]
        file_stream=None,  # type: Optional[Union[IO, "models.SourcePath"]]
        **kwargs  # type: Any
    ):
        # type: (...) -> LROPoller
        """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.
        :type include_text_details: bool
        :param file_stream: .json, .pdf, .jpg, .png or .tiff type file stream.
        :type file_stream: ~azure.ai.formrecognizer.models.SourcePath
        :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: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :paramtype polling: bool or ~azure.core.polling.PollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
        :return: An instance of LROPoller that returns either None or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        polling = kwargs.pop('polling', False)  # type: Union[bool, PollingMethod]
        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 = self._analyze_receipt_async_initial(
                include_text_details=include_text_details,
                file_stream=file_stream,
                cls=lambda x,y,z: x,
                **kwargs
            )

        kwargs.pop('error_map', None)
        kwargs.pop('content_type', None)

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

        if polling is True: polling_method = LROBasePolling(lro_delay,  **kwargs)
        elif polling is False: polling_method = NoPolling()
        else: polling_method = polling
        if cont_token:
            return LROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        else:
            return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
    begin_analyze_receipt_async.metadata = {'url': '/prebuilt/receipt/analyze'}  # type: ignore

    @distributed_trace
    def get_analyze_receipt_result(
        self,
        result_id,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> "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.models.AnalyzeOperationResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.AnalyzeOperationResult"]
        error_map = {404: ResourceNotFoundError, 409: ResourceExistsError}
        error_map.update(kwargs.pop('error_map', {}))

        # Construct URL
        url = self.get_analyze_receipt_result.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
            'resultId': self._serialize.url("result_id", result_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Accept'] = 'application/json'

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize(models.ErrorResponse, 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

    def _analyze_layout_async_initial(
        self,
        file_stream=None,  # type: Optional[Union[IO, "models.SourcePath"]]
        **kwargs  # type: Any
    ):
        # type: (...) -> None
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {404: ResourceNotFoundError, 409: ResourceExistsError}
        error_map.update(kwargs.pop('error_map', {}))
        content_type = kwargs.pop("content_type", "application/json")

        # Construct URL
        url = self._analyze_layout_async_initial.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')

        # Construct and send request
        body_content_kwargs = {}  # type: Dict[str, Any]
        if header_parameters['Content-Type'].split(";")[0] in ['application/pdf', 'image/jpeg', 'image/png', 'image/tiff']:
            body_content_kwargs['stream_content'] = file_stream
        elif header_parameters['Content-Type'].split(";")[0] in ['application/json']:
            if file_stream is not None:
                body_content = self._serialize.body(file_stream, 'SourcePath')
            else:
                body_content = None
            body_content_kwargs['content'] = body_content
        else:
            raise ValueError(
                "The content_type '{}' is not one of the allowed values: "
                "['application/pdf', 'image/jpeg', 'image/png', 'image/tiff', 'application/json']".format(header_parameters['Content-Type'])
            )
        request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)

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

        if response.status_code not in [202]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize(models.ErrorResponse, response)
            raise HttpResponseError(response=response, model=error)

        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
    def begin_analyze_layout_async(
        self,
        file_stream=None,  # type: Optional[Union[IO, "models.SourcePath"]]
        **kwargs  # type: Any
    ):
        # type: (...) -> LROPoller
        """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.
        :type file_stream: ~azure.ai.formrecognizer.models.SourcePath
        :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: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :paramtype polling: bool or ~azure.core.polling.PollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
        :return: An instance of LROPoller that returns either None or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        polling = kwargs.pop('polling', False)  # type: Union[bool, PollingMethod]
        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 = self._analyze_layout_async_initial(
                file_stream=file_stream,
                cls=lambda x,y,z: x,
                **kwargs
            )

        kwargs.pop('error_map', None)
        kwargs.pop('content_type', None)

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

        if polling is True: polling_method = LROBasePolling(lro_delay,  **kwargs)
        elif polling is False: polling_method = NoPolling()
        else: polling_method = polling
        if cont_token:
            return LROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        else:
            return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
    begin_analyze_layout_async.metadata = {'url': '/layout/analyze'}  # type: ignore

    @distributed_trace
    def get_analyze_layout_result(
        self,
        result_id,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> "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.models.AnalyzeOperationResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.AnalyzeOperationResult"]
        error_map = {404: ResourceNotFoundError, 409: ResourceExistsError}
        error_map.update(kwargs.pop('error_map', {}))

        # Construct URL
        url = self.get_analyze_layout_result.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
            'resultId': self._serialize.url("result_id", result_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Accept'] = 'application/json'

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize(models.ErrorResponse, 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  # type: Any
    ):
        # type: (...) -> Iterable["models.Models"]
        """List Custom Models.

        Get information about all custom models.

        :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.paging.ItemPaged[~azure.ai.formrecognizer.models.Models]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.Models"]
        error_map = {404: ResourceNotFoundError, 409: ResourceExistsError}
        error_map.update(kwargs.pop('error_map', {}))
        op = "full"

        def prepare_request(next_link=None):
            if not next_link:
                # Construct URL
                url = self.list_custom_models.metadata['url']  # type: ignore
                path_format_arguments = {
                    'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
                }
                url = self._client.format_url(url, **path_format_arguments)
                # Construct parameters
                query_parameters = {}  # type: Dict[str, Any]
                query_parameters['op'] = self._serialize.query("op", op, 'str')

            else:
                url = next_link
                query_parameters = {}  # type: Dict[str, Any]
                path_format_arguments = {
                    'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
                }
                url = self._client.format_url(url, **path_format_arguments)
            # Construct headers
            header_parameters = {}  # type: Dict[str, Any]
            header_parameters['Accept'] = 'application/json'

            # Construct and send request
            request = self._client.get(url, query_parameters, header_parameters)
            return request

        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, iter(list_of_elem)

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

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

            if response.status_code not in [200]:
                error = self._deserialize(models.ErrorResponse, response)
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                raise HttpResponseError(response=response, model=error)

            return pipeline_response

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

    @distributed_trace
    def get_custom_models(
        self,
        **kwargs  # type: Any
    ):
        # type: (...) -> "models.Models"
        """Get Custom Models.

        Get information about all custom models.

        :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.models.Models
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.Models"]
        error_map = {404: ResourceNotFoundError, 409: ResourceExistsError}
        error_map.update(kwargs.pop('error_map', {}))
        op = "summary"

        # Construct URL
        url = self.get_custom_models.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['op'] = self._serialize.query("op", op, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Accept'] = 'application/json'

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize(models.ErrorResponse, 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
