async def test_long_running_negative():
    global LOCATION_BODY
    global POLLING_STATUS

    # Test LRO PUT throws for invalid json
    LOCATION_BODY = '{'
    response = TestBasePolling.mock_send('POST', 202,
                                         {'location': LOCATION_URL})
    poll = async_poller(CLIENT, response, TestBasePolling.mock_outputs,
                        AsyncLROBasePolling(0))
    with pytest.raises(DecodeError):
        await poll

    LOCATION_BODY = '{\'"}'
    response = TestBasePolling.mock_send('POST', 202,
                                         {'location': LOCATION_URL})
    poll = async_poller(CLIENT, response, TestBasePolling.mock_outputs,
                        AsyncLROBasePolling(0))
    with pytest.raises(DecodeError):
        await poll

    LOCATION_BODY = '{'
    POLLING_STATUS = 203
    response = TestBasePolling.mock_send('POST', 202,
                                         {'location': LOCATION_URL})
    poll = async_poller(CLIENT, response, TestBasePolling.mock_outputs,
                        AsyncLROBasePolling(0))
    with pytest.raises(
            HttpResponseError):  # TODO: Node.js raises on deserialization
        await poll

    LOCATION_BODY = json.dumps({'name': TEST_NAME})
    POLLING_STATUS = 200
async def test_post(async_pipeline_client_builder, deserialization_cb):

    # Test POST LRO with both Location and Operation-Location

    # The initial response contains both Location and Operation-Location, a 202 and no Body
    initial_response = TestBasePolling.mock_send(
        'POST', 202, {
            'location': 'http://example.org/location',
            'operation-location': 'http://example.org/async_monitor',
        }, '')

    async def send(request, **kwargs):
        assert request.method == 'GET'

        if request.url == 'http://example.org/location':
            return TestBasePolling.mock_send('GET',
                                             200,
                                             body={
                                                 'location_result': True
                                             }).http_response
        elif request.url == 'http://example.org/async_monitor':
            return TestBasePolling.mock_send('GET',
                                             200,
                                             body={
                                                 'status': 'Succeeded'
                                             }).http_response
        else:
            pytest.fail("No other query allowed")

    client = async_pipeline_client_builder(send)

    # LRO options with Location final state
    poll = async_poller(client, initial_response, deserialization_cb,
                        AsyncLROBasePolling(0))
    result = await poll
    assert result['location_result'] == True

    # Location has no body
    async def send(request, **kwargs):
        assert request.method == 'GET'

        if request.url == 'http://example.org/location':
            return TestBasePolling.mock_send('GET', 200,
                                             body=None).http_response
        elif request.url == 'http://example.org/async_monitor':
            return TestBasePolling.mock_send('GET',
                                             200,
                                             body={
                                                 'status': 'Succeeded'
                                             }).http_response
        else:
            pytest.fail("No other query allowed")

    client = async_pipeline_client_builder(send)

    poll = async_poller(client, initial_response, deserialization_cb,
                        AsyncLROBasePolling(0))
    result = await poll
    assert result is None
Example #3
0
async def test_long_running_post():

    # Test polling from operation-location header
    response = TestBasePolling.mock_send(
        'POST', 201,
        {'operation-location': ASYNC_URL},
        body={'properties':{'provisioningState': 'Succeeded'}})
    polling_method = AsyncLROBasePolling(0)
    poll = await async_poller(CLIENT, response,
        TestBasePolling.mock_deserialization_no_body,
        polling_method)
    assert polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollAsyncOpHeader is None

    # Test polling from operation-location header
    response = TestBasePolling.mock_send(
        'POST', 202,
        {'operation-location': ASYNC_URL},
        body={'properties':{'provisioningState': 'Succeeded'}})
    polling_method = AsyncLROBasePolling(0)
    poll = await async_poller(CLIENT, response,
        TestBasePolling.mock_deserialization_no_body,
        polling_method)
    assert polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollAsyncOpHeader is None

    # Test polling from location header
    response = TestBasePolling.mock_send(
        'POST', 202,
        {'location': LOCATION_URL},
        body={'properties':{'provisioningState': 'Succeeded'}})
    polling_method = AsyncLROBasePolling(0)
    poll = await async_poller(CLIENT, response,
        TestBasePolling.mock_outputs,
        polling_method)
    assert poll.name == TEST_NAME
    assert polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollLocationHeader is None

    # Test fail to poll from operation-location header
    response = TestBasePolling.mock_send(
        'POST', 202,
        {'operation-location': ERROR})
    with pytest.raises(BadEndpointError):
        await async_poller(CLIENT, response,
            TestBasePolling.mock_outputs,
            AsyncLROBasePolling(0))

    # Test fail to poll from location header
    response = TestBasePolling.mock_send(
        'POST', 202,
        {'location': ERROR})
    with pytest.raises(BadEndpointError):
        await async_poller(CLIENT, response,
            TestBasePolling.mock_outputs,
            AsyncLROBasePolling(0))
async def test_long_running_negative(http_request, http_response):
    global LOCATION_BODY
    global POLLING_STATUS
    CLIENT.http_request_type = http_request
    CLIENT.http_response_type = http_response
    # Test LRO PUT throws for invalid json
    LOCATION_BODY = '{'
    response = TestBasePolling.mock_send(
        http_request,
        http_response,
        'POST', 202,
        {'location': LOCATION_URL})
    poll = async_poller(
        CLIENT,
        response,
        TestBasePolling.mock_outputs,
        AsyncLROBasePolling(0)
    )
    with pytest.raises(DecodeError):
        await poll

    LOCATION_BODY = '{\'"}'
    response = TestBasePolling.mock_send(
        http_request,
        http_response,
        'POST', 202,
        {'location': LOCATION_URL})
    poll = async_poller(CLIENT, response,
        TestBasePolling.mock_outputs,
        AsyncLROBasePolling(0))
    with pytest.raises(DecodeError):
        await poll

    LOCATION_BODY = '{'
    POLLING_STATUS = 203
    response = TestBasePolling.mock_send(
        http_request,
        http_response,
        'POST', 202,
        {'location': LOCATION_URL})
    poll = async_poller(CLIENT, response,
        TestBasePolling.mock_outputs,
        AsyncLROBasePolling(0))
    with pytest.raises(HttpResponseError) as error: # TODO: Node.js raises on deserialization
        await poll
    assert error.value.continuation_token == base64.b64encode(pickle.dumps(response)).decode('ascii')

    LOCATION_BODY = json.dumps({ 'name': TEST_NAME })
    POLLING_STATUS = 200
Example #5
0
    async def train_model(self,
                          training_files_url: str,
                          use_training_labels: Optional[bool] = False,
                          **kwargs: Any) -> CustomFormModel:
        """Create and train a custom model. The request must include a `training_files_url` parameter that is an
        externally accessible Azure storage blob container Uri (preferably a Shared Access Signature Uri).
        Models are trained using documents that are of the following content type - 'application/pdf',
        'image/jpeg', 'image/png', 'image/tiff'. Other type of content in the container is ignored.

        :param str training_files_url: An Azure Storage blob container's SAS URI.
        :param bool use_training_labels: Whether to train with labels or not. Corresponding labeled files must
            exist in the blob container.
        :keyword str prefix: A case-sensitive prefix string to filter documents for training.
            Use `prefix` to filter documents themselves, or to restrict sub folders for training
            when `include_sub_folders` is set to True. Not supported if training with labels.
        :keyword bool include_sub_folders: A flag to indicate if sub folders
            will also need to be included when searching for content to be preprocessed.
            Use with `prefix` to filter for only certain sub folders. Not supported if training with labels.
        :keyword int polling_interval: Waiting time between two polls for LRO operations
            if no Retry-After header is present. Defaults to 5 seconds.
        :return: CustomFormModel
        :rtype: ~azure.ai.formrecognizer.CustomFormModel
        :raises ~azure.core.exceptions.HttpResponseError:
            Note that if the training fails, the exception is raised, but a model with an
            "invalid" status is still created. You can delete this model by calling :func:`~delete_model()`

        .. admonition:: Example:

            .. literalinclude:: ../samples/async_samples/sample_train_model_without_labels_async.py
                :start-after: [START training_async]
                :end-before: [END training_async]
                :language: python
                :dedent: 8
                :caption: Training a model with your custom forms.
        """

        cls = kwargs.pop("cls", None)
        polling_interval = kwargs.pop("polling_interval", POLLING_INTERVAL)
        response = await self._client.train_custom_model_async(
            train_request=TrainRequest(source=training_files_url,
                                       use_label_file=use_training_labels,
                                       source_filter=TrainSourceFilter(
                                           prefix=kwargs.pop("prefix", ""),
                                           include_sub_folders=kwargs.pop(
                                               "include_sub_folders", False))),
            cls=lambda pipeline_response, _, response_headers:
            pipeline_response,
            error_map=error_map,
            **kwargs)

        def callback(raw_response):
            model = self._client._deserialize(Model, raw_response)
            return CustomFormModel._from_generated(model)

        deserialization_callback = cls if cls else callback
        return await async_poller(
            self._client._client, response, deserialization_callback,
            AsyncLROBasePolling(timeout=polling_interval,
                                lro_algorithms=[TrainingPolling()],
                                **kwargs))
Example #6
0
    async def wait_until_done(self, job_id, **kwargs):
        # type: (str, **Any) -> JobStatusResult
        """

        :param job_id: guid id for job
        :type job_id: str
        :return: JobStatusResult
        :rtype: JobStatusResult
        """
        pipeline_response = await self._client.document_translation.get_operation_status(
            job_id,
            cls=lambda pipeline_response, _, response_headers: pipeline_response
        )

        def callback(raw_response):
            detail = self._client._deserialize(_BatchStatusDetail, raw_response)  # pylint: disable=protected-access
            return JobStatusResult._from_generated(detail)  # pylint: disable=protected-access

        poller = AsyncLROPoller(
            client=self._client._client,  # pylint: disable=protected-access
            initial_response=pipeline_response,
            deserialization_callback=callback,
            polling_method=AsyncLROBasePolling(
                timeout=30,
                lro_algorithms=[TranslationPolling()],
                **kwargs
            ),
        )
        return await poller.result()
Example #7
0
    async def begin_extract_receipts(
            self, stream: IO[bytes],
            **kwargs: Any) -> List["ExtractedReceipt"]:
        """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'.

        :param stream: .pdf, .jpg, .png or .tiff type file stream.
        :type stream: stream
        :keyword bool include_text_details: Include text lines and element references in the result.
        :keyword str content_type: Media type of the body sent to the API.
        :return: LROPoller
        :rtype: ~azure.core.polling.LROPoller
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        if isinstance(stream, six.string_types):
            raise TypeError(
                "Call begin_extract_receipts_from_url() to analyze a receipt from a url."
            )

        include_text_details = kwargs.pop("include_text_details", False)
        content_type = kwargs.pop("content_type", None)
        if content_type is None:
            content_type = get_content_type(stream)

        return await self._client.analyze_receipt_async(
            file_stream=stream,
            content_type=content_type,
            include_text_details=include_text_details,
            cls=kwargs.pop("cls", self._receipt_callback),
            polling=AsyncLROBasePolling(timeout=POLLING_INTERVAL, **kwargs),
            **kwargs)
Example #8
0
    async def begin_extract_receipts_from_url(
            self, url: str, **kwargs: Any) -> List["ExtractedReceipt"]:
        """Extract field text and semantic values from a given receipt document.
        The input document must be the location (Url) of the document to be analyzed.

        :param url: The url of the receipt.
        :type url: str
        :keyword bool include_text_details: Include text lines and element references in the result.
        :return: LROPoller
        :rtype: ~azure.core.polling.LROPoller
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        if not isinstance(url, six.string_types):
            raise TypeError(
                "Call begin_extract_receipts() to analyze a receipt from a stream."
            )

        include_text_details = kwargs.pop("include_text_details", False)

        return await self._client.analyze_receipt_async(
            file_stream={"source": url},
            include_text_details=include_text_details,
            cls=kwargs.pop("cls", self._receipt_callback),
            polling=AsyncLROBasePolling(timeout=POLLING_INTERVAL, **kwargs),
            **kwargs)
Example #9
0
    async def begin_extract_layouts(
            self, stream: IO[bytes],
            **kwargs: Any) -> List["ExtractedLayoutPage"]:
        """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'.

        :param stream: .pdf, .jpg, .png or .tiff type file stream.
        :type stream: stream
        :keyword str content_type: Media type of the body sent to the API.
        :return: LROPoller
        :rtype: ~azure.core.polling.LROPoller
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        if isinstance(stream, six.string_types):
            raise TypeError(
                "Call begin_extract_layouts_from_url() to analyze a document from a url."
            )

        content_type = kwargs.pop("content_type", None)
        if content_type is None:
            content_type = get_content_type(stream)

        return await self._client.analyze_layout_async(
            file_stream=stream,
            content_type=content_type,
            cls=kwargs.pop("cls", self._layout_callback),
            polling=AsyncLROBasePolling(timeout=POLLING_INTERVAL, **kwargs),
            **kwargs)
Example #10
0
    async def begin_unsubscribe_trigger_from_events(
        self,
        trigger_name: str,
        **kwargs
    ) -> AsyncLROPoller["_models.TriggerSubscriptionOperationStatus"]:
        """Unsubscribe event trigger from events.

        :param trigger_name: The trigger name.
        :type trigger_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
        :return: An instance of AsyncLROPoller that returns either TriggerSubscriptionOperationStatus or the result of cls(response)
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.synapse.artifacts.models.TriggerSubscriptionOperationStatus]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        polling = kwargs.pop('polling', False)  # type: Union[bool, AsyncPollingMethod]
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.TriggerSubscriptionOperationStatus"]
        lro_delay = kwargs.pop(
            'polling_interval',
            self._config.polling_interval
        )
        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
        if cont_token is None:
            raw_result = await self._unsubscribe_trigger_from_events_initial(
                trigger_name=trigger_name,
                cls=lambda x,y,z: x,
                **kwargs
            )

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

        def get_long_running_output(pipeline_response):
            deserialized = self._deserialize('TriggerSubscriptionOperationStatus', pipeline_response)

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

        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
            'triggerName': self._serialize.url("trigger_name", trigger_name, 'str', max_length=260, min_length=1, pattern=r'^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$'),
        }

        if polling is True: polling_method = AsyncLROBasePolling(lro_delay, path_format_arguments=path_format_arguments,  **kwargs)
        elif polling is False: polling_method = AsyncNoPolling()
        else: polling_method = polling
        if cont_token:
            return AsyncLROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        else:
            return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
    async def begin_backup(
            self, blob_storage_url: str, sas_token: str,
            **kwargs: "Any") -> "AsyncLROPoller[BackupOperation]":
        """Begin a full backup of the Key Vault.

        :param str blob_storage_url: URL of the blob storage container in which the backup will be stored, for example
            https://<account>.blob.core.windows.net/backup
        :param str sas_token: a Shared Access Signature (SAS) token authorizing access to the blob storage resource
        :keyword str continuation_token: a continuation token to restart polling from a saved state
        :returns: An AsyncLROPoller. Call `result()` on this object to get a :class:`BackupOperation`.
        :rtype: ~azure.core.polling.AsyncLROPoller[BackupOperation]
        """
        polling_interval = kwargs.pop("_polling_interval", 5)
        sas_parameter = self._models.SASTokenParameter(
            storage_resource_uri=blob_storage_url, token=sas_token)
        return await self._client.begin_full_backup(
            vault_base_url=self._vault_url,
            azure_storage_blob_container_uri=sas_parameter,
            cls=BackupOperation._wrap_generated,
            continuation_token=kwargs.pop("continuation_token", None),
            polling=AsyncLROBasePolling(
                lro_algorithms=[KeyVaultBackupClientPolling()],
                timeout=polling_interval,
                **kwargs),
            **kwargs)
    async def recognize_receipts_from_url(
            self,
            url: str,
            **kwargs: Any
    ) -> List["USReceipt"]:
        """Extract field text and semantic values from a given US sales receipt.
        The input document must be the location (Url) of the receipt to be analyzed.

        :param url: The url of the receipt. Currently only supports US sales receipts.
        :type url: str
        :keyword bool include_text_content: Include text lines and text content references in the result.
        :return: A list of USReceipt.
        :rtype: list[~azure.ai.formrecognizer.USReceipt]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

        include_text_content = kwargs.pop("include_text_content", False)

        return await self._client.analyze_receipt_async(
            file_stream={"source": url},
            include_text_details=include_text_content,
            cls=kwargs.pop("cls", self._receipt_callback),
            polling=AsyncLROBasePolling(timeout=POLLING_INTERVAL, **kwargs),
            error_map=error_map,
            **kwargs
        )
    async def recognize_content(self, stream: Union[bytes, IO[bytes]], **kwargs: Any) -> List["FormPage"]:
        """Extract text and content/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'.

        :param stream: .pdf, .jpg, .png or .tiff type file stream.
        :type stream: stream
        :keyword str content_type: Media type of the body sent to the API. Content-type is
            auto-detected, but can be overridden by passing this keyword argument. For options,
            see :class:`~azure.ai.formrecognizer.FormContentType`.
        :return: A list of FormPage.
        :rtype: list[~azure.ai.formrecognizer.FormPage]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

        content_type = kwargs.pop("content_type", None)
        if content_type == "application/json":
            raise TypeError("Call begin_recognize_content_from_url() to analyze a document from a url.")

        if content_type is None:
            content_type = get_content_type(stream)

        return await self._client.analyze_layout_async(
            file_stream=stream,
            content_type=content_type,
            cls=kwargs.pop("cls", self._content_callback),
            polling=AsyncLROBasePolling(timeout=POLLING_INTERVAL, **kwargs),
            error_map=error_map,
            **kwargs
        )
    async def begin_selective_restore(
        self, blob_storage_uri: str, sas_token: str, folder_name: str, key_name: str, **kwargs: "Any"
    ) -> "AsyncLROPoller[SelectiveKeyRestoreOperation]":
        """Restore a single key from a full Key Vault backup.

        :param str blob_storage_uri: URI of the blob storage resource in which the backup is stored
        :param str sas_token: a Shared Access Signature (SAS) token authorizing access to the blob storage resource
        :param str folder_name: name of the blob container which contains the backup
        :param str key_name: name of the key to restore from the backup
        :rtype: ~azure.core.polling.AsyncLROPoller[RestoreOperation]
        """
        polling_interval = kwargs.pop("_polling_interval", 5)
        sas_parameter = self._models.SASTokenParameter(storage_resource_uri=blob_storage_uri, token=sas_token)
        restore_details = self._models.SelectiveKeyRestoreOperationParameters(
            sas_token_parameters=sas_parameter, folder=folder_name,
        )
        return await self._client.begin_selective_key_restore_operation(
            vault_base_url=self._vault_url,
            key_name=key_name,
            restore_blob_details=restore_details,
            cls=SelectiveKeyRestoreOperation._wrap_generated,
            continuation_token=kwargs.pop("continuation_token", None),
            polling=AsyncLROBasePolling(
                lro_algorithms=[KeyVaultBackupClientPolling()], timeout=polling_interval, **kwargs
            ),
            **kwargs
        )
    async def begin_selective_restore(
            self, folder_url: str, sas_token: str, key_name: str,
            **kwargs: "Any") -> "AsyncLROPoller[SelectiveKeyRestoreOperation]":
        """Restore a single key from a full Key Vault backup.

        :param str folder_url: URL for the blob storage resource, including the path to the blob holding the
            backup. This would be the `folder_url` of a :class:`BackupOperation` returned by
            :func:`begin_backup` or :func:`get_backup_status`, for example
            https://<account>.blob.core.windows.net/backup/mhsm-account-2020090117323313
        :param str sas_token: a Shared Access Signature (SAS) token authorizing access to the blob storage resource
        :param str key_name: name of the key to restore from the backup
        :rtype: ~azure.core.polling.AsyncLROPoller[RestoreOperation]
        """
        polling_interval = kwargs.pop("_polling_interval", 5)
        container_url, folder_name = parse_folder_url(folder_url)
        sas_parameter = self._models.SASTokenParameter(
            storage_resource_uri=container_url, token=sas_token)
        restore_details = self._models.SelectiveKeyRestoreOperationParameters(
            sas_token_parameters=sas_parameter, folder=folder_name)
        return await self._client.begin_selective_key_restore_operation(
            vault_base_url=self._vault_url,
            key_name=key_name,
            restore_blob_details=restore_details,
            cls=SelectiveKeyRestoreOperation._wrap_generated,
            continuation_token=kwargs.pop("continuation_token", None),
            polling=AsyncLROBasePolling(
                lro_algorithms=[KeyVaultBackupClientPolling()],
                timeout=polling_interval,
                **kwargs),
            **kwargs)
    async def begin_recognize_receipts(
            self, receipt: Union[bytes, IO[bytes]],
            **kwargs: Any) -> AsyncLROPoller[List[RecognizedForm]]:
        """Extract field text and semantic values from a given US sales receipt.
        The input document must be of one of the supported content types - 'application/pdf',
        'image/jpeg', 'image/png' or 'image/tiff'.

        See fields found on a receipt here:
        https://aka.ms/azsdk/python/formrecognizer/receiptfields

        :param receipt: JPEG, PNG, PDF and TIFF type file stream or bytes.
            Currently only supports US sales receipts.
        :type receipt: bytes or IO[bytes]
        :keyword bool include_field_elements:
            Whether or not to include field elements such as lines and words in addition to form fields.
        :keyword content_type: Media type of the body sent to the API. Content-type is
            auto-detected, but can be overridden by passing this keyword argument. For options,
            see :class:`~azure.ai.formrecognizer.FormContentType`.
        :paramtype content_type: str or ~azure.ai.formrecognizer.FormContentType
        :keyword int polling_interval: Waiting time between two polls for LRO operations
            if no Retry-After header is present. Defaults to 5 seconds.
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :return: An instance of an AsyncLROPoller. Call `result()` on the poller
            object to return a list[:class:`~azure.ai.formrecognizer.RecognizedForm`].
        :rtype: ~azure.core.polling.AsyncLROPoller[list[~azure.ai.formrecognizer.RecognizedForm]]
        :raises ~azure.core.exceptions.HttpResponseError:

        .. admonition:: Example:

            .. literalinclude:: ../samples/async_samples/sample_recognize_receipts_async.py
                :start-after: [START recognize_receipts_async]
                :end-before: [END recognize_receipts_async]
                :language: python
                :dedent: 8
                :caption: Recognize US sales receipt fields.
        """

        polling_interval = kwargs.pop("polling_interval",
                                      self._client._config.polling_interval)
        continuation_token = kwargs.pop("continuation_token", None)
        content_type = kwargs.pop("content_type", None)
        if content_type == "application/json":
            raise TypeError(
                "Call begin_recognize_receipts_from_url() to analyze a receipt from a URL."
            )

        include_field_elements = kwargs.pop("include_field_elements", False)

        if content_type is None:
            content_type = get_content_type(receipt)

        return await self._client.begin_analyze_receipt_async(  # type: ignore
            file_stream=receipt,
            content_type=content_type,
            include_text_details=include_field_elements,
            cls=kwargs.pop("cls", self._receipt_callback),
            polling=AsyncLROBasePolling(timeout=polling_interval, **kwargs),
            error_map=error_map,
            continuation_token=continuation_token,
            **kwargs)
Example #17
0
    async def begin_copy_model(
            self, model_id: str, target: dict,
            **kwargs: Any) -> AsyncLROPoller[CustomFormModelInfo]:
        """Copy a custom model stored in this resource (the source) to the user specified
        target Form Recognizer resource. This should be called with the source Form Recognizer resource
        (with the model that is intended to be copied). The `target` parameter should be supplied from the
        target resource's output from calling the :func:`~get_copy_authorization()` method.

        :param str model_id: Model identifier of the model to copy to target resource.
        :param dict target:
            The copy authorization generated from the target resource's call to
            :func:`~get_copy_authorization()`.
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if
            no Retry-After header is present.
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :return: An instance of an AsyncLROPoller. Call `result()` on the poller
            object to return a :class:`~azure.ai.formrecognizer.CustomFormModelInfo`.
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.ai.formrecognizer.CustomFormModelInfo]
        :raises ~azure.core.exceptions.HttpResponseError:

        .. admonition:: Example:

            .. literalinclude:: ../samples/async_samples/sample_copy_model_async.py
                :start-after: [START copy_model_async]
                :end-before: [END copy_model_async]
                :language: python
                :dedent: 8
                :caption: Copy a model from the source resource to the target resource
        """

        if not model_id:
            raise ValueError("model_id cannot be None or empty.")

        continuation_token = kwargs.pop("continuation_token", None)
        polling_interval = kwargs.pop("polling_interval",
                                      self._client._config.polling_interval)

        def _copy_callback(raw_response, _, headers):  # pylint: disable=unused-argument
            copy_result = self._deserialize(
                self._generated_models.CopyOperationResult, raw_response)
            return CustomFormModelInfo._from_generated(copy_result,
                                                       target["modelId"])

        return await self._client.begin_copy_custom_model(  # type: ignore
            model_id=model_id,
            copy_request=CopyRequest(
                target_resource_id=target["resourceId"],
                target_resource_region=target["resourceRegion"],
                copy_authorization=CopyAuthorizationResult(
                    access_token=target["accessToken"],
                    model_id=target["modelId"],
                    expiration_date_time_ticks=target[
                        "expirationDateTimeTicks"])),
            cls=kwargs.pop("cls", _copy_callback),
            polling=AsyncLROBasePolling(timeout=polling_interval,
                                        lro_algorithms=[CopyPolling()],
                                        **kwargs),
            error_map=error_map,
            continuation_token=continuation_token,
            **kwargs)
Example #18
0
    async def begin_copy_model(
        self, model_id: str, target: dict, **kwargs: Any
    ) -> AsyncDocumentModelAdministrationLROPoller[DocumentModel]:
        """Copy a model stored in this resource (the source) to the user specified
        target Form Recognizer resource.

        This should be called with the source Form Recognizer resource
        (with the model that is intended to be copied). The `target` parameter should be supplied from the
        target resource's output from calling the :func:`~get_copy_authorization()` method.

        :param str model_id: Model identifier of the model to copy to target resource.
        :param dict target:
            The copy authorization generated from the target resource's call to
            :func:`~get_copy_authorization()`.
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :return: An instance of a AsyncDocumentModelAdministrationLROPoller. Call `result()` on the poller
            object to return a :class:`~azure.ai.formrecognizer.DocumentModel`.
        :rtype: ~azure.ai.formrecognizer.aio.AsyncDocumentModelAdministrationLROPoller[DocumentModel]
        :raises ~azure.core.exceptions.HttpResponseError:

        .. admonition:: Example:

            .. literalinclude:: ../samples/v3.2-beta/async_samples/sample_copy_model_async.py
                :start-after: [START begin_copy_model_async]
                :end-before: [END begin_copy_model_async]
                :language: python
                :dedent: 4
                :caption: Copy a model from the source resource to the target resource
        """
        def _copy_callback(raw_response, _, headers):  # pylint: disable=unused-argument
            op_response = self._deserialize(
                self._generated_models.GetOperationResponse, raw_response)
            model_info = self._deserialize(self._generated_models.ModelInfo,
                                           op_response.result)
            return DocumentModel._from_generated(model_info)

        if not model_id:
            raise ValueError("model_id cannot be None or empty.")

        polling_interval = kwargs.pop("polling_interval",
                                      self._client._config.polling_interval)
        continuation_token = kwargs.pop("continuation_token", None)

        return await self._client.begin_copy_document_model_to(  # type: ignore
            model_id=model_id,
            copy_to_request=self._generated_models.CopyAuthorization(
                target_resource_id=target["targetResourceId"],
                target_resource_region=target["targetResourceRegion"],
                target_model_id=target["targetModelId"],
                access_token=target["accessToken"],
                expiration_date_time=target["expirationDateTime"],
                target_model_location=target["targetModelLocation"],
            ) if target else None,
            cls=kwargs.pop("cls", _copy_callback),
            polling=AsyncLROBasePolling(
                timeout=polling_interval,
                lro_algorithms=[DocumentModelAdministrationPolling()],
                **kwargs),
            continuation_token=continuation_token,
            **kwargs)
    async def begin_recognize_content_from_url(self, form_url: str, **kwargs: Any) -> AsyncLROPoller[List[FormPage]]:
        """Extract text and layout information from a given document.
        The input document must be the location (Url) of the document to be analyzed.

        :param str form_url: The url of the form to analyze. The input must be a valid, encoded url
            of one of the supported formats: JPEG, PNG, PDF and TIFF.
        :keyword int polling_interval: Waiting time between two polls for LRO operations
            if no Retry-After header is present. Defaults to 5 seconds.
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :return: An instance of an AsyncLROPoller. Call `result()` on the poller
            object to return a list[:class:`~azure.ai.formrecognizer.FormPage`].
        :rtype: ~azure.core.polling.AsyncLROPoller[list[~azure.ai.formrecognizer.FormPage]]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

        polling_interval = kwargs.pop("polling_interval", self._client._config.polling_interval)
        continuation_token = kwargs.pop("continuation_token", None)
        return await self._client.begin_analyze_layout_async(  # type: ignore
            file_stream={"source": form_url},
            cls=kwargs.pop("cls", self._content_callback),
            polling=AsyncLROBasePolling(
                timeout=polling_interval,
                **kwargs
            ),
            error_map=error_map,
            continuation_token=continuation_token,
            **kwargs
        )
    async def recognize_receipts_from_url(self, url: str,
                                          **kwargs: Any) -> List["USReceipt"]:
        """Extract field text and semantic values from a given US sales receipt.
        The input document must be the location (Url) of the receipt to be analyzed.

        :param url: The url of the receipt. Currently only supports US sales receipts.
        :type url: str
        :keyword bool include_text_content:
            Whether or not to include text elements such as lines and words in addition to form fields.
        :keyword int polling_interval: Waiting time between two polls for LRO operations
            if no Retry-After header is present. Defaults to 5 seconds.
        :return: A list of USReceipt.
        :rtype: list[~azure.ai.formrecognizer.USReceipt]
        :raises ~azure.core.exceptions.HttpResponseError:

        .. admonition:: Example:

            .. literalinclude:: ../samples/async_samples/sample_recognize_receipts_from_url_async.py
                :start-after: [START recognize_receipts_from_url_async]
                :end-before: [END recognize_receipts_from_url_async]
                :language: python
                :dedent: 8
                :caption: Recognize US sales receipt fields from a URL.
        """

        polling_interval = kwargs.pop("polling_interval", POLLING_INTERVAL)
        include_text_content = kwargs.pop("include_text_content", False)

        return await self._client.analyze_receipt_async(  # type: ignore
            file_stream={"source": url},
            include_text_details=include_text_content,
            cls=kwargs.pop("cls", self._receipt_callback),
            polling=AsyncLROBasePolling(timeout=polling_interval, **kwargs),
            error_map=error_map,
            **kwargs)
    async def begin_execute_command(
        self,
        request: "_models.DataFlowDebugCommandRequest",
        **kwargs
    ) -> AsyncLROPoller["_models.DataFlowDebugCommandResponse"]:
        """Execute a data flow debug command.

        :param request: Data flow debug command definition.
        :type request: ~azure.synapse.artifacts.models.DataFlowDebugCommandRequest
        :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.AsyncPollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
        :return: An instance of AsyncLROPoller that returns either DataFlowDebugCommandResponse or the result of cls(response)
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.synapse.artifacts.models.DataFlowDebugCommandResponse]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        polling = kwargs.pop('polling', False)  # type: Union[bool, AsyncPollingMethod]
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.DataFlowDebugCommandResponse"]
        lro_delay = kwargs.pop(
            'polling_interval',
            self._config.polling_interval
        )
        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
        if cont_token is None:
            raw_result = await self._execute_command_initial(
                request=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):
            deserialized = self._deserialize('DataFlowDebugCommandResponse', pipeline_response)

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

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

        if polling is True: polling_method = AsyncLROBasePolling(lro_delay, path_format_arguments=path_format_arguments,  **kwargs)
        elif polling is False: polling_method = AsyncNoPolling()
        else: polling_method = polling
        if cont_token:
            return AsyncLROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        else:
            return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
    async def begin_execute_spark_job_definition(
            self, spark_job_definition_name: str,
            **kwargs) -> AsyncLROPoller["models.SparkBatchJob"]:
        """Executes the spark job definition.

        :param spark_job_definition_name: The spark job definition name.
        :type spark_job_definition_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
        :return: An instance of AsyncLROPoller that returns either SparkBatchJob or the result of cls(response)
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.synapse.artifacts.models.SparkBatchJob]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        polling = kwargs.pop('polling',
                             False)  # type: Union[bool, AsyncPollingMethod]
        cls = kwargs.pop('cls', None)  # type: ClsType["models.SparkBatchJob"]
        lro_delay = kwargs.pop('polling_interval',
                               self._config.polling_interval)
        cont_token = kwargs.pop('continuation_token',
                                None)  # type: Optional[str]
        if cont_token is None:
            raw_result = await self._execute_spark_job_definition_initial(
                spark_job_definition_name=spark_job_definition_name,
                cls=lambda x, y, z: x,
                **kwargs)

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

        def get_long_running_output(pipeline_response):
            deserialized = self._deserialize('SparkBatchJob',
                                             pipeline_response)

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

        if polling is True:
            polling_method = AsyncLROBasePolling(
                lro_delay,
                lro_options={'final-state-via': 'location'},
                **kwargs)
        elif polling is False:
            polling_method = AsyncNoPolling()
        else:
            polling_method = polling
        if cont_token:
            return AsyncLROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output)
        else:
            return AsyncLROPoller(self._client, raw_result,
                                  get_long_running_output, polling_method)
Example #23
0
    async def begin_release_phone_number(
        self,
        phone_number: str,
        **kwargs
    ) -> AsyncLROPoller[None]:
        """Releases an acquired phone number.

        Releases an acquired phone number.

        :param phone_number: Phone number to be released, e.g. +11234567890.
        :type phone_number: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: Pass in True if you'd like the AsyncLROBasePolling polling method,
         False for no polling, or your own initialized polling object for a personal polling strategy.
        :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
        :return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
        :rtype: ~azure.core.polling.AsyncLROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        polling = kwargs.pop('polling', False)  # type: Union[bool, AsyncPollingMethod]
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        lro_delay = kwargs.pop(
            'polling_interval',
            self._config.polling_interval
        )
        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
        if cont_token is None:
            raw_result = await self._release_phone_number_initial(
                phone_number=phone_number,
                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, {})

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

        if polling is True: polling_method = AsyncLROBasePolling(lro_delay, path_format_arguments=path_format_arguments,  **kwargs)
        elif polling is False: polling_method = AsyncNoPolling()
        else: polling_method = polling
        if cont_token:
            return AsyncLROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        else:
            return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
Example #24
0
    async def begin_create_composed_model(self, model_ids, **kwargs):
        # type: (List[str], Any) -> AsyncDocumentModelAdministrationLROPoller[DocumentModel]
        """Creates a composed model from a collection of existing models.

        A composed model allows multiple models to be called with a single model ID. When a document is
        submitted to be analyzed with a composed model ID, a classification step is first performed to
        route it to the correct custom model.

        :param list[str] model_ids: List of model IDs to use in the composed model.
        :keyword str model_id: A unique ID for your composed model.
            If not specified, a model ID will be created for you.
        :keyword str description: An optional description to add to the model.
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :return: An instance of an AsyncDocumentModelAdministrationLROPoller. Call `result()` on the poller
            object to return a :class:`~azure.ai.formrecognizer.DocumentModel`.
        :rtype: ~azure.ai.formrecognizer.aio.AsyncDocumentModelAdministrationLROPoller[DocumentModel]
        :raises ~azure.core.exceptions.HttpResponseError:

        .. admonition:: Example:

            .. literalinclude:: ../samples/v3.2-beta/async_samples/sample_create_composed_model_async.py
                :start-after: [START composed_model_async]
                :end-before: [END composed_model_async]
                :language: python
                :dedent: 4
                :caption: Creating a composed model with existing models.
        """
        def _compose_callback(raw_response, _, headers):  # pylint: disable=unused-argument
            op_response = self._deserialize(
                self._generated_models.GetOperationResponse, raw_response)
            model_info = self._deserialize(self._generated_models.ModelInfo,
                                           op_response.result)
            return DocumentModel._from_generated(model_info)

        model_id = kwargs.pop("model_id", None)
        description = kwargs.pop("description", None)
        continuation_token = kwargs.pop("continuation_token", None)
        polling_interval = kwargs.pop("polling_interval",
                                      self._client._config.polling_interval)

        if model_id is None:
            model_id = str(uuid.uuid4())

        return await self._client.begin_compose_document_model(  # type: ignore
            compose_request=self._generated_models.ComposeDocumentModelRequest(
                model_id=model_id,
                description=description,
                component_models=[
                    self._generated_models.ComponentModelInfo(
                        model_id=model_id) for model_id in model_ids
                ] if model_ids else [],
            ),
            cls=kwargs.pop("cls", _compose_callback),
            polling=AsyncLROBasePolling(
                timeout=polling_interval,
                lro_algorithms=[DocumentModelAdministrationPolling()],
                **kwargs),
            continuation_token=continuation_token,
            **kwargs)
    async def begin_recognize_custom_forms_from_url(
            self, model_id: str, form_url: str,
            **kwargs: Any) -> AsyncLROPoller[List[RecognizedForm]]:
        """Analyze a custom form with a model trained with or without labels. The form
        to analyze should be of the same type as the forms that were used to train the model.
        The input document must be the location (URL) of the document to be analyzed.

        :param str model_id: Custom model identifier.
        :param str form_url: The URL of the form to analyze. The input must be a valid, encoded URL
            of one of the supported formats: JPEG, PNG, PDF, TIFF, or BMP.
        :keyword bool include_field_elements:
            Whether or not to include all lines per page and field elements such as lines, words,
            and selection marks for each form field.
        :keyword list[str] pages: Custom page numbers for multi-page documents(PDF/TIFF). Input the page numbers
            and/or ranges of pages you want to get in the result. For a range of pages, use a hyphen, like
            `pages=["1-3", "5-6"]`. Separate each page number or range with a comma.
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :return: An instance of an AsyncLROPoller. Call `result()` on the poller
            object to return a list[:class:`~azure.ai.formrecognizer.RecognizedForm`].
        :rtype: ~azure.core.polling.AsyncLROPoller[list[~azure.ai.formrecognizer.RecognizedForm]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

        if not model_id:
            raise ValueError("model_id cannot be None or empty.")
        polling_interval = kwargs.pop("polling_interval",
                                      self._client._config.polling_interval)

        pages = kwargs.pop("pages", None)
        continuation_token = kwargs.pop("continuation_token", None)
        include_field_elements = kwargs.pop("include_field_elements", False)

        def analyze_callback(raw_response, _, headers):  # pylint: disable=unused-argument
            analyze_result = self._deserialize(
                self._generated_models.AnalyzeOperationResult, raw_response)
            return prepare_form_result(analyze_result, model_id)

        callback = kwargs.pop("cls", analyze_callback)
        polling = AsyncLROBasePolling(timeout=polling_interval,
                                      lro_algorithms=[AnalyzePolling()],
                                      **kwargs)

        # FIXME: part of this code will be removed once autorest can handle diff mixin
        # signatures across API versions
        if pages:
            if self._api_version == FormRecognizerApiVersion.V2_1:
                kwargs.update({"pages": pages})
            else:
                raise ValueError(
                    "'pages' is only available for API version V2_1 and up")

        return await self._client.begin_analyze_with_custom_model(  # type: ignore
            file_stream={"source": form_url},
            model_id=model_id,
            include_text_details=include_field_elements,
            cls=callback,
            polling=polling,
            continuation_token=continuation_token,
            **kwargs)
Example #26
0
    async def begin_create_composed_model(
        self, model_ids: List[str], **kwargs: Any
    ) -> AsyncLROPoller[CustomFormModel]:
        """Creates a composed model from a collection of existing models that were trained with labels.

        A composed model allows multiple models to be called with a single model ID. When a document is
        submitted to be analyzed with a composed model ID, a classification step is first performed to
        route it to the correct custom model.

        :param list[str] model_ids: List of model IDs to use in the composed model.
        :keyword str model_name: An optional, user-defined name to associate with your model.
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :return: An instance of an AsyncLROPoller. Call `result()` on the poller
            object to return a :class:`~azure.ai.formrecognizer.CustomFormModel`.
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.ai.formrecognizer.CustomFormModel]
        :raises ~azure.core.exceptions.HttpResponseError:

        .. versionadded:: v2.1
            The *begin_create_composed_model* client method

        .. admonition:: Example:

            .. literalinclude:: ../samples/async_samples/sample_create_composed_model_async.py
                :start-after: [START begin_create_composed_model_async]
                :end-before: [END begin_create_composed_model_async]
                :language: python
                :dedent: 8
                :caption: Create a composed model
        """

        def _compose_callback(
            raw_response, _, headers
        ):  # pylint: disable=unused-argument
            model = self._deserialize(self._generated_models.Model, raw_response)
            return CustomFormModel._from_generated_composed(model)

        model_name = kwargs.pop("model_name", None)
        polling_interval = kwargs.pop(
            "polling_interval", self._client._config.polling_interval
        )
        continuation_token = kwargs.pop("continuation_token", None)

        try:
            return await self._client.begin_compose_custom_models_async(  # type: ignore
                {"model_ids": model_ids, "model_name": model_name},
                cls=kwargs.pop("cls", _compose_callback),
                polling=AsyncLROBasePolling(
                    timeout=polling_interval,
                    lro_algorithms=[TrainingPolling()],
                    **kwargs
                ),
                continuation_token=continuation_token,
                **kwargs
            )
        except ValueError:
            raise ValueError(
                "Method 'begin_create_composed_model' is only available for API version V2_1 and up"
            )
Example #27
0
    async def begin_delete_spark_configuration(
        self,
        spark_configuration_name: str,
        **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Deletes a sparkConfiguration.

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

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

        if polling is True: polling_method = AsyncLROBasePolling(lro_delay, path_format_arguments=path_format_arguments,  **kwargs)
        elif polling is False: polling_method = AsyncNoPolling()
        else: polling_method = polling
        if cont_token:
            return AsyncLROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        else:
            return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
def test_polling_with_path_format_arguments():
    method = AsyncLROBasePolling(
        timeout=0,
        path_format_arguments={"host": "host:3000", "accountName": "local"}
    )
    client = AsyncPipelineClient(base_url="http://{accountName}{host}")

    method._operation = LocationPolling()
    method._operation._location_url = "/results/1"
    method._client = client
    assert "http://localhost:3000/results/1" == method._client.format_url(method._operation.get_polling_url(), **method._path_format_arguments)
Example #29
0
    async def begin_recognize_content(
            self,
            form: Union[bytes, IO[bytes]],
            **kwargs: Any
    ) -> AsyncLROPoller[List[FormPage]]:
        """Extract text and content/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'.

        :param form: JPEG, PNG, PDF and TIFF type file stream or bytes.
        :type form: bytes or IO[bytes]
        :keyword content_type: Media type of the body sent to the API. Content-type is
            auto-detected, but can be overridden by passing this keyword argument. For options,
            see :class:`~azure.ai.formrecognizer.FormContentType`.
        :paramtype content_type: str or ~azure.ai.formrecognizer.FormContentType
        :keyword int polling_interval: Waiting time between two polls for LRO operations
            if no Retry-After header is present. Defaults to 5 seconds.
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :return: An instance of an AsyncLROPoller. Call `result()` on the poller
            object to return a list[:class:`~azure.ai.formrecognizer.FormPage`].
        :rtype: ~azure.core.polling.AsyncLROPoller[list[~azure.ai.formrecognizer.FormPage]]
        :raises ~azure.core.exceptions.HttpResponseError:

        .. admonition:: Example:

            .. literalinclude:: ../samples/async_samples/sample_recognize_content_async.py
                :start-after: [START recognize_content_async]
                :end-before: [END recognize_content_async]
                :language: python
                :dedent: 8
                :caption: Recognize text and content/layout information from a form.
        """

        polling_interval = kwargs.pop("polling_interval", self._client._config.polling_interval)
        continuation_token = kwargs.pop("continuation_token", None)
        content_type = kwargs.pop("content_type", None)
        if content_type == "application/json":
            raise TypeError("Call begin_recognize_content_from_url() to analyze a document from a URL.")

        if content_type is None:
            content_type = get_content_type(form)

        return await self._client.begin_analyze_layout_async(  # type: ignore
            file_stream=form,
            content_type=content_type,
            cls=kwargs.pop("cls", self._content_callback),
            polling=AsyncLROBasePolling(
                timeout=polling_interval,
                **kwargs
            ),
            error_map=error_map,
            continuation_token=continuation_token,
            **kwargs
        )
async def test_long_running_delete():
    # Test polling from operation-location header
    response = TestBasePolling.mock_send('DELETE',
                                         202,
                                         {'operation-location': ASYNC_URL},
                                         body="")
    polling_method = AsyncLROBasePolling(0)
    poll = await async_poller(CLIENT, response,
                              TestBasePolling.mock_deserialization_no_body,
                              polling_method)
    assert poll is None
    assert polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollAsyncOpHeader is None