def begin_recognize_custom_forms_from_url(self, model_id, form_url, **kwargs):
        # type: (str, str, Any) -> LROPoller[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, or TIFF.
        :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 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 LROPoller. Call `result()` on the poller
            object to return a list[:class:`~azure.ai.formrecognizer.RecognizedForm`].
        :rtype: ~azure.core.polling.LROPoller[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)
        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)

        return 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=kwargs.pop("cls", analyze_callback),
            polling=LROBasePolling(timeout=polling_interval, lro_algorithms=[AnalyzePolling()], **kwargs),
            continuation_token=continuation_token,
            **kwargs
        )
    def begin_analyze_layout_async(
        self,
        file_stream=None,  # type: Optional[Union[str, "models.SourcePath"]]
        **kwargs  # type: Any
    ):
        # type: (...) -> LROPoller
        """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.

        Analyze Layout.

        :param file_stream: .json, .pdf, .jpg, .png or .tiff type file stream.
        :type file_stream: ~azure.ai.formrecognizer.models.SourcePath
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword polling: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :paramtype polling: bool or ~azure.core.polling.PollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
        :return: An instance of LROPoller that returns None
        :rtype: ~azure.core.polling.LROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        polling = kwargs.pop('polling',
                             False)  # type: Union[bool, PollingMethod]
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        lro_delay = kwargs.pop('polling_interval',
                               self._config.polling_interval)
        raw_result = self._analyze_layout_async_initial(
            file_stream=file_stream, cls=lambda x, y, z: x, **kwargs)

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

        if polling is True:
            polling_method = LROBasePolling(lro_delay, **kwargs)
        elif polling is False:
            polling_method = NoPolling()
        else:
            polling_method = polling
        return LROPoller(self._client, raw_result, get_long_running_output,
                         polling_method)
    def begin_recognize_receipts_from_url(self, receipt_url, **kwargs):
        # type: (str, Any) -> LROPoller[List[RecognizedReceipt]]
        """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 str receipt_url: The url of the receipt to analyze. The input must be a valid, encoded url
            of one of the supported formats: JPEG, PNG, PDF and TIFF. Currently only supports
            US sales receipts.
        :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.
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :return: An instance of an LROPoller. Call `result()` on the poller
            object to return a list[:class:`~azure.ai.formrecognizer.RecognizedReceipt`].
        :rtype: ~azure.core.polling.LROPoller[list[~azure.ai.formrecognizer.RecognizedReceipt]]
        :raises ~azure.core.exceptions.HttpResponseError:

        .. admonition:: Example:

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

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

        return self._client.begin_analyze_receipt_async(
            file_stream={"source": receipt_url},
            include_text_details=include_text_content,
            cls=kwargs.pop("cls", self._receipt_callback),
            polling=LROBasePolling(timeout=polling_interval, **kwargs),
            error_map=error_map,
            continuation_token=continuation_token,
            **kwargs
        )
def test_post_resource_location(pipeline_client_builder, deserialization_cb,
                                http_request, http_response):

    # ResourceLocation

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

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

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

    client = pipeline_client_builder(send)

    poll = LROPoller(client, initial_response, deserialization_cb,
                     LROBasePolling(0))
    result = poll.result()
    assert result['location_result'] == True
    def begin_full_backup(self, blob_storage_url, sas_token, **kwargs):
        # type: (str, str, **Any) -> LROPoller[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 instance of an LROPoller. Call `result()` on the poller object to get a :class:`BackupOperation`.
        :rtype: ~azure.core.polling.LROPoller[BackupOperation]
        """
        polling_interval = kwargs.pop("_polling_interval", 5)
        sas_parameter = self._models.SASTokenParameter(storage_resource_uri=blob_storage_url, token=sas_token)
        return 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=LROBasePolling(lro_algorithms=[KeyVaultBackupClientPolling()], timeout=polling_interval, **kwargs),
            **kwargs
        )
示例#6
0
    def begin_extract_layouts_from_url(self, url, **kwargs):
        # type: (str, Any) -> LROPoller
        """Extract text and layout information from a given document.
        The input document must be the location (Url) of the document to be analyzed.

        :param url: The url of the document.
        :type url: str
        :return: LROPoller
        :rtype: ~azure.core.polling.LROPoller[list[~azure.ai.formrecognizer.ExtractedLayoutPage]]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        if not isinstance(url, six.string_types):
            raise TypeError(
                "Call begin_extract_layouts() to analyze a document from a stream."
            )

        return self._client.begin_analyze_layout_async(
            file_stream={"source": url},
            cls=kwargs.pop("cls", self._layout_callback),
            polling=LROBasePolling(timeout=POLLING_INTERVAL, **kwargs),
            **kwargs)
    def begin_recognize_custom_forms_from_url(self, model_id, form_url,
                                              **kwargs):
        # type: (str, str, Any) -> LROPoller
        """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 and TIFF.
        :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: An instance of an LROPoller. Call `result()` on the poller
            object to return a list[:class:`~azure.ai.formrecognizer.RecognizedForm`].
        :rtype: ~azure.core.polling.LROPoller[list[~azure.ai.formrecognizer.RecognizedForm]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

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

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

        deserialization_callback = cls if cls else analyze_callback
        return self._client.begin_analyze_with_custom_model(
            file_stream={"source": form_url},
            model_id=model_id,
            include_text_details=include_text_content,
            cls=deserialization_callback,
            polling=LROBasePolling(timeout=polling_interval,
                                   lro_algorithms=[AnalyzePolling()],
                                   **kwargs),
            error_map=error_map,
            **kwargs)
示例#8
0
    def begin_extract_labeled_forms_from_url(self, url, model_id, **kwargs):
        # type: (str, str, Any) -> LROPoller
        """Analyze Form.

        :param url: The url of the document.
        :type url: str
        :param str model_id: Model identifier.
        :keyword bool include_text_details: Include text lines and element references in the result.
        :return: LROPoller
        :rtype: ~azure.core.polling.LROPoller[list[~azure.ai.formrecognizer.ExtractedLabeledForm]]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        if not isinstance(url, six.string_types):
            raise TypeError(
                "Call begin_extract_labeled_forms() to analyze a document from a stream."
            )

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

        def callback(raw_response, _, headers):  # pylint: disable=unused-argument
            extracted_form = self._client._deserialize(AnalyzeOperationResult,
                                                       raw_response)
            if not extracted_form.analyze_result.document_results:
                raise ValueError(
                    "Cannot call begin_extract_labeled_forms_from_url() with the ID of a model trained "
                    "without labels. Please call begin_extract_form_pages_from_url() instead."
                )
            return prepare_labeled_result(extracted_form)

        return self._client.begin_analyze_with_custom_model(
            file_stream={"source": url},
            model_id=model_id,
            include_text_details=include_text_details,
            cls=kwargs.pop("cls", callback),
            polling=LROBasePolling(timeout=POLLING_INTERVAL,
                                   lro_algorithms=[AnalyzePolling()],
                                   **kwargs),
            **kwargs)
    def begin_recognize_receipts(self, stream, **kwargs):
        # type: (Union[bytes, IO[bytes]], Any) -> LROPoller
        """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'.

        :param stream: .pdf, .jpg, .png or .tiff type file stream.
             Currently only supports US sales receipts.
        :type stream: stream
        :keyword bool include_text_content: Include text lines and text content references in the result.
        :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: An instance of an LROPoller. Call `result()` on the poller
            object to return a list[:class:`~azure.ai.formrecognizer.USReceipt`].
        :rtype: ~azure.core.polling.LROPoller[list[~azure.ai.formrecognizer.USReceipt]]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

        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_text_content = kwargs.pop("include_text_content", False)

        if content_type is None:
            content_type = get_content_type(stream)

        return self._client.begin_analyze_receipt_async(
            file_stream=stream,
            content_type=content_type,
            include_text_details=include_text_content,
            cls=kwargs.pop("cls", self._receipt_callback),
            polling=LROBasePolling(timeout=POLLING_INTERVAL, **kwargs),
            error_map=error_map,
            **kwargs)
示例#10
0
    def begin_recognize_content_from_url(self, url, **kwargs):
        # type: (str, Any) -> LROPoller
        """Extract text and layout information from a given document.
        The input document must be the location (Url) of the document to be analyzed.

        :param url: The url of the document.
        :type url: str
        :keyword int polling_interval: Waiting time between two polls for LRO operations
            if no Retry-After header is present. Defaults to 5 seconds.
        :return: An instance of an LROPoller. Call `result()` on the poller
            object to return a list[:class:`~azure.ai.formrecognizer.FormPage`].
        :rtype: ~azure.core.polling.LROPoller[list[~azure.ai.formrecognizer.FormPage]]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

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

        return self._client.begin_analyze_layout_async(
            file_stream={"source": url},
            cls=kwargs.pop("cls", self._content_callback),
            polling=LROBasePolling(timeout=polling_interval, **kwargs),
            error_map=error_map,
            **kwargs)
    def begin_recognize_receipts_from_url(self, url, **kwargs):
        # type: (str, Any) -> LROPoller
        """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: An instance of an LROPoller. Call `result()` on the poller
            object to return a list[:class:`~azure.ai.formrecognizer.USReceipt`].
        :rtype: ~azure.core.polling.LROPoller[list[~azure.ai.formrecognizer.USReceipt]]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

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

        return self._client.begin_analyze_receipt_async(
            file_stream={"source": url},
            include_text_details=include_text_content,
            cls=kwargs.pop("cls", self._receipt_callback),
            polling=LROBasePolling(timeout=POLLING_INTERVAL, **kwargs),
            error_map=error_map,
            **kwargs)
    def begin_full_restore(self, blob_storage_url, sas_token, **kwargs):
        # type: (str, str, **Any) -> LROPoller[RestoreOperation]
        """Restore a full backup of a Key Vault.

        :param str blob_storage_url: URL of the blob holding the backup. This would be the `blob_storage_url` of a
            :class:`BackupOperation` returned by :func:`begin_full_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
        :rtype: ~azure.core.polling.LROPoller[RestoreOperation]
        """
        polling_interval = kwargs.pop("_polling_interval", 5)
        container_url, folder_name = parse_blob_storage_url(blob_storage_url)
        sas_parameter = self._models.SASTokenParameter(storage_resource_uri=container_url, token=sas_token)
        restore_details = self._models.RestoreOperationParameters(
            sas_token_parameters=sas_parameter, folder_to_restore=folder_name
        )
        return self._client.begin_full_restore_operation(
            vault_base_url=self._vault_url,
            restore_blob_details=restore_details,
            cls=RestoreOperation._wrap_generated,
            continuation_token=kwargs.pop("continuation_token", None),
            polling=LROBasePolling(lro_algorithms=[KeyVaultBackupClientPolling()], timeout=polling_interval, **kwargs),
            **kwargs
        )
示例#13
0
    def begin_recognize_receipts_from_url(self, url, **kwargs):
        # type: (str, Any) -> LROPoller
        """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.
        :keyword int polling_interval: Waiting time between two polls for LRO operations
            if no Retry-After header is present. Defaults to 5 seconds.
        :return: An instance of an LROPoller. Call `result()` on the poller
            object to return a list[:class:`~azure.ai.formrecognizer.USReceipt`].
        :rtype: ~azure.core.polling.LROPoller[list[~azure.ai.formrecognizer.USReceipt]]
        :raises ~azure.core.exceptions.HttpResponseError:

        .. admonition:: Example:

            .. literalinclude:: ../samples/sample_recognize_receipts_from_url.py
                :start-after: [START recognize_receipts_from_url]
                :end-before: [END recognize_receipts_from_url]
                :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 self._client.begin_analyze_receipt_async(
            file_stream={"source": url},
            include_text_details=include_text_content,
            cls=kwargs.pop("cls", self._receipt_callback),
            polling=LROBasePolling(timeout=polling_interval, **kwargs),
            error_map=error_map,
            **kwargs
        )
    def begin_selective_key_restore_operation(
        self,
        vault_base_url,  # type: str
        key_name,  # type: str
        restore_blob_details=None,  # type: Optional["_models.SelectiveKeyRestoreOperationParameters"]
        **kwargs  # type: Any
    ):
        # type: (...) -> LROPoller["_models.SelectiveKeyRestoreOperation"]
        """Restores all key versions of a given key using user supplied SAS token pointing to a previously
        stored Azure Blob storage backup folder.

        :param vault_base_url: The vault name, for example https://myvault.vault.azure.net.
        :type vault_base_url: str
        :param key_name: The name of the key to be restored from the user supplied backup.
        :type key_name: str
        :param restore_blob_details: The Azure blob SAS token pointing to a folder where the previous
         successful full backup was stored.
        :type restore_blob_details: ~azure.keyvault.v7_3_preview.models.SelectiveKeyRestoreOperationParameters
        :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 SelectiveKeyRestoreOperation or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[~azure.keyvault.v7_3_preview.models.SelectiveKeyRestoreOperation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        polling = kwargs.pop('polling',
                             True)  # type: Union[bool, PollingMethod]
        cls = kwargs.pop(
            'cls',
            None)  # type: ClsType["_models.SelectiveKeyRestoreOperation"]
        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._selective_key_restore_operation_initial(
                vault_base_url=vault_base_url,
                key_name=key_name,
                restore_blob_details=restore_blob_details,
                cls=lambda x, y, z: x,
                **kwargs)

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

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers['Retry-After'] = self._deserialize(
                'int', response.headers.get('Retry-After'))
            response_headers['Azure-AsyncOperation'] = self._deserialize(
                'str', response.headers.get('Azure-AsyncOperation'))
            deserialized = self._deserialize('SelectiveKeyRestoreOperation',
                                             pipeline_response)

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

        path_format_arguments = {
            'vaultBaseUrl':
            self._serialize.url("vault_base_url",
                                vault_base_url,
                                'str',
                                skip_quote=True),
            'keyName':
            self._serialize.url("key_name", key_name, 'str'),
        }

        if polling is True:
            polling_method = LROBasePolling(
                lro_delay,
                lro_options={'final-state-via': 'azure-async-operation'},
                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)
示例#15
0
    def begin_create_or_update_pipeline(
        self,
        pipeline_name,  # type: str
        pipeline,  # type: "_models.PipelineResource"
        if_match=None,  # type: Optional[str]
        **kwargs  # type: Any
    ):
        # type: (...) -> LROPoller["_models.PipelineResource"]
        """Creates or updates a pipeline.

        :param pipeline_name: The pipeline name.
        :type pipeline_name: str
        :param pipeline: Pipeline resource definition.
        :type pipeline: ~azure.synapse.artifacts.models.PipelineResource
        :param if_match: ETag of the pipeline entity.  Should only be specified for update, for which
         it should match existing entity or can be * for unconditional update.
        :type if_match: 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 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 PipelineResource or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[~azure.synapse.artifacts.models.PipelineResource]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        polling = kwargs.pop('polling', True)  # type: Union[bool, PollingMethod]
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.PipelineResource"]
        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._create_or_update_pipeline_initial(
                pipeline_name=pipeline_name,
                pipeline=pipeline,
                if_match=if_match,
                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('PipelineResource', 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),
            'pipelineName': self._serialize.url("pipeline_name", pipeline_name, 'str', max_length=260, min_length=1, pattern=r'^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$'),
        }

        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)
示例#16
0
    def begin_recognize_custom_forms(self, model_id, stream, **kwargs):
        # type: (str, Union[bytes, IO[bytes]], Any) -> LROPoller
        """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 of one of the supported content types - 'application/pdf',
        'image/jpeg', 'image/png' or 'image/tiff'.

        :param str model_id: Custom model identifier.
        :param stream: .pdf, .jpg, .png or .tiff type file stream.
        :type stream: bytes or IO[bytes]
        :keyword bool include_text_content:
            Whether or not to include text elements such as lines and words in addition to form fields.
        :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`.
        :keyword int polling_interval: Waiting time between two polls for LRO operations
            if no Retry-After header is present. Defaults to 5 seconds.
        :return: An instance of an LROPoller. Call `result()` on the poller
            object to return a list[:class:`~azure.ai.formrecognizer.RecognizedForm`].
        :rtype: ~azure.core.polling.LROPoller[list[~azure.ai.formrecognizer.RecognizedForm]
        :raises ~azure.core.exceptions.HttpResponseError:

        .. admonition:: Example:

            .. literalinclude:: ../samples/sample_recognize_custom_forms.py
                :start-after: [START recognize_custom_forms]
                :end-before: [END recognize_custom_forms]
                :language: python
                :dedent: 8
                :caption: Recognize fields and values from a custom form.
        """

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

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

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

        deserialization_callback = cls if cls else analyze_callback
        return self._client.begin_analyze_with_custom_model(
            file_stream=stream,
            model_id=model_id,
            include_text_details=include_text_content,
            content_type=content_type,
            cls=deserialization_callback,
            polling=LROBasePolling(timeout=polling_interval,
                                   lro_algorithms=[AnalyzePolling()],
                                   **kwargs),
            error_map=error_map,
            **kwargs)
    def begin_full_backup(
            self,
            vault_base_url,  # type: str
            azure_storage_blob_container_uri=None,  # type: Optional["_models.SASTokenParameter"]
            **kwargs  # type: Any
    ):
        # type: (...) -> LROPoller["_models.FullBackupOperation"]
        """Creates a full backup using a user-provided SAS token to an Azure blob storage container.

        :param vault_base_url: The vault name, for example https://myvault.vault.azure.net.
        :type vault_base_url: str
        :param azure_storage_blob_container_uri: Azure blob shared access signature token pointing to a
         valid Azure blob container where full backup needs to be stored. This token needs to be valid
         for at least next 24 hours from the time of making this call.
        :type azure_storage_blob_container_uri: ~azure.keyvault.v7_3_preview.models.SASTokenParameter
        :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 FullBackupOperation or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[~azure.keyvault.v7_3_preview.models.FullBackupOperation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        polling = kwargs.pop('polling',
                             True)  # type: Union[bool, PollingMethod]
        cls = kwargs.pop('cls',
                         None)  # type: ClsType["_models.FullBackupOperation"]
        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._full_backup_initial(
                vault_base_url=vault_base_url,
                azure_storage_blob_container_uri=
                azure_storage_blob_container_uri,
                cls=lambda x, y, z: x,
                **kwargs)

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

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers['Retry-After'] = self._deserialize(
                'int', response.headers.get('Retry-After'))
            response_headers['Azure-AsyncOperation'] = self._deserialize(
                'str', response.headers.get('Azure-AsyncOperation'))
            deserialized = self._deserialize('FullBackupOperation',
                                             pipeline_response)

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

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

        if polling is True:
            polling_method = LROBasePolling(
                lro_delay,
                lro_options={'final-state-via': 'azure-async-operation'},
                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)
示例#18
0
    def begin_recognize_custom_forms_from_url(self, model_id, form_url,
                                              **kwargs):
        # type: (str, str, Any) -> LROPoller[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 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 LROPoller. Call `result()` on the poller
            object to return a list[:class:`~azure.ai.formrecognizer.RecognizedForm`].
        :rtype: ~azure.core.polling.LROPoller[list[~azure.ai.formrecognizer.RecognizedForm]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

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

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

        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 = LROBasePolling(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_PREVIEW:
                kwargs.update({"pages": pages})
            else:
                raise ValueError(
                    "'pages' is only available for API version V2_1_PREVIEW and up"
                )

        return 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)
示例#19
0
    def test_long_running_patch(self):

        # Test polling from location header
        response = TestBasePolling.mock_send(
            'PATCH', 202,
            {'location': LOCATION_URL},
            body={'properties':{'provisioningState': 'Succeeded'}})
        poll = LROPoller(CLIENT, response,
            TestBasePolling.mock_outputs,
            LROBasePolling(0))
        assert poll.result().name == TEST_NAME
        assert poll._polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollLocationHeader is None

        # Test polling from operation-location header
        response = TestBasePolling.mock_send(
            'PATCH', 202,
            {'operation-location': ASYNC_URL},
            body={'properties':{'provisioningState': 'Succeeded'}})
        poll = LROPoller(CLIENT, response,
            TestBasePolling.mock_outputs,
            LROBasePolling(0))
        assert poll.result().name == TEST_NAME
        assert not hasattr(poll._polling_method._pipeline_response, 'randomFieldFromPollAsyncOpHeader')

        # Test polling from location header
        response = TestBasePolling.mock_send(
            'PATCH', 200,
            {'location': LOCATION_URL},
            body={'properties':{'provisioningState': 'Succeeded'}})
        poll = LROPoller(CLIENT, response,
            TestBasePolling.mock_outputs,
            LROBasePolling(0))
        assert poll.result().name == TEST_NAME
        assert poll._polling_method._pipeline_response.http_response.internal_response.randomFieldFromPollLocationHeader is None

        # Test polling from operation-location header
        response = TestBasePolling.mock_send(
            'PATCH', 200,
            {'operation-location': ASYNC_URL},
            body={'properties':{'provisioningState': 'Succeeded'}})
        poll = LROPoller(CLIENT, response,
            TestBasePolling.mock_outputs,
            LROBasePolling(0))
        assert poll.result().name == TEST_NAME
        assert not hasattr(poll._polling_method._pipeline_response, 'randomFieldFromPollAsyncOpHeader')

        # Test fail to poll from operation-location header
        response = TestBasePolling.mock_send(
            'PATCH', 202,
            {'operation-location': ERROR})
        with pytest.raises(BadEndpointError):
            poll = LROPoller(CLIENT, response,
                TestBasePolling.mock_outputs,
                LROBasePolling(0)).result()

        # Test fail to poll from location header
        response = TestBasePolling.mock_send(
            'PATCH', 202,
            {'location': ERROR})
        with pytest.raises(BadEndpointError):
            poll = LROPoller(CLIENT, response,
                TestBasePolling.mock_outputs,
                LROBasePolling(0)).result()
    def begin_create_cascade_delete_job(
            self,
            job_id,  # type: str
            farmer_id,  # type: str
            **kwargs  # type: Any
    ):
        # type: (...) -> LROPoller["_models.CascadeDeleteJob"]
        """Create a cascade delete job for specified farmer.

        :param job_id: Job ID supplied by end user.
        :type job_id: str
        :param farmer_id: ID of the farmer to be deleted.
        :type farmer_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: By default, your polling method will be 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 CascadeDeleteJob or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[~azure.agrifood.farming.models.CascadeDeleteJob]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        polling = kwargs.pop('polling',
                             True)  # type: Union[bool, PollingMethod]
        cls = kwargs.pop('cls',
                         None)  # type: ClsType["_models.CascadeDeleteJob"]
        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._create_cascade_delete_job_initial(
                job_id=job_id,
                farmer_id=farmer_id,
                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('CascadeDeleteJob',
                                             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),
            'jobId':
            self._serialize.url("job_id", job_id, 'str'),
        }

        if polling is True:
            polling_method = LROBasePolling(
                lro_delay,
                lro_options={'final-state-via': 'location'},
                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)
    def begin_rename_sql_script(
            self,
            sql_script_name,  # type: str
            new_name=None,  # type: Optional[str]
            **kwargs  # type: Any
    ):
        # type: (...) -> LROPoller[None]
        """Renames a sqlScript.

        :param sql_script_name: The sql script name.
        :type sql_script_name: str
        :param new_name: New name of the artifact.
        :type new_name: str
        :keyword api_version: Api Version. The default value is "2020-12-01". Note that overriding this
         default value may result in unsupported behavior.
        :paramtype api_version: 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 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
        """
        api_version = kwargs.pop('api_version', "2020-12-01")  # type: str
        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._rename_sql_script_initial(
                sql_script_name=sql_script_name,
                new_name=new_name,
                api_version=api_version,
                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)
    def begin_copy_model(
        self,
        model_id,  # type: str
        target,  # type: Dict
        **kwargs  # type: Any
    ):
        # type: (...) -> LROPoller[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 LROPoller. Call `result()` on the poller
            object to return a :class:`~azure.ai.formrecognizer.CustomFormModelInfo`.
        :rtype: ~azure.core.polling.LROPoller[~azure.ai.formrecognizer.CustomFormModelInfo]
        :raises ~azure.core.exceptions.HttpResponseError:

        .. admonition:: Example:

            .. literalinclude:: ../samples/sample_copy_model.py
                :start-after: [START begin_copy_model]
                :end-before: [END begin_copy_model]
                :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.")

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

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

        return 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=LROBasePolling(timeout=polling_interval, lro_algorithms=[CopyPolling()], **kwargs),
            error_map=error_map,
            continuation_token=continuation_token,
            **kwargs
        )
    def begin_training(self, training_files_url, use_training_labels, **kwargs):
        # type: (str, bool, Any) -> LROPoller[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 in the source path for
            training. For example, when using a Azure storage blob Uri, use the prefix to restrict sub
            folders for training.
        :keyword bool include_sub_folders: A flag to indicate if sub folders within the set of prefix folders
            will also need to be included when searching for content to be preprocessed. 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.
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :return: An instance of an LROPoller. Call `result()` on the poller
            object to return a :class:`~azure.ai.formrecognizer.CustomFormModel`.
        :rtype: ~azure.core.polling.LROPoller[~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/sample_train_model_without_labels.py
                :start-after: [START training]
                :end-before: [END training]
                :language: python
                :dedent: 8
                :caption: Training a model with your custom forms.
        """

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

        cls = kwargs.pop("cls", None)
        continuation_token = kwargs.pop("continuation_token", None)
        polling_interval = kwargs.pop("polling_interval", self._client._config.polling_interval)
        deserialization_callback = cls if cls else callback

        if continuation_token:
            return LROPoller.from_continuation_token(
                polling_method=LROBasePolling(timeout=polling_interval, lro_algorithms=[TrainingPolling()], **kwargs),
                continuation_token=continuation_token,
                client=self._client._client,
                deserialization_callback=deserialization_callback
            )

        response = self._client.train_custom_model_async(  # type: ignore
            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
        )  # type: PipelineResponseType

        return LROPoller(
            self._client._client,
            response,
            deserialization_callback,
            LROBasePolling(timeout=polling_interval, lro_algorithms=[TrainingPolling()], **kwargs)
        )
示例#24
0
    def begin_debug_spark_job_definition(
            self,
            properties,  # type: "_models.SparkJobDefinition"
            **kwargs  # type: Any
    ):
        # type: (...) -> LROPoller["_models.SparkBatchJob"]
        """Debug the spark job definition.

        :param properties: Properties of spark job definition.
        :type properties: ~azure.synapse.artifacts.v2020_12_01.models.SparkJobDefinition
        :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 SparkBatchJob or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[~azure.synapse.artifacts.v2020_12_01.models.SparkBatchJob]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        polling = kwargs.pop('polling',
                             True)  # type: Union[bool, PollingMethod]
        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 = self._debug_spark_job_definition_initial(
                properties=properties, 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

        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,
                lro_options={'final-state-via': 'location'},
                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)
示例#25
0
    def begin_training(self, training_files_url, use_training_labels,
                       **kwargs):
        # type: (str, bool, Any) -> LROPoller[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). Note that
        a container URI (without SAS) is accepted only when the container is public.
        Models are trained using documents that are of the following content type - 'application/pdf',
        'image/jpeg', 'image/png', 'image/tiff', or 'image/bmp'. Other types of content in the container is ignored.

        :param str training_files_url: An Azure Storage blob container's SAS URI. A container URI (without SAS)
            can be used if the container is public. For more information on setting up a training data set, see:
            https://docs.microsoft.com/azure/cognitive-services/form-recognizer/build-training-data-set
        :param bool use_training_labels: Whether to train with labels or not. Corresponding labeled files must
            exist in the blob container if set to `True`.
        :keyword str prefix: A case-sensitive prefix string to filter documents in the source path for
            training. For example, when using a Azure storage blob URI, use the prefix to restrict sub
            folders for training.
        :keyword bool include_subfolders: A flag to indicate if subfolders within the set of prefix folders
            will also need to be included when searching for content to be preprocessed. Not supported if
            training with labels.
        :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 LROPoller. Call `result()` on the poller
            object to return a :class:`~azure.ai.formrecognizer.CustomFormModel`.
        :rtype: ~azure.core.polling.LROPoller[~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()`

        .. versionadded:: v2.1
            The *model_name* keyword argument

        .. admonition:: Example:

            .. literalinclude:: ../samples/sample_train_model_without_labels.py
                :start-after: [START training]
                :end-before: [END training]
                :language: python
                :dedent: 8
                :caption: Training a model (without labels) with your custom forms.
        """
        def callback_v2_0(raw_response):
            model = self._deserialize(self._generated_models.Model,
                                      raw_response)
            return CustomFormModel._from_generated(
                model, api_version=self._api_version)

        def callback_v2_1(raw_response, _, headers):  # pylint: disable=unused-argument
            model = self._deserialize(self._generated_models.Model,
                                      raw_response)
            return CustomFormModel._from_generated(
                model, api_version=self._api_version)

        cls = kwargs.pop("cls", None)
        model_name = kwargs.pop("model_name", None)
        if model_name and self._api_version == "2.0":
            raise ValueError(
                "'model_name' is only available for API version V2_1 and up")
        continuation_token = kwargs.pop("continuation_token", None)
        polling_interval = kwargs.pop("polling_interval",
                                      self._client._config.polling_interval)

        if self._api_version == "2.0":
            deserialization_callback = cls if cls else callback_v2_0
            if continuation_token:
                return LROPoller.from_continuation_token(
                    polling_method=LROBasePolling(
                        timeout=polling_interval,
                        lro_algorithms=[TrainingPolling()],
                        **kwargs),
                    continuation_token=continuation_token,
                    client=self._client._client,
                    deserialization_callback=deserialization_callback,
                )

            response = self._client.train_custom_model_async(  # type: ignore
                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_subfolders",
                                                       False),
                    ),
                ),
                cls=lambda pipeline_response, _, response_headers:
                pipeline_response,
                **kwargs)  # type: PipelineResponseType

            return LROPoller(
                self._client._client,
                response,
                deserialization_callback,
                LROBasePolling(timeout=polling_interval,
                               lro_algorithms=[TrainingPolling()],
                               **kwargs),
            )

        deserialization_callback = cls if cls else callback_v2_1
        return self._client.begin_train_custom_model_async(  # type: ignore
            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_subfolders",
                                                   False),
                ),
                model_name=model_name,
            ),
            cls=deserialization_callback,
            continuation_token=continuation_token,
            polling=LROBasePolling(timeout=polling_interval,
                                   lro_algorithms=[TrainingPolling()],
                                   **kwargs),
            **kwargs)
示例#26
0
    def begin_create(
            self,
            library_name,  # type: str
            **kwargs  # type: Any
    ):
        # type: (...) -> LROPoller["_models.LibraryResourceInfo"]
        """Creates a library with the library name.

        :param library_name: file name to upload. Minimum length of the filename should be 1 excluding
         the extension length.
        :type library_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 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:
        """
        polling = kwargs.pop('polling',
                             True)  # type: Union[bool, PollingMethod]
        cls = kwargs.pop('cls',
                         None)  # type: ClsType["_models.LibraryResourceInfo"]
        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._create_initial(library_name=library_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('LibraryResourceInfo',
                                             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),
            'libraryName':
            self._serialize.url("library_name",
                                library_name,
                                'str',
                                max_length=100,
                                min_length=0),
        }

        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)
示例#27
0
    def begin_rename_pipeline(
        self,
        pipeline_name,  # type: str
        new_name=None,  # type: Optional[str]
        **kwargs  # type: Any
    ):
        # type: (...) -> LROPoller[None]
        """Renames a pipeline.

        :param pipeline_name: The pipeline name.
        :type pipeline_name: str
        :param new_name: New name of the artifact.
        :type new_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 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:
        """
        polling = kwargs.pop('polling', True)  # type: Union[bool, PollingMethod]
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        lro_delay = kwargs.pop(
            'polling_interval',
            self._config.polling_interval
        )
        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
        if cont_token is None:
            raw_result = self._rename_pipeline_initial(
                pipeline_name=pipeline_name,
                new_name=new_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),
            'pipelineName': self._serialize.url("pipeline_name", pipeline_name, 'str', max_length=260, min_length=1, pattern=r'^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$'),
        }

        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)
示例#28
0
    def begin_recognize_custom_forms(self, model_id, form, **kwargs):
        # type: (str, Union[bytes, IO[bytes]], Any) -> LROPoller[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 of one of the supported content types - 'application/pdf',
        'image/jpeg', 'image/png', 'image/tiff', or 'image/bmp'.

        :param str model_id: Custom model identifier.
        :param form: JPEG, PNG, PDF, TIFF, or BMP type file stream or bytes.
        :type form: bytes or IO[bytes]
        :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 content_type: Content-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 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 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 LROPoller. Call `result()` on the poller
            object to return a list[:class:`~azure.ai.formrecognizer.RecognizedForm`].
        :rtype: ~azure.core.polling.LROPoller[list[~azure.ai.formrecognizer.RecognizedForm]
        :raises ~azure.core.exceptions.HttpResponseError:

        .. admonition:: Example:

            .. literalinclude:: ../samples/sample_recognize_custom_forms.py
                :start-after: [START recognize_custom_forms]
                :end-before: [END recognize_custom_forms]
                :language: python
                :dedent: 8
                :caption: Recognize fields and values from a custom form.
        """

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

        pages = kwargs.pop("pages", None)
        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_custom_forms_from_url() to analyze a document from a URL."
            )
        if content_type is None and continuation_token is None:
            content_type = get_content_type(form)

        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 = LROBasePolling(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_PREVIEW:
                kwargs.update({"pages": pages})
            else:
                raise ValueError(
                    "'pages' is only available for API version V2_1_PREVIEW and up"
                )

        return self._client.begin_analyze_with_custom_model(  # type: ignore
            file_stream=form,
            model_id=model_id,
            include_text_details=include_field_elements,
            content_type=content_type,
            cls=callback,
            polling=polling,
            continuation_token=continuation_token,
            **kwargs)
示例#29
0
    def begin_conversation_analysis(self, task: JSON,
                                    **kwargs: Any) -> LROPoller[JSON]:
        """Submit analysis job for conversations.

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

        :param task: The collection of conversations to analyze and one or more tasks to execute.
        :type task: JSON
        :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 JSON object
        :rtype: ~azure.core.polling.LROPoller[JSON]
        :raises: ~azure.core.exceptions.HttpResponseError

        Example:
            .. code-block:: python

                # JSON input template you can fill out and use as your body input.
                task = {
                    "analysisInput": {
                        "conversations": [
                            {
                                "domain": "str",  # Optional. Enumeration of
                                  supported conversational domains. Known values are: "finance",
                                  "healthcare", "generic".
                                "id": "str",  # Required. Unique identifier for the
                                  conversation.
                                "language": "str",  # Required. The language of the
                                  conversation item in BCP-47 format.
                                modality: modality
                            }
                        ]
                    },
                    "displayName": "str",  # Optional. Optional display name for the analysis
                      job.
                    "tasks": [
                        {
                            "taskName": "str",  # Optional. Required. The set of tasks to
                              execute on the input conversation.
                            kind: AnalyzeConversationLROTask
                        }
                    ]
                }

                # response body for status code(s): 200
                response.json() == {
                    "createdDateTime": "2020-02-20 00:00:00",  # Required.
                    "displayName": "str",  # Optional.
                    "errors": [
                        {
                            "code": "str",  # Required. One of a server-defined set of
                              error codes. Known values are: "InvalidRequest", "InvalidArgument",
                              "Unauthorized", "Forbidden", "NotFound", "ProjectNotFound",
                              "OperationNotFound", "AzureCognitiveSearchNotFound",
                              "AzureCognitiveSearchIndexNotFound", "TooManyRequests",
                              "AzureCognitiveSearchThrottling",
                              "AzureCognitiveSearchIndexLimitReached", "InternalServerError",
                              "ServiceUnavailable", "Timeout", "QuotaExceeded", "Conflict", "Warning".
                            "details": [
                                ...
                            ],
                            "innererror": {
                                "code": "str",  # Required. One of a server-defined
                                  set of error codes. Known values are: "InvalidRequest",
                                  "InvalidParameterValue", "KnowledgeBaseNotFound",
                                  "AzureCognitiveSearchNotFound", "AzureCognitiveSearchThrottling",
                                  "ExtractionFailure", "InvalidRequestBodyFormat", "EmptyRequest",
                                  "MissingInputDocuments", "InvalidDocument", "ModelVersionIncorrect",
                                  "InvalidDocumentBatch", "UnsupportedLanguageCode",
                                  "InvalidCountryHint".
                                "details": {
                                    "str": "str"  # Optional. Error details.
                                },
                                "innererror": ...,
                                "message": "str",  # Required. Error message.
                                "target": "str"  # Optional. Error target.
                            },
                            "message": "str",  # Required. A human-readable
                              representation of the error.
                            "target": "str"  # Optional. The target of the error.
                        }
                    ],
                    "expirationDateTime": "2020-02-20 00:00:00",  # Optional.
                    "jobId": "str",  # Required.
                    "lastUpdatedDateTime": "2020-02-20 00:00:00",  # Required.
                    "nextLink": "str",  # Optional.
                    "statistics": {
                        "conversationsCount": 0,  # Required. Number of conversations
                          submitted in the request.
                        "erroneousConversationsCount": 0,  # Required. Number of invalid
                          documents. This includes empty, over-size limit or non-supported languages
                          documents.
                        "transactionsCount": 0.0,  # Required. Number of transactions for the
                          request.
                        "validConversationsCount": 0  # Required. Number of conversations
                          documents. This excludes empty, over-size limit or non-supported languages
                          documents.
                    },
                    "status": "str",  # Required. Known values are: "notStarted", "running",
                      "succeeded", "partiallyCompleted", "failed", "cancelled", "cancelling".
                    "tasks": {
                        "completed": 0,  # Required. Count of tasks completed successfully.
                        "failed": 0,  # Required. Count of tasks that failed.
                        "inProgress": 0,  # Required. Count of tasks in progress currently.
                        "items": [
                            {
                                "lastUpdateDateTime": "2020-02-20 00:00:00",  #
                                  Required. The last updated time in UTC for the task.
                                "status": "str",  # Required. The status of the task
                                  at the mentioned last update time. Known values are: "notStarted",
                                  "running", "succeeded", "failed", "cancelled", "cancelling".
                                "taskName": "str",  # Optional. List of results from
                                  tasks (if available).
                                kind: AnalyzeConversationJobResult
                            }
                        ],
                        "total": 0  # Required. Total count of tasks submitted as part of the
                          job.
                    }
                }
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop(
            'api_version', _params.pop('api-version',
                                       "2022-05-15-preview"))  # type: str
        content_type = kwargs.pop(
            'content_type',
            _headers.pop('Content-Type',
                         "application/json"))  # type: Optional[str]
        cls = kwargs.pop('cls', None)  # type: ClsType[JSON]
        polling = kwargs.pop('polling',
                             True)  # type: Union[bool, PollingMethod]
        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._conversation_analysis_initial(  # type: ignore
                task=task,
                api_version=api_version,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs)
        kwargs.pop('error_map', None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            if response.content:
                deserialized = response.json()
            else:
                deserialized = None
            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 = cast(
                PollingMethod,
                LROBasePolling(lro_delay,
                               path_format_arguments=path_format_arguments,
                               **kwargs))  # type: PollingMethod
        elif polling is False:
            polling_method = cast(PollingMethod, 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)
        return LROPoller(self._client, raw_result, get_long_running_output,
                         polling_method)
    def begin_create_or_update_sql_script(
            self,
            sql_script_name,  # type: str
            sql_script,  # type: "_models.SqlScriptResource"
            if_match=None,  # type: Optional[str]
            **kwargs  # type: Any
    ):
        # type: (...) -> LROPoller["_models.SqlScriptResource"]
        """Creates or updates a Sql Script.

        :param sql_script_name: The sql script name.
        :type sql_script_name: str
        :param sql_script: Sql Script resource definition.
        :type sql_script: ~azure.synapse.artifacts.models.SqlScriptResource
        :param if_match: ETag of the SQL script entity.  Should only be specified for update, for which
         it should match existing entity or can be * for unconditional update.
        :type if_match: str
        :keyword api_version: Api Version. The default value is "2020-12-01". Note that overriding this
         default value may result in unsupported behavior.
        :paramtype api_version: 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 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 SqlScriptResource or the result of
         cls(response)
        :rtype: ~azure.core.polling.LROPoller[~azure.synapse.artifacts.models.SqlScriptResource]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        api_version = kwargs.pop('api_version', "2020-12-01")  # type: str
        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["_models.SqlScriptResource"]
        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._create_or_update_sql_script_initial(
                sql_script_name=sql_script_name,
                sql_script=sql_script,
                if_match=if_match,
                api_version=api_version,
                content_type=content_type,
                cls=lambda x, y, z: x,
                **kwargs)
        kwargs.pop('error_map', None)

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = self._deserialize('SqlScriptResource',
                                             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 = 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)