diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/__init__.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/__init__.py index a3039bd0c18f..5065778e8872 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/__init__.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/__init__.py @@ -50,11 +50,17 @@ EnableProcessorMetadata, EnableProcessorRequest, EnableProcessorResponse, + EvaluateProcessorVersionMetadata, + EvaluateProcessorVersionRequest, + EvaluateProcessorVersionResponse, FetchProcessorTypesRequest, FetchProcessorTypesResponse, + GetEvaluationRequest, GetProcessorRequest, GetProcessorVersionRequest, HumanReviewStatus, + ListEvaluationsRequest, + ListEvaluationsResponse, ListProcessorsRequest, ListProcessorsResponse, ListProcessorTypesRequest, @@ -69,11 +75,15 @@ SetDefaultProcessorVersionMetadata, SetDefaultProcessorVersionRequest, SetDefaultProcessorVersionResponse, + TrainProcessorVersionMetadata, + TrainProcessorVersionRequest, + TrainProcessorVersionResponse, UndeployProcessorVersionMetadata, UndeployProcessorVersionRequest, UndeployProcessorVersionResponse, ) from .types.document_schema import DocumentSchema +from .types.evaluation import Evaluation from .types.geometry import BoundingPoly, NormalizedVertex, Vertex from .types.operation_metadata import CommonOperationMetadata from .types.processor import Processor, ProcessorVersion @@ -106,14 +116,21 @@ "EnableProcessorMetadata", "EnableProcessorRequest", "EnableProcessorResponse", + "EvaluateProcessorVersionMetadata", + "EvaluateProcessorVersionRequest", + "EvaluateProcessorVersionResponse", + "Evaluation", "FetchProcessorTypesRequest", "FetchProcessorTypesResponse", "GcsDocument", "GcsDocuments", "GcsPrefix", + "GetEvaluationRequest", "GetProcessorRequest", "GetProcessorVersionRequest", "HumanReviewStatus", + "ListEvaluationsRequest", + "ListEvaluationsResponse", "ListProcessorTypesRequest", "ListProcessorTypesResponse", "ListProcessorVersionsRequest", @@ -133,6 +150,9 @@ "SetDefaultProcessorVersionMetadata", "SetDefaultProcessorVersionRequest", "SetDefaultProcessorVersionResponse", + "TrainProcessorVersionMetadata", + "TrainProcessorVersionRequest", + "TrainProcessorVersionResponse", "UndeployProcessorVersionMetadata", "UndeployProcessorVersionRequest", "UndeployProcessorVersionResponse", diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/gapic_metadata.json b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/gapic_metadata.json index 77ce70c074f7..c2f2d8797813 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/gapic_metadata.json +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/gapic_metadata.json @@ -45,11 +45,21 @@ "enable_processor" ] }, + "EvaluateProcessorVersion": { + "methods": [ + "evaluate_processor_version" + ] + }, "FetchProcessorTypes": { "methods": [ "fetch_processor_types" ] }, + "GetEvaluation": { + "methods": [ + "get_evaluation" + ] + }, "GetProcessor": { "methods": [ "get_processor" @@ -60,6 +70,11 @@ "get_processor_version" ] }, + "ListEvaluations": { + "methods": [ + "list_evaluations" + ] + }, "ListProcessorTypes": { "methods": [ "list_processor_types" @@ -90,6 +105,11 @@ "set_default_processor_version" ] }, + "TrainProcessorVersion": { + "methods": [ + "train_processor_version" + ] + }, "UndeployProcessorVersion": { "methods": [ "undeploy_processor_version" @@ -135,11 +155,21 @@ "enable_processor" ] }, + "EvaluateProcessorVersion": { + "methods": [ + "evaluate_processor_version" + ] + }, "FetchProcessorTypes": { "methods": [ "fetch_processor_types" ] }, + "GetEvaluation": { + "methods": [ + "get_evaluation" + ] + }, "GetProcessor": { "methods": [ "get_processor" @@ -150,6 +180,11 @@ "get_processor_version" ] }, + "ListEvaluations": { + "methods": [ + "list_evaluations" + ] + }, "ListProcessorTypes": { "methods": [ "list_processor_types" @@ -180,6 +215,11 @@ "set_default_processor_version" ] }, + "TrainProcessorVersion": { + "methods": [ + "train_processor_version" + ] + }, "UndeployProcessorVersion": { "methods": [ "undeploy_processor_version" diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/async_client.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/async_client.py index 4b43ccc4da25..54ab219e2afd 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/async_client.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/async_client.py @@ -49,7 +49,12 @@ from google.protobuf import timestamp_pb2 # type: ignore from google.cloud.documentai_v1beta3.services.document_processor_service import pagers -from google.cloud.documentai_v1beta3.types import document, document_processor_service +from google.cloud.documentai_v1beta3.types import ( + document, + document_processor_service, + document_schema, + evaluation, +) from google.cloud.documentai_v1beta3.types import processor from google.cloud.documentai_v1beta3.types import processor as gcd_processor from google.cloud.documentai_v1beta3.types import processor_type @@ -72,6 +77,10 @@ class DocumentProcessorServiceAsyncClient: DEFAULT_ENDPOINT = DocumentProcessorServiceClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = DocumentProcessorServiceClient.DEFAULT_MTLS_ENDPOINT + evaluation_path = staticmethod(DocumentProcessorServiceClient.evaluation_path) + parse_evaluation_path = staticmethod( + DocumentProcessorServiceClient.parse_evaluation_path + ) human_review_config_path = staticmethod( DocumentProcessorServiceClient.human_review_config_path ) @@ -965,6 +974,137 @@ async def sample_get_processor(): # Done; return the response. return response + async def train_processor_version( + self, + request: Optional[ + Union[document_processor_service.TrainProcessorVersionRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + processor_version: Optional[processor.ProcessorVersion] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Trains a new processor version. Operation metadata is returned + as cloud_documentai_core.TrainProcessorVersionMetadata. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import documentai_v1beta3 + + async def sample_train_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.TrainProcessorVersionRequest( + parent="parent_value", + ) + + # Make the request + operation = client.train_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1beta3.types.TrainProcessorVersionRequest, dict]]): + The request object. Request message for the create + processor version method. + parent (:class:`str`): + Required. The parent (project, location and processor) + to create the new version for. Format: + ``projects/{project}/locations/{location}/processors/{processor}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + processor_version (:class:`google.cloud.documentai_v1beta3.types.ProcessorVersion`): + Required. The processor version to be + created. + + This corresponds to the ``processor_version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.documentai_v1beta3.types.TrainProcessorVersionResponse` + The response for the TrainProcessorVersion method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, processor_version]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = document_processor_service.TrainProcessorVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if processor_version is not None: + request.processor_version = processor_version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.train_processor_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + document_processor_service.TrainProcessorVersionResponse, + metadata_type=document_processor_service.TrainProcessorVersionMetadata, + ) + + # Done; return the response. + return response + async def get_processor_version( self, request: Optional[ @@ -2247,6 +2387,354 @@ async def sample_review_document(): # Done; return the response. return response + async def evaluate_processor_version( + self, + request: Optional[ + Union[document_processor_service.EvaluateProcessorVersionRequest, dict] + ] = None, + *, + processor_version: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Evaluates a ProcessorVersion against annotated + documents, producing an Evaluation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import documentai_v1beta3 + + async def sample_evaluate_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.EvaluateProcessorVersionRequest( + processor_version="processor_version_value", + ) + + # Make the request + operation = client.evaluate_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1beta3.types.EvaluateProcessorVersionRequest, dict]]): + The request object. Evaluates the given ProcessorVersion + against the supplied documents. + processor_version (:class:`str`): + Required. The resource name of the + [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] + to evaluate. + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` + + This corresponds to the ``processor_version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.documentai_v1beta3.types.EvaluateProcessorVersionResponse` + Metadata of the EvaluateProcessorVersion method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([processor_version]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = document_processor_service.EvaluateProcessorVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if processor_version is not None: + request.processor_version = processor_version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.evaluate_processor_version, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("processor_version", request.processor_version),) + ), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + document_processor_service.EvaluateProcessorVersionResponse, + metadata_type=document_processor_service.EvaluateProcessorVersionMetadata, + ) + + # Done; return the response. + return response + + async def get_evaluation( + self, + request: Optional[ + Union[document_processor_service.GetEvaluationRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> evaluation.Evaluation: + r"""Retrieves a specific evaluation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import documentai_v1beta3 + + async def sample_get_evaluation(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.GetEvaluationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_evaluation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1beta3.types.GetEvaluationRequest, dict]]): + The request object. Retrieves a specific Evaluation. + name (:class:`str`): + Required. The resource name of the + [Evaluation][google.cloud.documentai.v1beta3.Evaluation] + to get. + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}/evaluations/{evaluation}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.documentai_v1beta3.types.Evaluation: + An evaluation of a ProcessorVersion's + performance. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = document_processor_service.GetEvaluationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_evaluation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_evaluations( + self, + request: Optional[ + Union[document_processor_service.ListEvaluationsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEvaluationsAsyncPager: + r"""Retrieves a set of evaluations for a given processor + version. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import documentai_v1beta3 + + async def sample_list_evaluations(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.ListEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.documentai_v1beta3.types.ListEvaluationsRequest, dict]]): + The request object. Retrieves a list of evaluations for + a given ProcessorVersion. + parent (:class:`str`): + Required. The resource name of the + [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] + to list evaluations for. + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.documentai_v1beta3.services.document_processor_service.pagers.ListEvaluationsAsyncPager: + The response from ListEvaluations. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = document_processor_service.ListEvaluationsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_evaluations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEvaluationsAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + async def list_operations( self, request: Optional[operations_pb2.ListOperationsRequest] = None, diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/client.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/client.py index 5b9545359f5e..acae0661ca8a 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/client.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/client.py @@ -53,7 +53,12 @@ from google.protobuf import timestamp_pb2 # type: ignore from google.cloud.documentai_v1beta3.services.document_processor_service import pagers -from google.cloud.documentai_v1beta3.types import document, document_processor_service +from google.cloud.documentai_v1beta3.types import ( + document, + document_processor_service, + document_schema, + evaluation, +) from google.cloud.documentai_v1beta3.types import processor from google.cloud.documentai_v1beta3.types import processor as gcd_processor from google.cloud.documentai_v1beta3.types import processor_type @@ -189,6 +194,32 @@ def transport(self) -> DocumentProcessorServiceTransport: """ return self._transport + @staticmethod + def evaluation_path( + project: str, + location: str, + processor: str, + processor_version: str, + evaluation: str, + ) -> str: + """Returns a fully-qualified evaluation string.""" + return "projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}/evaluations/{evaluation}".format( + project=project, + location=location, + processor=processor, + processor_version=processor_version, + evaluation=evaluation, + ) + + @staticmethod + def parse_evaluation_path(path: str) -> Dict[str, str]: + """Parses a evaluation path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/processors/(?P.+?)/processorVersions/(?P.+?)/evaluations/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def human_review_config_path( project: str, @@ -1219,6 +1250,139 @@ def sample_get_processor(): # Done; return the response. return response + def train_processor_version( + self, + request: Optional[ + Union[document_processor_service.TrainProcessorVersionRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + processor_version: Optional[processor.ProcessorVersion] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Trains a new processor version. Operation metadata is returned + as cloud_documentai_core.TrainProcessorVersionMetadata. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import documentai_v1beta3 + + def sample_train_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.TrainProcessorVersionRequest( + parent="parent_value", + ) + + # Make the request + operation = client.train_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1beta3.types.TrainProcessorVersionRequest, dict]): + The request object. Request message for the create + processor version method. + parent (str): + Required. The parent (project, location and processor) + to create the new version for. Format: + ``projects/{project}/locations/{location}/processors/{processor}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + processor_version (google.cloud.documentai_v1beta3.types.ProcessorVersion): + Required. The processor version to be + created. + + This corresponds to the ``processor_version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.documentai_v1beta3.types.TrainProcessorVersionResponse` + The response for the TrainProcessorVersion method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, processor_version]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a document_processor_service.TrainProcessorVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, document_processor_service.TrainProcessorVersionRequest + ): + request = document_processor_service.TrainProcessorVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if processor_version is not None: + request.processor_version = processor_version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.train_processor_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + document_processor_service.TrainProcessorVersionResponse, + metadata_type=document_processor_service.TrainProcessorVersionMetadata, + ) + + # Done; return the response. + return response + def get_processor_version( self, request: Optional[ @@ -2514,6 +2678,360 @@ def sample_review_document(): # Done; return the response. return response + def evaluate_processor_version( + self, + request: Optional[ + Union[document_processor_service.EvaluateProcessorVersionRequest, dict] + ] = None, + *, + processor_version: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Evaluates a ProcessorVersion against annotated + documents, producing an Evaluation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import documentai_v1beta3 + + def sample_evaluate_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.EvaluateProcessorVersionRequest( + processor_version="processor_version_value", + ) + + # Make the request + operation = client.evaluate_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1beta3.types.EvaluateProcessorVersionRequest, dict]): + The request object. Evaluates the given ProcessorVersion + against the supplied documents. + processor_version (str): + Required. The resource name of the + [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] + to evaluate. + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` + + This corresponds to the ``processor_version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.documentai_v1beta3.types.EvaluateProcessorVersionResponse` + Metadata of the EvaluateProcessorVersion method. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([processor_version]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a document_processor_service.EvaluateProcessorVersionRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, document_processor_service.EvaluateProcessorVersionRequest + ): + request = document_processor_service.EvaluateProcessorVersionRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if processor_version is not None: + request.processor_version = processor_version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.evaluate_processor_version + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("processor_version", request.processor_version),) + ), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + document_processor_service.EvaluateProcessorVersionResponse, + metadata_type=document_processor_service.EvaluateProcessorVersionMetadata, + ) + + # Done; return the response. + return response + + def get_evaluation( + self, + request: Optional[ + Union[document_processor_service.GetEvaluationRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> evaluation.Evaluation: + r"""Retrieves a specific evaluation. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import documentai_v1beta3 + + def sample_get_evaluation(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.GetEvaluationRequest( + name="name_value", + ) + + # Make the request + response = client.get_evaluation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.documentai_v1beta3.types.GetEvaluationRequest, dict]): + The request object. Retrieves a specific Evaluation. + name (str): + Required. The resource name of the + [Evaluation][google.cloud.documentai.v1beta3.Evaluation] + to get. + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}/evaluations/{evaluation}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.documentai_v1beta3.types.Evaluation: + An evaluation of a ProcessorVersion's + performance. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a document_processor_service.GetEvaluationRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document_processor_service.GetEvaluationRequest): + request = document_processor_service.GetEvaluationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_evaluation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_evaluations( + self, + request: Optional[ + Union[document_processor_service.ListEvaluationsRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEvaluationsPager: + r"""Retrieves a set of evaluations for a given processor + version. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import documentai_v1beta3 + + def sample_list_evaluations(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.ListEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.documentai_v1beta3.types.ListEvaluationsRequest, dict]): + The request object. Retrieves a list of evaluations for + a given ProcessorVersion. + parent (str): + Required. The resource name of the + [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] + to list evaluations for. + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.documentai_v1beta3.services.document_processor_service.pagers.ListEvaluationsPager: + The response from ListEvaluations. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a document_processor_service.ListEvaluationsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, document_processor_service.ListEvaluationsRequest): + request = document_processor_service.ListEvaluationsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_evaluations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEvaluationsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self): return self diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/pagers.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/pagers.py index 7c24a9d28533..00bc6c75c071 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/pagers.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/pagers.py @@ -26,6 +26,7 @@ from google.cloud.documentai_v1beta3.types import ( document_processor_service, + evaluation, processor, processor_type, ) @@ -427,3 +428,135 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEvaluationsPager: + """A pager for iterating through ``list_evaluations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.documentai_v1beta3.types.ListEvaluationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``evaluations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEvaluations`` requests and continue to iterate + through the ``evaluations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.documentai_v1beta3.types.ListEvaluationsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., document_processor_service.ListEvaluationsResponse], + request: document_processor_service.ListEvaluationsRequest, + response: document_processor_service.ListEvaluationsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.documentai_v1beta3.types.ListEvaluationsRequest): + The initial request object. + response (google.cloud.documentai_v1beta3.types.ListEvaluationsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = document_processor_service.ListEvaluationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[document_processor_service.ListEvaluationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[evaluation.Evaluation]: + for page in self.pages: + yield from page.evaluations + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEvaluationsAsyncPager: + """A pager for iterating through ``list_evaluations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.documentai_v1beta3.types.ListEvaluationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``evaluations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEvaluations`` requests and continue to iterate + through the ``evaluations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.documentai_v1beta3.types.ListEvaluationsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[document_processor_service.ListEvaluationsResponse] + ], + request: document_processor_service.ListEvaluationsRequest, + response: document_processor_service.ListEvaluationsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.documentai_v1beta3.types.ListEvaluationsRequest): + The initial request object. + response (google.cloud.documentai_v1beta3.types.ListEvaluationsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = document_processor_service.ListEvaluationsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[document_processor_service.ListEvaluationsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[evaluation.Evaluation]: + async def async_generator(): + async for page in self.pages: + for response in page.evaluations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/transports/base.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/transports/base.py index 51d32d840c49..92033dfd7dfc 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/transports/base.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/transports/base.py @@ -27,7 +27,7 @@ from google.oauth2 import service_account # type: ignore import pkg_resources -from google.cloud.documentai_v1beta3.types import document_processor_service +from google.cloud.documentai_v1beta3.types import document_processor_service, evaluation from google.cloud.documentai_v1beta3.types import processor from google.cloud.documentai_v1beta3.types import processor as gcd_processor @@ -181,6 +181,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.train_processor_version: gapic_v1.method.wrap_method( + self.train_processor_version, + default_timeout=None, + client_info=client_info, + ), self.get_processor_version: gapic_v1.method.wrap_method( self.get_processor_version, default_timeout=None, @@ -246,6 +251,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=120.0, client_info=client_info, ), + self.evaluate_processor_version: gapic_v1.method.wrap_method( + self.evaluate_processor_version, + default_timeout=None, + client_info=client_info, + ), + self.get_evaluation: gapic_v1.method.wrap_method( + self.get_evaluation, + default_timeout=None, + client_info=client_info, + ), + self.list_evaluations: gapic_v1.method.wrap_method( + self.list_evaluations, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -328,6 +348,15 @@ def get_processor( ]: raise NotImplementedError() + @property + def train_processor_version( + self, + ) -> Callable[ + [document_processor_service.TrainProcessorVersionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def get_processor_version( self, @@ -430,6 +459,36 @@ def review_document( ]: raise NotImplementedError() + @property + def evaluate_processor_version( + self, + ) -> Callable[ + [document_processor_service.EvaluateProcessorVersionRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_evaluation( + self, + ) -> Callable[ + [document_processor_service.GetEvaluationRequest], + Union[evaluation.Evaluation, Awaitable[evaluation.Evaluation]], + ]: + raise NotImplementedError() + + @property + def list_evaluations( + self, + ) -> Callable[ + [document_processor_service.ListEvaluationsRequest], + Union[ + document_processor_service.ListEvaluationsResponse, + Awaitable[document_processor_service.ListEvaluationsResponse], + ], + ]: + raise NotImplementedError() + @property def list_operations( self, diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc.py index 84ece01ac143..cc21ecc8a0f7 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc.py @@ -24,7 +24,7 @@ from google.longrunning import operations_pb2 # type: ignore import grpc # type: ignore -from google.cloud.documentai_v1beta3.types import document_processor_service +from google.cloud.documentai_v1beta3.types import document_processor_service, evaluation from google.cloud.documentai_v1beta3.types import processor from google.cloud.documentai_v1beta3.types import processor as gcd_processor @@ -425,6 +425,36 @@ def get_processor( ) return self._stubs["get_processor"] + @property + def train_processor_version( + self, + ) -> Callable[ + [document_processor_service.TrainProcessorVersionRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the train processor version method over gRPC. + + Trains a new processor version. Operation metadata is returned + as cloud_documentai_core.TrainProcessorVersionMetadata. + + Returns: + Callable[[~.TrainProcessorVersionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "train_processor_version" not in self._stubs: + self._stubs["train_processor_version"] = self.grpc_channel.unary_unary( + "/google.cloud.documentai.v1beta3.DocumentProcessorService/TrainProcessorVersion", + request_serializer=document_processor_service.TrainProcessorVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["train_processor_version"] + @property def get_processor_version( self, @@ -752,6 +782,94 @@ def review_document( ) return self._stubs["review_document"] + @property + def evaluate_processor_version( + self, + ) -> Callable[ + [document_processor_service.EvaluateProcessorVersionRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the evaluate processor version method over gRPC. + + Evaluates a ProcessorVersion against annotated + documents, producing an Evaluation. + + Returns: + Callable[[~.EvaluateProcessorVersionRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "evaluate_processor_version" not in self._stubs: + self._stubs["evaluate_processor_version"] = self.grpc_channel.unary_unary( + "/google.cloud.documentai.v1beta3.DocumentProcessorService/EvaluateProcessorVersion", + request_serializer=document_processor_service.EvaluateProcessorVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["evaluate_processor_version"] + + @property + def get_evaluation( + self, + ) -> Callable[ + [document_processor_service.GetEvaluationRequest], evaluation.Evaluation + ]: + r"""Return a callable for the get evaluation method over gRPC. + + Retrieves a specific evaluation. + + Returns: + Callable[[~.GetEvaluationRequest], + ~.Evaluation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_evaluation" not in self._stubs: + self._stubs["get_evaluation"] = self.grpc_channel.unary_unary( + "/google.cloud.documentai.v1beta3.DocumentProcessorService/GetEvaluation", + request_serializer=document_processor_service.GetEvaluationRequest.serialize, + response_deserializer=evaluation.Evaluation.deserialize, + ) + return self._stubs["get_evaluation"] + + @property + def list_evaluations( + self, + ) -> Callable[ + [document_processor_service.ListEvaluationsRequest], + document_processor_service.ListEvaluationsResponse, + ]: + r"""Return a callable for the list evaluations method over gRPC. + + Retrieves a set of evaluations for a given processor + version. + + Returns: + Callable[[~.ListEvaluationsRequest], + ~.ListEvaluationsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_evaluations" not in self._stubs: + self._stubs["list_evaluations"] = self.grpc_channel.unary_unary( + "/google.cloud.documentai.v1beta3.DocumentProcessorService/ListEvaluations", + request_serializer=document_processor_service.ListEvaluationsRequest.serialize, + response_deserializer=document_processor_service.ListEvaluationsResponse.deserialize, + ) + return self._stubs["list_evaluations"] + def close(self): self.grpc_channel.close() diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc_asyncio.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc_asyncio.py index b274c6335fa5..04d18b838189 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/services/document_processor_service/transports/grpc_asyncio.py @@ -24,7 +24,7 @@ import grpc # type: ignore from grpc.experimental import aio # type: ignore -from google.cloud.documentai_v1beta3.types import document_processor_service +from google.cloud.documentai_v1beta3.types import document_processor_service, evaluation from google.cloud.documentai_v1beta3.types import processor from google.cloud.documentai_v1beta3.types import processor as gcd_processor @@ -431,6 +431,36 @@ def get_processor( ) return self._stubs["get_processor"] + @property + def train_processor_version( + self, + ) -> Callable[ + [document_processor_service.TrainProcessorVersionRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the train processor version method over gRPC. + + Trains a new processor version. Operation metadata is returned + as cloud_documentai_core.TrainProcessorVersionMetadata. + + Returns: + Callable[[~.TrainProcessorVersionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "train_processor_version" not in self._stubs: + self._stubs["train_processor_version"] = self.grpc_channel.unary_unary( + "/google.cloud.documentai.v1beta3.DocumentProcessorService/TrainProcessorVersion", + request_serializer=document_processor_service.TrainProcessorVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["train_processor_version"] + @property def get_processor_version( self, @@ -763,6 +793,95 @@ def review_document( ) return self._stubs["review_document"] + @property + def evaluate_processor_version( + self, + ) -> Callable[ + [document_processor_service.EvaluateProcessorVersionRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the evaluate processor version method over gRPC. + + Evaluates a ProcessorVersion against annotated + documents, producing an Evaluation. + + Returns: + Callable[[~.EvaluateProcessorVersionRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "evaluate_processor_version" not in self._stubs: + self._stubs["evaluate_processor_version"] = self.grpc_channel.unary_unary( + "/google.cloud.documentai.v1beta3.DocumentProcessorService/EvaluateProcessorVersion", + request_serializer=document_processor_service.EvaluateProcessorVersionRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["evaluate_processor_version"] + + @property + def get_evaluation( + self, + ) -> Callable[ + [document_processor_service.GetEvaluationRequest], + Awaitable[evaluation.Evaluation], + ]: + r"""Return a callable for the get evaluation method over gRPC. + + Retrieves a specific evaluation. + + Returns: + Callable[[~.GetEvaluationRequest], + Awaitable[~.Evaluation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_evaluation" not in self._stubs: + self._stubs["get_evaluation"] = self.grpc_channel.unary_unary( + "/google.cloud.documentai.v1beta3.DocumentProcessorService/GetEvaluation", + request_serializer=document_processor_service.GetEvaluationRequest.serialize, + response_deserializer=evaluation.Evaluation.deserialize, + ) + return self._stubs["get_evaluation"] + + @property + def list_evaluations( + self, + ) -> Callable[ + [document_processor_service.ListEvaluationsRequest], + Awaitable[document_processor_service.ListEvaluationsResponse], + ]: + r"""Return a callable for the list evaluations method over gRPC. + + Retrieves a set of evaluations for a given processor + version. + + Returns: + Callable[[~.ListEvaluationsRequest], + Awaitable[~.ListEvaluationsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_evaluations" not in self._stubs: + self._stubs["list_evaluations"] = self.grpc_channel.unary_unary( + "/google.cloud.documentai.v1beta3.DocumentProcessorService/ListEvaluations", + request_serializer=document_processor_service.ListEvaluationsRequest.serialize, + response_deserializer=document_processor_service.ListEvaluationsResponse.deserialize, + ) + return self._stubs["list_evaluations"] + def close(self): return self.grpc_channel.close() diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/__init__.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/__init__.py index 2ed2cde6997b..b8a711e7c805 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/__init__.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/__init__.py @@ -41,11 +41,17 @@ EnableProcessorMetadata, EnableProcessorRequest, EnableProcessorResponse, + EvaluateProcessorVersionMetadata, + EvaluateProcessorVersionRequest, + EvaluateProcessorVersionResponse, FetchProcessorTypesRequest, FetchProcessorTypesResponse, + GetEvaluationRequest, GetProcessorRequest, GetProcessorVersionRequest, HumanReviewStatus, + ListEvaluationsRequest, + ListEvaluationsResponse, ListProcessorsRequest, ListProcessorsResponse, ListProcessorTypesRequest, @@ -60,11 +66,15 @@ SetDefaultProcessorVersionMetadata, SetDefaultProcessorVersionRequest, SetDefaultProcessorVersionResponse, + TrainProcessorVersionMetadata, + TrainProcessorVersionRequest, + TrainProcessorVersionResponse, UndeployProcessorVersionMetadata, UndeployProcessorVersionRequest, UndeployProcessorVersionResponse, ) from .document_schema import DocumentSchema +from .evaluation import Evaluation from .geometry import BoundingPoly, NormalizedVertex, Vertex from .operation_metadata import CommonOperationMetadata from .processor import Processor, ProcessorVersion @@ -96,11 +106,17 @@ "EnableProcessorMetadata", "EnableProcessorRequest", "EnableProcessorResponse", + "EvaluateProcessorVersionMetadata", + "EvaluateProcessorVersionRequest", + "EvaluateProcessorVersionResponse", "FetchProcessorTypesRequest", "FetchProcessorTypesResponse", + "GetEvaluationRequest", "GetProcessorRequest", "GetProcessorVersionRequest", "HumanReviewStatus", + "ListEvaluationsRequest", + "ListEvaluationsResponse", "ListProcessorsRequest", "ListProcessorsResponse", "ListProcessorTypesRequest", @@ -115,10 +131,14 @@ "SetDefaultProcessorVersionMetadata", "SetDefaultProcessorVersionRequest", "SetDefaultProcessorVersionResponse", + "TrainProcessorVersionMetadata", + "TrainProcessorVersionRequest", + "TrainProcessorVersionResponse", "UndeployProcessorVersionMetadata", "UndeployProcessorVersionRequest", "UndeployProcessorVersionResponse", "DocumentSchema", + "Evaluation", "BoundingPoly", "NormalizedVertex", "Vertex", diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/barcode.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/barcode.py index ca09a327363a..b14eaf1cd708 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/barcode.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/barcode.py @@ -30,25 +30,41 @@ class Barcode(proto.Message): Attributes: format_ (str): - Format of a barcode. The supported formats are: CODE_128: - Code 128 type. CODE_39: Code 39 type. CODE_93: Code 93 type. - CODABAR: Codabar type. DATA_MATRIX: 2D Data Matrix type. - ITF: ITF type. EAN_13: EAN-13 type. EAN_8: EAN-8 type. - QR_CODE: 2D QR code type. UPC_A: UPC-A type. UPC_E: UPC-E - type. PDF417: PDF417 type. AZTEC: 2D Aztec code type. - DATABAR: GS1 DataBar code type. + Format of a barcode. The supported formats are: + + - ``CODE_128``: Code 128 type. + - ``CODE_39``: Code 39 type. + - ``CODE_93``: Code 93 type. + - ``CODABAR``: Codabar type. + - ``DATA_MATRIX``: 2D Data Matrix type. + - ``ITF``: ITF type. + - ``EAN_13``: EAN-13 type. + - ``EAN_8``: EAN-8 type. + - ``QR_CODE``: 2D QR code type. + - ``UPC_A``: UPC-A type. + - ``UPC_E``: UPC-E type. + - ``PDF417``: PDF417 type. + - ``AZTEC``: 2D Aztec code type. + - ``DATABAR``: GS1 DataBar code type. value_format (str): Value format describes the format of the value that a - barcode encodes. The supported formats are: CONTACT_INFO: - Contact information. EMAIL: Email address. ISBN: ISBN - identifier. PHONE: Phone number. PRODUCT: Product. SMS: SMS - message. TEXT: Text string. URL: URL address. WIFI: Wifi - information. GEO: Geo-localization. CALENDAR_EVENT: Calendar - event. DRIVER_LICENSE: Driver's license. + barcode encodes. The supported formats are: + + - ``CONTACT_INFO``: Contact information. + - ``EMAIL``: Email address. + - ``ISBN``: ISBN identifier. + - ``PHONE``: Phone number. + - ``PRODUCT``: Product. + - ``SMS``: SMS message. + - ``TEXT``: Text string. + - ``URL``: URL address. + - ``WIFI``: Wifi information. + - ``GEO``: Geo-localization. + - ``CALENDAR_EVENT``: Calendar event. + - ``DRIVER_LICENSE``: Driver's license. raw_value (str): - Raw value encoded in the barcode. - For example, - 'MEBKM:TITLE:Google;URL:https://www.google.com;;'. + Raw value encoded in the barcode. For example: + ``'MEBKM:TITLE:Google;URL:https://www.google.com;;'``. """ format_: str = proto.Field( diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document.py index fc82558876b1..e7ec9877f79c 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document.py @@ -87,9 +87,10 @@ class Document(proto.Message): [Document.entities][google.cloud.documentai.v1beta3.Document.entities]. text_changes (MutableSequence[google.cloud.documentai_v1beta3.types.Document.TextChange]): Placeholder. A list of text corrections made to - [Document.text]. This is usually used for annotating - corrections to OCR mistakes. Text changes for a given - revision may not overlap with each other. + [Document.text][google.cloud.documentai.v1beta3.Document.text]. + This is usually used for annotating corrections to OCR + mistakes. Text changes for a given revision may not overlap + with each other. shard_info (google.cloud.documentai_v1beta3.types.Document.ShardInfo): Information about the sharding if this document is sharded part of a larger document. @@ -155,6 +156,9 @@ class Style(proto.Message): https://www.w3schools.com/cssref/pr_text_text-decoration.asp font_size (google.cloud.documentai_v1beta3.types.Document.Style.FontSize): Font size. + font_family (str): + Font family such as ``Arial``, ``Times New Roman``. + https://www.w3schools.com/cssref/pr_font_font-family.asp """ class FontSize(proto.Message): @@ -209,6 +213,10 @@ class FontSize(proto.Message): number=7, message="Document.Style.FontSize", ) + font_family: str = proto.Field( + proto.STRING, + number=8, + ) class Page(proto.Message): r"""A page in a [Document][google.cloud.documentai.v1beta3.Document]. @@ -268,6 +276,8 @@ class Page(proto.Message): page. detected_barcodes (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedBarcode]): A list of detected barcodes. + image_quality_scores (google.cloud.documentai_v1beta3.types.Document.Page.ImageQualityScores): + Image Quality Scores. provenance (google.cloud.documentai_v1beta3.types.Document.Provenance): The history of this page. """ @@ -376,7 +386,7 @@ class Layout(proto.Message): [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout] within context of the object this layout is for. e.g. confidence can be for a single token, a table, a visual - element, etc. depending on context. Range [0, 1]. + element, etc. depending on context. Range ``[0, 1]``. bounding_poly (google.cloud.documentai_v1beta3.types.BoundingPoly): The bounding polygon for the [Layout][google.cloud.documentai.v1beta3.Document.Page.Layout]. @@ -531,7 +541,7 @@ class Token(proto.Message): A list of detected languages together with confidence. provenance (google.cloud.documentai_v1beta3.types.Document.Provenance): - The history of this annotation. + The history of this annotation. """ class DetectedBreak(proto.Message): @@ -654,6 +664,8 @@ class Table(proto.Message): detected_languages (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.DetectedLanguage]): A list of detected languages together with confidence. + provenance (google.cloud.documentai_v1beta3.types.Document.Provenance): + The history of this table. """ class TableRow(proto.Message): @@ -736,6 +748,11 @@ class TableCell(proto.Message): number=4, message="Document.Page.DetectedLanguage", ) + provenance: "Document.Provenance" = proto.Field( + proto.MESSAGE, + number=5, + message="Document.Provenance", + ) class FormField(proto.Message): r"""A form field detected on the page. @@ -850,11 +867,11 @@ class DetectedLanguage(proto.Message): Attributes: language_code (str): - The BCP-47 language code, such as "en-US" or "sr-Latn". For - more information, see + The BCP-47 language code, such as ``en-US`` or ``sr-Latn``. + For more information, see https://www.unicode.org/reports/tr35/#Unicode_locale_identifier. confidence (float): - Confidence of detected language. Range [0, 1]. + Confidence of detected language. Range ``[0, 1]``. """ language_code: str = proto.Field( @@ -866,6 +883,58 @@ class DetectedLanguage(proto.Message): number=2, ) + class ImageQualityScores(proto.Message): + r"""Image Quality Scores for the page image + + Attributes: + quality_score (float): + The overall quality score. Range ``[0, 1]`` where 1 is + perfect quality. + detected_defects (MutableSequence[google.cloud.documentai_v1beta3.types.Document.Page.ImageQualityScores.DetectedDefect]): + A list of detected defects. + """ + + class DetectedDefect(proto.Message): + r"""Image Quality Defects + + Attributes: + type_ (str): + Name of the defect type. Supported values are: + + - ``quality/defect_blurry`` + - ``quality/defect_noisy`` + - ``quality/defect_dark`` + - ``quality/defect_faint`` + - ``quality/defect_text_too_small`` + - ``quality/defect_document_cutoff`` + - ``quality/defect_text_cutoff`` + - ``quality/defect_glare`` + confidence (float): + Confidence of detected defect. Range ``[0, 1]`` where 1 + indicates strong confidence of that the defect exists. + """ + + type_: str = proto.Field( + proto.STRING, + number=1, + ) + confidence: float = proto.Field( + proto.FLOAT, + number=2, + ) + + quality_score: float = proto.Field( + proto.FLOAT, + number=1, + ) + detected_defects: MutableSequence[ + "Document.Page.ImageQualityScores.DetectedDefect" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Document.Page.ImageQualityScores.DetectedDefect", + ) + page_number: int = proto.Field( proto.INT32, number=1, @@ -946,6 +1015,11 @@ class DetectedLanguage(proto.Message): number=15, message="Document.Page.DetectedBarcode", ) + image_quality_scores: "Document.Page.ImageQualityScores" = proto.Field( + proto.MESSAGE, + number=17, + message="Document.Page.ImageQualityScores", + ) provenance: "Document.Provenance" = proto.Field( proto.MESSAGE, number=16, @@ -965,14 +1039,13 @@ class Entity(proto.Message): type_ (str): Required. Entity type from a schema e.g. ``Address``. mention_text (str): - Optional. Text value in the document e.g. - ``1600 Amphitheatre Pkwy``. If the entity is not present in - the document, this field will be empty. + Optional. Text value of the entity e.g. + ``1600 Amphitheatre Pkwy``. mention_id (str): Optional. Deprecated. Use ``id`` field instead. confidence (float): - Optional. Confidence of detected Schema entity. Range [0, - 1]. + Optional. Confidence of detected Schema entity. Range + ``[0, 1]``. page_anchor (google.cloud.documentai_v1beta3.types.Document.PageAnchor): Optional. Represents the provenance of this entity wrt. the location on the page where it @@ -1270,7 +1343,7 @@ class PageRef(proto.Message): a layout element on the page. confidence (float): Optional. Confidence of detected page element, if - applicable. Range [0, 1]. + applicable. Range ``[0, 1]``. """ class LayoutType(proto.Enum): diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document_io.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document_io.py index 16a86eb92ee3..4edbf5ff83ce 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document_io.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document_io.py @@ -38,7 +38,8 @@ class RawDocument(proto.Message): Inline document content. mime_type (str): An IANA MIME type (RFC6838) indicating the nature and format - of the [content]. + of the + [content][google.cloud.documentai.v1beta3.RawDocument.content]. """ content: bytes = proto.Field( @@ -115,7 +116,7 @@ class BatchDocumentsInputConfig(proto.Message): Attributes: gcs_prefix (google.cloud.documentai_v1beta3.types.GcsPrefix): The set of documents that match the specified Cloud Storage - [gcs_prefix]. + ``gcs_prefix``. This field is a member of `oneof`_ ``source``. gcs_documents (google.cloud.documentai_v1beta3.types.GcsDocuments): diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document_processor_service.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document_processor_service.py index 0c2e75aab024..f7d74b576ffe 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document_processor_service.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document_processor_service.py @@ -23,6 +23,7 @@ from google.cloud.documentai_v1beta3.types import document_schema as gcd_document_schema from google.cloud.documentai_v1beta3.types import document as gcd_document from google.cloud.documentai_v1beta3.types import document_io +from google.cloud.documentai_v1beta3.types import evaluation as gcd_evaluation from google.cloud.documentai_v1beta3.types import operation_metadata from google.cloud.documentai_v1beta3.types import processor as gcd_processor from google.cloud.documentai_v1beta3.types import processor_type @@ -66,9 +67,18 @@ "SetDefaultProcessorVersionRequest", "SetDefaultProcessorVersionResponse", "SetDefaultProcessorVersionMetadata", + "TrainProcessorVersionRequest", + "TrainProcessorVersionResponse", + "TrainProcessorVersionMetadata", "ReviewDocumentRequest", "ReviewDocumentResponse", "ReviewDocumentOperationMetadata", + "EvaluateProcessorVersionRequest", + "EvaluateProcessorVersionMetadata", + "EvaluateProcessorVersionResponse", + "GetEvaluationRequest", + "ListEvaluationsRequest", + "ListEvaluationsResponse", }, ) @@ -111,8 +121,10 @@ class ProcessRequest(proto.Message): Whether Human Review feature should be skipped for this request. Default to false. field_mask (google.protobuf.field_mask_pb2.FieldMask): - Specifies which fields to include in - ProcessResponse's document. + Specifies which fields to include in ProcessResponse's + document. Only supports top level document and pages field + so it must be in the form of ``{document_field_name}`` or + ``pages.{page_field_name}``. """ inline_document: gcd_document.Document = proto.Field( @@ -959,6 +971,163 @@ class SetDefaultProcessorVersionMetadata(proto.Message): ) +class TrainProcessorVersionRequest(proto.Message): + r"""Request message for the create processor version method. + + Attributes: + parent (str): + Required. The parent (project, location and processor) to + create the new version for. Format: + ``projects/{project}/locations/{location}/processors/{processor}``. + processor_version (google.cloud.documentai_v1beta3.types.ProcessorVersion): + Required. The processor version to be + created. + document_schema (google.cloud.documentai_v1beta3.types.DocumentSchema): + Optional. The schema the processor version + will be trained with. + input_data (google.cloud.documentai_v1beta3.types.TrainProcessorVersionRequest.InputData): + Optional. The input data used to train the + ``ProcessorVersion``. + base_processor_version (str): + Optional. The processor version to use as a base for + training. This processor version must be a child of + ``parent``. Format: + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}``. + """ + + class InputData(proto.Message): + r"""The input data used to train a new ``ProcessorVersion``. + + Attributes: + training_documents (google.cloud.documentai_v1beta3.types.BatchDocumentsInputConfig): + The documents used for training the new + version. + test_documents (google.cloud.documentai_v1beta3.types.BatchDocumentsInputConfig): + The documents used for testing the trained + version. + """ + + training_documents: document_io.BatchDocumentsInputConfig = proto.Field( + proto.MESSAGE, + number=3, + message=document_io.BatchDocumentsInputConfig, + ) + test_documents: document_io.BatchDocumentsInputConfig = proto.Field( + proto.MESSAGE, + number=4, + message=document_io.BatchDocumentsInputConfig, + ) + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + processor_version: gcd_processor.ProcessorVersion = proto.Field( + proto.MESSAGE, + number=2, + message=gcd_processor.ProcessorVersion, + ) + document_schema: gcd_document_schema.DocumentSchema = proto.Field( + proto.MESSAGE, + number=10, + message=gcd_document_schema.DocumentSchema, + ) + input_data: InputData = proto.Field( + proto.MESSAGE, + number=4, + message=InputData, + ) + base_processor_version: str = proto.Field( + proto.STRING, + number=8, + ) + + +class TrainProcessorVersionResponse(proto.Message): + r"""The response for the TrainProcessorVersion method. + + Attributes: + processor_version (str): + The resource name of the processor version + produced by training. + """ + + processor_version: str = proto.Field( + proto.STRING, + number=1, + ) + + +class TrainProcessorVersionMetadata(proto.Message): + r"""The metadata that represents a processor version being + created. + + Attributes: + common_metadata (google.cloud.documentai_v1beta3.types.CommonOperationMetadata): + The basic metadata of the long running + operation. + training_dataset_validation (google.cloud.documentai_v1beta3.types.TrainProcessorVersionMetadata.DatasetValidation): + The training dataset validation information. + test_dataset_validation (google.cloud.documentai_v1beta3.types.TrainProcessorVersionMetadata.DatasetValidation): + The test dataset validation information. + """ + + class DatasetValidation(proto.Message): + r"""The dataset validation information. + This includes any and all errors with documents and the dataset. + + Attributes: + document_error_count (int): + The total number of document errors. + dataset_error_count (int): + The total number of dataset errors. + document_errors (MutableSequence[google.rpc.status_pb2.Status]): + Error information pertaining to specific + documents. A maximum of 10 document errors will + be returned. Any document with errors will not + be used throughout training. + dataset_errors (MutableSequence[google.rpc.status_pb2.Status]): + Error information for the dataset as a whole. + A maximum of 10 dataset errors will be returned. + A single dataset error is terminal for training. + """ + + document_error_count: int = proto.Field( + proto.INT32, + number=3, + ) + dataset_error_count: int = proto.Field( + proto.INT32, + number=4, + ) + document_errors: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=status_pb2.Status, + ) + dataset_errors: MutableSequence[status_pb2.Status] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + + common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( + proto.MESSAGE, + number=1, + message=operation_metadata.CommonOperationMetadata, + ) + training_dataset_validation: DatasetValidation = proto.Field( + proto.MESSAGE, + number=2, + message=DatasetValidation, + ) + test_dataset_validation: DatasetValidation = proto.Field( + proto.MESSAGE, + number=3, + message=DatasetValidation, + ) + + class ReviewDocumentRequest(proto.Message): r"""Request message for review document method. @@ -1116,4 +1285,138 @@ class State(proto.Enum): ) +class EvaluateProcessorVersionRequest(proto.Message): + r"""Evaluates the given ProcessorVersion against the supplied + documents. + + Attributes: + processor_version (str): + Required. The resource name of the + [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] + to evaluate. + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` + evaluation_documents (google.cloud.documentai_v1beta3.types.BatchDocumentsInputConfig): + Optional. The documents used in the + evaluation. If unspecified, use the processor's + dataset as evaluation input. + """ + + processor_version: str = proto.Field( + proto.STRING, + number=1, + ) + evaluation_documents: document_io.BatchDocumentsInputConfig = proto.Field( + proto.MESSAGE, + number=3, + message=document_io.BatchDocumentsInputConfig, + ) + + +class EvaluateProcessorVersionMetadata(proto.Message): + r"""Metadata of the EvaluateProcessorVersion method. + + Attributes: + common_metadata (google.cloud.documentai_v1beta3.types.CommonOperationMetadata): + The basic metadata of the long running + operation. + """ + + common_metadata: operation_metadata.CommonOperationMetadata = proto.Field( + proto.MESSAGE, + number=1, + message=operation_metadata.CommonOperationMetadata, + ) + + +class EvaluateProcessorVersionResponse(proto.Message): + r"""Metadata of the EvaluateProcessorVersion method. + + Attributes: + evaluation (str): + The resource name of the created evaluation. + """ + + evaluation: str = proto.Field( + proto.STRING, + number=2, + ) + + +class GetEvaluationRequest(proto.Message): + r"""Retrieves a specific Evaluation. + + Attributes: + name (str): + Required. The resource name of the + [Evaluation][google.cloud.documentai.v1beta3.Evaluation] to + get. + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}/evaluations/{evaluation}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListEvaluationsRequest(proto.Message): + r"""Retrieves a list of evaluations for a given ProcessorVersion. + + Attributes: + parent (str): + Required. The resource name of the + [ProcessorVersion][google.cloud.documentai.v1beta3.ProcessorVersion] + to list evaluations for. + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processorVersion}`` + page_size (int): + The standard list page size. + If unspecified, at most 5 evaluations will be + returned. The maximum value is 100; values above + 100 will be coerced to 100. + page_token (str): + A page token, received from a previous ``ListEvaluations`` + call. Provide this to retrieve the subsequent page. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListEvaluationsResponse(proto.Message): + r"""The response from ListEvaluations. + + Attributes: + evaluations (MutableSequence[google.cloud.documentai_v1beta3.types.Evaluation]): + The evaluations requested. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + evaluations: MutableSequence[gcd_evaluation.Evaluation] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=gcd_evaluation.Evaluation, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document_schema.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document_schema.py index d784a4c64edb..c2d47c6835e6 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document_schema.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/document_schema.py @@ -65,16 +65,16 @@ class EntityType(proto.Message): and cannot be a 'Common Type'. Besides that we use the following naming conventions: - - *use snake_casing* + - *use ``snake_casing``* - name matching is case-insensitive - Maximum 64 characters. - Must start with a letter. - Allowed characters: ASCII letters ``[a-z0-9_-]``. (For backward compatibility internal infrastructure and tooling can handle any ascii character) - - The '/' is sometimes used to denote a property of a type. - For example line_item/amount. This convention is - deprecated, but will still be honored for backward + - The ``/`` is sometimes used to denote a property of a + type. For example ``line_item/amount``. This convention + is deprecated, but will still be honored for backward compatibility. base_types (MutableSequence[str]): The entity type that this type is derived diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/evaluation.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/evaluation.py new file mode 100644 index 000000000000..c0cd3b61583a --- /dev/null +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/evaluation.py @@ -0,0 +1,290 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.documentai.v1beta3", + manifest={ + "Evaluation", + }, +) + + +class Evaluation(proto.Message): + r"""An evaluation of a ProcessorVersion's performance. + + Attributes: + name (str): + The resource name of the evaluation. Format: + ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}/evaluations/{evaluation}`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + The time that the evaluation was created. + document_counters (google.cloud.documentai_v1beta3.types.Evaluation.Counters): + Counters for the documents used in the + evaluation. + all_entities_metrics (google.cloud.documentai_v1beta3.types.Evaluation.MultiConfidenceMetrics): + Metrics for all the entities in aggregate. + entity_metrics (MutableMapping[str, google.cloud.documentai_v1beta3.types.Evaluation.MultiConfidenceMetrics]): + Metrics across confidence levels, for + different entities. + kms_key_name (str): + The KMS key name used for encryption. + kms_key_version_name (str): + The KMS key version with which data is + encrypted. + """ + + class Counters(proto.Message): + r"""Evaluation counters for the documents that were used. + + Attributes: + input_documents_count (int): + How many documents were sent for evaluation. + invalid_documents_count (int): + How many documents were not included in the + evaluation as they didn't pass validation. + failed_documents_count (int): + How many documents were not included in the + evaluation as Document AI failed to process + them. + evaluated_documents_count (int): + How many documents were used in the + evaluation. + """ + + input_documents_count: int = proto.Field( + proto.INT32, + number=1, + ) + invalid_documents_count: int = proto.Field( + proto.INT32, + number=2, + ) + failed_documents_count: int = proto.Field( + proto.INT32, + number=3, + ) + evaluated_documents_count: int = proto.Field( + proto.INT32, + number=4, + ) + + class Metrics(proto.Message): + r"""Evaluation metrics, either in aggregate or about a specific + entity. + + Attributes: + precision (float): + The calculated precision. + recall (float): + The calculated recall. + f1_score (float): + The calculated f1 score. + predicted_occurrences_count (int): + The amount of occurrences in predicted + documents. + ground_truth_occurrences_count (int): + The amount of occurrences in ground truth + documents. + predicted_document_count (int): + The amount of documents with a predicted + occurrence. + ground_truth_document_count (int): + The amount of documents with a ground truth + occurrence. + true_positives_count (int): + The amount of true positives. + false_positives_count (int): + The amount of false positives. + false_negatives_count (int): + The amount of false negatives. + total_documents_count (int): + The amount of documents that had an + occurrence of this label. + """ + + precision: float = proto.Field( + proto.FLOAT, + number=1, + ) + recall: float = proto.Field( + proto.FLOAT, + number=2, + ) + f1_score: float = proto.Field( + proto.FLOAT, + number=3, + ) + predicted_occurrences_count: int = proto.Field( + proto.INT32, + number=4, + ) + ground_truth_occurrences_count: int = proto.Field( + proto.INT32, + number=5, + ) + predicted_document_count: int = proto.Field( + proto.INT32, + number=10, + ) + ground_truth_document_count: int = proto.Field( + proto.INT32, + number=11, + ) + true_positives_count: int = proto.Field( + proto.INT32, + number=6, + ) + false_positives_count: int = proto.Field( + proto.INT32, + number=7, + ) + false_negatives_count: int = proto.Field( + proto.INT32, + number=8, + ) + total_documents_count: int = proto.Field( + proto.INT32, + number=9, + ) + + class ConfidenceLevelMetrics(proto.Message): + r"""Evaluations metrics, at a specific confidence level. + + Attributes: + confidence_level (float): + The confidence level. + metrics (google.cloud.documentai_v1beta3.types.Evaluation.Metrics): + The metrics at the specific confidence level. + """ + + confidence_level: float = proto.Field( + proto.FLOAT, + number=1, + ) + metrics: "Evaluation.Metrics" = proto.Field( + proto.MESSAGE, + number=2, + message="Evaluation.Metrics", + ) + + class MultiConfidenceMetrics(proto.Message): + r"""Metrics across multiple confidence levels. + + Attributes: + confidence_level_metrics (MutableSequence[google.cloud.documentai_v1beta3.types.Evaluation.ConfidenceLevelMetrics]): + Metrics across confidence levels with fuzzy + matching enabled. + confidence_level_metrics_exact (MutableSequence[google.cloud.documentai_v1beta3.types.Evaluation.ConfidenceLevelMetrics]): + Metrics across confidence levels with only + exact matching. + auprc (float): + The calculated area under the precision + recall curve (AUPRC), computed by integrating + over all confidence thresholds. + estimated_calibration_error (float): + The Estimated Calibration Error (ECE) of the + confidence of the predicted entities. + auprc_exact (float): + The AUPRC for metrics with fuzzy matching + disabled, i.e., exact matching only. + estimated_calibration_error_exact (float): + The ECE for the predicted entities with fuzzy + matching disabled, i.e., exact matching only. + metrics_type (google.cloud.documentai_v1beta3.types.Evaluation.MultiConfidenceMetrics.MetricsType): + The metrics type for the label. + """ + + class MetricsType(proto.Enum): + r"""A type that determines how metrics should be interpreted.""" + METRICS_TYPE_UNSPECIFIED = 0 + AGGREGATE = 1 + + confidence_level_metrics: MutableSequence[ + "Evaluation.ConfidenceLevelMetrics" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Evaluation.ConfidenceLevelMetrics", + ) + confidence_level_metrics_exact: MutableSequence[ + "Evaluation.ConfidenceLevelMetrics" + ] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="Evaluation.ConfidenceLevelMetrics", + ) + auprc: float = proto.Field( + proto.FLOAT, + number=2, + ) + estimated_calibration_error: float = proto.Field( + proto.FLOAT, + number=3, + ) + auprc_exact: float = proto.Field( + proto.FLOAT, + number=5, + ) + estimated_calibration_error_exact: float = proto.Field( + proto.FLOAT, + number=6, + ) + metrics_type: "Evaluation.MultiConfidenceMetrics.MetricsType" = proto.Field( + proto.ENUM, + number=7, + enum="Evaluation.MultiConfidenceMetrics.MetricsType", + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + document_counters: Counters = proto.Field( + proto.MESSAGE, + number=5, + message=Counters, + ) + all_entities_metrics: MultiConfidenceMetrics = proto.Field( + proto.MESSAGE, + number=3, + message=MultiConfidenceMetrics, + ) + entity_metrics: MutableMapping[str, MultiConfidenceMetrics] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=4, + message=MultiConfidenceMetrics, + ) + kms_key_name: str = proto.Field( + proto.STRING, + number=6, + ) + kms_key_version_name: str = proto.Field( + proto.STRING, + number=7, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/processor.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/processor.py index 7a46f2219994..c0510d67cb8c 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/processor.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/processor.py @@ -18,6 +18,8 @@ from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore +from google.cloud.documentai_v1beta3.types import document_schema as gcd_document_schema + __protobuf__ = proto.module( package="google.cloud.documentai.v1beta3", manifest={ @@ -41,6 +43,9 @@ class ProcessorVersion(proto.Message): ``projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}`` display_name (str): The display name of the processor version. + document_schema (google.cloud.documentai_v1beta3.types.DocumentSchema): + The schema of the processor version. + Describes the output. state (google.cloud.documentai_v1beta3.types.ProcessorVersion.State): The state of the processor version. create_time (google.protobuf.timestamp_pb2.Timestamp): @@ -100,6 +105,11 @@ class DeprecationInfo(proto.Message): proto.STRING, number=2, ) + document_schema: gcd_document_schema.DocumentSchema = proto.Field( + proto.MESSAGE, + number=12, + message=gcd_document_schema.DocumentSchema, + ) state: State = proto.Field( proto.ENUM, number=6, @@ -139,8 +149,9 @@ class Processor(proto.Message): Format: ``projects/{project}/locations/{location}/processors/{processor}`` type_ (str): - The processor type, e.g., OCR_PROCESSOR, INVOICE_PROCESSOR, - etc. To get a list of processors types, see + The processor type, e.g., ``OCR_PROCESSOR``, + ``INVOICE_PROCESSOR``, etc. To get a list of processors + types, see [FetchProcessorTypes][google.cloud.documentai.v1beta3.DocumentProcessorService.FetchProcessorTypes]. display_name (str): The display name of the processor. diff --git a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/processor_type.py b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/processor_type.py index ad034b5ed27a..7f62cdb7792e 100644 --- a/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/processor_type.py +++ b/packages/google-cloud-documentai/google/cloud/documentai_v1beta3/types/processor_type.py @@ -33,9 +33,10 @@ class ProcessorType(proto.Message): Attributes: name (str): The resource name of the processor type. Format: - projects/{project}/processorTypes/{processor_type} + ``projects/{project}/processorTypes/{processor_type}`` type_ (str): - The type of the processor, e.g., "invoice_parsing". + The processor type, e.g., ``OCR_PROCESSOR``, + ``INVOICE_PROCESSOR``, etc. category (str): The processor category, used by UI to group processor types. diff --git a/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_async.py b/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_async.py new file mode 100644 index 000000000000..4d8177fc8155 --- /dev/null +++ b/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for EvaluateProcessorVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-documentai + + +# [START documentai_v1beta3_generated_DocumentProcessorService_EvaluateProcessorVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import documentai_v1beta3 + + +async def sample_evaluate_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.EvaluateProcessorVersionRequest( + processor_version="processor_version_value", + ) + + # Make the request + operation = client.evaluate_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_EvaluateProcessorVersion_async] diff --git a/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_sync.py b/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_sync.py new file mode 100644 index 000000000000..fb73099354e9 --- /dev/null +++ b/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for EvaluateProcessorVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-documentai + + +# [START documentai_v1beta3_generated_DocumentProcessorService_EvaluateProcessorVersion_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import documentai_v1beta3 + + +def sample_evaluate_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.EvaluateProcessorVersionRequest( + processor_version="processor_version_value", + ) + + # Make the request + operation = client.evaluate_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_EvaluateProcessorVersion_sync] diff --git a/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_async.py b/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_async.py new file mode 100644 index 000000000000..c2306172cb61 --- /dev/null +++ b/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-documentai + + +# [START documentai_v1beta3_generated_DocumentProcessorService_GetEvaluation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import documentai_v1beta3 + + +async def sample_get_evaluation(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.GetEvaluationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_evaluation(request=request) + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_GetEvaluation_async] diff --git a/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_sync.py b/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_sync.py new file mode 100644 index 000000000000..d126b6bd35eb --- /dev/null +++ b/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_get_evaluation_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEvaluation +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-documentai + + +# [START documentai_v1beta3_generated_DocumentProcessorService_GetEvaluation_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import documentai_v1beta3 + + +def sample_get_evaluation(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.GetEvaluationRequest( + name="name_value", + ) + + # Make the request + response = client.get_evaluation(request=request) + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_GetEvaluation_sync] diff --git a/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_async.py b/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_async.py new file mode 100644 index 000000000000..be38a0059e59 --- /dev/null +++ b/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvaluations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-documentai + + +# [START documentai_v1beta3_generated_DocumentProcessorService_ListEvaluations_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import documentai_v1beta3 + + +async def sample_list_evaluations(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.ListEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluations(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_ListEvaluations_async] diff --git a/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_sync.py b/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_sync.py new file mode 100644 index 000000000000..3849d890120e --- /dev/null +++ b/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_list_evaluations_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEvaluations +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-documentai + + +# [START documentai_v1beta3_generated_DocumentProcessorService_ListEvaluations_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import documentai_v1beta3 + + +def sample_list_evaluations(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.ListEvaluationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_evaluations(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_ListEvaluations_sync] diff --git a/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_async.py b/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_async.py new file mode 100644 index 000000000000..38c225e29a23 --- /dev/null +++ b/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TrainProcessorVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-documentai + + +# [START documentai_v1beta3_generated_DocumentProcessorService_TrainProcessorVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import documentai_v1beta3 + + +async def sample_train_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceAsyncClient() + + # Initialize request argument(s) + request = documentai_v1beta3.TrainProcessorVersionRequest( + parent="parent_value", + ) + + # Make the request + operation = client.train_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_TrainProcessorVersion_async] diff --git a/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_sync.py b/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_sync.py new file mode 100644 index 000000000000..3d9fa4ea4812 --- /dev/null +++ b/packages/google-cloud-documentai/samples/generated_samples/documentai_v1beta3_generated_document_processor_service_train_processor_version_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for TrainProcessorVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-documentai + + +# [START documentai_v1beta3_generated_DocumentProcessorService_TrainProcessorVersion_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import documentai_v1beta3 + + +def sample_train_processor_version(): + # Create a client + client = documentai_v1beta3.DocumentProcessorServiceClient() + + # Initialize request argument(s) + request = documentai_v1beta3.TrainProcessorVersionRequest( + parent="parent_value", + ) + + # Make the request + operation = client.train_processor_version(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END documentai_v1beta3_generated_DocumentProcessorService_TrainProcessorVersion_sync] diff --git a/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json b/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json index 74c31699c6c7..e88607d518f5 100644 --- a/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json +++ b/packages/google-cloud-documentai/samples/generated_samples/snippet_metadata_google.cloud.documentai.v1beta3.json @@ -1130,6 +1130,167 @@ ], "title": "documentai_v1beta3_generated_document_processor_service_enable_processor_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.evaluate_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.EvaluateProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "EvaluateProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.EvaluateProcessorVersionRequest" + }, + { + "name": "processor_version", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "evaluate_processor_version" + }, + "description": "Sample for EvaluateProcessorVersion", + "file": "documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_EvaluateProcessorVersion_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.evaluate_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.EvaluateProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "EvaluateProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.EvaluateProcessorVersionRequest" + }, + { + "name": "processor_version", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "evaluate_processor_version" + }, + "description": "Sample for EvaluateProcessorVersion", + "file": "documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_EvaluateProcessorVersion_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta3_generated_document_processor_service_evaluate_processor_version_sync.py" + }, { "canonical": true, "clientMethod": { @@ -1172,11 +1333,333 @@ "resultType": "google.cloud.documentai_v1beta3.types.FetchProcessorTypesResponse", "shortName": "fetch_processor_types" }, - "description": "Sample for FetchProcessorTypes", - "file": "documentai_v1beta3_generated_document_processor_service_fetch_processor_types_async.py", + "description": "Sample for FetchProcessorTypes", + "file": "documentai_v1beta3_generated_document_processor_service_fetch_processor_types_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_FetchProcessorTypes_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta3_generated_document_processor_service_fetch_processor_types_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.fetch_processor_types", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.FetchProcessorTypes", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "FetchProcessorTypes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.FetchProcessorTypesRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.documentai_v1beta3.types.FetchProcessorTypesResponse", + "shortName": "fetch_processor_types" + }, + "description": "Sample for FetchProcessorTypes", + "file": "documentai_v1beta3_generated_document_processor_service_fetch_processor_types_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_FetchProcessorTypes_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta3_generated_document_processor_service_fetch_processor_types_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.get_evaluation", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetEvaluation", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "GetEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.GetEvaluationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.documentai_v1beta3.types.Evaluation", + "shortName": "get_evaluation" + }, + "description": "Sample for GetEvaluation", + "file": "documentai_v1beta3_generated_document_processor_service_get_evaluation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetEvaluation_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta3_generated_document_processor_service_get_evaluation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.get_evaluation", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetEvaluation", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "GetEvaluation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.GetEvaluationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.documentai_v1beta3.types.Evaluation", + "shortName": "get_evaluation" + }, + "description": "Sample for GetEvaluation", + "file": "documentai_v1beta3_generated_document_processor_service_get_evaluation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetEvaluation_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta3_generated_document_processor_service_get_evaluation_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.get_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "GetProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.GetProcessorVersionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.documentai_v1beta3.types.ProcessorVersion", + "shortName": "get_processor_version" + }, + "description": "Sample for GetProcessorVersion", + "file": "documentai_v1beta3_generated_document_processor_service_get_processor_version_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_FetchProcessorTypes_async", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetProcessorVersion_async", "segments": [ { "end": 51, @@ -1209,7 +1692,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "documentai_v1beta3_generated_document_processor_service_fetch_processor_types_async.py" + "title": "documentai_v1beta3_generated_document_processor_service_get_processor_version_async.py" }, { "canonical": true, @@ -1218,22 +1701,22 @@ "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", "shortName": "DocumentProcessorServiceClient" }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.fetch_processor_types", + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.get_processor_version", "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.FetchProcessorTypes", + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessorVersion", "service": { "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", "shortName": "DocumentProcessorService" }, - "shortName": "FetchProcessorTypes" + "shortName": "GetProcessorVersion" }, "parameters": [ { "name": "request", - "type": "google.cloud.documentai_v1beta3.types.FetchProcessorTypesRequest" + "type": "google.cloud.documentai_v1beta3.types.GetProcessorVersionRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -1249,14 +1732,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.documentai_v1beta3.types.FetchProcessorTypesResponse", - "shortName": "fetch_processor_types" + "resultType": "google.cloud.documentai_v1beta3.types.ProcessorVersion", + "shortName": "get_processor_version" }, - "description": "Sample for FetchProcessorTypes", - "file": "documentai_v1beta3_generated_document_processor_service_fetch_processor_types_sync.py", + "description": "Sample for GetProcessorVersion", + "file": "documentai_v1beta3_generated_document_processor_service_get_processor_version_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_FetchProcessorTypes_sync", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetProcessorVersion_sync", "segments": [ { "end": 51, @@ -1289,7 +1772,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "documentai_v1beta3_generated_document_processor_service_fetch_processor_types_sync.py" + "title": "documentai_v1beta3_generated_document_processor_service_get_processor_version_sync.py" }, { "canonical": true, @@ -1299,19 +1782,19 @@ "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", "shortName": "DocumentProcessorServiceAsyncClient" }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.get_processor_version", + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.get_processor", "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessorVersion", + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessor", "service": { "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", "shortName": "DocumentProcessorService" }, - "shortName": "GetProcessorVersion" + "shortName": "GetProcessor" }, "parameters": [ { "name": "request", - "type": "google.cloud.documentai_v1beta3.types.GetProcessorVersionRequest" + "type": "google.cloud.documentai_v1beta3.types.GetProcessorRequest" }, { "name": "name", @@ -1330,14 +1813,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.documentai_v1beta3.types.ProcessorVersion", - "shortName": "get_processor_version" + "resultType": "google.cloud.documentai_v1beta3.types.Processor", + "shortName": "get_processor" }, - "description": "Sample for GetProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_get_processor_version_async.py", + "description": "Sample for GetProcessor", + "file": "documentai_v1beta3_generated_document_processor_service_get_processor_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetProcessorVersion_async", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetProcessor_async", "segments": [ { "end": 51, @@ -1370,7 +1853,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "documentai_v1beta3_generated_document_processor_service_get_processor_version_async.py" + "title": "documentai_v1beta3_generated_document_processor_service_get_processor_async.py" }, { "canonical": true, @@ -1379,19 +1862,19 @@ "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", "shortName": "DocumentProcessorServiceClient" }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.get_processor_version", + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.get_processor", "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessorVersion", + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessor", "service": { "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", "shortName": "DocumentProcessorService" }, - "shortName": "GetProcessorVersion" + "shortName": "GetProcessor" }, "parameters": [ { "name": "request", - "type": "google.cloud.documentai_v1beta3.types.GetProcessorVersionRequest" + "type": "google.cloud.documentai_v1beta3.types.GetProcessorRequest" }, { "name": "name", @@ -1410,14 +1893,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.documentai_v1beta3.types.ProcessorVersion", - "shortName": "get_processor_version" + "resultType": "google.cloud.documentai_v1beta3.types.Processor", + "shortName": "get_processor" }, - "description": "Sample for GetProcessorVersion", - "file": "documentai_v1beta3_generated_document_processor_service_get_processor_version_sync.py", + "description": "Sample for GetProcessor", + "file": "documentai_v1beta3_generated_document_processor_service_get_processor_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetProcessorVersion_sync", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetProcessor_sync", "segments": [ { "end": 51, @@ -1450,7 +1933,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "documentai_v1beta3_generated_document_processor_service_get_processor_version_sync.py" + "title": "documentai_v1beta3_generated_document_processor_service_get_processor_sync.py" }, { "canonical": true, @@ -1460,22 +1943,22 @@ "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", "shortName": "DocumentProcessorServiceAsyncClient" }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.get_processor", + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.list_evaluations", "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessor", + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListEvaluations", "service": { "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", "shortName": "DocumentProcessorService" }, - "shortName": "GetProcessor" + "shortName": "ListEvaluations" }, "parameters": [ { "name": "request", - "type": "google.cloud.documentai_v1beta3.types.GetProcessorRequest" + "type": "google.cloud.documentai_v1beta3.types.ListEvaluationsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -1491,22 +1974,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.documentai_v1beta3.types.Processor", - "shortName": "get_processor" + "resultType": "google.cloud.documentai_v1beta3.services.document_processor_service.pagers.ListEvaluationsAsyncPager", + "shortName": "list_evaluations" }, - "description": "Sample for GetProcessor", - "file": "documentai_v1beta3_generated_document_processor_service_get_processor_async.py", + "description": "Sample for ListEvaluations", + "file": "documentai_v1beta3_generated_document_processor_service_list_evaluations_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetProcessor_async", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListEvaluations_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1526,12 +2009,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "documentai_v1beta3_generated_document_processor_service_get_processor_async.py" + "title": "documentai_v1beta3_generated_document_processor_service_list_evaluations_async.py" }, { "canonical": true, @@ -1540,22 +2023,22 @@ "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", "shortName": "DocumentProcessorServiceClient" }, - "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.get_processor", + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.list_evaluations", "method": { - "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.GetProcessor", + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.ListEvaluations", "service": { "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", "shortName": "DocumentProcessorService" }, - "shortName": "GetProcessor" + "shortName": "ListEvaluations" }, "parameters": [ { "name": "request", - "type": "google.cloud.documentai_v1beta3.types.GetProcessorRequest" + "type": "google.cloud.documentai_v1beta3.types.ListEvaluationsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -1571,22 +2054,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.documentai_v1beta3.types.Processor", - "shortName": "get_processor" + "resultType": "google.cloud.documentai_v1beta3.services.document_processor_service.pagers.ListEvaluationsPager", + "shortName": "list_evaluations" }, - "description": "Sample for GetProcessor", - "file": "documentai_v1beta3_generated_document_processor_service_get_processor_sync.py", + "description": "Sample for ListEvaluations", + "file": "documentai_v1beta3_generated_document_processor_service_list_evaluations_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_GetProcessor_sync", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_ListEvaluations_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1606,12 +2089,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "documentai_v1beta3_generated_document_processor_service_get_processor_sync.py" + "title": "documentai_v1beta3_generated_document_processor_service_list_evaluations_sync.py" }, { "canonical": true, @@ -2571,6 +3054,175 @@ ], "title": "documentai_v1beta3_generated_document_processor_service_set_default_processor_version_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient", + "shortName": "DocumentProcessorServiceAsyncClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceAsyncClient.train_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.TrainProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "TrainProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.TrainProcessorVersionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "processor_version", + "type": "google.cloud.documentai_v1beta3.types.ProcessorVersion" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "train_processor_version" + }, + "description": "Sample for TrainProcessorVersion", + "file": "documentai_v1beta3_generated_document_processor_service_train_processor_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_TrainProcessorVersion_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta3_generated_document_processor_service_train_processor_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient", + "shortName": "DocumentProcessorServiceClient" + }, + "fullName": "google.cloud.documentai_v1beta3.DocumentProcessorServiceClient.train_processor_version", + "method": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService.TrainProcessorVersion", + "service": { + "fullName": "google.cloud.documentai.v1beta3.DocumentProcessorService", + "shortName": "DocumentProcessorService" + }, + "shortName": "TrainProcessorVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.documentai_v1beta3.types.TrainProcessorVersionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "processor_version", + "type": "google.cloud.documentai_v1beta3.types.ProcessorVersion" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "train_processor_version" + }, + "description": "Sample for TrainProcessorVersion", + "file": "documentai_v1beta3_generated_document_processor_service_train_processor_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "documentai_v1beta3_generated_DocumentProcessorService_TrainProcessorVersion_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "documentai_v1beta3_generated_document_processor_service_train_processor_version_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-documentai/scripts/fixup_documentai_v1beta3_keywords.py b/packages/google-cloud-documentai/scripts/fixup_documentai_v1beta3_keywords.py index 494d085514d5..31eecd92d58c 100644 --- a/packages/google-cloud-documentai/scripts/fixup_documentai_v1beta3_keywords.py +++ b/packages/google-cloud-documentai/scripts/fixup_documentai_v1beta3_keywords.py @@ -46,15 +46,19 @@ class documentaiCallTransformer(cst.CSTTransformer): 'deploy_processor_version': ('name', ), 'disable_processor': ('name', ), 'enable_processor': ('name', ), + 'evaluate_processor_version': ('processor_version', 'evaluation_documents', ), 'fetch_processor_types': ('parent', ), + 'get_evaluation': ('name', ), 'get_processor': ('name', ), 'get_processor_version': ('name', ), + 'list_evaluations': ('parent', 'page_size', 'page_token', ), 'list_processors': ('parent', 'page_size', 'page_token', ), 'list_processor_types': ('parent', 'page_size', 'page_token', ), 'list_processor_versions': ('parent', 'page_size', 'page_token', ), 'process_document': ('name', 'inline_document', 'raw_document', 'document', 'skip_human_review', 'field_mask', ), 'review_document': ('human_review_config', 'inline_document', 'document', 'enable_schema_validation', 'priority', 'document_schema', ), 'set_default_processor_version': ('processor', 'default_processor_version', ), + 'train_processor_version': ('parent', 'processor_version', 'document_schema', 'input_data', 'base_processor_version', ), 'undeploy_processor_version': ('name', ), } diff --git a/packages/google-cloud-documentai/tests/unit/gapic/documentai_v1beta3/test_document_processor_service.py b/packages/google-cloud-documentai/tests/unit/gapic/documentai_v1beta3/test_document_processor_service.py index 41efd4dda865..9d4c63ce4d64 100644 --- a/packages/google-cloud-documentai/tests/unit/gapic/documentai_v1beta3/test_document_processor_service.py +++ b/packages/google-cloud-documentai/tests/unit/gapic/documentai_v1beta3/test_document_processor_service.py @@ -72,6 +72,7 @@ document_io, document_processor_service, document_schema, + evaluation, geometry, ) from google.cloud.documentai_v1beta3.types import processor @@ -2575,6 +2576,257 @@ async def test_get_processor_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + document_processor_service.TrainProcessorVersionRequest, + dict, + ], +) +def test_train_processor_version(request_type, transport: str = "grpc"): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_processor_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.train_processor_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.TrainProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_train_processor_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_processor_version), "__call__" + ) as call: + client.train_processor_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.TrainProcessorVersionRequest() + + +@pytest.mark.asyncio +async def test_train_processor_version_async( + transport: str = "grpc_asyncio", + request_type=document_processor_service.TrainProcessorVersionRequest, +): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_processor_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.train_processor_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.TrainProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_train_processor_version_async_from_dict(): + await test_train_processor_version_async(request_type=dict) + + +def test_train_processor_version_field_headers(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_processor_service.TrainProcessorVersionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_processor_version), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.train_processor_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_train_processor_version_field_headers_async(): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_processor_service.TrainProcessorVersionRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_processor_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.train_processor_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_train_processor_version_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_processor_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.train_processor_version( + parent="parent_value", + processor_version=processor.ProcessorVersion(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].processor_version + mock_val = processor.ProcessorVersion(name="name_value") + assert arg == mock_val + + +def test_train_processor_version_flattened_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.train_processor_version( + document_processor_service.TrainProcessorVersionRequest(), + parent="parent_value", + processor_version=processor.ProcessorVersion(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_train_processor_version_flattened_async(): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.train_processor_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.train_processor_version( + parent="parent_value", + processor_version=processor.ProcessorVersion(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].processor_version + mock_val = processor.ProcessorVersion(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_train_processor_version_flattened_error_async(): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.train_processor_version( + document_processor_service.TrainProcessorVersionRequest(), + parent="parent_value", + processor_version=processor.ProcessorVersion(name="name_value"), + ) + + @pytest.mark.parametrize( "request_type", [ @@ -5184,32 +5436,935 @@ async def test_review_document_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DocumentProcessorServiceGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + document_processor_service.EvaluateProcessorVersionRequest, + dict, + ], +) +def test_evaluate_processor_version(request_type, transport: str = "grpc"): + client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - with pytest.raises(ValueError): - client = DocumentProcessorServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.DocumentProcessorServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DocumentProcessorServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # It is an error to provide an api_key and a transport instance. - transport = transports.DocumentProcessorServiceGrpcTransport( + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.evaluate_processor_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.evaluate_processor_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.EvaluateProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_evaluate_processor_version_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentProcessorServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - options = client_options.ClientOptions() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.evaluate_processor_version), "__call__" + ) as call: + client.evaluate_processor_version() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.EvaluateProcessorVersionRequest() + + +@pytest.mark.asyncio +async def test_evaluate_processor_version_async( + transport: str = "grpc_asyncio", + request_type=document_processor_service.EvaluateProcessorVersionRequest, +): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.evaluate_processor_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.evaluate_processor_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.EvaluateProcessorVersionRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_evaluate_processor_version_async_from_dict(): + await test_evaluate_processor_version_async(request_type=dict) + + +def test_evaluate_processor_version_field_headers(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_processor_service.EvaluateProcessorVersionRequest() + + request.processor_version = "processor_version_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.evaluate_processor_version), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.evaluate_processor_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "processor_version=processor_version_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_evaluate_processor_version_field_headers_async(): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_processor_service.EvaluateProcessorVersionRequest() + + request.processor_version = "processor_version_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.evaluate_processor_version), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.evaluate_processor_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "processor_version=processor_version_value", + ) in kw["metadata"] + + +def test_evaluate_processor_version_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.evaluate_processor_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.evaluate_processor_version( + processor_version="processor_version_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].processor_version + mock_val = "processor_version_value" + assert arg == mock_val + + +def test_evaluate_processor_version_flattened_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.evaluate_processor_version( + document_processor_service.EvaluateProcessorVersionRequest(), + processor_version="processor_version_value", + ) + + +@pytest.mark.asyncio +async def test_evaluate_processor_version_flattened_async(): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.evaluate_processor_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.evaluate_processor_version( + processor_version="processor_version_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].processor_version + mock_val = "processor_version_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_evaluate_processor_version_flattened_error_async(): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.evaluate_processor_version( + document_processor_service.EvaluateProcessorVersionRequest(), + processor_version="processor_version_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + document_processor_service.GetEvaluationRequest, + dict, + ], +) +def test_get_evaluation(request_type, transport: str = "grpc"): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.Evaluation( + name="name_value", + kms_key_name="kms_key_name_value", + kms_key_version_name="kms_key_version_name_value", + ) + response = client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.GetEvaluationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.Evaluation) + assert response.name == "name_value" + assert response.kms_key_name == "kms_key_name_value" + assert response.kms_key_version_name == "kms_key_version_name_value" + + +def test_get_evaluation_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + client.get_evaluation() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.GetEvaluationRequest() + + +@pytest.mark.asyncio +async def test_get_evaluation_async( + transport: str = "grpc_asyncio", + request_type=document_processor_service.GetEvaluationRequest, +): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.Evaluation( + name="name_value", + kms_key_name="kms_key_name_value", + kms_key_version_name="kms_key_version_name_value", + ) + ) + response = await client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.GetEvaluationRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, evaluation.Evaluation) + assert response.name == "name_value" + assert response.kms_key_name == "kms_key_name_value" + assert response.kms_key_version_name == "kms_key_version_name_value" + + +@pytest.mark.asyncio +async def test_get_evaluation_async_from_dict(): + await test_get_evaluation_async(request_type=dict) + + +def test_get_evaluation_field_headers(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_processor_service.GetEvaluationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + call.return_value = evaluation.Evaluation() + client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_evaluation_field_headers_async(): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_processor_service.GetEvaluationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.Evaluation() + ) + await client.get_evaluation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_evaluation_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.Evaluation() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_evaluation( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_evaluation_flattened_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_evaluation( + document_processor_service.GetEvaluationRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_evaluation_flattened_async(): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_evaluation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = evaluation.Evaluation() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + evaluation.Evaluation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_evaluation( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_evaluation_flattened_error_async(): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_evaluation( + document_processor_service.GetEvaluationRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + document_processor_service.ListEvaluationsRequest, + dict, + ], +) +def test_list_evaluations(request_type, transport: str = "grpc"): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ListEvaluationsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.ListEvaluationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_evaluations_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + client.list_evaluations() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.ListEvaluationsRequest() + + +@pytest.mark.asyncio +async def test_list_evaluations_async( + transport: str = "grpc_asyncio", + request_type=document_processor_service.ListEvaluationsRequest, +): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + document_processor_service.ListEvaluationsResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == document_processor_service.ListEvaluationsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEvaluationsAsyncPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_evaluations_async_from_dict(): + await test_list_evaluations_async(request_type=dict) + + +def test_list_evaluations_field_headers(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_processor_service.ListEvaluationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + call.return_value = document_processor_service.ListEvaluationsResponse() + client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_evaluations_field_headers_async(): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = document_processor_service.ListEvaluationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + document_processor_service.ListEvaluationsResponse() + ) + await client.list_evaluations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_evaluations_flattened(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ListEvaluationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_evaluations( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_evaluations_flattened_error(): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_evaluations( + document_processor_service.ListEvaluationsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_evaluations_flattened_async(): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = document_processor_service.ListEvaluationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + document_processor_service.ListEvaluationsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_evaluations( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_evaluations_flattened_error_async(): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_evaluations( + document_processor_service.ListEvaluationsRequest(), + parent="parent_value", + ) + + +def test_list_evaluations_pager(transport_name: str = "grpc"): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token="abc", + ), + document_processor_service.ListEvaluationsResponse( + evaluations=[], + next_page_token="def", + ), + document_processor_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token="ghi", + ), + document_processor_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_evaluations(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, evaluation.Evaluation) for i in results) + + +def test_list_evaluations_pages(transport_name: str = "grpc"): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_evaluations), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token="abc", + ), + document_processor_service.ListEvaluationsResponse( + evaluations=[], + next_page_token="def", + ), + document_processor_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token="ghi", + ), + document_processor_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + RuntimeError, + ) + pages = list(client.list_evaluations(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_evaluations_async_pager(): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluations), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token="abc", + ), + document_processor_service.ListEvaluationsResponse( + evaluations=[], + next_page_token="def", + ), + document_processor_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token="ghi", + ), + document_processor_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_evaluations( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, evaluation.Evaluation) for i in responses) + + +@pytest.mark.asyncio +async def test_list_evaluations_async_pages(): + client = DocumentProcessorServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_evaluations), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + document_processor_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + next_page_token="abc", + ), + document_processor_service.ListEvaluationsResponse( + evaluations=[], + next_page_token="def", + ), + document_processor_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + ], + next_page_token="ghi", + ), + document_processor_service.ListEvaluationsResponse( + evaluations=[ + evaluation.Evaluation(), + evaluation.Evaluation(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_evaluations(request={}) + ).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DocumentProcessorServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentProcessorServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DocumentProcessorServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DocumentProcessorServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DocumentProcessorServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() options.api_key = "api_key" with pytest.raises(ValueError): client = DocumentProcessorServiceClient( @@ -5327,6 +6482,7 @@ def test_document_processor_service_base_transport(): "list_processor_types", "list_processors", "get_processor", + "train_processor_version", "get_processor_version", "list_processor_versions", "delete_processor_version", @@ -5338,6 +6494,9 @@ def test_document_processor_service_base_transport(): "disable_processor", "set_default_processor_version", "review_document", + "evaluate_processor_version", + "get_evaluation", + "list_evaluations", "get_location", "list_locations", "get_operation", @@ -5731,10 +6890,44 @@ def test_document_processor_service_grpc_lro_async_client(): assert transport.operations_client is transport.operations_client -def test_human_review_config_path(): +def test_evaluation_path(): project = "squid" location = "clam" processor = "whelk" + processor_version = "octopus" + evaluation = "oyster" + expected = "projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}/evaluations/{evaluation}".format( + project=project, + location=location, + processor=processor, + processor_version=processor_version, + evaluation=evaluation, + ) + actual = DocumentProcessorServiceClient.evaluation_path( + project, location, processor, processor_version, evaluation + ) + assert expected == actual + + +def test_parse_evaluation_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "processor": "mussel", + "processor_version": "winkle", + "evaluation": "nautilus", + } + path = DocumentProcessorServiceClient.evaluation_path(**expected) + + # Check that the path construction is reversible. + actual = DocumentProcessorServiceClient.parse_evaluation_path(path) + assert expected == actual + + +def test_human_review_config_path(): + project = "scallop" + location = "abalone" + processor = "squid" expected = "projects/{project}/locations/{location}/processors/{processor}/humanReviewConfig".format( project=project, location=location, @@ -5748,9 +6941,9 @@ def test_human_review_config_path(): def test_parse_human_review_config_path(): expected = { - "project": "octopus", - "location": "oyster", - "processor": "nudibranch", + "project": "clam", + "location": "whelk", + "processor": "octopus", } path = DocumentProcessorServiceClient.human_review_config_path(**expected) @@ -5760,9 +6953,9 @@ def test_parse_human_review_config_path(): def test_processor_path(): - project = "cuttlefish" - location = "mussel" - processor = "winkle" + project = "oyster" + location = "nudibranch" + processor = "cuttlefish" expected = "projects/{project}/locations/{location}/processors/{processor}".format( project=project, location=location, @@ -5774,9 +6967,9 @@ def test_processor_path(): def test_parse_processor_path(): expected = { - "project": "nautilus", - "location": "scallop", - "processor": "abalone", + "project": "mussel", + "location": "winkle", + "processor": "nautilus", } path = DocumentProcessorServiceClient.processor_path(**expected) @@ -5786,9 +6979,9 @@ def test_parse_processor_path(): def test_processor_type_path(): - project = "squid" - location = "clam" - processor_type = "whelk" + project = "scallop" + location = "abalone" + processor_type = "squid" expected = "projects/{project}/locations/{location}/processorTypes/{processor_type}".format( project=project, location=location, @@ -5802,9 +6995,9 @@ def test_processor_type_path(): def test_parse_processor_type_path(): expected = { - "project": "octopus", - "location": "oyster", - "processor_type": "nudibranch", + "project": "clam", + "location": "whelk", + "processor_type": "octopus", } path = DocumentProcessorServiceClient.processor_type_path(**expected) @@ -5814,10 +7007,10 @@ def test_parse_processor_type_path(): def test_processor_version_path(): - project = "cuttlefish" - location = "mussel" - processor = "winkle" - processor_version = "nautilus" + project = "oyster" + location = "nudibranch" + processor = "cuttlefish" + processor_version = "mussel" expected = "projects/{project}/locations/{location}/processors/{processor}/processorVersions/{processor_version}".format( project=project, location=location, @@ -5832,10 +7025,10 @@ def test_processor_version_path(): def test_parse_processor_version_path(): expected = { - "project": "scallop", - "location": "abalone", - "processor": "squid", - "processor_version": "clam", + "project": "winkle", + "location": "nautilus", + "processor": "scallop", + "processor_version": "abalone", } path = DocumentProcessorServiceClient.processor_version_path(**expected) @@ -5845,7 +7038,7 @@ def test_parse_processor_version_path(): def test_common_billing_account_path(): - billing_account = "whelk" + billing_account = "squid" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -5855,7 +7048,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "octopus", + "billing_account": "clam", } path = DocumentProcessorServiceClient.common_billing_account_path(**expected) @@ -5865,7 +7058,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "oyster" + folder = "whelk" expected = "folders/{folder}".format( folder=folder, ) @@ -5875,7 +7068,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nudibranch", + "folder": "octopus", } path = DocumentProcessorServiceClient.common_folder_path(**expected) @@ -5885,7 +7078,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "cuttlefish" + organization = "oyster" expected = "organizations/{organization}".format( organization=organization, ) @@ -5895,7 +7088,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "mussel", + "organization": "nudibranch", } path = DocumentProcessorServiceClient.common_organization_path(**expected) @@ -5905,7 +7098,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "winkle" + project = "cuttlefish" expected = "projects/{project}".format( project=project, ) @@ -5915,7 +7108,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nautilus", + "project": "mussel", } path = DocumentProcessorServiceClient.common_project_path(**expected) @@ -5925,8 +7118,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "scallop" - location = "abalone" + project = "winkle" + location = "nautilus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -5937,8 +7130,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "squid", - "location": "clam", + "project": "scallop", + "location": "abalone", } path = DocumentProcessorServiceClient.common_location_path(**expected)