# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
import functools
from typing import TYPE_CHECKING
import warnings

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

from .. import models as _models
from .._vendor import _convert_request, _format_url_section

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]]

_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False
# fmt: off

def build_train_custom_model_async_request(
    **kwargs  # type: Any
):
    # type: (...) -> HttpRequest
    content_type = kwargs.pop('content_type', None)  # type: Optional[str]

    accept = "application/json"
    # Construct URL
    url = kwargs.pop("template_url", '/custom/models')

    # Construct headers
    header_parameters = kwargs.pop("headers", {})  # type: Dict[str, Any]
    if content_type is not None:
        header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
    header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="POST",
        url=url,
        headers=header_parameters,
        **kwargs
    )


def build_get_custom_model_request(
    model_id,  # type: str
    **kwargs  # type: Any
):
    # type: (...) -> HttpRequest
    include_keys = kwargs.pop('include_keys', False)  # type: Optional[bool]

    accept = "application/json"
    # Construct URL
    url = kwargs.pop("template_url", '/custom/models/{modelId}')
    path_format_arguments = {
        "modelId": _SERIALIZER.url("model_id", model_id, 'str'),
    }

    url = _format_url_section(url, **path_format_arguments)

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

    # Construct headers
    header_parameters = kwargs.pop("headers", {})  # type: Dict[str, Any]
    header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="GET",
        url=url,
        params=query_parameters,
        headers=header_parameters,
        **kwargs
    )


def build_delete_custom_model_request(
    model_id,  # type: str
    **kwargs  # type: Any
):
    # type: (...) -> HttpRequest
    accept = "application/json"
    # Construct URL
    url = kwargs.pop("template_url", '/custom/models/{modelId}')
    path_format_arguments = {
        "modelId": _SERIALIZER.url("model_id", model_id, 'str'),
    }

    url = _format_url_section(url, **path_format_arguments)

    # Construct headers
    header_parameters = kwargs.pop("headers", {})  # type: Dict[str, Any]
    header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="DELETE",
        url=url,
        headers=header_parameters,
        **kwargs
    )


def build_analyze_with_custom_model_request_initial(
    model_id,  # type: str
    **kwargs  # type: Any
):
    # type: (...) -> HttpRequest
    content_type = kwargs.pop('content_type', None)  # type: Optional[Union[str, "_models.ContentType"]]
    include_text_details = kwargs.pop('include_text_details', False)  # type: Optional[bool]

    accept = "application/json"
    # Construct URL
    url = kwargs.pop("template_url", '/custom/models/{modelId}/analyze')
    path_format_arguments = {
        "modelId": _SERIALIZER.url("model_id", model_id, 'str'),
    }

    url = _format_url_section(url, **path_format_arguments)

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

    # Construct headers
    header_parameters = kwargs.pop("headers", {})  # type: Dict[str, Any]
    if content_type is not None:
        header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
    header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="POST",
        url=url,
        params=query_parameters,
        headers=header_parameters,
        **kwargs
    )


def build_get_analyze_form_result_request(
    model_id,  # type: str
    result_id,  # type: str
    **kwargs  # type: Any
):
    # type: (...) -> HttpRequest
    accept = "application/json"
    # Construct URL
    url = kwargs.pop("template_url", '/custom/models/{modelId}/analyzeResults/{resultId}')
    path_format_arguments = {
        "modelId": _SERIALIZER.url("model_id", model_id, 'str'),
        "resultId": _SERIALIZER.url("result_id", result_id, 'str'),
    }

    url = _format_url_section(url, **path_format_arguments)

    # Construct headers
    header_parameters = kwargs.pop("headers", {})  # type: Dict[str, Any]
    header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="GET",
        url=url,
        headers=header_parameters,
        **kwargs
    )


def build_copy_custom_model_request_initial(
    model_id,  # type: str
    **kwargs  # type: Any
):
    # type: (...) -> HttpRequest
    content_type = kwargs.pop('content_type', None)  # type: Optional[str]

    accept = "application/json"
    # Construct URL
    url = kwargs.pop("template_url", '/custom/models/{modelId}/copy')
    path_format_arguments = {
        "modelId": _SERIALIZER.url("model_id", model_id, 'str'),
    }

    url = _format_url_section(url, **path_format_arguments)

    # Construct headers
    header_parameters = kwargs.pop("headers", {})  # type: Dict[str, Any]
    if content_type is not None:
        header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
    header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="POST",
        url=url,
        headers=header_parameters,
        **kwargs
    )


def build_get_custom_model_copy_result_request(
    model_id,  # type: str
    result_id,  # type: str
    **kwargs  # type: Any
):
    # type: (...) -> HttpRequest
    accept = "application/json"
    # Construct URL
    url = kwargs.pop("template_url", '/custom/models/{modelId}/copyResults/{resultId}')
    path_format_arguments = {
        "modelId": _SERIALIZER.url("model_id", model_id, 'str'),
        "resultId": _SERIALIZER.url("result_id", result_id, 'str'),
    }

    url = _format_url_section(url, **path_format_arguments)

    # Construct headers
    header_parameters = kwargs.pop("headers", {})  # type: Dict[str, Any]
    header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="GET",
        url=url,
        headers=header_parameters,
        **kwargs
    )


def build_generate_model_copy_authorization_request(
    **kwargs  # type: Any
):
    # type: (...) -> HttpRequest
    accept = "application/json"
    # Construct URL
    url = kwargs.pop("template_url", '/custom/models/copyAuthorization')

    # Construct headers
    header_parameters = kwargs.pop("headers", {})  # type: Dict[str, Any]
    header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="POST",
        url=url,
        headers=header_parameters,
        **kwargs
    )


def build_analyze_receipt_async_request_initial(
    **kwargs  # type: Any
):
    # type: (...) -> HttpRequest
    content_type = kwargs.pop('content_type', None)  # type: Optional[Union[str, "_models.ContentType"]]
    include_text_details = kwargs.pop('include_text_details', False)  # type: Optional[bool]

    accept = "application/json"
    # Construct URL
    url = kwargs.pop("template_url", '/prebuilt/receipt/analyze')

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

    # Construct headers
    header_parameters = kwargs.pop("headers", {})  # type: Dict[str, Any]
    if content_type is not None:
        header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
    header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="POST",
        url=url,
        params=query_parameters,
        headers=header_parameters,
        **kwargs
    )


def build_get_analyze_receipt_result_request(
    result_id,  # type: str
    **kwargs  # type: Any
):
    # type: (...) -> HttpRequest
    accept = "application/json"
    # Construct URL
    url = kwargs.pop("template_url", '/prebuilt/receipt/analyzeResults/{resultId}')
    path_format_arguments = {
        "resultId": _SERIALIZER.url("result_id", result_id, 'str'),
    }

    url = _format_url_section(url, **path_format_arguments)

    # Construct headers
    header_parameters = kwargs.pop("headers", {})  # type: Dict[str, Any]
    header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="GET",
        url=url,
        headers=header_parameters,
        **kwargs
    )


def build_analyze_layout_async_request_initial(
    **kwargs  # type: Any
):
    # type: (...) -> HttpRequest
    content_type = kwargs.pop('content_type', None)  # type: Optional[Union[str, "_models.ContentType"]]

    accept = "application/json"
    # Construct URL
    url = kwargs.pop("template_url", '/layout/analyze')

    # Construct headers
    header_parameters = kwargs.pop("headers", {})  # type: Dict[str, Any]
    if content_type is not None:
        header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
    header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="POST",
        url=url,
        headers=header_parameters,
        **kwargs
    )


def build_get_analyze_layout_result_request(
    result_id,  # type: str
    **kwargs  # type: Any
):
    # type: (...) -> HttpRequest
    accept = "application/json"
    # Construct URL
    url = kwargs.pop("template_url", '/layout/analyzeResults/{resultId}')
    path_format_arguments = {
        "resultId": _SERIALIZER.url("result_id", result_id, 'str'),
    }

    url = _format_url_section(url, **path_format_arguments)

    # Construct headers
    header_parameters = kwargs.pop("headers", {})  # type: Dict[str, Any]
    header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="GET",
        url=url,
        headers=header_parameters,
        **kwargs
    )


def build_list_custom_models_request(
    **kwargs  # type: Any
):
    # type: (...) -> HttpRequest
    op = kwargs.pop('op', "full")  # type: str

    accept = "application/json"
    # Construct URL
    url = kwargs.pop("template_url", '/custom/models')

    # Construct parameters
    query_parameters = kwargs.pop("params", {})  # type: Dict[str, Any]
    query_parameters['op'] = _SERIALIZER.query("op", op, 'str')

    # Construct headers
    header_parameters = kwargs.pop("headers", {})  # type: Dict[str, Any]
    header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="GET",
        url=url,
        params=query_parameters,
        headers=header_parameters,
        **kwargs
    )


def build_get_custom_models_request(
    **kwargs  # type: Any
):
    # type: (...) -> HttpRequest
    op = kwargs.pop('op', "summary")  # type: str

    accept = "application/json"
    # Construct URL
    url = kwargs.pop("template_url", '/custom/models')

    # Construct parameters
    query_parameters = kwargs.pop("params", {})  # type: Dict[str, Any]
    query_parameters['op'] = _SERIALIZER.query("op", op, 'str')

    # Construct headers
    header_parameters = kwargs.pop("headers", {})  # type: Dict[str, Any]
    header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="GET",
        url=url,
        params=query_parameters,
        headers=header_parameters,
        **kwargs
    )

# fmt: on
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.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
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

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

        _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'],
        )
        request = _convert_request(request)
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

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

        
        request = build_get_custom_model_request(
            model_id=model_id,
            include_keys=include_keys,
            template_url=self.get_custom_model.metadata['url'],
        )
        request = _convert_request(request)
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

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

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

        deserialized = self._deserialize('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 = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

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

        pipeline_response = 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.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


    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 = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

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

        _json = None
        _content = None
        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'],
        )
        request = _convert_request(request)
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

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

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

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


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

    _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[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.
        :type include_text_details: bool
        :param file_stream: .json, .pdf, .jpg, .png or .tiff type file stream.
        :type file_stream: IO or ~azure.ai.formrecognizer.v2_0.models.SourcePath
        :keyword str content_type: Media type of the body sent to the API. Default value is
         "application/json". Allowed values are: "application/pdf", "image/jpeg", "image/png",
         "image/tiff", "application/json."
        :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 LROBasePolling. Pass in False for
         this operation to not poll, or pass in your own initialized polling object for a personal
         polling strategy.
        :paramtype polling: bool or ~azure.core.polling.PollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no
         Retry-After header is present.
        :return: An instance of LROPoller that returns either None or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[None]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        content_type = kwargs.pop('content_type', "application/json")  # type: Optional[Union[str, "_models.ContentType"]]
        polling = kwargs.pop('polling', True)  # type: Union[bool, azure.core.polling.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,
                content_type=content_type,
                cls=lambda x,y,z: x,
                **kwargs
            )
        kwargs.pop('error_map', None)

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


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

        if polling is True: polling_method = LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **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.v2_0.models.AnalyzeOperationResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.AnalyzeOperationResult"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        
        request = build_get_analyze_form_result_request(
            model_id=model_id,
            result_id=result_id,
            template_url=self.get_analyze_form_result.metadata['url'],
        )
        request = _convert_request(request)
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

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

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

        deserialized = self._deserialize('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 = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

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

        _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'],
        )
        request = _convert_request(request)
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

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

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

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


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

    _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[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 LROBasePolling. Pass in False for
         this operation to not poll, or pass in your own initialized polling object for a personal
         polling strategy.
        :paramtype polling: bool or ~azure.core.polling.PollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no
         Retry-After header is present.
        :return: An instance of LROPoller that returns either None or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[None]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        content_type = kwargs.pop('content_type', "application/json")  # type: Optional[str]
        polling = kwargs.pop('polling', True)  # type: Union[bool, azure.core.polling.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,
                content_type=content_type,
                cls=lambda x,y,z: x,
                **kwargs
            )
        kwargs.pop('error_map', None)

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


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

        if polling is True: polling_method = LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **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.v2_0.models.CopyOperationResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.CopyOperationResult"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        
        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'],
        )
        request = _convert_request(request)
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

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

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

        deserialized = self._deserialize('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.v2_0.models.CopyAuthorizationResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.CopyAuthorizationResult"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

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

        pipeline_response = 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.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


    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 = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

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

        _json = None
        _content = None
        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'],
        )
        request = _convert_request(request)
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

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

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

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


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

    _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[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.
        :type include_text_details: bool
        :param file_stream: .json, .pdf, .jpg, .png or .tiff type file stream.
        :type file_stream: IO or ~azure.ai.formrecognizer.v2_0.models.SourcePath
        :keyword str content_type: Media type of the body sent to the API. Default value is
         "application/json". Allowed values are: "application/pdf", "image/jpeg", "image/png",
         "image/tiff", "application/json."
        :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 LROBasePolling. Pass in False for
         this operation to not poll, or pass in your own initialized polling object for a personal
         polling strategy.
        :paramtype polling: bool or ~azure.core.polling.PollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no
         Retry-After header is present.
        :return: An instance of LROPoller that returns either None or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[None]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        content_type = kwargs.pop('content_type', "application/json")  # type: Optional[Union[str, "_models.ContentType"]]
        polling = kwargs.pop('polling', True)  # type: Union[bool, azure.core.polling.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,
                content_type=content_type,
                cls=lambda x,y,z: x,
                **kwargs
            )
        kwargs.pop('error_map', None)

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


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

        if polling is True: polling_method = LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **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.v2_0.models.AnalyzeOperationResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.AnalyzeOperationResult"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

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

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

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

        deserialized = self._deserialize('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 = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

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

        _json = None
        _content = None
        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'],
        )
        request = _convert_request(request)
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)

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

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

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


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

    _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[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.
        :type file_stream: IO or ~azure.ai.formrecognizer.v2_0.models.SourcePath
        :keyword str content_type: Media type of the body sent to the API. Default value is
         "application/json". Allowed values are: "application/pdf", "image/jpeg", "image/png",
         "image/tiff", "application/json."
        :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 LROBasePolling. Pass in False for
         this operation to not poll, or pass in your own initialized polling object for a personal
         polling strategy.
        :paramtype polling: bool or ~azure.core.polling.PollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no
         Retry-After header is present.
        :return: An instance of LROPoller that returns either None or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[None]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        content_type = kwargs.pop('content_type', "application/json")  # type: Optional[Union[str, "_models.ContentType"]]
        polling = kwargs.pop('polling', True)  # type: Union[bool, azure.core.polling.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,
                content_type=content_type,
                cls=lambda x,y,z: x,
                **kwargs
            )
        kwargs.pop('error_map', None)

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


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

        if polling is True: polling_method = LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **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.v2_0.models.AnalyzeOperationResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.AnalyzeOperationResult"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

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

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

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

        deserialized = self._deserialize('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 op: Specify whether to return summary or full list of models. The 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.paging.ItemPaged[~azure.ai.formrecognizer.v2_0.models.Models]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        op = kwargs.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', {}))
        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'],
                )
                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)

            else:
                
                request = build_list_custom_models_request(
                    op=op,
                    template_url=next_link,
                )
                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)

                path_format_arguments = {
                    "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
                }
                request.method = "GET"
            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]:
                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 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 op: Specify whether to return summary or full list of models. The 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
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.Models"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        op = kwargs.pop('op', "summary")  # type: str

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

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

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

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

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

        return deserialized

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

